diff --git "a/2448.jsonl" "b/2448.jsonl" new file mode 100644--- /dev/null +++ "b/2448.jsonl" @@ -0,0 +1,620 @@ +{"seq_id":"240051753","text":"import urllib.request\nimport re\nimport xml.etree.ElementTree as ET\n\n\ndef getExchangeRates():\n url = \"http://www.floatrates.com/daily/gbp.xml\"\n response = urllib.request.urlopen(url)\n xml = response.read()\n xmlStr = str(xml)\n #lines = xmlStr.split(\"\\\\n\")\n #dest = 'conversion.xml'\n #fx = open(dest,\"w\")\n #for line in lines:\n #fx.write(line)\n return xmlStr\n\n\ndef formatXML(xmlStr):\n #f = open('conversion.xml')\n #n = open('newconversion.xml','w')\n\n #strToSearch = \"\"\n #for line in xmlStr:\n # strToSearch += line\n\n patFinder = re.compile(r\"\\\\t|b'|'\")\n findPat = re.findall(patFinder, xmlStr)\n xmlStr = patFinder.sub('', xmlStr)\n\n #n.write(subFound)\n #n.close()\n\n return xmlStr\n\n\ndef getCountryExchangeRate(country, xmlStr):\n #tree = xml\n #tree = ET.parse(xmlStr)#ET.parse('newconversion.xml')\n root = ET.fromstring(xmlStr)\n if (country == \"US\"):\n country = \"U.S. Dollar\"\n elif (country == \"AUS\"):\n country = \"Australian Dollar\"\n else:\n print (\"Country does not exist. Please use 'US' or 'AUS'\")\n exit(1)\n\n\n conversionRate = 0\n for item in root.findall('item'):\n targetName = item.find('targetName').text\n exchangeRate = item.find('exchangeRate').text\n if targetName == country:\n conversionRate = exchangeRate\n return conversionRate\n\n\ndef getExchangeRate(country):\n xmlStr = getExchangeRates()\n formatXML(xmlStr)\n getCountryExchangeRate(country, xmlStr)\n","sub_path":"George/testapp/exchangeRates.py","file_name":"exchangeRates.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"89210938","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport datetime\n\ndef split_last(str_in, sep, first=False):\n separated = str_in.split(sep)\n if first:\n end = sep.join(separated[1:])\n first = separated[0]\n return first, end\n else:\n start = sep.join(separated[:-1])\n last = separated[-1]\n return start, last\n\ndef append_num_suffix(day):\n num_suffix = ['th', 'st', 'nd', 'rd']\n if day % 10 in [1, 2, 3] and day not in [11, 12, 13]:\n return str(day) + num_suffix[day % 10]\n else:\n return str(day) + num_suffix[0]\n\ndef filename_to_date_string(name_in):\n main_name, ext = split_last(name_in.lower(), os.path.extsep)\n\n year, month, dayrem = main_name.split('-')\n if '_' in dayrem:\n day, rem = dayrem.split('_')\n else:\n day = dayrem\n rem = None\n \n year = int(year)\n month = int(month)\n day = int(day)\n \n date = datetime.date(year=year, month=month, day=day)\n \n final_name = date.strftime('%Y %B') + ' '\n final_name += append_num_suffix(date.day) + ' '\n final_name += date.strftime('(%A)')\n\n if rem != None:\n page_num = rem.replace('page', '').upper()\n if page_num == 'FORGOT':\n page_num = 'Unknown'\n final_name += ' {Page ' + page_num + '}'\n return final_name\n\ndef main(pic_dir):\n pic_files = []\n # r=root, d=directories, f = files\n for r, d, f in os.walk(pic_dir):\n for filename in f:\n main_name, ext = split_last(filename.lower(), os.path.extsep)\n if (ext in ['jpg', 'jpeg']) and (main_name not in ['preview']):\n pic_files.append(filename)\n break #prevent descending into subfolders\n pic_files.sort()\n\n strings = []\n for f in pic_files:\n these_strings = dict()\n these_strings['date'] = filename_to_date_string(f)\n these_strings['title'] = '## ' + these_strings['date'] + ' [[Table of Contents]](#table-of-contents)'\n these_strings['pic'] = '![' + these_strings['date'] + '](' + f + ')'\n \n these_strings['link'] = these_strings['date'].lower()\n for x in ',()[]{}#':\n these_strings['link'] = these_strings['link'].replace(x, '')\n these_strings['link'] = these_strings['link'].replace(' ', '-')\n these_strings['link'] += '-table-of-contents'\n these_strings['link'] = '#' + these_strings['link']\n strings.append(these_strings)\n \n print('## Table of Contents')\n for s in strings:\n print('* [' + s['date'] + '](' + s['link'] + ')')\n print()\n for s in strings:\n print(s['title'])\n print('
')\n print(' Show')\n print()\n print(' ' + s['pic'])\n print('
')\n print()\n\nscript_path = os.path.dirname(os.path.realpath(__file__))\nmain(script_path)\n","sub_path":"texts/My Scans/md_gen.py","file_name":"md_gen.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"484397159","text":"import fresh_tomatoes\r\nimport media\r\n\r\nlion_king = media.Movie(\"Lion King\",\r\n \"The story of a lion cub's journey to adulthood\"\r\n \" and acceptance of his royal destiny.\",\r\n \"https://upload.wikimedia.org/wikipedia/en/thumb/3/3d/The_Lion_King_poster.jpg/220px-The_Lion_King_poster.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=V6jOvVf05aQ\")\r\nfive_hundred_days_of_summer = media.Movie(\"500 Days of Summer\",\r\n \"An offbeat romantic comedy about a \"\r\n \"woman who doesn't believe true love\"\r\n \" exists, and the young man who \"\r\n \"falls for her.\",\r\n \"https://upload.wikimedia.org/wikipedia/en/d/d1/Five_hundred_days_of_summer.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=PsD0NpFSADM\")\r\n\r\nferris_bueller = media.Movie(\"Ferris Bueller's Day Off\",\r\n \"A high school wise guy is determined \"\r\n \"to have a day off from school, despite what \"\r\n \"the Principal thinks of that.\",\r\n \"https://upload.wikimedia.org/wikipedia/en/9/9b/Ferris_Bueller%27s_Day_Off.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=D6gABQFR94U\")\r\n\r\nspirited_away = media.Movie(\"Spirited Away\",\r\n \"During her family's move to the suburbs, \"\r\n \"a sullen 10-year-old girl wanders into a world \"\r\n \"ruled by gods, witches, and spirits, \"\r\n \"and where humans are changed into beasts.\",\r\n \"https://images-na.ssl-images-amazon.com/images/M/MV5BOGJjNzZmMmUtMjljNC00ZjU5LWJiODQtZmEzZTU0MjBlNzgxL2ltYWdlXkEyXkFqcGdeQXVyNTAyODkwOQ@@._V1_SY1000_CR0,0,675,1000_AL_.jpg\", # NOQA\r\n \"https://www.youtube.com/watch?v=ByXuk9QqQkk\")\r\n\r\nmovies = [lion_king, five_hundred_days_of_summer, ferris_bueller, spirited_away] # NOQA\r\n\r\nfresh_tomatoes.open_movies_page(movies)\r\n\r\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552726957","text":"import logging\nimport os\nfrom argparse import ArgumentParser\n\nimport discord\nfrom discord.ext import commands\n\nimport Util\nfrom Util import Configuration, GearbotLogging, GlobalHandlers\n\n\ndef prefix_callable(bot, message):\n return GlobalHandlers.prefix_callable(bot, message)\n\nbot = commands.AutoShardedBot(command_prefix=prefix_callable, case_insensitive=True)\nbot.STARTUP_COMPLETE = False\nbot.user_messages = 0\nbot.bot_messages = 0\nbot.self_messages = 0\nbot.commandCount = 0\nbot.custom_command_count = 0\nbot.errors = 0\nbot.eaten = 0\nbot.database_errors = 0\n\n@bot.event\nasync def on_ready():\n await GlobalHandlers.on_ready(bot)\n\n@bot.event\nasync def on_message(message:discord.Message):\n await GlobalHandlers.on_message(bot, message)\n\n\n@bot.event\nasync def on_guild_join(guild: discord.Guild):\n await GlobalHandlers.on_guild_join(guild)\n\n@bot.event\nasync def on_guild_remove(guild: discord.Guild):\n await GlobalHandlers.on_guild_remove(guild)\n\n@bot.event\nasync def on_command_error(ctx: commands.Context, error):\n await GlobalHandlers.on_command_error(bot, ctx, error)\n\n\n@bot.event\nasync def on_error(event, *args, **kwargs):\n await GlobalHandlers.on_error(bot, event, *args, **kwargs)\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument(\"--debug\", help=\"Runs the bot in debug mode\", dest='debug', action='store_true')\n parser.add_argument(\"--debugLogging\", help=\"Set debug logging level\", action='store_true')\n parser.add_argument(\"--token\", help=\"Specify your Discord token\")\n\n logger = logging.getLogger('discord')\n logger.setLevel(logging.INFO)\n handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w+')\n handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\n logger.addHandler(handler)\n\n GearbotLogging.init_logger()\n\n clargs = parser.parse_args()\n if 'gearbotlogin' in os.environ:\n token = os.environ['gearbotlogin']\n elif clargs.token:\n token = clargs.token\n elif not Configuration.getMasterConfigVar(\"LOGIN_TOKEN\", \"0\") is \"0\":\n token = Configuration.getMasterConfigVar(\"LOGIN_TOKEN\")\n else:\n token = input(\"Please enter your Discord token: \")\n bot.remove_command(\"help\")\n Util.prepDatabase(bot)\n GearbotLogging.info(\"Ready to go, spinning up the gears\")\n bot.run(token)\n GearbotLogging.info(\"GearBot shutting down, cleaning up\")\n bot.database_connection.close()\n GearbotLogging.info(\"Cleanup complete\")\n\n","sub_path":"GearBot/Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"161191676","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# this module provides all needed requests aginst the Jira API\n#\n\nimport pymysql\nimport requests\nimport json\nfrom sshtunnel import SSHTunnelForwarder\nimport auth_module\nimport error\n\nimport time\nimport datetime\n\njira_headers = {\"Content-type\": \"application/json\"}\nconfigs = auth_module.read_configs()\nauth = (configs[\"jira\"][\"user\"], configs[\"jira\"][\"secret\"])\n\n\n# post new worklog and return worklog_id\ndef post_worklog(issue_key, user, comment, dateStarted, timeSpent):\n url = configs[\"jira\"][\"socket\"] + \"/rest/tempo-timesheets/3/worklogs\"\n data = {\"timeSpentSeconds\": timeSpent, \"dateStarted\": dateStarted, \"comment\": comment, \"author\": {\"name\": user}, \"issue\": {\"key\": issue_key}}\n response = requests.request(\"POST\", url, data=json.dumps(data), auth=auth, headers=jira_headers)\n array = json.loads(response.text)\n# print(response.text)\n # error interception logis\n try:\n if array[\"errors\"][\"dateStarted\"] == \"User timesheet is not open\":\n return [\"closed timesheet\", ]\n except:\n try:\n return [True, array[\"jiraWorklogId\"]]\n except:\n return [False, response.text]\n\n\n# get user_key from email\ndef get_user_key(email):\n url = configs[\"jira\"][\"socket\"] + \"/rest/api/2/user/search?username=\" + email\n response = requests.request(\"GET\", url, auth=auth, headers=jira_headers)\n array = json.loads(response.text)\n # error interception logic\n try:\n user_key = array[0][\"name\"]\n return user_key\n except:\n error.error_log(\"Jira-user doesn't exist, could not write timeoff:\", email, response.text, \"synch\", False)\n return False\n\n\n# get worklogs recently updated\ndef get_worklogs_updated(date):\n with SSHTunnelForwarder(\n (configs[\"jira_ssh\"][\"host\"], configs[\"jira_ssh\"][\"port\"]),\n ssh_username = configs[\"jira_ssh\"][\"user\"],\n ssh_password = configs[\"jira_ssh\"][\"secret\"],\n remote_bind_address = (configs[\"jira_db\"][\"host\"], configs[\"jira_db\"][\"port\"])) as tunnel:\n connection = auth_module.connect_jira_db(tunnel)\n db = connection[0]; cursor = connection[1]; table = connection[2]\n\n# date = \"2019-09-04 11:40:00\" #test\n sql = \"SELECT ID FROM %s WHERE UPDATED >= '%s' AND UPDATEAUTHOR != 'jira'\"%(table, date)\n cursor.execute(sql)\n result = cursor.fetchall()\n _WLids = []\n for item in result:\n _WLids.append(int(item[0]))\n if db.open:\n db.close()\n return _WLids\n\n\n# get worklogs from id list\ndef get_worklogs(_list):\n url = configs[\"jira\"][\"socket\"] + \"/rest/api/2/worklog/list\"\n data = {\"ids\":_list}\n response = requests.request(\"POST\", url, data=json.dumps(data), auth=auth, headers=jira_headers)\n try:\n array = json.loads(response.text.encode('utf-8'))\n return array\n except:\n error.error_log(\"could not connect to jira, worklog synchronisation failed\", \"\", \"\", \"synch\", True)\n return False\n\n\n# get worklogs recently deleted\ndef get_del_worklogs(time):\n url = configs[\"jira\"][\"socket\"] + \"/rest/api/2/worklog/deleted?since=\" + str(time)\n response = requests.request(\"GET\", url, auth=auth, headers=jira_headers)\n array = json.loads(response.text)\n _del = []\n for index, item in enumerate(array[\"values\"]):\n _del.append(item[\"worklogId\"])\n return _del\n\n\n# check if worklog already exists\ndef check_jira(name, date, issue_key):\n date = ''.join(date.split())[:-6]\n url = configs[\"jira\"][\"socket\"] + \"/rest/tempo-timesheets/3/worklogs?dateFrom=%s&dateTo=%s&username=%s&projectKey=INT\"%(date, date, name)\n response = requests.request(\"GET\", url, auth=auth, headers=jira_headers)\n array = json.loads(response.text)\n if array == []:\n return False\n else:\n for index, item in enumerate(array):\n if item[\"issue\"][\"key\"] == issue_key:\n return True\n return False\n\n\n# get jira issue_key from issueID\ndef get_issue_key(_id):\n url = configs[\"jira\"][\"socket\"] + \"/rest/api/2/issue/\" + str(_id)\n response = requests.request(\"GET\", url, auth=auth, headers=jira_headers)\n array = json.loads(response.text)\n return array[\"key\"]\n","sub_path":"modules/jira_requests.py","file_name":"jira_requests.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"287988649","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# njuguoyi @ 2016-03-09 16:55:48\n\n\"\"\"\n实现一个优��级队列\n\"\"\"\nimport heapq\n\nclass PriorityQueue:\n def __init__(self):\n self._queue = []\n self._index = 0\n\n # 先按-priority排序,再按self._index排序\n def push(self, item, priority):\n heapq.heappush(self._queue, (-priority, self._index, item))\n self._index += 1\n\n # 返回最高优先级的元组中的item\n def pop(self):\n return heapq.heappop(self._queue)[-1]\n\nclass Item:\n def __init__(self, name):\n self.name = name\n def __repr__(self):\n return 'Item({!r})'.format(self.name)\n\nq = PriorityQueue()\nq.push(Item('foo'), 1)\nq.push(Item('bar'), 5)\nq.push(Item('spam'), 4)\nq.push(Item('grok'), 1)\nprint(q.pop())\nprint(q.pop())\nprint(q.pop())\nprint(q.pop())\n\n# Python3中的字符串格式化操作\nprint(\"{0}, {1}\".format(\"Hello\", \"World!\"))\nprint(\"{first}, {second}\".format(first=\"Hello\", second=\"World!\"))\n","sub_path":"chap3/3.5.py","file_name":"3.5.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"457739466","text":"__author__ = \"Narwhale\"\nimport pika,time\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))\nchannel = connection.channel()\nchannel.queue_declare(queue='hello3',durable=True)#durable队列持久化\n\ndef callback(ch, method, properties, body):\n print(\" [x] Received %r\" % body)\n time.sleep(30)\n print('-->',ch,method,properties)\n ch.basic_ack(delivery_tag=method.delivery_tag) #用途是当客户端1突然断开链接,rebbitMQ会将未处理完的消息传给客户端2\nchannel.basic_qos(prefetch_count=1)\nchannel.basic_consume(callback,\n queue='hello3',\n\n )\n\nprint(' [*] Waiting for messages. To exit press CTRL+C')\nchannel.start_consuming()","sub_path":"编程/3月/3.2/pika_receive.py","file_name":"pika_receive.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"88698430","text":"#Created on July 8 2014\n\n#@author: Ambarish\n\n#Find Cost of Tile to Cover W x H Floor \n#Calculate the total cost of tile it would take to cover a floor plan of \n#width and height, using a cost entered by the user.\n\ndef calc(cost,width,height):\n total = cost*width*height\n return total\n\ncost = float(input(\"Enter cost per tile: \"))\nwidth = float(input(\"Enter width of room: \"))\nheight = float(input(\"Enter height of room: \"))\ntotal = calc(cost,width,height)\nprint(\"The total cost for tiling is \", \"$\" + '{0:.2f}'.format(total))\n\n\n","sub_path":"tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"439805717","text":"# -*- coding: utf-8 -*-\n\nimport cStringIO\nfrom odoo.report.report_sxw import report_sxw\nfrom odoo.api import Environment\nfrom mailmerge import MailMerge\n\ntemplate = u\"../addons/report_doc/檢測報告.docx\"\n\n\nclass GeneReportWord(report_sxw):\n\n def create(self, cr, uid, ids, data, context=None):\n self.env = Environment(cr, uid, context)\n report_obj = self.env['ir.actions.report.xml']\n report = report_obj.search([('report_name', '=', self.name[7:])])\n if report.ids:\n self.title = report.name\n if report.report_type == 'docx':\n return self.create_word_report(ids, data, report)\n return super(GeneReportWord, self).create(cr, uid, ids, data, context)\n\n def create_word_report(self, ids, data, report):\n path_data = self.env['report.doc'].search([('name','=',u'檢測報告')])\n template = path_data.path\n self.parser_instance = self.parser(\n self.env.cr, self.env.uid, self.name2, self.env.context)\n objs = self.getObjects(\n self.env.cr, self.env.uid, ids, self.env.context)\n self.parser_instance.set_context(objs, data, ids, 'docx')\n file_data = cStringIO.StringIO()\n document = MailMerge(template)\n self.generate_word_report(document, data, objs, report)\n document.write(file_data)\n document.close()\n file_data.seek(0)\n return (file_data.read(), 'docx')\n\n def generate_word_report(self, document, data, objs, report):\n raise NotImplementedError()\n","sub_path":"addons/report_doc/report/report_doc.py","file_name":"report_doc.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"519107440","text":"import gdal\nimport argparse\nimport shutil\nimport subprocess\n\nimport raster_utilities as ras_util\n\n\ndef main():\n # Parse commandline arguments\n parser = argparse.ArgumentParser(description='Change the data type of a raster.')\n parser.add_argument('--input_raster', '-i', help='the intensity raster', required=True)\n parser.add_argument('--output_raster', '-o', help='the output raster', required=True)\n parser.add_argument('--data_type', '-d', help='the output data type', choices=('Int16', 'UInt16'), required=True)\n parser.add_argument('--bbox', '-b', help='projwin bbox- ulx uly lrx lry', nargs=4)\n args = parser.parse_args()\n\n src_ds = gdal.Open(args.input_raster)\n band = src_ds.GetRasterBand(1)\n\n run_gdal = False\n\n cmd = ['gdal_translate', args.input_raster, '-ot', args.data_type, '-co', 'COMPRESS=LZW', args.output_raster]\n cmd += ['--config', 'GDAL_CACHEMAX', ras_util.get_mem_pct()]\n\n if args.bbox:\n cmd += ['-projwin', args.bbox[0], args.bbox[1], args.bbox[2], args.bbox[3]]\n run_gdal = True\n\n if gdal.GetDataTypeName(band.DataType) != args.data_type:\n run_gdal = True\n\n # If the initial data type is correct and no bounding box is specified, just copy it to the output\n if run_gdal:\n subprocess.check_call(cmd)\n\n else:\n shutil.copy(args.input_raster, args.output_raster)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"raster_processing/utilities/write_16bit_raster.py","file_name":"write_16bit_raster.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"357886591","text":"import datetime\nimport os\nimport threading\nfrom enum import Enum\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import messagebox\nfrom tkinter import ttk\n\nimport web_driver\n\n\nclass Status(Enum):\n NORMAL = 0\n BOT_IS_RUNNING = 1\n BOT_STOPPED_RUNNING = 2\n BOT_IS_UPDATING_FILE = 3\n BOT_STOPPED_UPDATING_FILE = 4\n BOT_ERROR = 5\n\n\nclass Title:\n def __init__(self, master):\n self.frame = Frame(master)\n self.frame.pack()\n\n self.title = Label(self.frame, text=\"Pool Permit Scraper Bot\")\n self.title.pack()\n\n\nclass Form:\n def __init__(self, master):\n self.filename = \"No file chosen.\"\n\n self.frame = Frame(master)\n self.frame.pack()\n\n self.label_start = Label(self.frame, text=\"Start Date\")\n self.label_end = Label(self.frame, text=\"End Date\")\n self.label_choose_file = Label(self.frame, text=\"Choose File to Update: \")\n self.label_filename = Label(self.frame, text=\"No file chosen.\")\n\n self.entry_start = Entry(self.frame)\n self.entry_end = Entry(self.frame)\n\n self.button_choose_file = ttk.Button(self.frame, text=\"Choose file\", command=self.get_filename)\n\n # Grid setup\n self.label_start.grid(row=0, sticky=E)\n self.label_end.grid(row=1, sticky=E)\n self.label_choose_file.grid(row=2, sticky=E)\n self.label_filename.grid(row=2, column=1)\n\n self.entry_start.grid(row=0, column=1, columnspan=2, sticky=EW)\n self.entry_start.insert(0, \"mm/dd/yyyy\")\n self.entry_start.bind(\"\", lambda event: self.clear_placeholder(event, self.entry_start))\n self.entry_end.grid(row=1, column=1, columnspan=2, sticky=EW)\n self.entry_end.insert(0, \"mm/dd/yyyy\")\n self.entry_end.bind(\"\", lambda event: self.clear_placeholder(event, self.entry_end))\n\n self.button_choose_file.grid(row=2, column=2)\n\n def get_filename(self):\n self.filename = filedialog.askopenfilename(initialdir=os.path.expanduser(\"~/Desktop/\"),\n title=\"Choose file\",\n filetypes=((\"csv files\", \"*.csv\"),))\n if self.filename == \"\":\n self.filename = \"No file chosen.\"\n self.label_filename.config(text=self.filename)\n\n def clear_placeholder(self, event, entry):\n if entry.get() == \"mm/dd/yyyy\":\n entry.delete(0, END)\n\n\nclass RunBotButtons:\n def __init__(self, master, form):\n self.status_bar = None\n self.status = Status.NORMAL\n self.form = form\n\n self.frame = Frame(master)\n self.frame.pack()\n\n self.button_run = ttk.Button(self.frame, text=\"Run Bot\", command=self.run_bot_thread)\n self.button_update = ttk.Button(self.frame, text=\"Update File\", command=self.update_file_thread)\n\n self.button_run.grid(row=0)\n self.button_update.grid(row=0, column=2)\n\n def set_status_bar_object(self, status_bar):\n \"\"\"\n Set an instance of StatusBar to self.status_bar.\n This is needed to call the change_status_message()\n function in the StatusBar object.\n\n Parameters\n ----------\n status_bar: StatusBar\n An instance of StatusBar. Displays\n various messages to the user based\n on the current status of the bot.\n\n \"\"\"\n\n self.status_bar = status_bar\n\n def run_bot_thread(self):\n \"\"\"\n A wrapper for self.run_bot().\n\n The self.run_bot() function will be run in a\n thread so that the GUI doesn't get held up\n when the function is executing.\n\n \"\"\"\n\n self.button_run.config(state=DISABLED)\n\n formatted_date_range = self.check_date_format()\n\n if not formatted_date_range:\n self.button_run.config(state=NORMAL)\n return\n else:\n start_datetime, end_datetime, delta = formatted_date_range\n run_bot_thread = threading.Thread(target=self.run_bot, args=(start_datetime, end_datetime, delta,))\n run_bot_thread.start()\n\n def run_bot(self, start_datetime, end_datetime, delta):\n \"\"\"\n Executes web_driver.run_bot(). When the\n function finishes executing, the \"Run Bot\"\n button will be re-enabled.\n\n \"\"\"\n\n if self.status_bar is not None:\n self.status_bar.change_status_message(Status.BOT_IS_RUNNING)\n\n if not web_driver.run_bot(start_datetime, end_datetime, delta):\n self.status_bar.change_status_message(Status.BOT_ERROR)\n else:\n if self.status_bar is not None:\n self.status_bar.change_status_message(Status.BOT_STOPPED_RUNNING)\n self.button_run.config(state=NORMAL)\n\n def update_file_thread(self):\n \"\"\"\n A wrapper for self.update_file().\n\n The self.update_file() function will be run in a\n thread so that the GUI doesn't get held up\n when the function is executing.\n\n \"\"\"\n\n self.button_update.config(state=DISABLED)\n if self.form.filename == \"No file chosen.\":\n messagebox.showwarning(title=\"No File Chosen\", message=\"Please choose a file to update and try again.\")\n self.button_update.config(state=NORMAL)\n return\n\n update_file_thread = threading.Thread(target=self.update_file)\n update_file_thread.start()\n\n def update_file(self):\n \"\"\"\n Executes web_driver.update_file(). When the\n function finishes executing. the \"Update File\"\n button will be re-enabled.\n\n \"\"\"\n\n if self.status_bar is not None:\n self.status_bar.change_status_message(Status.BOT_IS_UPDATING_FILE)\n\n if not web_driver.update_file(self.form.label_filename.cget(\"text\")):\n self.status_bar.change_status_message(Status.BOT_ERROR)\n else:\n if self.status_bar is not None:\n self.status_bar.change_status_message(Status.BOT_STOPPED_UPDATING_FILE)\n self.button_update.config(state=NORMAL)\n\n def check_date_format(self):\n \"\"\"\n Date format is mm/dd/yyyy\n\n Returns\n -------\n tuple\n A 3-tuple filled with the start\n datetime, end datetime, and the\n date difference (delta) respectively.\n The datetime is referring to the Python\n datetime object. Return None if the\n input date is not in a valid format.\n\n \"\"\"\n\n start_date = self.form.entry_start.get().split(\"/\")\n end_date = self.form.entry_end.get().split(\"/\")\n\n if len(start_date) != 3 or len(end_date) != 3:\n messagebox.showwarning(title=\"Invalid Date Format\", message=\"Please enter your date in the format: mm/dd/yyyy\")\n return None\n\n if len(start_date[0]) != 2 or len(start_date[1]) != 2 or len(start_date[2]) != 4:\n messagebox.showwarning(title=\"Invalid Date Format\", message=\"Please enter your date in the format: mm/dd/yyyy\")\n return None\n\n if len(end_date[0]) != 2 or len(end_date[1]) != 2 or len(end_date[2]) != 4:\n messagebox.showwarning(title=\"Invalid Date Format\", message=\"Please enter your date in the format: mm/dd/yyyy\")\n return None\n\n try:\n # Convert date from string to integer\n start_date = [int(date) for date in start_date]\n end_date = [int(date) for date in end_date]\n\n start = datetime.datetime(start_date[2], start_date[0], start_date[1])\n end = datetime.datetime(end_date[2], end_date[0], end_date[1])\n delta = end - start\n if delta.days < 0:\n raise DateRangeInvalid\n except ValueError:\n messagebox.showwarning(title=\"Invalid Date\", message=\"Please enter a valid date.\")\n return None\n except TypeError:\n messagebox.showwarning(title=\"Invalid Date Format\", message=\"Date must only contain numbers.\")\n return None\n except DateRangeInvalid:\n messagebox.showwarning(title=\"Invalid Date Range\", message=\"End date is earlier than start date. Please check your dates and try again.\")\n return None\n\n # Format start and end date to: mmm dd, yyyy\n start_ts = datetime.datetime.strptime(self.form.entry_start.get(), \"%m/%d/%Y\").timestamp()\n end_ts = datetime.datetime.strptime(self.form.entry_end.get(), \"%m/%d/%Y\").timestamp()\n start_datetime = datetime.datetime.fromtimestamp(start_ts)\n end_datetime = datetime.datetime.fromtimestamp(end_ts)\n return start_datetime, end_datetime, delta\n\n\nclass StatusBar:\n def __init__(self, master):\n self.frame = Frame(master)\n self.frame.pack()\n\n self.status = Label(self.frame,\n text=\"Enter a date range above and click \\\"Run Bot\\\" to start.\\n\"\n \"To update an existing file, choose the file and click \\\"Update File\\\".\",\n bd=1,\n relief=SUNKEN,\n anchor=W)\n\n self.status.pack()\n\n def change_status_message(self, status):\n if status == Status.NORMAL:\n self.status.config(text=\"Enter a date range above and click \\\"Run Bot\\\" to start.\\n\"\\\n \"To update an existing file, choose the file and click \\\"Update File\\\".\")\n elif status == Status.BOT_IS_RUNNING:\n self.status.config(text=\"Bot is gathering permits from the date range you specified.\\n\"\\\n \"Please wait...\")\n elif status == Status.BOT_STOPPED_RUNNING:\n self.status.config(text=\"Bot has finished gathering permits.\\n\"\\\n \"A csv file containing the permit(s) has been saved on your desktop.\\n\"\\\n \"The name of this file is in the format: _to__permits\")\n elif status == Status.BOT_IS_UPDATING_FILE:\n self.status.config(text=\"Bot is updating the permit(s) from the file you specified.\\n\"\\\n \"Please wait...\")\n elif status == Status.BOT_STOPPED_UPDATING_FILE:\n self.status.config(text=\"Bot has finished updating permits in the given file.\\n\"\\\n \"A csv file containing updated permits has been saved to your desktop.\\n\"\\\n \"The name of this file is in the format: updated_.\")\n elif status == Status.BOT_ERROR:\n self.status.config(text=\"An error occurred while running the bot.\\n\"\n \"Please keep the browser window open when running the bot and make sure you have\\n\"\n \"internet connection.\")\n\n\nclass DateRangeInvalid(Exception):\n def __init__(self):\n pass\n\n\ndef main():\n root = Tk()\n root.resizable(width=0, height=0)\n root.title(\"Pool Permit Scraper\")\n\n Title(root)\n form = Form(root)\n run_bot = RunBotButtons(root, form)\n status_bar = StatusBar(root)\n run_bot.set_status_bar_object(status_bar)\n\n root.mainloop()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":11302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"159773223","text":"import io\nimport os\nimport unittest\n\nimport tidy\nimport tidy.lib\n\nDATA_STORAGE = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"test_data\")\n\n\nclass TidyTestCase(unittest.TestCase):\n input1 = \"\"\n input2 = \"\\n\" + \"

asdkfjhasldkfjhsldjas\\n\" * 100\n test_file = os.path.join(DATA_STORAGE, \"test.html\")\n\n def default_docs(self):\n doc1 = tidy.parseString(self.input1)\n doc2 = tidy.parseString(self.input2)\n doc3 = tidy.parse(self.test_file, char_encoding=\"ascii\")\n return (doc1, doc2, doc3)\n\n def test_bad_options(self):\n badopts = [{\"foo\": 1}]\n for opts in badopts:\n with self.assertRaisesRegex(\n tidy.InvalidOptionError, \"not a valid Tidy option\"\n ):\n tidy.parseString(self.input2, **opts)\n\n def test_bad_option_values(self):\n badopts = [{\"indent\": \"---\"}, {\"indent_spaces\": None}]\n for opts in badopts:\n with self.assertRaisesRegex(\n tidy.OptionArgError, \"missing or malformed argument\"\n ):\n tidy.parseString(self.input2, **opts)\n\n def test_encodings(self):\n text = (\n open(self.test_file, \"rb\")\n .read()\n .decode(\"utf8\")\n .encode(\"ascii\", \"xmlcharrefreplace\")\n )\n doc1u = tidy.parseString(text, input_encoding=\"ascii\", output_encoding=\"latin1\")\n self.assertTrue(doc1u.getvalue().find(b\"\\xe9\") >= 0)\n doc2u = tidy.parseString(text, input_encoding=\"ascii\", output_encoding=\"utf8\")\n self.assertTrue(doc2u.getvalue().find(b\"\\xc3\\xa9\") >= 0)\n\n def test_error_lines(self):\n for doc in self.default_docs():\n self.assertEqual(doc.errors[0].line, 1)\n\n def test_nonexisting(self):\n os.environ.pop(\"IGNORE_MISSING_TIDY\", None)\n doc = tidy.parse(os.path.join(DATA_STORAGE, \"missing.html\"))\n self.assertEqual(str(doc).strip(), \"\")\n self.assertIn(\"missing.html\", doc.errors[0].message)\n if doc.errors[0].severity == \"E\":\n self.assertEqual(doc.errors[0].severity, \"E\")\n self.assertTrue(str(doc.errors[0]).startswith(\"Error\"))\n else:\n # Tidy 5.5.19 and newer\n self.assertEqual(doc.errors[0].severity, \"D\")\n self.assertTrue(str(doc.errors[0]).startswith(\"Document\"))\n\n def test_options(self):\n doc1 = tidy.parseString(\n self.input1, add_xml_decl=1, show_errors=1, newline=\"CR\", output_xhtml=1\n )\n self.assertIn(\"CDATA\", str(doc1))\n doc2 = tidy.parseString(\n \"\", add_xml_decl=1, show_errors=1, newline=\"CR\", output_xhtml=1\n )\n self.assertTrue(str(doc2).startswith(\"\", str(doc1))\n self.assertIn(\"\", str(doc2))\n self.assertIn(\"\", doc3.gettext())\n\n def test_big(self):\n text = \"x\" * 16384\n doc = tidy.parseString(f\"{text}\")\n self.assertIn(text, str(doc))\n\n def test_unicode(self):\n doc = tidy.parseString(\"zkouška\")\n self.assertIn(\"zkouška\", doc.gettext())\n\n def test_write(self):\n doc = tidy.parseString(self.input1)\n handle = io.BytesIO()\n doc.write(handle)\n self.assertEqual(doc.getvalue(), handle.getvalue())\n\n def test_errors(self):\n doc = tidy.parseString(self.input1)\n for error in doc.errors:\n self.assertTrue(str(error).startswith(\"line\"))\n self.assertTrue(repr(error).startswith(\"ReportItem\"))\n\n def test_report_item(self):\n item = tidy.ReportItem(\"Invalid: error\")\n self.assertEqual(item.get_severity(), \"Invalid\")\n\n def test_missing_load(self):\n with self.assertRaises(OSError):\n tidy.lib.Loader(libnames=(\"not-existing-library\",))\n\n def test_lib_from_environ(self):\n os.environ[\"TIDY_LIBRARY_FULL_PATH\"] = \"/foo/bar/tidy\"\n loader = tidy.lib.Loader()\n expected_libnames = (\n \"/foo/bar/tidy\",\n \"libtidy.so\",\n \"libtidy.dylib\",\n \"tidy\",\n \"cygtidy-0-99-0\",\n \"libtidy-0.99.so.0\",\n \"libtidy-0.99.so.0.0.0\",\n \"libtidy.so.5\",\n \"libtidy.so.58\",\n \"libtidy.so.5deb1\",\n \"libtidy\",\n \"tidylib\",\n )\n self.assertEqual(loader.libnames, expected_libnames)\n","sub_path":"tidy/test_tidy.py","file_name":"test_tidy.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"142810199","text":"from ui import *\nfrom time import sleep\nfrom parse import *\n\n\ndef main():\n \"\"\"Main flux of the program. First, it parses the three data files into dicts.\n The interactive menu function is invoked and it manages the flux of the game, except\n a KeyboardInterrupt (ctrl-c) or EOFError (ctrl-v) are raised. In this case the program\n goes back to the main menu, invoking again the function.\n \"\"\"\n SUPERS = to_dict('supermercados.csv')\n PRODUCTS = to_dict('productos.csv')\n PRICES = create_prices_dict('precios.csv')\n loop = True\n while loop:\n try:\n interactive_menu(SUPERS, PRODUCTS, PRICES)\n loop = False\n except (KeyboardInterrupt, EOFError):\n try:\n print('\\n\\nVolviendo al menú principal...')\n sleep(0.4)\n except (KeyboardInterrupt, EOFError): # In case any of this exceptions is raised during the 0.4 sleep\n continue\n\n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"652987293","text":"\"\"\"\r\nlogInterface.py\r\nPurpose: Extract error messages with specific pattern and update a database with those details, and at the same time enriching by adding more characteristics. The tool also aggregates the number of failures for a certain resource as well as counting repeated failures. The tool evaluates first the complete log file and subsequently only the recent entries that are created after the full log file evaluation. The script can be scheduled by using the operating system tools.\r\n\r\nChanges that are required: The tool assumes that the log file in the default location. However, database details must be updated. Therefore the \"conn\" variable must be defined with correct database details. A database must be created prior to executing the script, and the related details are provided as part of the complete package.\r\nDevelopment environment: \r\nDevelopment: Python 3.6.5\r\nOS: OpenSuSe Linux 15.0\r\nDatabase: MySql 8.1.3\r\n\r\n\"\"\"\r\n\r\n\r\nimport pymysql\r\nfrom dateutil import parser\r\nfrom datetime import timedelta\r\nconn = pymysql.connect(host='localhost',user='root',password='D#3Qh!hHYt45Bn',db='hacdata')\r\nresource_id = []\r\ncount_for_skipping = 0\r\na = conn.cursor()\r\nsqlQuery = \"select count(event_date),event_date from hacdata.hac_main group by event_date ORDER by event_date DESC LIMIT 1\"\r\ndate_time_for_comparison = None\r\ntry:\r\n a.execute(sqlQuery)\r\n rows = a.fetchall()\r\n for row in rows:\r\n number_of_rows_in_log_file_to_be_skipped = row[0]\r\n date_time_for_comparison = row[1]\r\nexcept :\r\n print(\"Something went wrong deleting previous data from table\")\r\nwith open('/var/log/pacemaker/pacemaker.log','r') as rf:\r\n\r\n for line in rf:\r\n if line.find(\"not running\")!= -1:\r\n time_stamp = line[0:15]\r\n date_time = parser.parse(time_stamp)\r\n\r\n server = line.split()[4]\r\n process = line.split()[5].split(\":\")[0]\r\n if line.find(\"=not running\")!= -1:\r\n hac_resource_name = line.split(\"=\")[0].split()[-1]\r\n else:\r\n hac_resource_name = line.split(\":\")[5].split()[-3]\r\n sqlQuery = (\"select * FROM hacdata.configuration WHERE HAC_resource_name = '%s' limit 1\" % hac_resource_name)\r\n a.execute(sqlQuery)\r\n rows = a.fetchall()\r\n length_of_data_tuple = len(rows)\r\n if length_of_data_tuple != 0:\r\n for row in rows:\r\n configuration_resource_id = row[0]\r\n resource_name = row[1]\r\n group_id = row[3]\r\n cluster_id = row[4]\r\n node_id= row[5]\r\n error_msg = \"not running\"\r\n dependency_factor = int(row[9] + row[13] + row[14])\r\n current_state = row[8]\r\n failure_repetition = 0\r\n aggregated_failure_count = 0\r\n two_minutes_time = date_time - timedelta(0, 120)\r\n four_hours = date_time - timedelta(0, 14400)\r\n resource_tuple_name_time = [item for item in resource_id if item[0] == hac_resource_name]\r\n flag_for_same_time_resource = False\r\n for resource_tuple_name_time_item in resource_tuple_name_time:\r\n item_time = resource_tuple_name_time_item[1]\r\n if item_time == date_time and resource_tuple_name_time_item[0] == hac_resource_name:\r\n flag_for_same_time_resource = True\r\n break\r\n # if item_time >= four_hours and item_time <= date_time:\r\n # aggregated_failure_count = aggregated_failure_count + 1\r\n # if item_time >= two_minutes_time and item_time <= date_time:\r\n # failure_repetition = failure_repetition + 1\r\n if not flag_for_same_time_resource:\r\n for resource_tuple_name_time_item in resource_tuple_name_time:\r\n item_time = resource_tuple_name_time_item[1]\r\n if item_time >= four_hours and item_time <= date_time:\r\n aggregated_failure_count = aggregated_failure_count + 1\r\n if item_time >= two_minutes_time and item_time <= date_time:\r\n failure_repetition = failure_repetition + 1\r\n resource_id.append((hac_resource_name, date_time))\r\n if date_time_for_comparison == None:\r\n sqlQuery = \"INSERT INTO hacdata.hac_main(`configuration_resource_id`, `resource_name`, `HAC_resource_name`, `group_id`, `cluster_id`, `node_id`, `error_message`, `event_date`,`current_state`, `aggeregated_failure_count`, `failure_repetition`, `error_rating`,`dependency_factor`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s, %s )\"\r\n try:\r\n a.execute(sqlQuery, (\r\n configuration_resource_id, resource_name, hac_resource_name, group_id, cluster_id, node_id,\r\n error_msg, date_time, current_state, aggregated_failure_count, failure_repetition, 1,\r\n dependency_factor))\r\n conn.commit()\r\n except:\r\n print(\"Something went wrong for : \" + hac_resource_name + \" with timestamp \" + time_stamp)\r\n elif (date_time > date_time_for_comparison) or (number_of_rows_in_log_file_to_be_skipped == 0):\r\n sqlQuery = \"INSERT INTO hacdata.hac_main(`configuration_resource_id`, `resource_name`, `HAC_resource_name`, `group_id`, `cluster_id`, `node_id`, `error_message`, `event_date`,`current_state`, `aggeregated_failure_count`, `failure_repetition`, `error_rating`,`dependency_factor`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s, %s )\"\r\n try:\r\n a.execute(sqlQuery, (configuration_resource_id,resource_name, hac_resource_name, group_id, cluster_id, node_id, error_msg, date_time, current_state, aggregated_failure_count, failure_repetition, 1, dependency_factor))\r\n conn.commit()\r\n except :\r\n print(\"Something went wrong for : \"+ hac_resource_name + \" with timestamp \" + time_stamp)\r\n else:\r\n if date_time_for_comparison == date_time:\r\n number_of_rows_in_log_file_to_be_skipped = number_of_rows_in_log_file_to_be_skipped - 1\r\n","sub_path":"logInterface.py","file_name":"logInterface.py","file_ext":"py","file_size_in_byte":6600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"638715322","text":"import json\nfrom datetime import datetime\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import has_permissions, MissingPermissions\n\nget_channel_id = \"\"\nget_channel_name = \"\"\nget_json_name = \"\"\n\n\nclass e_ch(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n async def ech(self, ctx, args, ch_name, ch_nameFull):\n characters = \"<#>\"\n\n if args.startswith(\"<#\"):\n if args.endswith(\">\"):\n for i in range(len(characters)):\n args = args.replace(characters[i], \"\")\n if len(args) == 18:\n if discord.utils.get(ctx.guild.text_channels, id=int(str(args))):\n global get_channel_id\n global get_channel_name\n global get_json_name\n\n get_channel_name = self.bot.get_channel(int(str(args)))\n get_json_name = ch_name\n get_channel_id = args\n\n await ctx.send(f\"{ch_nameFull} 채널이 앞으로 \" + f\"<#{get_channel_id}>\" + \"에서 표시됩니다.\")\n\n with open('../bot/config.json', encoding='UTF8') as json_file:\n json_data = json.load(json_file)\n\n json_data[get_json_name] = f\"{get_channel_name}\"\n\n with open('../bot/config.json', 'w', encoding='UTF8') as json_file_save:\n json.dump(json_data, json_file_save, indent=\"\\t\", ensure_ascii=False)\n else:\n await ctx.send(\"해당 채널은 알수없는 채널입니다 다시 입력해주세요.\", delete_after=5.0)\n else:\n await ctx.send(\"채널을 맨션해주세요! (\\\"예 : #채널\\\")\", delete_after=5.0)\n else:\n await ctx.send(\"채널을 맨션해주세요! (\\\"예 : #채널\\\")\", delete_after=5.0)\n\n @commands.command()\n @has_permissions(manage_channels=True)\n async def 채널수정(self, ctx, *args):\n if args[0] == \"help\":\n chennel = await ctx.guild.create_text_channel(\"채널멘션\")\n tmp = await ctx.send(\n \"사용법 : /edit_channelname [wcn/bcn/ncn/lacn/cl] \" + chennel.mention + \"\\n\\n변경 가능한 채널 : \\n \"\n \" - wcn(환영인사)\\n - \"\n \"bcn(Bye Channel)\\n \"\n \" - ncn(처벌내역)\\n - \"\n \"lacn(내부공지)\\n - \"\n \"cl(채팅로그)\")\n delete_channel = discord.utils.get(ctx.guild.text_channels, name=\"채널멘션\")\n await delete_channel.delete()\n await tmp.edit(\n content=\"사용법 : /채널수정 [wcn/bcn/ncn/lacn/cl] #채널멘션\\n\\n변경 가능한 채널 : \\n - wcn(환영인사)\\n - bcn(\"\n \"Bye Channel)\\n - ncn(처벌내역)\\n - lacn(내부공지)\\n - cl(채팅로그)\")\n\n if args[0] == \"wcn\":\n await e_ch.ech(self, ctx, args[1], \"welcome_channel_name\", \"Welcome Channel\")\n elif args[0] == \"bcn\":\n await e_ch.ech(self, ctx, args[1], \"bye_channel_name\", \"Bye Channel\")\n elif args[0] == \"ncn\":\n await e_ch.ech(self, ctx, args[1], \"notice_channel_name\", \"처벌���역\")\n elif args[0] == \"lacn\":\n await e_ch.ech(self, ctx, args[1], \"local_announcement_channel_name\", \"내부공지\")\n elif args[0] == \"cl\":\n await e_ch.ech(self, ctx, args[1], \"chat_log\", \"채팅로그\")\n\n @채널수정.error\n async def 채널수정_error(self, ctx, error):\n if isinstance(error, MissingPermissions):\n mper = \"MANAGE_CHANNELS\"\n mp = discord.Embed(title=\"권한 부족 이벤트 발생!\", timestamp=datetime.utcnow(), color=0xfc7f03)\n mp.add_field(name=\"자세한 내용\", value=f\"당신은 `{mper}` 권한이 없어 해당 명령어 사용이 거부되었습니다. 자세한 내용은 관리자에게 문의해주세요.\",\n inline=True)\n mp.set_footer(text=\"BY - zz0#1446\")\n await ctx.send(ctx.message.author.mention, embed=mp)\n else:\n print(error)\n await self.bot.on_command_error(ctx, error)\n\n\ndef setup(bot):\n bot.add_cog(e_ch(bot))\n","sub_path":"bot/Cogs/채널수정.py","file_name":"채널수정.py","file_ext":"py","file_size_in_byte":4649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"394317900","text":"## -*- coding: utf-8 -*-\n##----------------------------------------------------------------------\n## interface_discovery helpers\n##----------------------------------------------------------------------\n## Copyright (C) 2007-2014 The NOC Project\n## See LICENSE for details\n##----------------------------------------------------------------------\n\n## NOC modules\nfrom noc.main.models import PyRule\nfrom noc.inv.models.interfaceclassificationrule import InterfaceClassificationRule\nfrom noc.settings import config\n\n\n_get_interface_profile = None\n\n\ndef prepare_classification():\n global _get_interface_profile\n\n p = config.get(\"interface_discovery\", \"classification_pyrule\")\n if p:\n # Use pyRule\n r = list(PyRule.objects.filter(name=p,\n interface=\"IInterfaceClassification\"))\n if r:\n # logging.info(\"Enabling interface classification pyRule '%s'\" % p)\n _get_interface_profile = r[0]\n else:\n #logging.error(\"Interface classification pyRule '%s' is not found. Ignoring\" % p)\n pass\n elif InterfaceClassificationRule.objects.filter(is_active=True).count():\n # Load rules\n #logging.info(\"Compiling interface classification rules:\\n\"\n # \"-----[CODE]-----\\n%s\\n-----[END]-----\" %\\\n # InterfaceClassificationRule.get_classificator_code())\n _get_interface_profile = InterfaceClassificationRule.get_classificator()\n\n\ndef get_interface_profile(interface):\n \"\"\"\n Perform interface classification and return interface profile name.\n Can be redefined in custom solutions\n :param interface: Interface instance\n :returns: profile name or None\n \"\"\"\n if _get_interface_profile:\n return _get_interface_profile(interface=interface)\n else:\n return None\n\n## Compile classification rule\nprepare_classification()","sub_path":"solutions/noc/default/discovery/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"116151841","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 22 15:05:04 2021\r\n\r\n@author: sauba\r\n\"\"\"\r\n\r\nfrom Bio import SeqIO\r\nfrom Bio.Seq import Seq\r\nSpecies= \"Cydia_pomonella\"\r\nGenome_name = \"GCA_003425675.2_Cpom.V2_genomic.fna\"\r\nScaff = \"QFTL02000035.1\"\r\nreverse_c = 0 #1 = yes, 0 = no\r\n# for pasting 15987935-15987831\r\nexon = \"Exon_7\"\r\nstart = 2258684\r\nend = 2258794\r\n\r\n#frame = 1\r\n\r\nif exon == \"Exon_1\":\r\n frame = 1\r\nelif exon == \"Exon_2\":\r\n frame = 1\r\nelif exon == \"Exon_3\":\r\n frame = 1\r\nelif exon == \"Exon_4\":\r\n frame = 3\r\nelif exon == \"Exon_5\":\r\n frame = 2\r\nelif exon == \"Exon_6\":\r\n frame = 2\r\nelif exon == \"Exon_7\":\r\n frame = 1\r\n\r\nout_Seq = ''\r\nfasta_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/\"+Genome_name),'r')\r\nfor record in SeqIO.parse(fasta_file,\"fasta\"):\r\n# print (record.id)\r\n if record.id == Scaff:\r\n sequence = str(record.seq)\r\n out_Seq = Seq(sequence[start-1:end])\r\n if reverse_c == 1:\r\n out_Seq = str(out_Seq)\r\n dna_seq = Seq(out_Seq)\r\n out_Seq = dna_seq.reverse_complement()\r\nif len(out_Seq) < 10000: #fixing error due to mistake in typing the coordinate, change this for longer sequence\r\n print (out_Seq)\r\n if frame == 1 :\r\n out_trans = out_Seq[0:]\r\n if frame == 2 :\r\n out_trans = out_Seq[1:]\r\n if frame == 3 :\r\n out_trans = out_Seq[2:]\r\n print (\"\\n\\n\"+out_trans.translate()) \r\nelse:\r\n print (\"too long\")\r\n assert(False)\r\n \r\n \r\n# break\r\nfasta_file.close()\r\nout_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/\"+exon+\"_yellow-e.fa\"),'w')\r\noutput_sequence = \">\"+Species+\"_Yellow_\"+Scaff+\"_\"+exon+\"_\"+str(start)+\"-\"+str(end)+\"\\n\"+str(out_Seq)+\"\\n\"\r\nout_file.write(output_sequence)\r\nout_file.close()\r\n\r\n\r\nif \"Exon_7\" in exon:\r\n exon_1_file = (open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/Exon_1_yellow-e.fa\"),'r')).readlines()\r\n exon_2_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/Exon_2_yellow-e.fa\"),'r').readlines()\r\n exon_3_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/Exon_3_yellow-e.fa\"),'r').readlines()\r\n exon_4_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/Exon_4_yellow-e.fa\"),'r').readlines()\r\n exon_5_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/Exon_5_yellow-e.fa\"),'r').readlines()\r\n exon_6_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/Exon_6_yellow-e.fa\"),'r').readlines()\r\n exon_7_file = open((\"F:/2021-04-22_Genomes/1.Lepidoptera/ncbi_dataset/data/\"+Species+\"/Exon_7_yellow-e.fa\"),'r').readlines()\r\n \r\n #print(exon_1_file)\r\n \r\n# out_comb = exon_1_file[0]+exon_1_file[1][:-1]+exon_2_file[1][:-1]+exon_3_file[1]\r\n out_comb = exon_1_file[0]+exon_1_file[1][:-1]+exon_2_file[1][:-1]+exon_3_file[1][:-1]+exon_4_file[1][:-1]+exon_5_file[1][:-1]+exon_6_file[1][:-1]+exon_7_file[1]\r\n out_comb_seq = Seq(out_comb.split(\"\\n\")[1])\r\n print(\"\\n\"+out_comb_seq.translate())\r\n out_comb_file = open((\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/Genes/1.Raw/1.Lepidoptera/5.Yellow-e/2.Extracted/\"+Species+\".txt\"),'w')\r\n out_comb_file.write(out_comb)\r\n out_comb_file.close()\r\n# exon_1_file.close()\r\n# exon_2_file.close()\r\n# exon_3_file.close()","sub_path":"sequence_extraction.py","file_name":"sequence_extraction.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"176371077","text":"import pandas as pd\nfrom visualise import word_cloud\nfrom nlp import transform\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score\n\n\ndef load_data():\n data = pd.read_csv(\"spam.csv\", encoding=\"latin-1\")\n data.drop(columns=data.columns[2:], inplace=True)\n data.columns = [\"label\", \"message\"]\n return data\n\n\ndef main():\n # 1. Load and transform\n data = load_data()\n data['label'] = data['label'].map({'ham': 0, 'spam': 1})\n messages = data['message'].apply(transform)\n\n # 1a. TD/IDF\n messages = messages.apply(lambda x: ' '.join(x))\n vectorizer = CountVectorizer()\n counts = vectorizer.fit_transform(messages)\n transformer = TfidfTransformer().fit(counts)\n counts = transformer.transform(counts)\n\n # 2. Visualize\n word_cloud(data[data[\"label\"] == 0][\"message\"])\n word_cloud(data[data[\"label\"] == 1][\"message\"])\n\n # 3. Train\n X_train, X_test, y_train, y_test = train_test_split(\n counts, data['label'], test_size=0.25, random_state=69)\n c = MultinomialNB()\n c.fit(X_train, y_train)\n\n # 4. Test\n predictions = c.predict(X_test)\n print(accuracy_score(y_test, predictions))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"01-naive-bayes-spam-code/01-naive-bayes-spam/tf_idf_filter.py","file_name":"tf_idf_filter.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"651774195","text":"import re\n\ndef checkItemValidity(val:list)->bool:\n if val[0] == 'byr':\n byr = int(val[1])\n if byr <= 2002 and byr >= 1920:\n return True\n if val[0] == 'iyr':\n iyr = int(val[1])\n if iyr <= 2020 and iyr >= 2010:\n return True\n if val[0] == 'eyr':\n eyr = int(val[1])\n if eyr <= 2030 and eyr >= 2020:\n return True\n if val[0] == 'hgt':\n hgt = val[1]\n p = re.compile(\"(.[0-9]*)(.[a-z]*)\")\n result = p.search(hgt)\n height = int(result.group(1))\n unit = result.group(2)\n if (unit == \"cm\"):\n if(height >= 150 and height <= 193):\n return True\n elif (unit == \"in\"):\n if(height >= 59 and height <= 76):\n return True\n if val[0] == 'hcl':\n p = re.compile(\"#[0-9a-f]{6}\")\n result = p.search(val[1])\n if result:\n return True\n if val[0] == 'ecl':\n colourValid = {'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'}\n if val[1] in colourValid:\n return True\n if val[0] == 'pid':\n p = re.compile(\"[0-9]{9}\")\n result = p.search(val[1])\n if result and len(val[1]) == 9:\n return True\n\n return False\n \n\ndef checkValidity(detail:list)->bool:\n mandatory = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}\n for val in detail:\n val = val.split(\":\")\n if val[0] in mandatory:\n if(checkItemValidity(val)):\n mandatory.remove(val[0])\n if len(mandatory) > 0:\n return False\n return True\n\ndef part(details:list)->int:\n count = 0\n for detail in details:\n detail = detail.split()\n if checkValidity(detail):\n count += 1\n return count\n\ndef main():\n # Read textfile\n f = open(\"input.txt\", 'r')\n lines = f.read()\n lines = lines.split(\"\\n\\n\")\n \n print(part(lines)) \n \nif __name__ == \"__main__\":\n main()\n \n ","sub_path":"adventOfCode/day4/day4.py","file_name":"day4.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"114598371","text":"# 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-)\nimport os\nimport time\nfrom bs4 import BeautifulSoup\nimport urllib.request\nimport urllib\n\n\ndef download_pic(url_pic,local_pic):\n urllib.request.urlretrieve(url_pic, local_pic)\n pass\n\n\nurl = 'https://www.enterdesk.com/zhuomianbizhi/secaibizhi/'\nheaders = {'User-agent':'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0'}\nr = urllib.request.Request(url, headers=headers)\nresponse = urllib.request.urlopen(r, timeout=20)\nhtml = response.read()\nsoup = BeautifulSoup(html, 'lxml')\na = soup.find_all('img')\n# 创建目录\nfile_name = r'E:\\pythonProgram\\LittleProgram\\picture'\n\nif not os.path.exists(file_name):\n os.mkdir(file_name)\n\nfor i, j in zip(a, range(len(a))):\n local_pic_path = os.path.join(file_name, str(j)+'.png')\n time.sleep(2)\n print('{0}/{1}'.format(j + 1, len(a)))\n print(i['src'])\n try:\n download_pic(i['src'], local_pic=local_pic_path)\n except:\n continue\nprint('下载完成')\n\n","sub_path":"OtherCode/spider_pictures.py","file_name":"spider_pictures.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"202216703","text":"# -*- coding: utf-8 -*-\n\"\"\"\nStandard Quicksort with Normal Partition\nCreated on Sat Jul 17 00:10:11 2021\n@author: howez\n\"\"\"\n\ndef QUICKSORT(A,p,r):\n if len(A) == 1:\n return A\n if p', root1.destroy())\n but.pack()\n root1.mainloop()\n else:\n Playlist_saver = open(Playlists_folder + str(Artist) + '.m3u', 'tw',\n encoding='utf-8')\n for folder, subdirs, files in os.walk(music_folder + os.listdir(music_folder)[Ch]):\n for filename in fnmatch.filter(files, pattern):\n fullname = os.path.join(folder, filename)\n Playlist_saver.write(\"\\n\" + fullname.replace('\\\\', '/'))\n\n for filename in fnmatch.filter(files, pattern_2):\n fullname = os.path.join(folder, filename)\n Playlist_saver.write(\"\\n\" + fullname.replace('\\\\', '/'))\n Playlist_saver.close()\n Ch = Ch + 1\n except:\n return 'sucks'\n\nbutton_strt = Button(root, text='НАЧАТЬ', width=21, height=3, bg='red', fg='white', font='arial 14',\n command=button_start)\nbutton_strt.pack()\nroot.mainloop()\n\n","sub_path":"Script with Buttons.py","file_name":"Script with Buttons.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"124634716","text":"import yaml\n\n\ndef ini_case(_path, case_file):\n \"\"\"\n case初始化.yml测试用例\n :param _path: case路径\n :param case_file: case名称\n :return:\n \"\"\"\n try:\n with open(_path + '/' + case_file + '.yml', 'r', encoding=\"utf-8\") as f:\n project_dict = yaml.load(f,Loader=yaml.FullLoader)\n except FileNotFoundError:\n with open(_path + '/' + case_file + '.yaml', 'r', encoding=\"utf-8\") as f:\n project_dict = yaml.load(f,Loader=yaml.FullLoader)\n return project_dict\n\n\n# if __name__ == '__main__':\n# path = r'F:/pythoncode/learn_pytest_20200720/page/home'\n# case_file = 'famous_list'\n# print(ini_case(path, case_file))","sub_path":"unit/initializeCase.py","file_name":"initializeCase.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"5687615","text":"from sys import stdin\n\ndef mergeSort(alist,cont):\n cont+=1\n if len(alist)>1:\n mid = len(alist)//2\n lefthalf = alist[:mid]\n righthalf = alist[mid:]\n\n mergeSort(lefthalf,cont)\n mergeSort(righthalf,cont)\n\n i=0\n j=0\n k=0\n while i < len(lefthalf) and j < len(righthalf):\n if lefthalf[i] < righthalf[j]:\n alist[k]=lefthalf[i]\n i=i+1\n else:\n alist[k]=righthalf[j]\n j=j+1\n k=k+1\n\n while i < len(lefthalf):\n alist[k]=lefthalf[i]\n i=i+1\n k=k+1\n\n while j < len(righthalf):\n alist[k]=righthalf[j]\n j=j+1\n k=k+1\n print(cont)\n return alist\n\n\n\ndef main():\n lis=[]\n res=\"\"\n n=int(stdin.readline().strip())\n a=stdin.readline().strip().split()\n for i in range(len(a)):\n lis.append(int(a[i]))\n c=mergeSort(lis,0)\n res=str(c[0])+\" \"+str(c[len(c)-1])\n print(res)\n\n\nmain()\n","sub_path":"laboratorios/Lab-3/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"519587357","text":"###########################################\n# Author: Malay Agarwal\n# Problem: \n# . Implement a data structure to \n# accomplish this, with the following API:\n# record(order_id): adds the order_id to \n# the log\n# get_last(i): gets the ith last element \n# from the log. i is guaranteed to be \n# smaller than or equal to N.\n###########################################\n\nclass CircQueue:\n def __init__(self, size):\n self.size = size\n self.data = [None for i in range(size)]\n self.front, self.rear = None, None\n\n\n def record(self, order_id):\n if(self.front is None):\n self.front, self.rear = 0, -1\n elif((self.rear+1)%self.size == self.front):\n self.front = (self.front+1)%self.size\n self.rear = (self.rear+1)%self.size\n self.data[self.rear] = order_id\n\n\n def get_last(self, i):\n index = (self.front + self.size - i)%self.size\n return self.data[index]\n\nqueue = CircQueue(3)\nqueue.record(1)\nqueue.record(2)\nqueue.record(3)\nqueue.record(4)\nqueue.record(5)\nqueue.record(6)\nprint (queue.get_last(2))\nprint (queue.get_last(1))","sub_path":"Day13.py","file_name":"Day13.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"86120652","text":"import h5py\nimport csv\nimport sys\n\n\"\"\" first argument: \n second argument: /path/to/output.csv\n\n\"\"\" \n\nhdf5_path = sys.argv[1]\ncsv_path = sys.argv[2]\n\nh5pyFile = h5py.File(hdf5_path,'r')\ncoord = h5pyFile[\"/PartType0/Coordinates\"]\nmasses = h5pyFile[\"/PartType0/Masses\"]\n\n\ncsvFile = open(csv_path,'wb')\nwriter = csv.writer(csvFile,delimiter = ' ')\nwriter.writerow([masses[0]])\nfor c in coord:\n writer.writerow(c)\ncsvFile.close() \n\nh5pyFile.close()\n","sub_path":"bachelorthesis/evaluation/code/hdf5_to_csv.py","file_name":"hdf5_to_csv.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"106643424","text":"# -*- coding: utf-8 -*-\n\"\"\"Base pytest configuration file.\"\"\"\nimport json\nimport os\nimport shutil\nimport sys\n\nimport pytest\nfrom tcex import TcEx\nfrom .tc_token import TcToken\n\n\n# instance of tc token to retrieve testing token from API\ntc_token = TcToken()\n\n\n# install.json data for testing\npytest_install_json = {\n 'allowOnDemand': True,\n 'commitHash': 'abc123',\n 'displayName': 'Pytest',\n 'features': ['aotExecutionEnabled', 'appBuilderCompliant', 'layoutEnabledApp', 'secureParams'],\n 'languageVersion': '3.6',\n 'listDelimiter': '|',\n 'note': '',\n 'params': [\n {\n 'label': 'My Book',\n 'name': 'my_bool',\n 'note': '',\n 'required': True,\n 'sequence': 1,\n 'type': 'Boolean',\n },\n {\n 'label': 'My Multi',\n 'name': 'my_multi',\n 'note': '',\n 'required': False,\n 'sequence': 8,\n 'type': 'MultiChoice',\n 'validValues': ['one', 'two'],\n },\n ],\n 'playbook': {'outputVariables': [], 'type': 'Utility'},\n 'programLanguage': 'PYTHON',\n 'programMain': 'run',\n 'programVersion': '1.0.0',\n 'runtimeLevel': 'Playbook',\n}\n\n\n#\n# Standard config for tcex instance\n#\n\n_config_data = {\n # connection\n 'api_default_org': os.getenv('API_DEFAULT_ORG'),\n # 'tc_token': tc_token.service_token,\n 'tc_token': tc_token.api_token,\n 'tc_token_expires': '1700000000',\n 'tc_owner': os.getenv('TC_OWNER', 'TCI'),\n # hmac auth (for session tests)\n 'api_access_id': os.getenv('API_ACCESS_ID'),\n 'api_secret_key': os.getenv('API_SECRET_KEY'),\n # logging\n 'tc_log_level': os.getenv('TC_LOG_LEVEL', 'trace'),\n 'tc_log_to_api': str(os.getenv('TC_LOG_TO_API', 'false')).lower() in ['true'],\n # paths\n 'tc_api_path': os.getenv('TC_API_PATH'),\n 'tc_in_path': os.getenv('TC_IN_PATH', 'log'),\n 'tc_log_path': os.getenv('TC_LOG_PATH', 'log'),\n 'tc_out_path': os.getenv('TC_OUT_API', 'log'),\n 'tc_temp_path': os.getenv('TC_TEMP_PATH', 'log'),\n # playbooks\n 'tc_playbook_db_type': os.getenv('TC_PLAYBOOK_DB_TYPE', 'Redis'),\n 'tc_playbook_db_context': os.getenv(\n 'TC_PLAYBOOK_DB_CONTEXT', '0d5a675a-1d60-4679-bd01-3948d6a0a8bd'\n ),\n 'tc_playbook_db_path': os.getenv('TC_PLAYBOOK_DB_PATH', 'localhost'),\n 'tc_playbook_db_port': os.getenv('TC_PLAYBOOK_DB_PORT', '6379'),\n # proxy\n 'tc_proxy_tc': str(os.getenv('TC_PROXY_TC', 'false')).lower() in ['true'],\n 'tc_proxy_external': str(os.getenv('TC_PROXY_EXTERNAL', 'false')).lower() in ['true'],\n}\n\n# proxy\nif os.getenv('TC_PROXY_HOST'):\n _config_data['tc_proxy_host'] = os.getenv('TC_PROXY_HOST')\nif os.getenv('TC_PROXY_PORT'):\n _config_data['tc_proxy_port'] = os.getenv('TC_PROXY_PORT')\nif os.getenv('TC_PROXY_USERNAME'):\n _config_data['tc_proxy_username'] = os.getenv('TC_PROXY_USERNAME')\nif os.getenv('TC_PROXY_PASSWORD'):\n _config_data['tc_proxy_password'] = os.getenv('TC_PROXY_PASSWORD')\n\n\ndef pytest_configure(config): # pylint: disable=unused-argument\n \"\"\"Execute configure logic.\n\n Allows plugins and conftest files to perform initial configuration. This hook is called for\n every plugin and initial conftest file after command line options have been parsed.\n \"\"\"\n\n # remove log directory\n try:\n shutil.rmtree('log')\n except OSError:\n pass\n\n # create testing install.json\n with open('install.json', 'w') as fh:\n json.dump(pytest_install_json, fh, indent=2)\n\n\ndef pytest_sessionstart(session): # pylint: disable=unused-argument\n \"\"\"Execute session start logic.\n\n Runs after the Session object has been created and before performing collection and entering\n the run test loop.\n \"\"\"\n\n\ndef pytest_sessionfinish(session, exitstatus): # pylint: disable=unused-argument\n \"\"\"Execute session finish logic.\n\n Runs after whole test run completes, before returning the exit status.\n \"\"\"\n\n\ndef pytest_unconfigure(config): # pylint: disable=unused-argument\n \"\"\"Execute uncofigure logic before test process is exited.\"\"\"\n try:\n # remove temp install.json directory\n os.remove('install.json')\n except OSError:\n pass\n\n\n#\n# fixtures\n#\n\n\n# @pytest.fixture(scope='module')\n@pytest.fixture()\ndef config_data():\n \"\"\"Return tcex config data.\"\"\"\n return _config_data\n\n\n@pytest.fixture()\ndef tc_api_token():\n \"\"\"Return a valid TC api token.\"\"\"\n return tc_token.api_token\n\n\n@pytest.fixture()\ndef tc_log_file():\n \"\"\"Return tcex config data.\"\"\"\n return _tc_log_file()\n\n\n@pytest.fixture()\ndef tc_service_token():\n \"\"\"Return a valid TC service token.\"\"\"\n return tc_token.service_token\n\n\n@pytest.fixture()\ndef tcex():\n \"\"\"Return an instance of tcex.\"\"\"\n # create log structure for feature/test (e.g., args/test_args.log)\n config_data_ = dict(_config_data)\n config_data_['tc_log_file'] = _tc_log_file()\n\n # clear sys.argv to avoid invalid arguments\n sys.argv = sys.argv[:1]\n return TcEx(config=config_data_)\n\n\n@pytest.fixture()\ndef tcex_proxy_external():\n \"\"\"Return an instance of tcex.\n\n mitmproxy -p 4242 --ssl-insecure\n \"\"\"\n # create log structure for feature/test (e.g., args/test_args.log)\n config_data_ = dict(_config_data)\n config_data_['tc_proxy_external'] = True\n config_data_['tc_proxy_host'] = 'localhost'\n config_data_['tc_proxy_port'] = '4242'\n\n # clear sys.argv to avoid invalid arguments\n sys.argv = sys.argv[:1]\n return TcEx(config=config_data_)\n\n\n#\n# misc functions\n#\n\n\ndef _tc_log_file():\n \"\"\"Return config file name for current test case.\"\"\"\n test_data = os.getenv('PYTEST_CURRENT_TEST').split(' ')[0].split('::')\n test_feature = test_data[0].split('/')[1].replace('/', '-')\n test_name = test_data[-1].replace('/', '-').replace('[', '-')\n return os.path.join(test_feature, '{}.log'.format(test_name))\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":5907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"28858935","text":"\"\"\"\nExercise 5: Take the following Python code that stores a string:\nstr = 'X-DSPAM-Confidence:0.8475'\nUse find and string slicing to extract the portion of the string after\nthe colon character and then use the float function to convert the extracted string\ninto a floating point number.\n\"\"\"\n\ndef main():\n \"\"\"main function to output float in a string\"\"\"\n string = 'X-DSPAM-Confidence:0.8475'\n pos = string.find(':')\n num = float(string[pos + 1 :])\n print (num)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Chap6/exercise6_5.py","file_name":"exercise6_5.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"69693109","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 29 14:34:15 2019\n\n@author: Jian Zhou\n\"\"\"\n\nimport torch\nimport torch.optim as optim\nfrom Load_inputs import Dataloder # Load the whole video\n#from model import Net\nimport torch.nn as nn\nimport numpy as np\nimport time\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n#from Model3D import NET\n#from CNN3D_archt2 import NET\nfrom Model3DTest import NET\nimport torchvision\nfrom torchvision import transforms\n\nfrom PIL import Image\nimport os\nimport os.path\nimport random\n\n# Test git push 2\n\n# net = Net()\n# print(net)\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\ncuda=torch.device('cuda')\n\nNet3D = NET()\n# Net3D = Net3D.double()\n'''\ndataloader = Dataloder()\n\ninputloader, Num_input = dataloader.getloader()\n# Num_input: Total number of input images\nprint('Num of input images = ', Num_input, '\\n')\n'''\n\ncriterion = nn.CrossEntropyLoss(weight=torch.Tensor([0.3,1.0]).cuda())# Initial: 0.005,0.1. Real(0) 8293, (1)1691\n# 80 out of 401 frames from E044_Max_13 over all time period \n # 0.15, 1.0, Epo 35 LrINI=0.01 lr=0.01, Lr_decay=10: 0.993, 0.965; 8185(8197), 1679(1787);\n \n # 0.3, 1.0, Epo 35 LrINI=0.01 lr=0.01, Lr_decay=10: 0.995, 0.975; 8219(8230), 1680(1754); \n # Epo 35 lrINI=0.1 lr=0.01, Lr_dacay=10: 0.981, 0.913; 8034(8086), 1639(1898); \n # Epo 60 lrINI=0.01 lr=0.01, Lr_dacay=15: 0.996, 0.980; 8235(8244), 1682(1740). BEST!\n \n # Epo 35 LrINI=0.01 lr=0.01, Lr_decay=5: 0.984, 0.920; 8159(8296), 1554(1688);# lr becomes useless when it's too smaller. lr should NOT be used for too short epoch\n # Epo 60(35 is enough!) LrINI=0.01, lr=0.01, Lr_decay=15: 0.996, 0.978; 8225(8233), 1683(1751);\n # 0.4, 1.0, Epo 35 LrINI=0.01 lr=0.01, Lr_decay=10: 0.994, 0.971; 8220(8247), 1664(1737);\n\n# First 80 out of 402 frames from E040_Min_13\n # 0.3, 1.0, Epo 35 lrINI=0.01 lr=0.01, Lr_dacay=15: 0.999, 0.973; 9476(9497), 481(487).\n \n \noptimizer = optim.SGD(Net3D.parameters(), lr=0.01, momentum=0.9)\n#Stochastic Gradient Descent simplest update weights \n\ndef adjust_lr(optimizer, epoch, lr_decay=15):\n lr = 0.01 *(0.1**((epoch)//lr_decay))# epoch-1\n if (epoch) % lr_decay == 0: # epoch-1\n print('LR is set to: ', lr)\n \n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef compute_acc(pred, label): # calculate accuracy\n pred = pred.unsqueeze(1)\n # Increase a dimension of pred in order to compare with label\n #label = label.unsqueeze(1)# Extend 1 dimension because it has one less dimension compared with pred!\n \n # print(' pred size in comput_acc:', pred.shape)\n # print(' label size in comput_acc:', label.shape,'\\n')\n # print(' '.join('%5s' % classes[pred[j]] for j in range(2)))\n \n acc_sum = (pred == label).sum()\n # Totally 96*104*batchsize. predictions/comparisons.\n return acc_sum.item()\n\n\ndef compute_F(pred, label): # calculate F1 scores for 2 labels\n pred = pred.unsqueeze(1).numpy()\n label = label.numpy()\n # Make pred and label have same dimensions, 5 dimensions\n \n # print('pred size in compute_F = ', pred.shape)\n # print('label size in compute_F = ', label.shape,'\\n')\n \n # print(Counter(label.reshape(-1)))\n # Totally 96*104*batch_size predictions/comparisons\n Pred_Tru = []\n # All returned true\n Real_Tru = []\n # All real true\n Corr_Tru = []\n # Correct predicted true\n \n for i in range(2):# Based on the number of classes\n Pred_Tru.append((pred == i).sum())\n Real_Tru.append((label == i).sum())\n Corr_Tru.append(((pred == i)*(label == i)).sum())\n # classes = ['outside','onside'] deined in find_classes():\n \n return Pred_Tru, Real_Tru, Corr_Tru\n\ndef Read_label(labeldir):\n LABELS = []\n Labels = [] # np.zeros(((1,96,104)))\n CountLabl=0\n \n for filename in os.listdir(labeldir):\n LABELS.append(filename)\n CountLabl +=1\n for filename in os.listdir(labeldir):\n LABELS[int(filename[7:-4])-1]=filename# LABELS[0] stores 'GrdTruh13.png'. Here 7:-4 means 13.\n \n for i in range(CountLabl):\n _Label = os.path.join(labeldir, LABELS[i])# print(_image) # : Data\\Inputs\\Label\\GrdTruhX.png. Labeldir is 'Data\\\\Inputs\\\\Label'\n _Labels = Image.open(_Label) \n # print(' Type of _Labels is ', type(_Labels)) # Type is \n # print(' Size of _Labels is ', _Labels.shape)\n \n _Labels = transforms.ToTensor()(_Labels)\n # print('Shape of _Labels is ', _Labels.shape)\n\n Labels.append(_Labels) # Labels' type is \n \n return Labels\n \n################################################ \n'''\n LABELS = []\n _label=os.path.join(labeldir,'GrdTruh.png')\n \n LABELS.append(_label)# class 'list'\n # print('shape of _label is ', np.shape(LABELS)) # (1,)\n\n _Labels = Image.open(LABELS[0])\n # Class list cannot use read \n #LABELS=np.asarray(_Labels)\n #print('shape of LABELS is ', LABELS.shape)# [96,104]\n \n _Labels = transforms.ToTensor()(_Labels)\n # print('Shape of _Labels is ', _Labels.shape) [1,96,104]. Automatically add one dimension to _Labels\n # transforms.ToTensor() only works for numpy with 2 dimensons or 3 dimensons \n return _Labels\n'''\n################################################\n\n\n########## Main function ##############\n# t3 = time.time()\n'''\noutput_target = [] \nnet.load_state_dict(torch.load('model.ckpt'))# Load the trained 2DCNN model.\n# This 2D CNN model is trained(290 frames) and tested(100 frames), for E044_Max_13. \n\n#INPTIMGS=np.zeros(((401, 96, 104)))\n \n#for i, data in enumerate(inputloader, 0):\n# INPUTS = data\n# INPTIMGS[i,:,:] = INPUTS[0,0,:,:] # inputs_size:[1,1,96,104]\n \n #if i==3:\n # plt.imshow(inputs[0,0,:,:])\n # break\n ## Starts from i=183 to i=400, all images are zeros!!!!!?????\n \nwith torch.no_grad():\n net.eval()\n \n T_0 = 0\n Pred = []\n \n# Based on trained 2DCNN model, predict on the whole video frames to identify central circle. Find T_0\n for i, data in enumerate(inputloader, 0):# of total frames, batch size is 1\n # i iteration starts from 0 !\n \n # print('Current image is ',i, '\\n')\n inputs = data\n # inputs_size: [batch size, # of input channels(image value of each pixel), # of rows, # of columns]\n # [1,1,96,104]\n #plt.imshow(inputs[0,0,:,:])\n \n outputs = net(inputs)# Outputs_size: [1 batch size, 2 (Probility of being each class), 96 of rows, 104 of columns]\n _, pred = torch.max(outputs, dim=1)\n # pred_size: [1,96,104], Pick the highest probility of belonging to a class at each pixel\n \n # print('Orig output_size = ', outputs.size()) # [1,2,96,104]\n # print('Orig pred size = ', pred.size()) # [1,96,104]\n \n Pred = pred.numpy()# type is numpy.ndarray\n \n [Deph,Heit,Widt]=Pred.shape\n # pred_size is [1 (batch size),96,104]\n # plt.imshow(Pred[0,:,:])\n #if i==3:\n # plt.imshow(inputs[0,0,:,:])\n # break\n \n if Pred[0, int(Heit/2-1), int(Widt/2-1)] == 1:\n # Find the 1st predicted frame that has a circle in the center, i.e., if center posization (47,51) is 1.\n # \n T_0 = i # Starts from 0!\n print ('T_0 = ',T_0, ', Count from 0', '\\n')\n # print ('Size of selected Pred = ', Pred[0,:,:].shape)\n # plt.imshow(Pred[0,:,:])\n \n #print('Pred[0,47,51] = ', Pred[0,47,51], ', Max of Pred[0,:,:] = ', np.max(Pred[0,:,:]))\n # Check what's the range of Pred[]\n # Whether Prediction of a frame is in [0 ~ 1]!!!\n break\n \n PRED = np.zeros(((Num_input, Heit, Widt)))# type is numpy.ndarray\n # Store all predicted frames with pixels labeled as either 0 or 1\n # print('Shape of PRED = ', PRED.shape, end = '\\n\\n')\n # (401,96,104)\n \n NwMatrix = np.zeros(((Num_input - T_0, Heit, Widt)))\n # Store predicted frames starts from T_0\n \n NewMatrix = np.zeros(((1, Heit, Widt))) # Store predicted frames having central rectangle\n Fram = np.zeros((Heit, Widt))\n InputImags = np.zeros(((Num_input, Heit, Widt)))\n # Store all modified input images\n InptFram = np.zeros(((Num_input-T_0, Heit, Widt)))\n INPTFram = np.zeros(((1, Heit, Widt)))\n \n for i, data in enumerate(inputloader, 0):# i: Total # of input frames, because batch size is 1\n \n inputs = data\n \n InputImags[i,:,:] = inputs[0,0,:,:] # inputs_size:[1,1,96,104]. Range is in [0.0, 1.0]\n \n outputs = net(inputs)\n # print('Input type is ', type(inputs),', Output type is ', type(outputs))\n # input/output type is Totensor\n _, pred = torch.max(outputs, dim=1)\n \n PRED[i,:,:]=pred.numpy()\n # if PRED[i, int(Heit/2-1), int(Widt/2-1)] !=1:\n \n # Predict pixels on each frame for being 0 or 1 \n \n # print('Current iteration = ', i+1)\n \n # print('Type of inputs = ', type(inputs),'\\n', 'Shape of inputs = ', inputs.shape) # [Tensor, [1,1,96,104]\n # print('\\n','Type of outputs = ', type(outputs), '\\n', 'Shape of outputs = ', outputs.shape) # Tensor, [1,2,96,104]\n print('Prediction based on trained 2DCNN is finished...', '\\n')\n \n T_abnol = 0\n # Stores NO. of frame that is predicted abnormally, i.e., no center circle in the frame\n \n######## Centering the rectangle of each frame after T_0\n for i in range (T_0, Num_input):# i from T_0 to (Num_input-1) \n Flag = 0\n \n # print('Current iteration = ', i-T_0+1)\n if PRED[i, int(Heit/2-1), int(Widt/2-1)] != 1:\n # Find frames that don't have a central circle after T_0\n T_abnol = np.append(T_abnol,i) \n # 1st item of T_abnol is 0, which should be disgarded. Before T_0 also should be recorded\n continue\n else:\n TemFra = InputImags[i,:,:][np.newaxis] # Make it to be 3 dimensions. for numpy.ndarray\n INPTFram = np.append(INPTFram, TemFra, axis=0)\n \n print('Shape of INPTFram = ', INPTFram.shape)\n \n IpVide = INPTFram[1:INPTFram.shape[0],:,:][np.newaxis][np.newaxis]\n print('Shape of IpVide = ', IpVide.shape)\n \nprint(' 2DCNN predicted outliers are ', T_abnol)\n# t4 = time.time()\nprint('Total time of 2D CNN based processing is {:.4f} sec'.format(t4-t3),'\\n')\n\n#NewInpVid=np.zeros(((Num_input-T_0,96,104)))\nNewInpVid=np.zeros(((IpVide.shape[2],96,104)))\n\nfor i in range (IpVide.shape[2]):\n NewInpVid[i,:,:] = IpVide[0,0,i,:,:]\n# for i in range (80):# Select every 4 frame to form the input for 3DCNN model\n# NewInpVid[i,:,:] = IpVide[0,0,4*i,:,:] # The last frame is No. 316, which starts from 0.\n#NewInpVid[79,:,:]=IpVide[0,0,IpVide.shape[2]-1,:,:]\n\n# for i in range(80):\n# NewInpVid[i,:,:] = IpVide[0,0,i,:,:]# First 80 video frames which have center nuggets as 3D inputs. Last 80 frames: -i-1\n # Range in [0.0,1.0]\n# Labels = Read_label('Data\\\\Inputs\\\\Label')\n\nNewInpVid = transforms.ToTensor()(NewInpVid[:,:,:])\n# Converts a PIL Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].\n\nNewInpVid = NewInpVid.permute(1,2,0) # Original NewInpVid has 3 dimensions\nprint('Shape of NewInpVId = ', NewInpVid.shape) # [Num of frames,96,104]\n \n#NewInpVid = NewInpVid.unsqueeze(0).unsqueeze(0) # for torch.tensor \n#print('Shape of NewInpVId = ', NewInpVid.shape, ', Type of NewInpVid = ', type(NewInpVid))# [1,1,80,96,104], Tensor\n\nNum_Sepa=50 # Continuous 50 frames are used as a input for training 3D CNN model\nNum_Dis=7\nNum_Ite=6\n\nINPUT = np.zeros(((1, Heit, Widt)))\nfor i in range (Num_Ite):\n for j in range (Num_Sepa):\n TMPIMG = NewInpVid[Num_Dis*j+i,:,:][np.newaxis]\n INPUT = np.append(INPUT, TMPIMG, axis=0)\n # INPUT = torch.cat((INPUT, TMPIMG), 0)\nINPUT = INPUT [1:INPUT.shape[0],:,:] # All training datasets are stored in INPUTS continuously\nprint(' Size of INPUT is ', INPUT.shape, ', Type of INPUT is ', type(INPUT))\n\n\n#INPUT = transforms.ToTensor()(INPUT[:,:,:])\n#INPUT = INPUT.permute(1,2,0) # Original NewInpVid has 3 dimensions\n#print(' Size of INPUT after ToTensor is ', INPUT.shape, ', Type of INPUT after ToTensor is ', type(INPUT))\n'''\n# t4 = time.time()\n\n################### Start to train CNN 3D model #############\nprint('Frames updating finished,', '3D CNN starts...', '\\n')\n\n#cuda = torch.device('cuda')\n#with torch.cuda.device(0):\n\n#Net3D.load_state_dict(torch.load('model3D.ckpt')) \nNet3D.to(cuda)\n\nLabelS = Read_label('Inputs/Label') # Read the ground truth for actual measured nugget \n# print('Type of Labels is ', type(Labels), ', Size of Labels is ', len(Labels)) # class 'list'. Size is the number of nugget ground truth\n\n#LabelS = LabelS.to(cuda) # send the inputs and targets at every step to the GPU too\n\nY=66 #For E040-44 96*104; For E50-54: 92*104; For E68-72: 74*94; For E63-67: 60*78; For E47-49: 104*184; For E75-78: 66*90; For E59-61: 102*118\nX=90\n\nLabels = torch.tensor(np.zeros(((len(LabelS), Y, X))), device=cuda)\n'''\n# For E068-072\nfor i in range(8):\n Labels[i,:,:] = LabelS[i][0,5:79,9:103]\nfor i in range(2):\n Labels[i+8,:,:]=LabelS[i+8][0,:,1:95]\n'''\n#for i in range(10): #For E040-044 OR E50-54\n# Labels[i,:,:] = LabelS[i][0,:,:] \n\n#for i in range(6):# For E047-049\n# Labels[i,:,:]=LabelS[i][0,1:105,1:185]\n\n \n# For E063-067\n#Lab=4\n#for i in range(Lab):\n# Labels[i,:,:] = LabelS[i][0,:,1:79]\n#for i in range(6):\n# Labels[i+Lab,:,:]=LabelS[i+Lab][0,5:65,1:79]\n\nfor i in range(4): #For E075-76 (81*100 to 66*90)\n Labels[i,:,:] = LabelS[i][0,7:73,5:95] \nfor i in range(4): #For E77-78\n Labels[i+4,:,:]=LabelS[i+4][0,:,:]\n\n#for i in range(6):\n# Labels[i,:,:] = LabelS[i][0,1:103,1:119]\n#for i in range(4):\n# Labels[i+4,:,:]=LabelS[i+4][0,:,:]\n\n# labels shape are [# of considered,Y,X], type is torch.tensor\n#Labels = torch.cat(tuple(Labels)) # After this, Labels' size is [# of labels considered,96,104], type is torch.tensor\n# print(' After torch.cat, type of Labels is ' , type(Labels), ', size of Labels is ', Labels.shape)\n\nLabels = 255 * Labels \n\n#Inputs=np.append(Input_13_50_7_45,Input_14_50_7_45,axis=0)\n#Inputs=np.append(Inputs,Input_15_50_7_45,axis=0)\n\n# data=np.load('Input_13.npy')\n\n#Inputs=np.load('Input_{:}_NoOtlrs.npy'.format(1)) # Load E040-E044\n#for i in range (9): \n# Inputs=np.append(Inputs,np.load('Input_{:}_NoOtlrs.npy'.format(i+2)),axis=0)\n\nInputs=np.load('Input_{:}_ExaNor.npy'.format(1)) # Load E068-72\n#Inputs=np.load('Input_{:}.npy'.format(1)) # Load E050-E054\n#Inputs=np.load('Input_pix_{:}.npy'.format(1))\n\nfor i in range (len(LabelS)-1): \n #Inputs=np.append(Inputs,np.load('Input_pix_{:}.npy'.format(i+2)),axis=0)\n Inputs=np.append(Inputs,np.load('Input_{:}_ExaNor.npy'.format(i+2)),axis=0)\n #Inputs=np.append(Inputs,np.load('Input_{:}.npy'.format(i+2)),axis=0)\n\n#Inputs = Inputs.to(cuda) # send the inputs and targets at every step to the GPU too\n\nINputs= transforms.ToTensor()(Inputs)\nINputs = INputs.permute(1,2,0) # shape is [# of frames, height, width]\n\nINputs = INputs.to(cuda)\n\n# print('Type of INputs is ', type(INputs), ', Size of INputs is ',INputs.shape)\n# INputs = INputs.unsqueeze(0)\n# print('Shape of INputs is ', INputs.shape)\n\nLen_Frm = 30\nNum_Dat=int(INputs.shape[0]/Len_Frm) # Total num of datasets\nTag=np.zeros(Num_Dat)\nStep=7\nNum_Tst=len(LabelS) # Num of datasets left as test datasets\nNum_EchDat=35 # Num of datasets for each video\n\nfor i in range (int(Num_Dat/Num_EchDat)):# Store each sub-video dataset Tag to identify which nugget ground truth should be used.\n Tag[Num_EchDat*i:Num_EchDat*i+Num_EchDat]=i # 0~(Num_EchDat-1): 0; Num_EchDat~(2Num_EchDat-1): 1; ...9 \n\nRodmlst=[] \nRodmlst=random.sample(range(0,Num_Dat),Num_Dat) # Permute sub-video datasets in a random order. from 0 to Tag.size-1, randomly select Tag.size number of values\n\nfor epoch in range (10):\n t1=time.time()\n Pred_acc, Total = 0, 0 \n Running_loss = 0.0\n # print('\\n', '3DCNN train epoch: {:} '.format(epoch+1)) \n # F_scores = []\n Pred_True = [] \n Real_True = []\n Corr_True = []\n \n adjust_lr(optimizer, epoch, lr_decay=15)\n \n for i in range (Num_Dat-Num_Tst):# 135-6=129 For Max. 90-4=86 for Min\n t3=time.time()\n \n print('\\n', '3DCNN train epoch: {:} '.format(epoch+1), ' Num of training input: {:}'.format(i+1))\n # print('\\n', ' Num of training input: {:}'.format(i+1))\n F_scores = []\n \n Tmp=Rodmlst[i]\n INPUTS = INputs[Tmp*Len_Frm:(Tmp+1)*Len_Frm,:,:]\n INPUTS = INPUTS.unsqueeze(0).unsqueeze(0)\n #print(' Shape of INPUTS is ', INPUTS.shape)\n \n LABEL = Labels[int(Tag[Tmp]),:,:].unsqueeze(0).unsqueeze(0).unsqueeze(0) # Make it have 5 dimensions\n # print('Type of LABEL is ', type(LABEL), ' Shape of LABEL is ', LABEL.shape) \n print(' NO. sub-video data is ',Tmp, ', NO. Label is ', int(Tag[Tmp]))\n \n #INPUTS = NewInpVid[i*Num_Sepa:Num_Sepa*(i+1),:,:]\n #INPUTS = INPUT[i*Num_Sepa:Num_Sepa*(i+1),:,:]\n \n #INPUTS = INPUTS.unsqueeze(0).unsqueeze(0) # Extend 2 dimensions to INPUTS to make it to be 5 dimensions \n #print(' Shape of INPUTS is ', INPUTS.shape)\n \n #Labels = Read_label('Data\\\\Inputs\\\\Label') # Read the ground truth for actual measured nugget compared with 3D CNN output \n #Labels = 255 * Labels \n #print('\\n', 'Size of Labels: ', Labels.size(), 'Type of Labels: ', type(Labels)) \n # [1,96,104], class: torch.Tensor\n \n optimizer.zero_grad()\n #NewInpVid = transforms.ToTensor()(IpVide[0,0,303:391,:,:])# Original starts from 3.\n \n # NewInpVid = transforms.ToTensor()(NewInpVid[:,:,:])\n \n # NewInpVid = NewInpVid.permute(1,2,0) # Original NewInpVid has 3 dimensions\n # print('Shape of NewInpVId = ', NewInpVid.shape, '\\n')\n \n # NewInpVid = NewInpVid.unsqueeze(0).unsqueeze(0) \n # print('Shape of NewInpVId = ', NewInpVid.shape, '\\n', 'Type of NewInpVid = ', type(NewInpVid))\n \n Outputs = Net3D(INPUTS.float())\n # Because it is known that there are 391 images input in total\n # Output_size: [1,2,1,96,104]\n \n # Convert input to float is faster regarding running than converting model to double\n \n # Outputs = Net3D(NwFrame[0,0,3:390,:,:])\n _, PRedt=torch.max(Outputs, dim=1)\n #print('\\n','Size of Predt: ', Predt.size())\n # Predt_size: [1,1,96,104], delete the 2nd dimension of Outputs. Because pick the highest probility of belonging to a class at each pixel\n \n # LABEL=Labels.long() No difference is incurred for labels by adding '.long()' regarding type and size.\n # print('\\n', 'Size of LABEL: ', LABEL.size(), 'Type of LABEL: ', type(LABEL)) \n\n #Predt=PRedt.to('cpu')\n \n acc = compute_acc(PRedt, LABEL.long())\n Pred_acc += acc\n Total += Y*X\n print(' Average acc:', Pred_acc/Total)\n \n Predt=PRedt.to('cpu')\n LABEL_cpu=LABEL.to('cpu')\n\n Pred_True, Real_True, Corr_True = compute_F(Predt, LABEL_cpu.long())\n # Total evaluated cells are 96*104*batch size\n # print('Pred_True = ', len(Pred_True))\n \n for j in range(2): # Based on the number of classes\n F_scores.append(2*Corr_True[j]/(Pred_True[j]+Real_True[j]))\n print('Pred_outside pixels(0) =', Pred_True[0], ', Pred_onside pixels(0) =', Pred_True[1])\n print('Real_outside pixels(0) =', Real_True[0], ', Real_onside pixels(0) =', Real_True[1])\n print(' Corre_outside pixels(0) =', Corr_True[0], ', Corre_onside pixels(0) =', Corr_True[1]) \n print(' F_scores:', F_scores)\n \n n,c,d,h,w=Outputs.size()# [1,2,1,96,104]\n \n Outputs = Outputs.transpose(1,2).transpose(2,3).transpose(3,4).contiguous().view(-1,c)\n # After, outputs: [9984,2] ?\n \n LABEL = LABEL.view(-1).long() # Make labels to be 1 diamention by multiplying all original diamentions \n # : [9984]: from (1*1*1*96*104)\n #print(' Max of LABEL is ', np.max(LABEL.numpy()), ', Min of LABEL is ', np.min(LABEL.numpy())) \n #print('\\n','Shape of LABEL is ', LABEL.shape, ', Type of LABEL = ', type(LABEL))#[]\n #print('Latest Output_size = ', Outputs.size())\n # print('After Labels_size = ', Labels.size())\n #print(' Max of Outputs is ', np.max(Outputs.numpy()[:,0]), ', Min of Outputs is ', np.min(Outputs.numpy()[:,0]))\n #print(' Max of Outputs is ', np.max(Outputs.numpy()[:,1]), ', Min of Outputs is ', np.min(Outputs.numpy()[:,1]))\n # np.max(Outputs.numpy()[0,0,0,:,:])\n #print('\\n','Shape of Outputs is ', Outputs.shape, ', Type of Outputs = ', type(Outputs))\n #print(Counter(LABEL.numpy().reshape(-1)))\n\n loss = criterion(Outputs, LABEL) # LABEL shape: [1,1,1,96,104]?\n # outputs: 2 probibilities of being each class at each pixel. labels: actual class of each pixel ? \n print('Train loss:',loss.item()) \n \n loss.backward() # backpropagate the error (gradients back into the network’s parameters)\n optimizer.step()\n # Does the update\n \n # print statistics\n Running_loss += loss.item() \n \n # plt.imshow(Predt[0,0,:,:].numpy())\n t4=time.time()\n print('3DCNN precition time for one dataset is {:.4f} sec'.format(t4-t3), end ='\\n')\n \n t2 = time.time()\n print('Total training time is {:.4f} sec'.format(t2-t1), end ='\\n\\n')\n \n torch.save(Net3D.state_dict(), 'model3D.ckpt') \n\nplt.imshow(Predt[0,0,:,:].numpy())\n\n\n#############################################################\nprint('\\n','3D CNN Training ends, testing starts...')\nt5 = time.time()\noutput_target = [] \n\n#Net3D.load_state_dict(torch.load('model3D.ckpt')) \n\nwith torch.no_grad():\n Net3D.eval()\n pred_acc, total = 0, 0\n #Dia_X1, Dia_Y1, Flg = 0, 0, 0\n #Dia_X2, Dia_Y2, = 0, 0\n \n #F_scores = []\n Pred_True = [] \n Real_True = []\n Corr_True = []\n \n for i in range(Num_Tst):# For Min13_14 forming 86 Training datasets. NO. 62, 80, 51 and 41 are used as test datasets\n # For NO.13_14_Cat5_Len30_Stp7_NumEch35: NO. 311, 227, 160, 73, 284, 54, 236, 117, 330, 53 are used for test \n # For E040-E044 from Min13 to Max14, [38, 156, 53, 55, 52, 84, 185, 166, 138, 226] are left for testing\n # For E040-044 from Min13 to Max14, [257, 105, 158, 280, 64, 240, 82, 177, 162, 120] are not used for training, ExaNor, IniArcht\n # For E068-072, Non-concatenate: Datasets: [330, 112, 303, 316, 101, 96, 349, 302, 127, 265] not used for training.\n # For E063-067, from Min13-Max14, [142, 264, 50, 8, 145, 99, 63, 310, 240, 5] are not used for training\n # For E063-067, from Min13-Max14,[183, 175, 140, 293, 323, 258, 4, 219, 106, 327] are not used for ExaNorm training\n # For E063-067, from Min13-Max14,[72, 38, 253, 349, 63, 338, 130, 230, 110, 116] are not used for NonNorm training\n # For E063-067, from Min13-Max14,[265, 202, 310, 148, 249, 24, 145, 169, 119, 7] are not used for ExaNorm training, Archt2\n # For E047-049, from Target13-Max14, [12, 62, 80, 48, 1, 28] are not used for ExaNorm training, Atcht3\n # For E047-049, from Target13-Max14, [171, 100, 57, 155, 114, 187] are not used for ExaNorm training, InitArcht\n # For E075-078, from Low13-Max14, [135, 84, 91, 46, 272, 95, 158, 113] are not used for ExaNorm Training, Archt3\n # For E075-078, from Low13-Max14, [64, 54, 53, 222, 274, 94, 184, 46] are not used for ExaNorm Training, InitModel\n # For E059-061, from Target13-Max14: [77, 89, 68, 35, 78, 172] are not used for ExaNorm Training, InitModel\n print('\\n',' Num of test input: {:}'.format(i+1))\n \n t7 = time.time()\n F_scores = []\n \n Tmp=Rodmlst[Num_Dat-i-1]\n \n INPUTS = INputs[Tmp*Len_Frm:(Tmp+1)*Len_Frm,:,:]\n INPUTS = INPUTS.unsqueeze(0).unsqueeze(0)\n #print(' Shape of INPUTS is ', INPUTS.shape)# [1,1,50(length of a sub-video data),96,104]\n \n LABEL = Labels[int(Tag[Tmp]),:,:].unsqueeze(0).unsqueeze(0).unsqueeze(0) # Make it have 5 dimensions\n print(' NO. sub-video data for Test is ',Tmp, ', NO. Label is ', int(Tag[Tmp]))\n \n Outputs = Net3D(INPUTS.float())\n #print('Shape of Outputs is ', Outputs.shape)#[1,2,1,96,104]\n _, PRedt=torch.max(Outputs, dim=1)\n \n #output_target.append(Predt)\n # print(' Type of output_target is ', type(output_target))# class 'list'\n # print('output_target_size = ', len(output_target))# size is 1\n # for i in rang(2)\n # print(' '.join('%5s' % classes[pred[j,]] for j in range(2))) \n acc = compute_acc(PRedt, LABEL.long())\n pred_acc += acc\n total += Y*X\n print('Average acc:', pred_acc/total)\n \n Predt=PRedt.to('cpu')\n LABEL_cpu=LABEL.to('cpu')\n\n output_target.append(Predt)\n Pred_True, Real_True, Corr_True = compute_F(Predt, LABEL_cpu.long())\n # Total evaluated cells are 96*104*batch size\n # print('Pred_True = ', len(Pred_True))\n \n for j in range(2): # Based on the number of classes\n F_scores.append(2*Corr_True[j]/(Pred_True[j]+Real_True[j]))\n print(' Pred_outside=', Pred_True[0], ', Pred_onside=', Pred_True[1])\n print(' Real_outside=', Real_True[0], ', Real_onside=', Real_True[1])\n print(' Corre_outside=', Corr_True[0], ', Corre_onside=', Corr_True[1])\n print(' F_scores:', F_scores)\n \n # print('input_size = ', input.size())\n # print('orig output_size = ', outputs.size())\n # print('orig labels_size = ', labels.size())\n \n n,c,d,h,w=Outputs.size()# [1,2,1,96,104]\n Outputs = Outputs.transpose(1,2).transpose(2,3).transpose(3,4).contiguous().view(-1,c)\n # After, Outputs size is [9984,2] \n \n LABEL = LABEL.view(-1).long() # Make labels to be 1 diamention by multiplying all original diamentions \n \n # print('Latest Outputs_size = ', Outputs.size())# [9984,2]\n # print('After LABEL_size = ', LABEL.size()) # [9984]\n \n loss = criterion(Outputs, LABEL) # Outputs [1,2,1,96,104]. LABEL [1,1,1,96,104]!\n print('Test loss:',loss.item())\n t8 = time.time()\n print('3DCNN prediction time for one dataset is {:.4f} sec'.format(t8-t7), end ='\\n\\n')\n \n t6 = time.time()\n print('Total testing time is {:.4f} sec'.format(t6-t5))\n\nnp.save('Exp3DTrndat.npy', Rodmlst[Num_Dat-Num_Tst:Num_Dat])\nprint('Unused training data is:', Rodmlst[Num_Dat-Num_Tst:Num_Dat]) \nplt.imshow(Predt[0,0,:,:]) \noutput_target = torch.cat(tuple(output_target))\nprint('Test_output', output_target.shape) # [3(# of test data),1,96,104]\n#print(' Type of output_target is ', type(output_target))# class 'torch.Tensor'\n # output_target is accumulated over all test samples\n","sub_path":"Train_3DCNN.py","file_name":"Train_3DCNN.py","file_ext":"py","file_size_in_byte":27407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"311898028","text":"from flask import Flask\napp = Flask(__name__)\nfrom sense_hat import SenseHat\nimport time\n\nsense = SenseHat()\n\n@app.route('/')\ndef hello_world():\n return '

Que pasa perro

'\n\t\n@app.route('/temp')\ndef printemp():\n\ttemp = sense.get_temperature()\n\treturn str(temp)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"285965462","text":"str1 = 'this is a test'\r\nstr2 = 'wokka wokka!!!'\r\nbyte1 = b'this is a test'\r\nbyte2 = b'wokka wokka!!!'\r\nhex1 = byte1.hex()\r\nhex2 = byte2.hex()\r\ndef hammingDistance(str1,str2):\r\n xor = lambda b1,b2: b1^b2\r\n count = 0\r\n for byte in zip(str1,str2):\r\n \r\n count += bin(byte[0]^byte[1]).count('1')\r\n\r\n return count\r\nprint(hammingDistance(byte1,byte2))\r\n\r\n\r\n","sub_path":"Cryptology Scripts/playground.py","file_name":"playground.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"209511397","text":"print('Podaj kolejne elementy tablicy')\ntab = []\nfor i in range(10):\n i = int(input(''))\n tab.append(i)\ndef powtarzane(arr):\n for i in tab:\n x = arr.count(i)\n if x == 1:\n print(i,end=' ')\npowtarzane(tab) \n","sub_path":"04-Subroutines/af_37.py","file_name":"af_37.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"220309206","text":"import pytest\n\nfrom busy_beaver.blueprints.integration.slack import (\n ACCOUNT_ALREADY_ASSOCIATED,\n UNKNOWN_COMMAND,\n VERIFY_ACCOUNT,\n reply_to_user_with_github_login_link,\n)\nfrom busy_beaver.models import User\n\nMODULE_TO_TEST = \"busy_beaver.blueprints.integration.slack\"\n\n\n@pytest.fixture\ndef patcher(monkeypatch):\n \"\"\"Helper to patch in the correct spot\"\"\"\n\n def _patcher(namespace, replacement_object):\n namespace_to_patch = f\"{MODULE_TO_TEST}.{namespace}\"\n monkeypatch.setattr(namespace_to_patch, replacement_object)\n return replacement_object\n\n yield _patcher\n\n\n@pytest.fixture\ndef patched_slack(patcher):\n def _wrapper(mock_to_return):\n return patcher(\"slack\", mock_to_return)\n\n return _wrapper\n\n\ndef test_slack_callback_url_verification(client, session, patched_slack):\n # Arrange\n challenge_code = \"test_code\"\n data = {\"type\": \"url_verification\", \"challenge\": challenge_code}\n\n # Act\n resp = client.post(\"/slack-event-subscription\", json=data)\n\n # Assert\n assert resp.status_code == 200\n assert resp.json == {\"challenge\": challenge_code}\n\n\ndef test_slack_callback_bot_message_is_ignored(mocker, client, session, patched_slack):\n \"\"\"Bot get notified of its own DM replies to users... ignore\"\"\"\n # Arrange\n slack = patched_slack(mocker.MagicMock())\n # TODO find out how messages are really sent and make these tests a lot more robust\n data = {\n \"type\": \"unknown todo\",\n \"event\": {\"type\": \"message\", \"subtype\": \"bot_message\"},\n }\n\n # Act\n resp = client.post(\"/slack-event-subscription\", json=data)\n\n # Assert\n assert resp.status_code == 200\n assert len(slack.mock_calls) == 0\n\n\ndef test_slack_callback_user_dms_bot_reply(mocker, client, session, patched_slack):\n \"\"\"Bot get notified of its own DM replies to users... ignore\"\"\"\n # Arrange\n slack = patched_slack(mocker.MagicMock())\n channel_id = 5\n # TODO find out how messages are really sent and make these tests a lot more robust\n data = {\n \"type\": \"unknown todo\",\n \"event\": {\n \"type\": \"message\",\n \"subtype\": \"not bot_message\",\n \"channel_type\": \"im\",\n \"text\": \"random\",\n \"user\": \"random_user\",\n \"channel\": channel_id,\n },\n }\n\n # Act\n resp = client.post(\"/slack-event-subscription\", json=data)\n\n # Assert\n assert resp.status_code == 200\n assert len(slack.mock_calls) == 1\n args, kwargs = slack.post_message.call_args\n assert kwargs[\"channel_id\"] == channel_id\n\n\n@pytest.fixture\ndef create_slack_message():\n def _create_slack_message_dict(*, text, user=\"test_user\"):\n return {\n \"type\": \"message\",\n \"subtype\": \"not bot_message\", # TODO, what does it really look like\n \"channel_type\": \"im\",\n \"text\": text,\n \"user\": user,\n \"channel\": \"test_channel\",\n }\n\n return _create_slack_message_dict\n\n\ndef test_reply_unknown_command(mocker, session, patched_slack, create_slack_message):\n # Arrange\n slack = patched_slack(mocker.MagicMock())\n message = create_slack_message(text=\"hi\")\n\n # Act\n reply_to_user_with_github_login_link(message)\n\n # Assert\n assert len(slack.mock_calls) == 1\n args, kwargs = slack.post_message.call_args\n assert UNKNOWN_COMMAND in args\n\n\ndef test_reply_new_account(mocker, session, patched_slack, create_slack_message):\n # Arrange\n slack = patched_slack(mocker.MagicMock())\n message = create_slack_message(text=\"connect\")\n\n # Act\n reply_to_user_with_github_login_link(message)\n\n # Assert\n assert len(slack.mock_calls) == 1\n args, kwargs = slack.post_message.call_args\n assert VERIFY_ACCOUNT in args\n\n\ndef test_reply_existing_account(mocker, session, patched_slack, create_slack_message):\n # Arrange\n username = \"test_user\"\n user = User(slack_id=username)\n session.add(user)\n session.commit()\n\n message = create_slack_message(text=\"connect\", user=username)\n slack = patched_slack(mocker.MagicMock())\n\n # Act\n reply_to_user_with_github_login_link(message)\n\n # Assert\n assert len(slack.mock_calls) == 1\n args, kwargs = slack.post_message.call_args\n assert ACCOUNT_ALREADY_ASSOCIATED in args\n\n\ndef test_reply_existing_account_reconnect(\n mocker, session, patched_slack, create_slack_message\n):\n # Arrange\n username = \"test_user\"\n user = User(slack_id=username)\n session.add(user)\n session.commit()\n\n message = create_slack_message(text=\"reconnect\", user=username)\n slack = patched_slack(mocker.MagicMock())\n\n # Act\n reply_to_user_with_github_login_link(message)\n\n # Assert\n assert len(slack.mock_calls) == 1\n args, kwargs = slack.post_message.call_args\n assert VERIFY_ACCOUNT in args\n","sub_path":"tests/blueprints/integration/slack_test.py","file_name":"slack_test.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"98519848","text":"# !/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n'''\nAuthor: lvxiing\ndate: 2019/4/27 23:22\n'''\n\n\"\"\"\n将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。\n\"\"\"\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n if not l1:\n return l2\n if not l2:\n return l1\n if l1.val > l2.val:\n res = l2\n res.next = self.mergeTwoLists(l1, l2.next)\n else:\n res = l1\n res.next = self.mergeTwoLists(l1.next, l2)\n return res\n\n\n# 测试:\nnode1 = ListNode(1)\nnode2 = ListNode(2)\nnode3 = ListNode(4)\n\nnode4 = ListNode(1)\nnode5 = ListNode(3)\nnode6 = ListNode(4)\n\nnode1.next = node2\nnode2.next = node3\nnode4.next = node5\nnode5.next = node6\n\ns = Solution()\nprint(s.mergeTwoLists(node1, node4).val)\nprint(s.mergeTwoLists(node1, node4).next.val)\n","sub_path":"Leetcode/leetcode021.py","file_name":"leetcode021.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"487474752","text":"# Importig required Libaries\nfrom keras.callbacks import TensorBoard\nfrom keras.layers import Activation, Dense, Flatten, Cropping2D, Conv2D\nfrom keras.models import Sequential\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.layers import Lambda\nfrom keras.backend import tf as ktf\nimport csv\nimport pickle\nimport cv2\nimport numpy as np\nfrom IPython.core.debugger import set_trace\n\n\n\n\n \n \n\ntrain_datagen = ImageDataGenerator(featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False,\n samplewise_std_normalization=False, zca_whitening=False, zca_epsilon=1e-6, rotation_range=10, width_shift_range=0.2, \n height_shift_range=0.2,shear_range=0, zoom_range=0.1, channel_shift_range=0., fill_mode='nearest', cval=0., \n horizontal_flip=False,vertical_flip=False, rescale=None, preprocessing_function=None, data_format=\"channels_last\")\n\n\n\ndef PatternRecognitionModel(input_shape):\n '''\n Pattern Recognition model consists of 24 Sequential layers \n 6 Convolutional layers followed by relu activation layer.\n 5 Fully connected layers followed bye relu activation layer.\n Convolutional layers plays important role in segregating all lane curve extractions and curvation associated information.\n Fully connected layers plays important role in reducing network size layer by layer in extracting curvature of lanes in taking the steering angle prediction\n \n Loss\n ----\n mean squared error loss is considered in optimizing the model performance\n Optimizer\n --------\n Adam optimizer is considered in changing the learning rate to converging Neural network in getting high performance in prediction\n default learning rate of 0.9 to 0.999 increment of optimization with the step of 0.001 is considered\n keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n \n \n '''\n # Model\n model = Sequential()\n# Convolutional\n model.add(Cropping2D(cropping=((70, 25), (0, 0)), input_shape=input_shape))\n# Lambda(lambda image: ktf.image.resize_images(image, (80, 200)))\n model.add(Lambda(lambda x: (x / 255.0) - 0.5))\n model.add(Conv2D(filters=6, kernel_size=(5, 5), strides=(2, 2), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros'))\n model.add(Activation('relu'))\n model.add(Conv2D(filters=16, kernel_size=(5, 5), strides=(2, 2), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros'))\n model.add(Activation('relu'))\n model.add(Conv2D(filters=32, kernel_size=(5, 5), strides=(2, 2), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros'))\n model.add(Activation('relu'))\n model.add(Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros'))\n model.add(Activation('relu'))\n model.add(Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='valid', dilation_rate=(1, 1),use_bias=True, \n kernel_initializer='glorot_uniform',bias_initializer='zeros'))\n model.add(Activation('relu'))\n # Fully connected\n model.add(Flatten())\n model.add(Dense(units=1164))\n model.add(Activation('relu'))\n model.add(Dense(units=100))\n model.add(Activation('relu'))\n model.add(Dense(units=50))\n model.add(Activation('relu'))\n model.add(Dense(units=10))\n model.add(Activation('relu'))\n model.add(Dense(units=1))\n model.compile(loss='mean_squared_error', optimizer='Adam', metrics=['mae'])\n return model\n\n\ndef Pattern_Recognion_Model_API(X_train,y_train):\n '''\n Pattern Recognition model with the use Functional API method consists of 24 Sequential layers \n 6 Convolutional layers followed by relu activation layer.\n 5 Fully connected layers followed bye relu activation layer.\n Convolutional layers plays important role in segregating all lane curve extractions and curvation associated information.\n Fully connected layers plays important role in reducing network size layer by layer in extracting curvature of lanes in taking the steering angle prediction\n \n Loss\n ----\n mean squared error loss is considered in optimizing the model performance\n Optimizer\n --------\n Adam optimizer is considered in changing the learning rate to converging Neural network in getting high performance in prediction\n default learning rate of 0.9 to 0.999 increment of optimization with the step of 0.001 is considered\n keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\n \n \n '''\n\n X_input = Input(shape=X_train.shape, name='img_in')\n X = Cropping2D(cropping=((70, 25), (0, 0)))(X_input)\n #X = Lambda(lambda image: ktf.image.resize_images(image, (80, 200)))(X)\n X = Lambda(lambda x: (x / 255.0) - 0.5)(X)\n X = Conv2D(filters=6, kernel_size=(5, 5), strides=(2, 2), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros')(X)\n X = Activation('relu')(X)\n X = Conv2D(filters=16, kernel_size=(5, 5), strides=(2, 2), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros')(X)\n X = Activation('relu')(X)\n X = Conv2D(filters=32, kernel_size=(5, 5), strides=(2, 2), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros')(X)\n X = Activation('relu')(X)\n X = Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros')(X)\n X = Activation('relu')(X)\n X = Conv2D(filters=32,kernel_size=(3, 3), strides=(1, 1), padding='valid', dilation_rate=(1, 1), use_bias=True,\n kernel_initializer='glorot_uniform', bias_initializer='zeros')(X)\n X = Activation('relu')(X)\n # Fully connected\n X = Flatten()(X)\n # model.add(Dropout(0.35))\n X = Dense(units=1164)(X)\n X = Activation('relu')(X)\n X = Dense(units=100)(X)\n X = Activation('relu')(X)\n X = Dense(units=50)(X)\n X = Activation('relu')(X)\n X = Dense(units=10)(X)\n X = Activation('relu')(X)\n X = Dense(units=1)(X)\n model=Model(inputs=X_input, outputs=X, name='Convolve')\n model.compile(optimizer='adam',loss='mean_squared_error',metrics = ['mse'])\n return model\n\n\n# Hyper parameters considered for model\nbatch_size = 10\nepochs = 10\n# Loading the preprocessed data \nwith open('/opt/ProcessedData.data','rb') as file:\n x_test, y_test = pickle.load(file)\n x_valid, y_valid = pickle.load(file)\n x_train,y_train = pickle.load(file)\n file.close()\n\nprint('Train data shape',x_train.shape)\nprint('Train data shape ', x_train.shape)\n \n# Initializing the Generator function \ndatagen = ImageDataGenerator()\n\n# Initializing the train, test and validation data to Augmentation data generator\ntrain_generator = datagen.flow(x_train, y_train, batch_size=batch_size)\nvalid_generator = datagen.flow(x_valid, y_valid, batch_size=batch_size)\ntest_generator = datagen.flow(x_test, y_test, batch_size=batch_size)\n\n# Initializing the Convolutional model\nmodel = PatternRecognitionModel(x_train[0].shape)\n#model = PatternRecognitionModel_API(x_train[0].shape)\nmodel.summary()\n\n#Training the model\nmodel.fit_generator(train_generator, steps_per_epoch=int(np.ceil(len(x_train) / float(batch_size))), epochs=epochs, workers=4,\n verbose=1, validation_data=valid_generator, validation_steps=int(np.ceil(len(x_valid) / float(batch_size))))\n\n# Saving the model to disk\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n json_file.write(model_json)\n\nmodel.save('model.h5')\nprint('Models saved Successfully')\n","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":8260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"530671137","text":"from django import forms\nfrom django.conf import settings\nfrom django.core.files import File\nfrom django.core.urlresolvers import reverse\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext as _\n\nimport urllib2\n\nfrom ajax_upload.models import UploadedFile\n\n\nclass AjaxUploadException(Exception):\n pass\n\n\nclass AjaxClearableFileInput(forms.TextInput):\n template_with_clear = '' # We don't need this\n template_with_initial = '%(input)s'\n\n def render(self, name, value, attrs=None):\n attrs = attrs or {}\n if value:\n filename = value\n else:\n filename = ''\n attrs.update({\n 'type': 'file',\n 'class': attrs.get('class', '') + 'ajax-upload',\n 'data-filename': filename, # This is so the javascript can get the actual value\n 'data-required': self.is_required or '',\n 'data-upload-url': reverse('ajax-upload')\n })\n output = super(AjaxClearableFileInput, self).render(name, value, attrs)\n return mark_safe(output)\n","sub_path":"ajax_upload/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"263871898","text":"# -*- encoding: utf-8 -*-\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2016-2018 Tobias Koch \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 os\nimport re\nimport pwd\nimport stat\nimport hashlib\nimport shutil\nimport socket\n\nimport org.boltlinux.package.libarchive as libarchive\nfrom org.boltlinux.package.libarchive import ArchiveEntry, ArchiveFileWriter\nfrom org.boltlinux.deb2bolt.changelog import Changelog\nfrom org.boltlinux.deb2bolt.patchseries import PatchSeries\nfrom org.boltlinux.deb2bolt.binarypackage import BinaryPackage\nfrom org.boltlinux.deb2bolt.basepackage import BasePackageMixin\nfrom org.boltlinux.deb2bolt.packageutils import PackageUtilsMixin\nfrom org.boltlinux.error import BoltSyntaxError, InvocationError\n\nPKG_RULES_XML_TEMPLATE = \"\"\"\\\n\n\n \n \n \n\n \n \n \n\n \n \n \n\n\"\"\"\n\nSOURCE_PKG_XML_TEMPLATE = \"\"\"\\\n\n\n \n \n \n\n \n \n %(summary)s\n

\n%(description)s\n

\n
\n\n \n \n \n \n%(patches)s\n \n%(build_deps)s\\\n \n\n \n \n\n%(binary_packages)s\n \n
\n\"\"\"\n\nclass SourcePackage(BasePackageMixin, PackageUtilsMixin):\n\n def __init__(self, filename, app_config, use_network=True):\n if not os.path.exists(filename):\n raise InvocationError(\"no such file '%s'.\" % filename)\n\n with open(filename, \"r\", encoding=\"utf-8\") as f:\n content = f.read()\n\n self.app_config = app_config\n\n # generate maintainer info\n pwent = pwd.getpwuid(os.getuid())\n maintainer_name = pwent.pw_gecos.split(\",\")[0] or \"Unknown User\"\n maintainer_email = pwent.pw_name + \"@\" + socket.gethostname()\n maintainer_info = app_config.get(\"maintainer-info\", {})\n\n maintainer_info.setdefault(\"name\", maintainer_name)\n maintainer_info.setdefault(\"email\", maintainer_email)\n\n content = re.sub(r\"^\\s*\\n$\", r\"\\n\", content, flags=re.M)\n blocks = re.split(r\"\\n\\n\", content)\n debdir = os.path.dirname(filename)\n\n try:\n self.parse_content(blocks.pop(0))\n except:\n msg = \"error parsing control file.\"\n raise BoltSyntaxError(msg)\n #end try\n\n self.patches = PatchSeries()\n for patch_subdir in [\"patches-applied\", \"patches\"]:\n series_file = os.path.join(debdir, patch_subdir, \"series\")\n if os.path.exists(series_file):\n self.patches = PatchSeries(series_file)\n break\n #end if\n #end for\n\n self.changelog = Changelog(\n os.path.join(debdir, \"changelog\"),\n maintainer_info\n )\n self.version = self.changelog.releases[0].version\n self.revision = self.changelog.releases[0].revision\n self.packages = []\n self.directory = debdir\n self.tarball = self.find_orig_tarball(debdir)\n self.patch_tarball = \"debian.1.tar.gz\"\n\n pkg_mirror = self.app_config.get(\"upstream\", {}).get(\"mirror\")\n\n for entry in blocks:\n if not entry.strip():\n continue\n\n bin_pkg = BinaryPackage(entry)\n if not \"name\" in bin_pkg.fields:\n continue\n\n bin_pkg.fields[\"version\"] = self.version\n\n # throw out udebs and debug packages\n if bin_pkg.fields.get(\"section\", \"\") == \"debian-installer\":\n continue\n if re.match(r\".*?-(?:udeb|dbg|debug)$\",\n bin_pkg.fields.get(\"package\", \"\")):\n continue\n if bin_pkg.fields.get(\"xc-package-type\", \"\") == \"udeb\":\n continue\n\n bin_pkg.load_content_spec(debdir, bin_pkg.get(\"name\"),\n self.version, use_network=use_network, mirror=pkg_mirror)\n self.packages.append(bin_pkg)\n #end for\n\n if use_network:\n self.simplify_package_contents()\n\n self.arch_indep = True\n for bin_pkg in self.packages:\n if bin_pkg.fields.get(\"architecture\", \"all\") != \"all\":\n self.arch_indep = False\n break\n #end if\n #end for\n\n if self.tarball:\n h = hashlib.sha256()\n with open(self.tarball, \"rb\") as f:\n while True:\n buf = f.read(4096)\n if not buf:\n break\n h.update(buf)\n #end while\n #end with\n self.sha256sum = h.hexdigest()\n else:\n self.sha256sum = \"\"\n #end if\n\n self.sha256sum_patches = \"\"\n #end function\n\n def simplify_package_contents(self):\n for pkg in self.packages:\n uniq_prefixes = {}\n pkg.contents.sort()\n\n for entry in pkg.contents:\n entry_path = os.path.dirname(entry[0])\n entry_type = entry[1]\n entry_uniq = True\n\n if not entry_path or entry_type == stat.S_IFDIR:\n continue\n\n entry_path = entry_path.rstrip(os.sep) + os.sep\n\n # check if the path is also in another package\n for tmp_pkg in self.packages:\n if id(tmp_pkg) == id(pkg):\n continue\n for tmp_entry in tmp_pkg.contents:\n tmp_entry_path = tmp_entry[0]\n if tmp_entry_path.startswith(entry_path):\n entry_uniq = False\n break\n #end for\n if not entry_uniq:\n break\n #end for\n\n if not entry_uniq:\n continue\n\n # check if there are collisions and fix them\n for prefix in list(uniq_prefixes):\n if prefix.startswith(entry_path):\n del uniq_prefixes[prefix]\n elif entry_path.startswith(prefix + os.sep):\n entry_uniq = False\n break\n #end if\n #end for\n\n if entry_uniq:\n uniq_prefixes[entry_path.rstrip(os.sep)] = 1\n #end for\n\n # delete entries that are included in a prefix\n i = 0\n while i < len(pkg.contents):\n entry = pkg.contents[i]\n\n entry_path = entry[0]\n entry_type = entry[1]\n\n if entry_type != stat.S_IFDIR:\n entry_path = os.path.dirname(entry_path)\n\n index_deleted = False\n\n for prefix in uniq_prefixes:\n if entry_path == prefix or \\\n entry_path.startswith(prefix + os.sep):\n del pkg.contents[i]\n index_deleted = True\n break\n #end if\n #end for\n\n if not index_deleted:\n i += 1\n #end while\n\n for entry_path in uniq_prefixes:\n pkg.contents.append([entry_path, 0, 0, \"root\", \"root\"])\n #end for\n #end function\n\n def as_xml(self, indent=0):\n binary_pkgs = \"\"\n for pkg in self.packages:\n pkg_name = pkg.get(\"name\")\n if pkg_name.endswith(\"-doc\"):\n continue\n binary_pkgs += \" \" + \"\\n\" % pkg_name\n #end for\n\n build_deps = \"\"\n for dep in self.get(\"build-depends\"):\n pkg_name, pkg_version = dep\n\n if self.is_pkg_name_debian_specific(pkg_name):\n continue\n\n if dep[1]:\n build_deps += \" \" * 12\n build_deps += \"\\n\" \\\n % (dep[0], dep[1])\n else:\n build_deps += \" \" * 12 + \"\\n\" % dep[0]\n #end for\n\n desc = self.packages[0].get(\"description\", \"\")\n if desc:\n desc = re.sub(r\"^\\s*\", r\" \" * 12, desc, flags=re.M)\n\n if self.tarball:\n extension = self.tarball.rsplit(\".\", 1)[-1]\n tarball = self.get(\"name\") + \"-\" + self.version + \".tar.\" + \\\n extension\n else:\n tarball = self.get(\"name\") + \"-\" + self.version + \".tar.gz\"\n #end if\n\n info_set = {\n \"source_name\": self.get(\"name\"),\n \"arch_indep\": \"true\" if self.arch_indep else \"false\",\n \"summary\": self.packages[0].get(\"summary\", \"\"),\n \"description\": desc,\n \"upstream_version\": self.version,\n \"tarball\": tarball,\n \"build_deps\": build_deps,\n \"binary_packages\": binary_pkgs,\n \"patches\": self.patches.as_xml(indent=2),\n \"source_sha256sum\": self.sha256sum,\n \"patches_sha256sum\": self.sha256sum_patches,\n \"patch_tarball\": self.patch_tarball\n }\n\n return SOURCE_PKG_XML_TEMPLATE % info_set\n #end function\n\n def find_orig_tarball(self, directory):\n search_dir = os.path.join(directory, \"..\", \"..\")\n source_name = self.get(\"name\")\n\n for entry in os.listdir(search_dir):\n m = re.match(\"^%s_.*?\\\\.orig\\\\.tar\\\\.\\\\w+$\" % source_name, entry)\n if m:\n return os.path.join(search_dir, entry)\n #end for\n\n return None\n #end function\n\n def to_bolt(self, gen_patches=False, use_orig=False, use_network=True,\n set_maintainer=False):\n with open(\"changelog.xml\", \"w+\", encoding=\"utf-8\") as f:\n f.write(self.changelog.as_xml(set_maintainer=set_maintainer))\n with open(\"rules.xml\", \"w+\", encoding=\"utf-8\") as f:\n f.write(PKG_RULES_XML_TEMPLATE)\n\n source_section = self.get(\"section\", \"unknown\")\n\n for pkg in self.packages:\n pkg_name = pkg.get(\"name\")\n\n if pkg_name.endswith(\"-doc\"):\n continue\n if not pkg.get(\"section\", \"\"):\n pkg.fields[\"section\"] = source_section\n with open(pkg_name + \".xml\", \"w+\", encoding=\"utf-8\") as f:\n f.write(pkg.as_xml())\n #end for\n\n if gen_patches:\n patch_dir = os.path.join(self.directory, self.patches.patch_subdir)\n filename = self.version + os.sep + \\\n \"debian.%s.tar.gz\" % self.revision\n os.makedirs(self.version, exist_ok=True)\n\n with ArchiveFileWriter(filename, libarchive.FORMAT_TAR_USTAR,\n libarchive.COMPRESSION_GZIP) as archive:\n with ArchiveEntry() as archive_entry:\n for p in self.patches:\n p = re.sub(r\"\\s+-p\\d+\\s*$\", r\"\", p)\n patch_abs_path = os.path.join(patch_dir, p)\n\n archive_entry.clear()\n archive_entry.copy_stat(patch_abs_path)\n archive_entry.pathname = \"patches\" + os.sep + p\n archive_entry.uname = \"root\"\n archive_entry.gname = \"root\"\n archive.write_entry(archive_entry)\n\n with open(patch_abs_path, \"rb\") as f:\n while True:\n buf = f.read(4096)\n if not buf:\n break\n archive.write_data(buf)\n #end while\n #end with\n #end for\n #end with\n #end with\n\n with open(filename, \"rb\") as f:\n h = hashlib.sha256()\n while True:\n buf = f.read(4096)\n if not buf:\n break\n h.update(buf)\n #end while\n self.sha256sum_patches = h.hexdigest()\n self.patch_tarball = os.path.basename(filename)\n #end with\n #end if\n\n if use_orig and self.tarball:\n extension = self.tarball.rsplit(\".\", 1)[-1]\n filename = self.get(\"name\") + \"-\" + self.version + \".tar.\" + \\\n extension\n os.makedirs(self.version, exist_ok=True)\n shutil.copyfile(self.tarball, self.version + os.sep +filename)\n #end if\n\n with open(\"package.xml\", \"w+\", encoding=\"utf-8\") as f:\n f.write(self.as_xml())\n #end function\n\n#end class\n","sub_path":"lib/org/boltlinux/deb2bolt/sourcepackage.py","file_name":"sourcepackage.py","file_ext":"py","file_size_in_byte":14676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"233569505","text":"ista_populada = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]\nlista_vazia = []\n\n# Para inserir elementos em uma lista\nlista_vazia.append(1)\nlista_vazia.append(2)\nlista_vazia.append(3)\nlista_vazia.append(4)\nlista_vazia.append(5)\nlista_vazia.append(6)\nlista_vazia.append(7)\nlista_vazia.append(8)\nlista_vazia.append(9)\nlista_vazia.append(10)\n\nprint(lista_populada)\nprint(lista_vazia)\n\n# Primeiro elemento\nprint(lista_vazia[0])\n\nlista_populada = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]\n\n# Imprimir APENAS O QUINTO ELEMENTO da lista_vazia\nfor n in lista_vazia:\n print('Imprimindo o número ' + str(n))\n\nfor i in range(10):\n pass\n\n# Exercício:\n# Escreva um programa que cadastre 10 \n# usuários\n# e salve eles em uma lista.\n# Após os 10 serem cadastrados, exiba\n# o nome dos usuários cadastrados\n\n# Para os mais **apressadinhos**\n\n# Alterar o programa para:\n# 1- Perguntar se o usuário quer finalizar o programa (\n# o usuário irá digitar uma opção entre (s/n)\n# )\n# Utilizar a função ''.format() para criar um menu de opções\n# As opções devem conter:\n# 1- Cadastrar novo usuário\n# 2- Listar usuário existentes\n# 3- (Só para quem é vida loka) buscar e deletar um usuário\n\n# Resolução\n\nlista_de_usuarios = []\n\nfor i in range(10):\n usuario = {\n 'nome': input('Digite seu nome: '),\n 'idade': input('Digite sua idade: '),\n 'email': input('Digite seu email: '),\n }\n lista_de_usuarios.append(usuario)\n\ntamanho_da_lista = len(lista_de_usuarios)\nfor i in range(tamanho_da_lista):\n print(lista_de_usuarios[i]['nome'])\n\nfor usuario in lista_de_usuarios:\n print(usuario['nome'])\n\ndontpad.com/python-520","sub_path":"aula_1/lista.py","file_name":"lista.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"160980812","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport unicodedata\n\nfrom melody_dl.InfoExtractor import InfoExtractor\n\n\nclass BandCamp(InfoExtractor):\n VALID_URL = r'http://([^.]+).bandcamp.com/album/([^$/]+)'\n TESTS = [{\n 'type': 'album',\n 'url': 'http://lifeformed.bandcamp.com/album/fastfall',\n 'expects': {\n \"tracks\": [{\n \"duration\": \"179.2\",\n \"track\": \"1\",\n \"type\": \"mp3\",\n \"artist\": \"Lifeformed\",\n \"album\": \"Fastfall\",\n \"title\": \"Cider Time\",\n \"url\": \"http://popplers5.bandcamp.com/download/track?enc=mp3-128&fsig=d93545c5331c6e3ace1557a788acb28a&id=456447029&stream=1&ts=1399623102.0\"\n }]\n }\n }]\n\n\n def extract(self, url):\n if not self.webpage_response:\n self.request_webpage(url)\n\n self.soup = self.BeautifulSoup(self.webpage_response.text)\n\n album_meta = self._extract_album_meta_data(self.webpage_response.text)\n\n tracks = []\n\n for track in album_meta['tracks']:\n track = self._get_track_meta_data(track)\n track['artist'] = album_meta['artist']\n track['album'] = album_meta['title']\n track['type'] = 'mp3'\n tracks.append(track)\n\n # album['full'] = self.all_tracks_available(album)\n # album['art'] = self.get_album_art()\n\n return {\n # \"art\": tracks[0]['art'],\n \"tracks\": tracks,\n }\n\n\n ##\n ## Private\n ##\n\n\n def _get_artist(self):\n artist = self.soup.find(\"div\", { \"class\" : \"store_product_title\" }).find(text=True, recursive=False)\n return self.cleanup(artist)\n\n\n def _get_album(self):\n album = self.soup.find(\"div\", { \"class\" : \"product_title\" }).get_text()\n return self.cleanup(album)\n\n\n def _extract_tracks(self):\n \"\"\" Extract all tracks and return them as an array of dicts \"\"\"\n\n results = []\n tracks = self.soup.find('div', {'class' : 'track_list_simple'}).findAll('li')\n\n for i, track in enumerate(tracks):\n key = track.find('div', {\"class\": \"play-track\"})[\"data-media\"]\n track_meta = self._get_track_meta_json(key)\n\n results.append({\n \"track\": str(i + 1),\n \"title\": track_meta['full_title'],\n \"artist\": self._get_artist(),\n \"album\": self._get_album(),\n \"url\": track_meta['stream_url'],\n \"art\": track_meta['album_cover'],\n \"id\": key\n })\n\n break\n\n return results\n\n\n def _extract_album_meta_data(self, html):\n album = {}\n\n embedData = self._get_embed_string_block(html)\n\n block = html.split(\"var TralbumData = \")\n\n stringBlock = block[1]\n stringBlock = unicodedata.normalize('NFKD', stringBlock).encode('ascii', 'ignore')\n stringBlock = stringBlock.split(\"};\")[0] + \"};\"\n stringBlock = read_js_object(\"var TralbumData = %s\" % str(stringBlock))\n\n album['title'] = embedData['EmbedData']['album_title']\n album['artist'] = stringBlock['TralbumData']['artist']\n album['tracks'] = stringBlock['TralbumData']['trackinfo']\n\n return album\n\n\n def _get_embed_string_block(self, html):\n embedBlock = html.split(\"var EmbedData = \")\n\n embedStringBlock = embedBlock[1]\n embedStringBlock = unicodedata.normalize('NFKD', embedStringBlock).encode('ascii', 'ignore')\n embedStringBlock = embedStringBlock.split(\"};\")[0] + \"};\"\n embedStringBlock = read_js_object(\"var EmbedData = %s\" % str(embedStringBlock))\n\n return embedStringBlock\n\n\n def _get_album_art(self):\n url = self.soup.find(id='tralbumArt').find_all('img')[0]['src']\n return url\n\n\n def _get_track_meta_data(self, track):\n new_track = {}\n\n if type(track['file']) is not str:\n if track['file'].has_key('mp3-128'):\n new_track['url'] = track['file']['mp3-128']\n else:\n new_track['url'] = None\n\n new_track['duration'] = track['duration']\n new_track['track'] = track['track_num']\n new_track['title'] = track['title']\n\n return new_track\n\n def _all_tracks_available(self, album):\n for track in album['tracks']:\n if track['url'] is None:\n return False\n\n return True\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\"\"\" Simple JavaScript/ECMAScript object literal reader\nOnly supports object literals wrapped in `var x = ...;` statements, so you\nmight want to do read_js_object('var x = %s;' % literal) if it's in another format.\n\nRequires the slimit library for parsing.\n\nBasic constand folding on strings and numbers is done, e.g. \"hi \" + \"there!\" reduces to \"hi there!\",\nand 1+1 reduces to 2.\n\nCopyright (c) 2013 darkf\nLicensed under the terms of the WTFPL:\n\n\"\"\"\n\nfrom slimit.parser import Parser\nfrom slimit.visitors.nodevisitor import ASTVisitor\nimport slimit.ast as ast\n\n\ndef read_js_object(code):\n\n def visit(node):\n if isinstance(node, ast.Program):\n d = {}\n for child in node:\n if not isinstance(child, ast.VarStatement):\n raise ValueError('All statements should be var statements'\n )\n (key, val) = visit(child)\n d[key] = val\n return d\n elif isinstance(node, ast.VarStatement):\n return visit(node.children()[0])\n elif isinstance(node, ast.VarDecl):\n return (visit(node.identifier), visit(node.initializer))\n elif isinstance(node, ast.Object):\n d = {}\n for property in node:\n key = visit(property.left)\n value = visit(property.right)\n d[key] = value\n return d\n elif isinstance(node, ast.BinOp):\n\n # simple constant folding\n\n if node.op == '+':\n if isinstance(node.left, ast.String) \\\n and isinstance(node.right, ast.String):\n return visit(node.left) + visit(node.right)\n elif isinstance(node.left, ast.Number) \\\n and isinstance(node.right, ast.Number):\n return visit(node.left) + visit(node.right)\n else:\n raise ValueError('Cannot + on anything other than two literals'\n )\n else:\n raise ValueError(\"Cannot do operator '%s'\" % node.op)\n elif isinstance(node, ast.String):\n\n return node.value.strip('\"').strip(\"'\")\n elif isinstance(node, ast.Array):\n return [visit(x) for x in node]\n elif isinstance(node, ast.Number) or isinstance(node,\n ast.Identifier) or isinstance(node, ast.Boolean) \\\n or isinstance(node, ast.Null):\n return node.value\n else:\n raise Exception('Unhandled node: %r' % node)\n\n return visit(Parser().parse(code))\n\n","sub_path":"melody_dl/extractor/BandCamp.py","file_name":"BandCamp.py","file_ext":"py","file_size_in_byte":7088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"444729039","text":"import operator\n\nclass ProcessManager:\n\n def __init__(self):\n self.process_list = list()\n\n def get_process_list(self):\n \"\"\"\n :return: 프로세스 정보가 담긴 리스트 \n \"\"\"\n return self.process_list\n\n def is_app_killed(self, package_name):\n \"\"\"\n 가장 최근에 실행된 프로세스가 kill되었는지 확인하는 함수\n \"\"\"\n for process in reversed(self.process_list):\n if process['package_name'] == package_name:\n if process['kill_time'] is None:\n return False\n else:\n return True\n return True # 처음으로 삽입되는 경우\n\n def start_app(self, package_name, start_time):\n \"\"\"\n 새로운 앱이 실행되었을때 새로운 process dictionary를 생성하여 process_list에 삽입\n \"\"\"\n \n if not(self.is_app_killed(package_name)):\n return # 종료되지 않은 동일한 프로세스가 있으니 무시\n\n process = dict()\n process['package_name'] = package_name\n process['start_time'] = start_time\n process['touch'] = list()\n process['kill_time'] = None\n\n self.process_list.append(process)\n\n def kill_app(self, package_name, kill_time):\n \"\"\"\n 시작된 프로세스가 없다면 무시한다.\n 시작된 프로세스가 있다면 해당 프로세스의 dictonary kill_time입력한다.\n \"\"\"\n\n for process in reversed(self.process_list):\n if process['package_name'] == package_name:\n if process['kill_time'] == None:\n process['kill_time'] = kill_time\n return\n\n def delete_not_killed(self):\n \"\"\"\n 전체 리스트를 순회하면서 kill_time이 없는(아직 종료되지 않은 프로세스)들을 제거해버린다.\n 종료되지 않은 프로세스들의 kill_time은 None으로 되어있다.\n \"\"\"\n for process in self.process_list:\n if process['kill_time'] == None:\n self.process_list.remove(process)\n\n def put_touch_event(self, list_event):\n self.process_list = self.sort_by_time()\n for event in list_event:\n start_time = event[0]\n\n for process in self.process_list:\n if start_time > process['start_time']:\n process['touch'].append(event)\n break\n\n\n def sort_by_time(self):\n \"\"\"\n process_list를 start_time을 기준으로 오름차준 정렬하여 반환해 준다.\n :return start_time으로 정렬된 process_list: \n \"\"\"\n sorted_list = sorted(self.process_list, key=operator.itemgetter('start_time'))\n\n return sorted_list\n\n\n\n \n","sub_path":"process_manager.py","file_name":"process_manager.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"299733296","text":"import numpy as np\nimport random\nfrom keras import regularizers\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Dropout\nimport crocoddyl\nfrom tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())\ncrocoddyl.switchToNumpyMatrix()\n\nclass regression():\n def __init__(self,\n n_trajectories: int = 10000,\n n_hidden: int = 5,\n state_weight: float = 1., \n control_weight: float = .3, \n nodes: int = 300,\n save_trajectories: bool = False,\n save_model: bool = False,\n plot: bool = False):\n \n self.__n_trajectories = n_trajectories\n self.__state_weight = state_weight\n self.__control_weight = control_weight\n self.__nodes = nodes\n self.__n_hidden = n_hidden\n self.save_trajectories = save_trajectories\n self.save_model = save_model\n self.plot = plot\n \n \n def _generate_trajectories(self):\n \"\"\"\n This could be done better with pool. But since we are generating a maximum of 10K trajectories,\n there' no need for pool\n \"\"\"\n\n starting_configurations = []\n optimal_trajectories = []\n feasible_trajectories = 0\n for _ in range(self.__n_trajectories):\n initial_config = np.matrix([random.uniform(-2.1, 2.),\n random.uniform(-2.1, 2.),\n random.uniform(0, 1)]).T\n model = crocoddyl.ActionModelUnicycle()\n model.costWeights = np.matrix([self.__state_weight, self.__control_weight]).T\n problem = crocoddyl.ShootingProblem(initial_config, [ model ] * self.__nodes, model)\n ddp = crocoddyl.SolverDDP(problem)\n ddp.solve()\n if ddp.isFeasible:\n ddp_xs = np.squeeze(np.asarray(ddp.xs))\n ddp_us = np.squeeze(np.asarray(ddp.us))\n feasible_trajectories += 1\n x = ddp_xs[1:,0]\n y = ddp_xs[1:,1]\n theta = ddp_xs[1:,2]\n velocity = ddp_us[:,0]\n torque = ddp_us[:,1]\n optimal_trajectory = np.hstack((x, y, theta, velocity, torque))\n starting_configurations.append(np.squeeze(np.asarray(initial_config)))\n optimal_trajectories.append(optimal_trajectory)\n\n starting_configurations = np.asarray(starting_configurations)\n optimal_trajectories = np.asarray(optimal_trajectories)\n if self.save_trajectories:\n f = open('../../data/x_data.pkl', 'wb')\n cPickle.dump(starting_configurations, f, protocol=cPickle.HIGHEST_PROTOCOL)\n g = open(\"../../data/y_data.pkl\", \"wb\")\n cPickle.dump(optimal_trajectories, g, protocol=cPickle.HIGHEST_PROTOCOL)\n f.close(), g.close()\n\n\n\n return starting_configurations, optimal_trajectories, feasible_trajectories\n \n def keras_net(self, save: bool = False):\n starting_configurations, optimal_trajectories, feasible_trajectories = self._generate_trajectories()\n x_train = starting_configurations[0 : 9000, :]\n y_train = optimal_trajectories[0 : 9000, :]\n x_test = starting_configurations[9000 :, :]\n y_test = optimal_trajectories[9000 :, :]\n model = Sequential()\n model.add(Dense(256, input_dim=(starting_configurations.shape[1])))\n model.add(Activation('relu'))\n for _ in range(self.__n_hidden):\n model.add(Dense(256,\n activation = \"tanh\",\n kernel_initializer='random_uniform',\n kernel_regularizer=regularizers.l2(0.01),\n activity_regularizer=regularizers.l1(0.01))) \n model.add(Dropout(0.25))\n \n model.add(Dense(optimal_trajectories.shape[1], \n activation = 'linear'))\n \n sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)\n model.compile(loss='mean_squared_error',\n optimizer=sgd,\n metrics=['mean_squared_error', \"mean_absolute_error\"])\n \n print('Train...')\n \n model.fit(x_train, \n y_train,\n batch_size = 32,\n epochs = 200,\n verbose = 1\n )\n \n score = model.evaluate(x_test, y_test, batch_size = 16, use_multiprocessing=True)\n \n print(score)\n return model\n \nif __name__=='__main__':\n regression = regression()\n neural_net = regression.keras_net()\n","sub_path":"src/neural_net/keras_net.py","file_name":"keras_net.py","file_ext":"py","file_size_in_byte":4781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"119007387","text":"from tensorflow.python.ops import variable_scope as vs\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.ops import tensor_array_ops, control_flow_ops\nfrom tensorflow.python.ops.rnn_cell_impl import RNNCell, MultiRNNCell\nimport tensorflow as tf\n\nfrom tensorflow.python.layers import base as base_layer\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import init_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops.rnn_cell_impl import _WEIGHTS_VARIABLE_NAME, _BIAS_VARIABLE_NAME, RNNCell\n\nclass REN_MemoryBank(RNNCell):\n\n def __init__(self,\n num_slots,\n num_units,\n initializer=tf.random_normal_initializer(mean=0.0, stddev=0.1),\n activation=tf.identity,\n reuse=False,\n name=None):\n\n super(REN_MemoryBank, self).__init__(_reuse=reuse, name=name)\n self.input_spec = base_layer.InputSpec(ndim=2)\n\n self._num_slots = num_slots\n self._num_units = num_units\n\n self._state_is_tuple = False\n self._activation = activation\n self._kernel_initializer = initializer\n\n self._state_size = [self._num_slots, self._num_units]\n self._output_size = self._num_units\n\n @property\n def state_size(self):\n return self._state_size\n\n @property\n def output_size(self):\n return self._output_size\n\n def zero_state(self, batch_size, dtype):\n zero_state = tf.zeros(dtype=dtype, shape=[batch_size, self._num_slots, self._num_units])\n return zero_state\n\n def build(self, inputs_shape):\n if inputs_shape[1].value is None:\n raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\"\n % inputs_shape)\n\n input_depth = inputs_shape[1].value\n\n self._keys = self.add_variable(\n _WEIGHTS_VARIABLE_NAME + '_keys',\n shape=[self._num_slots, self._num_units],\n initializer=self._kernel_initializer)\n\n self._kernel_U = self.add_variable(\n _WEIGHTS_VARIABLE_NAME + '_U',\n shape=[self._num_units, self._num_units],\n initializer=self._kernel_initializer)\n\n self._kernel_V = self.add_variable(\n _WEIGHTS_VARIABLE_NAME + '_V',\n shape=[self._num_units, self._num_units],\n initializer=self._kernel_initializer)\n\n self._kernel_W = self.add_variable(\n _WEIGHTS_VARIABLE_NAME + '_W',\n shape=[self._num_units, self._num_units],\n initializer=self._kernel_initializer)\n\n self._kernel_H = self.add_variable(\n _WEIGHTS_VARIABLE_NAME + '_H',\n shape=[self._num_units, self._num_units],\n initializer=self._kernel_initializer)\n\n ## note:\n # the paper mentions a matrix R\n # that matrix serves as the kernel for a fc layer for the logits;\n # in our implementation, we do not include it within the memory bank\n\n self.built = True\n\n def call(self, inputs, state):\n sigma = math_ops.sigmoid\n phi = self._activation\n\n ## equation (2) in paper\n # g is the scalar gating based on matching keys or contents\n key_dotprods = tf.matmul(inputs, tf.transpose(self._keys, [1, 0])) # shape: [batch_size, num_slots]\n content_dotprods = tf.reduce_sum(tf.expand_dims(inputs, 1) * state, axis=2) # shape: [batch_size, num_slots]\n g = sigma(key_dotprods + content_dotprods) # shape: [batch_size, num_slots]\n\n ## equation (3) in paper:\n Uh = math_ops.reduce_sum(\n math_ops.multiply(\n tf.expand_dims(state, 3) # expanded shape: [batch_size, num_slots, num_units, 1]\n , tf.expand_dims(tf.expand_dims(self._kernel_U, 0), 1) # expanded shape: [1, 1, num_units, num_units]\n ), axis=-1)\n\n Vw = math_ops.matmul(\n self._keys # keys shape: [num_slots, num_units]\n , self._kernel_V)\n\n Ws = math_ops.matmul(\n inputs # input s_t's shape: [batch_size, num_units]\n , self._kernel_W)\n\n # Uh has shape [batch_size, num_slots, num_units]\n # Vw has shape [num_slots, num_units]\n # Ws has shape [batch_size, num_units]\n # paper computes htilde by broadcasting along the missing dimensions:\n\n Vw = tf.expand_dims(Vw, 0) # shape: [1, num_slots, num_units]\n Ws = tf.expand_dims(Ws, 1) # shape: [batch_size, 1, num_units]\n\n htilde = phi(Uh + Vw + Ws)\n\n # paper computes new state h via a multiplicative gate on htilde\n # but the gate g has shape [batch_size, num_slots]\n # so we expand dims in order to do another array broadcast:\n g = tf.expand_dims(g, 2) # shape: [batch_size, num_slots, 1]\n\n h = state\n\n ## equation (4) in paper:\n h_new = h + g * htilde\n\n ## equation (5) in paper:\n h_new = tf.nn.l2_normalize(h_new, dim=2)\n\n # we return 'output' and 'state' to conform with RNNCell specification\n # but in practice we will use a separate function to query the memory bank,\n # and simply use the 'call' method to incrementally update the state\n return h_new, h_new\n\n def query(self, queries, state):\n ## equation (6) in paper\n\n content_dotprods = tf.reduce_sum(tf.expand_dims(queries, 1) * state, axis=2) # shape: [batch_size, num_slots]\n attn_coefs = tf.nn.softmax(content_dotprods, dim=1) # shape: [batch_size, num_slots]\n\n attn_coefs = tf.expand_dims(attn_coefs, axis=2) # shape: [batch_size, num_slots, 1]\n u = tf.reduce_sum(attn_coefs * state, axis=1) # shape: [batch_size, num_units]\n\n Hu = math_ops.matmul(u, self._kernel_H) # [batch_size, num_units]\n q = queries\n\n phi = self._activation\n return phi(q + Hu)","sub_path":"memory_bank.py","file_name":"memory_bank.py","file_ext":"py","file_size_in_byte":5799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"626414466","text":"'''\n OpenDSS RIAPS device\n \n Model fragment:\n \n app APP {\n message CommandReq;\n message CommandRep;\n message Measurement;\n\n device OpenDSS {\n ans command : (CommandReq, CommandRep);\n pub data : Measurement;\n inside relay;\n }\n\n A compatible component must access the device component via a \n matching qry port. \n \n Message types and protocol\n \n All messages are Python objects, as shown below. Elements with UpperCase names are to be set by the app. \n \n - CommandReq: The client component uses these messages to control the agent.\n [ 'sub', (ObjectName, AttributeName, Unit) ] - instruct the agent to start publishing measurement data from the Object.Attribute of the model. \n [ 'pub', (ObjectName, AttributeName, Value, Unit)] - set the value of the selected Object.Attribute. \n [ 'qry', (ObjectName, AttributeName, Unit) ] - query the last known value of the Object.Attribute. \n - CommandRep: The agent replies with these messages to the commands.\n 'ok' - Reply for 'sub', 'pub', commands\n (ObjectName, AttributeName, Value, Unit, TimeStamp) - Response to query, the value of the requested Object.Attribute.\n - Measurement: Data messages that are published by the agent (as requested by a 'sub' command)\n (ObjectName, AttributeName, Value, Unit, TimeStamp) - The value of the selected Object.Attribute.\n'''\n\nimport time\nimport sys\nimport os,signal\nimport logging\nimport socket\nimport traceback\nimport argparse\nimport threading\nfrom threading import RLock\nimport zmq\nimport rpyc\nimport rpyc.core\nimport rpyc.utils\nfrom riaps.utils import spdlog_setup\nimport spdlog\nfrom rpyc.utils.factory import DiscoveryError\nfrom riaps.run.comp import Component\n\nrpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True\n\nDSSACLIENT_ENDPOINT = 'inproc://dssa-client'\nDSSACLIENT_DATA_ENDPOINT = 'inproc://dssa-client-datal'\n\nclass DSSAClient(threading.Thread):\n SERVICENAME = 'RIAPS_DSSA'\n RECONNECT = False\n def __init__(self,owner,name,host,port,trigger,logger):\n threading.Thread.__init__(self)\n self.owner = owner\n # loggerName = self.owner.getActorName() + '.' + self.owner.getName() + '.' + 'GLAClient'\n self.logger = logger # spdlog.ConsoleLogger(loggerName,True,True,False)\n # self.logger.set_pattern(spdlog_setup.global_pattern)\n # self.logger.set_level(spdlog.LogLevel.DEBUG)\n self.name = name\n self.host = host\n self.port = port\n self.relay = None\n self.trigger = trigger\n self.bgsrv = None\n self.bgsrv_data_outer = None\n self.bgsrv_data_inner = None\n self.active = threading.Event()\n self.active.clear()\n self.terminated = threading.Event()\n self.terminated.clear()\n self.lock = RLock()\n self.poller = None\n self.subs = []\n self.queries = []\n self.conn = None\n self.context = zmq.Context()\n \n def login(self,retry = True):\n self.logger.info(\"login()\")\n self.conn = None\n while True:\n try:\n addrs = rpyc.utils.factory.discover(DSSAClient.SERVICENAME)\n for host,port in addrs:\n try:\n self.conn = rpyc.connect(host,port,\n config = {\"allow_public_attrs\" : True})\n except socket.error as e:\n print(\"%s.%s: %s\" %(str(host),str(port),str(e)))\n pass\n if self.conn: break\n except DiscoveryError:\n self.logger.info(\"discovery of %s failed\" % (DSSAClient.SERVICENAME))\n pass\n if self.conn: break\n if self.host and self.port:\n try:\n self.conn = rpyc.connect(self.host,self.port,\n config = {\"allow_public_attrs\" : True})\n except socket.error as e:\n print(\"%s.%s: %s\" %(str(host),str(port),str(e)))\n pass\n if self.conn: break\n if retry == False:\n return False\n else:\n time.sleep(5)\n continue\n self.bgsrv = rpyc.BgServingThread(self.conn,self.handleBgServingThreadException)\n resp = None\n try: \n resp = self.conn.root.login(self.name,self.callback)\n except:\n traceback.print_exc()\n pass\n return type(resp) == tuple and resp[0] == 'ok'\n\n def subscribe(self,subs):\n if self.conn:\n self.logger.info(\"subscribing\")\n with self.lock: \n for sub in subs:\n self.conn.root.subscribe(sub)\n else:\n self.subs = subs\n\n def publish(self,pubs):\n if self.conn:\n with self.lock:\n for pub in pubs:\n self.conn.root.publish(pub)\n else:\n self.pubs = pubs\n \n def reply(self,id,msg):\n try: \n cmd = msg[0]\n assert(cmd == 'ans')\n rep = [cmd,id] + [msg[1:]]\n self.logger.info(\"run: sending reply = %s\" % str(rep))\n self.relay.send_pyobj(rep)\n except:\n info = sys.exc_info()\n self.logger.error(\"Error in reply '%s': %s %s\" % (cmd, info[0], info[1]))\n traceback.print_exc()\n raise\n \n def query(self, id, queries):\n if self.conn:\n with self.lock: \n for query in queries:\n result = self.conn.root.query(query)\n self.reply(id,result)\n else:\n self.queries = queries\n \n def setup(self):\n self.logger.info(\"setup()\")\n self.relay = self.trigger.setupPlug(self)\n self.poller = zmq.Poller()\n self.poller.register(self.relay,zmq.POLLIN)\n self.bgsrv_data_outer = self.context.socket(zmq.PAIR)\n global DSSACLIENT_DATA_ENDPOINT\n self.bgsrv_data_outer.bind(DSSACLIENT_DATA_ENDPOINT)\n self.poller.register(self.bgsrv_data_outer,zmq.POLLIN)\n \n def run(self):\n self.setup()\n ok = True\n while True:\n self.active.wait(None) # Events to handle activation/termination\n if self.terminated.is_set(): break\n if self.active.is_set():\n ok = self.login(True)\n if ok: self.logger.info(\"run: loop...\")\n while ok:\n try:\n sockets = dict(self.poller.poll(1000.0))\n if self.terminated.is_set(): break\n toDelete = []\n for s in sockets:\n if s == self.relay:\n self.logger.info(\"checking relay\")\n msg = self.relay.recv_pyobj()\n # msg = ['sub', ( obj, attr, unit ) ... ] -- Subscribe \n # msg = ['pub', ( obj, attr, unit ) ... ] -- Publish\n # msg = ['qry', id, ( obj, attr, unit ) ... ] -- Query \n self.logger.info(\"run: relay recv = %s\" % str(msg))\n cmd = msg[0]\n if cmd == 'sub':\n self.subscribe(msg[1:])\n elif cmd == 'pub': \n self.publish(msg[1:])\n elif cmd == 'qry':\n self.query(msg[1],msg[2:])\n else:\n self.logger.error('run: error in command: %s' % str(msg))\n elif s == self.bgsrv_data_outer:\n msg = self.bgsrv_data_outer.recv_pyobj()\n self.logger.info(\"run: sending data = %s\" % str(msg))\n self.relay.send_pyobj(msg)\n else:\n pass # Spurious socket? \n toDelete += [s]\n for s in toDelete:\n del sockets[s]\n except:\n traceback.print_exc()\n ok = False\n if self.terminated.is_set() or (self.bgsrv == None and self.conn == None): break\n if self.terminated.is_set(): break\n if DSSAClient.RECONNECT:\n self.logger.info(\"Connection to controller lost - retrying\")\n continue\n else:\n break\n self.logger.info('DSSAClient terminated')\n \n def setupBgSocket(self):\n global DSSACLIENT_DATA_ENDPOINT\n self.bgsrv_data_inner = self.context.socket(zmq.PAIR)\n self.bgsrv_data_inner.connect(DSSACLIENT_DATA_ENDPOINT)\n \n def handleBgServingThreadException(self):\n self.bgsrv = None\n self.conn = None\n self.bgsrv_data_inner.close()\n self.bgsrv_data_inner = None\n \n def callback(self,msg):\n '''\n Callback from server - runs in the the background server thread \n '''\n assert type(msg) == tuple\n if self.bgsrv_data_inner == None: self.setupBgSocket()\n \n reply = None\n try: \n cmd = msg[0]\n if cmd == 'sendClient':\n self.bgsrv_data_inner.send_pyobj(msg)\n else:\n pass\n except:\n info = sys.exc_info()\n self.logger.error(\"Error in callback '%s': %s %s\" % (cmd, info[0], info[1]))\n traceback.print_exc()\n raise\n return reply\n\n def activate(self):\n self.active.set()\n self.logger.info('DSSAClient activated')\n \n def deactivate(self):\n self.active.clear()\n self.logger.info('DSSAClient deactivated')\n \n def terminate(self):\n self.active.set()\n self.terminated.set()\n self.logger.info('DSSAClient terminating')\n \n def get_plug(self):\n return self.relay\n\nclass OpenDSS(Component):\n def __init__(self, host='', port=0):\n super(OpenDSS, self).__init__()\n self.logger.info(\"OpenDSS.__init__()\")\n self.host = host\n self.port = port\n self.running = False\n self.DSSAClient = None\n \n def handleActivate(self):\n self.logger.info(\"OpenDSS.handleActivate()\")\n try:\n clientName = \"DSSA-%s\" % str(hex(int.from_bytes(self.getActorID(),'big')))\n self.DSSAClient = DSSAClient(self,clientName,self.host,self.port,self.relay,self.logger)\n self.DSSAClient.start() # Run the thread\n plug = None\n while plug is None:\n plug = self.glaClient.get_plug()\n time.sleep(0.1)\n self.plugID = self.relay.get_plug_identity(plug)\n self.relay.activate()\n self.DSSAClient.activate()\n self.running = True\n except Exception as e:\n self.logger.error('Exception: %s' % str(e))\n if self.DSSAClient != None:\n self.DSSAClient.stop()\n \n def on_command(self):\n msg = self.command.recv_pyobj()\n self.logger.info(\"on_command(): %s\" % str(msg))\n cmd = msg[0]\n if not self.running:\n self.logger.info(\"DSSA Client not running\")\n return\n if cmd == 'pub' : \n # msg = [ 'pub' , ( 'obj', 'attr', 'unit' ) ... ] -- Publish\n self.relay.set_identity(self.plugID)\n self.relay.send_pyobj(msg)\n self.command.send_pyobj('ok')\n elif cmd == 'sub':\n # msg = [ 'sub' , ( 'obj', 'attr', 'unit' ) ... ] -- Subscribe\n self.relay.set_identity(self.plugID) \n self.relay.send_pyobj(msg)\n self.command.send_pyobj('ok')\n elif cmd == 'qry':\n # msg = [ 'qry' , ( 'obj', 'attr', 'unit' ) ... ] -- Query\n id = self.command.get_identity()\n qry = [cmd,id] + msg[1:]\n self.relay.set_identity(self.plugID)\n self.relay.send_pyobj(qry)\n else:\n self.logger.error(\"OpenDSS.on_command: unknown command: %s\" % str(msg))\n \n def on_relay(self):\n msg = self.relay.recv_pyobj()\n self.logger.info(\"on_relay(): recv = %s\" % str(msg))\n cmd = msg[0]\n if cmd == 'sendClient':\n data = msg[1:]\n self.data.send_pyobj(data)\n elif cmd == 'ans': \n id,ans = msg[1],msg[2]\n self.command.set_identity(id)\n self.command.send_pyobj(ans)\n else:\n pass\n\n def __destroy__(self):\n self.logger.info(\"__destroy__\")\n self.running = False\n self.DSSAClient.deactivate()\n self.DSSAClient.terminate()\n self.DSSAClient.join()\n self.logger.info(\"__destroy__ed\")\n \n \n","sub_path":"device/OpenDSS.py","file_name":"OpenDSS.py","file_ext":"py","file_size_in_byte":13161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"630283602","text":"from __future__ import absolute_import\n\nimport logging\nimport numpy as np\n\nfrom . import pg_config\nfrom relaax.common.algorithms.lib import experience\nfrom .model_api import ModelApi\n\nlogger = logging.getLogger(__name__)\n\n\n# PG Trainer implements training regime for Policy Gradient algorithm\n# If exploit on init set to True, agent will run in exploitation regime:\n# stop updating shared parameters and at the end of every episode load\n# new policy parameters from PS\nclass Trainer(object):\n def __init__(self, session_arg, exploit, parameter_server, metrics):\n self.ps = parameter_server\n self.metrics = metrics\n self.exploit = exploit\n self.last_state = None\n self.last_action = None\n self.keys = ['reward', 'state', 'action']\n self.experience = None\n self.model_api = ModelApi(session_arg, exploit, parameter_server)\n self.begin()\n\n def begin(self):\n assert self.experience is None\n self.model_api.load_shared_parameters()\n self.experience = experience.Experience(*self.keys)\n\n def end(self):\n assert self.experience is not None\n _experience = self.experience\n self.experience = None\n\n if not self.exploit:\n self.model_api.apply_gradients(self.model_api.compute_gradients(_experience), len(_experience))\n\n def reset(self):\n self.experience = None\n\n def step(self, reward, state, terminal):\n if reward is not None:\n self.push_experience(reward, terminal)\n if terminal and state is not None:\n logger.warning('PG Agent.step ignores state in case of terminal.')\n state = None\n else:\n assert state is not None\n if not terminal:\n state = np.asarray(state)\n if state.size == 0:\n state = np.asarray([0])\n state = np.reshape(state, state.shape + (1,))\n action = self.get_action(state)\n self.keep_state_and_action(state, action)\n return action\n\n # Helper methods\n def push_experience(self, reward, terminal):\n assert self.last_state is not None\n assert self.last_action is not None\n\n assert self.experience is not None\n self.experience.push_record(reward=reward, state=self.last_state, action=self.last_action)\n\n if (len(self.experience) == pg_config.config.batch_size) or terminal:\n self.end()\n if terminal:\n self.reset()\n self.begin()\n\n self.last_state = None\n self.last_action = None\n\n def get_action(self, state):\n if state is None:\n return None\n action = self.model_api.action_from_policy(state)\n assert action is not None\n return action\n\n def keep_state_and_action(self, state, action):\n assert self.last_state is None\n assert self.last_action is None\n\n self.last_state = state\n self.last_action = action\n","sub_path":"relaax/algorithms/policy_gradient/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"507259908","text":"import requests\nimport json\nimport pprint\nimport re\nimport ast\n\n# vars\nsyllables=0\nsyllables1=0\nsyllables2=0\nsyllables3=0\nsyllables4=0\nsyllables5 = 0\nsentences=0\nwords=0\n\nstorymaplist=['d51f8ab5d4b84a8d8208a369fad5f520', '0a718288bcb44cbe9f5cf439179b719d','12ba699e36d549daa5f0f27a63c2ebe0']\n\nfor i in range(0, len(storymaplist)):\n storymap=storymaplist[i]\n URL2=\"https://www.arcgis.com/sharing/rest/content/items/\" + storymap + \"/data\"\n publicURL=\"https://storymaps.arcgis.com/stories/\" + storymap\n\n # get storymap json\n resp = requests.get(URL2)\n mytext = resp.content\n\n # pprint.pprint(jtext)\n\n # convert json to python dictionary\n jtext = json.loads(mytext)\n\n # loop over nodes and check for data-text\n for i, entry in enumerate(jtext['nodes']):\n try:\n summary = jtext['nodes'][entry][\"data\"][\"summary\"]\n if len(summary) != 0:\n title = jtext['nodes'][entry][\"data\"][\"title\"]\n except:\n dummyload=1\n\n try:\n myvar = jtext['nodes'][entry][\"data\"][\"text\"]\n except:\n myvar=''\n\n myvar=re.sub('<[^<]+?>', '', myvar)\n # output to screen for testing\n #print(myvar)\n if len(myvar) != 0:\n syllables1 = myvar.count('a')\n syllables2 = myvar.count('e')\n syllables3 = myvar.count('i')\n syllables4 = myvar.count('o')\n syllables5 = myvar.count('u')\n syllables = syllables + syllables1 + syllables2 + syllables3 + syllables4 + syllables5\n # remove common diphthongs and trailing e to improve syllable count\n trailingE = myvar.count('e ')\n #dip1 = myvar.count('ea')\n dip1 = 0 # set to zero to align better with MS Words FK results\n syllables = syllables - trailingE - dip1\n words = words + myvar.count(' ') +1\n sentences = sentences + myvar.count('.') + myvar.count('?')+ myvar.count('!') + .45 # the final constant is intended to help ofset title lines that don't contain punctuation. this number can be adjusted (prob .2 to 1.0).\n #print(syllables, words, sentences)\n\n # calculate fk\n print('Title: ' + title)\n print('URL: ' + publicURL)\n fk = (.39 * (words / sentences)) + (11.8 * (syllables / words)) -15.59\n # estimate Lexile Reader Measure\n # table: http://www.evers.cps.edu/What%20is%20A%20Lexile%20and%20How%20Does%20it%20Compare%20to%20My%20RIT%20Score.html\n # table: https://www.lexialearning.com/blog/more-number-what-is-lexile-measure\n final_fk = round(fk, 1)\n with open('lexile.txt') as f:\n data = f.read()\n lexiledata = ast.literal_eval(data)\n for key in lexiledata:\n if str(key) == str(final_fk):\n print('Estimated Lexile reading score: ' + str(lexiledata[key]) + 'L')\n print('Approximate Flesch-Kincaid reading grade level: ', final_fk)\n print(' ')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"328947642","text":"import numpy as np\nfrom matplotlib.pyplot import *\n\ndef interpolate(X, Y):\n k = len(X)\n L = lambda j: lambda x: np.prod([\n (x - X[i]) / (X[j] - X[i]) for i in range(k) if i != j\n ])\n P = lambda x: np.sum([Y[j] * L(j)(x) for j in range(k)])\n return P\n\nif __name__ == '__main__':\n x = np.arange(10)\n y = x ** 2\n f = lagrange(x, y)\n plot(x, y)\n plot(x, [f(xi) for xi in x])\n show()\n","sub_path":"interpolation/lagrange.py","file_name":"lagrange.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"392618542","text":"import sys\nimport numpy as np\nimport pickle\n\nimport matplotlib as mpl\nmpl.use('TkAgg')\n\nfrom sklearn import model_selection, svm, preprocessing\nfrom sklearn.metrics import accuracy_score,confusion_matrix, f1_score, recall_score, precision_score\nfrom mnistloader.mnist_loader import MNIST\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nstyle.use('ggplot')\n\nold_stdout = sys.stdout\nlog_file = open(\"SVMsummary.log\",\"w\")\nsys.stdout = log_file\nprint(\"SVM Log :\\n\\n\")\ndata = MNIST('./mnistloader/dataset/')\n\nimg_train, labels_train = data.load_training()\ntrain_img = np.array(img_train)\ntrain_labels = np.array(labels_train)\nimg_test, labels_test = data.load_testing()\ntest_img = np.array(img_test)\ntest_labels = np.array(labels_test)\n\nX = train_img\ny = train_labels\n\nclf = svm.SVC(gamma=0.1, kernel='poly')\nclf.fit(X,y)\n\nwith open('MNIST_SVM.pickle','wb') as f:\n\tpickle.dump(clf, f)\n\npickle_in = open('MNIST_SVM.pickle','rb')\nclf = pickle.load(pickle_in)\n\n# acc = clf.score(X,y)\n# y_pred = clf.predict(X)\n# accuracy = accuracy_score(y, y_pred)\n# precision = precision_score(y, y_pred,average='macro')\n# recall = recall_score(y, y_pred,average='macro')\n# f1 = f1_score(y, y_pred,average='macro')\n# conf_mat = confusion_matrix(y,y_pred)\n#\n# print('\\nSVM Trained Classifier Accuracy: ',acc)\n# print('\\nAccuracy of Classifier on Training Images: ',accuracy)\n# print('\\nPrecision of Classifier on Training Images: ',precision)\n# print('\\nRecall of Classifier on Training Images: ',recall)\n# print('\\nF1 of Classifier on Training Images: ',f1)\n# print('\\nConfusion Matrix: \\n',conf_mat)\n#\n# plt.matshow(conf_mat)\n# plt.title('Confusion Matrix for Training Data')\n# plt.colorbar()\n# plt.ylabel('True label')\n# plt.xlabel('Predicted label')\n# plt.show()\n\ntest_labels_pred = clf.predict(test_img)\n\nacc = accuracy_score(test_labels,test_labels_pred)\ntprecision = precision_score(test_labels,test_labels_pred,average='macro')\ntrecall = recall_score(test_labels,test_labels_pred,average='macro')\ntf1 = f1_score(test_labels,test_labels_pred,average='macro')\nconf_mat_test = confusion_matrix(test_labels,test_labels_pred)\n\nprint('\\nAccuracy of Classifier on Test Images: ',acc)\nprint('\\nPrecision of Classifier on Test Images: ',tprecision)\nprint('\\nRecall of Classifier on Test Images: ',trecall)\nprint('\\nF1 of Classifier on Test Images: ',tf1)\nprint('\\nConfusion Matrix for Test Data: \\n',conf_mat_test)\n\n# Plot Confusion Matrix for Test Data\nplt.matshow(conf_mat_test)\nplt.title('Confusion Matrix for Test Data')\nplt.colorbar()\nplt.ylabel('True label')\nplt.xlabel('Predicted label')\nplt.axis('off')\nplt.show()\n\nsys.stdout = old_stdout\nlog_file.close()\n","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":2652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"61068505","text":"# Leetcode - 4 - Median of two sorted arrays - https://leetcode.com/problems/median-of-two-sorted-arrays/\n# Time compexity - min(O(log(N) ,o(logM)) which ever is smaller that we consider\n# space complexity - O(1)\n# Approach - we do binary search for the smaller array and divide the partions into two parts for both arrays. The condition should be L1<=R1 and R2 and L2<=R1 and R2.\n\nclass Solution(object):\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n if len(nums1)>len(nums2):\n return self.findMedianSortedArrays(nums2,nums1)\n \n n1=len(nums1)\n n2=len(nums2)\n \n low=0\n high=n1\n while low<=high:\n partx=low+(high-low)//2\n party=(n1+n2+1)//2 -partx # 1 to consider odd length\n L1=float(\"-inf\") if partx == 0 else nums1[partx-1]\n R1=float(\"inf\") if partx==n1 else nums1[partx]\n L2=float(\"-inf\") if party==0 else nums2[party-1]\n R2=float(\"inf\") if party==n2 else nums2[party]\n #base condition \n if (L1<=R2 and L2<=R1):\n if (n1+n2)%2==0:\n return (max(L1,L2)+min(R1,R2))/2.0\n else:\n return max(L1,L2)\n elif L2>R1:\n low=partx+1\n else:\n high=partx-1\n return -1\n \n \n \n \n","sub_path":"Problem-90.py","file_name":"Problem-90.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"571797130","text":"#!/usr/bin/env python2.7\n\n\"\"\"\nContacts Manager and Sms.\nUsage:\n contact add -n -p \n contact search \n contact text -m ...\n contact view []\n contact (-i | --interactive)\n contact (-h | --help)\nOptions:\n -i, --interactive Interactive Mode\n -h, --help Show this screen and exit\n -n Person's name\n -p Person's phone number\n -m Message to send to a recipient\n\"\"\"\n\nimport sys\nimport cmd\nimport sqlite3\nfrom docopt import docopt, DocoptExit\n\nimport add_contact.addContact as addContact\nimport text_contact.textContact as textContact\nimport search_contact.searchContact as searchContact\nimport view_messages.viewMessages as viewMessages\n\nconn = sqlite3.connect('database/app_data.db')\n\ndef docopt_cmd(func):\n \"\"\"\n This decorator is used to simplify the try/except block and pass the result\n of the docopt parsing to the called action.\n \"\"\"\n\n def fn(self, arg):\n try:\n opt = docopt(fn.__doc__, arg)\n\n except DocoptExit as e:\n # The DocoptExit is thrown when the args do not match.\n # We print a message to the user and the usage block.\n\n print('Invalid Command!')\n print(e)\n return\n\n except SystemExit:\n # The SystemExit exception prints the usage for --help\n # We do not need to do the print here.\n\n return\n\n return func(self, opt)\n\n fn.__name__ = func.__name__\n fn.__doc__ = func.__doc__\n fn.__dict__.update(func.__dict__)\n return fn\n\nclass ContactsInteractive(cmd.Cmd):\n intro = '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n' \\\n \t+ 'Welcome to Contacts Manager Console Application.\\n' \\\n + 'Add, search, and send one-way text messages to your contacts.\\n' \\\n + 'Note: Only Kenyan phone numbers are supported, (+254 7xx xxx xxx).\\n' \\\n + '(type help for a list of commands.)\\n'\\\n + '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'\n prompt = '(Contacts) '\n\n @docopt_cmd\n def do_add(self, arg):\n \"\"\"\n Add a person to contacts list.\n Usage:\n \tadd -n -p \n \"\"\"\n print (addContact.add(arg))\n\n @docopt_cmd\n def do_search(self, arg):\n \"\"\"\n Search a person in contacts list.\n Usage:\n \tsearch \n \"\"\"\n print (searchContact.search(arg))\n\n @docopt_cmd\n def do_text(self, arg):\n \"\"\"\n Message a person in contacts list.\n Usage:\n \ttext -m ...\n \"\"\"\n print (textContact.text(arg))\n\n @docopt_cmd\n def do_view(self, arg):\n \"\"\"\n View messages sent to a contact or view all sent messages.\n Usage:\n view []\n \"\"\"\n print (viewMessages.view(arg))\n\n def do_quit(self, arg):\n \"\"\"\n Quits out of Interactive Mode.\n \"\"\"\n\n print('Thank you for using Contacts Manager. Bye!')\n conn.close()\n exit()\nopt = docopt(__doc__, sys.argv[1:])\n\nif opt['--interactive']:\n ContactsInteractive().cmdloop()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"541711325","text":"from __future__ import annotations\n\n__all__ = (\"fit\", \"fixed_poi_fit\")\n\nfrom functools import partial\nfrom typing import TYPE_CHECKING, Any, Callable, cast\n\nimport jax\nimport jax.numpy as jnp\nimport jaxopt\nimport optax\n\nfrom relaxed._types import Array\n\nif TYPE_CHECKING:\n import pyhf\n\n\n@partial(jax.jit, static_argnames=[\"objective_fn\"])\ndef _minimize(\n objective_fn: Callable[..., float], init_pars: Array, lr: float, *obj_args: Any\n) -> Array:\n converted_fn, aux_pars = jax.closure_convert(objective_fn, init_pars, *obj_args)\n # aux_pars seems to be empty? took that line from jax docs example...\n solver = jaxopt.OptaxSolver(\n fun=converted_fn, opt=optax.adam(lr), implicit_diff=True, maxiter=5000\n )\n return solver.run(init_pars, *obj_args, *aux_pars)[0]\n\n\ndef global_fit_objective(data: Array, model: pyhf.Model) -> Callable[[Array], float]:\n def fit_objective(lhood_pars_to_optimize: Array) -> float: # NLL\n \"\"\"lhood_pars_to_optimize: either all pars, or just nuisance pars\"\"\"\n return cast(\n float, -model.logpdf(lhood_pars_to_optimize, data)[0]\n ) # pyhf.Model.logpdf returns list[float]\n\n return fit_objective\n\n\n@partial(jax.jit, static_argnames=[\"model\"])\ndef fit(\n data: Array,\n model: pyhf.Model,\n init_pars: Array,\n lr: float = 1e-3,\n) -> Array:\n obj = global_fit_objective(data, model)\n fit_res = _minimize(obj, init_pars, lr)\n return fit_res\n\n\ndef fixed_poi_fit_objective(\n data: Array,\n model: pyhf.Model,\n) -> Callable[[Array, float], float]:\n poi_idx = model.config.poi_index\n\n def fit_objective(\n lhood_pars_to_optimize: Array, poi_condition: float\n ) -> float: # NLL\n \"\"\"lhood_pars_to_optimize: either all pars, or just nuisance pars\"\"\"\n # pyhf.Model.logpdf returns list[float]\n blank = jnp.zeros_like(jnp.asarray(model.config.suggested_init()))\n blank += lhood_pars_to_optimize\n return cast(float, -model.logpdf(blank.at[poi_idx].set(poi_condition), data)[0])\n\n return fit_objective\n\n\n@partial(jax.jit, static_argnames=[\"model\"])\ndef fixed_poi_fit(\n data: Array,\n model: pyhf.Model,\n init_pars: Array,\n poi_condition: float,\n lr: float = 1e-3,\n) -> Array:\n obj = fixed_poi_fit_objective(data, model)\n fit_res = _minimize(obj, init_pars, lr, poi_condition)\n blank = jnp.zeros_like(jnp.asarray(model.config.suggested_init()))\n blank += fit_res\n poi_idx = model.config.poi_index\n return blank.at[poi_idx].set(poi_condition)\n","sub_path":"src/relaxed/mle.py","file_name":"mle.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"251709366","text":"\"\"\"Initial Migration\n\nRevision ID: 162cc5d1ce75\nRevises: b2800662e1e9\nCreate Date: 2021-06-12 22:10:31.983931\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '162cc5d1ce75'\ndown_revision = 'b2800662e1e9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('pitches', 'pitch_id')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('pitches', sa.Column('pitch_id', sa.INTEGER(), autoincrement=False, nullable=True))\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/162cc5d1ce75_initial_migration.py","file_name":"162cc5d1ce75_initial_migration.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"553376971","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def maxAncestorDiff(self, root: TreeNode) -> int:\n ans = 0\n def dfs(node):\n nonlocal ans\n if not node:\n return float('inf'), -float('inf')\n \n if (not node.left) and (not node.right):\n return node.val, node.val\n\n l_min, l_max = dfs(node.left)\n r_min, r_max = dfs(node.right)\n min_v, max_v = min(l_min, r_min), max(l_max, r_max)\n \n ans = max(ans, abs(node.val - min_v), abs(max_v - node.val))\n \n return min(l_min, r_min, node.val), max(l_max, r_max, node.val)\n \n dfs(root)\n return ans\n \n ","sub_path":"Python/1026_Maximum Difference Between Node and Ancestor.py","file_name":"1026_Maximum Difference Between Node and Ancestor.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"353215669","text":"from collections import OrderedDict\n\nfrom django.contrib.auth.models import User\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\n\nfrom api.driving.models import Student, Parent\n\n\n# Create your dictionary class\nclass MyDic(dict):\n\n # __init__ function\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self = dict()\n\n # Function to add key:value\n def add(self, key, value):\n self[key] = value\n\n\nclass UserSerialize(serializers.ModelSerializer):\n\n class Meta:\n model = User\n fields = [\n 'email',\n 'first_name',\n 'last_name',\n ]\n\n extra_kwargs = {\n 'first_name' : {\n 'read_only' : True\n },\n 'last_name' : {\n 'read_only' : True\n }\n }\n\n\nclass ParentSerializer(serializers.ModelSerializer):\n user = UserSerialize()\n\n class Meta:\n model = Parent\n fields = [\n 'user'\n ]\n\n\nclass GetStudentsSerializer(serializers.Serializer):\n parent = ParentSerializer()\n\n class Meta:\n model = Student\n fields = [\n 'parent',\n ]\n\n def validate(self, data):\n parent = data.get(\"parent\")\n user = parent.get(\"user\")\n email = user.get(\"email\")\n\n student_set = Student.objects.filter(parent__user__email=email)\n if not student_set.exists():\n raise ValidationError(\"This parent doesn't exist!\")\n\n i = 1\n myData = {}\n myData[\"student\"] = []\n\n\n for student in student_set:\n myStudent = MyDic()\n myStudent.add('first_name',student.user.first_name)\n myStudent.add('last_name',student.user.last_name)\n myData[\"student\"].append(myStudent)\n\n # myUser[\"user\"] = my_dic\n # myData[\"parent\"] = myUser\n print(myData)\n\n return myData\n\n","sub_path":"api/driving/rapport/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"46272910","text":"\"\"\"\nsentry.web.frontend.explore\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.\n:license: BSD, see LICENSE for more details.\n\"\"\"\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom sentry.models import TagKey, TagValue, Group\nfrom sentry.web.decorators import login_required, has_access\nfrom sentry.web.helpers import render_to_response\n\nDEFAULT_SORT_OPTION = 'recent'\nSORT_OPTIONS = {\n 'recent': 'Last Seen',\n 'newest': 'First Seen',\n 'events': 'Number of Events',\n}\n\n\n@has_access\n@login_required\ndef list_tag(request, team, project, tag_name):\n try:\n tag = TagKey.objects.get(project=project, key=tag_name)\n except TagKey.DoesNotExist:\n return HttpResponseRedirect(reverse('sentry-stream', args=[team.slug, project.slug]))\n\n sort = request.GET.get('sort')\n if sort not in SORT_OPTIONS:\n sort = DEFAULT_SORT_OPTION\n\n tag_list = TagValue.objects.filter(project=project, key=tag_name)\n\n if sort == 'recent':\n tag_list = tag_list.order_by('-last_seen')\n elif sort == 'newest':\n tag_list = tag_list.order_by('-first_seen')\n elif sort == 'events':\n tag_list = tag_list.order_by('-times_seen')\n\n return render_to_response('sentry/explore/list_tag.html', {\n 'team': team,\n 'project': project,\n 'tag': tag,\n 'tag_list': tag_list,\n 'sort_label': SORT_OPTIONS[sort],\n 'SORT_OPTIONS': SORT_OPTIONS,\n }, request)\n\n\n@has_access\n@login_required\ndef tag_details(request, team, project, tag_name, tag_id):\n try:\n tag = TagKey.objects.get(project=project, key=tag_name)\n except TagKey.DoesNotExist:\n return HttpResponseRedirect(reverse('sentry-stream', args=[team.slug, project.slug]))\n\n tag_value = TagValue.objects.get(\n project=project,\n key=tag_name,\n id=tag_id,\n )\n\n event_list = Group.objects.filter(\n grouptag__project=project,\n grouptag__key=tag_name,\n grouptag__value=tag_value.value,\n )\n\n return render_to_response('sentry/explore/tag_details.html', {\n 'team': team,\n 'project': project,\n 'tag': tag,\n 'tag_value': tag_value,\n 'event_list': event_list,\n }, request)\n","sub_path":"src/sentry/web/frontend/explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"512843047","text":"\n\nfrom collections import deque\nclass topologicalSort():\n def __init__(self, n):\n self.n = n\n self.g = [[] for _ in range(n)]\n self.edgeNum = [0] * n\n def makeEdge(self, u, v):\n assert u != v\n self.g[u].append(v)\n self.edgeNum[v] += 1 # 入次++\n def solve(self):\n q = deque([])\n ans = []\n for i in range(self.n):\n if(self.edgeNum[i] != 0): continue\n q.appendleft(i)\n ans.append(i)\n while(len(q) > 0):\n cur = q.popleft()\n for nxt in self.g[cur]:\n self.edgeNum[nxt] -= 1\n if self.edgeNum[nxt] == 0:\n ans.append(nxt)\n q.append(nxt)\n return ans\n\n\ndef GRL_4_B():\n n, m = map(int, input().split())\n ts = topologicalSort(n)\n for _ in range(m):\n u, v = map(int, input().split())\n ts.makeEdge(u, v)\n ans = ts.solve()\n for x in ans: print(x)\n\nGRL_4_B()","sub_path":"atcoder/lib/graph/topogogcalSort.py","file_name":"topogogcalSort.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"470767030","text":"from __future__ import print_function # Debugging purposes\nimport sys\n\n# Debugging purposes\ndef dbg(text):\n print(text, file=sys.stderr)\n sys.stderr.flush()\n\n\nDIRS = [\n ((-1, 0), \"up\"),\n ((0, 1), \"right\"),\n ((1, 0), \"down\"),\n ((0, -1), \"left\")\n]\n\n\n# can modify this to look at string directly\ndef get_field_index(row, col):\n return row*16 + col\n\nclass Board:\n\n def __init__(self, width, height):\n self.width = width\n self.height = height\n self.cell = [[\".\" for col in range (0, width)] for row in range(0, height)]\n\n self.my_botid = \"-1\"\n self.other_botid = \"-1\"\n self.my_bot_position = (-1, -1)\n self.other_bot_position = (-1, -1)\n\n def find_starting_pos(self, my_botid, field):\n self.my_botid = str(my_botid)\n self.other_botid = str(1 - my_botid)\n field_array = field.split(\",\")\n for row in range(1, 15):\n for col in range(1, 7):\n cell_value = field_array[get_field_index(row, col)]\n if (cell_value == \"0\" or cell_value == \"1\"):\n if (self.my_botid == cell_value):\n self.my_bot_position = (row, col)\n self.other_bot_position = (row, 15-col)\n self.cell[row][col] = self.my_botid\n self.cell[row][15-col] = self.other_botid\n else:\n self.my_bot_position = (row, 15-col)\n self.other_bot_position = (row, col)\n self.cell[row][15-col] = self.my_botid\n self.cell[row][col] = self.other_botid\n\n def block_cell(self, position):\n (row, col) = position\n self.cell[row][col] = \"x\"\n\n def update_board(self, new_board):\n new_board = new_board.split(\",\")\n self.output()\n\n self.block_cell(self.my_bot_position)\n self.block_cell(self.other_bot_position)\n\n for (row, col) in self.get_adjacent(self.my_bot_position):\n potential_pos = new_board[get_field_index(row, col)]\n if potential_pos == self.my_botid:\n self.my_bot_position = (row, col)\n self.cell[row][col] = self.my_botid\n break\n\n for (row, col) in self.get_adjacent(self.other_bot_position):\n potential_pos = new_board[get_field_index(row, col)]\n if potential_pos == self.other_botid:\n self.other_bot_position = (row, col)\n self.cell[row][col] = self.other_botid\n break\n\n\n def is_legal(self, row, col):\n return self.cell[row][col] == \".\" and row>=0 and col>=0 and col(.*?)

',\n \"success\": \"succesfully\"\n },\n \"https://hashtoolkit.com/decrypt-hash/\": {\n \"parameters\": {\"hash\": sha1},\n \"regex\": r'',\n \"success\": \"Hash Results\"\n }\n }\n global HEADER\n\n def decriptor(self):\n for web, data in self.URL.items():\n response = requests.get(web, params=data[\"parameters\"], headers=HEADER, timeout=5)\n\n yield [web, re.search(data[\"regex\"], response.text).group(1)] if data[\"success\"] in response.text else [web, \"N/A\"]\n\n class SHA1_POST:\n def __init__(self, sha1):\n self.URL = {\n \"https://md5decrypt.net/en/Sha1\": {\n \"parameters\": {\n \"hash\": sha1,\n \"captcha58\": \"\",\n \"ahah58\": \"15dcf9dc3024bc33a723cb4958598499\",\n \"decrypt\": \"Decrypt\"\n },\n \"regex\": r'.(*?)\\b',\n \"success\": \"Found in\"\n\n }\n }\n global HEADER\n\n def decriptor(self):\n for web, data in self.URL.items():\n response = requests.post(web, data=data[\"parameters\"], headers=HEADER, timeout=5)\n\n yield [web, re.search(data[\"regex\"], response.text).group(1)] if data[\"success\"] in response.text else [web, \"N/A\"]\n\n\nclass MD5:\n class MD5_GET:\n def __init__(self, md5):\n self.URL = {\n \"https://md5.gromweb.com/\": {\n \"parameters\": {\"md5\": md5},\n \"regex\": r'string\">(.*?)

',\n \"success\": \"succesfully\"\n\n }\n }\n global HEADER\n\n def decriptor(self):\n for web, data in self.URL.items():\n response = requests.get(web, params=data[\"parameters\"], headers=HEADER, timeout=5)\n\n yield [web, re.search(data[\"regex\"], response.text).group(1)] if data[\"success\"] in response.text else [web, \"N/A\"]\n\n class MD5_POST:\n def __init__(self, md5):\n self.URL = {\n \"https://www.md5online.org/md5-decrypt.html\": {\n \"parameters\": {\n \"hash\": md5,\n \"quick\": 1,\n \"g-recaptcha-response\": \"03AGdBq26CyPfi9sd2pWnFD4YT2ltLdFk39ZIbj3MiBNASmxFR1WmqJbFFwzlm-PmTUUR4TYdo21hwlrTE-bWfU5r3FNbs3NQe78gaijYaKYnE7taH62qchs1tPW-_rgjmfrdRAgrgWQn2962YrbpO3Dyge-O2evTSP5SP-WOWXwNR065JTjaJatQIMcd0RUpFQjBEuZH_rIaOS0hV1YK0kl7NcYCa8cAolxgygvS9IpEi9oZ3Q__zNdqF6peUnfIoQ8odx0El_XKWchIXVfQs088z3l9HW2nU-a51ewVpHL049bfuoABTzgYqLH_nn7zIaHZKeZcbv_JZ1nlg6unESc0ThBtkBmL0TcRhqSNh5E88nGpVR-ri86dUcJM5f7Tn13IAD8eLimnkda6dGxvW302f-y5YV1F3Aw\"\n },\n \"regex\": r'Found : *?',\n \"success\": \">Found : \"\n\n }\n }\n\n global HEADER\n\n def decriptor(self):\n for web, data in self.URL.items():\n response = requests.post(web, params=data[\"parameters\"], headers=HEADER, timeout=5)\n\n yield [web, re.search(data[\"regex\"], response.text).group(1)] if data[\"success\"] in response.text else [web, \"N/A\"]\n\n\nif __name__ == \"__main__\":\n hash_ = getopt(argv[1:], \"e:\", [\"encoding=\"])[1][0]\n encoding_ = \"ALL\"\n\n for opt, arg in getopt(argv[1:], \"e:\", [\"encoding=\"])[0]:\n if opt in [\"-e\", \"--encoding\"]:\n encoding_ = arg\n\n if encoding_:\n if encoding_.upper() in [\"MD5\",\"ALL\"] and hash_:\n MD5_G = MD5().MD5_GET(hash_)\n\n print(\"\\n\\nMD5 GET\")\n for web_, decode_ in MD5_G.decriptor():\n print(web_, \":\", decode_)\n\n if encoding_.upper() in [\"SHA1\",\"ALL\"] and hash_:\n SHA_G = SHA1().SHA1_GET(hash_)\n\n print(\"\\n\\nSHA1 GET\")\n for web_, decode_ in SHA_G.decriptor():\n print(web_, \":\", decode_)\n\n if encoding_.upper() in [\"MD5\",\"ALL\"] and hash_:\n MD5_P = MD5().MD5_POST(hash_)\n\n print(\"\\n\\nMD5 POST\")\n for web_, decode_ in MD5_P.decriptor():\n print(web_, \":\", decode_)\n\n if encoding_.upper() in [\"SHA1\",\"ALL\"] and hash_:\n SHA_P = SHA1().SHA1_POST(hash_)\n\n print(\"\\n\\nSHA1 POST\")\n for web_, decode_ in SHA_P.decriptor():\n print(web_, \":\", decode_)\n","sub_path":"decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"487625834","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n \nfrom __future__ import print_function, unicode_literals\nimport requests\nimport pprint\nimport json\nimport psycopg2\nfrom datetime import timedelta\nimport time\nimport datetime\n#\nimport argparse\n#APIKEY = 'a457ce84d8c5de43c9e909ea49bb9e8f'\n#ROOMID = '152553520'\n#ROOMID='152582262'\ndef convhtml(htmlcont):\n\timport html2text\n \n\thc=htmlcont.decode('utf-8')\n\t\n\th= html2text.HTML2Text()\n\th.ignore_links = True\n\th.escape_all=True\n\ttext=h.handle(hc)\n\tprint(text)\n\treturn text \ndef cwpost(arglist):\n\ttext=arglist[0]\n\trmid=arglist[1]\n\tprint (text)\n\tprint (rmid)\n\ttextv=text\n\tAPIKEY= 'e21da3c399cf0fb644faaee7f64eea7b'\n\tENDPOINT = 'https://api.chatwork.com/v2'\n\tROOMID=rmid\n\t#ROOMID='152939278'\n\tpost_message_url = '{}/rooms/{}/messages'.format(ENDPOINT, ROOMID)\n\tprint (post_message_url)\n\theaders = { 'X-ChatWorkToken': APIKEY }\n\tparams = { 'body': textv }\n\n\tresp = requests.post(post_message_url,\n headers=headers,\n params=params)\n\n\n\n\n\tpprint.pprint(resp.content)\n \nif __name__=='__main__':\n\n\tparser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\t'''\n\tparser.add_argument(\n 'text',\n help='text')\n '''\n\tparser.add_argument(\"-v\", \"--val\",\n help=\"multiple values for this option\",\n nargs=\"*\",\n dest=\"vals\"\n )\n \n\targs = parser.parse_args()\n \n\tcwpost(args.vals)\n\n","sub_path":"cwpost.py","file_name":"cwpost.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"631240514","text":"\"\"\"\nSpace game\nRyan Kynor\nChecklist:\nfixed star field\n~~Sun sprite~~\nat least one player\nmuliple players or multplie inanimate objects to avoid\nanimated rocket thrust\ncollisions destroy ship\nmoving ships\nrotating ships\nSource:\nlines 23 - 27 based off of orininal space game code\nlines 123 and 124 taken from idea in original code\n\"\"\"\n\n#key list starts a line 1067 in ggame.py file\n\nfrom ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame\nfrom math import cos, sin\nSCREEN_WIDTH = 640\nSCREEN_HEIGHT = 480\n\n\nclass Sun(Sprite):\n \"\"\"\n The Sun on the Screen\n \"\"\"\n \n asset = ImageAsset(\"images/sun.png\")\n height = 80\n width = 80\n \n def __init__(self, position):\n super().__init__(Sun.asset, position)\n self.weight = 1\n self.fxcenter = 0.5\n self.fycenter = 0.5\n self.circularCollisionModel()\n \n \n \nclass Starfield(Sprite):\n \"\"\"\n The Starfield\n \"\"\"\n \n asset = ImageAsset(\"images/starfield.jpg\")\n #height = SCREEN_HEIGHT\n #width = SCREEN_WIDTH\n \n def __init__(self, position):\n super().__init__(Starfield.asset, position)\n self.weight = 1\n self.fxcenter = 0.5\n self.fycenter = 0.5\n\n\n\nclass SpaceShip(Sprite):\n \"\"\"\n Animated space ship\n \"\"\"\n asset = ImageAsset(\"images/four_spaceship_by_albertov_with_thrust.png\", \n Frame(227,0,292-227,125), 4, 'vertical')\n \n#spaceship spawn movement\n def __init__(self, position):\n super().__init__(SpaceShip.asset, position)\n self.vx = 0\n self.vy = 0\n self.vr = 0.00\n self.thrust = 0\n self.thrustframe = 1\n self.rotateRight = 0\n self.rotateLeft = 0\n self.forward = 0\n self.explode3 = 0\n \n #Thrust detection\n SpaceGame.listenKeyEvent(\"keydown\", \"w\", self.thrustOn)\n SpaceGame.listenKeyEvent(\"keyup\", \"w\", self.thrustOff)\n \n #Rotation detection\n \n SpaceGame.listenKeyEvent(\"keydown\", \"w\", self.moveForwardOn)\n SpaceGame.listenKeyEvent(\"keyup\", \"w\", self.moveForwardOff)\n \"\"\"\n SpaceGame.listenKeyEvent(\"keydown\", \"s\", self.moveBackOn)\n SpaceGame.listenKeyEvent(\"keyup\", \"s\", self.moveBackOff)\n \"\"\"\n \n SpaceGame.listenKeyEvent(\"keydown\", \"a\", self.rotateLeftOn)\n SpaceGame.listenKeyEvent(\"keyup\", \"a\", self.rotateLeftOff)\n \n SpaceGame.listenKeyEvent(\"keydown\", \"d\", self.rotateRightOn)\n SpaceGame.listenKeyEvent(\"keyup\", \"d\", self.rotateRightOff)\n #Rotation animation\n \n #SpaceGame.listenKeyEvent(\"keydown\", \"w\",\n self.fxcenter = self.fycenter = 0.5\n\n#display of thrust\n def step(self):\n if self.explode3 == 1:\n asset = ImageAsset(\"images/explosion2.png\", Frame(0,0,128,128), 10, \"horrizontal\")\n if (self.y > 200) and (self.y < 250) and (self.x > 200) and (self.x < 250):\n self.explode3 = 1\n self.vy = 0\n self.vx = 0\n self.vr = 0\n self.visible = False\n explosion(self.position)\n else:\n self.explode3 = 0\n self.x += self.vx\n self.y += self.vy\n self.rotation += self.vr\n if self.thrust == 1:\n self.setImage(self.thrustframe)\n self.thrustframe += 1\n self.vy = self.vy -0.001\n if self.thrustframe == 4:\n self.thrustframe = 1\n else:\n self.setImage(0)\n\n #if self.collision(self.app.sun) == true:\n # self.explode()\n \n#rotation\n if self.rotateRight == 1:\n self.vr = self.vr -0.001\n if self.rotateLeft == 1:\n self.vr = self.vr +0.001\n self.rotation += self.vr # <<<< change rotation!\n if self.forward == 1: # <<<< forward\n self.vy+=(-cos(self.rotation))\n self.vx+=(-sin(self.rotation))\n \n\n#thrust\n def thrustOn(self, event):\n self.thrust = 1\n def thrustOff(self, event):\n self.thrust = 0\n#explode\n def explode(self):\n print(\"explode\")\n self.explosion(self.position)\n self.destroy()\n \n#movement\n def moveForwardOn(self,event):\n self.forward = 1\n def moveForwardOff(self,event):\n self.forward = 0\n \n def moveRightOn(self,event):\n self.right = 1\n def moveRightOff(self,event):\n self.right = 0\n \n def moveLeftOn(self,event):\n self.left = 1\n def moveLeftOff(self,event):\n self.left = 0\n \n def moveBackOn(self,event):\n self.back = 1\n def moveBackOff(self,event):\n self.back = 0\n \n#rotation\n def rotateRightOn(self,event):\n self.rotateRight = 1\n def rotateRightOff(self,event):\n self.rotateRight = 0\n \n def rotateLeftOn(self,event):\n self.rotateLeft = 1\n def rotateLeftOff(self,event):\n self.rotateLeft = 0\n \n#explosion image\nclass explosion(Sprite):\n\n asset = ImageAsset (\"images/explosion2.png\", Frame(0,0,195,192), 25, \"horizontal\")\n def __init__(self,position):\n super().__init__(explosion.asset, position)\n self.center = (0.5,0.5)\n self.Frame = 0\n self.eSpeed = 0\n def step(self):\n self.setImage(self.Frame)\n self.eSpeed += 0.3\n #self.Frame = init(self.eSpeed)\n self.Frame += 1\n if self.Frame == 25:\n self.destroy() # <<< self.destroy() ??\n\n\"\"\"\nif (y > 200) and (y < 250):\n if (x > 200) and (x < 250):\n explode3 = 1\nelse:\n explode3 = 0\n\"\"\"\nclass SpaceGame(App):\n \"\"\"\n Tutorial4 space game example.\n \"\"\"\n def __init__(self, width, height):\n super().__init__(width, height)\n black = Color(0, 1)\n noline = LineStyle(0, black)\n bg_asset = RectangleAsset(width, height, noline, black)\n bg = Sprite(bg_asset, (0,0))\n \n Starfield((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))\n Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))\n SpaceShip((190,240))\n #SpaceShip((150,150))\n #SpaceShip((200,50))\n\n def step(self):\n for ship in self.getSpritesbyClass(SpaceShip):\n ship.step()\n for explode in self.getSpritesbyClass(explosion):\n explode.step()\n\n\n#Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))\n\nmyapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)\nmyapp.run()\n\n\n\n#self rotation will give you the current angle of rotation in radians","sub_path":"spaceshooter.py","file_name":"spaceshooter.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"358064178","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 30 15:55:29 2015\r\n\r\n@author: Lukas Vikander\r\n\"\"\"\r\nimport numpy\r\nimport pylab\r\n\r\ndef Hittadrift(Qin,Hin):\r\n\r\n poly = numpy.poly1d(coff)\r\n\r\n Qleta = numpy.linspace(0.95*Qin,1.05*Qin,50)\r\n I = len(Qleta)\r\n A,B,C= [],[],[]\r\n\r\n\r\n for I in Qleta:\r\n H = ((Qleta[1]**2)/(Qin**2))*Hin\r\n Hper = poly(I)\r\n Hdiff = abs(H-Hper)\r\n diff = 100-(abs(Hper-Hin)*100)/Hin\r\n A.append(Hper,Hdiff)\r\n B.append(Hdiff)\r\n C.append(diff)\r\n\r\n G,T = numpy.max(C),numpy.argmax(C)\r\n\r\n Qdrif,Hdrif = Qleta[T],A[T]\r\n return Qdrif,Hdrif,G\r\n#pylab.plot(Qdrif,Hdrif,'o')\r\n\r\n\r\n\r\n \r\n","sub_path":"pumpa/templates/Pythonkod/old code/Hittadrift.py","file_name":"Hittadrift.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"514211277","text":"# -*- coding: utf-8 -*-\n\nfrom django import template\n\nregister = template.Library()\n\n@register.inclusion_tag('common/templatetags/display_as_ul.html')\ndef display_as_ul(form):\n \"\"\"\n Muestra los campos del formulario en forma de lista\n \"\"\"\n return {'form': form}\n","sub_path":"common/templatetags/form_display.py","file_name":"form_display.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"425618369","text":"import array\nimport math\nimport time\n\nimport audiobusio\nimport board\nfrom adafruit_circuitplayground import cp\n\n\ndef mean(values):\n return sum(values) / len(values)\n\n\ndef normalized_rms(values):\n minbuf = int(mean(values))\n sum_of_samples = sum(\n float(sample - minbuf) * (sample - minbuf)\n for sample in values\n )\n\n return math.sqrt(sum_of_samples / len(values))\n\n\ndef activate():\n global is_active\n global previous_time\n \n if not is_active:\n is_active = True\n current_time = time.monotonic()\n previous_time = current_time\n cp.pixels.fill(green)\n print(\"START\")\n\n\ndef deactivate():\n global is_active\n global previous_time\n \n if is_active == None or is_active:\n is_active = False\n previous_time = None\n cp.pixels.fill(red)\n print(\"STOP\")\n\n\ndef read_sensors(mic, samples):\n mic.record(samples, len(samples))\n sound = normalized_rms(samples)\n print(\"OK\", cp.temperature * 9 / 5 + 32, cp.light, sound, sep=\",\")\n\n\nmic = audiobusio.PDMIn(\n board.MICROPHONE_CLOCK,\n board.MICROPHONE_DATA,\n sample_rate=16000,\n bit_depth=16\n)\nsamples = array.array('H', [0] * 160)\nprevious_time = None\ninterval = 60 * 1 # seconds * minutes\nred = (10, 0, 0)\ngreen = (0, 10, 0)\nis_active = None\n\ndeactivate()\n\nwhile True:\n current_time = time.monotonic()\n\n if is_active and abs(current_time - previous_time) >= interval:\n read_sensors(mic, samples)\n previous_time = current_time \n\n if cp.button_a:\n activate()\n \n elif cp.button_b:\n deactivate()","sub_path":"cpx/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"528243035","text":"#!/usr/bin/env python\n\nfrom pushbullet import PushBullet\nimport config as conf\nimport credentials as cred\n\n#config\nall_people = ['julian','sarah']\n\npb = PushBullet(cred.pushbullet_api_key)\n\ndef send(title, data, people, data_type = 'text'):\n\tif people == 'all':\n\t\tpersons\t= all_people\n\telse:\n\t\tpersons = people.split(',')\n\tfor person in persons:\n\t\tentity = get_contact(person)\n\t\tif entity:\n\t\t\tif data_type == 'url':\n\t\t\t\tsuccess, push = entity.push_link(title, data)\n\t\t\telif data_type == 'address':\n\t\t\t\tsuccess, push = entity.push_address(title, data)\n\t\t\telse:\n\t\t\t\tsuccess, push = entity.push_note(title, data)\n\t\telse:\n\t\t\traise Exception(\"Unknown contact: \" + person)\n\t\t\ndef get_device(name):\n\tfor device in get_devices():\n\t\t#print device.nickname\n\t\tif device.nickname.lower() == name.lower():\n\t\t\treturn device\n\traise Exception(\"Couldn't find device called: \" + name)\n\treturn None\n\ndef get_contact(name):\n\tfor contact in get_contacts():\n\t\t#print device.nickname\n\t\tif contact.name.lower() == name.lower():\n\t\t\treturn contact\n\traise Exception(\"Couldn't find contact called: \" + name)\n\treturn None\n\ndef get_devices():\n\treturn pb.devices\n\ndef get_contacts():\n\treturn pb.contacts\n","sub_path":"server/lib/pushbullet_api.py","file_name":"pushbullet_api.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"409046174","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n# @Time : 2020/8/25 4:16 PM\n# @Author: zhangzhihui.wisdom\n# @File:secondarySearch.py\nimport sys\n\nif __name__ == '__main__':\n print('search')\n # the first way:\n # numbers = []\n # lines = []\n # end = 'EOF'\n # print(\"please input multiline data (input end od file to end)\")\n # for line in iter(input, end):\n # lines.append(line)\n #\n # print(lines)\n # the second way\n strList = []\n for number in sys.stdin:\n # default split symbols are \\n \\t and space\n tempStr = number.split()\n strList.extend(tempStr)\n # convert a string type array to int\n strList = list(map(int, strList))\n print(strList)\n strList.sort()\n print(strList)\n print(len(strList))\n index = len(strList) // 2\n print(index)\n target = 9\n flag = False\n left = 0\n right = len(strList)\n while left <= right:\n mid = left + (right - left) >> 1\n if target == strList[mid]:\n flag = True\n break\n elif target < strList[mid]:\n mid -= 1\n else:\n mid += 1\n if flag:\n print(mid)\n else:\n print(len(strList) + 1)\n","sub_path":"python3/secondarySearch.py","file_name":"secondarySearch.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"223087525","text":"\"\"\"\r\nScott Nerlino code challenge submission for EITC.\r\nSee updated README.md for additional information.\r\n\r\nWhile looking for additional tests cases, I believe I found your source!!!\r\nhtttp://slocums.homestead.com/gamescore.html\r\n\"\"\"\r\n\r\nimport collections\r\nimport sys\r\n\r\n__author__ = 'Scott Nerlino'\r\n\r\n\r\ndef score_game(roll_list):\r\n \"\"\"\r\n Determines the final score for an American Bowling game rolls given by\r\n roll_list. After testing several solutions, including a simple list\r\n and a generator, the queue code was easiest to follow.\r\n\r\n :param roll_list: A list of sequential values representing rolls.\r\n Values are 1-9 for number of pins knocked down,\r\n \"-\" for zero pins, \"/\" for a spare,\r\n and \"X\" for a strike.\r\n\r\n :return: An int score in range [0, 300]\r\n \"\"\"\r\n roll_queue = __configure_rolls(roll_list)\r\n game_score = 0\r\n for _ in range(0, 10):\r\n curr_roll = roll_queue.popleft()\r\n if curr_roll == \"X\":\r\n # Use case Two Strikes followed by a roll\r\n if roll_queue[0] == \"X\":\r\n game_score += 20 + (10\r\n if roll_queue[1] == \"X\"\r\n else int(roll_queue[1]))\r\n # Use case One Strike followed by an open frame or a spare\r\n else:\r\n game_score += 10 + (10\r\n if roll_queue[1] == '/'\r\n else\r\n int(roll_queue[0]) + int(roll_queue[1]))\r\n else:\r\n next_roll = roll_queue.popleft()\r\n # Use case, spare in current frame\r\n if next_roll == \"/\":\r\n game_score += 10 + (10\r\n if roll_queue[0] == \"X\"\r\n else int(roll_queue[0]))\r\n # Use case, open frame\r\n else:\r\n game_score += int(curr_roll) + int(next_roll)\r\n return game_score\r\n\r\n\r\ndef __configure_rolls(rolls_string):\r\n \"\"\"\r\n Converts the roll_list to a deque and removes \"-\" characters and replaces\r\n them with 0s for scoring.\r\n\r\n :param rolls_string: A string of sequential values representing rolls.\r\n Values are 1-9 for number of pins knocked\r\n down, \"-\" for zero pins, \"/\" for a spare,\r\n and \"X\" for a strike.\r\n\r\n :return: a collections.deque of the roll_list with \"-\"s replaced with 0s\r\n \"\"\"\r\n return collections.deque(rolls_string.replace(\"-\", \"0\"))\r\n\r\n\r\ndef print_usage():\r\n \"\"\"\r\n Prints the usage if called as a Main.\r\n\r\n :return: None\r\n \"\"\"\r\n print(\"usage: python bowling_game [-f file_path | rolls] \")\r\n print(\" -f Reads the file given in file_path and scores each line\"\r\n \" with a \\\\n character terminating the game.\")\r\n print(\" -h Prints this usage information.\")\r\n print(\" rolls - a string of rolls to produce a game score.\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n if len(sys.argv) == 3:\r\n if sys.argv[1].lower() == \"-f\":\r\n try:\r\n path = sys.argv[2]\r\n with open(path, 'r') as f:\r\n for rolls in f.readlines():\r\n rolls = rolls.strip()\r\n score = score_game(rolls)\r\n print(f\"Your game:\\t{rolls}\\nYou scored:\\t{score}\\n\")\r\n except FileNotFoundError:\r\n print(f\"The path you provided {path} was not found.\")\r\n if sys.argv[1].lower() == \"-h\":\r\n print_usage()\r\n elif len(sys.argv) == 2:\r\n rolls = sys.argv[1]\r\n score = score_game(rolls)\r\n print(f\"Your game:\\t{rolls}\\nYou scored:\\t{score}\")\r\n else:\r\n print_usage()\r\n","sub_path":"src/bowling_game.py","file_name":"bowling_game.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"250528735","text":"# It Works!\nfrom dwave.system.samplers import DWaveSampler\nfrom dwave.system.composites import EmbeddingComposite\n\nDWAVE_SAPI_URL = 'https://cloud.dwavesys.com/sapi'\nDWAVE_TOKEN = 'DEV-7c86da7d5e80b59ef47d1a76f9a99a4a924654bf'\nDWAVE_SOLVER = 'DW_2000Q_2_1'\n\nlinear = {('me', 'me'): -1, ('you', 'you'): -1, ('them', 'them'): -1}\nquadratic = {('me', 'you'): 2, ('me', 'you'): 2, ('me', 'you'): 2}\nQ = dict(linear)\nQ.update(quadratic)\nresponse = EmbeddingComposite(DWaveSampler()).sample_qubo(Q, num_reads=10000)\nfor sample in response.data():\n print(sample)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"370191747","text":"import nltk\n\n\ndef splitWords(fileName):\n \"\"\"\n\n :param fileName:\n :return: a set that contains different words\n \"\"\"\n\n words = set()\n\n # word rule\n patt = \"[A-Za-z]\\w+\"\n\n with open(fileName, \"r\") as fileObj:\n for paragraph in fileObj:\n temp = nltk.RegexpTokenizer(patt).tokenize(paragraph)\n words.update(temp)\n return words","sub_path":"split_word.py","file_name":"split_word.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"543996873","text":"import inspect\nimport six\nfrom collections import OrderedDict\n\nfrom graphql.core.type import (\n GraphQLObjectType,\n GraphQLInterfaceType\n)\n\nfrom graphene import signals\nfrom graphene.core.options import Options\nfrom graphene.utils import memoize\nfrom graphene.core.schema import register_internal_type\n\n\nclass ObjectTypeMeta(type):\n options_cls = Options\n\n def is_interface(cls, parents):\n return Interface in parents\n\n def is_mutation(cls, parents):\n return Mutation in parents\n\n def __new__(cls, name, bases, attrs):\n super_new = super(ObjectTypeMeta, cls).__new__\n parents = [b for b in bases if isinstance(b, cls)]\n if not parents:\n # If this isn't a subclass of Model, don't do anything special.\n return super_new(cls, name, bases, attrs)\n\n module = attrs.pop('__module__')\n doc = attrs.pop('__doc__', None)\n new_class = super_new(cls, name, bases, {\n '__module__': module,\n '__doc__': doc\n })\n attr_meta = attrs.pop('Meta', None)\n if not attr_meta:\n meta = None\n # meta = getattr(new_class, 'Meta', None)\n else:\n meta = attr_meta\n\n base_meta = getattr(new_class, '_meta', None)\n\n new_class.add_to_class('_meta', new_class.options_cls(meta))\n\n new_class._meta.interface = new_class.is_interface(parents)\n new_class._meta.mutation = new_class.is_mutation(parents)\n\n assert not (new_class._meta.interface and new_class._meta.mutation)\n\n # Add all attributes to the class.\n for obj_name, obj in attrs.items():\n new_class.add_to_class(obj_name, obj)\n new_class.add_extra_fields()\n\n new_fields = new_class._meta.local_fields\n field_names = {f.name: f for f in new_fields}\n\n for base in parents:\n if not hasattr(base, '_meta'):\n # Things without _meta aren't functional models, so they're\n # uninteresting parents.\n continue\n # if base._meta.schema != new_class._meta.schema:\n # raise Exception('The parent schema is not the same')\n\n parent_fields = base._meta.local_fields\n # Check for clashes between locally declared fields and those\n # on the base classes (we cannot handle shadowed fields at the\n # moment).\n for field in parent_fields:\n if field.name in field_names and field.__class__ != field_names[field].__class__:\n raise Exception(\n 'Local field %r in class %r clashes '\n 'with field of similar name from '\n 'base class %r' % (\n field.name, name, base.__name__)\n )\n new_class._meta.parents.append(base)\n if base._meta.interface:\n new_class._meta.interfaces.append(base)\n # new_class._meta.parents.extend(base._meta.parents)\n\n new_class._prepare()\n return new_class\n\n def add_extra_fields(cls):\n pass\n\n def _prepare(cls):\n signals.class_prepared.send(cls)\n\n def add_to_class(cls, name, value):\n # We should call the contribute_to_class method only if it's bound\n if not inspect.isclass(value) and hasattr(value, 'contribute_to_class'):\n value.contribute_to_class(cls, name)\n else:\n setattr(cls, name, value)\n\n\nclass BaseObjectType(object):\n\n def __new__(cls, instance=None, *args, **kwargs):\n if cls._meta.interface:\n raise Exception(\"An interface cannot be initialized\")\n if instance is None:\n return None\n elif type(instance) is cls:\n instance = instance.instance\n return super(BaseObjectType, cls).__new__(cls, *args, **kwargs)\n\n def __init__(self, instance):\n signals.pre_init.send(self.__class__, instance=instance)\n self.instance = instance\n signals.post_init.send(self.__class__, instance=self)\n\n def __getattr__(self, name):\n if self.instance:\n return getattr(self.instance, name)\n\n def get_field(self, field):\n return getattr(self.instance, field, None)\n\n def resolve(self, field_name, args, info):\n custom_resolve_fn = 'resolve_%s' % field_name\n if hasattr(self, custom_resolve_fn):\n resolve_fn = getattr(self, custom_resolve_fn)\n return resolve_fn(args, info)\n return self.get_field(field_name)\n\n @classmethod\n def resolve_type(cls, schema, instance, *_):\n return instance.internal_type(schema)\n\n @classmethod\n @memoize\n @register_internal_type\n def internal_type(cls, schema):\n fields_list = cls._meta.fields\n fields = lambda: OrderedDict([(f.name, f.internal_field(schema))\n for f in fields_list])\n if cls._meta.interface:\n return GraphQLInterfaceType(\n cls._meta.type_name,\n description=cls._meta.description,\n resolve_type=lambda *\n args, **kwargs: cls.resolve_type(schema, *args, **kwargs),\n fields=fields\n )\n return GraphQLObjectType(\n cls._meta.type_name,\n description=cls._meta.description,\n interfaces=[i.internal_type(schema) for i in cls._meta.interfaces],\n fields=fields\n )\n\n\nclass ObjectType(six.with_metaclass(ObjectTypeMeta, BaseObjectType)):\n pass\n\n\nclass Mutation(six.with_metaclass(ObjectTypeMeta, BaseObjectType)):\n pass\n\n\nclass Interface(six.with_metaclass(ObjectTypeMeta, BaseObjectType)):\n pass\n","sub_path":"graphene/core/types.py","file_name":"types.py","file_ext":"py","file_size_in_byte":5730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"600314612","text":"from django import forms\n\nfrom .models import Topic,Entry\n\n\nclass TopicForm(forms.ModelForm):\n class Meta():\n model = Topic\n fields = ['text']\n labels = {'text': ''}\n widgets = {'text': forms.TextInput(attrs={'placeholder': 'topic'})}\n\nclass EntryForm(forms.ModelForm):\n class Meta():\n model = Entry\n fields = ['text']\n labels = {\n 'text': ''\n }\n widgets = {'text': forms.Textarea(attrs={'rows': 5,\n 'cols': 30,'placeholder': 'Be appropriate'}) }\n\n","sub_path":"topics/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"48127623","text":"# Write a Python function that takes a list of words and a character,\n# and counts how many of the words in the list begin with that character\n\ndef count_a(word_list, my_char):\n sum = 0\n for i in word_list:\n print(i)\n if i[0] == my_char:\n sum += 1\n return sum\n\nmy_list = input(\"Enter a list of words: \").split()\nmy_char = input(\"Enter a character to count among first letters: \")\n\nprint(count_a(my_list, my_char))\n","sub_path":"S1/Lecture 8/Exercise 4.py","file_name":"Exercise 4.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"617804972","text":"#!/usr/bin/env python\n\nimport logging\n\nimport alembic.command\nimport alembic.config\nimport uvicorn\n\nfrom settings import settings\n\nlogger = logging.getLogger()\nlogging.basicConfig(level=logging.DEBUG if settings.debug else logging.INFO)\n\n\ndef migrate():\n cfg = alembic.config.Config(\"alembic.ini\")\n alembic.command.upgrade(cfg, \"head\")\n\n\ndef start_server():\n options = {}\n if settings.debug:\n options[\"reload\"] = True\n options[\"log_level\"] = \"debug\"\n options[\"debug\"] = True\n else:\n options[\"log_level\"] = \"info\"\n\n uvicorn.run(\"some_stuff:app\", host=\"0.0.0.0\", **options)\n\n\ndef main():\n migrate()\n start_server()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"118178227","text":"import uuid\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.db.models import Sum\nfrom django.utils.functional import cached_property\nfrom sorl.thumbnail import ImageField\n\nfrom lens.apps.core.models.core import Timestamped\n\n\nclass Topic(Timestamped):\n CITY, HASHTAG, USER = 0, 1, 2\n TYPE_LIST = (\n (HASHTAG, 'Hashtag'),\n (USER, 'User'),\n (CITY, 'City'),\n )\n\n name = models.CharField(max_length=128, unique=True, db_index=True)\n type = models.IntegerField(choices=TYPE_LIST, default=HASHTAG)\n recommended = models.BooleanField(default=False)\n\n # User that 'owns' this topic\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='own_topic', null=True, blank=True)\n\n def __str__(self):\n return \"#{}\".format(self.name)\n\n\ndef image_original_upload(instance, filename):\n ext = filename.split('.')[-1]\n return 'images/original/{0}.{1}'.format(uuid.uuid4(), ext)\n\n\nclass Post(Timestamped):\n IMAGE, VIDEO = 1, 2\n TYPE_LIST = (\n (IMAGE, 'Image'),\n (VIDEO, 'Video'),\n )\n\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts')\n\n # Unused for now\n type = models.IntegerField(choices=TYPE_LIST, default=IMAGE)\n\n title = models.CharField(max_length=128)\n description = models.TextField(max_length=1024, null=True, blank=True)\n\n image = ImageField(upload_to=image_original_upload)\n width = models.IntegerField(blank=True)\n height = models.IntegerField(blank=True)\n\n topics = models.ManyToManyField(Topic, blank=True)\n\n location = models.ForeignKey(Topic, null=True, blank=True, on_delete=models.SET_NULL, related_name='posts')\n\n class Meta:\n ordering = ['-created_at', ]\n\n def save(self, force_insert=False, force_update=False, using=None, update_fields=None):\n if not self.width or not self.height:\n self.width = self.image.width\n self.height = self.image.height\n\n super(Post, self).save(force_insert, force_update, using, update_fields)\n\n @cached_property\n def get_votes(self):\n return PostVote.objects.filter(\n post_id=self.pk\n ).aggregate(\n votes=Sum('type')\n )['votes'] or 0\n\n @cached_property\n def get_comments_length(self):\n return self.comments.all().count()\n\n\nclass PostVote(Timestamped):\n Up, Down = 1, -1\n TYPE_LIST = (\n (Up, 'Up'),\n (Down, 'Down'),\n )\n\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='votes')\n post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='votes')\n\n type = models.IntegerField(choices=TYPE_LIST)\n\n class Meta:\n unique_together = ((\"user\", \"post\"),)\n\n\nclass PostComment(Timestamped):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comments')\n post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')\n\n text = models.TextField(max_length=1024)\n\n\nclass Collection(Timestamped):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='collections')\n name = models.CharField(max_length=64)\n posts = models.ManyToManyField(Post, related_name='collections')\n\n def __str__(self):\n return \"{}\".format(self.name)\n","sub_path":"lens/apps/social/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"535891767","text":"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\n\ndef maybe(repo_rule, name, **kwargs):\n \"\"\"Defines a repository if it does not already exist.\n \"\"\"\n if name not in native.existing_rules():\n repo_rule(name = name, **kwargs)\n\ndef llvmbzlgen_repositories():\n \"\"\"Defines external repositories for llvmbzlgen Bazel rules.\n\n These repositories must be loaded before calling external.bzl%llvmbzlgen_dependencies.\n \"\"\"\n maybe(\n http_archive,\n name = \"io_bazel_rules_go\",\n urls = [\n \"https://storage.googleapis.com/bazel-mirror/github.com/bazelbuild/rules_go/releases/download/0.18.6/rules_go-0.18.6.tar.gz\",\n \"https://github.com/bazelbuild/rules_go/releases/download/0.18.6/rules_go-0.18.6.tar.gz\",\n ],\n sha256 = \"f04d2373bcaf8aa09bccb08a98a57e721306c8f6043a2a0ee610fd6853dcde3d\",\n )\n\n maybe(\n http_archive,\n name = \"bazel_gazelle\",\n urls = [\"https://github.com/bazelbuild/bazel-gazelle/releases/download/0.17.0/bazel-gazelle-0.17.0.tar.gz\"],\n sha256 = \"3c681998538231a2d24d0c07ed5a7658cb72bfb5fd4bf9911157c0e9ac6a2687\",\n )\n","sub_path":"setup.bzl","file_name":"setup.bzl","file_ext":"bzl","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"264279478","text":"\"\"\"\nEmail message and address formatting/parsing functions.\n\"\"\"\nimport copy\nimport email.charset\nimport email.generator\nimport email.policy\nimport email.utils\nimport io\nimport re\nfrom email.message import Message\nfrom typing import List\n\n\n__all__ = (\"flatten_message\", \"parse_address\", \"quote_address\")\n\n\nSPECIALS_REGEX = re.compile(r'[][\\\\()<>@,:;\".]')\nESCAPES_REGEX = re.compile(r'[\\\\\"]')\nUTF8_CHARSET = email.charset.Charset(\"utf-8\")\n\n\ndef parse_address(address: str) -> str:\n \"\"\"\n Parse an email address, falling back to the raw string given.\n \"\"\"\n display_name, parsed_address = email.utils.parseaddr(address)\n\n return parsed_address or address.strip()\n\n\ndef quote_address(address: str) -> str:\n \"\"\"\n Quote a subset of the email addresses defined by RFC 821.\n \"\"\"\n parsed_address = parse_address(address)\n return \"<{}>\".format(parsed_address)\n\n\ndef formataddr(pair):\n \"\"\"\n Copied from the standard library, and modified to handle international (UTF-8)\n email addresses.\n\n The inverse of parseaddr(), this takes a 2-tuple of the form\n (realname, email_address) and returns the string value suitable\n for an RFC 2822 From, To or Cc header.\n If the first element of pair is false, then the second element is\n returned unmodified.\n \"\"\"\n name, address = pair\n if name:\n encoded_name = UTF8_CHARSET.header_encode(name)\n return \"{} <{}>\".format(encoded_name, address)\n else:\n quotes = \"\"\n if SPECIALS_REGEX.search(name):\n quotes = '\"'\n name = ESCAPES_REGEX.sub(r\"\\\\\\g<0>\", name)\n return \"{}{}{} <{}>\".format(quotes, name, quotes, address)\n return address\n\n\ndef flatten_message(\n message: Message, utf8: bool = False, cte_type: str = \"8bit\"\n) -> bytes:\n # Make a local copy so we can delete the bcc headers.\n message_copy = copy.copy(message)\n del message_copy[\"Bcc\"]\n del message_copy[\"Resent-Bcc\"]\n\n if utf8:\n policy = email.policy.SMTPUTF8 # type: email.policy.Policy\n else:\n policy = email.policy.SMTP\n\n if policy.cte_type != cte_type:\n policy = policy.clone(cte_type=cte_type)\n\n with io.BytesIO() as messageio:\n generator = email.generator.BytesGenerator( # type: ignore\n messageio, policy=policy\n )\n generator.flatten(message_copy)\n flat_message = messageio.getvalue()\n\n return flat_message\n\n\ndef extract_sender(message: Message) -> str:\n \"\"\"\n Extract the sender from the message object given.\n \"\"\"\n resent_dates = message.get_all(\"Resent-Date\")\n\n if resent_dates is not None and len(resent_dates) > 1:\n raise ValueError(\"Message has more than one 'Resent-' header block\")\n elif resent_dates:\n sender_header = \"Resent-Sender\"\n from_header = \"Resent-From\"\n else:\n sender_header = \"Sender\"\n from_header = \"From\"\n\n # Prefer the sender field per RFC 2822:3.6.2.\n if sender_header in message:\n sender = message[sender_header]\n else:\n sender = message[from_header]\n\n if sender is None:\n sender = \"\"\n\n return str(sender)\n\n\ndef extract_recipients(message: Message) -> List[str]:\n \"\"\"\n Extract the recipients from the message object given.\n \"\"\"\n recipients = [] # type: List[str]\n\n resent_dates = message.get_all(\"Resent-Date\")\n\n if resent_dates is not None and len(resent_dates) > 1:\n raise ValueError(\"Message has more than one 'Resent-' header block\")\n elif resent_dates:\n recipient_headers = (\"Resent-To\", \"Resent-Cc\", \"Resent-Bcc\")\n else:\n recipient_headers = (\"To\", \"Cc\", \"Bcc\")\n\n for header in recipient_headers:\n for recipient in message.get_all(header, failobj=[]):\n recipients.append(str(recipient))\n\n parsed_recipients = [\n str(formataddr(address)) for address in email.utils.getaddresses(recipients)\n ]\n\n return parsed_recipients\n","sub_path":"src/aiosmtplib/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"10111944","text":"\nimport threading, signal\nfrom . import config\nfrom .webserver import TlawsWebServer\nfrom .logger import TlawsLogger\nfrom .wrapper import JSONWrapper\n\nclass TlawsApplication:\n\n def __init__(self):\n self.not_running = threading.Event()\n print(\"[+] Starting Tlaws\")\n\n # gracefull shutdown signal handler\n signal.signal(signal.SIGTERM, self.shutdown)\n signal.signal(signal.SIGINT, self.shutdown)\n\n # Starting logger\n self.logger = TlawsLogger(self)\n self.logger.start()\n\n # Starting grapher\n self.wrapper = JSONWrapper(self)\n\n # Starting web server\n self.webserver = TlawsWebServer(self)\n self.webserver.start()\n\n def shutdown(self, signum, frame):\n print(\"[-] SIGNAL\", signum,\n \"received, shutting down gracefully\")\n self.not_running.set()\n\n def run(self):\n while not self.not_running.is_set():\n self.not_running.wait(1)\n\n self.webserver.stop()\n self.logger.stop()\n self.logger.join()\n print(\"[-] Tlaws has stopped\")\n","sub_path":"tlaws/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"45274320","text":"from django.urls import path\nfrom .views import *\n\nurlpatterns = [\n #Home para pacientes \n path('inicio/',inicio_view, name='inicio'),\n \n path('mensaje//',mensajes_view, name='mensaje'),\n \n #sección de pacientes\n path('seleccionar_medico/',seleccionar_medico_view, name='seleccionar_medico'),\n path('cambiar_medico//',cambiar_medico_view, name='cambiar_medico'),\n path('solicitar_atencion/', atencion_agregar_view, name='solicitar_atencion'),\n path('historial/',historial_view, name='historial'), #url para ver detalles de las citas del paciente\n\n \n \n \n]","sub_path":"apps/pacientes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"364095047","text":"#imports\nfrom ..data_file_io.data_file_directory import DataFileDirectory\nfrom ..data_file_io.config import RUN_OPT_CONST\nfrom ..utilities.argument_parsing import create_dir, config_path\nfrom ..utilities.logging import Logger\nfrom argparse import ArgumentParser\nimport pathlib, datetime\n\ndef main(args=None) :\n #make the argument parser\n parser = ArgumentParser()\n #positional argument: path to directory to hold reconstructed files\n parser.add_argument('workingdir', type=create_dir, help='Path to the directory to hold reconstructed files')\n #optional arguments\n parser.add_argument('--config', default=RUN_OPT_CONST.DEFAULT_CONFIG_FILE, type=config_path,\n help=f\"\"\"Name of config file in config_files directory, or path to a file in a different location \n (default={RUN_OPT_CONST.DEFAULT_CONFIG_FILE})\"\"\")\n parser.add_argument('--topic_name', default=RUN_OPT_CONST.DEFAULT_TOPIC_NAME,\n help=f'Name of the topic to consume from (default={RUN_OPT_CONST.DEFAULT_TOPIC_NAME})')\n parser.add_argument('--n_threads', default=RUN_OPT_CONST.N_DEFAULT_DOWNLOAD_THREADS, type=int,\n help=f'Maximum number of threads to use (default={RUN_OPT_CONST.N_DEFAULT_DOWNLOAD_THREADS})')\n parser.add_argument('--update_seconds', default=RUN_OPT_CONST.DEFAULT_UPDATE_SECONDS, type=int,\n help=f\"\"\"Number of seconds to wait between printing a '.' to the console to indicate the program is alive \n (default={RUN_OPT_CONST.DEFAULT_UPDATE_SECONDS})\"\"\")\n parser.add_argument('--consumer_group_ID', \n help='ID to use for all consumers in the group (by default a new, unique, ID will be created)')\n args = parser.parse_args(args=args)\n #get the logger\n filename = pathlib.Path(__file__).name.split('.')[0]\n logger = Logger(filename,filepath=pathlib.Path(args.workingdir)/f'{filename}.log')\n #make the DataFileDirectory\n reconstructor_directory = DataFileDirectory(args.workingdir,logger=logger)\n #start the reconstructor running (returns total number of chunks read and total number of files completely reconstructed)\n run_start = datetime.datetime.now()\n logger.info(f'Listening for files to reconstruct in {args.workingdir}')\n n_msgs,complete_filenames = reconstructor_directory.reconstruct(args.config,args.topic_name,\n n_threads=args.n_threads,\n update_secs=args.update_seconds,\n consumer_group_ID=args.consumer_group_ID)\n run_stop = datetime.datetime.now()\n #shut down when that function returns\n logger.info(f'File reconstructor writing to {args.workingdir} shut down')\n msg = f'{n_msgs} total messages were consumed'\n if len(complete_filenames)>0 :\n msg+=f' and the following {len(complete_filenames)} file'\n if len(complete_filenames)==1 :\n msg+=' was'\n else :\n msg+='s were'\n msg+=' successfully reconstructed'\n msg+=f' from {run_start} to {run_stop}'\n for fn in complete_filenames :\n msg+=f'\\n\\t{fn}'\n logger.info(msg)\n\nif __name__=='__main__' :\n main()\n","sub_path":"openmsipython/command_line_scripts/reconstruct_data_files.py","file_name":"reconstruct_data_files.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"500078954","text":"import sys\nimport argparse\nimport numpy as np\nimport tensorflow as tf\nfrom basic_prune import PRUNE, calc_pmi, proximity_loss\n\ndef ranking_loss(model, transition_matrix):\n all_ranks = model.all_rank()\n v1 = tf.sparse_tensor_dense_matmul(sp_a=transition_matrix, b=all_ranks)\n return tf.reduce_mean(tf.square(v1 - all_ranks))\n\ndef full_loss(model, latent_size, source, target, transition_matrix, pmis, lamb):\n p_loss = proximity_loss(model, latent_size, source, target, pmis)\n r_loss = ranking_loss(model, transition_matrix)\n return p_loss + lamb * r_loss\n\ndef constraint_loss(model):\n all_ranks = model.all_rank()\n return tf.square(tf.reduce_sum(all_ranks) - model.instances)\n\ndef full_loss_with_constraints(model, latent_size, source, target, transition_matrix, pmis, lamb):\n f_loss = full_loss(model, latent_size, source, target, transition_matrix, pmis, lamb)\n c_loss = constraint_loss(model)\n return f_loss + 0.001 * c_loss\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description=\"Restructured PRUNE.\")\n\n parser.add_argument('--inputgraph', nargs='?',\n default='sample/graph.edgelist',\n help='Input graph path')\n\n parser.add_argument('--output', nargs='?', default='graph.embeddings',\n help='Output node embeddings of the graph')\n\n parser.add_argument('--dimension', type=int, default=128,\n help='Embedding dimension. Default is 128.')\n\n parser.add_argument('--lamb', type=float, default=0.01,\n help='Parameter lambda in objective. Default is 0.01.')\n\n parser.add_argument('--learning_rate', type=float, default=1e-4,\n help='Learning rate for Adam. Default is 1e-4.')\n\n parser.add_argument('--epoch', type=int, default=50,\n help='Training epochs. Default is 50.')\n\n args = parser.parse_args()\n\n # parameters\n #input_graph = sys.argv[1]\n embedding_size = args.dimension\n hidden_size = 128\n latent_size = 64\n num_epochs = args.epoch\n lamb = args.lamb\n learning_rate = args.learning_rate\n \n graph = np.loadtxt(args.inputgraph).astype(np.int32)\n nodeCount = graph.max() + 1\n M = len(graph[:, 0])\n out_degrees = np.zeros([nodeCount, 1])\n in_degrees = np.zeros([nodeCount, 1])\n for node_i, node_j in graph:\n out_degrees[node_i] += 1\n in_degrees[node_j] += 1\n \n data = []\n rows = []\n cols = []\n for node_i, node_j in graph:\n if (out_degrees[node_j] > 0):\n rows.append(node_i)\n cols.append(node_j)\n data.append(1.0 / float(out_degrees[node_j]))\n data = np.array(data, copy=False)\n rows = np.array(rows, dtype=np.int32, copy=False)\n cols = np.array(cols, dtype=np.int32, copy=False)\n sparse_trans_mat = tf.SparseTensorValue(indices=np.array([rows, cols]).T, values=data, dense_shape=[nodeCount, nodeCount])\n pmis = calc_pmi(graph, in_degrees, out_degrees)\n \n pmi = tf.placeholder(\"float\", [M, 1])\n source = tf.placeholder(tf.int32, [M])\n target = tf.placeholder(tf.int32, [M])\n transition_matrix = tf.sparse_placeholder(tf.float32)\n model = PRUNE(nodeCount, embedding_size, hidden_size, latent_size, \"PRUNE\")\n cost = full_loss_with_constraints(model, latent_size, source, target, transition_matrix, pmi, lamb)\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n init = tf.global_variables_initializer()\n\n with tf.Session() as sess:\n sess.run(init)\n feed_dict = {\n pmi: pmis,\n source: graph[:, 0],\n target: graph[:, 1],\n transition_matrix: sparse_trans_mat\n }\n for i in range(num_epochs):\n print(\"Epoch-->\" + str(i+1) + \" ...\")\n sess.run(optimizer, feed_dict=feed_dict)\n print(sess.run(cost, feed_dict=feed_dict))\n if((i+1) % 10 == 0):\n embs = sess.run(model.E.W)\n filename = \"full_rank_embeddings_epoch\" + str(i+1)\n np.savetxt(filename, embs, delimiter = \",\")\n # final_embeddings = sess.run(model.E.W)\n # np.savetxt(args.output, final_embeddings, delimiter = \",\")","sub_path":"src/PRUNE_re_full_rank_constrained.py","file_name":"PRUNE_re_full_rank_constrained.py","file_ext":"py","file_size_in_byte":4257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"133763498","text":"import xml.etree.ElementTree as ET\n\nbaxter_robot = ET.parse('baxter_robot.urdf')\nbaxter_moveit = ET.parse('baxter_moveit.urdf')\n\nrobot_root = baxter_robot.getroot()\nmoveit_root = baxter_moveit.getroot()\n\nfloat_fields = ['radius',\n'mass',\n'value', \n'ix',\n'ixx',\n'ixy',\n'ixz',\n'iyy',\n'iyz',\n'izz',\n'length']\n\nfor element in robot_root.iter():\n\tfor key,value in element.attrib.iteritems():\n\t\tif key in float_fields:\n\t\t\telement.set(key, str(float(value)))\n\t\telse:\n\t\t\telement.set(key, value.strip())\n\nrobot_links = baxter_robot.findall('link')\nrobot_joints = baxter_robot.findall('joint')\n\nmoveit_links = baxter_moveit.findall('link')\nmoveit_joints = baxter_moveit.findall('joint')\n\nfor m_link in moveit_links:\n\tfound = False\n\tfor r_link in robot_links:\n\t\tif r_link.get('name') == m_link.get('name'):\n\t\t\tfound = True\n\tif not found:\n\t\trobot_root.append(m_link)\n\nfor m_joint in moveit_joints:\n\tfound = False\n\tfor r_joint in robot_joints:\n\t\tif r_joint.get('name') == m_joint.get('name'):\n\t\t\tfound = True\n\tif not found:\n\t\trobot_root.append(m_joint)\n\nbaxter_robot.write('baxter_combined.urdf')","sub_path":"baxter_description/urdf/combine.py","file_name":"combine.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"233447320","text":"import cv2 as cv\n\nimg_roi_y = 30\nimg_roi_x = 200\nimg_roi_height = 350 # [2]设置ROI区域的高度\nimg_roi_width = 350 # [3]设置ROI区域的宽度\ncapture = cv.VideoCapture(0)\nindex = 1\nnum = 150\nwhile True:\n ret, frame = capture.read()\n if ret is True:\n img_roi = frame[img_roi_y:(img_roi_y + img_roi_height), img_roi_x:(img_roi_x + img_roi_width)]\n cv.imshow(\"frame\", img_roi)\n index += 1\n if index % 6 == 0: # 每20帧保存一次图像\n num += 1\n cv.imwrite(\"./data/test/\"\n + \"gesture_5.\"+str(num) + \".jpg\", img_roi)\n c = cv.waitKey(50) # 每50ms判断一下键盘的触发。 0则为无限等待。\n if c == 27: # 在ASCII码中27表示ESC键,ord函数可以将字符转换为ASCII码。\n break\n if index == 300:\n break\n else:\n break\n\ncv.destroyAllWindows()\ncapture.release()\n","sub_path":"gesture识别/gesture-recognition/GetTestImage.py","file_name":"GetTestImage.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"416918613","text":"from django.conf.urls import patterns, include, url\nimport views\n\nurlpatterns = patterns(\n '',\n url(r'^checkout$', views.checkout, name='cashdesk.checkout'),\n url(r'^presalebon$', views.presalebon, name='cashdesk.presalebon'),\n url(r'^autocomplete$', views.autocomplete, name='cashdesk.autocomplete'),\n url(r'^printerconf$', views.printerconf, name='cashdesk.printerconf'),\n url(r'^$', views.index, name='cashdesk.index'),\n url(r'^drawer$', views.drawer, name='cashdesk.drawer'),\n url(r'^service$', views.service, name='cashdesk.service'),\n url(r'^stats$', views.stats, name='cashdesk.stats'),\n)\n","sub_path":"MrmcdCashdesk/cashdesk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"148671790","text":"#Lector Archivos v1\n#Autor Matias Cea\n\nimport csv\nlista=[]\nwith open('Destinos.csv', 'r') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n lista.append([row[0], row[3], row[1], row[2]])\n\n\n#--------------------- Escribir Archivo----------------------\nf = open('Destinos1.csv', 'a')\n\nwith f:\n writer = csv.writer(f)\n for row in lista:\n writer.writerow(row)\n","sub_path":"Desktop/IIC2413-Grupo83-master/Datos/Copia de Lector_Paises.py","file_name":"Copia de Lector_Paises.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"428882364","text":"\"\"\"This code was created to test the sqlite DB creation test. The issue in question is when moving the application around the\ntable manga_list will likely not prexist in the same directory as specified especially after packaging up the application\nto resolve this I will create an exception handler where instead of using an existing sqlite.db file I will have the application\ncreate a *.db file along with the table manga_list and have it store it in the file directory system of the application\"\"\"\nimport sqlite3\nfrom sqlite3 import Error\nimport os.path\n\ntry:\n BASE_DIR = os.path.dirname(os.path.abspath(__file__))\n db_path = os.path.join(BASE_DIR, \"sqlite.db\")\n database = db_path\n conn = sqlite3.connect(database)\n cur = conn.cursor() # create sqlite cursor object allowing sql statements to be executed\n cur.execute(\"SELECT * FROM manga_list\")\nexcept sqlite3.OperationalError as e:\n with conn:\n cur.execute(\"CREATE TABLE manga_list (id INTEGER PRIMARY KEY,name STRING,url STRING,image STRING);\")\n print(e)\n\n \n\n\ncur = conn.cursor() # create sqlite cursor object allowing sql statements to be executed\ncur.execute(\"SELECT * FROM manga_list\")\n# creates list of manga_list table allowing for loop to run and populate the BoxLayout\ndb_list = cur.fetchall()\nprint(db_list)\n","sub_path":"kivy-app/TEST/sqlite/sqlitetest.py","file_name":"sqlitetest.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"5047588","text":"#http://www.codeskulptor.org/#user30_YW5OMEPQEnl45TL.py\n\n#Screen Saver Upgraded\n#import modules\nimport simplegui\n\n#define global variables\nmessage=\"Welcome!\"\nposition =[0,32]\nflag =[0,0]\ncolor=\"White\"\n\n#define time handlers\ndef slider():\n global position, flag\n if (flag[0]==0):\n position[0]+=1\n elif (flag[0]==1):\n position[0]-=1\n if (flag[1]==0):\n position[1]+=1\n elif (flag[1]==1):\n position[1]-=1\n if(position[0]>=255):\n flag[0]=1\n elif(position[0]<=0):\n flag[0]=0\n if(position[1]>=270):\n flag[1]=1\n elif(position[1]<=32):\n flag[1]=0\n\n#define input handlers \ndef input_color(strn):\n global color\n color=strn\n \ndef input_field(strn):\n global message,position_max \n message =strn\n\n#define input handler\ndef display(canvas):\n canvas.draw_text(message, position,35,color)\n\n#create frame\nframe=simplegui.create_frame(\"Screen Saver\",400,300)\n\n#create handlers\nscreen=frame.set_draw_handler(display)\ntext=frame.add_input(\"Message\",input_field,100)\ntext2=frame.add_input(\"Color\",input_color,100)\ntimer=simplegui.create_timer(20, slider)\n\n#start timer and frame\nframe.start()\ntimer.start()\n","sub_path":"ScreenSaver upgraded.py","file_name":"ScreenSaver upgraded.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"339264882","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 ('web', '0019_auto_20150731_1453'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='eventstatistics',\n name='event',\n field=models.ForeignKey(verbose_name='Event', to='web.Events'),\n ),\n ]\n","sub_path":"web/migrations/0020_auto_20150731_1454.py","file_name":"0020_auto_20150731_1454.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"275059661","text":"# -*- coding: utf-8 -*-\nfrom urllib.parse import quote\nimport scrapy\nfrom entry.items import EntryItem\n\nclass BaiduEntrySpider(scrapy.Spider):\n name = 'baiduEntry'\n allowed_domains = ['baidu.com']\n\n\n def __init__(self, category, *args, **kwargs):\n super(BaiduEntrySpider, self).__init__(*args, **kwargs)\n self.start_category = category\n self.start_url = 'http://baike.baidu.com/fenlei/' + quote(category)\n\n def start_requests(self):\n return [scrapy.Request(url=self.start_url, callback=self.parse,\n meta={'category': [self.start_category], 'url': self.start_url})]\n\n def parse(self, response):\n category = response.xpath('//*[@id=\"content-main\"]/div[3]/div[2]/div[1]/div[2]')\n category_titles = category.xpath('./div[@class=\"category-title \"]/a')\n for category_title in category_titles:\n category_url = \"http://baike.baidu.com\" + category_title.xpath('./@href').extract()[0]\n category_name = category_title.xpath('./text()').extract()[0]\n print(category_url, category_name)\n cate = response.meta['category'].copy()\n cate.append(category_name)\n yield scrapy.Request(url=category_url, callback=self.parse,\n meta={'category': cate, 'url': category_url})\n yield scrapy.Request(url=response.meta['url'], callback=self.entryURL_parse, dont_filter=True,\n meta={'url_info': {'index': 1, 'limit': 100, 'offset': 0},\n 'category': response.meta['category']})\n\n def entryURL_parse(self, response):\n entries = response.xpath('//*[@id=\"content-main\"]/div[3]/div[2]/div[1]/div[3]/div[1]/ul/li')\n if len(entries) > 0:\n for entry in entries:\n item = EntryItem()\n item['name'] = entry.xpath('.//div[@class=\"list\"]/a/text()').extract()[0]\n item['url'] = 'http://baike.baidu.com' + entry.xpath('.//div[@class=\"list\"]/a/@href').extract()[0]\n item['category'] = response.meta['category']\n #print(item['name'], item['url'], item['category'])\n yield scrapy.Request(url=item['url'], callback=self.entry_parse, meta={'item': item})\n url_info = response.meta['url_info']\n url_info['index'] = url_info['index'] + 1\n url_info['offset'] = url_info['offset'] + url_info['limit']\n url = response.meta['url'] + '?limit={}&index={}&offset={}#gotoList'.format(url_info['limit'], url_info['index'], url_info['offset'])\n yield scrapy.Request(url, callback=self.entryURL_parse,\n meta={'url_info': url_info, 'category': response.meta['category']})\n\n def entry_parse(self, response):\n main_content = response.xpath('/html/body//div[@class=\"main-content\"]')\n summary = ''.join(main_content.xpath('./div[@class=\"lemma-summary\"]//text()').extract())\n cata = main_content.xpath('./div[@class=\"lemmaWgt-lemmaCatalog\"]//div[@class=\"catalog-list column-3\"]//li')\n catalog = \"\"\n for li in cata:\n level = li.xpath('./@class').extract_first()\n if level == 'level1':\n title = li.xpath('./span[@class=\"text\"]/a/text()').extract_first()\n catalog = catalog + title + '\\n'\n elif level == 'level2':\n title = li.xpath('./span[@class=\"text\"]/a/text()').extract_first()\n catalog = catalog + \" \" + title + '\\n'\n divs = main_content.xpath('./div')\n content = \"\"\n for div in divs:\n cl = div.xpath('./@class').extract()\n if cl == []:\n continue\n else:\n cl = cl[0]\n if cl == \"para-title level-2\" or cl == \"para-title level-3\" or cl == \"para\":\n content = content + ''.join(div.xpath('./*/text()').extract())\n item = response.meta['item']\n item['summary'] = summary\n item['catalog'] = catalog\n item['content'] = content\n yield item\n","sub_path":"entry/spiders/baiduEntry.py","file_name":"baiduEntry.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"287841054","text":"import argparse\n\nimport time\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport loaddata\nimport util\nimport numpy as np\nimport sobel\nfrom models import modules, net, resnet, densenet, senet\nimport os\nfrom pathlib import Path\n\nfrom models_resnet import Resnet18_md, Resnet18Encoder\n\nimport matplotlib.pyplot as plt\n# 2019-03-19\n# Coding TODO\n# 1. program argument full specification (what options to allow) and implementation: 1V\n# 2. write code so that if there is no such model file, grab it from url \n# 3. In training saving + continued training full specification and implementation\nuse_cuda = torch.cuda.is_available()\n\ndef define_test_model():\n\t#archs = {\"Resnet\", \"Densenet\", \"SEnet\", \"Custom\"}\n\tis_resnet = args.arch == \"Resnet\" #True #False #True\n\tis_densenet = args.arch == \"Densenet\" # #False #True #False # False\n\tis_senet = args.arch == \"SEnet\" # True #False #True #False\n\tis_custom = args.arch == \"Custom\"\n\n\tif is_resnet:\n\t\t#original_model = resnet.resnet18(pretrained = pretrain_logical)\n\t\t#Encoder = modules.E_resnet(original_model) \n\t\t#model = net.model(Encoder, num_features=2048, block_channel = [256, 512, 1024, 2048])\n\n\t\tstereoModel = Resnet18Encoder(3) \n\t\tmodel_dict = stereoModel.state_dict()\n\t\tencoder_dict = torch.load('./models/monodepth_resnet18_001.pth',map_location='cpu' )\n\t\tnew_dict = {}\n\t\tfor key in encoder_dict:\n\t\t\t# print(key) \n\t\t\tif key in model_dict:\n\t\t\t\tnew_dict[key] = encoder_dict[key]\n\n\t\tstereoModel.load_state_dict(new_dict )\t\t\n\t\tEncoder = stereoModel\n\t\tmodel = net.model(Encoder, num_features=512, block_channel = [64, 128, 256, 512])\n\t\tprint(\"Loading a model...\")\n\t\tprint(\"/model_epoch_{}.pth\".format(str(args.load_epoch)))\n\t\tmodel = model.cuda().float()\n\t\t#print(stereoModel)\n\t\t#print(model)\n\t\t\n\t\tmodel_dict = torch.load(args.load_dir + \"/original_model_epoch_{}.pth\".format(str(args.load_epoch)) )\n\t\tnew_dict = model_dict\n\t\t#new_dict = {}\n\t\t#for key in model_dict:\n\t\t#\tnew_dict[key[7:]] = model_dict[key]\n\t\tmodel.load_state_dict(new_dict)\n\t\t\n\tif is_densenet:\n\t\t# TODO: no dot bug\n\t\toriginal_model = densenet.densenet161(pretrained=True)\n\t\tEncoder = modules.E_densenet(original_model)\n\t\tmodel = net.model(Encoder, num_features=2208, block_channel = [192, 384, 1056, 2208])\n\n\tif is_senet:\n\t\toriginal_model = senet.senet154(pretrained='imagenet')\n\t\tEncoder = modules.E_senet(original_model)\n\t\tmodel = net.model(Encoder, num_features=2048, block_channel = [256, 512, 1024, 2048])\n\n\treturn model \n\n\ndef define_train_model():\n\t#archs = {\"Resnet\", \"Densenet\", \"SEnet\", \"Custom\"}\n\tis_resnet = args.arch == \"Resnet\" #True #False #True\n\tis_densenet = args.arch == \"Densenet\" # #False #True #False # False\n\tis_senet = args.arch == \"SEnet\" # True #False #True #False\n\tis_custom = args.arch == \"Custom\"\n\n\tuse18 = True # True\n\tif is_resnet:\n\t\tif not use18:\n\t\t\toriginal_model = resnet.resnet18(pretrained = True)\n\t\t\tEncoder = modules.E_resnet(original_model) \n\t\t\tmodel = net.model(Encoder, num_features=512, block_channel = [64, 128, 256, 512])\n\t\telse:\n\t\t\tstereoModel = Resnet18Encoder(3) \n\t\t\tmodel_dict = stereoModel.state_dict()\n\t\t\t# 'pretrained_model/'\n\t\t\tencoder_dict = torch.load('./models/monodepth_resnet18_001.pth',map_location='cpu' )\n\t\t\tnew_dict = {}\n\t\t\tfor key in encoder_dict:\n\t\t\t\tif key in model_dict:\n\t\t\t\t\tnew_dict[key] = encoder_dict[key]\n\n\t\t\tstereoModel.load_state_dict(new_dict )\n\t\t\tEncoder = stereoModel\n\t\t\tmodel = net.model(Encoder, num_features=512, block_channel = [64, 128, 256, 512]) \n\t\t \n\tif is_densenet:\n\t\toriginal_model = densenet.densenet161(pretrained=True)\n\t\tEncoder = modules.E_densenet(original_model)\n\t\tmodel = net.model(Encoder, num_features=2208, block_channel = [192, 384, 1056, 2208])\n\tif is_senet:\n\t\toriginal_model = senet.senet154(pretrained='imagenet')\n\t\tEncoder = modules.E_senet(original_model)\n\t\tmodel = net.model(Encoder, num_features=2048, block_channel = [256, 512, 1024, 2048])\n\n\treturn model\n\ndef edge_detection(depth):\n\tif use_cuda:\n\t\tget_edge = sobel.Sobel().cuda()\n\telse:\n\t\tget_edge = sobel.Sobel()\n\n\tedge_xy = get_edge(depth)\n\tedge_sobel = torch.pow(edge_xy[:, 0, :, :], 2) + \\\n\t\ttorch.pow(edge_xy[:, 1, :, :], 2)\n\tedge_sobel = torch.sqrt(edge_sobel)\n\n\treturn edge_sobel\n\ndef visualize_image(image, b_output, output, depth):\n\timage = image.squeeze().permute(1,2,0)\n\tdepth = depth.squeeze()\n\tb_output = b_output.squeeze()\n\toutput = output.squeeze()\n\terrors = util.evaluateError(output, depth)\n\t\n\ttitles = [\"image\", \"b_prediction\", \"prediction\", \"gt\"]\n\timages = [image, b_output, output, depth]\n\tcols = 1\n\n\tn_images = len(images)\n\tif titles is None: titles = ['Image (%d)' % i for i in range(1,n_images + 1)]\n\tfig = plt.figure()\n\tfor n, (image, title) in enumerate(zip(images, titles)):\n\t\ta = fig.add_subplot(cols, np.ceil(n_images/float(cols)), n + 1)\n\t\t#if image.ndim == 2:\n\t\t#\tplt.gray()\n\t\tplt.imshow(image)\n\t\ta.set_title(title)\n\t#plt.title(str(errors))\n\tprint(str(errors))\n\tfig.set_size_inches(np.array(fig.get_size_inches()) * n_images)\n\tplt.show()\n\t\n\ndef test(thre):\n\tmodel = define_test_model()\n\ttest_loader = loaddata.getTestingData(1)\n\t#test_loader = loaddata.getStyleTestingData(1)\n\t\n\tmodel.eval()\n\n\ttotalNumber = 0\n\n\tAe = 0\n\tPe = 0\n\tRe = 0\n\tFe = 0\n\n\terrorSum = {'MSE': 0, 'RMSE': 0, 'ABS_REL': 0, 'LG10': 0,\n\t\t\t\t'MAE': 0, 'DELTA1': 0, 'DELTA2': 0, 'DELTA3': 0}\n\n\twith torch.no_grad():\n\t\tfor i, sample_batched in enumerate(test_loader):\n\t\t\timage, depth = sample_batched['image'], sample_batched['depth']\n\n\t\t\t# depth = depth.cuda(async=True)\n\n\t\t\tif use_cuda:\n\t\t\t\tdepth = depth.cuda()\n\t\t\t\timage = image.cuda()\n\t\t\telse:\n\t\t\t\tpass\n\t\t\t\t#image = torch.autograd.Variable(image, volatile=True)\n\t\t\t\t#depth = torch.autograd.Variable(depth, volatile=True)\n\t\t\t#print(image.size())\n\t\t\t#print(image[0][3])\n\t\t\timage = image[:,0:3,:,:]#image.squeeze()\n\t\t\t#print(image.size())\n\t\t\tb_output = model(image)\n\t\t\t\n\t\t\t#output = torch.nn.functional.upsample(output, size=[depth.size(2),depth.size(3)], mode='bilinear')\n\t\t\toutput = torch.nn.functional.interpolate(b_output, size=[depth.size(2),depth.size(3)], mode='bilinear', align_corners=False)\n\t\t\t#visualize_image(image, b_output, output, depth)\n\n\t\t\tdepth_edge = edge_detection(depth)\n\t\t\toutput_edge = edge_detection(output)\n\n\t\t\tbatchSize = depth.size(0)\n\t\t\ttotalNumber = totalNumber + batchSize\n\t\t\terrors = util.evaluateError(output, depth)\n\t\t\terrorSum = util.addErrors(errorSum, errors, batchSize)\n\t\t\taverageError = util.averageErrors(errorSum, totalNumber)\n\n\t\t\tedge1_valid = (depth_edge > thre)\n\t\t\tedge2_valid = (output_edge > thre)\n\t\t\t#print(output_edge)\n\t\t\t#exit()\n\n\t\t\tnvalid = np.sum(torch.eq(edge1_valid, edge2_valid).float().data.cpu().numpy())\n\t\t\tA = nvalid / (depth.size(2)*depth.size(3))\n\n\t\t\tnvalid2 = np.sum(((edge1_valid + edge2_valid) ==2).float().data.cpu().numpy())\n\t\t\tP = nvalid2 / (np.sum(edge2_valid.data.cpu().numpy()))\n\t\t\tR = nvalid2 / (np.sum(edge1_valid.data.cpu().numpy()))\n\n\t\t\tF = (2 * P * R) / (P + R)\n\n\t\t\tAe += A\n\t\t\tPe += P\n\t\t\tRe += R\n\t\t\tFe += F\n\t\t\tprint('Epoch: [{0}/{1}]\\t' .format( i, len(test_loader))) \n\t\t\t\n\n\tAv = Ae / totalNumber\n\tPv = Pe / totalNumber\n\tRv = Re / totalNumber\n\tFv = Fe / totalNumber\n\tprint('PV', Pv)\n\tprint('RV', Rv)\n\tprint('FV', Fv)\n\n\taverageError['RMSE'] = np.sqrt(averageError['MSE'])\n\tprint(averageError)\n\n\tif is_resnet:\n\t if pretrain_logical: \n\t\t save_name = 'resnet_pretrained'\n\t else:\n\t\t save_name = 'renet_untrained'\n\telif is_densenet:\n\t if pretrain_logical:\n\t\t save_name = 'densenet_pretrained'\n\t else:\n\t\t save_name = 'densenet_untrained'\n\telse:\n\t if pretrain_logical:\n\t\t save_name = 'senet_pretrained'\n\t else:\n\t\t save_name = 'senet_untrained'\n\n\tdir_path = os.path.dirname(os.path.realpath(__file__))\n\tresult_out_path = Path(dir_path +'/csvs')\n\tif not result_out_path.exists():\n\t\tresult_out_path.mkdir()\n\n\twith open('csvs/'+save_name+'.csv', 'w') as sub:\n\t\tsub.write('RV' + str(Rv) + '\\n')\n\t\tsub.write('FV' + str(Fv) + '\\n')\n\t\tsub.write('RMSE'+ str(averageError['RMSE']) + '\\n')\n\tprint('Done!') \n\treturn\n\ndef train(train_loader, model, optimizer, epoch):\n\tcriterion = nn.L1Loss()\n\tbatch_time = AverageMeter()\n\tlosses = AverageMeter()\n\n\tmodel.train()\n\n\tcos = nn.CosineSimilarity(dim=1, eps=0)\n\tif use_cuda:\n\t\tget_gradient = sobel.Sobel().cuda()\n\telse:\n\t\tget_gradient = sobel.Sobel()#.cuda()\n\n\tend = time.time()\n\tfor i, sample_batched in enumerate(train_loader):\n\t\timage, depth = sample_batched['image'], sample_batched['depth']\n\n\t\t#depth = depth.cuda(async=True)\n\t\tif use_cuda:\n\t\t\tdepth = depth.cuda()\n\t\t\timage = image.cuda()\n\t\telse:\n\t\t\timage = torch.autograd.Variable(image)\n\t\t\tdepth = torch.autograd.Variable(depth)\n\n\t\tones = torch.ones(depth.size(0), 1, depth.size(2),depth.size(3)).float().cuda()\n\t\tones = torch.autograd.Variable(ones)\n\t\toptimizer.zero_grad()\n\n\t\toutput = model(image)\n\t\t#output = torch.nn.functional.upsample(output, size=[depth.size(2),depth.size(3)], mode='bilinear')\n\t\toutput = torch.nn.functional.interpolate(output, size=[depth.size(2),depth.size(3)], mode='bilinear', align_corners=False)\n\n\t\tdepth_grad = get_gradient(depth)\n\t\toutput_grad = get_gradient(output)\n\t\tdepth_grad_dx = depth_grad[:, 0, :, :].contiguous().view_as(depth)\n\t\tdepth_grad_dy = depth_grad[:, 1, :, :].contiguous().view_as(depth)\n\t\toutput_grad_dx = output_grad[:, 0, :, :].contiguous().view_as(depth)\n\t\toutput_grad_dy = output_grad[:, 1, :, :].contiguous().view_as(depth)\n\n\t\tdepth_normal = torch.cat((-depth_grad_dx, -depth_grad_dy, ones), 1)\n\t\toutput_normal = torch.cat((-output_grad_dx, -output_grad_dy, ones), 1)\n\n\t\t# depth_normal = F.normalize(depth_normal, p=2, dim=1)\n\t\t# output_normal = F.normalize(output_normal, p=2, dim=1)\n\n\t\tloss_depth = torch.log(torch.abs(output - depth) + 0.5).mean()\n\t\tloss_dx = torch.log(torch.abs(output_grad_dx - depth_grad_dx) + 0.5).mean()\n\t\tloss_dy = torch.log(torch.abs(output_grad_dy - depth_grad_dy) + 0.5).mean()\n\t\tloss_normal = torch.abs(1 - cos(output_normal, depth_normal)).mean()\n\t\t\n\t\t# TODO: grad_dx, grad_dy being negative: is it ok or is something wrong here?\n\t\t#print(\"losses:\",loss_depth, loss_dx, loss_dy, loss_normal)\n\t\tloss = loss_depth + loss_normal + (loss_dx + loss_dy)\n\n\t\t#losses.update(loss.data[0], image.size(0))\n\t\tlosses.update(loss.data.item(), image.size(0))\n\t\tloss.backward()\n\t\toptimizer.step()\n\n\t\tbatch_time.update(time.time() - end)\n\t\tend = time.time()\n \n\t\tbatchSize = depth.size(0)\n\n\t\tprint('Epoch: [{0}][{1}/{2}]\\t'\n\t\t 'Time {batch_time.val:.3f} ({batch_time.sum:.3f})\\t'\n\t\t 'Loss {loss.val:.4f} ({loss.avg:.4f})'\n\t\t .format(epoch, i, len(train_loader), batch_time=batch_time, loss=losses))\n \n\ndef adjust_learning_rate(optimizer, epoch):\n\tlr = args.lr * (0.3 ** (epoch // 5))\n\tfor param_group in optimizer.param_groups:\n\t\tparam_group['lr'] = lr\n\n\nclass AverageMeter(object):\n\tdef __init__(self):\n\t\tself.reset()\n\n\tdef reset(self):\n\t\tself.val = 0\n\t\tself.avg = 0\n\t\tself.sum = 0\n\t\tself.count = 0\n\n\tdef update(self, val, n=1):\n\t\tself.val = val\n\t\tself.sum += val * n\n\t\tself.count += n\n\t\tself.avg = self.sum / self.count\n\n\ndef save_checkpoint(state, filename='checkpoint.pth.tar'):\n\tfilename = 'resnet_untrained.pth'\n\ttorch.save(state, filename)\n\n\ndef main():\n\tparser = argparse.ArgumentParser(description='PyTorch Depth Estimation')\n\tparser.add_argument('--mode', default=\"test\", type=str, help='number of total epochs to run')\n\n\tparser.add_argument('--premodel', default=\"scratch\", \n\t\t\t\t\t\ttype=str, help='pretrained model options: imagenet, stereo_view, scratch')\n\n\t# conflict with mode argument\n\t# parser.add_argument('--finetune', default=False, \n\t# \t\t\t\t\ttype=bool,\n\t# \t\t\t\t\thelp='pretrained model options: imagenet, stereo_view, scratch')\n\t\n\t# doing this will result in ignoring the premodel argument\n\tparser.add_argument('--model', default=\"None\", #default=\"./models/monodepth_resnet18_001.pth\", \n\t\t\t\t\t\ttype=str, help='filepath of the model')\n\tparser.add_argument('--arch', default=\"Resnet\", #default=\"./models/monodepth_resnet18_001.pth\", \n\t\t\t\t\t\ttype=str, help='choice of architecture')\n\tparser.add_argument('--epochs', default=5, type=int,\n\t\t\t\t\t\thelp='number of total epochs to run')\n\tparser.add_argument('--start-epoch', default=0, type=int,\n\t\t\t\t\t\thelp='manual epoch number (useful on restarts)')\n\tparser.add_argument('--lr', '--learning-rate', default=0.0001, type=float,\n\t\t\t\t\t\thelp='initial learning rate')\n\tparser.add_argument('--momentum', default=0.9, type=float, help='momentum')\n\tparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,\n\t\t\t\t\t\thelp='weight decay (default: 1e-4)')\n\tparser.add_argument('--load_epoch', default=\"4\", #default=\"./models/monodepth_resnet18_001.pth\", \n\t\t\t\t\t\ttype=str, help='choice of epch')\t\n\tparser.add_argument('--load_dir', default=\"./model_output\", #default=\"./models/monodepth_resnet18_001.pth\", \n\t\t\t\t\t\ttype=str, help='choice of output')\t\n\tglobal args\n\targs = parser.parse_args()\n\tmodes = {\"test\", \"train\"}\n\tpremodels = {\"imagenet\", \"stereo_view\", \"scratch\"}\n\tarchs = {\"Resnet\", \"Densenet\", \"SEnet\", \"Custom\"}\n\t\n\tif args.mode not in modes or args.premodel not in premodels or args.arch not in archs:\n\t\tprint(\"invalid arguments!\")\n\t\texit(1)\n\n\tif args.mode == \"test\":\n\t\tthreshold = 0.25\n\t\ttest(threshold)\n\telse:\n\t\tmodel = define_train_model()\n \n\t\tif torch.cuda.device_count() == 8:\n\t\t\tmodel = torch.nn.DataParallel(model, device_ids=[0, 1, 2, 3, 4, 5, 6, 7]).cuda()\n\t\t\tbatch_size = 64\n\t\telif torch.cuda.device_count() == 4:\n\t\t\tmodel = torch.nn.DataParallel(model, device_ids=[0, 1, 2, 3]).cuda()\n\t\t\tbatch_size = 32\n\t\telif torch.cuda.device_count() == 2:\n\t\t\tmodel = torch.nn.DataParallel(model, device_ids=[0, 1]).cuda()\n\t\t\tbatch_size = 8\n\t\telse:\n\t\t\tmodel = model.cuda()\n\t\t\tbatch_size = 4\n\t\t\t#batch_size = 11\n\n\t\tcudnn.benchmark = True\n\t\toptimizer = torch.optim.Adam(model.parameters(), args.lr, weight_decay=args.weight_decay)\n\n\t\ttrain_loader = loaddata.getTrainingData(batch_size)\n\t\t#train_loader = loaddata.getStyleTrainingData(batch_size)\n\t\tdir_path = os.path.dirname(os.path.realpath(__file__))\n\t\tmodel_out_path = dir_path + '/model_output'\n\t\tmodel_out_path = Path(model_out_path)\n\t\tif not model_out_path.exists():\n\t\t\tmodel_out_path.mkdir()\n\t\tfor epoch in range(args.start_epoch, args.epochs):\n\t\t\tadjust_learning_rate(optimizer, epoch)\n\t\t\ttrain(train_loader, model, optimizer, epoch)\n\n\t\t\ttorch.save(model.state_dict(), model_out_path/\"_model_epoch_{}.pth\".format(epoch)) \n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"59606740","text":"import yfinance as yf\nmsft = yf.Ticker(\"MSFT\")\nmsft.info\nimport datetime\n\ntoday = datetime.date.today()\ntomorrow = datetime.date.today() + datetime.timedelta(days=1)\n\ndata = yf.download(\"^SPX ^IXIC ^DJI ^TNX SPY QQQ IWM SOXX\", start=\"2020-01-01\", end=tomorrow)\ndata.to_csv(\"/Users/guoqiong/life/invest/stock/yahoo_data/etf.txt\")\n","sub_path":"src/investment/yahoo_download_data.py","file_name":"yahoo_download_data.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"619690466","text":"import os\nimport string\nimport warnings\n\nimport numpy as np\n\n\nfrom ..grids import RasterField, StructuredField, UnstructuredField\n\nclass Error(Exception):\n pass\n\n\nclass DimensionError(Error):\n def __init__(self, msg):\n self._msg = msg\n\n def __str__(self):\n return self._msg\n\n\nclass BadFileFormatError(Error):\n def __init__(self, fmt):\n self._format = fmt\n\n def __str__(self):\n return self._format\n\n\n\ndef positive_dimensions(shape):\n return shape[shape > 0]\n\n\ndef find_unknown_dimension(shape):\n (unknown_dim, ) = np.where(np.array(shape) < 0)\n if len(unknown_dim) > 1:\n raise DimensionError('more than one unknown dimension')\n try:\n return unknown_dim[0]\n except IndexError:\n return None\n\n\ndef fix_unknown_shape(shape, size):\n \"\"\"\n >>> print fix_unknown_shape((4, 3), 12)\n (4, 3)\n >>> print fix_unknown_shape((4, -1), 12)\n (4, 3)\n \"\"\"\n if len(shape) > 0:\n new_shape = np.array(shape)\n else:\n if size != 0:\n raise DimensionError('total size of new array must be unchanged')\n return (0, )\n\n known_element_count = np.prod(new_shape[new_shape > 0])\n if size % known_element_count != 0:\n raise DimensionError('total size of new array must be unchanged')\n\n unknown_dim = find_unknown_dimension(new_shape)\n if unknown_dim is not None:\n new_shape[unknown_dim] = size / known_element_count\n\n return tuple(new_shape)\n\n\ndef is_structured_port(port, var_name):\n if hasattr(port, 'get_grid_shape'):\n shape = port.get_grid_shape(var_name)\n if shape is None:\n return False\n else:\n return False\n return True\n\n\ndef is_rectilinear_port(port, var_name):\n if is_structured_port(port, var_name) and hasattr(port, 'get_grid_spacing'):\n spacing = port.get_grid_spacing(var_name)\n if spacing is None:\n return False\n else:\n return False\n return True\n\n\ndef port_is_one_point(port, var_name):\n shape = port.get_grid_shape(var_name)\n if len(shape) == 1 and shape[0] == 1:\n return True\n else:\n return False\n\n\ndef _port_shape_as_array(port, var_name):\n return port.get_grid_shape(var_name)\n\n\ndef _port_spacing_as_array(port, var_name):\n if port_is_one_point(port, var_name):\n spacing = np.array([1.])\n else:\n spacing = port.get_grid_spacing(var_name)\n return spacing\n\n\ndef _port_origin_as_array(port, var_name):\n if port_is_one_point(port, var_name):\n origin = np.array([0.])\n else:\n try:\n origin = port.get_grid_origin(var_name)\n except AttributeError:\n origin = port.get_grid_lower_left(var_name)\n warnings.warn('get_grid_lower_left', DeprecationWarning)\n return origin\n\n\ndef _construct_port_as_rectilinear_field(port, var_name, data_array):\n shape = _port_shape_as_array(port, var_name)\n spacing = _port_spacing_as_array(port, var_name)\n origin = _port_origin_as_array(port, var_name)\n\n shape = fix_unknown_shape(shape, data_array.size)\n\n return RasterField(shape, spacing, origin, indexing='ij')\n\n\ndef _construct_port_as_structured_field(port, var_name, data_array):\n shape = _port_shape_as_array(port, var_name)\n shape = fix_unknown_shape(shape, data_array.size)\n\n x = port.get_grid_x(var_name)\n y = port.get_grid_y(var_name)\n\n return StructuredField(x, y, shape)\n\n\ndef _construct_port_as_unstructured_field(port, var_name):\n x = port.get_grid_x(var_name)\n y = port.get_grid_y(var_name)\n c = port.get_grid_connectivity(var_name)\n o = port.get_grid_offset(var_name)\n\n return UnstructuredField(x, y, c, o)\n\n\ndef _construct_port_as_field(port, var_name):\n data_array = port.get_grid_values(var_name)\n if data_array is None:\n raise ValueError(var_name)\n\n if is_rectilinear_port(port, var_name):\n field = _construct_port_as_rectilinear_field(port, var_name,\n data_array)\n elif is_structured_port(port, var_name):\n field = _construct_port_as_structured_field(port, var_name, data_array)\n else:\n field = _construct_port_as_unstructured_field(port, var_name)\n\n field.add_field(var_name, data_array,\n centering=get_data_centering(field, data_array))\n\n return field\n\n\ndef get_data_centering(field, data_array):\n if data_is_centered_on_points(field, data_array):\n centering = 'point'\n elif data_is_centered_on_cells(field, data_array):\n centering = 'zonal'\n else:\n raise RuntimeError('statement should not be reached')\n return centering\n\n\ndef mesh_size_has_changed(field, data):\n return data.size not in [field.get_point_count(), field.get_cell_count()]\n\n\ndef data_is_centered_on_points(field, data):\n return data.size == field.get_point_count()\n\n\ndef data_is_centered_on_cells(field, data):\n return data.size == field.get_cell_count()\n\n\ndef _reconstruct_port_as_field (port, field):\n for var_name in field.keys():\n data_array = port.get_grid_values(var_name)\n\n if mesh_size_has_changed(field, data_array):\n field = _construct_port_as_field(port, var_name)\n else:\n field.add_field(var_name, data_array,\n centering=get_data_centering(field, data_array))\n\n return field\n\n\n_FORMAT_EXTENSION = {\n 'nc': '.nc',\n 'vtk': '.vtu',\n 'bov': '.bov'\n}\n\n\ndef normalize_format_name(fmt):\n if fmt.startswith('.'):\n fmt = fmt[1:]\n return fmt.lower()\n\n\ndef format_to_file_extension(fmt):\n try:\n return _FORMAT_EXTENSION[normalize_format_name(fmt)]\n except KeyError:\n raise BadFileFormatError(normalize_format_name(fmt))\n\n\ndef _file_name_lacks_extension(file_name):\n (_, ext) = os.path.splitext(file_name)\n return len(ext) <= 1\n\n\ndef construct_file_name(var_name, template='${var}', fmt=None, prefix=''):\n file_template = string.Template(template)\n file_name = file_template.safe_substitute(var=var_name)\n\n if _file_name_lacks_extension(file_name):\n file_ext = format_to_file_extension(fmt)\n file_name = file_name + file_ext\n\n return os.path.join(prefix, file_name)\n\n\ndef next_unique_file_name(file_name):\n (base, ext) = os.path.splitext(file_name)\n count = 0\n while os.path.isfile(file_name):\n file_name = base + '.%d' % count + ext\n count += 1\n return file_name\n","sub_path":"cmt/portprinter/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"345379307","text":"# Данный пример меняет логические уровни на выводе модуля.\n # $ Строки со знаком $ являются необязательными.\nfrom pyiArduinoI2Cexpander import * # Подключаем библиотеку для работы с расширителем выводов.\nfrom time import sleep # \next = pyiArduinoI2Cexpander(0x08) # Объявляем объект ext для работы с функциями модуля pyiArduinoI2Cexpander, указывая адрес модуля на шине I2C.\n # Если объявить объект без указания адреса (pyiArduinoI2Cexpander()), то адрес будет найден автоматически.\next.pinMode(7, OUTPUT, DIGITAL) # $ Конфигурируем вывод 7 на работу в качестве цифрового выхода.\nprint(\"Моргаем светодиодом.\" # \n \" Нажмите ctrl+c для выхода\") #\nwhile True: # \n ext.digitalWrite(7, HIGH) # Устанавливаем высокий логический уровень на выводе 7.\n sleep(.5) # Ждём пол секунды.\n ext.digitalWrite(7, LOW) # Устанавливаем низкий логический уровень на выводе 7.\n sleep(.5) # Ждём пол секунды.\n #\n# ПРИМЕЧАНИЕ:\n# Для проверки работы скетча подключите светодиод к 7 выводу.\n","sub_path":"pyiArduinoI2Cexpander/examples/digitalWrite.py","file_name":"digitalWrite.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"471094292","text":"import pandas as pd\r\nimport sys\r\n\r\n\r\nclass BureauBalance:\r\n\r\n def __init__(self):\r\n print(\"***Processing bureau_balance.csv started - please wait......***\")\r\n try:\r\n self.bureau_balance = pd.read_csv('bureau_balance.csv')\r\n except FileNotFoundError:\r\n print(\"***Please make sure the path name of the data set - balance_bureau.csv***\")\r\n sys.exit(1)\r\n self.Pr_bureau_balance = self.bur_bal()\r\n\r\n def bur_bal(self):\r\n try:\r\n dt = self.bureau_balance\r\n dt.drop(['MONTHS_BALANCE'], axis=1)\r\n dt['STATUS'] = dt['STATUS'].astype(\"str\")\r\n dt['STATUS'] = list(map(lambda x: \"D\" if x.isdigit() else x, dt['STATUS']))\r\n dt = dt.groupby(['SK_ID_BUREAU', 'STATUS'], sort=True).size().reset_index(name='counts')\r\n dt = dt.sort_values('counts').groupby('SK_ID_BUREAU').first()\r\n dt['STATUS'] = list(map(lambda x: 1 if x == \"D\" else (2 if x == \"C\" else 3), dt['STATUS']))\r\n dt = dt.drop('counts', axis=1)\r\n dt.to_csv(\"processed_data_set/Pr_bureau_balance.csv\")\r\n return dt\r\n except Exception as e:\r\n print(e)\r\n sys.exit(1)\r\n\r\n def __str__(self):\r\n return \"***Process Finished***\"\r\n\r\nif __name__ == '__main__':\r\n b_bal = BureauBalance()\r\n Pr_bureau_balance = b_bal.Pr_bureau_balance\r\n print(b_bal)\r\n","sub_path":"Data_Cleaning.py","file_name":"Data_Cleaning.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"109396344","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 19 15:20:06 2019\r\n\r\n@author: baipl\r\n\"\"\"\r\n\r\nnum = 28\r\nans = 1\r\nif num <=1 :\r\n print(False)\r\ni = 2\r\nwhile i*i <= num:\r\n if num % i == 0:\r\n ans += i;\r\n if i*i != num:\r\n ans += num/i\r\n i += 1\r\nif ans == num:\r\n print(True)\r\nelse:\r\n print(False)\r\n","sub_path":"Problem0507_PerfectNumber.py","file_name":"Problem0507_PerfectNumber.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"18804449","text":"from cutil import printVar\nfrom cutil import setCopy\nfrom com.jython.ui.server.guice import ServiceInjector\nfrom cutil import setAddEditMode\n\ndef __create_list(op, var) :\n seq = op.getAllPersons()\n list = []\n \n for s in seq : \n elem = {}\n elem[\"key\"] = s.id\n elem[\"pnumber\"] = s.getPersonNumb()\n elem[\"pname\"] = s.getPersonName()\n list.append(elem)\n \n map={} \n map[\"list\"] = list\n var[\"JLIST_MAP\"] = map\n\n\ndef doaction(action,var):\n printVar(\"dialogres\",action,var)\n op = ServiceInjector.constructPersonOp()\n\n if action == \"before\" :\n __create_list(op,var)\n setAddEditMode(var,\"list\",[\"pname,pnumber\"])\n \n \n if action == \"run1\" :\n var[\"JUP_DIALOG\"] = \"resdialog.xml\"\n var['JAFTERDIALOG_ACTION'] = \"actionres\"\n var[\"JUPDIALOG_START\"] = \"Hello from script\"\n \n if action == \"editlistrowaction\" :\n var[\"JLIST_EDIT_ACTIONOK_list\"] = True\n \n if action == \"selectvar\" :\n var[\"JUP_DIALOG\"] = \"resdialog.xml\"\n var['JAFTERDIALOG_ACTION'] = \"selectrowvalue\"\n \n if action == \"selectrowvalue\" :\n setCopy(var,[\"key\",\"pname\",\"pnumber\"],\"list\")\n var[\"pname\"] = var[\"JUPDIALOG_BUTTON\"]\n var[\"pnumber\"] = var[\"JUPDIALOG_RES\"]\n var[\"key\"] = 999\n \n \n if action == \"actionres\" :\n setCopy(var,[\"buttonres\",\"stringres\"])\n var[\"buttonres\"] = var[\"JUPDIALOG_BUTTON\"]\n var[\"stringres\"] =var[\"JUPDIALOG_RES\"]\n \n# \n# \n# String JBUTTONRES = \"JUPDIALOG_BUTTON\";\n# String JBUTTONDIALOGRES = \"JUPDIALOG_RES\"; \n \ndef resaction(action,var):\n printVar(\"resaction\",action,var)\n if action == \"before\" :\n var[\"start\"] = var[\"JUPDIALOG_START\"]\n var[\"JCOPY_start\"] = True\n \n if action == \"res2\" :\n var[\"JCLOSE_DIALOG\"] = True\n if action == \"res3\" :\n var[\"JCLOSE_DIALOG\"] = \"result res 3\"\n \n ","sub_path":"hotel/sample/resources/resources/packages/testpack/dialogres.py","file_name":"dialogres.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"208975762","text":"import math\r\nimport numpy as np\r\nimport pygame\r\nimport random\r\nimport sys\r\n\r\npygame.init()\r\n\r\ndef create_board():\r\n board = np.zeros((row_count, col_count))\r\n return board\r\n\r\ndef drop_piece(board, row, col, piece):\r\n board[row][col] = piece\r\n\r\ndef is_valid_loc(board, col):\r\n return board[row_count - 1][col] == 0\r\n\r\ndef get_next_open_row(board, col):\r\n for r in range(row_count):\r\n if board[r][col] == 0:\r\n return r\r\n\r\ndef print_board(board):\r\n print(np.flip(board, 0))\r\n\r\ndef win_move(board, piece):\r\n # Check horizontals\r\n for c in range(col_count - 3):\r\n for r in range(row_count):\r\n if (board[r][c] == piece and board[r][c+1] == piece and\r\n board[r][c+2] == piece and board[r][c+3] == piece):\r\n return True\r\n \r\n # Check verticals\r\n for c in range(col_count):\r\n for r in range(row_count - 3):\r\n if (board[r][c] == piece and board[r+1][c] == piece and\r\n board[r+2][c] == piece and board[r+3][c] == piece):\r\n return True\r\n \r\n # Check positive diagonals\r\n for c in range(col_count - 3):\r\n for r in range(row_count - 3):\r\n if (board[r][c] == piece and board[r+1][c+1] == piece and\r\n board[r+2][c+2] == piece and board[r+3][c+3] == piece):\r\n return True\r\n \r\n # Check negative diagonals\r\n for c in range(col_count - 3):\r\n for r in range(3, row_count):\r\n if (board[r][c] == piece and board[r-1][c+1] == piece and\r\n board[r-2][c+2] == piece and board[r-3][c+3] == piece):\r\n return True\r\n\r\ndef draw_board(board):\r\n board = np.flip(board, 0)\r\n for c in range(col_count):\r\n for r in range(row_count):\r\n pygame.draw.rect(screen, blue, (c * square_size, r * square_size + square_size, square_size, square_size))\r\n if board[r][c] == 0:\r\n pygame.draw.circle(screen, black, (int(c * square_size + square_size / 2), int(r * square_size + square_size + square_size / 2)), radius)\r\n elif board[r][c] == player_piece:\r\n pygame.draw.circle(screen, red, (int(c * square_size + square_size / 2), int(r * square_size + square_size + square_size / 2)), radius)\r\n else:\r\n pygame.draw.circle(screen, yellow, (int(c * square_size + square_size / 2), int(r * square_size + square_size + square_size / 2)), radius)\r\n pygame.display.update()\r\n\r\ndef evaluate_window(window, piece):\r\n score = 0\r\n opp_piece = player_piece\r\n if piece == player_piece:\r\n opp_piece = ai_piece\r\n\r\n if window.count(piece) == 4:\r\n score += 100\r\n elif window.count(piece) == 3 and window.count(empty) == 1:\r\n score += 5\r\n elif window.count(piece) == 2 and window.count(empty) == 2:\r\n score += 2\r\n if window.count(opp_piece) == 3 and window.count(empty) == 1:\r\n score -= 4\r\n return score\r\n\r\ndef score_position(board, piece):\r\n score = 0\r\n # Score center column\r\n center_array = [int(i) for i in list(board[:, col_count//2])]\r\n center_count = center_array.count(piece)\r\n score += center_count * 3\r\n\r\n # Score horizontal\r\n for r in range(row_count):\r\n row_array = [int(i) for i in list(board[r, :])]\r\n for c in range(col_count - 3):\r\n window = row_array[c:c+4]\r\n score += evaluate_window(window, piece)\r\n\r\n # Score vertical\r\n for c in range(col_count):\r\n col_array = [int(i) for i in list(board[:, c])]\r\n for r in range(row_count - 3):\r\n window = col_array[r:r+4]\r\n score += evaluate_window(window, piece)\r\n \r\n # Score positive diagonal\r\n for r in range(row_count - 3):\r\n for c in range(col_count - 3):\r\n window = [board[r+i][c+i] for i in range(4)]\r\n score += evaluate_window(window, piece)\r\n\r\n # Score negative diagonal\r\n for r in range(row_count - 3):\r\n for c in range(col_count - 3):\r\n window = [board[r+3-i][c+i] for i in range(4)]\r\n score += evaluate_window(window, piece)\r\n return score\r\n\r\ndef is_terminal_node(board):\r\n return win_move(board, player_piece) or win_move(board, ai_piece) or len(get_valid_locations(board)) == 0\r\n\r\ndef minimax(board, depth, alpha, beta, maximizingPlayer):\r\n valid_locations = get_valid_locations(board)\r\n is_terminal = is_terminal_node(board)\r\n if depth == 0 or is_terminal:\r\n if is_terminal:\r\n if win_move(board, ai_piece):\r\n return (None, 1000000000000)\r\n elif win_move(board, player_piece):\r\n return (None, -1000000000000)\r\n else: # Game is over, no more valid moves\r\n return (None, 0)\r\n else: # Depth is zero\r\n return (None, score_position(board, ai_piece))\r\n if maximizingPlayer:\r\n value = -math.inf\r\n column = random.choice(valid_locations)\r\n for col in valid_locations:\r\n row = get_next_open_row(board, col)\r\n b_copy = board.copy()\r\n drop_piece(b_copy, row, col, ai_piece)\r\n new_score = minimax(b_copy, depth - 1, alpha, beta, False)[1]\r\n if new_score > value:\r\n value = new_score\r\n column = col\r\n alpha = max(alpha, value)\r\n if alpha >= beta:\r\n break\r\n return column, value\r\n\r\n else: # Minimizing player\r\n value = math.inf\r\n column = random.choice(valid_locations)\r\n for col in valid_locations:\r\n row = get_next_open_row(board, col)\r\n b_copy = board.copy()\r\n drop_piece(b_copy, row, col, player_piece)\r\n new_score = minimax(b_copy, depth - 1, alpha, beta, True)[1]\r\n if new_score < value:\r\n value = new_score\r\n column = col\r\n beta = min(beta, value)\r\n if alpha >= beta:\r\n break\r\n return column, value\r\n\r\ndef get_valid_locations(board):\r\n valid_locations = []\r\n for col in range(col_count):\r\n if is_valid_loc(board, col):\r\n valid_locations.append(col)\r\n return valid_locations\r\n\r\ndef pick_best_move(board, piece):\r\n valid_locations = get_valid_locations(board)\r\n best_col = random.choice(valid_locations)\r\n best_score = -10000\r\n for col in valid_locations:\r\n row = get_next_open_row(board, col)\r\n temp_board = board.copy()\r\n drop_piece(temp_board, row, col, piece)\r\n score = score_position(temp_board, piece)\r\n if score > best_score:\r\n best_score = score\r\n best_col = col\r\n return best_col\r\n\r\n# Colors\r\nblack = (0, 0, 0)\r\nblue = (0, 0, 255)\r\nred = (255, 0, 0)\r\nyellow = (255, 255, 0)\r\n\r\n# Screen\r\nrow_count = 6\r\ncol_count = 7\r\nsquare_size = 100\r\nradius = int(square_size / 2 - 5)\r\nwidth = col_count * square_size\r\nheight = (row_count + 1) * square_size\r\nscreen = pygame.display.set_mode((width, height))\r\nboard = create_board()\r\n# print_board(board) # development purpose only\r\ndraw_board(board)\r\npygame.display.update()\r\nmyFont = pygame.font.SysFont(\"monospace\", 75)\r\n\r\n# Main game loop\r\n_player = 0\r\n_ai = 1\r\nempty = 0\r\nplayer_piece = 1\r\nai_piece = 2\r\ngameover = False\r\nturn = random.randint(_player, _ai)\r\nwhile not gameover:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n \r\n # Player 1 as Human\r\n if event.type == pygame.MOUSEMOTION:\r\n pygame.draw.rect(screen, black, (0, 0, width, square_size))\r\n posx = event.pos[0]\r\n pygame.draw.circle(screen, red, (posx, int(square_size / 2)), radius)\r\n pygame.display.update()\r\n\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n pygame.draw.rect(screen, black, (0, 0, width, square_size))\r\n # Ask Player 1 input\r\n if turn == _player:\r\n posx = event.pos[0]\r\n col = int(math.floor(posx / square_size))\r\n if is_valid_loc(board, col):\r\n row = get_next_open_row(board, col)\r\n drop_piece(board, row, col, player_piece)\r\n if win_move(board, player_piece):\r\n label = myFont.render(\"Player 1 wins!\", 1, red)\r\n screen.blit(label, (40, 10))\r\n gameover = True\r\n # print_board(board) # development purpose only\r\n draw_board(board) \r\n turn = (turn + 1) % 2\r\n\r\n # Player 1 as AI\r\n '''\r\n if turn == _player and not gameover:\r\n col = pick_best_move(board, player_piece)\r\n if is_valid_loc(board, col):\r\n pygame.time.wait(500)\r\n row = get_next_open_row(board, col)\r\n drop_piece(board, row, col, player_piece)\r\n if win_move(board, player_piece):\r\n label = myFont.render(\"Player 1 wins!\", 1, red)\r\n screen.blit(label, (40, 10))\r\n gameover = True\r\n print_board(board)\r\n draw_board(board)\r\n turn = (turn + 1) % 2\r\n '''\r\n\r\n # Player 2 as AI\r\n if turn == _ai and not gameover:\r\n col = pick_best_move(board, ai_piece) # weak AI\r\n #col, minimax_score = minimax(board, 5, -math.inf, math.inf, True) # strong AI\r\n\r\n if is_valid_loc(board, col):\r\n row = get_next_open_row(board, col)\r\n drop_piece(board, row, col, ai_piece)\r\n if win_move(board, ai_piece):\r\n label = myFont.render(\"Player 2 wins!\", 1, yellow)\r\n screen.blit(label, (40, 10))\r\n gameover = True\r\n # print_board(board) # development purpose only\r\n draw_board(board)\r\n turn = (turn + 1) % 2\r\n\r\n if gameover:\r\n pygame.time.wait(3000)\r\n","sub_path":"Connect4/Connect4.py","file_name":"Connect4.py","file_ext":"py","file_size_in_byte":9966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"565773128","text":"from Products.Naaya.tests.NaayaTestCase import NaayaTestCase\nfrom Products.Naaya.NyFolder import addNyFolder\nfrom naaya.content.pointer.pointer_item import addNyPointer\n\nclass PageLoadTests(NaayaTestCase):\n def afterSetUp(self):\n portal = self.app.portal\n addNyFolder(portal, 'test_folder')\n addNyPointer(portal.test_folder, id='test_pointer', title='Test pointer')\n\n def beforeTearDown(self):\n self.app.portal.test_folder.manage_delObjects('test_pointer')\n self.app.portal.manage_delObjects('test_folder')\n\n def test_page_load(self):\n \"\"\"\n Try to render some basic pages; if they raise exceptions the test will fail.\n \"\"\"\n test_folder = self.app.portal.test_folder\n test_pointer = self.app.portal.test_folder.test_pointer\n\n test_folder.pointer_add_html()\n test_pointer.index_html()\n test_pointer.edit_html()\n\ndef test_suite():\n from unittest import TestSuite, makeSuite\n suite = TestSuite()\n suite.addTest(makeSuite(PageLoadTests))\n return suite\n","sub_path":"obsolete/old/Naaya-2009_12-editor/naaya/content/pointer/tests/testPageLoad.py","file_name":"testPageLoad.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"452360865","text":"#conding=utf-8\n\nimport pymongo\nfrom 开工工地信息管理 import change\n\n\nclient = pymongo.MongoClient('192.168.1.50', 27017)\ndb = client.mydb\ncollection = db.projectIM\n\nfor a in collection.find():\n print(a['开工信息的地理位置'])\n dd = a['开工信息的地理位置']\n jwd = change.locatebyAdd(dd)\n print(a['_id'])\n print(jwd)\n collection.update({'_id':a['_id']},{'$set':{'经纬度':jwd}})\n\n print(a)\nprint(collection.find_one())","sub_path":"开工工地信息管理/mongoAdd_jw.py","file_name":"mongoAdd_jw.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"337200546","text":"def f_int(question, minimum, maximum):\n while True:\n value = int(input(question))\n if value < minimum or value > maximum:\n print(\"Invalid value! Enter a value between {} and {}\".format(minimum, maximum))\n else:\n return value\n\nx = f_int(\"Enter a value:\", 0, 10)\nprint(x)","sub_path":"cap08/listagem-08-16.py","file_name":"listagem-08-16.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"503714113","text":"from django.shortcuts import render\r\n\r\nfrom rest_framework import status\r\nfrom rest_framework.decorators import api_view\r\nfrom rest_framework.response import Response\r\n\r\nfrom candidate.models import Candidate\r\nfrom api.serializers import CandidateSerializer\r\n\r\n\r\n@api_view(['GET', 'POST'])\r\ndef candidate_list(request):\r\n\r\n if request.method == 'GET':\r\n tasks = Candidate.objects.all()\r\n serializer = CandidateSerializer(tasks, many=True)\r\n return Response(serializer.data)\r\n\r\n elif request.method == 'POST':\r\n serializer = CandidateSerializer(data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data, status=status.HTTP_201_CREATED)\r\n else:\r\n return Response(\r\n serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n\r\n@api_view(['GET', 'PUT', 'DELETE'])\r\ndef candidate_detail(request, pk):\r\n\r\n\r\n try:\r\n task = Candidate.objects.get(pk=pk)\r\n except Candidate.DoesNotExist:\r\n return Response(status=status.HTTP_404_NOT_FOUND_BAD_REQUEST)\r\n\r\n if request.method == 'GET':\r\n serializer = CandidateSerializer(task)\r\n return Response(serializer.data)\r\n\r\n elif request.method == 'PUT':\r\n serializer = CandidateSerializer(task, data=request.data)\r\n if serializer.is_valid():\r\n serializer.save()\r\n return Response(serializer.data)\r\n else:\r\n return Response(\r\n serializer.errors, status=status.HTTP_400_BAD_REQUEST)\r\n\r\n elif request.method == 'DELETE':\r\n task.delete()\r\n return Response(status=status.HTTP_204_NO_CONTENT)\r\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"35001465","text":"from django.conf.urls import url, include\nimport views as api_views\nimport settings\n\nurlpatterns = [\n\turl(r'^$', api_views.api_home, name='api.home'),\n\turl(r'^auth/check/?', api_views.is_authenticated, name='api.is_authenticated'),\n\turl(r'^auth/test/?', api_views.has_auth, name='api.has_auth'),\n\turl(r'^auth/no_guest/?', api_views.no_guest, name='api.no_guest'),\n\turl(r'^auth/me/?', api_views.who, name='api.who'),\n\turl(r'^auth/shiny/?.*$', api_views.shiny_auth, name='api.shiny_auth'),\n\turl(r'^legacy/', include('api.urls_legacy')),\n\turl(r'^v1/', include('api.urls_v1')),\n\turl(r'^', include(settings.API_SERVE_DEFAULT)),\n\turl(r'^.*/?', api_views.handler404, name='api.not_found'),\n]\n","sub_path":"isbio/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"566686869","text":"import hashlib\nimport json\nfrom enum import Enum, IntEnum\nfrom time import time\nfrom typing import Any, Dict, Optional, overload\n\nfrom httpx import URL\n\nfrom hibiapi.utils.cache import disable_cache\nfrom hibiapi.utils.net import catch_network_error\nfrom hibiapi.utils.routing import BaseEndpoint\n\nfrom ..constants import BilibiliConstants\n\n\nclass TimelineType(str, Enum):\n \"\"\"\n 番剧时间线类型\n\n | **数值** | **含义** |\n |---|---|\n | global | 番剧 |\n | cn | 国产动画 |\n \"\"\"\n\n CN = \"cn\"\n GLOBAL = \"global\"\n\n\nclass CommentSortType(IntEnum):\n \"\"\"\n 评论排序类型\n\n | **数值** | **含义** |\n |---|---|\n | 0 | 按时间 |\n | 1 | 按热评 |\n | 2 | 按点赞 |\n \"\"\"\n\n LIKES = 2\n HOT = 1\n TIME = 0\n\n\nclass CommentType(IntEnum):\n \"\"\"\n 评论来源类型\n\n | **数值** | **含义** |\n |---|---|\n | 1 | 视频 |\n | 12 | 文章 |\n | 11 | 含图片的动态 |\n | 17 | 不含图片的动态 |\n | 14 | 音乐 |\n | 19 | 歌单 |\n \"\"\"\n\n VIDEO = 1\n ARTICLE = 12\n DYNAMIC_PICTURE = 11\n DYNAMIC_TEXT = 17\n AUDIO = 14\n AUDIO_LIST = 19\n\n\nclass VideoQualityType(IntEnum):\n \"\"\"\n 视频质量类型\n\n | **数值** | **含义** |\n |---|---|\n | 6 | 240P |\n | 16 | 360P |\n | 32 | 480P |\n | 64 | 720P |\n | 74 | 720P 60FPS |\n | 80 | 1080P |\n | 112 | 1080P+ |\n | 116 | 1080P 60FPS |\n | 120 | 4K |\n \"\"\"\n\n VIDEO_240P = 6\n VIDEO_360P = 16\n VIDEO_480P = 32\n VIDEO_720P = 64\n VIDEO_720P_60FPS = 74\n VIDEO_1080P = 80\n VIDEO_1080P_PLUS = 112\n VIDEO_1080P_60FPS = 116\n VIDEO_4K = 120\n\n\nclass VideoFormatType(IntEnum):\n \"\"\"\n 视频格式类型\n\n | **数值** | **含义** |\n |---|---|\n | 0 | FLV |\n | 2 | MP4 |\n | 16 | DASH |\n \"\"\"\n\n FLV = 0\n MP4 = 2\n DASH = 16\n\n\nclass RankBangumiType(str, Enum):\n \"\"\"\n 番剧排行榜类型\n\n | **数值** | **含义** |\n |---|---|\n | global | 番剧 |\n | cn | 国产动画 |\n \"\"\"\n\n CN = \"cn\"\n GLOBAL = \"global\"\n\n\nclass RankContentType(IntEnum):\n \"\"\"\n 视频排行榜内容类型\n\n | **数值** | **含义** |\n |---|---|\n | 0 | 全站 |\n | 1 | 动画 |\n | 168 | 国创相关 |\n | 3 | 音乐 |\n | 129 | 舞蹈 |\n | 4 | 游戏 |\n | 36 | 科技 |\n | 160 | 生活 |\n | 119 | 鬼畜 |\n | 155 | 时尚 |\n | 165 | 广告 |\n | 5 | 娱乐 |\n | 23 | 电影 |\n | 11 | 电视剧 |\n \"\"\"\n\n FULL_SITE = 0\n DOUGA = 1\n GUOCHUANG = 168\n MUSIC = 3\n DANCE = 129\n GAME = 4\n TECHNOLOGY = 36\n LIFE = 160\n KICHIKU = 119\n FASHION = 155\n INFORMATION = 165\n ENT = 5\n MOVIE = 23\n TV = 11\n\n\nclass RankDurationType(IntEnum):\n \"\"\"\n 排行榜时间段类型\n\n | **数值** | **含义** |\n |---|---|\n | 1 | 日排行 |\n | 3 | 三日排行 |\n | 7 | 周排行 |\n | 30 | 月排行 |\n \"\"\"\n\n DAILY = 1\n THREE_DAY = 3\n WEEKLY = 7\n MONTHLY = 30\n\n\nclass BaseBilibiliEndpoint(BaseEndpoint):\n def _sign(self, base: str, endpoint: str, params: Dict[str, Any]) -> URL:\n params.update(\n {\n **BilibiliConstants.DEFAULT_PARAMS,\n \"access_key\": BilibiliConstants.ACCESS_KEY,\n \"appkey\": BilibiliConstants.APP_KEY,\n \"ts\": int(time()),\n }\n )\n params = {k: params[k] for k in sorted(params.keys())}\n url = self._join(base=base, endpoint=endpoint, params=params)\n params[\"sign\"] = hashlib.md5(url.query + BilibiliConstants.SECRET).hexdigest()\n return URL(url, params=params)\n\n @staticmethod\n def _parse_json(content: str) -> Dict[str, Any]:\n content = content.replace(\"http:\", \"https:\")\n try:\n return json.loads(content)\n except json.JSONDecodeError:\n # NOTE: this is used to parse jsonp response\n right, left = content.find(\"(\"), content.rfind(\")\")\n return json.loads(content[right + 1 : left].strip())\n\n @overload\n async def request(\n self,\n endpoint: str,\n *,\n sign: bool = True,\n params: Optional[Dict[str, Any]] = None,\n ) -> Dict[str, Any]:\n ...\n\n @overload\n async def request(\n self,\n endpoint: str,\n source: str,\n *,\n sign: bool = True,\n params: Optional[Dict[str, Any]] = None,\n ) -> Dict[str, Any]:\n ...\n\n @disable_cache\n @catch_network_error\n async def request(\n self,\n endpoint: str,\n source: Optional[str] = None,\n *,\n sign: bool = True,\n params: Optional[Dict[str, Any]] = None,\n ) -> Dict[str, Any]:\n host = BilibiliConstants.SERVER_HOST[source or \"app\"]\n url = (\n self._join(base=host, endpoint=endpoint, params=params or {})\n if not sign\n else self._sign(base=host, endpoint=endpoint, params=params or {})\n )\n response = await self.client.get(url)\n response.raise_for_status()\n return self._parse_json(response.text)\n\n async def playurl(\n self,\n *,\n aid: int,\n cid: int,\n quality: VideoQualityType = VideoQualityType.VIDEO_480P,\n type: VideoFormatType = VideoFormatType.FLV,\n ):\n return await self.request(\n \"x/player/playurl\",\n \"api\",\n sign=False,\n params={\n \"avid\": aid,\n \"cid\": cid,\n \"qn\": quality,\n \"fnval\": type,\n \"fnver\": 0,\n \"fourk\": 0 if quality >= VideoQualityType.VIDEO_4K else 1,\n },\n )\n\n async def view(self, *, aid: int):\n return await self.request(\n \"x/v2/view\",\n params={\n \"aid\": aid,\n },\n )\n\n async def search(self, *, keyword: str, page: int = 1, pagesize: int = 20):\n return await self.request(\n \"x/v2/search\",\n params={\n \"duration\": 0,\n \"keyword\": keyword,\n \"pn\": page,\n \"ps\": pagesize,\n },\n )\n\n async def search_hot(self, *, limit: int = 50):\n return await self.request(\n \"x/v2/search/hot\",\n params={\n \"limit\": limit,\n },\n )\n\n async def search_suggest(self, *, keyword: str, type: str = \"accurate\"):\n return await self.request(\n \"x/v2/search/suggest\",\n params={\n \"keyword\": keyword,\n \"type\": type,\n },\n )\n\n async def space(self, *, vmid: int, page: int = 1, pagesize: int = 10):\n return await self.request(\n \"x/v2/space\",\n params={\n \"vmid\": vmid,\n \"ps\": pagesize,\n \"pn\": page,\n },\n )\n\n async def space_archive(self, *, vmid: int, page: int = 1, pagesize: int = 10):\n return await self.request(\n \"x/v2/space/archive\",\n params={\n \"vmid\": vmid,\n \"ps\": pagesize,\n \"pn\": page,\n },\n )\n\n async def favorite_video(\n self,\n fid: int,\n vmid: int,\n page: int = 1,\n pagesize: int = 20,\n ):\n return await self.request(\n \"x/v2/fav/video\",\n \"api\",\n params={\n \"fid\": fid,\n \"pn\": page,\n \"ps\": pagesize,\n \"vmid\": vmid,\n \"order\": \"ftime\",\n },\n )\n\n async def event_list(\n self,\n *,\n fid: int,\n vmid: int,\n page: int = 1,\n pagesize: int = 20,\n ): # NOTE: this endpoint is not used\n return await self.request(\n \"event/getlist\",\n \"api\",\n params={\n \"fid\": fid,\n \"pn\": page,\n \"ps\": pagesize,\n \"vmid\": vmid,\n \"order\": \"ftime\",\n },\n )\n\n async def season_info(self, *, season_id: int):\n return await self.request(\n \"api/season_v5\",\n \"bgm\",\n params={\n \"season_id\": season_id,\n },\n )\n\n async def bangumi_source(self, *, episode_id: int):\n return await self.request(\n \"api/get_source\",\n \"bgm\",\n params={\n \"episode_id\": episode_id,\n },\n )\n\n async def season_recommend(self, *, season_id: int):\n return await self.request(\n \"pgc/season/web/related/recommend\",\n \"api\",\n sign=False,\n params={\n \"season_id\": season_id,\n },\n )\n\n async def comments(\n self,\n *,\n type: CommentType,\n oid: int,\n sort: CommentSortType = CommentSortType.TIME,\n page: int = 1,\n pagesize: int = 20,\n ):\n return await self.request(\n \"x/v2/reply\",\n \"api\",\n sign=False,\n params={\n \"type\": type,\n \"oid\": oid,\n \"sort\": sort,\n \"pn\": page,\n \"ps\": pagesize,\n },\n )\n\n async def rank_list_bangumi(\n self,\n *,\n site: RankBangumiType = RankBangumiType.GLOBAL,\n duration: RankDurationType = RankDurationType.THREE_DAY,\n ):\n return await self.request(\n \"jsonp/season_rank_list/{site}/{duration}.ver\",\n \"bgm\",\n sign=False,\n params={\n \"duration\": duration,\n \"site\": site,\n },\n )\n\n async def rank_list(\n self,\n content: RankContentType = RankContentType.FULL_SITE,\n duration: RankDurationType = RankDurationType.THREE_DAY,\n new: bool = True,\n ):\n return await self.request(\n \"index/rank/all-{new_post}{duration}-{content}.json\",\n \"main\",\n sign=False,\n params={\n \"new_post\": \"\" if new else \"0\",\n \"duration\": duration,\n \"content\": content,\n },\n )\n\n async def type_dynamic(self):\n return await self.request(\n \"typedynamic/index\",\n \"api\",\n sign=False,\n params={\n \"type\": \"json\",\n },\n )\n\n async def timeline(self, type: TimelineType = TimelineType.GLOBAL):\n return await self.request(\n \"web_api/timeline_{type}\",\n \"bgm\",\n sign=False,\n params={\n \"type\": type,\n },\n )\n\n async def recommend(self):\n return await self.request(\"index/recommend.json\", \"main\", sign=False)\n\n async def suggest(self, *, keyword: str): # NOTE: this endpoint is not used\n return await self.request(\n \"main/suggest\",\n \"search\",\n sign=False,\n params={\n \"func\": \"suggest\",\n \"suggest_type\": \"accurate\",\n \"sug_type\": \"tag\",\n \"main_ver\": \"v1\",\n \"keyword\": keyword,\n },\n )\n","sub_path":"hibiapi/api/bilibili/api/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":11317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"43797135","text":"import tensorflow as tf\nimport numpy as np\nfrom tensorflow.contrib import slim\n# slim = tf.contrib.slim\n\nfrom .layer_ops import *\n\n\ndef hourglass_2d(x, n, dim, expand=64, self=None):\n dim2 = dim + expand\n x = x + conv2d(conv2d(x, dim), dim)\n if n == 4 and self is not None:\n self.x1 = x\n\n pool1 = slim.max_pool2d(x, [2, 2], padding='SAME')\n if n == 4 and self is not None:\n self.pool1 = pool1\n low1 = conv2d(pool1, dim2)\n if n == 4 and self is not None:\n self.low1 = low1\n if n > 1:\n low2 = hourglass_2d(low1, n - 1, dim2, self=self)\n else:\n low2 = conv2d(low1, dim2)\n\n low3 = conv2d(low2, dim)\n if n==1 and self is not None:\n self.low3=low3\n up2 = upnn2d(low3, x)\n if n==1 and self is not None:\n self.up2=up2\n out = up2 + x\n tf.add_to_collection(\"checkpoints\", out)\n\n return out\n\n\ndef hourglass_3d(x, n, dim, expand=48):\n dim2 = dim + expand\n\n x = x + conv3d(conv3d(x, dim), dim)\n tf.add_to_collection(\"checkpoints\", x)\n\n pool1 = slim.max_pool3d(x, [2, 2, 2], padding='SAME')\n\n low1 = conv3d(pool1, dim2)\n if n > 1:\n low2 = hourglass_3d(low1, n - 1, dim2)\n else:\n low2 = low1 + conv3d(conv3d(low1, dim2), dim2)\n\n low3 = conv3d(low2, dim)\n up2 = upnn3d(low3, x)\n\n out = up2 + x\n tf.add_to_collection(\"checkpoints\", out)\n\n return out\n","sub_path":"deepv2d/modules/networks/hg.py","file_name":"hg.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"72873034","text":"from Luna import tbot\nfrom telethon import *\nfrom pymongo import MongoClient\nfrom Luna import MONGO_DB_URI, CMD_HELP, CMD_FUN\nfrom Luna.events import bot\nimport dateparser\nimport os, asyncio\n\nclient = MongoClient()\nclient = MongoClient(MONGO_DB_URI)\ndb = client[\"missjuliarobot\"]\nalarms = db.alarm\napproved_users = db.approve\n\n\nasync def is_register_admin(chat, user):\n if isinstance(chat, (types.InputPeerChannel, types.InputChannel)):\n return isinstance(\n (\n await tbot(functions.channels.GetParticipantRequest(chat, user))\n ).participant,\n (types.ChannelParticipantAdmin, types.ChannelParticipantCreator),\n )\n if isinstance(chat, types.InputPeerUser):\n return True\n\n\ndef get_reason(id, time, user):\n return alarms.find_one({\"chat\": id, \"time\": time, \"user\": user})\n\n\n@bot(pattern=\"^/setalarm (.*)\")\nasync def _(event):\n if event.fwd_from:\n return \n quew = event.pattern_match.group(1)\n if \"|\" in quew:\n iid, zonee, reasonn = quew.split(\"|\")\n time = iid.strip()\n reason = reasonn.strip()\n zone = zonee.strip()\n if len(time) != 22:\n await event.reply(\"Please enter valid date and time.\")\n return\n ttime = dateparser.parse(\n f\"{time}\", settings={\"TIMEZONE\": f\"{zone}\", \"DATE_ORDER\": \"DMY\"}\n )\n if ttime == None:\n await event.reply(\"Please enter valid date and time.\")\n return\n time = ttime # exchange\n present = dateparser.parse(\n f\"now\", settings={\"TIMEZONE\": f\"{zone}\", \"DATE_ORDER\": \"YMD\"}\n )\n # print(time)\n # print(present)\n if not time > present:\n await event.reply(\"Please enter valid date and time.\")\n return\n if not reason:\n reason = \"No reason given\"\n chats = alarms.find({})\n for c in chats:\n if (\n event.chat_id == c[\"chat\"]\n and time == c[\"time\"]\n and f\"[user](tg://user?id={event.sender_id})\" == c[\"user\"]\n ):\n to_check = get_reason(\n id=event.chat_id,\n time=time,\n user=f\"[user](tg://user?id={event.sender_id})\",\n )\n alarms.update_one(\n {\n \"_id\": to_check[\"_id\"],\n \"chat\": to_check[\"chat\"],\n \"user\": to_check[\"user\"],\n \"time\": to_check[\"time\"],\n \"zone\": to_check[\"zone\"],\n \"reason\": to_check[\"reason\"],\n },\n {\"$set\": {\"reason\": reason, \"zone\": zone}},\n )\n await event.reply(\n \"This alarm is already set.\\nI am updating the reason(and zone) of the alarm with the new reason(and zone).\"\n )\n return\n alarms.insert_one(\n {\n \"chat\": event.chat_id,\n \"user\": f\"[user](tg://user?id={event.sender_id})\",\n \"time\": time,\n \"zone\": zone,\n \"reason\": reason,\n }\n )\n await event.reply(\"Alarm set successfully !\")\n\n\n@tbot.on(events.NewMessage(pattern=None))\nasync def tikclock(event):\n if event.is_private: \n return \n chats = alarms.find({})\n for c in chats:\n # print(c)\n chat = c[\"chat\"]\n user = c[\"user\"]\n time = c[\"time\"]\n zone = c[\"zone\"]\n reason = c[\"reason\"]\n present = dateparser.parse(\n f\"now\", settings={\"TIMEZONE\": f\"{zone}\", \"DATE_ORDER\": \"YMD\"}\n )\n ttime = dateparser.parse(f\"{time}\", settings={\"TIMEZONE\": f\"{zone}\"})\n if present > ttime:\n await tbot.send_message(\n chat,\n f\"**DING DONG**\\n\\n__This is an alarm set by__ {user} __for reason -__ `{reason}`\",\n )\n alarms.delete_one(\n {\n \"chat\": chat,\n \"user\": user,\n \"time\": time,\n \"zone\": zone,\n \"reason\": reason,\n }\n )\n break\n return\n continue\n\n\nfile_help = os.path.basename(__file__)\nfile_help = file_help.replace(\".py\", \"\")\nfile_helpo = file_help.replace(\"_\", \" \")\n\n__help__ = \"\"\"\n - /setalarm <(date) (time)|zone|reason>: sets a alarm/reminder \n\n**Syntax:** `/setalarm 01/01/2000 10:00:00 AM | America/New_York | breakfast`\n\n**NOTE:** \nPlease turn on notifications(PM/Group Chat) otherwise you will not get notification for the alarm !\n\"\"\"\n\nCMD_HELP.update({file_helpo: [file_helpo, __help__]})\n","sub_path":"Luna/modules/Alarm.py","file_name":"Alarm.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"356152149","text":"# -*- coding: utf-8 -*- \nimport logging\n#配置日至登记\nlogging.basicConfig(level=logging.INFO)\n\ndef foo(s):\n\tn = int(s)\n\t# 断言调试\n\t#assert n != 0, 'n is zero!'\n\tlogging.info('n = %d' % n)\n\treturn 10 / n\n\ndef main():\n\tfoo('0')\n\n\n##使用pdb方式调试 python - m pdb err.py .执行命令后进入调试模式\n#输入l可查看代码,n可以单步调试, p加变量名 可查看变量值,q结束调试\n\ns = '0'\nn = int(s)\nprint(10 / n)\n\n\n# 也可以导入pdb模块,使用pdb的set_trace 方法使程序暂停进入调试环境, 然后可以使用p来查看变量值,c继续运行\n\npdb.set_trace()\n\nn = 3\nn = n + 1","sub_path":"advance/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"191761785","text":"import pytest\nfrom unittest.mock import patch, Mock, AsyncMock\nfrom datetime import datetime, timedelta\n\nfrom aggregator.sources import Source\n\n\ndef test_cant_create_source_abstraction():\n with pytest.raises(TypeError) as error:\n Source()\n assert \"Can't instantiate abstract class\" in str(error.value)\n\n\ndef test_abstract_methods_not_inherited():\n class Heir(Source):\n pass\n with pytest.raises(TypeError) as error:\n Heir()\n assert \"Can't instantiate abstract class\" in str(error.value)\n\n\nclass MinimalHeir(Source):\n def __init__(self):\n self.expire_time = timedelta(seconds=30)\n self.last_updated = None\n\n async def load_data(self):\n return 'data'\n\n def prepare_data(self, data):\n return data\n\n\ndef test_minimal_heir():\n MinimalHeir()\n assert issubclass(MinimalHeir, Source)\n\n\ndef test_is_expired():\n heir = MinimalHeir()\n assert heir.is_expired()\n heir.last_updated = datetime.now() - timedelta(minutes=1)\n assert heir.is_expired()\n\n\ndef test_is_not_expired():\n heir = MinimalHeir()\n heir.last_updated = datetime.now() - timedelta(seconds=10)\n assert not heir.is_expired()\n\n\n@pytest.mark.asyncio\n@patch.object(MinimalHeir, 'load_data', AsyncMock())\n@patch.object(MinimalHeir, 'prepare_data', Mock())\nasync def test_update():\n heir = MinimalHeir()\n await heir.update()\n heir.load_data.assert_called_once()\n heir.prepare_data.assert_called_once()\n assert datetime.now() - heir.last_updated < timedelta(seconds=3)\n","sub_path":"tests/test_aggregator/test_source.py","file_name":"test_source.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"62422859","text":"#!/usr/bin/python2.7\n#\n# RequestLine.py\n#\n# Defines a HTTP request line template - used to make modelling kitty templates\n# easier.\n#\n# Written for COMP9447 by Cameron Lonsdale and Clancy Rye.\n\nfrom kitty.model import *\n\nclass RequestLine(Container):\n \"\"\"\n Container to fuzz the Request_Line of an HTTP Request\n ::\n Request-Line = Method SPACE Request-URI SPACE HTTP-Version CRLF\n\n Method = (GET | HEAD | POST | PUT | DELETE | TRACE | CONNECT)\n Space = \" \"\n Request-URI = Many things\n HTTP-Version = HTTP-Version = \"HTTP\" \"/\" 1*DIGIT \".\" 1*DIGIT\n CRLF = \"\\r\\n\"\n \"\"\"\n\n def __init__(self, method, path, HTTP_version=Static(\"HTTP/1.1\"), fuzzable=True, name=None):\n CRLF = Static(\"\\r\\n\")\n SPACE = Static(\" \")\n\n fields = [method, SPACE, path, SPACE, HTTP_version, CRLF]\n\n super(RequestLine, self).__init__(\n name=name, fields=fields, fuzzable=fuzzable)\n","sub_path":"coolcat/templates/RequestLine.py","file_name":"RequestLine.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"224341816","text":"import pandas as pd\nimport numpy as np\nimport preprocessor as p\nfrom sklearn.model_selection import train_test_split\n\nclass ml_preprocessor:\n\n def __init__(self, path=\"ks-projects-201801.csv\", dataframe: pd.DataFrame=None):\n\n if (dataframe.empty):\n preprocessor = p.preprocessor(path)\n self.dataframe = preprocessor.cleanDataset()\n else:\n self.dataframe = dataframe\n\n self.template = self.dataframe\n self.dataframe = self.main(self.dataframe)\n #print(self.dataframe.head())\n\n # prepare the user input in the same way as the training data to use it for prediction\n def preprocessInput(self, data: dict):\n # append the input into dataframe and preprocess it like the model data\n df = self.template.append(data, ignore_index = True)\n df = df.drop(columns=['state','ID', 'name', 'deadline', 'launched', 'pledged', 'backers', 'usd pledged', 'usd_pledged_real', 'percentage_reached_real', 'goal'])\n df = self.createDummies(df)\n\n # cut out the input row and format it to a 2-D numpy array\n df = df.iloc[-1,:]\n array = df.to_numpy()\n result = np.array([array])\n return result\n\n # method to prepate the dataframe for machine learning\n # uses the default csv file, calls preprocessor.py\n def getDataFrame(self) -> pd.DataFrame:\n return self.dataframe\n\n # method to prepate the dataframe for machine learning\n # does not use the default file, a dataframe has to be given as argument\n def preprocessDataFrame(self, dataframe: pd.DataFrame) -> pd.DataFrame:\n df = dataframe\n df = self.main(df)\n return df \n\n # internal method used for dropping and remapping columns, calls the createDummies method\n def main(self, dataframe: pd.DataFrame) -> pd.DataFrame:\n df = dataframe\n\n #drop unnecessary columns\n df = df.drop(columns=['ID', 'name', 'deadline', 'launched', 'pledged', 'backers', 'usd pledged', 'usd_pledged_real', 'percentage_reached_real', 'goal'])\n\n #remap values to 1 and 0\n dict1 = {'successful': 1, 'failed': 0}\n df['state'] = df['state'].map(dict1)\n dict2 = {True : 1, False : 0}\n df['category_difference'] = df['category_difference'].map(dict2)\n df_normalized = self.createDummies(df)\n\n return df_normalized\n\n #internal method used to create dummy columns\n def createDummies(self, dataframe: pd.DataFrame) -> pd.DataFrame:\n df = dataframe\n #create dummy columns\n dummy_main_category = pd.get_dummies(df['main_category'])\n dummy_category = pd.get_dummies(df['category'])\n dummy_currency = pd.get_dummies(df['currency'])\n dummy_country = pd.get_dummies(df['country'])\n\n #drop dummy source columns\n df = df.drop(columns=['main_category', 'category', 'currency', 'country'])\n\n #concat dataframe and dummy columns\n df_normalized = pd.concat([df, dummy_main_category, dummy_category, dummy_currency, dummy_country], axis=1)\n\n return df_normalized\n\n def getSets(self):\n kickstarter_dataset_target = self.dataframe['state'].values\n\n # remove the target values from the dataframe\n df = self.dataframe.drop(['state'], axis=1)\n\n # create array with data\n kickstarter_dataset_data = df.values\n\n # create testing and training sets (25% test)\n X_train, X_test, y_train, y_test = train_test_split(kickstarter_dataset_data,\n kickstarter_dataset_target,\n test_size=0.25,\n random_state=0)\n return X_train, X_test, y_train, y_test","sub_path":"src/ml_preprocessor.py","file_name":"ml_preprocessor.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"81148839","text":"#!/usr/bin/env python2\n#\n# Copyright (c) 2015 by Cisco Systems, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport argparse\nimport shutil\nimport socket\nimport sys\nimport time\nimport os\nimport re\nimport imp\nimport threading\nimport struct\nimport json\nimport zlib\nfrom subprocess import call\n\nINDENT = \" \"\n\n###############################################################################\n# Helper functions\n###############################################################################\n\ndef timestamp_to_string (timestamp):\n \"\"\"\n Convert a timestamp to a string\n \"\"\"\n try:\n string = \"{} ({}ms)\".format(time.ctime(timestamp / 1000), \n timestamp % 1000)\n except Exception as e:\n print(\"ERROR: Failed to decode timestamp {}: {}\".format(timestamp, e))\n string = \"{}\".format(timestamp)\n return string\n\n\ndef bytes_to_string (bytes):\n \"\"\"\n Convert a byte array into a string aa:bb:cc\n \"\"\"\n return \":\".join([\"{:02x}\".format(int(ord(c))) for c in bytes])\n\ndef print_at_indent (string, indent):\n \"\"\"\n Print a string indented by the specified level\n \"\"\"\n print(\"{}{}\".format(INDENT*indent, string))\n\n\ndef parse_schema_from_proto(input_file):\n \"\"\"\n Find the schema path and corresponding message definition in a .proto file\n \"\"\"\n with open(input_file) as f:\n schema_path = None\n msg_name = None\n for line in f.readlines():\n # Look for the first instance of the string \"message \"\n # and \"...schema_path = \"\n if msg_name == None:\n match = re.search(\"^message (\\S+)\", line)\n if match:\n msg_name = match.group(1)\n else:\n match = re.search(\".*schema_path = \\\"(\\S+)\\\"\", line)\n if match:\n schema_path = match.group(1)\n break\n\n return (schema_path,msg_name)\n \n\ndef compile_proto_file(input_files, output_path, include_path):\n \"\"\"\n Compile a .proto file using protoc\n \"\"\"\n command = [\"protoc\",\"--python_out\", output_path, \"-I\", include_path] + input_files.split(',')\n call(command)\n\n###############################################################################\n# GPB Decoding\n###############################################################################\n\ndef print_gpb_compact_msg (field, indent):\n \"\"\"\n Recursively iterate over a compactGPB obejct, displaying all fields at an \n appropriate indent.\n Argument: field\n The object to print.\n Argument: indent\n The indent level to start printing at.\n \"\"\"\n for descriptor in field.DESCRIPTOR.fields:\n value = getattr(field, descriptor.name)\n if descriptor.type == descriptor.TYPE_MESSAGE:\n # \n # If the value is a sub-message then recursively call this function\n # to decode it. If the message is repeated then iterate over each\n # item.\n #\n if descriptor.label == descriptor.LABEL_REPEATED:\n print_at_indent(\"{} ({} items) [\".format(\n descriptor.name, len(value)), \n indent)\n for i, item in enumerate(value):\n print_at_indent(\"{} {} {{\".format(descriptor.name, i),\n indent)\n print_gpb_compact_msg(item, indent+1)\n print_at_indent(\"}\", indent)\n if not args.print_all:\n # Stop after the first item unless all have been\n # requested\n break\n print_at_indent(\"]\", indent)\n else:\n print_at_indent(\"{} {{\".format(descriptor.name), indent)\n print_gpb_compact_msg(value, indent + 1)\n print_at_indent(\"}\", indent)\n elif descriptor.type == descriptor.TYPE_ENUM:\n #\n # For enum types print the enum name\n #\n enum_name = descriptor.enum_type.values[value].name\n print_at_indent(\"{}: {}\".format(descriptor.name, enum_name),\n indent)\n elif descriptor.type == descriptor.TYPE_BYTES:\n print_at_indent(\"{}: {}\".format(descriptor.name,\n bytes_to_string(value)), indent)\n else:\n # \n # For everything else just print the value\n #\n print_at_indent(\"{}: {}\".format(descriptor.name, value), indent)\n\ndef print_gpb_compact_hdr (header):\n \"\"\"\n Print the compact GPB message header\n \"\"\"\n print(\"\"\"\nEncoding:{:#x}\nPolicy Name:{}\nVersion:{}\nIdentifier:{}\nStart Time:{}\nEnd Time:{}\n# Tables: {}\"\"\".format(header.encoding,\n header.policy_name,\n header.version,\n header.identifier,\n timestamp_to_string(header.start_time),\n timestamp_to_string(header.end_time),\n len(header.tables))\n)\n\ndef decode_gpb_compact (message):\n \"\"\"\n Decode and print a GPB compact message\n \"\"\"\n header = telemetry_pb2.TelemetryHeader()\n try:\n header.ParseFromString(message)\n except Exception as e:\n print(\"ERROR decoding header. Not a valid 'TelemetryHeader' message. \"\n \"Full message dump below:\")\n print(bytes_to_string(message))\n return\n\n # Check the encoding value is correct\n ENCODING = 0x87654321\n if header.encoding != ENCODING:\n print(\"Invalid 'encoding' value {:#x} (expected {:#x})\".format(\n header.encoding, ENCODING))\n return\n\n # Print the message header\n print_gpb_compact_hdr(header)\n\n # Loop over the tables within the message, printing either just the first \n # row or all rows depending on the args specified\n\n for entry in header.tables:\n schema_path = entry.policy_path\n print(INDENT + \"Schema Path:{}\".format(schema_path))\n\n warning = \"\"\n if not args.print_all:\n warning = \"(Only first row displayed)\"\n print(INDENT + \"# Rows:{} {}\".format(len(entry.row), warning))\n\n if not schema_path in decoder_dict.keys():\n print(INDENT + \"No decoder available\")\n else:\n for i, row in enumerate(entry.row):\n print(INDENT * 2 + \"Row {}:\".format(i))\n row_msg = decoder_dict[schema_path]()\n try:\n row_msg.ParseFromString(row)\n print_gpb_compact_msg(row_msg, 2)\n print(\"\")\n except Exception as e:\n print(\"ERROR decoding row. Not a valid GPB message. Full \"\n \"message dump below:\")\n print(bytes_to_string(row))\n \n if not args.print_all:\n break\n\ndef print_gpb_kv_field_data (name, data, datatype, time, indent):\n \"\"\"\n Print a single row for a TelemetryField message\n \"\"\"\n if name == \"\":\n name = \"\"\n print_at_indent(\"{}: {} ({}) {}\".format(name, data, datatype, time),\n indent)\n\ndef print_gpb_kv_field (field, indent):\n \"\"\"\n Pretty-print a TelemtryField message\n \"\"\"\n # Decode the timestamp if there is one\n if field.timestamp != 0:\n time = timestamp_to_string(field.timestamp)\n else:\n time = \"\"\n \n # Find the datatype and print it\n datatypes = [\"bytes_value\",\n \"string_value\",\n \"bool_value\",\n \"uint32_value\",\n \"uint64_value\",\n \"sint32_value\",\n \"sint64_value\",\n \"double_value\",\n \"float_value\"]\n for d in datatypes:\n datatype = d[:-6]\n if field.HasField(d):\n if datatype == \"bytes\":\n print_gpb_kv_field_data(field.name,\n bytes_to_string(field.bytes_value),\n datatype, time, indent)\n else:\n print_gpb_kv_field_data(field.name, getattr(field,d), datatype,\n time, indent)\n\n # If 'fields' is used then recursively call this function to decode\n if len(field.fields) > 0:\n print_gpb_kv_field_data(field.name, \n \"fields\",\n \"items {}\".format(len(field.fields)),\n \"{} {{\".format(time), indent)\n\n for f in field.fields:\n print_gpb_kv_field(f, indent+1)\n print_at_indent(\"}\", indent)\n\n\n\ndef print_gpb_kv_hdr (header):\n \"\"\"\n Print the key-value GPB message header\n \"\"\"\n print(\"\"\"\nCollection ID: {}\nBase Path: {}\nSubscription ID: {}\nModel Version: {}\"\"\".format(header.collection_id,\n header.base_path,\n header.subscription_identifier,\n header.model_version))\n # start and end time are not always present\n if header.collection_start_time > 0:\n print(\"Start Time: {}\".format(timestamp_to_string(header.collection_start_time)))\n print(\"Msg Timestamp: {}\".format(timestamp_to_string(header.msg_timestamp)))\n if header.collection_end_time > 0:\n print(\"End Time: {}\".format(timestamp_to_string(header.collection_end_time)))\n print(\"Fields: {}\".format(len(header.fields))) \n\n \n\ndef decode_gpb_kv (message):\n \"\"\"\n Decode and print a GPB key-value message\n \"\"\"\n header = telemetry_kv_pb2.Telemetry()\n try:\n header.ParseFromString(message)\n except Exception as e:\n print(\"ERROR decoding header. Not a valid 'Telemetry' message. Full \"\n \"message dump below:\")\n print(bytes_to_string(message))\n return\n\n # Print the message header\n print_gpb_kv_hdr(header)\n\n # Loop over the tables within the message, printing either just the first \n # row or all rows depending on the args specified\n if args.print_all:\n for entry in header.fields:\n print_gpb_kv_field(entry, 2)\n elif len(header.fields) > 0 and not args.brief:\n print(\" Displaying first entry only\")\n print_gpb_kv_field(header.fields[0], 1)\n \n###############################################################################\n# JSON Decoder\n###############################################################################\n\ndef print_json_hdr (message):\n \"\"\"\n Print the values in the top level JSON object\n \"\"\"\n # Print everything except the Data, displaying timestamps in date format\n print(\"\")\n for key, value in message.items():\n if (key == \"CollectionStartTime\" or key == \"CollectionEndTime\" or\n key == \"Start Time\" or key == \"End Time\"):\n print(\"{}: {}\".format(key, timestamp_to_string(value)))\n elif key != \"Data\":\n print(\"{}: {}\".format(key, value))\n\n\ndef print_json_data(obj, indent):\n if type(obj) == dict:\n for key in list(obj.keys()):\n child = obj[key]\n # If the child object is a list or dictionary then indent using\n # braces. If the child is a leaf then just print on a single line.\n if type(child) == dict:\n print_at_indent(\"{} {{\".format(key), indent)\n print_json_data(obj[key], indent + 1)\n print_at_indent(\"}\", indent)\n elif type(child) == list:\n if not args.print_all:\n warning = \" - displaying first entry only\"\n else:\n warning = \"\"\n print_at_indent(\"{} ({} items{}) [\".format(key, len(child),\n warning), \n indent)\n print_json_data(obj[key], indent + 1)\n print_at_indent(\"]\", indent)\n elif key == \"CollectionTime\":\n # Pretty-print collection timestamp\n print_at_indent(\"{}: {}\".format(key, timestamp_to_string(child)), \n indent)\n else:\n print_at_indent(\"{}: {}\".format(key, str(child)), indent)\n elif type(obj) == list:\n for i, item in enumerate(obj):\n print_at_indent(\"[{}]\".format(i), indent)\n print_json_data(item, indent + 1)\n if not args.print_all:\n # Stop after first item\n break\n else:\n print_at_indent(\"{}\".format(str(obj)), indent)\n\n\ndef decode_json (message):\n \"\"\"\n Pretty-print a JSON message\n \"\"\"\n # Turn the binary data into ascii and convert it to JSON\n json_msg = None\n try:\n json_msg = json.loads(message.decode('ascii'))\n except Exception as e:\n print(\"ERROR: Failed to convert message to JSON: {}\".format(e))\n\n if json_msg != None:\n print_json_hdr(json_msg)\n if not args.brief:\n print(\"Data: {\")\n print_json_data(json_msg[\"Data\"], 1)\n\n##############################################################################\n# JSON v1 (Pre XR 6.1.0)\n##############################################################################\n\ndef unpack_v1_message(data):\n\n while len(data) > 0:\n _type = unpack_int(data)\n data = data[4:]\n\n if _type == 1:\n data = data[4:]\n yield 1, None\n elif _type == 2:\n msg_length = unpack_int(data)\n data = data[4:]\n msg = data[:msg_length]\n data = data[msg_length:]\n yield 2, msg\n\ndef get_v1_message(length, c):\n global v1_deco\n\n data = b\"\"\n while len(data) < length:\n data += c.recv(length - len(data))\n\n tlvs = []\n for x in unpack_v1_message(data):\n tlvs.append(x)\n\n #find the data\n for x in tlvs:\n if x[0] == 1:\n print(\" Reset Compressor TLV\")\n v1_deco = zlib.decompressobj()\n if x[0] == 2:\n print(\" Mesage TLV\")\n c_msg = x[1]\n j_msg_b = v1_deco.decompress(c_msg)\n decode_json(j_msg_b)\n\n\n###############################################################################\n# Event handling\n############################################################################### \n\n# Should use enum.Enum but not available in python2.7.1 on EnXR\nclass TCPMsgType():\n RESET_COMPRESSOR = 1\n JSON = 2\n GPB_COMPACT = 3\n GPB_KEY_VALUE = 4\n\n @classmethod\n def to_string (self, value):\n if value == 1:\n return \"RESET_COMPRESSOR (1)\"\n elif value == 2:\n return \"JSON (2)\"\n elif value == 3:\n return \"GPB_COMPACT (3)\"\n elif value == 4:\n return \"GPB_KEY_VALUE (4)\"\n else:\n raise ValueError(\"{} is not a valid TCP message type\".format(value))\n\n\nTCP_FLAG_ZLIB_COMPRESSION = 0x1\n\ndef tcp_flags_to_string (flags):\n strings = []\n if flags & TCP_FLAG_ZLIB_COMPRESSION != 0:\n strings.append(\"ZLIB compression\")\n if len(strings) == 0:\n return \"None\"\n else:\n return \"|\".join(strings)\n\ndef unpack_int(raw_data):\n return struct.unpack_from(\">I\", raw_data, 0)[0]\n\n\ndef get_message(conn, deco):\n \"\"\"\n Handle a receved TCP message\n Argument: conn\n TCP connection\n Argument: deco\n ZLIB decompression object\n Return: updated decompression object in the case where compression was\n reset\n \"\"\"\n print(\"Getting TCP message\")\n # v1 message header (from XR6.0) consists of just a 4-byte length\n # v2 message header (from XR6.1 onwards) consists of 3 4-byte fields:\n # Type,Flags,Length\n # If the first 4 bytes read is <=4 then it is too small to be a \n # valid length. Assume it is v2 instead\n # \n t = conn.recv(4)\n msg_type = unpack_int(t)\n if msg_type > 4:\n # V1 message - compressed JSON\n flags = TCP_FLAG_ZLIB_COMPRESSION\n msg_type_str = \"JSONv1 (COMPRESSED)\"\n length = msg_type\n msg_type = TCPMsgType.JSON\n print(\" Message Type: {}\".format(msg_type_str))\n return get_v1_message(length, conn)\n else:\n # V2 message\n try:\n msg_type_str = TCPMsgType.to_string(msg_type)\n print(\" Message Type: {})\".format(msg_type_str))\n except:\n print(\" Invalid Message type: {}\".format(msg_type))\n \n t = conn.recv(4)\n flags = unpack_int(t)\n print(\" Flags: {}\".format(tcp_flags_to_string(flags)))\n t = conn.recv(4)\n length = unpack_int(t)\n print(\" Length: {}\".format(length))\n \n # Read all the bytes of the message according to the length in the header \n data = b\"\"\n while len(data) < length:\n data += conn.recv(length - len(data))\n\n # Decompress the message if necessary. Otherwise use as-is\n if flags & TCP_FLAG_ZLIB_COMPRESSION != 0:\n try:\n print(\"Decompressing message\")\n msg = deco.decompress(data)\n except Exception as e:\n print(\"ERROR: failed to decompress message: {}\".format(e))\n msg = None\n else:\n msg = data\n\n # Decode the data according to the message type in the header\n print(\"Decoding message\")\n try:\n if msg_type == TCPMsgType.GPB_COMPACT:\n decode_gpb_compact(msg)\n elif msg_type == TCPMsgType.GPB_KEY_VALUE:\n decode_gpb_kv(msg)\n elif msg_type == TCPMsgType.JSON:\n decode_json(msg)\n elif msg_type == TCPMsgType.RESET_COMPRESSOR:\n deco = zlib.decompressobj()\n except Exception as e:\n print(\"ERROR: failed to decode TCP message: {}\".format(e))\n\n return deco\n\n\ndef tcp_loop ():\n \"\"\"\n Event Loop. Wait for TCP messages and pretty-print them\n \"\"\"\n while True:\n print(\"Waiting for TCP connection\")\n conn, addr = tcp_sock.accept()\n deco = zlib.decompressobj()\n print(\"Got TCP connection\")\n try:\n while True:\n deco = get_message(conn, deco)\n except Exception as e:\n print(\"ERROR: Failed to get TCP message. Attempting to reopen connection: {}\".format(e))\n\n\ndef udp_loop():\n \"\"\"\n Event loop. Wait for messages and then pretty-print them\n \"\"\"\n while True:\n print(\"Waiting for UDP message\")\n raw_message, address = udp_sock.recvfrom(2**16)\n # All UDP packets contain compact GPB messages\n decode_gpb_compact(raw_message)\n\n###############################################################################\n# Main\n###############################################################################\n\n# \n# Set up argument parsing\n#\nparser = argparse.ArgumentParser(description=\"\")\n\nparser.add_argument(\"--ip-address\",\n required=True,\n type=str)\n\nparser.add_argument(\"--port\",\n required=True,\n type=int)\n\nparser.add_argument(\"--protos\",\n required=False,\n type=str,\n nargs = '*',\n default=[],\n help = \"List of .proto files to be received in messages\")\n\nparser.add_argument(\"--print-all\",\n required=False,\n action='store_true',\n help = \"Display data for all items instead of just the first\")\n\nparser.add_argument(\"--brief\",\n required=False,\n action='store_true',\n help = \"Only display message headers, no data\")\n\nparser.add_argument(\"--tmp-dir\",\n required=False,\n type=str,\n default=\"/tmp/telem_gpb/\")\n\nparser.add_argument(\"--include-path\",\n required=False,\n type=str,\n default=\":\".join([\".\",\n \"/sw/packages/protoc/current/google/include/\",\n ]))\n\n#\n# Parse all arguments and bind to the specified IP address and port\nargs = parser.parse_args(sys.argv[1:])\n\n\n#\n# Bind to two sockets to handle either UDP or TCP data\nudp_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nudp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nudp_sock.bind((args.ip_address, args.port))\n\n\ntcp_sock = socket.socket()\ntcp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\ntcp_sock.bind((args.ip_address, args.port))\ntcp_sock.listen(1)\n\n\n#\n# Make sure the temp directory exists\n#\ntry:\n os.mkdir(args.tmp_dir)\nexcept OSError:\n pass\n\nsys.path.append(args.tmp_dir)\nsys.path.append(args.include_path)\n# For 'six' which is required by protobuf\n#sys.path.append(\"/auto/usrcisco-linux-rhel5.0-x86-64/packages/python/python-2.7.8/lib/python2.7/site-packages\")\n\n#\n# Compile the main telemetry proto files if they don't already exist.\n#\ntry:\n import telemetry_pb2\nexcept:\n compile_proto_file(\"telemetry.proto\", args.tmp_dir, args.include_path)\n compile_proto_file(\"descriptor.proto\", args.tmp_dir, args.include_path)\n compile_proto_file(\"cisco.proto\", args.tmp_dir, args.include_path)\n import telemetry_pb2\n\n# Key-value protobuf cannot be compiled using the old version of protoc \n# available so use a local pre-compiled version.\nimport telemetry_kv_pb2\n\n\n#\n# Create a dictionary for storing mapping from schema paths to\n# decoder objects\n#\ndecoder_dict = {}\n\n#\n# For each proto file\n# - attempt to compile it (this way we always use the latest .proto file)\n# - if that fails then try using an existing file (this means it is possible\n# to run the tool even if protoc is unavailable)\n# - import the compiled file\n# - find the schema path and message name\n# - store a mapping from schema path to msg class\n#\nfor proto in args.protos:\n name,ext = os.path.splitext(proto)\n module = \"{}_pb2\".format(name) \n compiled_filename = \"{}/{}.py\".format(args.tmp_dir, module)\n # protoc handily replaces hyphens with underscores in the filenames it\n # gnerates so we must do the same.\n compiled_filename = compiled_filename.replace(\"-\",\"_\")\n try:\n compile_proto_file(proto, args.tmp_dir, args.include_path)\n except Exception as e:\n if not os.path.isfile(compiled_filename):\n print(\"Failed to compile {}: {}\".format(\n proto, e))\n sys.exit(1)\n\n try:\n decoder = imp.load_source(module, compiled_filename)\n (schema_path, msg_name) = parse_schema_from_proto(proto)\n decoder_dict[schema_path] = getattr(decoder, msg_name)\n except Exception as e:\n print(\"Failed to load {}: {}\".format(compiled_filename, e))\n sys.exit(1)\n\n\n\n# \n# Spawn threads to listen on the TCP and UDP sockets\n#\ntcp_thread = threading.Thread(target=tcp_loop)\ntcp_thread.daemon = True\ntcp_thread.start()\n\nudp_thread = threading.Thread(target=udp_loop)\nudp_thread.daemon = True\nudp_thread.start()\n\ndone = False\nwhile not done:\n try:\n time.sleep(60)\n except KeyboardInterrupt:\n done = True\n\n","sub_path":"telemetry_receiver.py","file_name":"telemetry_receiver.py","file_ext":"py","file_size_in_byte":23571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"237708041","text":"# -*- coding: utf-8 -*-\r\nfrom decorators import *\r\nfrom api import *\r\nfrom opensocial.http import HttpResponseJson\r\nfrom module.common.static import ErrorCode\r\nfrom django.conf import settings\r\n\r\n@handle_verification\r\ndef query_player_equip_fragment(request):\r\n '''\r\n 查询用户装备碎片\r\n '''\r\n playerId = request.REQUEST.get(\"playerId\", \"\").strip()\r\n serverId = request.REQUEST.get(\"serverId\", str(settings.SERVERID)).strip()\r\n player = get_player_by_id_or_str(playerId, int(serverId))\r\n\r\n resdata = {}\r\n if not player:\r\n resdata[\"success\"] = False\r\n resdata[\"message\"] = u\"该玩家不存在!\"\r\n resdata[\"data\"] = []\r\n return HttpResponseJson(resdata)\r\n\r\n fragments = player.equipfragments.all().values()\r\n data = []\r\n for fragment in fragments:\r\n meta = fragment.to_dict()\r\n meta[\"name\"] = fragment.equipfragment and fragment.equipfragment.name or \"\"\r\n data.append(meta)\r\n resdata[\"success\"] = True\r\n resdata[\"message\"] = \"\"\r\n resdata[\"data\"] = data\r\n return HttpResponseJson(resdata)\r\n # if not player:\r\n # data = {\"success\": False,\r\n # \"message\": \"The user does not exist!\",\r\n # \"errorcode\": ErrorCode.ERROR_PLAYER_IS_NONE\r\n # }\r\n # return HttpResponseJson(data)\r\n\r\n # fragments = player.equipfragments.all().values()\r\n # data = []\r\n # for fragment in fragments:\r\n # meta = fragment.to_dict()\r\n # meta[\"name\"] = fragment.equipfragment and fragment.equipfragment.name or \"\"\r\n # data.append(meta)\r\n # return HttpResponseJson(data)\r\n\r\n","sub_path":"kiwibackend/application/website/mobile/views/gmapi/equipfragment.py","file_name":"equipfragment.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"64198275","text":"from __future__ import print_function\nimport time\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nfrom matplotlib.widgets import Button\nfrom ds_tools.mousetrajectory_gui import MouseTrajectory\nimport config2D as conf\n\n\nrc('font',**{'family':'serif','serif':['Times']})\nrc('text', usetex=True)\n\n'''\n Brings up an empty world environment to draw \"human-demonstrated\" trajectories\n'''\n\ndef generate_demo():\n\n #Create figure/environment to draw trajectories on\n fig, ax = plt.subplots()\n plt.subplots_adjust(bottom=0.2)\n points, = ax.plot([], [], 'ro', markersize=2, lw=2)\n ax.set_xlim(conf.base[0], conf.base[1])\n ax.set_ylim(conf.base[0], conf.base[1])\n plt.gca().set_aspect('equal', adjustable='box')\n plt.xlabel('$x_1$',fontsize=15)\n plt.ylabel('$x_2$',fontsize=15)\n plt.title('Draw trajectories to learn a motion policy:',fontsize=15)\n\n i = 1\n while i <=conf.objects[0][0]:\n ax.add_artist(plt.Rectangle((conf.objects[i][0], conf.objects[i][1]), conf.objects[i][2], conf.objects[i][3], fc='r'))\n i = i+1\n #ax.add_artist(plt.Rectangle((0.50, 0.25), 0.4, 0.1))\n ax.plot(conf.start[0], conf.start[1], 'rd', markersize=10, lw=2, color = 'b')\n ax.plot(conf.goal[0], conf.goal[1], 'rd', markersize=10, lw=2, color = 'g')\n\n # Add UI buttons for data/figure manipulation\n store_btn = plt.axes([0.67, 0.05, 0.075, 0.05])\n clear_btn = plt.axes([0.78, 0.05, 0.075, 0.05])\n snap_btn = plt.axes([0.15, 0.05, 0.075, 0.05]) \n bstore = Button(store_btn, 'store') \n bclear = Button(clear_btn, 'clear') \n bsnap = Button(snap_btn, 'snap')\n\n\n # Calling class to draw data on top of environment\n indexing = 1 # Set to 1 if you the snaps/data to be indexed with current time-stamp\n store_mat = 0 # Set to 1 if you want to store data in .mat structure for MATLAB\n draw_data = MouseTrajectory(points, indexing, store_mat)\n draw_data.connect()\n bstore.on_clicked(draw_data.store_callback)\n bclear.on_clicked(draw_data.clear_callback)\n bsnap.on_clicked(draw_data.snap_callback)\n\n\n # Show\n plt.show()\n\n\ndef print_lastz(z, traj):\n\n #Create figure/environment to draw trajectories on\n fig, ax = plt.subplots()\n plt.subplots_adjust(bottom=0.2)\n points, = ax.plot([], [], 'ro', markersize=2, lw=2)\n ax.set_xlim(conf.base[0], conf.base[1])\n ax.set_ylim(conf.base[0], conf.base[1])\n plt.gca().set_aspect('equal', adjustable='box')\n plt.xlabel('$x_1$',fontsize=15)\n plt.ylabel('$x_2$',fontsize=15)\n plt.title('Plotting last Z state in each partition:',fontsize=15)\n\n i = 1\n while i <=conf.objects[0][0]:\n ax.add_artist(plt.Rectangle((conf.objects[i][0], conf.objects[i][1]), conf.objects[i][2], conf.objects[i][3], fc='r'))\n i = i+1\n #ax.add_artist(plt.Rectangle((0.50, 0.25), 0.4, 0.1))\n ax.plot(conf.start[0], conf.start[1], 'rd', markersize=10, lw=2, color = 'b')\n ax.plot(conf.goal[0], conf.goal[1], 'rd', markersize=10, lw=2, color = 'g')\n\n \n\n\n # Show\n plt.show()\n","sub_path":"gym_2d/src/gym_2d/record_demo.py","file_name":"record_demo.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"141047324","text":"import pandas as pd\nimport numpy as np\n\n# Для работы с матрицами\nfrom scipy.sparse import csr_matrix\n\n# Матричная факторизация\nfrom implicit.als import AlternatingLeastSquares\nfrom implicit.nearest_neighbours import CosineRecommender, TFIDFRecommender, BM25Recommender, \\\n ItemItemRecommender # нужен для одного трюка\nfrom implicit.nearest_neighbours import bm25_weight, tfidf_weight\n\n# Ранжирующая модель\nfrom lightgbm import LGBMClassifier\n\n\nclass MainRecommender:\n \"\"\"Рекоммендации, которые можно получить из ALS\n \n Input\n -----\n user_item_matrix: pd.DataFrame\n Матрица взаимодействий user-item\n \"\"\"\n\n def __init__(self, data, weighting=True):\n\n # Создаем топ покупок\n self.top_purchases = data.groupby(['user_id', 'item_id'])['quantity'].count().reset_index()\n self.top_purchases.sort_values('quantity', ascending=False, inplace=True)\n self.top_purchases = self.top_purchases[self.top_purchases['item_id'] != 999999]\n\n # Топ покупок по всему датасету\n self.overall_top_purchases = data.groupby('item_id')['quantity'].count().reset_index()\n self.overall_top_purchases.sort_values('quantity', ascending=False, inplace=True)\n self.overall_top_purchases = self.overall_top_purchases[self.overall_top_purchases['item_id'] != 999999]\n self.overall_top_purchases = self.overall_top_purchases.item_id.tolist()\n\n # Матрица user-item\n self.user_item_matrix = self.prepare_matrix(data) # pd.DataFrame\n self.id_to_itemid, self.id_to_userid, self.itemid_to_id, self.userid_to_id = self.prepare_dicts(\n self.user_item_matrix)\n\n # Взвешивание\n if weighting:\n self.user_item_matrix = bm25_weight(self.user_item_matrix.T).T\n\n # Обучение и рекомендации\n self.model = self.fit(self.user_item_matrix)\n # self.own_recommender = self.fit_own_recommender(self.user_item_matrix)\n # self.cosin_recommender = self.fit_cosin_recommender(self.user_item_matrix)\n # self.tfidf_recommender = self.fit_tfidf_recommender(self.user_item_matrix)\n # self.tfidf100_recommender = self.fit_tfidf100_recommender(self.user_item_matrix)\n self.bm25_recommender = self.fit_bm25_recommender(self.user_item_matrix)\n\n @staticmethod\n def prepare_matrix(data):\n \"\"\"Готовит user-item матрицу\"\"\"\n user_item_matrix = pd.pivot_table(data,\n index='user_id', columns='item_id',\n values='sales_value', # Можно пробоват другие варианты\n aggfunc='sum',\n fill_value=0\n )\n\n user_item_matrix = user_item_matrix.astype(float) # необходимый тип матрицы для implicit\n\n return user_item_matrix\n\n @staticmethod\n def prepare_dicts(user_item_matrix):\n \"\"\"Подготавливает вспомогательные словари\"\"\"\n\n userids = user_item_matrix.index.values\n itemids = user_item_matrix.columns.values\n\n matrix_userids = np.arange(len(userids))\n matrix_itemids = np.arange(len(itemids))\n\n id_to_itemid = dict(zip(matrix_itemids, itemids))\n id_to_userid = dict(zip(matrix_userids, userids))\n\n itemid_to_id = dict(zip(itemids, matrix_itemids))\n userid_to_id = dict(zip(userids, matrix_userids))\n\n return id_to_itemid, id_to_userid, itemid_to_id, userid_to_id\n\n @staticmethod\n def fit_cosin_recommender(user_item_matrix):\n \"\"\"Обучает модель, которая рекомендует товары, среди товаров, купленных юзером\"\"\"\n\n cosin_recommender = CosineRecommender(K=2, num_threads=0)\n cosin_recommender.fit(csr_matrix(user_item_matrix).T.tocsr())\n\n return cosin_recommender\n\n @staticmethod\n def fit_tfidf_recommender(user_item_matrix):\n \"\"\"Обучает модель, которая рекомендует товары, среди товаров, купленных юзером\"\"\"\n\n tfidf_recommender = TFIDFRecommender(K=6, num_threads=0)\n tfidf_recommender.fit(csr_matrix(user_item_matrix).T.tocsr())\n\n return tfidf_recommender\n\n @staticmethod\n def fit_tfidf100_recommender(user_item_matrix):\n \"\"\"Обучает модель, которая рекомендует товары, среди товаров, купленных юзером\"\"\"\n\n tfidf100_recommender = TFIDFRecommender(K=100, num_threads=0)\n tfidf100_recommender.fit(csr_matrix(user_item_matrix).T.tocsr())\n\n return tfidf100_recommender\n\n @staticmethod\n def fit_bm25_recommender(user_item_matrix):\n \"\"\"Обучает модель, которая рекомендует товары, среди товаров, купленных юзером\"\"\"\n\n bm25_recommender = BM25Recommender(K=6, K1=1.2, B=.76, num_threads=0)\n bm25_recommender.fit(csr_matrix(user_item_matrix).T.tocsr())\n\n return bm25_recommender\n\n @staticmethod\n def fit_own_recommender(user_item_matrix):\n \"\"\"Обучает модель, которая рекомендует товары, среди товаров, купленных юзером\"\"\"\n\n own_recommender = ItemItemRecommender(K=1, num_threads=0)\n own_recommender.fit(csr_matrix(user_item_matrix).T.tocsr())\n\n return own_recommender\n\n @staticmethod\n def fit(user_item_matrix, n_factors=20, regularization=0.1, iterations=40, num_threads=0):\n \"\"\"Обучает ALS\"\"\"\n\n model = AlternatingLeastSquares(factors=n_factors,\n regularization=regularization,\n iterations=iterations,\n num_threads=num_threads)\n model.fit(csr_matrix(user_item_matrix).T.tocsr())\n\n return model\n\n def _update_dict(self, user_id):\n \"\"\"Если появился новый user / item, то нужно обновить словари\"\"\"\n\n if user_id not in self.userid_to_id.keys():\n max_id = max(list(self.userid_to_id.values()))\n max_id += 1\n\n self.userid_to_id.update({user_id: max_id})\n self.id_to_userid.update({max_id: user_id})\n\n def get_similar_item(self, item_id):\n \"\"\"Находит товар, похожий на item_id\"\"\"\n recs = self.model.similar_items(self.itemid_to_id[item_id], N=2)\n top_rec = recs[1][0]\n return self.id_to_itemid[top_rec]\n\n def _extend_with_top_popular(self, recommendations, N=5):\n \"\"\"Если кол-во рекоммендаций < N, то дополняем их топ-популярными\"\"\"\n\n recommendations.extend(self.overall_top_purchases[:N])\n\n unique_recommendations = []\n [unique_recommendations.append(item) for item in recommendations if item not in unique_recommendations]\n\n unique_recommendations = unique_recommendations[:N]\n\n # if len(recommendations) < N:\n # recommendations.extend(self.overall_top_purchases[:N])\n # recommendations = recommendations[:N]\n\n return unique_recommendations\n\n def _get_recommendations(self, user, model, N=5):\n \"\"\"Рекомендации через стардартные библиотеки implicit\"\"\"\n\n try:\n res = [self.id_to_itemid[rec[0]] for rec in\n model.recommend(userid=self.userid_to_id[user],\n user_items=csr_matrix(self.user_item_matrix).tocsr(), # на вход user-item matrix\n N=N,\n filter_already_liked_items=False,\n filter_items=[self.itemid_to_id[999999]],\n recalculate_user=True)]\n res = self._extend_with_top_popular(res, N=N)\n\n except:\n res = self.overall_top_purchases[:N]\n\n return res\n\n def get_als_recommendations(self, user, N=5):\n \"\"\"Рекомендации через стардартные библиотеки implicit\"\"\"\n\n self._update_dict(user_id=user)\n return self._get_recommendations(user, model=self.model, N=N)\n\n def get_own_recommendations(self, user, N=5):\n \"\"\"Рекомендуем товары среди тех, которые юзер уже купил\"\"\"\n\n self._update_dict(user_id=user)\n return self._get_recommendations(user, model=self.own_recommender, N=N)\n\n def get_cosin_recommendations(self, user, N=5):\n \"\"\"Рекомендуем товары среди тех, которые юзер уже купил\"\"\"\n\n self._update_dict(user_id=user)\n return self._get_recommendations(user, model=self.cosin_recommender, N=N)\n\n def get_tfidf_recommendations(self, user, N=5):\n \"\"\"Рекомендуем товары среди тех, которые юзер уже купил\"\"\"\n\n self._update_dict(user_id=user)\n return self._get_recommendations(user, model=self.tfidf_recommender, N=N)\n\n def get_tfidf100_recommendations(self, user, N=5):\n \"\"\"Рекомендуем товары среди тех, которые юзер уже купил\"\"\"\n\n self._update_dict(user_id=user)\n return self._get_recommendations(user, model=self.tfidf100_recommender, N=N)\n\n def get_bm25_recommendations(self, user, N=5):\n \"\"\"Рекомендуем товары среди тех, которые юзер уже купил\"\"\"\n\n self._update_dict(user_id=user)\n return self._get_recommendations(user, model=self.bm25_recommender, N=N)\n\n def get_similar_items_recommendation(self, user, N=5):\n \"\"\"Рекомендуем товары, похожие на топ-N купленных юзером товаров\"\"\"\n\n top_users_purchases = self.top_purchases[self.top_purchases['user_id'] == user].head(N)\n\n res = top_users_purchases['item_id'].apply(lambda x: self.get_similar_item(x)).tolist()\n\n res = self._extend_with_top_popular(res, N=N)\n\n assert len(res) == N, 'Количество рекомендаций != {}'.format(N)\n return res\n\n def get_similar_users_recommendation(self, user, N=5):\n \"\"\"Рекомендуем топ-N товаров, среди купленных похожими юзерами\"\"\"\n print(user)\n res = []\n\n self._update_dict(user_id=user)\n # Находим топ-N похожих пользователей\n try:\n similar_users = self.model.similar_users(self.userid_to_id[user], N=N + 1)\n similar_users = [rec_usr[0] for rec_usr in similar_users]\n similar_users = similar_users[1:]\n\n for usr in similar_users:\n res.extend(self.get_own_recommendations(self.id_to_userid[usr], N=1))\n\n res = self._extend_with_top_popular(res, N=N)\n except:\n res = self.overall_top_purchases[:N]\n\n assert len(res) == N, 'Количество рекомендаций != {}'.format(N)\n return res\n\n\nclass Ranking:\n \"\"\"Ранжирование кандидатов с помощью LGBM\n \n Input\n -----\n user_item_matrix: pd.DataFrame\n Матрица взаимодействий user-item\n X_train: pd.DataFrame\n Датафрейм с фичами для обучения модели второго уровня\n y_train: pd.Series\n Целевая переменная\n cat_feats: list\n Список категориальных фичей\n \"\"\"\n\n def __init__(self, X_train, y_train, cat_feats):\n self.model = self.model_fit(X_train, y_train, cat_feats)\n\n def model_fit(self, X_train, y_train, cat_feats):\n \"\"\"Обучение модели\"\"\"\n X_train[cat_feats] = X_train[cat_feats].astype('category')\n\n lgb = LGBMClassifier(objective='binary', max_depth=11, n_estimators=1005, categorical_column=cat_feats,\n random_state=42)\n\n lgb.fit(X_train, y_train)\n\n return lgb\n\n def make_predict(self, data, X_train):\n \"\"\"Прогноз модели\"\"\"\n preds = self.model.predict_proba(X_train)\n\n # Берем вероятность класса 1\n proba_1 = [i[1] for i in preds]\n\n result = data[['user_id', 'item_id']]\n result['proba'] = proba_1\n result.sort_values(['user_id', 'proba'], ascending=False, inplace=True)\n result = result.groupby('user_id').head(20)\n # Соберем результаты в строку\n result = result.groupby('user_id')['item_id'].unique().reset_index()\n result.columns = ['user_id', 'lgbm_rec']\n\n return result\n","sub_path":"src/recommenders.py","file_name":"recommenders.py","file_ext":"py","file_size_in_byte":13229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"157414056","text":"import numpy as np\n\nfrom abc import ABCMeta\n\ntry:\n import vrep\nexcept:\n print('--------------------------------------------------------------')\n print('\"vrep.py\" could not be imported. This means very probably that')\n print('either \"vrep.py\" or the remoteApi library could not be found.')\n print('Make sure both are in the same folder as this file,')\n print('or appropriately adjust the file \"vrep.py\"')\n print('--------------------------------------------------------------')\n print('')\n\nclass AVrepFunctions(metaclass=ABCMeta):\n def __init__(self):\n\n self.clientID = 0\n self.__getPosition = True\n self.__getOrientation = False\n\n def get_handles(self):\n # > get handle of environment object\n for key in self.handles_all:\n try:\n vrep_name = self.vrep_name_all[key]\n _, handles = vrep.simxGetObjectHandle(self.clientID,\n vrep_name, # name of object in vrep\n vrep.simx_opmode_blocking)\n self.handles_all[key] = handles\n\n if _ != 0:\n print(\"ERROR: Handle of \" + key + \" was not received\")\n else:\n print(\"Handle of \" + key + \" was received\")\n\n except:\n raise ValueError(\"receiving of environment handles failed\")\n\n def update_pose(self):\n \"\"\"\n geht durch alle objekte, liest deren pose und updated die gespeicherten werte\n :return:\n \"\"\"\n for key in self.handles_all:\n try:\n if self.handles_all[key] is not 0:\n if self.__getPosition:\n _ = vrep.simx_return_novalue_flag\n while _ != vrep.simx_return_ok:\n _ , position = vrep.simxGetObjectPosition(clientID=self.clientID,\n objectHandle=self.handles_all[key],\n relativeToObjectHandle=-1,\n operationMode=vrep.simx_opmode_blocking)\n self.position_all[key] = position\n\n if self.__getOrientation:\n _ = vrep.simx_return_novalue_flag\n while _ != vrep.simx_return_ok:\n _, orientation = vrep.simxGetObjectOrientation(clientID=self.clientID,\n objectHandle=self.handles_all[key],\n relativeToObjectHandle=-1,\n operationMode=vrep.simx_opmode_blocking)\n self.orientation_all[key] = orientation\n else:\n pass\n # print(\"Pose update not possible; no handle: \" + key)\n except:\n print(\"####################\")\n raise ValueError(\"Pose Update failed:\" + key)\n\n def print_pose(self):\n \"\"\"\n \"\"\"\n for key in self.handles_all:\n print(\"Position of \" + key + \" : \", end=\"\")\n print(np.around(self.position_all[key], decimals=3))\n print(\"Orientation of \" + key + \" : \", end=\"\")\n print(np.around(self.orientation_all[key], decimals=3))\n\n def start_up_simulation(self, dt):\n\n print(\"Start setUp of Simulation\")\n vrep.simxSetFloatingParameter(self.clientID,\n vrep.sim_floatparam_simulation_time_step,\n dt, # specify a simulation time step\n vrep.simx_opmode_oneshot)\n\n # --------------------- Start the simulation\n # start our simulation in lockstep with our code\n _ = vrep.simxStartSimulation(self.clientID,\n vrep.simx_opmode_blocking)\n if _ != 0: raise ValueError(\"simulation start failed\")\n\n _ = vrep.simxSynchronous(self.clientID, True)\n if _ != 0: raise ValueError(\"init of synchronisation failed\")\n\n print(\"setUp of Simulation finished\")\n","sub_path":"DeepLearningProject/hs_robot_demonstrat/NeuralRobotControl/SimulationInterface_Component/Vrep/AVrepFunctions.py","file_name":"AVrepFunctions.py","file_ext":"py","file_size_in_byte":4373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"236325966","text":"from lib.buffer_utils import BufferUtils\nfrom lib.fixture import Fixture\n\nclass Route(object):\n \"\"\" Climbing route specification, basically a group of fixtures with\n dictionary access by Fixture.pos1.\n \"\"\"\n\n __pixel_offset = 0\n\n def __init__(self, data = {}, fader = None, speed = None):\n self._data = data\n self.active = data.get(\"active\", False)\n self.color = tuple(data.get(\"color\", (0, 0, 0)))\n self.fixtures = [Fixture(item) for item in data.get(\"fixtures\")]\n self.index = data.get(\"index\", 0)\n # Caches\n self._addresses = []\n self._indices = []\n # Fading handling\n self.fader = fader\n self.speed = speed\n self._current_time = 0\n\n @property\n def addresses(self):\n \"\"\" Returns logical addresses of fixtures.\n \"\"\"\n if not self._addresses :\n f = lambda fd: (fd.strand, fd.address, Route.__pixel_offset)\n self._addresses = [f(fixture) for fixture in self.fixtures]\n return self._addresses\n\n @property\n def indices(self):\n \"\"\" Returns indices into pixel buffer.\n \"\"\"\n if not self._indices:\n self._indices = map(BufferUtils.logical_to_index, self.addresses)\n return self._indices\n\n def update(self, dt):\n self._current_time += int(dt*self.speed)\n self.color = self.fader.get_color_wrapped(self._current_time)\n\n def __len__(self):\n return len(self.fixtures)\n\n def __repr__(self):\n out = [self.active, self.color, self.fixtures, self.index]\n return \"\" % tuple(map(str, out))\n","sub_path":"lib/route.py","file_name":"route.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"9330475","text":"\"\"\"MMS URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url, patterns\nfrom django.contrib import admin\nfrom ajax_select import urls as ajax_select_urls\n\nadmin.autodiscover()\n\nurlpatterns = [\n\turl(r'^$',include('virtual_miseq.urls')),\n\turl(r'^virtual/',include('virtual_miseq.urls')),\n\turl(r'^physical/',include('virtual_miseq.urls')),\n url(r'^admin/', include(admin.site.urls)),\n#\turl(r'^admin/lookups/', include(ajax_select_urls)),\n\turl(r'^lookups/', include(ajax_select_urls)),\n#\turl(r'^search/',include('virtual_miseq.urls')),\n\t#url(r'lookups/', include(ajax_select_urls)),\n\turl(r'^selectable/', include('selectable.urls')),\n\turl(r'^contact/', 'MMS.views.contact'),#include('envelope.urls')),\n\n\turl(r'^chaining/', include('smart_selects.urls')),\n\t\n\t#login logout\n\turl(r'^accounts/login/$', 'MMS.views.login'),\n# \turl(r'^accounts/auth/$', 'MMS.views.auth_view'), \n \turl(r'^accounts/logout/$', 'MMS.views.logout'),\n \turl(r'^accounts/loggedin/$', 'MMS.views.loggedin'),\n \turl(r'^accounts/register/$', 'MMS.views.register_user'),\n \turl(r'^accounts/register_success/$', 'MMS.views.register_success'),\n\turl(r'^accounts/logout_success/$', 'MMS.views.logout_success'),\n\n\turl(r'^help/$', 'MMS.views.help'),\t\n\n\turl(r'^tracking/', include('tracking.urls')),\n]\n","sub_path":"MMS/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"544538797","text":"\"\"\"A video player class.\"\"\"\n\nfrom .video_library import VideoLibrary\nimport random\n\n\nclass VideoPlayer:\n \"\"\"A class used to represent a Video Player.\"\"\"\n playlists = {}\n\n pl_list = []\n\n playing = \"none\"\n\n pause = False\n\n store_video_id = \" \"\n\n def __init__(self):\n self._video_library = VideoLibrary()\n\n def number_of_videos(self):\n num_videos = len(self._video_library.get_all_videos())\n print(f\"{num_videos} videos in the library\")\n\n def show_all_videos(self):\n video_list = []\n \"\"\"Returns all videos.\"\"\"\n print(\"Here's a list of all available videos:\")\n vids = self._video_library.get_all_videos()\n for video in vids: #Could definitely been a custom method\n tags_list = \"\"\n for tag in video.tags:\n tags_list += tag + \" \"\n tags_list = tags_list[:-1]\n vid_info = f\"{video.title} ({video.video_id}) [{tags_list}]\"\n video_list.append(vid_info)\n video_list = sorted(video_list)\n for item in range(len(video_list)):\n print(video_list[item]) # will need revisiting to deal with vid_list[2]\n \n\n def play_video(self, video_id):\n self.store_video_id = video_id\n\n try:\n if self.playing == \"none\":\n \n vid = self._video_library.get_video(video_id)\n self.playing = vid.title\n print(\"Playing video: {}\".format(self.playing))\n #needs to be able to check if current video is playing and stop\n else:\n vid = self._video_library.get_video(video_id)\n check = vid.title\n print(f\"Stopping video: {self.playing}\")\n self.playing = check\n print(\"Playing video: {}\".format(self.playing))\n \n\n except:\n #print(self._video_library.get_video(video_id).values())\n print(\"Cannot play video: Video does not exist\")\n \n \n\n def stop_video(self): #IMPLEMENT\n if self.playing == \"none\":\n print(\"Cannot stop video: No video is currently playing\") \n else:\n print(f\"Stopping video: {self.playing}\")\n self.playing = \"none\"\n \n\n def play_random_video(self):\n \"\"\"Plays a random video from the video library.\"\"\"\n vid_list = []\n\n get_videos = self._video_library.get_all_videos()\n for video in get_videos:\n vid_list.append(video.video_id)\n rand = random.randint(0, len(vid_list)-1)\n\n if len(vid_list) == 0:\n print(\"No videos available\")\n else: #NEED TO IMPLEMENT STOP PREVIOUS (if previous playing)\n self.play_video(vid_list[rand]) #IS THIS THE VIDEO ID\n \n \n\n def pause_video(self):\n \"\"\"Pauses the current video.\"\"\"\n if self.pause == True:\n print(f\"Video already paused: {self.playing}\")\n elif self.playing == \"none\":\n print(\"Cannot pause video: No video is currently playing\")\n else:\n self.pause = True\n print(f\"Pausing video: {self.playing}\")\n\n \n\n def continue_video(self):\n \"\"\"Resumes playing the current video.\"\"\"\n if self.playing == \"none\":\n print(\"Cannot continue video: No video is currently playing\")\n elif self.pause == False:\n print(\"Cannot continue video: Video is not paused\")\n else:\n print(f\"Continuing video: {self.playing}\")\n self.pause = False\n\n def show_playing(self):\n \"\"\"Displays video currently playing.\"\"\"\n if self.playing == \"none\":\n print(\"No video is currently playing\")\n else:\n if_paused = \"\"\n if self.pause == True:\n if_paused = \" - PAUSED\"\n vid = self._video_library.get_video(self.store_video_id)\n tags_list = \"\"\n for tag in vid.tags:\n tags_list += tag + \" \"\n tags_list = tags_list[:-1]\n vid_info = f\"Currently playing: {vid.title} ({self.store_video_id}) [{tags_list}]{if_paused}\"\n print(vid_info)\n \n\n\n\n\n\n\n #The issue is the playlists are remaining throughout the test causing errors\n #I think playlist_names in pl_list is building up\n\n def create_playlist(self, playlist_name):\n \n if playlist_name.lower() not in self.pl_list: \n #casefold or lower might not work, not sure if it applied to whole of playlists\n self.playlists[playlist_name] = [] # dictionary list\n self.pl_list.append(playlist_name.lower())\n print(f\"Successfully created new playlist: {playlist_name}\")\n else:\n print(\"Cannot create playlist: A playlist with the same name already exists\")\n \n\n def add_to_playlist(self, playlist_name, video_id):\n \n if playlist_name.lower() not in self.pl_list: #Here it says it is... Error\n print(f\"Cannot add video to {playlist_name}: Playlist does not exist\")\n elif video_id not in self._video_library.get_all_videos():\n print(f\"Cannot add video to {playlist_name}: Video does not exist\")\n elif video_id in self.playlists[playlist_name]: #want this to access the list, check\n print(f\"Cannot add video to {playlist_name}: Video already added\")\n else:\n playlists[playlist_name].append(video_id) #I am sure this isn't accessing the list\n print(f\"Added video to {playlist_name}: {video_id}\")\n \n \n \n\n def show_all_playlists(self):\n \"\"\"Display all playlists.\"\"\"\n if len(self.playlists) == 0: #ADDED SELF HERE \n print(\"No playlists exist yet\")\n else:\n print(\"Showing all playlists:\")\n for key in self.playlists.keys():\n print(key)\n \n\n def show_playlist(self, playlist_name):\n if len(self.playlists[playlist_name]) == 0: #check again how to implement dictionaries with lists as value\n print(f\"Showing playlist: {playlist_name}\")\n print(\" No videos here yet\")\n elif playlist_name not in self.playlists.keys():\n print(f\"Cannot show playlist {playlist_name}: Playlist does not exist\")\n else:\n print(f\"Showing playlist: {playlist_name}\")\n for video in self.playlists[playlist_name]: #Value should == list\n print(str(video))\n \n \n \n\n def remove_from_playlist(self, playlist_name, video_id):\n if playlist_name not in self.playlists.keys():\n print(f\"Cannot remove video from {playlist_name}: Playlist does not exist\")\n elif video_id not in self.playlists[playlist_name]:\n print(f\"Cannot remove video from {playlist_name}: Video is not in playlist\")\n else:\n self.playlists[playlist_name].remove(video_id) # VALUE or VALUES? ... SILLY\n #YOU AUTOMATICALLY GET THE VALUE BACK FROM A KEY I THINK\n print(f\"Removed video from {playlist_name}: {video_id}\")\n\n def clear_playlist(self, playlist_name):\n if playlist_name not in self.playlists.keys():\n print(f\"Cannot clear playlist {playlist_name}: Playlist does not exist\")\n else:\n self.playlists[playlist_name].clear() #should it be x = x.clear()?\n print(f\"Successfully removed all videos from {playlist_name}\")\n\n def delete_playlist(self, playlist_name):\n if playlist_name not in self.playlists.keys():\n print(f\"Cannot delete playlist {playlist_name}: Playlist does not exist\")\n else:\n del self.playlists[playlist_name]\n print(f\"Deleted playlist: {playlist_name}\")\n\n\n\n\n\n \n\n def search_videos(self, search_term):\n all_videos = self._video_library.get_all_videos()\n\n count = 0\n match_list = []\n full_vid_info = []\n for vid in all_videos:\n tags_list = \"\"\n if search_term.lower() in vid.title.lower():\n count += 1\n for tag in vid.tags:\n tags_list += tag + \" \"\n tags_list = tags_list[:-1]\n vid_info = f\"{count}) {vid.title} ({vid.video_id}) [{tags_list}]\"\n match_list.append(vid.video_id)\n full_vid_info.append(vid_info)\n full_vid_info = sorted(full_vid_info)\n if len(match_list) == 0:\n print(f\"No search results for {search_term}\")\n else:\n print(f\"Here are the results for {search_term}:\")\n \n for video in full_vid_info:\n print(video)\n \n print(\"Would you like to play any of the above? If yes, \"\n \"specify the number of the video.\")\n user_input = input(\"Would you like to play any of the above? If yes, \"\n \"specify the number of the video.\")\n #print(user_input)\n try:\n val = int(user_input)\n if val > len(match_list):\n print(\"If your answer is not a valid number, we will assume it's a no.\")\n else:\n to_play = match_list[val - 1]\n self.play_video(to_play)\n except:\n print(\"If your answer is not a valid number, we will assume it's a no.\")\n \n \n \n \n \n\n def search_videos_tag(self, video_tag):\n \"\"\"Display all videos whose tags contains the provided tag.\n\n Args:\n video_tag: The video tag to be used in search.\n \"\"\"\n all_videos = self._video_library.get_all_videos()\n tag_videos = []\n\n \n \n for vid in all_videos:\n tags_list = \"\"\n for tag in vid.tags:\n tags_list += tag + \" \"\n tags_list = tags_list[:-1]\n vid_info = f\"{vid.title} ({vid.video_id}) [{tags_list}]\"\n if video_tag in tags_list:\n tag_videos.append(vid_info)\n tag_videos = sorted(tag_videos)\n if len(tag_videos) == 0:\n print(f\"No search results for {video_tag}\")\n else:\n print(f\"Here are the results for {video_tag}:\")\n count = 0\n for vid in tag_videos:\n count += 1\n print(f\"{count}) {vid}\")\n print(\"Would you like to play any of the above? If yes, specify the number of the video.\")\n #The above was added to pass the test, python would not naturally include this as part of the assert criteria\n user_input = input(\"Would you like to play any of the above? If yes, specify the number of the video.\")\n \n try:\n val = int(user_input)\n if val > len(tag_videos):\n print(\"If your answer is not a valid number, we will assume it's a no.\")\n else:\n to_play = tag_videos[val - 1]\n self.play_video(to_play)\n except:\n print(\"If your answer is not a valid number, we will assume it's a no.\")\n\n \n \n \n\n\n\n\n\n\n #Wanted to implement the below but have a dissertation due soon! Will attempt at later date :)\n # I also can not get this running without the completion of previous sections\n\n def flag_video(self, video_id, flag_reason=\"\"):\n \"\"\"Mark a video as flagged.\n\n Args:\n video_id: The video_id to be flagged.\n flag_reason: Reason for flagging the video.\n \"\"\"\n print(\"flag_video needs implementation\")\n\n def allow_video(self, video_id):\n \"\"\"Removes a flag from a video.\n\n Args:\n video_id: The video_id to be allowed again.\n \"\"\"\n print(\"allow_video needs implementation\")\n","sub_path":"python/src/video_player.py","file_name":"video_player.py","file_ext":"py","file_size_in_byte":11965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"280472670","text":"#!/usr/bin/env python3\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\n\n# templateized so that the year and semester can easily be changed\nurl = 'https://mysite.socccd.edu/onlineschedule/ClassFind.asp?siteID=A&termID={year}{semester}&termtype=&mktcode=CO20&header=Computer+Science'\n\nyear = 2018\nsemester = 3 # fall\nsem_map = {\n 1: 'Spring',\n 2: 'Summer',\n 3: 'Fall',\n }\n\n\n#*******************************************************************************************************************\ndef build_dict(url):\n # The page has a dangling /div\n # Python's html.parser doesn't handle this adequately, so we need html5lib\n soup = BeautifulSoup(urlopen(url).read(), \"html5lib\")\n\n # remove all icon tags\n for icons in soup.find_all(class_='material-icons'):\n icons.decompose()\n\n courses = []\n course_tables = soup.find_all(attrs={'class': 'class-list-course-list'})\n for course_table in course_tables:\n\n tickets = []\n\n # Clean up the prereq data\n prereq = course_table.find(class_='class-list-prereq')\n if prereq:\n prereq = prereq.text.strip()\n if prereq.startswith('Prerequisite: '):\n prereq = prereq.lstrip('Prerequisite: ')\n\n course_info = {\n 'units' : course_table.find(attrs={'class': 'class-list-unit'}).text.strip()[7:],\n 'prereq': prereq,\n }\n\n course = {\n 'course_id': course_table.find(attrs={'class': 'course-id'}).text.strip(),\n 'course_title' : course_table.find(attrs={'class': 'class-list-course-title'}).text.strip(),\n 'course_info' : course_info,\n 'course_description' : course_table.find(attrs={'class': 'class-list-course-desc'}).text.strip(),\n 'tickets': tickets,\n }\n courses.append(course)\n for section in course_table.find_all(attrs={'class': 'class-list-info-method'}):\n \n # remove all small tags\n for smalls in section.find_all(class_='ins-method'):\n smalls.decompose()\n class_days = section.find(attrs={'title': 'DAY'})\n class_days = list(class_days)\n\n class_times = list(section.find(attrs={'title': 'TIME'}).children)\n \n # Seperate Lab and Lecture Rooms\n lec_room = section.find(class_='class-list-room-text')\n lab_room = lec_room.find(class_='extra-room')\n # None-check for lab attrabutes\n if lab_room:\n lab_room.extract()\n lab_room = lab_room.text.strip()\n\n # If lab is in the same room as lecture\n if lab_room == None and class_times[-1].strip():\n lab_room = lec_room.text.strip()\n\n\n lecture = {\n 'day':class_days[0].strip(),\n 'time':class_times[0].strip(),\n 'room': lec_room.text.strip(),\n }\n lab = { \n 'day':class_days[-1].strip(),\n 'time':class_times[-1].strip(),\n 'room': lab_room,\n }\n ticket = {\n 'number': section.find(attrs={'class': 'class-list-info-ticket'}).text.strip(),\n 'status': section.find(attrs={'class': 'class-list-info-status'}).text.strip(),\n 'lecture': lecture,\n 'lab': lab, \n 'instructor': (section.find(attrs={'title': 'INSTRUCTOR'}).text.strip()),\n }\n tickets.append(ticket)\n return courses\n#*******************************************************************************************************************\n\n\n\n#*******************************************************************************************************************\ndef ticket_list(courses):\n tickets = []\n for course in courses:\n for ticket in course['tickets']:\n tickets.append(ticket['number'])\n return tickets\n#*******************************************************************************************************************\n\n\n\n#*******************************************************************************************************************\nif __name__ == '__main__':\n courses = build_dict(url.format(year=year, semester=semester))\n import json\n\n # templateized so that the year and semester can easily be changed with globals\n cFileName = 'courses{year}-{semester}.json'\n with open(cFileName.format(year=year, semester=semester), 'w') as file:\n json.dump(courses, file, sort_keys=True, indent=4)\n\n # templateized so that the year and semester can easily be changed with globals\n tickets = ticket_list(courses)\n tFilename = 'tickets{year}-{semester}.txt'\n with open(tFilename.format(year=year, semester=semester), 'w') as file:\n file.write('\\n'.join(tickets))\n#*******************************************************************************************************************\n","sub_path":"extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":5062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"326608279","text":"from sqlalchemy.dialects.mysql import BIGINT, VARCHAR\nfrom app import db\n\n\nclass Category(db.Model):\n __tablename__ = 'Category'\n __table_args__ = {\n 'mysql_engine': 'InnoDB',\n 'mysql_charset': 'utf8',\n 'extend_existing': True\n }\n\n id = db.Column(\n BIGINT(20, unsigned=True),\n primary_key=True,\n index=True\n )\n\n name = db.Column(\n VARCHAR(128)\n )","sub_path":"app/model/Category.py","file_name":"Category.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"653831527","text":"from django.http.response import HttpResponse\nfrom django.shortcuts import render, render_to_response\nfrom google.appengine.api import search\n#from xlsreaderapp.forms import SearchForm\nfrom google.appengine.api.search.search import AtomFacet, Facet\nfrom registration.models import UserDetail\nfrom category.models import Category, AttributeOption, CategoryAttribute, OptionTag\nfrom products.models import SupplierCategory, CatProductMapping, CatProduct\nfrom indure_search.forms import SearchForm\n\ndef create_index(request):\n\tindex = search.Index(name='supplier', namespace='tradejunctionProduct')\n\tsupp_detail = UserDetail.objects.filter(admin_status=2)\n\tfor s in supp_detail:\n\t\t#createDocument(s.user)\n\t\tsid = s.user.id\n\t\t#return HttpResponse(sid)\n\t\t\"\"\"Create a Document object\"\"\"\n\t\t# check for the fields that are always required.\n\t\tif sid:\n\t\t# First, check that the given sid has only visible ascii characters,\n\t\t# and does not contain whitespace. The pid will be used as the doc_id,\n\t\t# which has these requirements.\n\t\t\tsupcat_detail = SupplierCategory.objects.filter(supplier=sid)\n\t\t\tif supcat_detail:\n\t\t\t\tfor c in supcat_detail:\n\t\t\t\t\tmap_detail = CatProductMapping.objects.filter(suppliercat=c.id)\n\t\t\t\t\tif map_detail:\n\t\t\t\t\t\tfor m in map_detail:\n\t\t\t\t\t\t\tdocc = \"S\" + str(c.supplier.id) + \"C\" + str(c.category.id) + \"P\" + str(m.id)\n\t\t\t\t\t\t\t#return HttpResponse(c.supplier)\n\t\t\t\t\t\t\t# construct the document fields from the params\n\t\t\t\t\t\t\tresfields = buildFields(sid=c.supplier.id, catt=c.category.id, prod=m.id)\n\t\t\t\t\t\t\tfacet_fields = buildFacet(sid=c.supplier.id, catt=c.category.id, prod=m.id)\n\t\t\t\t\t\t\t# build and index the document. Use the pid (product id) as the doc id.\n\t\t\t\t\t\t\t# (If we did not do this, and left the doc_id unspecified, an id would be\n\t\t\t\t\t\t\t# auto-generated.)\n\t\t\t\t\t\t\t#from django.utils import simplejson\n\t\t\t\t\t\t\t#json_stuff = simplejson.dumps({\"list_of_jsonstuffs\" : resfields}) \n\t\t\t\t\t\t\t#return HttpResponse(json_stuff, content_type =\"application/json\")\n\t\t\t\t\t\t\t#return HttpResponse(resfields)\n\t\t\t\t\t\t\td = search.Document(doc_id=docc, fields=resfields, facets = facet_fields)\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t#fdg\n\t\t\t\t\t\t\t\tadd_result = index.put(d)\n\t\t\t\t\t\t\texcept search.Error:\n\t\t\t\t\t\t\t\treturn HttpResponse(\"error\")\n\t\t\telse:\n\t\t\t\tcontinue\t\t\t\t\t\n\t\telse:\n\t\t\traise HttpResponse('Missing parameter.') \n\treturn HttpResponse(\"done\")\t\t \n\t \n\ndef buildFields(sid,catt,prod):\n\t#fields = []\n\tsupplier_list = buildSuppFields(sid)\n\t#partial_fields = fields + supplier_list\n\tattribute_val_list = buildCatFields(sid,catt,prod)\n\tpartial_fields = supplier_list + attribute_val_list\n\t#mystring = attribute_val_list.split(\",\")\n\t#final_list = partial_fields + mystring[0]\n\t#final_string = final_list + ',facets =' + mystring[1]\n\t#return final_string\n\treturn partial_fields\n \ndef buildSuppFields(sid):\n\t#fields = []\n\tdet = UserDetail.objects.get(user=sid)\n\timgg = str(det.company_logo)\n\tfields = [search.TextField(name='company', value=det.company_name),\n search.TextField(name='website', value=det.comapny_website),\n search.TextField(name='image_url', value=imgg),\n ]\n\treturn fields \n\ndef buildCatFields(sid,catt,prod):\n\tfields = []\n\t#supcat_detail = SupplierCategory.objects.get(supplier=sid,category=catt)\n\t#map_detail = CatProductMapping.objects.filter(suppliercat=supcat_detail.id)\n\t#if map_detail:\n\t#\tcat_detail = Category.objects.get(id=catt)\n\t#\tfor m in map_detail:\n\tif prod:\n\t\tprod_detail = CatProduct.objects.filter(mapp=prod)\n\t\tfor p in prod_detail:\n\t\t\topt = AttributeOption.objects.get(id=p.options.id)\n\t\t\titem = search.TextField(name='attribute_val', value=opt.name)\n\t\t\tif item not in fields:\n\t\t\t\tfields.append(search.TextField(name='attribute_val', value=opt.name))\n\t\t\t\t#attribute_name = Category.objects.get(id=p.attribute)\n\t\t\t\ttag_detail = OptionTag.objects.filter(option=p.options)\n\t\t\t\tfor t in tag_detail:\n\t\t\t\t#tag = OptionTag.objects.get(id=t.id)\n\t\t\t\t\tfields.append(search.TextField(name='meta_tag', value=t.name))\n\t\t#return fields + ',' + facets\n\t\treturn fields\n\telse:\n\t\treturn fields\n\t\t \ndef buildFacet(sid,catt,prod):\n\tfacets = []\n\t#supcat_detail = SupplierCategory.objects.get(supplier=sid,category=catt)\n\t#map_detail = CatProductMapping.objects.filter(suppliercat=supcat_detail.id)\n\tif prod:\n\t\tcat_detail = Category.objects.get(id=catt)\n\t\tfacets.append(search.AtomFacet(name='category', value=cat_detail.name))\n\t\tprod_detail = CatProduct.objects.filter(mapp=prod)\n\t\tfor p in prod_detail:\n\t\t\topt = AttributeOption.objects.get(id=p.options.id)\n\t\t\titem = search.AtomFacet(name=opt.attribute.name, value=opt.name)\n\t\t\tif item not in facets:\n\t\t\t\tfacets.append(search.AtomFacet(name=opt.attribute.name, value=opt.name))\n\t\treturn facets\n\telse:\n\t\treturn facets \n\t\t\ndef search_sup(request):\n\tresults = \"\"\n\tfacet = list()\n\tdoc = list()\n\tindex_to_search = search.Index(name='supplier', namespace='tradejunctionProduct')\n\tif request.method == 'POST':\n\t\tform = SearchForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tsearched_txt = form.cleaned_data['search']\n\t\t\tquery = search.Query('meta_tag:'+searched_txt,enable_facet_discovery=True)\n\t\t\tsearch_results = index_to_search.search(query)\n\t\t\treturned_count = len(search_results.results)\n\t\t\tnumber_found = search_results.number_found\n\t\t\tfacet = search_results.facets\n\t\t\treturn render(request,'indure_search/bodysearch.html',{'form':form,'search_results':search_results,'facet':facet,'rc':returned_count,'nf':number_found}) \n\telse:\n\t\tform = SearchForm()\n\t\treturn render(request,'indure_search/bodysearch.html',{'form':form})\n\t\t\ndef facet_search(request):\n\tfacet_refinements= list()\n\tindex_to_search = search.Index(name='supplier', namespace='tradejunctionProduct')\n\tif request.method == 'POST': \n\t\tsearched_txt = request.POST.get('search_txt')\n\t\tfacet_string = request.POST.get('facet_string')\n\t\tif searched_txt:\n\t\t\tsearch_str = 'meta_tag:'+ searched_txt \n\t\t\tif facet_string:\n\t\t\t\tfacets= facet_string.split(\",\")\n\t\t\t\tquery = search.Query('meta_tag:'+searched_txt, facet_refinements=facets)\n\t\t\t\t#strr = '[' + facet_string + ']'\n\t\t\t\t#return HttpResponse(strr)\t\n\t\t\t\tsearch_results = index_to_search.search(query) \n\t\t\t\treturn render_to_response('indure_search/search_supplier_part.html', {\"search_results\": search_results})\n\t\t\telse:\n\t\t\t\tquery = search.Query('meta_tag:'+searched_txt,enable_facet_discovery=True)\n\t\t\t\tsearch_results = index_to_search.search(query)\n\t\t\t\treturn render_to_response('indure_search/search_supplier_part.html', {\"search_results\": search_results})\n\t\telse:\n\t\t\treturn HttpResponse(\"ngh\")\t\n\t\t\t\ndef facet_show(request):\n\tfacet_refinements= list()\n\tindex_to_search = search.Index(name='supplier', namespace='tradejunctionProduct')\n\tif request.method == 'POST': \n\t\tsearched_txt = request.POST.get('search_txt')\n\t\tfacet_string = request.POST.get('facet_string')\t\n\t\tif searched_txt:\n\t\t\tsearch_str = 'meta_tag:'+ searched_txt \n\t\t\tif facet_string:\n\t\t\t\tquery = search.Query('meta_tag:'+searched_txt, enable_facet_discovery=True, facet_refinements=[facet_string])\n\t\t\t\t#strr = '[' + facet_string + ']'\n\t\t\t\t#return HttpResponse(strr)\t\n\t\t\t\tsearch_results = index_to_search.search(query) \n\t\t\t\treturn render_to_response('indure_search/show_facet_part.html', {\"search_results\": search_results})\n\t\t\telse:\n\t\t\t\tquery = search.Query('meta_tag:'+searched_txt,enable_facet_discovery=True)\n\t\t\t\tsearch_results = index_to_search.search(query)\n\t\t\t\treturn render_to_response('indure_search/show_facet_part.html', {\"search_results\": search_results})\n\t\telse:\n\t\t\treturn HttpResponse(\"ngh\")\t\n","sub_path":"indure_search/views_full_text_search.py","file_name":"views_full_text_search.py","file_ext":"py","file_size_in_byte":7488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"346003786","text":"#!/usr/bin/env python3\n\n\"\"\"\nFile:\tprocess_parse_output.py\nAuthor:\tIvo Taris, s2188724\n\"\"\"\n\nimport os\nimport sys\nimport re\n\n#the absolute path to the original reviews\ndirectory = '/home/s2188724/csicorpus/reviews_propname/'\n\nfor file in os.listdir(directory):\n\t\n\tif '_triples_with_frames.txt' in file:\n\t\n\t\t#for each file create an absolute path to it\n\t\tfilePath = os.path.join(directory, file)\n\t\t\n\t\t#create a new filename for each file to be tokenized\n\t\tnewFilePath = filePath[:-4] + '_processed' + filePath[-4:]\n\t\tnf = open(newFilePath,\"w+\")\n\t\t\n\t\twith open(filePath) as f:\n\t\t\tfor line in f.readlines():\n\t\t\t\t\n\t\t\t\t#split on the \"/\" seperator\n\t\t\t\tfields = line.split('|')\n\t\t\t\t\n\t\t\t\tif len(fields) > 0 and fields[0] != 'top/top':\n\n\t\t\t\t\tlemma1 = fields[0].split('/')[0]\n\t\t\t\t\tlemma2 = fields[3].split('/')[0]\n\t\t\t\t\tpostag1 = fields[1]\n\t\t\t\t\tpostag2 = fields[4]\n\t\t\t\t\trelation = fields[2]\n\t\n\t\t\t\t\tnf.write(lemma1 + \"\\t\" + postag2 + \"\\t\" + relation + \"\\t\" + lemma2 + \"\\t\" + postag2 + \"\\n\")\n\t\t\t\t\n\t\tnf.close()\n\t\tf.close()\n\t\n","sub_path":"process_parse_output.py","file_name":"process_parse_output.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"620442106","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 ('personal_center', '0005_auto_20190513_1614'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Appendix',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255, verbose_name='\\u6587\\u4ef6\\u540d\\u79f0')),\n ('path', models.FilePathField(verbose_name='\\u6587\\u4ef6\\u5730\\u5740')),\n ],\n ),\n migrations.AddField(\n model_name='apply',\n name='appendix',\n field=models.ForeignKey(verbose_name='\\u9644\\u4ef6', blank=True, to='personal_center.Appendix', null=True),\n ),\n ]\n","sub_path":"personal_center/migrations/0006_auto_20190520_1300.py","file_name":"0006_auto_20190520_1300.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"281352608","text":"#!/usr/bin/env python3\nimport aiohttp\nimport argparse\nimport os\nimport asyncio\nimport json\nfrom bs4 import BeautifulSoup\n\n# initialize argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"url\", help=\"URL of the docukent\")\nparser.add_argument(\"name\", help=\"Number of pages\")\nargs = parser.parse_args()\n\ntry:\n os.mkdir(args.name)\nexcept FileExistsError:\n print(\"A corresponding folder folder already exists - overwriting anything inside\")\n\n\nasync def fetch():\n \"\"\" Actual asynchronous fetching method \"\"\"\n print(\"Fetching document page\")\n async with aiohttp.ClientSession() as session:\n # get the document page\n async with session.get(args.url) as response:\n text = await response.text()\n # parse the document page\n parsed = BeautifulSoup(text, \"html.parser\")\n # gets the required script text\n text = parsed.find_all(\"script\")[1].text # second script is the one we want\n # slicing the relevant part out of the script\n subs = text[text.find(\"pages\"):]\n subs = subs[subs.find('['):subs.find(']')+1]\n elements = json.loads(subs)\n images = tuple(map(lambda obj: obj[\"id\"], elements))\n print(\"Concurrently loading individual images - patience\")\n # starting individual tasks that load each image independently\n tasks = []\n for i in range(len(images)):\n tasks.append(fetch_image(i, images[i], session))\n await asyncio.gather(*tasks)\n\n\nasync def fetch_image(index: int, num: int, session: aiohttp.ClientSession):\n async with session.get(f\"http://wwii.germandocsinrussia.org/pages/{num}/zooms/8\", timeout=20*60) as response:\n image = await response.read() # read binary data\n with open(f\"{args.name}/{index}.jpg\", 'wb') as output:\n output.write(image)\n print(f\"saved index {index} - image id {num}!\")\n\nasyncio.get_event_loop().run_until_complete(fetch())\nprint(\"Finished\")\n","sub_path":"rusfetch.py","file_name":"rusfetch.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"495010990","text":"#Napisz pierwszy skrypt, w którym zadeklarujesz po dwie zmienne każdego typu a następnie wyświetl te zmienne\ndef zad_1():\n a = 1\n b = \"abc\"\n\n print(a, b)\n print(\"\\n-----------------------------\\n\")\n int1 = 10\n int2 = 123456789\n\n float1, float2 = 3.1415, -0.121\n\n complex1 = 1 + 1j\n complex2 = 2 - 3j\n\n string1 = 'Cos tam'\n string2 = 'jajo'\n print('int:', int1, int2)\n print('float:', float1, float2)\n print('complex:', complex1, complex2)\n print('string:', string1, string2)\n# wywolane zadan\nzad_1()","sub_path":"wd_cw01/Zad_1.py","file_name":"Zad_1.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"439481430","text":"import gym\nimport numpy as np\nimport gym_SmartPrimer.agents.baselineV2 as Baseline\nimport pickle\nimport argparse\n\n\n\n\n\nparser = argparse.ArgumentParser(description='example')\nparser.add_argument('--seed', type=int, default=0,\n help='numpy seed ')\nparser.add_argument('--time', type=int, default=1,\n help='numpy seed ')\nargs = parser.parse_args()\nnp.random.seed(args.seed)\n\n#create the environment\nenv = gym.make('gym_SmartPrimer:SmartPrimer-realistic-v2')\nagent = Baseline.BaselineAgent(env.action_space)\n\n#define number of children to simulate\nepisode_count = 500\n\nreward = 0\ndone = False\n\nfor i in range(episode_count):\n #get the new children\n ob = env.reset()\n while True:\n action = agent.act(ob, reward, done)\n ob, reward, done, Baseinfo = env.step(action)\n # if (i%500==0):\n # print(ob)\n # print(reward)\n # print(done)\n if done:\n agent.reset()\n break\n\n \n#make the plots\nenv.render()\nperformance = env.info['Performance']\nimprovement = env.info['Improvement']\n \npickle_name = '/Users/jiequanzhang/Desktop/smart_primer/gym-SmartPrimer/pickles/per_baseline_'+str(args.seed)+'.pickle'\nwith open(pickle_name , 'wb') as handle:\n pickle.dump(performance, handle, protocol=pickle.HIGHEST_PROTOCOL) \npickle_name = '/Users/jiequanzhang/Desktop/smart_primer/gym-SmartPrimer/pickles/imp_baseline_'+str(args.seed)+'.pickle'\nwith open(pickle_name , 'wb') as handle:\n pickle.dump(improvement, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \nactionInfo = env.info['actionInfo'] \npickle_name = '/Users/jiequanzhang/Desktop/smart_primer/gym-SmartPrimer/pickles/actionInfo_baseline_'+str(args.seed)+'.pickle'\nwith open(pickle_name , 'wb') as handle:\n pickle.dump(actionInfo, handle, protocol=pickle.HIGHEST_PROTOCOL) \n ","sub_path":"gym_SmartPrimer/examples/exampleBaselineSherry.py","file_name":"exampleBaselineSherry.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"140177986","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 7 13:42:06 2017\n\n@author: lagerwer\n\"\"\"\n\nimport numpy as np\nimport CT_CIRC_CONE_class as CT\nimport odl\nimport sup_func_MRFDK as sup\n#import algorithm_class as alg\n#from scipy.ndimage import uniform_filter\nimport image_measures as im\nimport pylab\nimport time\n#from skimage.util.arraycrop import crop\n# %%\npylab.close('all')\nstart = time.time()\ndef four_filt_interp(hf, CT_small, CT_big):\n size = np.size(hf)\n xp = np.linspace(0, np.pi, size)\n fp = np.real(np.asarray(hf))\n size2 = np.size(CT_big.fourier_filter_space)\n x = np.linspace(0, np.pi, size2)\n const = CT_small.conv_op.rs_filt.range.weighting.const / \\\n CT_big.conv_op.rs_filt.range.weighting.const\n return CT_big.fourier_filter_space.element(np.interp(x, xp, fp)) * const\ndef filt_interp(h, CT_small, CT_big):\n size = np.size(h)\n xp = np.linspace(0, np.pi, size)\n fp = (np.asarray(h))\n size2 = np.size(CT_big.filter_space)\n x = np.linspace(0, np.pi, size2)\n const = CT_big.conv_op.rs_filt.range.weighting.const / \\\n CT_small.conv_op.rs_filt.range.weighting.const\n\n return CT_big.filter_space.element(np.interp(x, xp, fp)) * const\n# %%\n# Note that the original object must be 4/5 of the amount of pixels\npix = 256\nvoxels = [pix, pix, pix]\n\n# Threshold for the nonuniform bin size in u and v direction\nbin_param = 2\n\n# Amount of source positions on the scanning curve\nangles = 360\n# Source radius and detector radius\n# !!! Note that for this to work we must have: det_rad = 0\nsrc_rad = 10 # expressed in object sizes\ndet_rad = 0\n# Gaussian or Poisson noise expressed respectively in percentage of the mean and maximum intensity I_0\nnoise = ['Poisson', 2 ** 8 - 1]\nphantom = 'Shepp-Logan'\n\npath = 'results/dump/'\n# %%\npix2 = [256]\nvoxels2 = [pix2, pix2, pix2]\n\n# Amount of source positions on the scanning curve\nangles2 = 360\n# Source radius and detector radius\n\nphantom2 = 'Var obj'\npath = 'results/dump/'\n\n\n# %%\ncase = CT.CT_CIRC_CONE(voxels, angles, bin_param, src_rad, det_rad, phantom,\n noise, sparse_meth='nearest')\n\ncase.do_alg('MRT_FDK', exp='yes', lam=2e-9)\ncase.do_alg('FDK', exp='yes', filt_type='Hann')\n#case.MR_FDK.rec(0).show()\nhf_big = case.MRT_FDK.hf[0]\ncase.make_table_results()\n\nt1 = time.time()\nprint(t1- start, ' finished computing filters and reconstructions')\n# %%\ncase2 = CT.CT_CIRC_CONE(voxels, angles2, bin_param, src_rad, det_rad, phantom2,\n noise, sparse_meth='nearest')\n\n#hf_big.show()\nhf_big = four_filt_interp(hf_big, case, case2)\ncase2.do_alg('FDK', exp='yes',filt_type='Hann')\ncase2.set_results('MRT_FDK', exp='yes', hf=hf_big)\ncase2.make_table_results()\ncase2.MRT_FDK.rec(0).show()\n\nt2 = time.time()\nprint(t2-t1, 'finished computing reconstructions with other filter')\n\n\n\n\n\n\n","sub_path":"Reusable_filt_angles.py","file_name":"Reusable_filt_angles.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"632758879","text":"from LALA.library.device.device import log_save\nfrom LALA.framework.exceptions import *\n\n\nclass ICMP(object):\n\n def __init__(self, session):\n self.session = session\n self._clear_parameters()\n\n def _clear_parameters(self):\n self.dst = ''\n self.result = ''\n self.package_num = 3 # default is 3\n self.timeout = 1 # in seconds\n self.retry_times = 1\n self.background = False\n\n def _send_traffic(self, dst, pkg_num, timeout, bg):\n output = ''\n if ':' in dst:\n if bg:\n self.session.ssh.cmd('sh -c \"nohup ping6 -n {dst} -c {pkg_num} &\"; sleep 1; echo ok'.format(dst=dst, pkg_num=pkg_num))\n else:\n output = self.session.ssh.cmd('ping6 -n ' + dst + ' -c ' + pkg_num)\n else:\n if bg:\n self.session.ssh.cmd('sh -c \"nohup ping {dst} -c {pkg_num} -W {timeout} &\"; sleep 1; echo ok'.format(dst=dst, pkg_num=pkg_num, timeout=timeout))\n else:\n output = self.session.ssh.cmd('ping ' + dst + ' -c ' + pkg_num + ' -W ' + timeout)\n return output\n\n @log_save('Send ICMP traffic', 'API')\n def send(self):\n \"\"\"\n Use pc send ICMP packets to destination\n\n :param str dst: destination ip \n :param str result: allow/deny--check all received or 0 received, default is None--do not check result \n :param int package_num: number of packets you want to send, default is 3 \n :param int timeout: number of seconds to wait for response, default is 1, take effect for ping, not ping6 \n :param int retry_times: the maximum number of retries, default is 1 \n :param bool background: send traffic at background, default is False\n\n :rtype: Nonelist\n :return: None\n\n Code Example::\n\n pc.client.ICMP.dst=\"188.138.95.5\"\n pc.client.ICMP.result=\"allow\"\n pc.client.ICMP.package_num = 3 # default is 3 \n pc.client.ICMP.timeout = 1 # default is 1 second \n pc.client.ICMP.retry_times = 1\n pc.client.ICMP.send()\n\n\n \"\"\"\n\n dst = self.dst\n result = self.result\n pkg_num = str(self.package_num)\n timeout = str(self.timeout)\n retry_times = self.retry_times\n bg = self.background\n\n self.session.log.info('Running API: %s, dst: %s, package_num: %s, result: %s, timeout: %s, retry_times: %s, background: %s' % (\n 'send_icmp_traffic', dst, pkg_num, result, timeout, str(retry_times), bg))\n\n result_value = ''\n if result:\n if result.lower() == 'allow' or result.lower() == 'deny':\n result_value = result.lower()\n else:\n self.session.wgassert.should_be_true(False, IllegalInputError,\n 'result:%s is valid.',\n 'result:%s not support, result must be \"allow\" or \"deny\".' % result)\n else:\n self.session.log.info('Sent %s packets, will NOT check the result.' % pkg_num)\n\n for i in range(retry_times + 1):\n self.session.log.info('start ping... NO.%s >>>' % str(i+1))\n output = self._send_traffic(dst, pkg_num, timeout, bg)\n if result_value == 'allow':\n if pkg_num + ' packets transmitted, ' + pkg_num + ' packets received' in output:\n break\n else:\n self.session.log.warn(\n pkg_num + ' packets transmitted, ' + pkg_num + ' packets received' + ' not in output')\n if i + 1 > retry_times:\n self.session.wgassert.should_be_true(False, ExpectICMPAllowError,\n 'The maximum number of retries has not been reached.',\n 'The maximum number of retries has been reached.')\n elif result_value == 'deny':\n if pkg_num + ' packets transmitted, 0 packets received' in output:\n break\n else:\n self.session.log.warn(pkg_num + ' packets transmitted, 0 packets received' + ' not in output')\n if i + 1 > retry_times:\n self.session.wgassert.should_be_true(False, ExpectICMPDenyError,\n 'The maximum number of retries has not been reached.',\n 'The maximum number of retries has been reached.')\n else:\n break\n\n self._clear_parameters()\n\n","sub_path":"client/ICMP.py","file_name":"ICMP.py","file_ext":"py","file_size_in_byte":4784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"600610420","text":"def rabbit_jumping(n, w):\r\n if n == 0 or n == 1:\r\n w.write('1')\r\n elif n == 2:\r\n w.write('2')\r\n else:\r\n first = 1\r\n second = 2\r\n third = 0\r\n i = 2\r\n while i != n:\r\n third = (first + second) % 1000000007\r\n first = second % 1000000007\r\n second = third % 1000000007\r\n i = i + 1\r\n w.write(str(third))\r\n\r\n\r\nf = open('input.txt')\r\nm = int(f.readline())\r\nw = open('output.txt', 'w')\r\nrabbit_jumping(m, w)","sub_path":"reccurency/rabbit.py","file_name":"rabbit.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"396009230","text":"# 네이버의 실시간 검색어를 크롤링하여 가져오는 프로그램\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nreq = requests.get('https://www.naver.com/')\nsource = req.text # req 변수에 저장된 HTML소스를 가져옴\nsoup = BeautifulSoup(source, 'html.parser')\n\ntop_list = soup.select(\n \"#PM_ID_ct > div.header > div.section_navbar > div.area_hotkeyword.PM_CL_realtimeKeyword_base > div.ah_list.PM_CL_realtimeKeyword_list_base > ul > li > a.ah_a > span.ah_k\")\nfor top in top_list:\n print(top.text)\n","sub_path":"src/real_time.py","file_name":"real_time.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"37929473","text":"# -*- coding: utf-8 -*-\n\n#\n# Author: Tomi Jylhä-Ollila, Finland 2016-2019\n#\n# This file is part of Kunquat.\n#\n# CC0 1.0 Universal, http://creativecommons.org/publicdomain/zero/1.0/\n#\n# To the extent possible under law, Kunquat Affirmers have waived all\n# copyright and related or neighboring rights to Kunquat.\n#\n\nfrom copy import deepcopy\nimport itertools\nimport re\n\nimport kunquat.tracker.config as config\n\n\nclass StyleManager():\n\n _STYLE_DEFAULTS = {\n 'border_thick_radius' : 0.4,\n 'border_thick_width' : 0.2,\n 'border_thin_radius' : 0.2,\n 'border_thin_width' : 0.1,\n 'combobox_arrow_size' : 0.8,\n 'combobox_button_size' : 0.6,\n 'dialog_button_width' : 9.0,\n 'dialog_icon_size' : 7.0,\n 'file_dialog_icon_size' : 1.5,\n 'large_padding' : 0.8,\n 'list_button_size' : 2.0,\n 'list_button_padding' : 0.2,\n 'medium_padding' : 0.4,\n 'menu_arrow_size' : 1.0,\n 'radio_border_radius' : 0.499,\n 'radio_check_size' : 1.0,\n 'radio_check_spacing' : 0.5,\n 'scrollbar_margin' : 1.1,\n 'scrollbar_size' : 1.2,\n 'sheet_grid_line_width' : 0.1,\n 'slider_handle_size' : 3.0,\n 'slider_thickness' : 1.0,\n 'small_padding' : 0.2,\n 'splitter_width' : 0.4,\n 'tab_bar_margin' : 0.4,\n 'tiny_arrow_button_size' : 0.9,\n 'tiny_padding' : 0.1,\n 'tool_button_size' : 3.4,\n 'tool_button_padding' : 0.62,\n 'typewriter_button_size' : 5.6,\n 'typewriter_padding' : 2.9,\n }\n\n _STYLE_COLOUR_DEFAULTS = {\n 'bg_colour' : '#4c474e',\n 'fg_colour' : '#dbdbdb',\n 'bg_sunken_colour' : '#2b2238',\n 'disabled_fg_colour' : '#969696',\n 'important_button_bg_colour' : '#d5412c',\n 'important_button_fg_colour' : '#fff',\n 'active_indicator_colour' : '#ff2020',\n 'conns_bg_colour' : '#111',\n 'conns_edge_colour' : '#ccc',\n 'conns_focus_colour' : '#f72',\n 'conns_port_colour' : '#eca',\n 'conns_invalid_port_colour' : '#f33',\n 'conns_inst_bg_colour' : '#335',\n 'conns_inst_fg_colour' : '#def',\n 'conns_effect_bg_colour' : '#543',\n 'conns_effect_fg_colour' : '#fed',\n 'conns_proc_voice_bg_colour' : '#255',\n 'conns_proc_voice_fg_colour' : '#cff',\n 'conns_proc_voice_selected_colour' : '#9b9',\n 'conns_proc_mixed_bg_colour' : '#525',\n 'conns_proc_mixed_fg_colour' : '#fcf',\n 'conns_master_bg_colour' : '#353',\n 'conns_master_fg_colour' : '#dfd',\n 'envelope_bg_colour' : '#000',\n 'envelope_axis_label_colour' : '#ccc',\n 'envelope_axis_line_colour' : '#ccc',\n 'envelope_curve_colour' : '#68a',\n 'envelope_node_colour' : '#eca',\n 'envelope_focus_colour' : '#f72',\n 'envelope_loop_marker_colour' : '#7799bb',\n 'peak_meter_bg_colour' : '#000',\n 'peak_meter_low_colour' : '#191',\n 'peak_meter_mid_colour' : '#ddcc33',\n 'peak_meter_high_colour' : '#e21',\n 'peak_meter_clip_colour' : '#f32',\n 'position_bg_colour' : '#000',\n 'position_fg_colour' : '#6d6',\n 'position_stopped_colour' : '#555',\n 'position_play_colour' : '#6d6',\n 'position_record_colour' : '#d43',\n 'position_infinite_colour' : '#fd5',\n 'position_title_colour' : '#777',\n 'sample_map_bg_colour' : '#000',\n 'sample_map_axis_label_colour' : '#ccc',\n 'sample_map_axis_line_colour' : '#ccc',\n 'sample_map_focus_colour' : '#f72',\n 'sample_map_point_colour' : '#eca',\n 'sample_map_selected_colour' : '#ffd',\n 'sheet_area_selection_colour' : '#8ac',\n 'sheet_canvas_bg_colour' : '#111',\n 'sheet_column_bg_colour' : '#000',\n 'sheet_column_border_colour' : '#222',\n 'sheet_cursor_view_line_colour' : '#def',\n 'sheet_cursor_edit_line_colour' : '#f84',\n 'sheet_grid_level_1_colour' : '#aaa',\n 'sheet_grid_level_2_colour' : '#666',\n 'sheet_grid_level_3_colour' : '#444',\n 'sheet_header_bg_colour' : '#242',\n 'sheet_header_fg_colour' : '#cea',\n 'sheet_header_solo_colour' : '#7e6',\n 'sheet_ruler_bg_colour' : '#125',\n 'sheet_ruler_fg_colour' : '#acf',\n 'sheet_ruler_playback_marker_colour': '#d68',\n 'sheet_playback_cursor_colour' : '#6e6',\n 'sheet_trigger_default_colour' : '#cde',\n 'sheet_trigger_note_on_colour' : '#fdb',\n 'sheet_trigger_hit_colour' : '#be8',\n 'sheet_trigger_note_off_colour' : '#c96',\n 'sheet_trigger_warning_bg_colour' : '#e31',\n 'sheet_trigger_warning_fg_colour' : '#ffc',\n 'system_load_bg_colour' : '#000',\n 'system_load_low_colour' : '#191',\n 'system_load_mid_colour' : '#dc3',\n 'system_load_high_colour' : '#e21',\n 'text_bg_colour' : '#211d2c',\n 'text_fg_colour' : '#d9c7a9',\n 'text_selected_bg_colour' : '#36a',\n 'text_selected_fg_colour' : '#ffc',\n 'text_disabled_fg_colour' : '#8b7865',\n 'waveform_bg_colour' : '#000',\n 'waveform_focus_colour' : '#fa5',\n 'waveform_centre_line_colour' : '#666',\n 'waveform_zoomed_out_colour' : '#67d091',\n 'waveform_single_item_colour' : '#67d091',\n 'waveform_interpolated_colour' : '#396',\n 'waveform_loop_marker_colour' : '#dfd58e',\n }\n\n _STYLE_CONFIG_DEFAULTS = {\n 'def_font_size' : 0,\n 'def_font_family' : '',\n 'border_contrast' : 0.25,\n 'button_brightness' : 0.10,\n 'button_press_brightness' : -0.2,\n }\n\n _STYLE_CONFIG_DEFAULTS.update(_STYLE_COLOUR_DEFAULTS)\n _STYLE_DEFAULTS.update(_STYLE_CONFIG_DEFAULTS)\n\n _THEME_DEFAULT = ('default', 'default')\n\n def __init__(self):\n self._controller = None\n self._ui_model = None\n self._session = None\n self._share = None\n self._init_ss = None\n\n def set_controller(self, controller):\n self._controller = controller\n self._session = controller.get_session()\n self._share = controller.get_share()\n\n # Verify the existence of selected theme\n assert self._ui_model\n theme_id = self.get_selected_theme_id()\n theme_type, theme_name = theme_id\n if theme_type == 'share':\n theme_names = self._share.get_theme_names()\n elif theme_type == 'custom':\n theme_names = config.get_config().get_theme_names()\n else:\n return\n\n if theme_name not in theme_names:\n self.set_selected_theme_id(StyleManager._THEME_DEFAULT)\n\n def set_ui_model(self, ui_model):\n self._ui_model = ui_model\n\n def set_init_style_sheet(self, init_ss):\n self._init_ss = init_ss\n\n def get_init_style_sheet(self):\n return self._init_ss\n\n def get_style_sheet_template(self):\n return self._share.get_style_sheet('default')\n\n def get_icons_dir(self):\n return self._share.get_icons_dir()\n\n def get_style_param(self, key):\n config_style = self._get_config_style()\n return config_style.get(key, self._STYLE_DEFAULTS[key])\n\n def try_flush_cached_style(self):\n cached_theme_id = self._session.cached_theme_id\n if (not cached_theme_id) or (not self._session.is_cached_theme_modified):\n return\n\n assert cached_theme_id[0] == 'custom'\n\n cfg = config.get_config()\n if cfg.set_theme(cached_theme_id[1], self._session.cached_theme):\n self._session.is_cached_theme_modified = False\n else:\n print('Could not save cached theme')\n\n def set_style_param(self, key, value):\n assert self.get_selected_theme_id()[0] == 'custom'\n\n if self._session.cached_theme_id != self.get_selected_theme_id():\n self.try_flush_cached_style()\n\n config_style = self._get_config_style()\n\n config_style[key] = value\n if key.endswith('_colour'):\n # Make sure that all colours are stored if one is changed\n for k in self._STYLE_COLOUR_DEFAULTS.keys():\n if (k != key) and (k not in config_style):\n config_style[k] = self._STYLE_COLOUR_DEFAULTS[k]\n\n self._session.cached_theme_id = self.get_selected_theme_id()\n self._session.cached_theme = config_style\n self._session.is_cached_theme_modified = True\n\n def set_reference_font_height(self, height):\n self._session.set_reference_font_height(height)\n\n def get_scaled_size(self, size_norm, min_size=1):\n ref_height = self._session.get_reference_font_height()\n return max(min_size, int(round(size_norm * ref_height)))\n\n def get_scaled_size_param(self, size_param, min_size=1):\n size_norm = self.get_style_param(size_param)\n return self.get_scaled_size(size_norm, min_size)\n\n def get_colour_param_intensity(self, param):\n colour = self._get_colour_from_str(self.get_style_param(param))\n return self.get_colour_intensity(colour)\n\n def get_colour_intensity(self, colour):\n return (colour[0] * 0.212) + (colour[1] * 0.715) + (colour[2] * 0.072)\n\n def get_adjusted_colour(self, param, brightness):\n orig_colour = self._get_colour_from_str(self.get_style_param(param))\n adjusted_colour = (c + brightness for c in orig_colour)\n return self._get_str_from_colour(adjusted_colour)\n\n def get_scaled_colour(self, param, mult):\n orig_colour = self._get_colour_from_str(self.get_style_param(param))\n scaled_colour = (c * mult for c in orig_colour)\n return self._get_str_from_colour(scaled_colour)\n\n def get_link_colour(self, colour_param='fg_colour'):\n shift = (-0.3, 0.1, 0.6)\n fg_colour = self._get_colour_from_str(self.get_style_param(colour_param))\n return self._get_str_from_colour(c + s for (c, s) in zip(fg_colour, shift))\n\n def get_help_style(self, font_size):\n share = self._controller.get_share()\n stored_style = share.get_help_style()\n\n substs = {\n '{': '{{',\n '}': '}}',\n '<': '{',\n '>': '}',\n }\n\n patterns = ['/\\*.*?\\*/'] + [re.escape(k) for k in substs.keys()]\n preformat = re.compile('|'.join(patterns), re.DOTALL)\n pref_style = preformat.sub(lambda mo: substs.get(mo.group(0), ''), stored_style)\n\n kwargs = {\n 'pt': _SizeHelper(font_size, 'pt'),\n 'px': _SizeHelper(self.get_scaled_size(1), 'px'),\n 'col': _ColourHelper(self),\n }\n\n final_style = pref_style.format(**kwargs)\n return final_style\n\n def get_stock_theme_ids(self):\n names = self._share.get_theme_names()\n return [StyleManager._THEME_DEFAULT] + [('share', n) for n in names]\n\n def get_custom_theme_ids(self):\n cfg = config.get_config()\n return [('custom', name) for name in cfg.get_theme_names()]\n\n def set_selected_theme_id(self, theme_id):\n cfg = config.get_config()\n cfg.set_value('selected_theme_id', theme_id)\n\n def get_selected_theme_id(self):\n cfg = config.get_config()\n stored_theme_id = cfg.get_value('selected_theme_id')\n if not stored_theme_id:\n return ('default', 'default')\n return tuple(stored_theme_id)\n\n def create_new_theme(self):\n cur_theme_data = self.get_theme_data(self.get_selected_theme_id(), cache=False)\n if 'name' in cur_theme_data:\n new_name = 'Copy of {}'.format(cur_theme_data['name'])\n else:\n new_name = 'New theme'\n\n new_theme_data = dict(StyleManager._STYLE_CONFIG_DEFAULTS)\n new_theme_data.update(cur_theme_data)\n new_theme_data['name'] = new_name\n\n cfg = config.get_config()\n new_theme_id = ('custom', cfg.make_theme_name(new_name, unique=True))\n if not new_theme_id[1]:\n print('could not create a new theme ID')\n return\n\n cfg.set_theme(new_theme_id[1], new_theme_data)\n\n return new_theme_id\n\n def get_theme_data(self, theme_id, cache=True):\n theme_type, theme_name = theme_id\n\n if theme_type == 'share':\n theme = self._share.get_theme(theme_name)\n return theme\n\n elif theme_type == 'custom':\n if self._session.cached_theme_id == theme_id:\n return self._session.cached_theme\n theme = config.get_config().get_theme(theme_name)\n if cache:\n self.try_flush_cached_style()\n self._session.cached_theme_id = theme_id\n self._session.cached_theme = theme\n return theme\n\n elif theme_type == 'default':\n theme = dict(StyleManager._STYLE_CONFIG_DEFAULTS)\n theme['name'] = 'Default'\n return theme\n\n assert False\n\n def get_theme_name(self, theme_id):\n return self.get_theme_data(theme_id, cache=False).get('name') or ''\n\n def set_theme_name_and_get_new_id(self, theme_id, disp_name):\n theme_type, old_theme_name = theme_id\n assert theme_type == 'custom'\n\n if theme_id == self._session.cached_theme_id:\n self.try_flush_cached_style()\n self._session.cached_theme_id = None\n self._session.cached_theme = {}\n\n cfg = config.get_config()\n new_theme_name = cfg.make_theme_name(disp_name, unique=False)\n if new_theme_name != old_theme_name:\n new_theme_name = cfg.make_theme_name(disp_name, unique=True)\n if not (new_theme_name and cfg.rename_theme(old_theme_name, new_theme_name)):\n new_theme_name = old_theme_name\n\n new_theme_id = ('custom', new_theme_name)\n\n theme = cfg.get_theme(new_theme_name)\n theme['name'] = disp_name\n cfg.set_theme(new_theme_name, theme)\n\n if not self._session.cached_theme_id:\n self._session.cached_theme_id = new_theme_id\n self._session.cached_theme = theme\n self._session.is_cached_theme_modified = False\n\n return new_theme_id\n\n def remove_theme(self, theme_id):\n theme_type, theme_name = theme_id\n assert theme_type == 'custom'\n config.get_config().remove_theme(theme_name)\n\n if self._session.cached_theme_id == theme_id:\n self._session.cached_theme_id = None\n self._session.cached_theme = {}\n self._session.is_cached_theme_modified = False\n\n def _is_theme_colours_only(self, theme):\n allowed_keys = (\n 'name',\n 'border_contrast',\n 'button_brightness',\n 'button_press_brightness')\n return all((k.endswith('_colour') or (k in allowed_keys)) for k in theme.keys())\n\n def is_theme_stock(self, theme_id):\n theme_type, _ = theme_id\n return (theme_type != 'custom')\n\n def _get_colour_from_str(self, s):\n if len(s) == 4:\n cs = [s[1], s[2], s[3]]\n colour = tuple(int(c, 16) / 15 for c in cs)\n elif len(s) == 7:\n cs = [s[1:3], s[3:5], s[5:7]]\n colour = tuple(int(c, 16) / 255 for c in cs)\n else:\n assert False\n return colour\n\n def _get_str_from_colour(self, colour):\n clamped = [min(max(0, c), 1) for c in colour]\n cs = ['{:02x}'.format(int(c * 255)) for c in clamped]\n s = '#' + ''.join(cs)\n assert len(s) == 7\n return s\n\n def _get_config_style(self):\n return self.get_theme_data(self.get_selected_theme_id()) or {}\n\n\nclass _SizeHelper():\n\n def __init__(self, default_size, suffix):\n self._size = default_size\n self._suffix = suffix\n\n def __getitem__(self, index):\n rel_size = float(index)\n abs_size = int(round(self._size * rel_size))\n return '{}{}'.format(abs_size, self._suffix)\n\n\nclass _ColourHelper():\n\n def __init__(self, style_mgr):\n self._style_mgr = style_mgr\n\n def __getitem__(self, name):\n if name == 'link_fg':\n return self._style_mgr.get_link_colour('text_fg_colour')\n elif name == 'table_even_bg':\n bg_intensity = self._style_mgr.get_colour_param_intensity('text_bg_colour')\n brightness = 0.12 if bg_intensity < 0.5 else -0.12\n adjusted = self._style_mgr.get_adjusted_colour('text_bg_colour', brightness)\n return adjusted\n\n colour_param = '{}_colour'.format(name)\n return self._style_mgr.get_style_param(colour_param)\n\n\n","sub_path":"kunquat/tracker/ui/model/stylemanager.py","file_name":"stylemanager.py","file_ext":"py","file_size_in_byte":17966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"54340828","text":"\"\"\"\n\nauthor: Sean Trott\n\nA simple logic machine that builds a world model of \npropositions and relations between them, then performs\nelementary derivations (modus ponens, etc.)\nto discover new truths.\n\n\"\"\"\n\nfrom atom import *\n\n\n\nclass LogicMachine(object):\n\n\tdef __init__(self):\n\t\tself.rules = [] #KnowledgeBase class? List of rules?\n\t\tself.knowledge = []\n\t\tself.declarations = []\n\t\tself.relations = dict(implies=self.implies,\n\t\t\t\t \t\t conjunction=self.conjunction,\n\t\t\t\t \t\t disjunction=self.disjunction,\n\t\t\t\t \t\t exclusive_or=self.exclusive_or\n\t\t\t\t \t\t )\n\n\tdef eval_prop(self, prop):\n\t\tif type(prop) == Atom:\n\t\t\tif prop in self.knowledge:\n\t\t\t\ti = self.knowledge.index(prop)\n\t\t\t\treturn str(self.knowledge[i])\n\t\t\telse:\n\t\t\t\treturn \"I don't know about {}.\".format(prop.name)\n\t\telif type(prop) == Declaration:\n\t\t\treturn eval_prop(prop.left) + eval_prop(prop.right)\n\n\n\tdef add_to_KB(self, info):\n\t\tif type(info) == Atom:\n\t\t\tself.add_knowledge(info)\n\t\telif type(info) == Declaration:\n\t\t\tself.add_declaration(info)\n\t\telif type(info) == Rule:\n\t\t\tself.add_rule(info)\n\n\tdef add_rule(self, rule):\n\t\tself.rules.append(rule)\n\n\tdef add_rules(self, rules):\n\t\tself.rules += rules\n\n\tdef add_declaration(self, declaration):\n\t\tself.declarations.append(declaration)\n\n\tdef assess_declaration(self, declaration):\n\t\t#print(declaration)\n\t\trelation = self.relations[declaration.relation]\n\t\tif type(declaration.left) == Atom:\n\t\t\tleft_value = self.assess_atom(declaration.left)\n\t\telse:\n\t\t\tleft_value = self.assess_declaration(declaration.left)\n\t\tif type(declaration.right) == Atom:\n\t\t\tright_value = self.assess_atom(declaration.right)\n\t\telse:\n\t\t\tright_value = self.assess_declaration(declaration.right)\n\t\treturn relation(left_value, right_value)\n\n\tdef assess_atom(self, atom):\n\t\tfor prop in self.knowledge:\n\t\t\tif prop.name == atom.name:\n\t\t\t\treturn prop.value==atom.value\n\n\t# TODO: Modify adding declarations for \"or\". How to add knowledge in this way?\n\tdef add_knowledge(self, knowledge):\n\t\tif type(knowledge) == Atom:\n\t\t\tif not knowledge in self.knowledge:\n\t\t\t\tself.knowledge.append(knowledge)\n\t\t\telse:\n\t\t\t\tself.knowledge[self.knowledge.index(knowledge)] = knowledge\n\t\telse:\n\t\t\tself.add_knowledge(knowledge.left)\n\t\t\tself.add_knowledge(knowledge.right)\n\n\tdef assess_prop(self, prop):\n\t\tif type(prop) == Atom:\n\t\t\treturn self.assess_atom(prop)\n\t\t\t#return prop.value\n\t\telif type(prop) == Declaration:\n\t\t\treturn self.assess_declaration(prop)\n\t\telif type(prop) == Rule:\n\t\t\tprint(\"Fix this part. What to do if it's a rule? line 69, logic_machine.py\")\n\t\t\t#return self.assess_rule(prop)\n\n\tdef assess_rule(self, rule):\n\t\tleft = rule.left\n\t\tright = rule.right\n\t\tself.relations[rule.relation](left, right)\n\n\n\tdef derive_truth(self):\n\t\tfor rule in self.rules:\n\t\t\tself.assess_rule(rule)\n\n\n\tdef implies(self, p, q):\n\t\tif self.assess_prop(p):\n\t\t\tself.add_knowledge(q)\n\n\tdef conjunction(self, p, q):\n\t\treturn p and q\n\n\tdef disjunction(self, p, q):\n\t\treturn p or q\n\n\tdef exclusive_or(self, p, q):\n\t\treturn bool(p) ^ bool(q)\n\n\n\n\nrules = [Rule(Atom(\"p\", True), Atom(\"q\", True), \"implies\")]\nlm = LogicMachine()\nlm.add_rules(rules)\nlm.add_knowledge(Atom(\"p\", True))\n\ntest = Declaration(Atom(\"p\", True), Atom(\"q\", True), relation=\"xor\")\ntest2 = Declaration(test, Atom(\"p\", True), relation=\"or\")\n\nrule = Rule(test, Atom(\"r\", True), \"implies\")\nlm.add_rule(rule)\n\nrule3 = Rule(Atom(\"r\", True), Declaration(Atom(\"a\"), Atom(\"b\"), relation=\"or\"), \"implies\")\nlm.add_rule(rule3)\n","sub_path":"logic_machine.py","file_name":"logic_machine.py","file_ext":"py","file_size_in_byte":3418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"531019452","text":"# -*- coding: UTF-8 -*-\r\nimport csv\r\nimport math\r\nimport operator\r\nimport random\r\nimport numpy as np\r\nimport pandas as pd\r\nimport os \r\nfrom math import exp\r\nimport math\r\nimport sklearn \r\nfrom sklearn import svm \r\nfrom sklearn.model_selection import train_test_split\r\nbasedir = os.path.abspath(os.path.dirname(__file__))\r\n\r\ndef fit( weight_temp, train_ar,status):\r\n accuracy = np.zeros(10)\r\n for i in range (0,10):\r\n predict_right = 0\r\n predict_fail = 0\r\n for j in range(len(train_ar)):\r\n resuit_sum = 0\r\n for k in range(0,status):#\r\n resuit_sum = resuit_sum + (weight_temp[i][k] * train_ar[j][k]) \r\n te = weight_temp[i][k] * train_ar[j][k] #\r\n # print(te,weight_temp[i][k],train_ar[j][k],sep = ',')\r\n # if math.isnan(te) == False:\r\n # print(j,k)\r\n #print(j,resuit_sum,sep = \",\")\r\n \r\n if resuit_sum * (train_ar[j][status] - 1.5) > 0:#\r\n predict_right = predict_right + 1\r\n\r\n\r\n else:\r\n predict_fail = predict_fail + 1\r\n\r\n # print(predict_fail,predict_right,sep = \",\") \r\n # print(predict_fail + predict_right)\r\n accuracy[i] = predict_right/(predict_right + predict_fail) \r\n \r\n return accuracy\r\n\r\n\r\ndef SCA(generation,filename):\r\n\r\n \r\n path = \"data_train/\" + filename\r\n datafile = path #参数初始化\r\n data = pd.read_excel(datafile, header = None) #读取数据\r\n data1 = (data - data.mean())/data.std() #零-均值规范化\r\n\r\n train_ar = np.array(data1)\r\n #train_ar.dtype = 'float64'\r\n\r\n train_ar1 = train_ar\r\n\r\n\r\n\r\n status = np.shape(train_ar)[1]\r\n status = status - 1\r\n mean = data.mean()\r\n std = data.std()\r\n mest = np.zeros((2,status))\r\n\r\n\r\n##支持向量机\r\n\r\n # x,y=np.split(train_ar1,indices_or_sections=(status,),axis=1) #x为数据,y为标签 \r\n # train_data,test_data,train_label,test_label =sklearn.model_selection.train_test_split(x,y, random_state=1, train_size=0.8,test_size=0.2) \r\n\r\n # train_label.dtype = 'int64'\r\n # test_label.dtype = 'int64'\r\n\r\n # classifier=svm.SVC(C=2,kernel='rbf',gamma=10,decision_function_shape='ovo')\r\n\r\n # classifier.fit(train_data,train_label.ravel())\r\n\r\n # print(\"训练集:\",classifier.score(train_data,train_label)) \r\n # print(\"测试集:\",classifier.score(test_data,test_label)) \r\n##\r\n for i in range(0,status):\r\n mest[0][i] = mean[i]\r\n\r\n for i in range(0,status):\r\n mest[1][i] = std[i]\r\n\r\n file_name = filename.split('.')[0]\r\n\r\n mestpath = basedir + \"/standard/\" + file_name\r\n np.savetxt(mestpath,mest)\r\n\r\n\r\n\r\n\r\n weight_origin = 2 * np.random.random((10,status)) - 1\r\n #print(train_ar)\r\n fitness = fit(weight_origin , train_ar,status)\r\n best = 0\r\n max = 0\r\n for i in range(len(fitness)):\r\n if fitness[i] > max:\r\n max = fitness[i]\r\n best = i\r\n\r\n # for i in range(0,23):\r\n # weight_origin[9] = weight_origin[best] \r\n\r\n T = generation\r\n population_best = np.zeros(status + 1)#\r\n for i in range(0,status):\r\n population_best[i] = weight_origin[best][i]\r\n\r\n population_best[status] = fitness[best]\r\n weight_temp = weight_origin\r\n\r\n for FEs in range(T): \r\n a1 = 5\r\n\r\n if FEs < 100:\r\n r1= a1-2 * a1 /(pow(math.e,FEs/T)); # r1 decreases linearly from a to 0\r\n else:\r\n r1= a1-FEs*( (a1) / T );\r\n\r\n for i in range(0,10):\r\n \r\n # if i != best:\r\n\r\n for j in range(0,status):#\r\n \r\n r2 = random.uniform(0,3.1415926)\r\n r3 = random.uniform(0, 2)\r\n r4 = random.random() \r\n if r4 >= 0.5:\r\n weight_temp[i][j] = weight_temp[i][j] + r1*(math.sin(r2)) * abs((r3*population_best[j])-weight_temp[i][j])\r\n else:\r\n weight_temp[i][j] = weight_temp[i][j] + r1*(math.cos(r2)) * abs((r3*population_best[j])-weight_temp[i][j])\r\n\r\n fitness = fit(weight_temp , train_ar,status)\r\n max = 0\r\n \r\n for l in range(len(fitness)):\r\n \r\n if fitness[l] >= max:\r\n max = fitness[l]\r\n best = l\r\n\r\n for i in range(0,status):\r\n\r\n if population_best[status] < fitness[best]:\r\n\r\n population_best[i] = weight_temp[best][i]\r\n population_best[status] = fitness[best]\r\n\r\n\r\n\r\n print( population_best[status] , best )\r\n # print(population_best)\r\n #print(fitness[best], best, sep = \",\")\r\n weight_final = np.zeros(status)\r\n for i in range(0,status):\r\n\r\n weight_final[i] = weight_temp[best][i]\r\n \r\n return population_best\r\n\r\ndef train(generation,filename):\r\n \r\n weight_final = SCA(generation,filename)\r\n return weight_final\r\n \r\n\r\ndef Run(testSet):\r\n traingroup = []\r\n testLength = len(testSet)\r\n for x in range(testLength):\r\n testSet[x] = float(testSet[x])\r\n testSet[10] = round(testSet[10]*0.1,1)\r\n \r\n weight = train()\r\n result_sum = 0\r\n for i in range(testLength):\r\n result_sum =result_sum + (weight[i] * testSet[i])\r\n\r\n if result_sum > 0 :\r\n result = 1\r\n else:\r\n result = 0\r\n\r\n return result\r\n\r\n\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"533110760","text":"import numpy\nimport re\n\ndef txt_to_array(text, transpose=False, char_strip=[]):\n \"\"\"\n Converts a tab-delimited stream into a 2-d array\n inputs:\n text - an opened file to be translated into the tree\n transpose - if True, converts rows to columns and vice versa\n char_strip - list of characters to remove from array\n \"\"\"\n\n array = []\n for r in text:\n row_split = r.split('\\t')\n entries = []\n for e in row_split:\n for c in char_strip:\n e = e.replace(c, \"\")\n entries.append(e.strip())\n array.append(entries)\n\n if transpose: return numpy.transpose(array)\n else: return array\n\ndef rules_to_dictionary(rules_array, value_array, rule_class=''):\n \"\"\"\n takes an entry_array and rules_array and outputs into a tuple:\n ((rule, category, rule_footnote), (value, value_footnote))\n both inputs have to be more than length 1 and equal length\n entry_array[0] must be the zone code, rules_array[0] is ignored ignored\n rule class is the broad classification of rules - i.e. Development Regulations vs Use Regulations\n \"\"\"\n\n dictionary = {}\n for i in range(1, len(value_array)):\n category = ''\n footnotes = []\n rule = rules_array[i]\n value = value_array[i]\n if '\\\\' in rule: # searches for the category delimiter\n rule_parts = [r.strip() for r in rule.split('\\\\')]\n category = rule_parts[0]\n rule = rule_parts[1]\n\n if '[' in rule: # searches for the footnote delimiter\n rule = rule.replace(']', '')\n rule_parts = [r.strip() for r in rule.split('[')]\n rule = rule_parts[0]\n footnotes.append(rule_parts[1])\n\n if '(' in value: # searches for the footnote delimter\n value = value.replace(')', '')\n value_parts = value.split('(')\n value = value_parts.pop(0)\n footnotes = footnotes + value_parts # add remaining parts to footnotes\n\n dictionary['\\\\'.join(filter(None, [rule_class, category, rule]))] = {\n 'class': rule_class, 'rule': rule, 'category': category, 'value': value, 'footnotes': footnotes}\n return dictionary\n\n# takes a string and replaces it with abbreviations, an array of tuples (full word, abbreviate)\ndef abbreviate(string, *abbreviations):\n string = string.lower()\n for a in abbreviations:\n string = string.replace(a[0].lower(), a[1].lower())\n return string\n\n#returns true if search matches string\ndef match_search(string, search, in_order=True):\n search = re.sub(r'\\W+', ' ', search).lower().strip()\n string = re.sub(r'\\W+', ' ', string).lower().strip()\n if search == string: return True\n else:\n for s in search.split(' '):\n if s not in string:\n return False\n else:\n if in_order:\n string = string.replace(s, '~').split('~')[-1]\n return True\n\n\n","sub_path":"calculations/TxtConverter.py","file_name":"TxtConverter.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"40848709","text":"def main():\n n = int(input())\n p = list(map(int, input().split()))\n loop = n - 3 + 1\n count = 0\n for i in range(loop):\n if p[i] < p[i + 1] < p[i + 2] or p[i + 2] < p[i + 1] < p[i]:\n count += 1\n print(count)\nmain() ","sub_path":"Python_codes/p02988/s588853693.py","file_name":"s588853693.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"627230459","text":"import argparse\r\nimport requests\r\nimport re\r\nimport json\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\n# Create argument parser object.\r\nparser = argparse.ArgumentParser(description='Process command line arguments')\r\n\r\n# Create required args group header.\r\nrequiredArgs = parser.add_argument_group('required arguments')\r\n\r\n# Call our object's add argument function.\r\nrequiredArgs.add_argument('-b','--bundleid', help='The bundle id of the app you wish to pull.', required=True)\r\n\r\n# Store our argument input.\r\nargs = parser.parse_args()\r\n\r\nurl = \"https://play.google.com/store/apps/details?id=\" + args.bundleid\r\npage = requests.get(url)\r\nsoup = BeautifulSoup(page.content, 'html.parser')\r\n\r\n\r\napp = {}\r\n\r\n# App name\r\napp['name'] = soup.title.get_text().replace(' - Apps on Google Play', '')\r\n\r\n# Cover art url\r\nfor img in soup.find_all('img'):\r\n if \"Cover art\" in str(img):\r\n app['cover art'] = img.get('src')\r\n break\r\n\r\n# App description\r\nfor desc in soup.find_all('meta'):\r\n if 'itemprop=\"description\"' in str(desc):\r\n app['description'] = desc.get('content')\r\n break\r\n\r\n# App version\r\nif len(soup.find_all(text=re.compile('Varies with device'))) > 0:\r\n app['version'] = 'Varies with device'\r\nelse:\r\n for span in soup.find_all('span'):\r\n if \"htlgb\" in str(span) and re.search('(?:(?:\\d+|[a-z])[.-]){2,}(?:\\d+|[a-z])', str(span)) and \"div\" not in str(span):\r\n app['version'] = span.contents[0]\r\n break\r\n\r\n# App updated date\r\nfor dates in soup.find_all('span'):\r\n if re.search('(January|February|March|April|May|June|July|August|September|October|November|December)\\s\\d\\d?,\\s\\d\\d\\d\\d', str(dates)):\r\n app['updated'] = dates.span.contents[0]\r\n break\r\n\r\n# Print JSON \r\nprint(json.dumps(app, indent=1))\r\n\r\n\r\ndef main():\r\n pass\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"API/Scraper-API/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"101910477","text":"from zeit.cms.testing import FunctionalTestCase\nimport os.path\nimport plone.testing\nimport unittest\nimport urllib\nimport xlrd\nimport zeit.brightcove.testing\nimport zeit.cms.tagging.testing\nimport zeit.cms.testing\nimport zeit.connector.interfaces\nimport zeit.content.article.testing\nimport zeit.content.image.testing\nimport zeit.imp.tests\nimport zeit.push.testing\nimport zeit.retresco.testing\nimport zope.component\nimport zope.component.hooks\n\n\nZCML_LAYER = zeit.cms.testing.ZCMLLayer(\n 'ftesting.zcml',\n product_config=(\n zeit.cms.testing.cms_product_config +\n zeit.content.article.testing.product_config +\n zeit.content.image.testing.product_config +\n zeit.imp.tests.product_config +\n zeit.push.testing.product_config +\n zeit.retresco.testing.product_config +\n zeit.brightcove.testing.product_config))\n\n\nclass SecurityPolicyLayer(plone.testing.Layer):\n\n defaultBases = (ZCML_LAYER, zeit.retresco.testing.TMS_MOCK_LAYER)\n\n def testSetUp(self):\n connector = zope.component.getUtility(\n zeit.connector.interfaces.IConnector)\n prop = connector._get_properties(\n 'http://xml.zeit.de/online/2007/01/Somalia')\n prop[zeit.cms.tagging.testing.KEYWORD_PROPERTY] = 'testtag'\n\nLAYER = SecurityPolicyLayer()\n\n\ndef make_xls_test(*args):\n # Since pytest picks up all descendants of unittest.TestCase, we must mix\n # that in here instead of directly having XLSSheetCase inherit from\n # FunctionalTestCaseCommon.\n case = type(\n 'SecurityPolicyXLSSheetCase',\n (SecurityPolicyXLSSheetCase, FunctionalTestCase), {})\n return case(*args)\n\n\nclass SecurityPolicyXLSSheetCase(object):\n\n layer = LAYER\n\n def __init__(self, username, cases, description):\n super(SecurityPolicyXLSSheetCase, self).__init__()\n self.username = username\n self.cases = cases\n self.description = description\n\n self.browser = zeit.cms.testing.Browser()\n self.browser.raiseHttpErrors = False\n if username != 'anonymous':\n password = self.username + 'pw'\n self.browser.addHeader(\n 'Authorization', 'Basic %s:%s' % (self.username, password))\n\n def tearDown(self):\n self.connector._reset()\n super(SecurityPolicyXLSSheetCase, self).tearDown()\n\n def runTest(self):\n for skin, path, form, expected in self.cases:\n if skin.strip() == 'python:':\n test = self # needed by the eval() call below\n site = zope.component.hooks.getSite()\n zope.component.hooks.setSite(self.getRootFolder())\n try:\n # XXX pass variables in explicitly\n eval(path)\n finally:\n zope.component.hooks.setSite(site)\n continue\n path_with_skin = 'http://localhost/++skin++%s%s' % (skin, path)\n path_with_skin = path_with_skin % dict(username=self.username)\n\n if form:\n self.browser.post(\n # XXX pass variables in explicitly\n path_with_skin, urllib.urlencode(eval(form)))\n else:\n self.browser.open(path_with_skin)\n\n status, msg = self.browser.headers['Status'].split(' ', 1)\n self.assertEquals(\n (int(status) < 400), expected,\n '%s: %s (expected <400: %s)\\n%s' % (\n path.encode('utf8'), status, bool(expected),\n self.browser.contents))\n\n def __str__(self):\n return '%s (%s.%s)' % (\n self.description,\n self.__class__.__module__, self.__class__.__name__)\n\n @property\n def connector(self):\n return zope.component.getUtility(zeit.connector.interfaces.IConnector)\n\n\ndef test_suite():\n book = xlrd.open_workbook(os.path.join(\n os.path.dirname(__file__), 'test.xls'))\n sheet = book.sheet_by_index(0)\n\n suite = unittest.TestSuite()\n\n username_row = 1\n username_column_start = 3\n\n for expected_column in xrange(username_column_start, sheet.ncols):\n username = sheet.cell_value(username_row, expected_column)\n if not username:\n continue\n\n cases = []\n start_row = None\n for row in xrange(2, sheet.nrows):\n if start_row is None:\n start_row = row\n skin = sheet.cell_value(row, 0)\n path = sheet.cell_value(row, 1)\n form = sheet.cell_value(row, 2)\n expected = sheet.cell_value(row, expected_column)\n if path:\n cases.append((skin, path, form, expected))\n if cases and (not path or row == sheet.nrows - 1):\n description = 'test.xls rows %d-%d for %s' % (\n start_row + 1, row, username)\n suite.addTest(make_xls_test(username, cases, description))\n cases = []\n start_row = None\n\n # Picked up by gocept.pytestlayer (the layer on the XLSCase is ignored)\n suite.layer = LAYER\n return suite\n","sub_path":"src/zeit/securitypolicy/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"514181131","text":"def my_squares(iters):\n import scipy as sc\n out = sc.zeros(iters)\n for i in range(iters):\n out[i] = i ** 2\n return out\n\ndef my_join(iters, string):\n out = ''\n for i in range(iters):\n out += \", \" + string\n return out\n\ndef run_my_funcs(x,y):\n print(x,y)\n my_squares(x)\n my_join(x,y)\n return 0\n\nrun_my_funcs(10000000,\"My string\")","sub_path":"CodeSolution/profileme3.py","file_name":"profileme3.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"242759578","text":"import os\nimport unittest\n\nfrom coast.piece import Piece\nfrom coast.torrent import Torrent\nfrom coast.messages import PieceMessage, RequestMessage\nfrom coast.helpermethods import one_directory_back\nfrom coast.constants import REQUEST_SIZE\n\nfrom test.test_data import test_first_piece_message, test_piece_message\n\n\nclass PieceTests(unittest.TestCase):\n\n\tdef test_piece_creation(self):\n\t\ttest_peer_id = \"-CO0001-5208360bf90d\"\n\t\ttest_port = 6881\n\t\troot_dir = one_directory_back(os.getcwd())\n\t\ttest_data_directory = os.path.join(root_dir, \"test/\")\n\t\ttest_torrent_file = \"ubuntu-16.10-desktop-amd64.iso.torrent\"\n\t\ttest_torrent_file_path = os.path.join(test_data_directory, test_torrent_file)\n\t\ttest_torrent = Torrent(test_peer_id, test_port, test_torrent_file_path)\n\n\t\ttest_piece_size = test_torrent.metadata[\"piece_length\"]\n\t\ttest_piece_index = 0\n\t\ttest_piece_hash = test_torrent.pieces_hashes[test_piece_index]\n\t\ttest_download_location = test_torrent.download_root\n\n\t\ttest_piece_block = PieceMessage(index=0, begin=0, block=(\"A\"*REQUEST_SIZE))\n\t\ttest_piece = Piece(test_piece_size, test_piece_index, test_piece_hash, test_download_location)\n\t\ttest_request = RequestMessage(index=test_piece_block.get_index(),\n\t\t\t\t\t\t\t\t\t begin=test_piece_block.get_begin())\n\t\ttest_piece.add_non_completed_request_index(test_request)\n\t\tself.assertEqual(0.0, test_piece.progress)\n\t\ttest_piece.append_data(test_piece_block)\n\t\tself.assertEqual(3.125, test_piece.progress)\n\t\t# check to see if our bytes were downloaded\n\t\tself.assertEqual(16384, len([val for val in test_piece.data if val != 0]))\n\t\t# check to see if our next index is correct\n\t\tself.assertEqual(16384, test_piece.get_next_begin())\n","sub_path":"test/piece_tests.py","file_name":"piece_tests.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"641055263","text":"################################################\n#\n# Dag VAE (DAVAE) - Main Module\n# Code for the main module of the Dag VAE\n#\n################################################\nimport torch \nimport torch.nn as nn\nimport numpy as np\nimport math\nfrom torch.autograd import Variable\nfrom EncDec import Encoder, Decoder, Attention, fix_enc_hidden, gather_last\nimport torch.nn.functional as F\nimport DAG\nfrom Beam import Beam\nimport data_utils\nimport generate as ge\nfrom data_utils import EOS_TOK, SOS_TOK, PAD_TOK, TUP_TOK\n\nclass DAVAE(nn.Module):\n def __init__(self, emb_size, hsize, vocab, latents, cell_type=\"GRU\", layers=2, bidir=True, pretrained=True, use_cuda=True, dropout=0.10):\n \"\"\"\n Args:\n emb_size (int) : size of input word embeddings\n hsize (int or tuple) : size of the hidden state (for one direction of encoder). If this is an integer then it is assumed\n to be the size for the encoder, and decoder is set the same. If a Tuple, then it should contain (encoder size, dec size)\n\n latents (LatentNode) : The root of a latent node tree (Note: Size of latent embedding dims should be 2*hsize if bidir!)\n layers (int) : layers for encoder and decoder\n vocab (Vocab object)\n bidir (bool) : use bidirectional encoder?\n cell_type (str) : 'LSTM' or 'GRU'\n sos_idx (int) : id of the start of sentence token\n \"\"\"\n super(DAVAE, self).__init__()\n\n self.embd_size=emb_size\n self.vocab = vocab\n self.vocab_size=len(vocab.stoi.keys())\n self.cell_type = cell_type\n self.layers = layers\n self.bidir=bidir\n self.sos_idx = self.vocab.stoi[SOS_TOK]\n self.eos_idx = self.vocab.stoi[EOS_TOK]\n self.pad_idx = self.vocab.stoi[PAD_TOK]\n self.tup_idx = self.vocab.stoi[TUP_TOK]\n self.latent_root = latents\n self.latent_dim = self.latent_root.dim\n self.use_cuda = use_cuda\n \n\n if isinstance(hsize, tuple):\n self.enc_hsize, self.dec_hsize = hsize\n elif bidir:\n self.enc_hsize = hsize\n self.dec_hsize = 2*hsize\n else:\n self.enc_hsize = hsize\n self.dec_hsize = hsize\n\n in_embedding = nn.Embedding(self.vocab_size, self.embd_size, padding_idx=self.pad_idx)\n out_embedding = nn.Embedding(self.vocab_size, self.embd_size, padding_idx=self.pad_idx)\n if pretrained:\n print(\"Using Pretrained\")\n in_embedding.weight.data = vocab.vectors\n out_embedding.weight.data = vocab.vectors\n\n \n self.encoder = Encoder(self.embd_size, self.enc_hsize, in_embedding, self.cell_type, self.layers, self.bidir, use_cuda=use_cuda)\n self.decoder = Decoder(self.embd_size, self.dec_hsize, out_embedding, self.cell_type, self.layers, attn_dim=(self.latent_dim, self.dec_hsize), use_cuda=use_cuda, dropout=dropout)\n\n self.logits_out= nn.Linear(self.dec_hsize, self.vocab_size) #Weights to calculate logits, out [batch, vocab_size]\n self.latent_in = nn.Linear(self.latent_dim, self.layers*self.dec_hsize) #Compute the query for the latents from the last encoder output vector\n if use_cuda:\n self.decoder = self.decoder.cuda()\n self.encoder = self.encoder.cuda()\n self.logits_out = self.logits_out.cuda()\n self.latent_in = self.latent_in.cuda()\n\n else:\n self.decoder = self.decoder\n self.encoder = self.encoder\n self.logits_out = self.logits_out\n self.latent_in = self.latent_in\n\n def set_use_cuda(self, value):\n self.use_cuda = value\n self.encoder.use_cuda = value\n self.decoder.use_cuda = value\n self.decoder.attention.use_cuda = value\n self.latent_root.set_use_cuda(value)\n\n def forward(self, input, seq_lens, beam_size=-1, str_out=False, max_len_decode=50, min_len_decode=0, n_best=1, encode_only=False):\n \"\"\"\n Args\n input (Tensor, [batch, seq_len]) : Tensor of input ids for the embeddings lookup\n seq_lens (Tensor [seq_len]) : Store the sequence lengths for each batch for packing\n str_output (bool) : set to true if you want the textual (greedy decoding) output, for evaultation\n use a batch size of 1 if doing this\n encode_only (bool) : Just encoder the input and return dhidden (initial decoder hidden) and latents\n Returns\n : List of outputs of the decoder (the softmax distributions) at each time step\n : The latent variable values for all latents\n : The latent root\n \"\"\"\n batch_size = input.size(0)\n if str_out: #use batch size 1 if trying to get actual output\n assert batch_size == 1\n\n # INIT THE ENCODER\n ehidden = self.encoder.initHidden(batch_size)\n\n #Encode the entire sequence\n #Output gives each state output, ehidden is the final state\n #output (Tensor, [batch, seq_len, hidden*directions] \n #ehidden [batch, layers*directions, hidden_size]\n \n # RUN FORWARD PASS THROUGH THE ENCODER\n enc_output, ehidden = self.encoder(input, ehidden, seq_lens) \n \n # LATENT STUFF #\n if self.use_cuda:\n enc_output_avg = torch.sum(enc_output, dim=1) / Variable(seq_lens.view(-1, 1).type(torch.FloatTensor).cuda())\n else:\n enc_output_avg = torch.sum(enc_output, dim=1) / Variable(seq_lens.view(-1, 1).type(torch.FloatTensor))\n\n initial_query = enc_output_avg\n\n latent_values, diffs = self.latent_root.forward(enc_output, seq_lens, initial_query) #[batch, num_latents, dim], get the quantized vectors for all latents\n\n # LATENT STUFF #\n\n top_level = latent_values[:, 0, :]\n\n dhidden = torch.nn.functional.tanh(self.latent_in(top_level).view(self.layers, batch_size, self.dec_hsize))\n\n if encode_only:\n if self.use_cuda:\n self.decoder.init_feed_(Variable(torch.zeros(batch_size, self.decoder.attn_dim)).cuda())\n else:\n self.decoder.init_feed_(Variable(torch.zeros(batch_size, self.decoder.attn_dim)))\n return dhidden, latent_values\n\n #Decode output one step at a time\n #THIS IS FOR TESTING/EVALUATING, FEED IN TOP OUTPUT AS INPUT (GREEDY DECODE)\n if str_out:\n if beam_size <=0:\n # GREEDY Decoding\n if self.use_cuda:\n self.decoder.init_feed_(Variable(torch.zeros(batch_size, self.decoder.attn_dim).cuda())) #initialize the input feed 0\n else:\n self.decoder.init_feed_(Variable(torch.zeros(batch_size, self.decoder.attn_dim))) \n\n return self.greedy_decode(input, dhidden, latent_values, max_len_decode)\n else:\n # BEAM Decoding \n return self.beam_decode(input, dhidden, latent_values, beam_size, max_len_decode, min_len_decode=min_len_decode)\n\n\n # This is for TRAINING, use teacher forcing \n if self.use_cuda:\n self.decoder.init_feed_(Variable(torch.zeros(batch_size, self.decoder.attn_dim).cuda())) #initialize the input feed 0\n else:\n self.decoder.init_feed_(Variable(torch.zeros(batch_size, self.decoder.attn_dim)))\n\n return self.train(input, batch_size, dhidden, latent_values, diffs)\n\n\n def train(self, input, batch_size, dhidden, latent_values, diffs, return_hid=False, use_eos=False):\n\n dec_outputs = []\n\n if use_eos:\n input_size = input.size(1) + 1\n else:\n input_size = input.size(1) #Dont need to process last since no eos\n\n for i in range(input_size):\n #Choose input for this step\n if i == 0:\n tens = torch.LongTensor(input.shape[0]).zero_() + self.sos_idx\n if self.use_cuda:\n dec_input = Variable(tens.cuda()) #Decoder input init with sos\n else:\n dec_input = Variable(tens)\n else: \n dec_input = input[:, i-1]\n\n dec_output, dhidden = self.decoder(dec_input, dhidden, latent_values) \n dec_outputs += [dec_output]\n \n dec_outputs = torch.stack(dec_outputs, dim=0) #DIMENSION SHOULD BE [Seq x batch x dec_hidden]\n\n if return_hid:\n return latent_values, self.latent_root, dhidden, dec_outputs #, (diffs_hid1, diffs_hid2)\n else:\n self.decoder.reset_feed_() #reset input feed so pytorch correctly cleans graph\n return latent_values, self.latent_root, diffs, dec_outputs #, (diffs_hid1, diffs_hid2)\n\n\n def greedy_decode(self, input, dhidden, latent_values, max_len_decode):\n\n outputs = []\n dec_input = Variable(torch.LongTensor(input.shape[0]).zero_() + self.sos_idx) \n prev_output = Variable(torch.LongTensor(input.shape[0]).zero_() + self.sos_idx)\n\n if self.decoder.input_feed is None:\n if self.use_cuda:\n self.decoder.init_feed_(Variable(torch.zeros(1, self.decoder.attn_dim).cuda())) #initialize the input feed 0\n else:\n self.decoder.init_feed_(Variable(torch.zeros(1, self.decoder.attn_dim))) \n\n for i in range(max_len_decode):\n if i == 0: #first input is SOS (start of sentence)\n dec_input = Variable(torch.LongTensor(input.shape[0]).zero_() + self.sos_idx)\n else:\n dec_input = prev_output\n #print(\"STEP {} INPUT: {}\".format(i, dec_input.data))\n\n dec_output, dhidden = self.decoder(dec_input, dhidden, latent_values)\n logits = self.logits_out(dec_output)\n\n probs = F.log_softmax(logits, dim=1)\n top_vals, top_inds = probs.topk(1, dim=1)\n \n outputs.append(top_inds.squeeze().data[0])\n prev_output = top_inds\n\n if top_inds.squeeze().data[0] == self.eos_idx:\n break\n\n self.decoder.reset_feed_() #reset input feed so pytorch correctly cleans graph\n return outputs\n\n\n def beam_decode(self, input, dhidden, latent_values, beam_size, max_len_decode, n_best=1, use_constraints=True, min_len_decode=0, init_beam=False):\n # dhidden [1, 1, hidden_size]\n # latent_values [1,3, hidden_size]\n\n # Fixed these values here for now\n batch_size = 1\n assert beam_size >= n_best, \"n_best cannot be greater than beam_size.\"\n\n # Helper functions for working with beams and batches\n def var(a): return Variable(a, volatile=True) \n\n def bottle(m):\n return m.view(batch_size * beam_size, -1)\n\n def unbottle(m):\n return m.view(beam_size, batch_size, -1)\n\n def beam_update(e, idx, positions, beam_size): \n sizes = e.size() # [1, beam_size, hidden_size] \n br = sizes[1] \n if len(sizes) == 3:\n sent_states = e.view(sizes[0], beam_size, br // beam_size,\n sizes[2])[:, :, idx]\n else:\n sent_states = e.view(sizes[0], beam_size,\n br // beam_size,\n sizes[2],\n sizes[3])[:, :, idx]\n\n # [1, beam_size, hidden_size]\n #print(\"POS: {}\".format(positions)) \n indexed_before = sent_states.data.index_select(1, positions)\n #print(\"INDEXED BEFORE: {}\".format(indexed_before))\n sent_states.data.copy_(\n sent_states.data.index_select(1, positions)) \n indexed_after = sent_states.data.index_select(1, positions) \n #print(\"INDEXED BEFORE: {}\".format(indexed_before))\n # TESTED that this does change so not always True depending on the positions above\n #print(\"STATE SAME? {}\".format(indexed_after.equal(indexed_before)))\n \n\n # 1. everything needs to be repeated for the beams\n # dec_input [beam_size] # prev_output [beam_size]\n \n # [1, beam_size, hidden_size]\n dhidden = dhidden.repeat(1, beam_size, 1) \n # [beam_size, hidden_size, 3]\n latent_values = latent_values.repeat(beam_size, 1, 1)\n\n # init after repeating everything\n if init_beam: #Init with the current input feed\n self.decoder.input_feed = self.decoder.input_feed.repeat(beam_size, 1) \n else:\n # init with beam_size zero\n if self.use_cuda:\n self.decoder.init_feed_(var(torch.zeros(beam_size, self.decoder.attn_dim).cuda())) #initialize the input feed 0\n else:\n self.decoder.init_feed_(var(torch.zeros(beam_size, self.decoder.attn_dim))) \n\n \n # 2. beam object as we have batch_size 1 during decoding\n beam = [Beam(beam_size, n_best=n_best,\n cuda=self.use_cuda,\n pad=1,\n eos=self.eos_idx,\n bos=self.sos_idx,\n min_length=10)] \n \n if init_beam: #if init_beam is true, then input will be the initial input to init beam with\n for b in beam:\n b.next_ys[0][0] = np.asscalar(input.data.numpy()[0])\n \n verb_list = [[]]*beam_size #for constraints\n \n # run the decoder to generate the sequence \n for i in range(max_len_decode): \n\n # one all beams have EOS break \n if all((b.done() for b in beam)):\n break\n\n # No need to explicitly set the input to previous output - beam advance does it. Make sure.\n inp = var(torch.stack([b.get_current_state() for b in beam])\n .t().contiguous().view(-1)) #[beam_size]\n # Tested that the last output is the input in the next time step.\n #print(\"STEP {}\".format(i))\n #print(\"INPUT: {}\".format(inp.data))\n \n # Run one step of the decoder\n # dec_out: beam x rnn_size \n \n dec_output, dhidden = self.decoder(inp, dhidden, latent_values)\n # [1, beam_size, hidden_size]\n dec_output = torch.unsqueeze(dec_output, 0) \n logits = self.logits_out(dec_output) \n probs = F.log_softmax(logits, dim=2).data \n out = unbottle(probs) # [beam_size, 1, vocab_size]\n out.log()\n\n # Advance each beam. \n\n for j, b in enumerate(beam):\n if use_constraints:\n b.advance(ge.schema_constraint(out[:,j], b.next_ys[-1], verb_list, min_len_decode=min_len_decode, step=i, eos_idx=self.eos_idx)) \n else: \n b.advance(out[:, j])\n\n # advance hidden state and input feed accordingly\n beam_update(dhidden, j, b.get_current_origin(), beam_size)\n beam_update(dec_output, j, b.get_current_origin(), beam_size)\n\n if use_constraints:\n verb_list = ge.update_verb_list(verb_list, b, self.tup_idx) #update list of currently used verbs\n \n self.decoder.input_feed = dec_output.squeeze(dim=0) # update input feed for the next step.\n\n # extract sentences (token ids) from beam and return\n ret = self._from_beam(beam, n_best=n_best)[0][0] # best hyp \n\n self.decoder.reset_feed_() #reset input feed so pytorch correctly cleans graph\n return ret\n \n def _from_beam(self, beam, n_best=1):\n ret = {\"predictions\": [],\n \"scores\": []}\n for b in beam: # Only 1 beam object. \n scores, ks = b.sort_finished(minimum=n_best)\n hyps = []\n for i, (times, k) in enumerate(ks[:n_best]):\n hyp = b.get_hyp(times, k)\n hyps.append(hyp)\n ret[\"predictions\"].append(hyps)\n ret[\"scores\"].append(scores) \n \n return ret['predictions']\n\n\n def decode(self, input, impute=None):\n \"\"\"\n Decode from just the latents (gives indices for latents)\n Args\n input (List, [num_latents]) \n impute (2-tuple (e2, delta), or None) compute interpolation\n between first element in input (e1) and e2 with weight delta (ie e = delta*e1 + (1-delta)*e2)\n Returns\n : List of outputs of the decoder (the softmax distributions) at each time step\n\n THIS CURRENTLY IS NOT FINISHED\n \"\"\"\n outputs = []\n my_lats = [self.latent_root]\n child1 = self.latent_root.children[0]\n child2 = child1.children[0]\n child3 = child2.children[0]\n child4 = child3.children[0]\n my_lats.append(child1)\n my_lats.append(child2)\n my_lats.append(child3)\n my_lats.append(child4)\n\n latent_list = []\n for i, ind in enumerate(input):\n print(\"decode i: {}.\".format(i))\n if impute is not None and i == 0:\n latent_list.append(impute[1]*my_lats[i].embeddings(Variable(torch.LongTensor([ind]))) \n + (1-impute[1])*my_lats[i].embeddings(Variable(torch.LongTensor([impute[0]]))))\n else:\n latent_list.append(my_lats[i].embeddings(Variable(torch.LongTensor([ind]))))\n latent_list = torch.stack(latent_list, 0) \n latent_values = latent_list.transpose(0,1)\n top_level = latent_values[:, 0, :]\n dhidden = self.latent_in(top_level).view(self.layers,1, self.dec_hsize)\n #DECODE\n outputs = self.beam_decode(torch.Tensor(1,1), dhidden, latent_values, 10, 50)\n\n\n self.decoder.reset_feed_() #reset input feed so pytorch correctly cleans graph\n return outputs\n\n \n","sub_path":"DAVAE.py","file_name":"DAVAE.py","file_ext":"py","file_size_in_byte":17794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"612314557","text":"from configparser import ConfigParser\r\nimport os\r\n\r\n\"\"\"\r\n Config Tools\r\n Author:Sobhan01-K\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\nclass Config:\r\n \"\"\" Config Tools \"\"\"\r\n def __init__(self,file_name,file_type,create_now=False):\r\n self.config = ConfigParser()\r\n self.BASE_DIR = os.getcwd()\r\n self.FILE_DIR = f'{self.BASE_DIR}\\{file_name}.{file_type}'\r\n self.create_now = create_now\r\n self.ERROR = 'Incorrect Information'\r\n if os.path.isfile(self.FILE_DIR):\r\n self.config.read(self.FILE_DIR)\r\n\r\n if self.create_now == True:\r\n if os.path.isfile(self.FILE_DIR):\r\n self.create_now = False\r\n else:\r\n with open(self.FILE_DIR,'w') as config_file:\r\n self.config.write(config_file)\r\n\r\n def write(self):\r\n with open(self.FILE_DIR,'w') as config_file:\r\n self.config.write(config_file)\r\n\r\n def load(self,file_dir,default_dir=True):\r\n if default_dir:\r\n self.config.read(self.FILE_DIR)\r\n else:\r\n self.config.read(file_dir) \r\n\r\n def create_section(self,section,key={}):\r\n \"\"\" section:[Section] | key = value \r\n YOU CAN PASS KEY WITH ZIP : \r\n keys = ['key1','key2','key3']\r\n values = ['value1','value2','value3']\r\n key = dict(zip(keys,values)) \"\"\"\r\n\r\n \r\n exists = self.config.has_section(section)\r\n if not exists:\r\n self.config[section] = key\r\n self.write()\r\n\r\n\r\n def add_key(self,section,key,value):\r\n \"\"\" Key = Value \"\"\"\r\n\r\n\r\n item = self.config[section]\r\n try:\r\n is_exists = item.get(key)\r\n if not is_exists:\r\n item[key] = value \r\n except:\r\n item[key] = value\r\n self.write()\r\n\r\n def query_value(self,section,key):\r\n \"\"\" Query Value \r\n [Section]\r\n Key = Value \"\"\"\r\n \r\n try:\r\n item = self.config[section]\r\n \r\n\r\n query = item.get(key)\r\n return query\r\n except:\r\n \r\n return self.ERROR\r\n \r\n \r\n def query_key(self,section,key):\r\n \"\"\" Query Key\r\n [Section]\r\n Key = Value \"\"\"\r\n \r\n try:\r\n\r\n query = self.config[section]\r\n value = query.get(key)\r\n item = key + ' = ' + value\r\n return item\r\n except:\r\n \r\n return self.ERROR\r\n \r\n \r\n\r\n def query_all_keys(self,section,return_list_value=False):\r\n \"\"\" Query All Keys In Section \"\"\"\r\n try:\r\n\r\n if return_list_value == False:\r\n keys = self.config[section]\r\n item = ''\r\n for key in keys:\r\n value = keys.get(key)\r\n item += key+' = '+value+'\\n'\r\n return item\r\n elif return_list_value:\r\n keys = self.config[section]\r\n item = []\r\n for key in keys:\r\n item.append(key)\r\n return item\r\n except:\r\n return self.ERROR \r\n\r\n\r\n\r\n def strict_key(self,section,key,value,defualt_value):\r\n try:\r\n query = self.query_key(section,key)\r\n \r\n not_change = False\r\n for i in value:\r\n item = ''.join(i)\r\n final = key + ' = ' + item\r\n if query == final:\r\n not_change = True\r\n break\r\n \r\n if not_change == False:\r\n self.config[section][key] = defualt_value\r\n self.write()\r\n except:\r\n \r\n return self.ERROR\r\n\r\n\r\n \r\n \r\n def is_section_exists(self,section):\r\n try:\r\n\r\n if section in self.config:\r\n return True\r\n else:\r\n return False\r\n except:\r\n \r\n return self.ERROR \r\n\r\n\r\n def is_value_exists(self,section,key,value):\r\n try:\r\n\r\n item = self.config[section].get(key)\r\n\r\n if item == value:\r\n return True\r\n else:\r\n return False\r\n except:\r\n \r\n return self.ERROR\r\n \r\n\r\n def is_key_exists(self,section,key):\r\n try:\r\n\r\n item = self.config[section]\r\n if item.get(key):\r\n return True\r\n else:\r\n return False\r\n except:\r\n \r\n return self.ERROR ","sub_path":"config_tools/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"562974785","text":"import pygame as pg\nimport sys\nimport random\npg.init()\n\nheight = 768\nwidth = 1024\nBGCOLOR = pg.Color('white')\ndisplay = pg.display.set_mode((width, height))\ndisplay.fill(BGCOLOR)\nclass Ball():\n def __init__(self,display):\n self._display = display\n self._x = 100\n self._y = 100\n self._r = 30\n self._vx = 3\n self._vy = 3\n self._color = pg.Color('green')\n\n def draw(self):\n pg.draw.circle(self._display,self._color, (self._x, self._y), self._r)\n \n def clear(self):\n pg.draw.circle(self._display,BGCOLOR, (self._x, self._y), self._r) \n \n def go(self):\n self._x += self._vx\n self._y += self._vy\n\n def move(self):\n self.clear()\n self.go()\n self.draw()\n\n def stop(self):\n self._vx = 0\n self._vy = 0\n\n def is_on_display(self):\n width, height = display.get_size()\n if (self._r < self._x < width - self._r) and (self._r < self._y < height - self._r):\n return True\n return False\n \n def is_catch(self, x, y):\n if ((x - self._x)**2 + (y - self._y)**2 <= self._r**2):\n return True\n return False\n\n def touch(self):\n if (self._x <= self._r):\n return 'left'\n if (self._x >= width - self._r):\n return 'right'\n if (self._y <= self._r):\n return 'up' \n if (self._y >= height - self._r):\n return 'down'\n return ''\n\nclass RandomPountBall(Ball):\n def __init__(self, display):\n super().__init__(display)\n width, height = display.get_size()\n a = self._r \n bx = width - self._r\n by = height - self._r\n self._x = random.randint(a, bx)\n self._y = random.randint(a, by)\n print(self._x, self._y)\n\nclass RandomPountMoveableBall(RandomPountBall):\n def __init__(self, display):\n super().__init__(display)\n while True:\n vx = random.randint(-3, 3)\n vy = random.randint(-3, 3)\n if (vx != 0 or vy != 0):\n self._vx = vx\n self._vy = vy\n break\n \n print(self._vx, self._vy)\n\nclass BillyardBall(RandomPountMoveableBall):\n def __init__(self, display):\n super().__init__(display)\n\n def go(self):\n super().go()\n width, height = self._display.get_size()\n if (self._x <= self._r or self._x >= width - self._r):\n self._vx = - self._vx\n if (self._y <= self._r or self._y >= height - self._r):\n self._vy = - self._vy\nclass Text():\n def __init__(self, display):\n self._display = display\n self._font = pg.font.SysFont('couriernew',28)\n self._color = pg.Color('red');\n self._place = (10, 10)\n\n def set_place(self, x, y):\n self._place = (x, y)\n def print(self, text):\n text = self._font.render(str(text), True, self._color)\n self._display.blit(text, self._place)\n\nballs = []\n\nfor i in range(3):\n ball = BillyardBall(display)\n ball.draw()\n balls.append(ball)\n\n\nclock =pg.time.Clock()\nleft_text = Text(display)\nleft_text.set_place(10, 420)\n\nright_text = Text(display)\nright_text.set_place(980, 420)\n\nup_text = Text(display)\nup_text.set_place(500, 10)\n\ndown_text = Text(display)\ndown_text.set_place(500, 740)\n\n\ncounters = {'up': 0, 'down': 0, 'left': 0, 'right':0}\nwhile True:\n for event in pg.event.get():\n if event.type == pg.QUIT:\n pg.quit()\n sys.exit()\n \n\n display.fill(BGCOLOR)\n \n for ball in balls:\n ball.move()\n touch = ball.touch()\n if (touch != ''):\n counters[touch] +=1\n\n left_text.print(counters['left'])\n right_text.print(counters['right'])\n up_text.print(counters['up'])\n down_text.print(counters['down'])\n pg.display.flip()\n clock.tick(54)","sub_path":"lesson24/balls.py","file_name":"balls.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"329840842","text":"# coding: utf8\n\n## En esta sección se definen las tablas correspondientes a la sección de \n## Vegetación y suelo\n## El campo de ID es automático en Web2py, por lo que no se incluye:\n\n###########################################\n# Transecto_ramas\n###########################################\n\nCampos_Transecto_ramas = [\n\n\tField('sitio_muestra_id','reference Sitio_muestra',required=True),\n\tField('direccion','string',required=True),\n\tField('pendiente','integer',required=True),\n\tField('abundancia_1h','integer',required=True),\n\tField('abundancia_10h','integer',required=True),\n\tField('abundancia_100h','integer',required=True)\n]\n\ndb.define_table('Transecto_ramas', *Campos_Transecto_ramas,\n\tsingular='Ramas en transecto', plural='Ramas en transectos')\n\n\n###########################################\n# Rama_1000h\n###########################################\n\nCampos_Rama_1000h = [ \n\n\tField('transecto_ramas_id','reference Transecto_ramas',required=True),\n\tField('diametro','double',required=True),\n\t\n\t#Se insertará a partir de un catálogo\n\tField('grado','integer',required=True)\n]\n\ndb.define_table('Rama_1000h', *Campos_Rama_1000h,\n\tsingular='Rama 1000h', plural='Ramas 1000h')\n\n\n###########################################\n# Punto_carbono\n###########################################\n\nCampos_Punto_carbono = [\n\n\tField('sitio_muestra_id','reference Sitio_muestra',required=True),\n\tField('transecto_direccion','string',required=True),\n\tField('transecto_distancia','integer',required=True),\n\n\t#Se insertará a partir de un catálogo\n\tField('material_tipo','string',required=True),\n\n\tField('grosor','integer',required=True),\n\n\t# Los siguientes campo se hicieron opcionales en esquema v14.\n\tField('peso_humedo','double'),\n\tField('peso_humedo_muestra','double'),\n\tField('peso_seco_muestra','double')\n]\n\ndb.define_table('Punto_carbono', *Campos_Punto_carbono,\n\tsingular='Carbono en el mantillo', plural='Carbono en el mantillo')\n\n##########################################################################\n## Arbol_transecto: arboles pequeños y arbustos\n##########################################################################\n\nCampos_Arbol_transecto = [\n\n Field('sitio_muestra_id','reference Sitio_muestra',required=True),\n\n #Se insertará a partir de un catálogo\n Field('transecto','string',required=True),\n Field('individuo_numero','integer',required=True),\n Field('nombre_comun','string'),\n Field('nombre_cientifico','string'),\n Field('forma_vida','string',required=True),\n Field('distancia_copa','double',required=True),\n Field('altura','double',required=True),\n \n ]\n\ndb.define_table('Arbol_transecto',*Campos_Arbol_transecto,\n singular='Árbol transecto',plural='Árboles transectos')\n\n###########################################\n# Arbol_cuadrante: árboles grandes\n###########################################\n\nCampos_Arbol_cuadrante = [\n\n\tField('sitio_muestra_id','reference Sitio_muestra',required=True),\n\tField('individuo_numero','integer',required=True),\n\n\t# El siguiente campo ya no es necesario para el protocolo de toma de datos\n\t# del cliente v5, pero es necesario mantenerlo para datos capturados con\n\t# protocolos anteriores\n\tField('existe', 'boolean',required=True),\n\n\tField('distancia','double'),\n\tField('azimut','double'),\n\tField('nombre_comun','string'),\n\tField('nombre_cientifico','string'),\n\tField('altura','double'),\n\tField('diametro_copa','double'),\n\n\t# El siguiente campo se cambió de tipo en el esquema v14.\n\tField('diametro_normal','string'),\n\n\t# Los siguientes campos se agregaron en el esquema v14.\n\tField('forma_vida', 'string'),\n\tField('cambios', 'string')\n\t]\n\ndb.define_table('Arbol_cuadrante', *Campos_Arbol_cuadrante,\n\tsingular='Árbol cuadrante', plural='Árboles cuadrantes')\n\n########################\n# Informacion_epifitas\n########################\n\nCampos_Informacion_epifitas = [\n\n\tField('conglomerado_muestra_id','reference Conglomerado_muestra',required=True),\n\tField('helechos_observados','boolean',required=True),\n\tField('orquideas_observadas','boolean',required=True),\n\tField('musgos_observados','boolean',required=True),\n\tField('liquenes_observados','boolean',required=True),\n\tField('cactaceas_observadas','boolean',required=True),\n\tField('bromeliaceas_observadas','boolean',required=True),\n\tField('otras_observadas','boolean',required=True),\n\tField('nombre_otras','string')\n\t]\n\ndb.define_table('Informacion_epifitas', *Campos_Informacion_epifitas,\n\tsingular='Epífita', plural='Epífitas')","sub_path":"models/07_vegetacion_suelo_f.py","file_name":"07_vegetacion_suelo_f.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"404568360","text":"import os, sys\n\nentity_relations_file = open(\"entsAndRels.txt\", 'r')\nfile_lines = entity_relations_file.readlines()\n\nwrite_file = open('sendBackToBraydenWhenDone.txt','a')\n\n\nfor n in file_lines:\n print(\"Is the following statement true?(y or n, x to exit)\")\n print(n)\n while True:\n input_var = raw_input()\n if input_var == 'y':\n write_file.write(n)\n break\n elif input_var == 'n':\n break\n elif input_var == 'x':\n sys.exit()\n else:\n input_var = ''\n","sub_path":"David and Pooja/++Validating Linked Mods/stephensYesAndNo copy.py","file_name":"stephensYesAndNo copy.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"548770105","text":"\"\"\"\n1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. Об окончании\nввода данных свидетельствует пустая строка.\n\"\"\"\n\nfile_name = 'user_file.txt'\n\nwith open(file_name, 'w', encoding='utf-8') as user_file:\n while True:\n user_string = input('Введите строку (окончание ввода - пустая строка): ').strip()\n if not len(user_string):\n break\n else:\n user_file.writelines('{}{}'.format(user_string, '\\n'))\n","sub_path":"lesson_5_1.py","file_name":"lesson_5_1.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"353585757","text":"class Solution:\n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n \n # STEP 1: Reverse outer array\n matrix.reverse()\n \n # STEP 2: Swap inner values for each row with the column values\n for i in range (len(matrix)):\n for j in range(i+1, len(matrix)):\n matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]","sub_path":"medium/Arrays/Rotate Image.py","file_name":"Rotate Image.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"475657157","text":"# import csv file thru liab\nimport os\nimport csv\n# Define csv file's location\ncsvpath = os.path.join('Resources', 'election_data.csv')\n\n#open csv file\nwith open(csvpath,'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n #skip headers row\n csv_header = next(csvreader,None)\n #print(csv_header)\n\n # Set empty list variables\n County= []\n Candidates = []\n CandidateWinner =[]\n VoteCount = []\n VotePercent =[]\n # Set Count # to Zero\n TotalCount = 0\n\n# Loop thru each row\n for row in csvreader: \n TotalCount += 1\n Candidates.append(row[2])\n for x in set(Candidates):\n CandidateWinner.append(x)\n VotesPerCandidte = Candidates.count(x)\n VoteCount.append(VotesPerCandidte)\n VotePercent.append(Candidates.count(x)/TotalCount)\n # Identify the max voted candidate\n Winner = CandidateWinner[VoteCount.index(max(VoteCount))]\n\n # output into text file\n with open('Election_Results' + '.txt', 'w') as text:\n text.write(\"Election Results\"+\"\\n\")\n text.write(\"----------------------------------------------------------\\n\")\n text.write(\"Total Vote: \" + str(TotalCount) + \"\\n\")\n text.write(\"----------------------------------------------------------\\n\")\n # Loop in Candidates pool, generate each candidate's vote count and percentage\n for i in range(len(set(Candidates))):\n text.write(CandidateWinner[i] + \": \" + str(round(VotePercent[i]*100,1)) +\"% (\" + str(VoteCount[i]) + \")\\n\")\n text.write(\"----------------------------------------------------------\\n\")\n text.write(\"Winner: \" + Winner +\"\\n\")\n text.write(\"----------------------------------------------------------\\n\")\n\n\n\n\n\n\n\n","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"133802191","text":"import numpy as np\nimport sklearn.decomposition\nimport sklearn.gaussian_process\n\n\nclass Emulator(object):\n\n def __init__(self, X, Y, n_components):\n # Use GaussianProcessRegressor later\n self._ncomp = n_components\n self._PCA = sklearn.decomposition.PCA(n_components=n_components)\n self._GP = sklearn.gaussian_process.GaussianProcess(\n theta0=1e-2,\n thetaL=1e-4,\n thetaU=1e-1,\n )\n self.train(X, Y)\n\n def train(self, X, Y):\n self._X = X\n self._Y = Y\n comp = self._PCA.fit_transform(Y)\n self._GP.fit(X, comp)\n\n def predict(self, X):\n X = np.atleast_2d(X)\n n_eval = X.shape[0]\n y = np.zeros((n_eval, self._GP.y.shape[1]))\n MSE = np.zeros(n_eval)\n for k in range(n_eval / 1000 + 1):\n batch_from = k * 1000\n batch_to = min([(k + 1) * 1000 + 1, n_eval + 1])\n y_, MSE_ = self._GP.predict(\n X[batch_from:batch_to],\n eval_MSE=True)\n #print(batch_from, batch_to, y_.shape)\n\n y[batch_from:batch_to] = y_\n MSE[batch_from:batch_to] = MSE_\n std = np.sqrt(MSE)\n return self.comp_to_spectrum(y), std\n\n def quick_predict(self, X):\n X = np.atleast_2d(X)\n assert X.shape[0] == 1\n return self.comp_to_spectrum(self._GP.predict(X))[0]\n\n def pca_transform(self, Y):\n return self._PCA.inverse_transform(self._PCA.transform(Y))\n\n def comp_to_spectrum(self, Y):\n return self._PCA.inverse_transform(Y)\n\n\nclass LogEmulator(Emulator):\n\n def train(self, X, Y):\n super(LogEmulator, self).train(X, np.log10(Y))\n\n def comp_to_spectrum(self, Y):\n return 10 ** super(LogEmulator, self).comp_to_spectrum(Y)\n\n\nclass DecoupledGaussianProcess(object):\n\n def __init__(self, N, *args, **kwargs):\n self.N = N\n self._GP = [\n sklearn.gaussian_process.GaussianProcess(*args, **kwargs)\n for _ in xrange(N)\n ]\n self.y = None\n\n def fit(self, X, y):\n assert y.shape[1] == self.N\n self.y = y\n for i in xrange(self.N):\n self._GP[i].fit(X, y[:, i])\n\n def predict(self, X, eval_MSE=False):\n X = np.atleast_2d(X)\n y = np.zeros((X.shape[0], self.N))\n if eval_MSE:\n MSE = np.zeros((X.shape[0], self.N))\n for i in xrange(self.N):\n y[:, i], MSE[:, i] = self._GP[i].predict(X, eval_MSE=eval_MSE)\n return y, MSE\n else:\n for i in xrange(self.N):\n y[:, i] = self._GP[i].predict(X)\n return y\n\n\n # def __getattr__(self, name):\n # try:\n # getattr(self._GP[0], name).__call__\n # except AttributeError:\n # return getattr(self._GP[0], name)\n # else:\n # def f(*args, **kwargs):\n # for GP in self._GP:\n # getattr(GP, name)(*args, **kwargs)\n # return f\n\n\nclass DecoupledEmulator(Emulator):\n\n def __init__(self, X, Y, n_components):\n # Use GaussianProcessRegressor later\n self._ncomp = n_components\n self._PCA = sklearn.decomposition.PCA(n_components=n_components)\n self._GP = DecoupledGaussianProcess(\n n_components,\n theta0=1e-2,\n thetaL=1e-4,\n thetaU=1e-1,\n storage_mode='light',\n )\n self.train(X, Y)\n\n def predict(self, *args, **kwargs):\n raise NotImplementedError\n","sub_path":"dalek/emulator.py","file_name":"emulator.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"344944239","text":"#!/usr/bin/python\nimport i3ipc\nfrom collections import deque\n\nCIRCULAR_BUFFER_DIM = 10\n\ni3 = i3ipc.Connection()\n\n# Circular buffer containing last used workspaces\nWORKSPACES_LIST = deque(maxlen = CIRCULAR_BUFFER_DIM)\nfirst_focused = i3.get_tree().find_focused()\nWORKSPACES_LIST.append({'id': first_focused.workspace().id, 'name': first_focused.workspace().name})\n\ndef isEmpty(workspace_id):\n workspace = i3.get_tree().find_by_id(workspace_id)\n if not workspace:\n return True\n if workspace.workspace().leaves():\n return False\n else:\n return True\n\ndef onFocus(self, e):\n if e.current:\n WORKSPACES_LIST.append({'id': e.current.id, 'name': e.current.name})\n\ndef onClose(self, e):\n focused = i3.get_tree().find_focused()\n if not focused.workspace().leaves():\n for w in reversed(WORKSPACES_LIST):\n if not isEmpty(w['id']):\n i3.command('workspace ' + w['name'])\n break\n\n\ni3.on('workspace::focus', onFocus)\ni3.on('window::close', onClose)\n\ni3.main()\n","sub_path":".scripts/i3_empty_wss.py","file_name":"i3_empty_wss.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"273301567","text":"import sys\r\nfrom PyQt5.Qt import Qt\r\nfrom PyQt5.QtGui import QIcon\r\nfrom PyQt5.QtWidgets import *\r\nimport numpy as np\r\n\r\nfrom backendImg import initplot, plot_origin, noise_plot, plott_origin, methodd, errorPlot\r\n\r\n\r\nclass Window1(QMainWindow):\r\n def __init__(self):\r\n # 父类的初始化\r\n super().__init__()\r\n\r\n # 初始化文件读取状态\r\n self.loadSignalStatus = False\r\n self.loadNoiseStatus = False\r\n self.signalFile = ''\r\n self.noiseFile = ''\r\n\r\n # 初始化信号与噪声参数\r\n self.snr = 0.0\r\n self.signal = 0\r\n self.noise = 0\r\n self.signalNoise = 0\r\n self.fs = 0\r\n self.interFreq = 0\r\n\r\n # UI初始化\r\n self.initUI()\r\n\r\n # 初始化关于窗口\r\n def initDialog(self):\r\n self.aboutDialog = QDialog()\r\n self.aboutDialog.setWindowTitle('关于')\r\n self.aboutDialog.setWindowModality(Qt.ApplicationModal)\r\n aboutLayout = QGridLayout(self.aboutDialog)\r\n self.aboutDialog.setLayout(aboutLayout)\r\n aboutLabel1 = QLabel(self)\r\n labelLine0 = '信号频率检测仿真\\n'\r\n labelLine1 = '实现了:\\n1.生成多种不同的信号和噪声\\n2.用四种方法检测频率\\n3.计算信噪比/频率误差曲线\\n4.调节干扰信号的频率\\n5.调节Welch法的重叠区域\\n版本: 0.0.1\\n'\r\n labelLine2 = '部分功能不完善'\r\n aboutLabel1.setText(labelLine0 + labelLine1 + labelLine2)\r\n aboutLayout.addWidget(aboutLabel1, 0, 0, 1, 1)\r\n\r\n # 初始化各种部件\r\n def initWidgets(self):\r\n\r\n # 绘制没有执行分析时的背景图片\r\n self.LTopCavans = initplot('Origin Signal')\r\n self.LBotmCavans = initplot('Received Signal')\r\n self.RTopCavans = initplot('Unknown')\r\n self.RBotmCavans = initplot('Unknown')\r\n\r\n # 设置信号选择下拉框\r\n self.signalComboItems = ['单频信号', '双频信号', '调幅信号', '调相信号', '无']\r\n self.signalCombo = QComboBox(self)\r\n self.signalCombo.setStatusTip('修改发射信号')\r\n self.signalCombo.addItems(self.signalComboItems)\r\n self.signalCombo.currentIndexChanged.connect(self.signalStatusChange)\r\n\r\n # 设置噪声选择下拉框\r\n self.noiseComboItems = ['无', '高斯白噪声', '均匀白噪声', '干扰信号']\r\n self.noiseCombo = QComboBox(self)\r\n self.noiseCombo.setStatusTip('修改噪声或干扰')\r\n self.noiseCombo.addItems(self.noiseComboItems)\r\n\r\n # 设置信噪比滑块\r\n self.snrSlider = QSlider(Qt.Horizontal, self)\r\n self.snrSlider.setStatusTip('修改信噪比')\r\n self.snrSlider.setMinimum(0)\r\n self.snrSlider.setMaximum(200)\r\n self.snrSlider.setSingleStep(1)\r\n self.snrSlider.setTickPosition(QSlider.TicksBelow)\r\n self.snrSlider.setTickInterval(10)\r\n self.snrSlider.setSliderPosition(100)\r\n self.snrSlider.valueChanged.connect(self.snrChanger)\r\n\r\n # 设置信噪比滑块显示\r\n self.snrChangeLabel = QLabel(self)\r\n self.snrChangeLabel.setText(\r\n '信噪比: ' + str(0) + 'dB')\r\n\r\n # 设置信噪比显示\r\n self.snrLabel = QLabel(self)\r\n self.snrLabel.setText('当前值: ' + str(self.snr) + 'dB')\r\n\r\n # 设置显示按钮\r\n self.displayButton = QPushButton(self)\r\n self.displayButton.setText('显示')\r\n self.displayButton.setStatusTip('显示选择的信号和噪声')\r\n self.displayButton.clicked.connect(self.display)\r\n\r\n # 设置分析信息显示\r\n self.infoLabel = QLabel(self)\r\n self.infoLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)\r\n self.infoLabel.setText('未运行分析')\r\n\r\n # 设置分析方法下拉框\r\n self.detcMethodComboItems = ['直接变换法', '自相关变换', 'Bartlett法', 'Welch法']\r\n self.detcMethodCombo = QComboBox(self)\r\n self.detcMethodCombo.setStatusTip('选择频率检测方式')\r\n self.detcMethodCombo.addItems(self.detcMethodComboItems)\r\n\r\n # 设置高级分析方法下拉框\r\n self.advancedComboItems = ['单频错误率分析', '干扰频移分析', 'Welch法重叠分析', '无']\r\n self.advancedCombo = QComboBox(self)\r\n self.advancedCombo.setStatusTip('选择高级分析模式')\r\n self.advancedCombo.addItems(self.advancedComboItems)\r\n self.advancedCombo.setEnabled(False)\r\n self.advancedCombo.setCurrentText('无')\r\n self.advancedCombo.currentTextChanged.connect(self.advancedStatus)\r\n\r\n # 设置额外参数输入框\r\n self.extraInputLine = QLineEdit(self)\r\n self.extraInputLine.setStatusTip('为高级分析输入额外参数')\r\n self.extraInputLine.setEnabled(False)\r\n self.extraInputLine.setPlaceholderText('额外参数:无')\r\n\r\n # 设置高级分析方法勾选框\r\n self.advAnalysisCheck = QCheckBox(self)\r\n self.advAnalysisCheck.setText('开启高级分析')\r\n self.advAnalysisCheck.toggle()\r\n self.advAnalysisCheck.setCheckState(False)\r\n self.advAnalysisCheck.stateChanged.connect(self.advancedStatus)\r\n\r\n # 设置分析按钮\r\n self.analysisButton = QPushButton(self)\r\n self.analysisButton.setText('分析')\r\n self.analysisButton.setStatusTip('开始进行频率分析')\r\n self.analysisButton.clicked.connect(self.analysis)\r\n\r\n def initUI(self):\r\n self.resize(1200, 900) # 设置主窗口大小\r\n self.setWindowTitle('信号频率检测仿真') # 设置标题\r\n self.statusBar().showMessage('加载中') # 设置状态栏显示\r\n self.show() # 显示主窗口\r\n\r\n self.initWidgets()\r\n self.initDialog()\r\n\r\n # 设置菜单栏\r\n\r\n # 设置加载信号动作\r\n self.loadSignalAct = QAction('加载信号', self)\r\n self.loadSignalAct.setShortcut('Ctrl+S')\r\n self.loadSignalAct.setStatusTip('加载文件中的信号')\r\n self.loadSignalAct.triggered.connect(self.loadSignal)\r\n\r\n # 设置加载噪声动作\r\n self.loadNoiseAct = QAction('加载噪声', self)\r\n self.loadNoiseAct.setShortcut('Ctrl+N')\r\n self.loadNoiseAct.setStatusTip('加载文件中的噪声或干扰')\r\n self.loadNoiseAct.triggered.connect(self.loadNoise)\r\n\r\n # 设置关于动作\r\n self.aboutAct = QAction('关于', self)\r\n self.aboutAct.setStatusTip('关于此程序的信息')\r\n self.aboutAct.triggered.connect(self.showAboutDialog)\r\n\r\n # 设置退出动作\r\n self.exitAct = QAction('退出', self)\r\n self.exitAct.setShortcut('Ctrl+Q')\r\n self.exitAct.setStatusTip('关闭当前程序')\r\n self.exitAct.triggered.connect(qApp.quit)\r\n\r\n # 把动作添加到菜单栏\r\n self.menuBarTop = self.menuBar()\r\n self.menuBarTop.addAction(self.loadSignalAct)\r\n self.menuBarTop.addAction(self.loadNoiseAct)\r\n self.menuBarTop.addAction(self.aboutAct)\r\n self.menuBarTop.addAction(self.exitAct)\r\n\r\n mainWidget = QWidget(self) # 创建主要部件\r\n self.setCentralWidget(mainWidget) # 把主要部件设为主窗口中央部件\r\n self.grid = QGridLayout() # 创建网格布局\r\n mainWidget.setLayout(self.grid) #设置主要部件的布局为网格布局\r\n # mainWidget.setStyleSheet('background-color:white')\r\n\r\n #为网格布局添加子部件\r\n self.grid.addWidget(self.LTopCavans, 0, 0, 3, 4)\r\n self.grid.addWidget(self.LBotmCavans, 3, 0, 3, 4)\r\n self.grid.addWidget(self.RTopCavans, 0, 4, 3, 4)\r\n self.grid.addWidget(self.RBotmCavans, 3, 4, 3, 4)\r\n self.grid.addWidget(self.signalCombo, 6, 0, 1, 1)\r\n self.grid.addWidget(self.noiseCombo, 7, 0, 1, 1)\r\n self.grid.addWidget(self.snrSlider, 6, 1, 1, 3)\r\n self.grid.addWidget(self.snrChangeLabel, 7, 1, 1, 1)\r\n self.grid.addWidget(self.snrLabel, 7, 2, 1, 1)\r\n self.grid.addWidget(self.displayButton, 7, 3, 1, 1)\r\n self.grid.addWidget(self.infoLabel, 6, 4, 1, 3)\r\n self.grid.addWidget(self.detcMethodCombo, 7, 4, 1, 1)\r\n self.grid.addWidget(self.advancedCombo, 7, 5, 1, 1)\r\n self.grid.addWidget(self.extraInputLine, 7, 6, 1, 1)\r\n self.grid.addWidget(self.advAnalysisCheck, 6, 7, 1, 1)\r\n self.grid.addWidget(self.analysisButton, 7, 7, 1, 1)\r\n\r\n self.statusBar().showMessage('就绪')\r\n self.update()\r\n\r\n #滑动滑块时显示信噪比\r\n def snrChanger(self):\r\n self.snrChangeLabel.setText(\r\n '信噪比: ' + str(round(self.snrSlider.value() / 10 - 15, 2)) + 'dB')\r\n\r\n #信号为'无'时使显示按钮无效\r\n def signalStatusChange(self):\r\n if self.signalCombo.currentText() == '无':\r\n self.displayButton.setEnabled(False)\r\n self.snrSlider.setEnabled(False)\r\n self.snrSlider.setValue(0)\r\n else:\r\n self.displayButton.setEnabled(True)\r\n self.snrSlider.setEnabled(True)\r\n\r\n #勾选高级分析勾选框和选择下拉框时改变UI设定\r\n def advancedStatus(self):\r\n if self.advAnalysisCheck.isChecked():\r\n self.advancedCombo.setEnabled(True)\r\n self.extraInputLine.setEnabled(True)\r\n self.loadNoiseAct.setEnabled(False)\r\n self.loadSignalAct.setEnabled(False)\r\n if self.advancedCombo.currentIndex() == 0:\r\n self.extraInputLine.setPlaceholderText('信噪比:begin end step')\r\n self.detcMethodCombo.setEnabled(True)\r\n elif self.advancedCombo.currentIndex() == 1:\r\n self.extraInputLine.setPlaceholderText('干扰信号频率:f')\r\n self.noiseCombo.setCurrentText('干扰信号')\r\n self.noiseCombo.setEnabled(False)\r\n self.detcMethodCombo.setEnabled(True)\r\n elif self.advancedCombo.currentIndex() == 2:\r\n self.extraInputLine.setPlaceholderText('窗口重叠因子:n')\r\n self.detcMethodCombo.setCurrentText('Welch法')\r\n self.noiseCombo.setEnabled(True)\r\n self.detcMethodCombo.setEnabled(False)\r\n else:\r\n self.advancedCombo.setCurrentText('无')\r\n self.advancedCombo.setEnabled(False)\r\n self.extraInputLine.setPlaceholderText('额外参数:无')\r\n self.extraInputLine.setEnabled(False)\r\n self.loadNoiseAct.setEnabled(True)\r\n self.loadSignalAct.setEnabled(True)\r\n self.noiseCombo.setEnabled(True)\r\n self.detcMethodCombo.setEnabled(True)\r\n\r\n #读取文件中的信号\r\n def loadSignal(self):\r\n self.signalFile = QFileDialog.getOpenFileName(\r\n self, '选择信号文件', './', '文本文件(*.txt)')\r\n self.statusBar().showMessage(str(self.signalFile))\r\n if (not self.loadSignalStatus) and (not self.signalFile[0] == ''):\r\n self.signal = np.loadtxt(self.signalFile[0])\r\n self.signalCombo.addItem('加载的信号')\r\n self.loadSignalStatus = True\r\n\r\n #读取文件中的噪声\r\n def loadNoise(self):\r\n self.noiseFile = QFileDialog.getOpenFileName(\r\n self, '选择噪声文件', './', '文本文件(*.txt)')\r\n self.statusBar().showMessage(str(self.noiseFile))\r\n if (not self.loadNoiseStatus) and (not self.noiseFile[0] == ''):\r\n self.noise = np.loadtxt(self.noiseFile[0])\r\n self.noiseCombo.addItem('加载的噪声')\r\n self.loadNoiseStatus = True\r\n\r\n #按下显示按钮时,显示选择的信号,信号频谱,加噪信号\r\n def display(self):\r\n if not self.advAnalysisCheck.isChecked():\r\n self.snr = round(self.snrSlider.value() / 10 - 15, 2)\r\n self.snrLabel.setText('当前值: ' + str(self.snr) + 'dB')\r\n\r\n LTopCavans, self.signal, self.fs = plot_origin(\r\n self.signalCombo.currentIndex(), self.signal)\r\n self.grid.itemAtPosition(0, 0).widget().deleteLater()\r\n self.grid.addWidget(LTopCavans, 0, 0, 3, 4)\r\n\r\n LBotmCavans, self.signalNoise = noise_plot(self.noiseCombo.currentIndex(\r\n ), self.snr, self.signal, self.fs, noise_txt=self.noise)\r\n self.grid.itemAtPosition(3, 0).widget().deleteLater()\r\n self.grid.addWidget(LBotmCavans, 3, 0, 3, 4)\r\n\r\n RTopCavans = plott_origin(self.signal, self.fs)\r\n self.grid.itemAtPosition(0, 4).widget().deleteLater()\r\n self.grid.addWidget(RTopCavans, 0, 4, 3, 4)\r\n else:\r\n self.snr = round(self.snrSlider.value() / 10 - 15, 2)\r\n self.snrLabel.setText('当前值: ' + str(self.snr) + 'dB')\r\n\r\n LTopCavans, self.signal, self.fs = plot_origin(\r\n self.signalCombo.currentIndex(), self.signal)\r\n self.grid.itemAtPosition(0, 0).widget().deleteLater()\r\n self.grid.addWidget(LTopCavans, 0, 0, 3, 4)\r\n if self.advancedCombo.currentIndex() == 1:\r\n LBotmCavans, self.signalNoise = noise_plot(self.noiseCombo.currentIndex(\r\n ), self.snr, self.signal, self.fs, f00=self.interFreq)\r\n else:\r\n LBotmCavans, self.signalNoise = noise_plot(self.noiseCombo.currentIndex(\r\n ), self.snr, self.signal, self.fs, noise_txt=self.noise)\r\n self.grid.itemAtPosition(3, 0).widget().deleteLater()\r\n self.grid.addWidget(LBotmCavans, 3, 0, 3, 4)\r\n\r\n RTopCavans = plott_origin(self.signal, self.fs)\r\n self.grid.itemAtPosition(0, 4).widget().deleteLater()\r\n self.grid.addWidget(RTopCavans, 0, 4, 3, 4)\r\n\r\n #按下分析时,根据选择的不同,显示不同的图形\r\n def analysis(self):\r\n if not self.advAnalysisCheck.isChecked():\r\n self.display()\r\n RBotmCavans, text = methodd(\r\n self.detcMethodCombo.currentIndex(), self.fs, self.signalNoise)\r\n self.grid.itemAtPosition(3, 4).widget().deleteLater()\r\n self.grid.addWidget(RBotmCavans, 3, 4, 3, 4)\r\n self.infoLabel.setText(text)\r\n elif self.advancedCombo.currentIndex() == 0:\r\n snrRange = self.extraInputLine.text().split()\r\n snrRange = [float(x) for x in snrRange]\r\n if len(snrRange) == 3:\r\n RBotmCavans, text = errorPlot(\r\n self.detcMethodCombo.currentIndex(), snrRange[0], snrRange[1], snrRange[2])\r\n else:\r\n RBotmCavans, text = errorPlot(\r\n self.detcMethodCombo.currentIndex())\r\n self.grid.itemAtPosition(3, 4).widget().deleteLater()\r\n self.grid.addWidget(RBotmCavans, 3, 4, 3, 4)\r\n self.infoLabel.setText(text)\r\n self.grid.itemAtPosition(0, 0).widget().deleteLater()\r\n self.grid.itemAtPosition(3, 0).widget().deleteLater()\r\n self.grid.itemAtPosition(0, 4).widget().deleteLater()\r\n self.LTopCavans = initplot('Original Signal')\r\n self.LBotmCavans = initplot('Received Signal')\r\n self.RTopCavans = initplot('Unknown')\r\n self.grid.addWidget(self.LTopCavans, 0, 0, 3, 4)\r\n self.grid.addWidget(self.LBotmCavans, 3, 0, 3, 4)\r\n self.grid.addWidget(self.RTopCavans, 0, 4, 3, 4)\r\n elif self.advancedCombo.currentIndex() == 1:\r\n x = self.extraInputLine.text()\r\n if x == '':\r\n self.interFreq = 10e2\r\n else:\r\n self.interFreq = float(x)\r\n self.display()\r\n RBotmCavans, text = methodd(\r\n self.detcMethodCombo.currentIndex(), self.fs, self.signalNoise)\r\n self.grid.itemAtPosition(3, 4).widget().deleteLater()\r\n self.grid.addWidget(RBotmCavans, 3, 4, 3, 4)\r\n self.infoLabel.setText(text)\r\n elif self.advancedCombo.currentIndex() == 2:\r\n self.display()\r\n n = self.extraInputLine.text()\r\n if n == '':\r\n n = 8\r\n elif float(n) >= 127:\r\n n = 127\r\n else:\r\n n = int(round(float(n)))\r\n RBotmCavans, text = methodd(\r\n self.detcMethodCombo.currentIndex(), self.fs, self.signalNoise, n)\r\n self.grid.itemAtPosition(3, 4).widget().deleteLater()\r\n self.grid.addWidget(RBotmCavans, 3, 4, 3, 4)\r\n self.infoLabel.setText(text)\r\n\r\n #显示关于窗口\r\n def showAboutDialog(self):\r\n self.aboutDialog.show()\r\n self.aboutDialog.exec()\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv) #创建启动APP\r\n win1 = Window1() #为APP创建窗口\r\n sys.exit(app.exec()) #退出APP\r\n","sub_path":"UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":16893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"603169573","text":"import picamera\n\nclass Camera:\n def __init__(self, bot):\n self._bot = bot\n\n self._cam = picamera.PiCamera()\n self._buffer = picamera.PiCameraCircularIO(self._cam, seconds=3)\n self._initialized = False\n\n def start(self):\n if not self._initialized:\n self._cam.__enter__()\n self._buffer.__enter__()\n self._initialized = True\n self._cam.start_recording(self._buffer)\n\n def stop(self):\n if self._cam.recording:\n self._cam.stop_recording()\n\n def __del__(self):\n self.stop()\n if self._initialized:\n self._buffer.__exit__()\n self._cam.__exit__()\n","sub_path":"botlib/camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"245413923","text":"# -*- coding: utf-8 -*-\r\n\r\ndef get_domino(graph, v, visited, dom = 1):\r\n\tvisited[v-1] = True\r\n\tfor i in graph[v-1]:\r\n\t\tif not visited[i-1]:\r\n\t\t\tget_domino(graph, i, visited,dom)\r\n\r\n\r\na,b,c = map(int, input().split())\r\nvisited = [False] * a\r\ngraph = []\r\nfor i in range(a):\r\n\tgraph.append([])\r\n\t\r\nfor i in range(b):\r\n\tstart, end = map(int, input().split())\r\n\tgraph[start-1].append(end)\r\n\r\nfall = 0\r\nfor i in range(c):\r\n\tpushed = int(input())\r\n\tvisited = [False] * a\r\n\tvisited[pushed-1]=True\r\n\tget_domino(graph, pushed, visited)\r\n\tfor k in range(a):\r\n\t\tif visited[k]==True:\r\n\t\t\tfall += 1\r\n\t\r\nprint(fall)\r\n\r\n","sub_path":"groom_level/domino_dfs_me.py","file_name":"domino_dfs_me.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"505087708","text":"\"\"\"\nimplement the class FancyTuple\n- The constructor takes 0 to 5 parameters\n- The elements of FancyTuple can be accessed as named properties: first, second, third, fourth, fifth.\nthe expression FancyTuple(\"dog\", \"cat\").first returns \"dog\" and FancyTuple(\"dog\", \"cat\").second returns \"cat\"\n- An AttributeError exceptopm is raised if a non-existing property is accessed FancyTuple(\"dog\", \"cat\").third raises AttributeError\n- len(FancyTuple(\"dog\", \"cat\")) returns 2\n\"\"\"\n\n\nclass FancyTuple:\n def __init__(self, *args):\n self.__dict__.update(zip(['first', 'second', 'third', 'fourth', 'fifth'], args))\n self.args = args\n\n def __len__(self):\n return len(self.args)\n\n def __repr__(self):\n return 'FancyTuple({})'.format(', '.join(map(repr, self.args)))\n\n\nif __name__ == \"__main__\":\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n items = [input() for _ in range(n)]\n\n t = FancyTuple(*items)\n\n q = int(input())\n for _ in range(q):\n command = input()\n if command == \"len\":\n fptr.write(str(len(t)) + \"\\n\")\n else:\n try:\n elem = getattr(t, command)\n except AttributeError:\n fptr.write(\"AttributeError\\n\")\n else:\n fptr.write(elem + \"\\n\")\n fptr.close()\n","sub_path":"fancy_tuple.py","file_name":"fancy_tuple.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"134513717","text":"import json\r\n\r\ng_cfg = {}\r\n\r\n\r\ndef LoadConfig(file_path):\r\n global g_cfg\r\n with open(file_path, 'r') as f:\r\n g_cfg = json.load(f)\r\n if \"login_page_bkg\" not in g_cfg['web']:\r\n g_cfg['web']['login_page_bkg'] = ''\r\n if 'app_url_prefix' not in g_cfg:\r\n g_cfg['app_url_prefix'] = r'/rgw'\r\n\r\n","sub_path":"g_vars.py","file_name":"g_vars.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"622567728","text":"\"\"\"\nNeural Style from Leon Gatys\n\nA commandline interface is provided through `python3 -m\ntorchelie.recipes.neural_style`\n\"\"\"\n\nimport torch\nfrom torchvision.transforms import ToTensor, ToPILImage\n\nfrom torchelie.loss import NeuralStyleLoss\nfrom torchelie.data_learning import ParameterizedImg\nfrom torchelie.recipes.recipebase import ImageOptimizationBaseRecipe\nimport torchelie.metrics.callbacks as cb\n\n\ndef t2pil(t):\n return ToPILImage()(t)\n\n\ndef pil2t(pil):\n return ToTensor()(pil)\n\n\nclass NeuralStyleRecipe(ImageOptimizationBaseRecipe):\n \"\"\"\n Neural Style Recipe\n\n First instantiate the recipe then call `recipe(n_iter, img)`\n\n Args:\n lr (float, optional): the learning rate\n device (device): where to run the computation\n visdom_env (str or None): the name of the visdom env to use, or None\n to disable Visdom\n \"\"\"\n\n def __init__(self, lr=0.01, device=\"cpu\", visdom_env='style'):\n super(NeuralStyleRecipe, self).__init__(callbacks=[\n cb.WindowedMetricAvg('content_loss'),\n cb.WindowedMetricAvg('style_loss'),\n ],\n visdom_env=visdom_env,\n log_every=1)\n\n self.loss = NeuralStyleLoss().to(device)\n self.device = device\n self.lr = lr\n\n def init(self, content_img, style_img, style_ratio, content_layers=None):\n self.loss.set_style(pil2t(style_img).to(self.device), style_ratio)\n self.loss.set_content(\n pil2t(content_img).to(self.device), content_layers)\n\n self.canvas = ParameterizedImg(3, content_img.height,\n content_img.width).to(self.device)\n\n self.opt = torch.optim.LBFGS(self.canvas.parameters(),\n lr=self.lr,\n history_size=50)\n\n def forward(self):\n losses = None\n\n def make_loss():\n nonlocal losses\n self.opt.zero_grad()\n input_img = self.canvas()\n loss, losses = self.loss(input_img)\n loss.backward()\n return loss\n\n loss = self.opt.step(make_loss).item()\n\n return {\n 'loss': loss,\n 'content_loss': losses['content_loss'],\n 'style_loss': losses['style_loss']\n }\n\n def result(self):\n return self.canvas.render()\n\n def __call__(self, n_iters, content, style, ratio, content_layers):\n \"\"\"\n Run the recipe\n\n Args:\n n_iters (int): number of iterations to run\n content (PIL.Image): content image\n style (PIL.Image): style image\n ratio (float): weight of style loss\n content_layers (list of str): layers on which to reconstruct\n content\n \"\"\"\n return super(NeuralStyleRecipe, self).__call__(n_iters, content, style,\n ratio, content_layers)\n\n\nif __name__ == '__main__':\n import argparse\n import sys\n from PIL import Image\n parser = argparse.ArgumentParser(\n description=\"Implementation of Neural Artistic Style by Gatys\")\n parser.add_argument('--content', required=True)\n parser.add_argument('--style', required=True)\n parser.add_argument('--out', required=True)\n parser.add_argument('--size', type=int)\n parser.add_argument('--scale', type=float, default=1)\n parser.add_argument('--ratio', default=1, type=float)\n parser.add_argument('--device', default='cuda')\n parser.add_argument('--content-layers',\n default=None,\n type=lambda x: x and x.split(','))\n parser.add_argument('--iters', default=100, type=int)\n parser.add_argument('--visdom-env')\n args = parser.parse_args(sys.argv[1:])\n\n stylizer = NeuralStyleRecipe(device=args.device,\n visdom_env=args.visdom_env)\n\n content = Image.open(args.content)\n content.thumbnail((args.size, args.size))\n\n style_img = Image.open(args.style)\n if args.scale != 1.0:\n new_style_size = (int(style_img.width * args.scale),\n int(style_img.height * args.scale))\n style_img = style_img.resize(new_style_size, Image.BICUBIC)\n\n result = stylizer(args.iters, content, style_img, args.ratio,\n args.content_layers)\n result = t2pil(result)\n\n result.save(args.out)\n","sub_path":"torchelie/recipes/neural_style.py","file_name":"neural_style.py","file_ext":"py","file_size_in_byte":4475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"187209928","text":"#!/usr/bin/python\n\"\"\"\nAssignment : https://homework.adhoc.team/slcsp/\nThe following code in python uses Pandas DataFrames to fetch the second lowest silver plan\nfor a group of zipcodes(that is present in the slcsp.csv file)\nThe input files that are passed to this code are\n\nZIPS_CSV_PATH = \"./input_data/zips.csv\"\nPLANS_CSV_PATH = \"./input_data/plans.csv\"\nSLCSP_CSV_PATH = \"./input_data/slcsp.csv\"\n\nKindly check if the files are present in the path defined. You could set your own path too. \n\nOUTPUT_SLCSP_CSV_PATH = \"./Output_slcsp.csv\"\n\nThis file contains the output with the rates for the desired zipcodes ONLY if you don't wish to update the\noriginal slcsp.csv file.\nThe program takes a user input to confirm the same\n\nMETAL_LEVEL = \"Silver\" \nThis assigns the metal level as Silver and can be easily changed to Gold, Platinum or any other value\nbased on the requirements\n\nThe program runs in two ways:\n-> Without any arguments : python run_slcsp.py\n\tThis will print the zipcodes and the respective slcsp rates on the screen and ask the user input\n\tto either create a new file OUTPUT_SLCSP_CSV_PATH or update the SLCSP_CSV_PATH\n\t\n-> With zipcodes as the arguments : python run_slcsp.py zip1 zip2 . . \n\tThis will print the zipcodes and the respective slcsp rates of the zipcodes passed on the screen\n\tand will also ask the user to input if they would like to write the full output to the\n\tOUTPUT_SLCSP_CSV_PATH or update the SLCSP_CSV_PATH\n\t\n-Use python run_slcsp.py -help to view the options\n\t\nIn both these cases, I have handled the ambiguous zips in the code. That is, if a zip is present\nin more than one area, then it is considered ambiguous and the respective column is left blank. \nIf any invalid zip is passed as an argument, then an error message is thrown. \n\nThis program has been tested on Mac and Windows 10, Python 3.9.5\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport sys\nimport warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\n\"\"\"\nDeclare the path variables for the input files, output file.\n\"\"\"\n\nZIPS_CSV_PATH = \"./input_data/zips.csv\"\nPLANS_CSV_PATH = \"./input_data/plans.csv\"\nSLCSP_CSV_PATH = \"./input_data/slcsp.csv\"\nOUTPUT_SLCSP_CSV_PATH = \"./Output_slcsp.csv\"\n\n\"\"\"Assign the Metal Level here to the plan that you would like to get the second smallest rates for \"\"\"\n\nMETAL_LEVEL = \"Silver\"\n\n\"\"\"\nHandling File read errors here. Pandas DataFrames are used to read the csv file\n\"\"\"\ntry:\n\twith open(ZIPS_CSV_PATH) as zips_csv, open(PLANS_CSV_PATH) as plans_csv, open(SLCSP_CSV_PATH) as slcsp_csv:\n\t\t\tplans = pd.read_csv(plans_csv)\n\t\t\tzips = pd.read_csv(zips_csv)\n\t\t\tslcsp = pd.read_csv(slcsp_csv)\nexcept OSError as e:\n\t\tprint(e)\n\t\tprint(\"Error : Unable to read the input files. Please re-check if the files are present\\n\")\n\t\tsys.exit(1)\n\t\t\n\t\t\n\"\"\"\nThis function runs the primary function called basic_function() that has the code to find the slcsp \nvalues. It aslo checks for the arguments passed in the CLI , validate the input and then perform the task accordingly\n\"\"\"\t\t\t\ndef check_args(cmd_line_args):\n\tresult = basic_function()\n\tif len(sys.argv) == 1:\n\t\tprint(result)\n\t\twrite_to_csv(result)\n\t\t\n\tif len(sys.argv) > 1:\n\t\tif (sys.argv[1] == \"-help\"):\n\t\t\tprint(\"\\nUsage :\")\n\t\t\tprint(\"Execute the SLCSC program : python run_slcsc.py\")\n\t\t\tprint(\"Execute the SLCSC with zipcodes as args: python run_slcsc.py zip1 zip2 ..\\n\")\n\t\t\tsys.exit()\n\t\telse:\t\n\t\t\tfor i in range(1,len(sys.argv)):\n\t\t\t\tif sys.argv[i].isdigit():\n\t\t\t\t\tres_index = result.index[result['zipcode']==int(sys.argv[i])].tolist()\n\t\t\t\telse:\n\t\t\t\t\tres_index=[]\n\t\t\t\tif not res_index or not sys.argv[i].isdigit():\n\t\t\t\t\tprint (\"\\nPlease re-check the zipcode : \",sys.argv[i],\"\\n\" )\n\t\t\t\telse:\n\t\t\t\t\tprint(result.iloc[res_index])\n\t\t\twrite_to_csv(result)\n\n\"\"\"\nThis function asks for the user input to direct the output to the desired location.\n\"\"\"\t\t\t\t\t\ndef write_to_csv(result):\n\twrite_to_csv = input (\"\\nDo you wish to write the complete output to the original SLCSP file? Enter:\\n y : To write to the original SLCSP.csv\\n n : To write to a separate OutputSLCSP file\\n\")\n\tif write_to_csv == 'y':\n\t\tresult.to_csv(SLCSP_CSV_PATH, index=False)\n\t\tprint(\"\\nOutput file available at :\",SLCSP_CSV_PATH,\"\\n\")\n\t\treturn\n\tif write_to_csv == 'n':\n\t\tresult.to_csv(OUTPUT_SLCSP_CSV_PATH, index=False)\n\t\tprint(\"\\nOutput file available at :\",OUTPUT_SLCSP_CSV_PATH,\"\\n\")\n\t\treturn\n\telse:\n\t\tprint(\"\\nInvalid Key Entered!\\n\")\n\t\treturn\n\t\t\n\"\"\"\nThis function is the primary function of the program. Here we fetch only the plans with the concerned Metal_Level\nThen we reduce the zips file to extract the zips that are needed in the output. We also remove the ambiguous zips,\nand finally find the nth smallest rate for the zips.\n\"\"\"\ndef basic_function():\n\t\n\t\"\"\"\n\tExtract only the silver plans from the plans.csv file. METAL_LEVEL is passed here that can be used to check for any other Metal_Type as well\n\tMerge the slcsc csv with the zips.csv file to fetch only the zips needed in the output(instead of fetching data for all the zips)\n\tThis reduces the computational costs before merging to fetch the rates for all the zips\n\t\"\"\"\n\tsilver_plans = plans[plans['metal_level'].str.contains(METAL_LEVEL , regex=False)]\n\treduced_zips = pd.merge(slcsp['zipcode'], zips, on='zipcode')\n\n\t\"\"\"Find the ambiguous zips by grouping the zipcodes and checking the rate_areas for the respective group of zips\n\tIf multiple rate_areas point to the same zip, then it can be considered as ambiguous.\n\tSo here, we remove the ambiguous zips from the list and fetch the rates for the zips that are not ambiguous\n\t\"\"\"\n\tremove_ambiguous_zips = reduced_zips.groupby('zipcode').rate_area.nunique() > 1\n\tremove_ambiguous_zips[remove_ambiguous_zips].index.to_frame()\n\trequired_zips = pd.DataFrame(remove_ambiguous_zips).reset_index()\n\trequired_zips = required_zips.loc[required_zips[\"rate_area\"] != 1]\n\trequired_zips_data = pd.merge(required_zips['zipcode'],reduced_zips,on = 'zipcode')\n\n\t\"\"\"Find the corresponding rates from the Silver plans.\"\"\"\n\tzipcode_silver_plans_rate = pd.merge(required_zips_data,silver_plans, on=['state','rate_area'])\n\t\n\t\"\"\"In the problem statement, we also had to assign blank to the zips that had only one rate which means that there was no second\n\tsmallest. These next statements filter out those zipcodes. That is, get only the zipcodes that have a size >1 (which means they have more than 1 rate_area)\n\t\"\"\"\n\tdf=zipcode_silver_plans_rate.groupby('zipcode').size().to_frame('size')\n\tzipcode_silver_plans_rate_reqa = pd.DataFrame(df).reset_index()\n\tzipcode_silver_plans_rate_reqa = zipcode_silver_plans_rate_reqa.loc[zipcode_silver_plans_rate_reqa[\"size\"] != 1]\n\tzipcode_silver_plans_rate_reqb = pd.merge(zipcode_silver_plans_rate_reqa['zipcode'],reduced_zips,on = 'zipcode')\n\tzipcode_silver_plans_rate_req = pd.merge(zipcode_silver_plans_rate_reqb,silver_plans, on=['state','rate_area'])\n\n\n\t\"\"\"Here we use the nsmallest() method to get the smallest two rates and keep only the last which is the second smallest rate for that zipcode\"\"\"\n\tsorted_zipcode_silver_plans_rate = zipcode_silver_plans_rate_req.groupby('zipcode')['rate'].nsmallest(2).reset_index().drop('level_1',1).drop_duplicates(subset=['zipcode'],keep='last')\n\n\n\t\"\"\"In the last step, we merge the zipcodes(from the output list) with the sorted_zipcode_silver_plans_rate to get the final desired data.\n\tHere I have also formatted the output to include blanks and display the decimal values to two places.\"\"\"\n\tfinal_result = pd.merge(slcsp['zipcode'],sorted_zipcode_silver_plans_rate[['zipcode','rate']], on = 'zipcode',how='left')\n\tfinal_result.fillna(' ', inplace=True)\n\t#final_result.index = np.arange(1, len(final_result)+1)\n\tpd.options.display.float_format = \"{:,.2f}\".format\n\treturn final_result\n\nif __name__ == \"__main__\":\n\t#basic_function()\n\tcheck_args(sys.argv)","sub_path":"test_run/run_slcsp.py","file_name":"run_slcsp.py","file_ext":"py","file_size_in_byte":7797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"252833139","text":"# -*- encoding: utf-8 -*-\ntry:\n import simplejson as json\nexcept:\n import json\nfrom django.core.cache import cache\nfrom products.product_utils import *\nfrom rest_framework import status\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import detail_route, list_route\nfrom rest_framework.response import Response\nfrom toolkit.mylogger import Logger\n\nfrom pre_check import PermissionCheck\n\n\nclass CategoryViewSet(PermissionCheck, viewsets.ViewSet):\n\n def create(self, request):\n return self.get_all_categories(request)\n\n def list(self, request):\n return self.get_all_categories(request)\n # return Response(json.dumps({\"code\": 0, \"msg\": \"权限认证成功\", \"content\": get_categories()}),\n # status=status.HTTP_200_OK)\n\n def get_all_categories(self, request):\n Logger.debug(\"get cmd get_categories.\")\n categories = cache.get(\"get_all_categories\")\n if categories:\n Logger.debug(\"get_categories query data from cache.\")\n return Response(categories, status=status.HTTP_200_OK)\n res = []\n for category in ProductCategory.objects.filter(active=True):\n res.append({\n \"id\": category.id,\n \"name\": category.name,\n \"pid\": category.parent_category_id or 0,\n 'level': category.step\n })\n if not res:\n return Response(json.dumps({\"code\": 1, \"msg\": \"category data query failed!\", \"content\": []}))\n response_data = json.dumps({\"code\": 0, \"msg\": \"category data query successful!\", \"content\": res})\n cache.set(\"get_all_categories\", response_data, timeout=60)\n Logger.debug(\"get_categories query data from database successful.\")\n return Response(response_data, status=status.HTTP_200_OK)\n\n @list_route(methods=['get', 'post'])\n def search(self, request):\n kw = request.GET.get('kw').strip()\n series = ProductBrandSeries.objects.select_related(\n 'brand').prefetch_related('brand__manufactors', 'brand__categories',\n 'brand__categories__parent_category',\n 'brand__categories__parent_category__parent_category').filter(\n Q(name=kw) | Q(brand__name=kw) | Q(\n brand__manufactors__name=kw) | Q(\n brand__categories__name=kw) | Q(\n brand__categories__parent_category__name=kw) | Q(\n brand__categories__parent_category__parent_category__name=kw)).order_by(\n 'brand__categories__parent_category__parent_category__no',\n 'brand__categories__parent_category__no', 'brand__categories__no',\n 'brand__manufactors__no', 'brand__no', 'no')\n result = []\n for se in series:\n for c3 in se.brand.categories.all():\n for manufactor in se.brand.manufactors.all():\n if not (se.active and se.brand.active and manufactor.active and c3.active and c3.parent_category.active and c3.parent_category.parent_category.active):\n continue\n result_dict = {\n 'first_category': c3.parent_category.parent_category.name,\n 'second_category': c3.parent_category.name,\n 'third_category': c3.name,\n 'category_id': c3.id, 'series_id': se.id,\n 'manufactor': manufactor.name, 'brand': se.brand.name,\n 'series': se.name}\n if result_dict['first_category'] == kw or result_dict[\n 'second_category'] == kw or result_dict[\n 'third_category'] == kw or result_dict[\n 'manufactor'] == kw or result_dict['brand'] == kw or result_dict['series'] == kw:\n result.append(result_dict)\n return Response(\n {'data': result}, status=status.HTTP_200_OK)\n\n @detail_route(methods=['get', 'post'])\n def sub_categories(self, request, pk):\n return Response(get_sub_categories(pk),\n status=status.HTTP_200_OK)\n\n @detail_route(methods=['get', 'post'])\n def manufactors(self, request, pk):\n return Response(get_category_manufactors(pk),\n status=status.HTTP_200_OK)\n\n @detail_route()\n def brands(self, request, pk=None):\n manufactor_id = request.GET.get('manufactor_id', 0)\n return Response(get_manufactor_brands(pk, manufactor_id),\n status=status.HTTP_200_OK)\n\n @list_route(methods=['get', 'post'])\n def batch_delete(self, request):\n parent_categories = ProductCategory.objects.filter(\n pk__in=request.POST.get('ids').split(','))\n for parent_category in parent_categories:\n if parent_category.sub_categories.exists():\n parent_category.sub_categories.all().update(active=False)\n parent_category.active = False\n parent_category.save()\n parent_category.delete()\n return Response({'success': 1},\n status=status.HTTP_200_OK)\n\n def destroy(self, request, pk=None):\n parent_category = ProductCategory.objects.get(pk=pk)\n if parent_category.sub_categories.exists():\n parent_category.sub_categories.all().update(active=False)\n parent_category.active = False\n parent_category.save()\n return Response({'success': 1},\n status=status.HTTP_200_OK)\n\n def update(self, request, pk=None):\n name = request.POST.get('name').strip()\n if name == '':\n return Response(\n {'success': 0, 'message': '分类名不能为空!'},\n status=status.HTTP_200_OK)\n ProductCategory.objects.filter(pk=pk).update(name=name)\n return Response({'success': 1}, status=status.HTTP_200_OK)\n\n @detail_route()\n def attribute(self, request, pk=None):\n attributes = get_category_attributes(pk)\n return Response(attributes, status=status.HTTP_200_OK)\n","sub_path":"gezusercenter/sdk/category_views.py","file_name":"category_views.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"145178207","text":"import sys\r\nif sys.version < '2.6':\r\n sys.exit('ERROR: Sorry, python 2.6 is required for this application.')\r\n\r\nsys.path.append('src') \r\nfrom distutils.core import setup\r\n\r\nimport py2exe\r\nimport os, glob, fnmatch \r\n\r\ndef opj(*args):\r\n path = os.path.join(*args)\r\n return os.path.normpath(path)\r\n\r\ndef find_data_files(srcdir, *wildcards, **kw):\r\n # get a list of all files under the srcdir matching wildcards,\r\n # returned in a format to be used for install_data\r\n def walk_helper(arg, dirname, files):\r\n if '.svn' in dirname:\r\n return\r\n names = []\r\n lst, wildcards = arg\r\n for wc in wildcards:\r\n wc_name = opj(dirname, wc)\r\n for f in files:\r\n filename = opj(dirname, f)\r\n\r\n if fnmatch.fnmatch(filename, wc_name) and not os.path.isdir(filename):\r\n names.append(filename)\r\n if names:\r\n lst.append( (dirname, names ) )\r\n\r\n file_list = []\r\n recursive = kw.get('recursive', True)\r\n if recursive:\r\n os.path.walk(srcdir, walk_helper, (file_list, wildcards))\r\n else:\r\n walk_helper((file_list, wildcards),\r\n srcdir,\r\n [os.path.basename(f) for f in glob.glob(opj(srcdir, '*'))])\r\n return file_list\r\n\r\npkgs = ['icdb', 'utils', 'vmware' ]\r\n \r\ndatafiles = [ ('.', ['README.txt', 'ancillary.txt', 'config.json.skel']) ] + \\\r\n [ ('share/db', [] )] + \\\r\n find_data_files('static', '*') + \\\r\n find_data_files('share','*') + \\\r\n find_data_files('bin', '*') + \\\r\n find_data_files('Microsoft.VC90.CRT', '*.*')\r\n\r\nexcludes = [\"pywin\", \"pywin.debugger\", \"pywin.debugger.dbgcon\",\r\n \"pywin.dialogs\", \"pywin.dialogs.list\" ]\r\n\r\nincludes = ['web', 'web.wsgiserver', 'web.contrib', \r\n 'suds', 'M2Crypto', \r\n 'email',\r\n 'email.base64mime',\r\n 'email.charset',\r\n 'email.encoders',\r\n 'email.errors',\r\n 'email.feedparser',\r\n 'email.generator',\r\n 'email.header',\r\n 'email.iterators',\r\n 'email.message',\r\n 'email.parser',\r\n 'email.quoprimime',\r\n 'email.utils',\r\n 'email._parseaddr',\r\n 'email.mime', \r\n 'email.mime.application', \r\n 'email.mime.audio', \r\n 'email.mime.base', \r\n 'email.mime.image', \r\n 'email.mime.message', \r\n 'email.mime.multipart', \r\n 'email.mime.nonmultipart', \r\n 'email.mime.text' \r\n ]\r\n\r\nclass Target:\r\n def __init__(self, **kw):\r\n self.__dict__.update(kw)\r\n # for the versioninfo resources\r\n self.version = \"7.0.0.0\" # build.py magic comment\r\n self.company_name = \"HP\"\r\n self.copyright = \"Copyright 2009 Hewlett-Packard Development Company, L.P.\"\r\n self.name = \"HP Insight Control for vCenter UI Manager\"\r\n self.description = \"HP Insight Control for vCenter UI Manager Service\"\r\n\r\nmanifest_template = '''\r\n\r\n\r\n\r\n%(prog)s Program\r\n\r\n \r\n \r\n \r\n\r\n\r\n'''\r\n\r\nRT_MANIFEST = 24\r\n\r\nhpuim_service = Target(\r\n # used for the versioninfo resource\r\n description = \"HP Insight Control for vCenter UI Manager\",\r\n # What to build\r\n modules = [ \"hpuim\" ],\r\n cmdline_style = 'pywin32',\r\n other_resources = [(RT_MANIFEST, 1, manifest_template % dict(prog=\"hpuim\"))],\r\n dest_base = \"hpuim\",\r\n icon_resources = [(0, \"hp.ico\")]\r\n )\r\n\r\nsetup(\r\n name='hpuim',\r\n version='7.0.0.0', # build.py magic comment\r\n package_dir = {'': 'src'},\r\n description='HP Insight Control for vCenter UI Manager',\r\n packages = pkgs,\r\n options = {\"py2exe\": \r\n {\r\n \"bundle_files\" : 3,\r\n \"compressed\" : 1,\r\n \"optimize\" : 2,\r\n \"excludes\" : excludes,\r\n \"includes\" : includes,\r\n \"dll_excludes\": ['w9xpopen.exe', 'mswsock.dll', 'powrprof.dll'],\r\n }\r\n }, \r\n zipfile = \"hpuim.zip\",\r\n data_files = datafiles,\r\n #console = ['src\\uim.py'],\r\n service = [ hpuim_service ], \r\n ) \r\n\r\n#os.system('ren dist uim')\r\n#from distutils.archive_util import make_zipfile\r\n#make_zipfile('uim', 'uim')\r\n","sub_path":"workspaces/voyage/uim/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":5083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"627094887","text":"#!/usr/bin/env python3\nfrom modules.intcode import IntcodeMachine\n\ninputfile = \"input.txt\"\nresults = []\n\nwith open(inputfile) as f:\n line = f.readlines()[0].strip()\n\ncodes = [ int(c) for c in line.split(',') ]\n\nim = IntcodeMachine(codes)\n# im.run()\ntry:\n im.run()\nexcept Exception as e:\n repr(e)\n print(im.program)\n print(im.instPoint)\n exit(-1)\n","sub_path":"day5/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"295477867","text":"\nfrom flask_socketio import emit, join_room, close_room\n\nfrom v1.apps.games.models import Game, Player, Role, Vote\nfrom v1.apps.users.models import User\nfrom v1.apps.parsers import *\nfrom v1.apps.database import *\n\nfrom random import shuffle, SystemRandom\nfrom collections import Counter\nimport string\n\ndef randomCode(size=10):\n return ''.join(SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(10))\n\ndef create_deck(deck_size):\n if deck_size < 6:\n num_ww = 1\n else:\n num_ww = 2\n villager = Role.query.filter_by(name=\"Villager\").first()\n werewolf = Role.query.filter_by(name=\"Werewolf\").first()\n seer = Role.query.filter_by(name=\"Seer\").first()\n deck = [villager] * (deck_size - 3) + [werewolf] * 2 + [seer] * 1\n shuffle(deck)\n return deck\n\ndef create_player(game, user):\n new_player = Player(game=game, user=user)\n db.session.add(new_player)\n db.session.commit()\n return new_player\n\ndef determine_winner(game):\n living_players = game.players.filter_by(alive=True)\n evil_players = living_players.join(Role).filter(Role.evil == True).all()\n good_players = living_players.join(Role).filter(Role.evil == False).all()\n if len(good_players) <= len(evil_players):\n game.winner = \"evil\"\n db.session.add(game)\n return \"evil\"\n if len(evil_players) == 0:\n game.winner = \"good\"\n db.session.add(game)\n return \"good\"\n return None\n\ndef set_next_turn(game):\n game.current_turn = game.current_turn + 1\n db.session.add(game)\n db.session.commit()\n return True\n\ndef kill_player(player):\n player = Player.query.get(player['id'])\n player.alive = False\n db.session.add(player)\n db.session.commit()\n return True\n\ndef tally_all_votes(game, turn):\n results = {}\n votes = game.votes.filter_by(turn = turn)\n vote_roles = []\n for vote in votes.all():\n if vote.role is not None:\n vote_roles.append(vote.role.id)\n roles = Role.query.all()\n living_roles = [role for role in roles if role.id in vote_roles]\n for role in living_roles:\n result = get_vote_result(votes, turn, role)\n if result is not None:\n results[role.name] = parse_player(result)\n result = get_vote_result(votes, turn)\n if result is not None:\n results['default'] = parse_player(result)\n return results, len(living_roles) + 1\n\ndef vote_objects_to_ids(votes):\n results = []\n for vote in votes:\n results.append(vote.choice.id)\n return results\n\ndef get_vote_result(votes, turn, role=None):\n result = vote_objects_to_ids(votes.filter(Vote.role == role).all())\n tally = Counter(result).most_common(2)\n #Ensure that a tie is not made\n if len(tally) < 2 or tally[0][1] > tally[1][1]:\n choice = Player.query.get(tally[0][0])\n return choice\n else:\n return None\n\ndef verify_vote(voter, choice, turn, role = None):\n game = voter.game\n if voter.alive:\n if choice.alive:\n if role is not None:\n if voter.role == role:\n return True\n else:\n print(\"Roles don't match\", voter.role.name)\n return False\n else:\n return True\n return False\n\ndef save_vote(voter, choice, turn, role = None):\n game = voter.game\n vote = Vote.query.filter_by(voter=voter).filter_by(turn=turn).filter_by(role=role).first()\n if vote is None:\n vote = Vote(turn=turn, choice=choice, voter=voter, game=game, role=role)\n else:\n vote.choice=choice\n db.session.add(vote)\n db.session.commit()\n\n## Counts up the votes and returns True if all votes are tallied\ndef verify_everyone_voted(game, turn):\n living_players = game.players.filter(Player.alive == True)\n living_players_special = living_players.join(Role).filter(Role.name != \"Villager\")\n player_votes_count = len(living_players.all()) + len(living_players_special.all())\n votes = game.votes.filter_by(turn = turn).all()\n if player_votes_count == len(votes):\n return 1\n elif player_votes_count < len(votes):\n print(\"Something went wrong\")\n return 2 #Something went wrong\n else:\n return 0\n\ndef handle_results(results):\n if 'default' in results:\n kill_player(results['default'])\n if 'Werewolf' in results:\n kill_player(results['Werewolf'])\n\ndef delete_game(game):\n game_id = game.id\n game_code = game.code\n db.session.delete(game)\n db.session.commit()\n emit('game_deleted',\n {\n \"deleted\": game_id,\n }, room=game_code)\n close_room(game_code)\n","sub_path":"server/v1/apps/games/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"297809956","text":"# -*- coding: utf-8; -*-\n# vi: set encoding=utf-8\n\nimport sys\nimport json\n\n\ndef main(source):\n with open(source) as fp:\n d = json.load(fp)\n for country in d['features']:\n print(json.dumps(dict(\n id=country['id'],\n name=country['properties']['name'],\n geometry=country['geometry'],\n )))\n\n\nif __name__ == '__main__':\n \"\"\"\n This script converts the ``countries.geo.json`` from\n `johan/world.geo.json`_\n into JSON that can be imported into Crate.IO\n\n Usage: python convert.py countries.geo.json | gzip -vc > countries.json\n \"\"\"\n main(*sys.argv[1:])","sub_path":"all-gists/8a7297838593287195b0/snippet.py","file_name":"snippet.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"167868482","text":"def grade_test(key, student_answers):\n ## total_questions = 5\n total_questions = len(key)\n index = 0\n correct = 0\n ## while the index is less than the total number of questions\n ## 0 < 5\n while index < total_questions:\n ## if the key is equal to the student answer\n if key[index] == student_answers[index]:\n ## add one to the variable correct\n correct += 1\n ## return the number of correct answers\n ## divided by the total number of questions\n ## in this case 4 / 5 = .8\n return correct / total_questions\n\n","sub_path":"0_introduction_to_python_review/6_grade_test.py","file_name":"6_grade_test.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"563129626","text":"from torch import nn\nfrom torch.nn import functional as F\nimport torch\nfrom torchvision import models\nimport torchvision\nimport math\ninput_size = (448, 448)\n\nclass Interpolate(nn.Module):\n def __init__(self, size=None, scale_factor=None, mode='nearest', align_corners=False):\n super(Interpolate, self).__init__()\n self.interp = nn.functional.interpolate\n self.size = size\n self.mode = mode\n self.scale_factor = scale_factor\n self.align_corners = align_corners\n\n def forward(self, x):\n x = self.interp(x, size=self.size, scale_factor=self.scale_factor,\n mode=self.mode, align_corners=self.align_corners)\n return x\n\ndef conv3x3(in_, out):\n return nn.Conv2d(in_, out, 3, padding=1)\n\ndef conv1x1(in_planes, out_planes, stride=1):\n \"\"\"1x1 convolution\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\nclass dilated_conv(nn.Module):\n def __init__(self, in_, out):\n super().__init__()\n self.conv_3x3 = nn.Conv2d(in_, in_, kernel_size=3, stride=1, padding=1, groups=in_)\n self.bn_conv3x3 = nn.BatchNorm2d(in_)\n self.conv_1x1 = nn.Conv2d(in_, out, kernel_size=1)\n self.bn_conv1x1 = nn.BatchNorm2d(out)\n def forward(self, x):\n out = self.bn_conv1x1(self.conv_1x1(self.bn_conv3x3(self.conv_3x3(x))))\n return out\n\nclass ConvRelu(nn.Module):\n def __init__(self, in_, out):\n super().__init__()\n self.conv = dilated_conv(in_, out)\n self.activation = nn.ReLU(inplace=True)\n\n def forward(self, x):\n x = self.conv(x)\n x = self.activation(x)\n return x\n\nclass Se_module_diff(nn.Module):\n def __init__(self, inp, oup, Avg_size = 1, se_ratio = 1):\n super().__init__()\n self.avg = nn.AdaptiveAvgPool2d((Avg_size, Avg_size))\n num_squeezed_channels = max(1,int(inp / se_ratio))\n self._se_reduce = nn.Conv2d(in_channels=inp, out_channels=num_squeezed_channels, kernel_size=1)\n self._se_expand = nn.Conv2d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1)\n self.Avg_size = Avg_size\n self.reset_parameters()\n\n #x and z are different conv layer and z pass through more convs\n def reset_parameters(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[0] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n\n def forward(self, x, z):\n SIZE = z.size()\n y = self.avg(x)\n y = self._se_reduce(y)\n y = y * torch.sigmoid(y)\n y = self._se_expand(y)\n if self.Avg_size != 1:\n y = F.upsample_bilinear(y, size=[SIZE[2], SIZE[3]])\n z = torch.sigmoid(y) * z\n return z\n\nclass DecoderBlockV2(nn.Module):\n def __init__(self, in_channels, middle_channels, out_channels, is_deconv=True):\n super(DecoderBlockV2, self).__init__()\n self.in_channels = in_channels\n\n if is_deconv:\n \"\"\"\n Paramaters for Deconvolution were chosen to avoid artifacts, following\n link https://distill.pub/2016/deconv-checkerboard/\n \"\"\"\n\n self.block = nn.Sequential(\n ConvRelu(in_channels, middle_channels),\n nn.ConvTranspose2d(middle_channels, out_channels, kernel_size=4, stride=2,\n padding=1),\n nn.ReLU(inplace=True)\n )\n else:\n self.block = nn.Sequential(\n Interpolate(scale_factor=2, mode='bilinear'),\n ConvRelu(in_channels, middle_channels),\n ConvRelu(middle_channels, out_channels),\n )\n\n def forward(self, x):\n return self.block(x)\n\n# class ASPP(nn.Module):\n# def __init__(self, in_channels, out_channels):\n# super().__init__()\n# mid_channels = 4\n# self.conv_1x1_1 = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n# self.bn_conv_1x1_1 = nn.BatchNorm2d(out_channels)\n#\n# self.conv_3x3_1 = nn.Conv2d(in_channels, in_channels * mid_channels, kernel_size=3, stride=1, padding=3,\n# dilation=3, groups=in_channels)\n# self.bn_conv_3x3_1_1 = nn.BatchNorm2d(in_channels * mid_channels)\n# # self.conv_3x3_1_point = nn.Conv2d(in_channels * out_channels, out_channels, kernel_size=3, padding=1)\n# self.conv_3x3_1_point = nn.Conv2d(in_channels * mid_channels, out_channels, kernel_size=1)\n# self.bn_conv_3x3_1_2 = nn.BatchNorm2d(out_channels)\n#\n# self.conv_3x3_2 = nn.Conv2d(in_channels, in_channels * mid_channels, kernel_size=3, stride=1, padding=7,\n# dilation=7, groups=in_channels)\n# self.bn_conv_3x3_2_1 = nn.BatchNorm2d(in_channels * mid_channels)\n# # self.conv_3x3_2_point = nn.Conv2d(in_channels * out_channels, out_channels, kernel_size=3, padding=1)\n# self.conv_3x3_2_point = nn.Conv2d(in_channels * mid_channels, out_channels, kernel_size=1)\n# self.bn_conv_3x3_2_2 = nn.BatchNorm2d(out_channels)\n#\n# self.conv_3x3_3 = nn.Conv2d(in_channels, in_channels * mid_channels, kernel_size=3, stride=1, padding=11,\n# dilation=11, groups=in_channels)\n# self.bn_conv_3x3_3_1 = nn.BatchNorm2d(in_channels * mid_channels)\n# # self.conv_3x3_3_point = nn.Conv2d(in_channels * out_channels, out_channels, kernel_size=3, padding=1)\n# self.conv_3x3_3_point = nn.Conv2d(in_channels * mid_channels, out_channels, kernel_size=1)\n# self.bn_conv_3x3_3_2 = nn.BatchNorm2d(out_channels)\n#\n# self.avg_pool = nn.AdaptiveAvgPool2d(1)\n# self.conv_1x1_2 = nn.Conv2d(in_channels, out_channels, kernel_size=1)\n# self.bn_conv_1x1_2 = nn.BatchNorm2d(out_channels)\n# self.conv_1x1_3 = nn.Conv2d(out_channels * 4, out_channels, kernel_size=1) # (160 = 5*32)\n# self.bn_conv_1x1_3 = nn.BatchNorm2d(out_channels)\n# self.conv_1x1_4 = nn.Conv2d(out_channels, out_channels, kernel_size=1)\n# def forward(self, x):\n# feature_map_h = x.size()[2] # (== h/16)\n# feature_map_w = x.size()[3] # (== w/16)\n# out_1x1 = F.relu(self.bn_conv_1x1_1(self.conv_1x1_1(x))) # 111(shape: ([16, 256, 14, 14])\n# out_3x3_1 = F.relu(self.bn_conv_3x3_1_2(\n# self.conv_3x3_1_point(self.bn_conv_3x3_1_1(self.conv_3x3_1(x))))) # (shape: ([16, 4, 14, 14])\n# out_3x3_2 = F.relu(self.bn_conv_3x3_2_2(\n# self.conv_3x3_2_point(self.bn_conv_3x3_2_1(self.conv_3x3_2(x))))) # (shape: ([16, 4, 14, 14])\n# out_3x3_3 = F.relu(self.bn_conv_3x3_3_2(\n# self.conv_3x3_3_point(self.bn_conv_3x3_3_1(self.conv_3x3_3(x))))) # (shape: [16, 4, 14, 14])\n#\n# # 把输出改为256\n# # out_img = self.avg_pool(x) # (shape: ([16, 256, 1, 1])\n# # out_img = F.relu(self.bn_conv_1x1_2(self.conv_1x1_2(out_img))) # (shape: [16, 4, 1, 1])\n# # out_img = F.upsample(out_img, size=(feature_map_h, feature_map_w),mode=\"bilinear\") # (shape: ([16, 4, 14, 14])\n#\n# x = torch.cat([out_1x1, out_3x3_1, out_3x3_2, out_3x3_3],1) # (shape: ([16, 20, 14, 14])\n# x = F.relu(self.bn_conv_1x1_3(self.conv_1x1_3(x))) # (shape: [16, 4, 14, 14])\n# x_out = self.conv_1x1_4(x) #[16, 256, 14, 14]\n#\n# return x_out\n\n\n\nclass UNet16(nn.Module):\n def __init__(self, num_classes=1, num_filters=32, pretrained=False, is_deconv=False):\n \"\"\"\n :param num_classes:\n :param num_filters:\n :param pretrained:\n False - no pre-trained network used\n True - encoder pre-trained with VGG16\n :is_deconv:\n False: bilinear interpolation is used in decoder\n True: deconvolution is used in decoder\n \"\"\"\n super().__init__()\n self.num_classes = num_classes\n self.relu = nn.ReLU(inplace=True)\n self.pool = nn.MaxPool2d(2, 2)\n self.num_filters = num_filters\n # self.dilated_conv1 = nn.Sequential(nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1, bias=False),\n # self.relu)\n # self.dilated_conv2 = nn.Sequential(nn.Conv2d(128, 128, kernel_size=3, stride=2, padding=1, bias=False),\n # self.relu)\n # self.dilated_conv3 = nn.Sequential(nn.Conv2d(256, 256, kernel_size=3, stride=2, padding=1, bias=False),\n # self.relu)\n # self.dilated_conv4 = nn.Sequential(nn.Conv2d(512, 512, kernel_size=3, stride=2, padding=1, bias=False),\n # self.relu)\n\n #print(torchvision.models.vgg16(pretrained=pretrained))\n\n self.encoder = torchvision.models.vgg16(pretrained=pretrained).features\n\n\n\n self.conv1 = nn.Sequential(self.encoder[0],\n self.relu,\n self.encoder[2],\n self.relu)\n\n self.conv2 = nn.Sequential(self.encoder[5],\n self.relu,\n self.encoder[7],\n self.relu)\n\n self.conv3 = nn.Sequential(self.encoder[10],\n self.relu,\n self.encoder[12],\n self.relu,\n self.encoder[14],\n self.relu)\n\n self.conv4 = nn.Sequential(self.encoder[17],\n self.relu,\n self.encoder[19],\n self.relu,\n self.encoder[21],\n self.relu)\n # self.aspp = ASPP(in_channels=256, out_channels=256)\n self.conv5 = nn.Sequential(self.encoder[24],\n self.relu,\n self.encoder[26],\n self.relu,\n self.encoder[28],\n self.relu)\n\n\n\n self.center = DecoderBlockV2(512, num_filters * 16, num_filters * 8, is_deconv)\n\n self.se_module_diff1 = Se_module_diff(inp=64, oup=num_filters // 2)\n self.se_module_diff2 = Se_module_diff(inp=128, oup=num_filters)\n self.se_module_diff3 = Se_module_diff(inp=256, oup=num_filters * 2)\n self.se_module_diff4 = Se_module_diff(inp=512, oup=num_filters * 4)\n self.se_module_diff5 = Se_module_diff(inp=512, oup=num_filters * 8)\n \"\"\"dec5\"\"\"\n self.conv5_s = conv1x1(512, num_filters * 8)\n self.dec5 = DecoderBlockV2(num_filters * 16, num_filters * 16, num_filters * 8, is_deconv)\n\n \"\"\"dec4\"\"\"\n self.dec5_s = conv1x1(num_filters * 8, num_filters * 4)\n self.conv4_s = conv1x1(512, num_filters * 4)\n self.center_e = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s = conv1x1(num_filters * 8, num_filters * 4)\n self.dec4 = DecoderBlockV2(num_filters * 4 * 3, num_filters * 4 * 2, num_filters * 4, is_deconv)\n self.deconv = nn.Sequential(self.dec5_s,\n self.conv4_s)\n\n \"\"\"dec3\"\"\"\n self.dec5_e1 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec5_s1 = conv1x1(num_filters * 4, num_filters * 2)\n self.dec4_s1 = conv1x1(num_filters * 4, num_filters * 2)\n self.conv3_s = conv1x1(256, num_filters * 2)\n self.center_e1 = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s1 = conv1x1(num_filters * 4, num_filters * 2)\n self.dec3 = DecoderBlockV2(num_filters * 2 * 4, num_filters * 2 * 2, num_filters * 2, is_deconv)\n\n \"\"\"dec2\"\"\"\n self.dec5_e2 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec5_s2 = conv1x1(num_filters * 2, num_filters)\n self.dec4_e2 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec4_s2 = conv1x1(num_filters * 2, num_filters)\n self.dec3_s2 = conv1x1(num_filters * 2, num_filters)\n self.conv2_s = conv1x1(128, num_filters)\n self.center_e2 = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s2 = conv1x1(num_filters * 2, num_filters)\n self.dec2 = DecoderBlockV2(num_filters * 5, num_filters * 3, num_filters, is_deconv)\n\n \"\"\"dec1\"\"\"\n self.dec5_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec5_s3 = conv1x1(num_filters, num_filters//2)\n self.dec4_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec4_s3 = conv1x1(num_filters, num_filters//2)\n self.dec3_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec3_s3 = conv1x1(num_filters, num_filters//2)\n self.dec2_s3 = conv1x1(num_filters, num_filters//2)\n self.conv1_s = conv1x1(64, num_filters//2) \n self.center_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s3 = conv1x1(num_filters, num_filters//2)\n self.dec1 = ConvRelu(num_filters * 3, num_filters)\n\n\n self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1)\n\n def forward(self, x):\n conv1 = self.conv1(x) #64\n conv2 = self.conv2(self.pool(conv1)) #128\n conv3 = self.conv3(self.pool(conv2)) #256\n conv4 = self.conv4(self.pool(conv3)) #512\n conv5 = self.conv5(self.pool(conv4)) #512\n\n\n\n\n center = self.center(self.pool(conv5)) #256\n\n \"\"\"dec5\"\"\"\n conv5_s = self.conv5_s(conv5)\n conv5_sse = self.se_module_diff5(conv5, conv5_s)\n dec5 = self.dec5(torch.cat([center, conv5_sse], 1)) # 256\n\n \"\"\"dec4\"\"\"\n dec5_s = self.dec5_s(dec5)\n conv4_s = self.conv4_s(conv4)\n conv4_sse = self.se_module_diff4(conv4, conv4_s)\n center_e = self.center_e(center)\n center_s = self.center_s(center_e)\n dec4 = self.dec4(torch.cat([dec5_s, conv4_sse, center_s], 1)) # 128\n\n \"\"\"dec3\"\"\"\n dec5_e1 = self.dec5_e1(dec5_s)\n dec5_s1 = self.dec5_s1(dec5_e1)\n dec4_s1 = self.dec4_s1(dec4)\n conv3_s = self.conv3_s(conv3)\n conv3_sse = self.se_module_diff3(conv3, conv3_s)\n center_e1 = self.center_e1(center_s)\n center_s1 = self.center_s1(center_e1)\n dec3 = self.dec3(torch.cat([dec5_s1, dec4_s1, conv3_sse, center_s1], 1)) # 64\n\n \"\"\"dec2\"\"\"\n dec5_e2 = self.dec5_e2(dec5_s1)\n dec5_s2 = self.dec5_s2(dec5_e2)\n dec4_e2 = self.dec5_e2(dec4_s1)\n dec4_s2 = self.dec4_s2(dec4_e2)\n dec3_s2 = self.dec3_s2(dec3)\n conv2_s = self.conv2_s(conv2)\n conv2_sse = self.se_module_diff2(conv2, conv2_s)\n center_e2 = self.center_e2(center_s1)\n center_s2 = self.center_s2(center_e2)\n dec2 = self.dec2(torch.cat([dec5_s2, dec4_s2, dec3_s2, conv2_sse, center_s2], 1)) # 32\n\n \"\"\"dec1\"\"\"\n dec5_e3 = self.dec5_e3(dec5_s2)\n dec5_s3 = self.dec5_s3(dec5_e3)\n dec4_e3 = self.dec4_e3(dec4_s2)\n dec4_s3 = self.dec4_s3(dec4_e3)\n dec3_e3 = self.dec3_e3(dec3_s2)\n dec3_s3 = self.dec3_s3(dec3_e3)\n dec2_s3 = self.dec2_s3(dec2)\n conv1_s = self.conv1_s(conv1)\n conv1_sse = self.se_module_diff1(conv1, conv1_s)\n center_e3 = self.center_e3(center_s2)\n center_s3 = self.center_s3(center_e3)\n dec1 = self.dec1(torch.cat([dec5_s3, dec4_s3, dec3_s3, dec2_s3, conv1_sse, center_s3], 1)) # 32\n\n # sse1 = self.se_module_diff1(conv1, dec1)\n\n if self.num_classes > 1:\n x_out = F.log_softmax(self.final(dec1), dim=1)\n else:\n x_out = self.final(dec1) #32/1\n #x_out = F.sigmoid(x_out)\n\n return x_out\n\nclass UNetResNet(nn.Module):\n \"\"\"PyTorch U-Net model using ResNet(34, 101 or 152) encoder.\n UNet: https://arxiv.org/abs/1505.04597\n ResNet: https://arxiv.org/abs/1512.03385\n Proposed by Alexander Buslaev: https://www.linkedin.com/in/al-buslaev/\n Args:\n encoder_depth (int): Depth of a ResNet encoder (34, 101 or 152).\n num_classes (int): Number of output classes.\n num_filters (int, optional): Number of filters in the last layer of decoder. Defaults to 32.\n dropout_2d (float, optional): Probability factor of dropout layer before output layer. Defaults to 0.2.\n pretrained (bool, optional):\n False - no pre-trained weights are being used.\n True - ResNet encoder is pre-trained on ImageNet.\n Defaults to False.\n is_deconv (bool, optional):\n False: bilinear interpolation is used in decoder.\n True: deconvolution is used in decoder.\n Defaults to False.\n \"\"\"\n\n def __init__(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2,\n pretrained=False, is_deconv=False):\n super().__init__()\n self.num_classes = num_classes\n self.dropout_2d = dropout_2d\n\n if encoder_depth == 34:\n self.encoder = torchvision.models.resnet34(pretrained=pretrained)\n bottom_channel_nr = 512\n elif encoder_depth == 101:\n self.encoder = torchvision.models.resnet101(pretrained=pretrained)\n bottom_channel_nr = 2048\n elif encoder_depth == 152:\n self.encoder = torchvision.models.resnet152(pretrained=pretrained)\n bottom_channel_nr = 2048\n else:\n raise NotImplementedError('only 34, 101, 152 version of Resnet are implemented')\n\n self.pool = nn.MaxPool2d(2, 2)\n\n self.relu = nn.ReLU(inplace=True)\n\n self.conv1 = nn.Sequential(self.encoder.conv1,\n self.encoder.bn1,\n self.encoder.relu,\n self.pool)\n\n self.conv2 = self.encoder.layer1 #64\n\n self.conv3 = self.encoder.layer2 #128\n\n self.conv4 = self.encoder.layer3 #256\n\n self.conv5 = self.encoder.layer4\n\n\n self.center = DecoderBlockV2(bottom_channel_nr, num_filters * 8 * 2, num_filters * 8, is_deconv)\n\n self.se_module_diff1 = Se_module_diff(inp=64, oup=16)\n self.se_module_diff2 = Se_module_diff(inp=64, oup=32)\n self.se_module_diff3 = Se_module_diff(inp=128, oup=64)\n self.se_module_diff4 = Se_module_diff(inp=256, oup=128)\n self.se_module_diff5 = Se_module_diff(inp=512, oup=256)\n\n \"\"\"dec5\"\"\"\n self.conv5_s = conv1x1(512, 256)\n self.dec5 = DecoderBlockV2(256 * 2, 256 * 2, 256, is_deconv)\n\n \"\"\"dec4\"\"\"\n self.dec5_s = conv1x1(256, 128)\n self.conv4_s = conv1x1(256, 128)\n self.center_e = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s = conv1x1(256, 128)\n self.dec4 = DecoderBlockV2(128 * 3, 128 * 2, 128, is_deconv)\n self.deconv = nn.Sequential(self.dec5_s,\n self.conv4_s)\n\n \"\"\"dec3\"\"\"\n self.dec5_e1 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec5_s1 = conv1x1(128, 64)\n self.dec4_s1 = conv1x1(128, 64)\n self.conv3_s = conv1x1(128, 64)\n self.center_e1 = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s1 = conv1x1(128, 64)\n self.dec3 = DecoderBlockV2(64 * 4, 64 * 2, 64, is_deconv)\n\n \"\"\"dec2\"\"\"\n self.dec5_e2 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec5_s2 = conv1x1(64, 32)\n self.dec4_e2 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec4_s2 = conv1x1(64, 32)\n self.dec3_s2 = conv1x1(64, 32)\n self.conv2_s = conv1x1(64, 32)\n self.center_e2 = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s2 = conv1x1(64, 32)\n self.dec2 = DecoderBlockV2(32 * 5, 32 * 3, 32, is_deconv)\n\n \"\"\"dec1\"\"\"\n self.dec5_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec5_s3 = conv1x1(32, 16)\n self.dec4_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec4_s3 = conv1x1(32, 16)\n self.dec3_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.dec3_s3 = conv1x1(32, 16)\n self.dec2_s3 = conv1x1(32, 16)\n self.conv1_e = Interpolate(scale_factor=2, mode='bilinear')\n self.conv1_s = conv1x1(64, 16)\n self.center_e3 = Interpolate(scale_factor=2, mode='bilinear')\n self.center_s3 = conv1x1(32, 16)\n self.dec1 = DecoderBlockV2(16 * 6, 16 * 3, num_filters, is_deconv)\n\n self.dec0 = ConvRelu(num_filters, num_filters)\n\n self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1)\n def forward(self, x):\n conv1 = self.conv1(x)\n conv2 = self.conv2(conv1)\n conv3 = self.conv3(conv2)\n conv4 = self.conv4(conv3)\n conv5 = self.conv5(conv4)\n\n pool = self.pool(conv5)\n center = self.center(pool)\n\n \"\"\"dec5\"\"\"\n conv5_s = self.conv5_s(conv5)\n conv5_sse = self.se_module_diff5(conv5, conv5_s)\n dec5 = self.dec5(torch.cat([center, conv5_sse], 1)) # 256\n\n \"\"\"dec4\"\"\"\n dec5_s = self.dec5_s(dec5)\n conv4_s = self.conv4_s(conv4)\n conv4_sse = self.se_module_diff4(conv4, conv4_s)\n center_e = self.center_e(center)\n center_s = self.center_s(center_e)\n dec4 = self.dec4(torch.cat([dec5_s, conv4_sse, center_s], 1)) # 128\n\n \"\"\"dec3\"\"\"\n dec5_e1 = self.dec5_e1(dec5_s)\n dec5_s1 = self.dec5_s1(dec5_e1)\n dec4_s1 = self.dec4_s1(dec4)\n conv3_s = self.conv3_s(conv3)\n conv3_sse = self.se_module_diff3(conv3, conv3_s)\n center_e1 = self.center_e1(center_s)\n center_s1 = self.center_s1(center_e1)\n dec3 = self.dec3(torch.cat([dec5_s1, dec4_s1, conv3_sse, center_s1], 1)) # 64\n\n \"\"\"dec2\"\"\"\n dec5_e2 = self.dec5_e2(dec5_s1)\n dec5_s2 = self.dec5_s2(dec5_e2)\n dec4_e2 = self.dec5_e2(dec4_s1)\n dec4_s2 = self.dec4_s2(dec4_e2)\n dec3_s2 = self.dec3_s2(dec3)\n conv2_s = self.conv2_s(conv2)\n conv2_sse = self.se_module_diff2(conv2, conv2_s)\n center_e2 = self.center_e2(center_s1)\n center_s2 = self.center_s2(center_e2)\n dec2 = self.dec2(torch.cat([dec5_s2, dec4_s2, dec3_s2, conv2_sse, center_s2], 1)) # 32\n\n \"\"\"dec1\"\"\"\n dec5_e3 = self.dec5_e3(dec5_s2)\n dec5_s3 = self.dec5_s3(dec5_e3)\n dec4_e3 = self.dec4_e3(dec4_s2)\n dec4_s3 = self.dec4_s3(dec4_e3)\n dec3_e3 = self.dec3_e3(dec3_s2)\n dec3_s3 = self.dec3_s3(dec3_e3)\n dec2_s3 = self.dec2_s3(dec2)\n conv1_e = self.conv1_e(conv1)\n conv1_s = self.conv1_s(conv1_e)\n conv1_sse = self.se_module_diff1(conv1, conv1_s)\n center_e3 = self.center_e3(center_s2)\n center_s3 = self.center_s3(center_e3)\n dec1 = self.dec1(torch.cat([dec5_s3, dec4_s3, dec3_s3, dec2_s3, conv1_sse, center_s3], 1)) # 32\n dec0 = self.dec0(dec1)\n\n return self.final(F.dropout2d(dec0, p=self.dropout_2d))\n","sub_path":"crack_segmentation-master/sse_cracknet_dilatedconv.py","file_name":"sse_cracknet_dilatedconv.py","file_ext":"py","file_size_in_byte":23945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"234286129","text":"#! /usr/bin/env python3\n\nimport requests,re,logging,os,sys\n\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')\n\nlogging.debug('Start download png...')\n\n#os.chdir(os.path.join('C:','Users','luo','Desktop'))\nos.chdir(r'/Users/luoxiaolei/Desktop')\n\nlogging.debug(os.getcwd())\n\nsourceUrl = 'https://github.com/Alvin9999/new-pac/wiki/ss%E5%85%8D%E8%B4%B9%E8%B4%A6%E5%8F%B7'\n\npngUrlRegex = re.compile(r'https://.*\\.PNG')\n\nupdateDateRegex = re.compile(r'\\d{4}年\\d{1,2}月\\d{1,2}日')\n\nresponse = requests.get(sourceUrl)\n\nresponse.raise_for_status()\n\nhtmlSource = response.text\n\npngUrl = pngUrlRegex.search(htmlSource).group()\n\nupdateDate = updateDateRegex.search(htmlSource).group()\n\nlogging.debug('pngUrl:'+pngUrl+'\\n'+'updateDate:'+updateDate)\n\npngResponse = requests.get(pngUrl)\n\nfor filename in os.listdir():\n if filename.endswith('.png') and filename == updateDate+'.png':\n logging.debug(filename)\n logging.debug('png existed')\n sys.exit()\n #else:\n #os.unlink(filename)\n #sys.exit()\n\nfile = open(updateDate+'.png','wb')\n\n\nfor chunk in pngResponse.iter_content(1024*5):#byte\n file.write(chunk)\n\nfile.close()\n\nlogging.debug('download completed...')\n","sub_path":"project/01checkProxy/checkProxyForMac.py","file_name":"checkProxyForMac.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"115605309","text":"\r\nfrom helperfun import *\r\n\r\n\r\n\r\n\r\n'''\r\n parse pdb with only nanotube atoms/conects\r\n\r\n'''\r\nif debug:\r\n print(\"label: \"+ label)\r\n\r\n# open pdb file\r\nempty_tube_file = open(\"../empty_tube/{}.pdb\".format(label), 'r')\r\n# seperate empty tube pdb file by header, atoms, conect\r\nheader, tube_atoms, tube_conect = seperate_empty_tube(empty_tube_file)\r\n# close it\r\nempty_tube_file.close()\r\n\r\n\r\n'''\r\n compute pdb atoms/conects for water molecules\r\n \r\n'''\r\n# get x,y coordinants representing the center of the Nano Tube \r\ntube_center = get_tube_center(tube_atoms)\r\nstartn = len(tube_atoms)+1\r\noxygen_quantity = calculate_water_molecules_inside_nanotube(rho)\r\noxygens = assign_positions_to_oxygens_list_pdb_new(oxygen_quantity, tube_center, startn)\r\n\r\nhydro1 = adding_H1(len(oxygens), angle, bond_length)\r\nhydro2 = adding_H2(hydro1, angle, bond_length)\r\nh1_final = final_position_for_H(oxygens, hydro1) #move the water atoms from the origin to the random positions generated in oxygens\r\nh2_final = final_position_for_H(oxygens, hydro2)\r\n\r\nwater_positions = water_class_pdb(oxygens, 4, h1_final, h2_final, 3, startn)\r\noxygens_to_print = water_positions.oxy_processed()\r\nhydro1_to_print = water_positions.hydro_processed1()\r\nhydro2_to_print = water_positions.hydro_processed2()\r\n\r\nwater_atoms = oxygens_to_print + hydro1_to_print + hydro2_to_print\r\nwater_atoms = sorted(water_atoms)\r\nwater_conect = water_conections(len(oxygens), startn)\r\n\r\n\r\n# centerAtoms(tube_atoms, tube_center)\r\ncenterAtoms(water_atoms, tube_center)\r\n\r\n'''\r\n output pdb of water-filled nanotube\r\n\r\n'''\r\nif debug:\r\n print(\"new tube center: \", get_tube_center(tube_atoms))\r\n print(\"tube atoms: %d\" % len(tube_atoms))\r\n print(\"water atoms: %d\" % len(water_atoms))\r\n print(\"total atoms: %d\" % (len(water_atoms) + len(tube_atoms)))\r\n\r\n# final_out = open(\"../filled_tube/{}.pdb\".format(label), 'w')\r\n# rebo/norebo in filename\r\nfinal_out = open(\"../filled_tube/{}.pdb\".format(label), 'w')\r\n\r\n\r\n\r\nfinal_out.write(header)\r\n\r\nfor atom in tube_atoms:\r\n\tline = formatPdbRow(atom, True)\r\n\tfinal_out.write(line)\r\nfor atom in water_atoms:\r\n line = formatPdbRow(atom, False)\r\n final_out.write(line)\r\nfor conect in tube_conect+water_conect:\r\n final_out.write(conect)\r\n\r\nfinal_out.write(\"END\\n\")\r\nfinal_out.close()\r\n\r\n\r\n\r\n\r\n'''\r\n output datafile of water-filled nanotube\r\n\r\n'''\r\n\r\nbonds = []\r\nangles = []\r\n\r\n# with open('data_file/{}.data'.format(label), 'w') as \r\n# datafile = open('../data_file/{}.data'.format(label), 'w')\r\n# rebo/norebo\r\ndatafile = open('../data_file/{}.data'.format(label), 'w')\r\n\r\n# format bonds,angles for water only\r\nfor conect in water_conect:\r\n conect = conect.split()\r\n if(len(conect) == 4):\r\n formatWaterBond(bonds, conect)\r\n formatWaterAngle(angles, conect)\r\n\r\ndataFileHeader(datafile, len(tube_atoms)+len(water_atoms), len(bonds), len(angles))\r\ndataFileMass(datafile)\r\ndataFileAtoms(datafile, tube_atoms+water_atoms)\r\ndataFileBonds(datafile, bonds)\r\ndataFileAngles(datafile, angles)","sub_path":"spencer/src/addwater.py","file_name":"addwater.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"107486426","text":"#!/usr/bin/env python3\n# coding: utf-8\n\nimport pyspark\nfrom pyspark import SparkConf\nfrom pyspark import SparkContext\nfrom pyspark.sql import SparkSession\nimport sys\n\n\"\"\" Create a SparkSession to use Spark\"\"\"\nconf = SparkConf().set('spark.driver.memory', '6G') \\\n .set('spark.executor.memory', \"4G\")\nconf = SparkConf()\nsc = SparkContext(conf=conf)\nspark = SparkSession(sc).builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n\n# Getting output_data directory from the bash command inside the BashOperator\noutput_data = sys.argv[1]\n\n# Read data from airport_i94port_join_table\ndf = spark.read.parquet(output_data + \"airport_i94port_join_table_cleaned.parquet\")\n\n# Select the columns \ndf_airport = df.select(\"ident\", \"type\", \"name\", \"i94port_code\", \"state_code\", 'elevation_ft', 'longitude', 'latitude')\n\n# Cahnge names of columns\nnames = ['airport_id', \"airport_type\", 'airport_name', 'i94port_code', 'state_code', 'elevation_ft', 'airport_longitude', 'airport_latitude']\ndf = df_airport.toDF(*names)\n\n# Write airport_table to output_data directory\ndf_airport.write.parquet(output_data + \"airport_table.parquet\", \n mode =\"overwrite\", partitionBy=[\"i94port_code\"])\n\n# print to the log\nprint(\"Write airport_table.parquet\")","sub_path":"src/airport.py","file_name":"airport.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"215357967","text":"from big_ol_pile_of_manim_imports import *\n\nclass Shapes(Scene):\n CONFIG ={\n \"color\": BLUE\n }\n def construct(self):\n print(\"Start\")\n dot = Dot()\n circle = Circle(radius= 1, color=self.color)\n circle2 = Circle(radius= 1.1)\n circle2.set_color(GREEN)\n self.add(dot)\n self.play(GrowFromCenter(circle),GrowFromCenter(circle2))\n self.wait(2)\n\n\n\nif __name__ == \"__main__\":\n module_name = os.path.basename(__file__)\n command = \"python3.7 -m manim -a -pl \" + module_name\n os.system(command)\n\n","sub_path":"Tutorial/n0_shapes_minimal_example+circle.py","file_name":"n0_shapes_minimal_example+circle.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"472732665","text":"#!/usr/bin/env python3\n\n'''\nGET OLD TWEETS\nCommand line wrapper\nSimon Lindgren 200219\n'''\n\nimport got3 as got\nimport sqlite3\nimport re\nimport sys\nimport datetime\n\n\ndef main():\n print(\"GET OLD TWEETS\")\n print(\"==============\")\n project_setup()\n create_database()\n run_search()\n remove_duplicates()\n\n\ndef project_setup():\n projname = input(\"Project name? \")\n global dbname\n dbname = (projname + \".db\")\n\n print(\"Searches can by done by search term(s), by username(s), or by both in combination\")\n\n # QUERYSEARCH\n print(\"\")\n print(\"Search terms, one or several separated by comma\")\n print(\"Leave empty to only search by username\")\n global keywords\n keywords = \"\"\n keywords = input('e.g. monkey,\"time for bananas\",#ape2020,\"donkey kong\": ')\n\n # USERNAMES\n print(\"\")\n print(\"Usernames, one or several separated by space\")\n print(\"Leave empty to only search by terms\")\n global usernames\n usernames = \"\"\n usernames = input('e.g. @nintendo @jupyter (with or without the \"@\"): ')\n usernames = [un for un in usernames.split()]\n\n # DATES\n print(\"\")\n print(\"Enter date range for search in YYYY-NN-DD format\")\n global since\n since = (input(\"start date UTC (included in search): \"))\n validate(since)\n global until\n until = (input(\"end date UTC (excluded from search): \"))\n validate(until)\n\n # TOPTWEETS\n print(\"\")\n print(\"Do you want to get only the Top Tweets?\")\n global toptweets\n top_t = input(\"y/n? \")\n if top_t == \"y\":\n toptweets = True\n else:\n toptweets = False\n\n #MAXTWEETS\n print(\"\")\n print(\"\\nEnter maximum number of tweets to get per search term, or set 0 to get all possible tweets\")\n global maxtweets\n maxtweets = (input(\"max tweets \"))\n if maxtweets.isnumeric():\n maxtweets = int(maxtweets)\n pass\n else:\n print(\"You did not enter a numeric value\")\n sys.exit()\n\ndef create_database():\n try:\n conn = sqlite3.connect(dbname)\n c = conn.cursor()\n c.execute(\"\"\"CREATE TABLE tweets (\n tweet_id TEXT,\n author TEXT,\n in_reply_to TEXT,\n tweet TEXT,\n date TEXT,\n retweets INT,\n favourites INT,\n mentions TEXT,\n hashtags TEXT,\n geo TEXT)\n \"\"\")\n conn.close()\n except:\n print(\"A database with this name already exists\")\n sys.exit()\n\ndef run_search():\n\n for kw in keywords.split(\",\"):\n\n print(\"Getting tweets for \" + kw)\n\n conn = sqlite3.connect(dbname)\n tweetCriteria = got.manager.TweetCriteria()\n\n # Set the search parameters that we always set\n tweetCriteria.setMaxTweets(maxtweets)\n tweetCriteria.setSince(since)\n tweetCriteria.setUntil(until)\n tweetCriteria.setTopTweets(toptweets)\n tweetCriteria.setEmoji(\"unicode\")\n\n if len(keywords) != 0:\n tweetCriteria.setQuerySearch(kw)\n if len(usernames) != 0:\n tweetCriteria.setUsername(usernames)\n\n\n tweets=got.manager.TweetManager.getTweets(tweetCriteria)\n for t in tweets:\n tweet_id = t.id\n author = t.username\n in_reply_to = t.to\n tweet = t.text\n date = t.date\n retweets = t.retweets\n favourites = t.favorites\n mentions = t.mentions\n hashtags = t.hashtags\n geo = t.geo\n\n\n conn.execute('INSERT INTO tweets (tweet_id, author, in_reply_to, tweet, date, retweets, favourites, mentions, hashtags,geo) VALUES (?,?,?,?,?,?,?,?,?,?)',\\\n (tweet_id, author, in_reply_to, tweet, date, retweets, favourites, mentions, hashtags, geo))\n conn.commit()\n\ndef remove_duplicates():\n\n conn = sqlite3.connect(dbname)\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE temp_table as SELECT DISTINCT * FROM tweets\")\n cur.execute(\"DELETE from tweets\")\n conn.commit()\n\n cur.execute(\"INSERT INTO tweets SELECT * FROM temp_table\")\n cur.execute(\"DELETE from temp_table\")\n conn.commit()\n\n cur.execute(\"SELECT max(rowid) from tweets\")\n n = cur.fetchone()[0]\n print(\"\\n\" + str(n) + \" tweets written to database\\n\")\n\ndef validate(date_text):\n try:\n datetime.datetime.strptime(date_text, '%Y-%m-%d')\n except ValueError:\n raise ValueError(\"Incorrect data format, should be YYYY-MM-DD\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"got3.py","file_name":"got3.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"389712824","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\nimport tensorflow as TensorFlow\nimport cv2\nimport sys\nsys.path.append(\"game/\")\nimport wrapped_flappy_bird as Game\nimport random\nimport numpy as Numpy\nfrom collections import deque\n\nGAME = 'bird' # the name of the game being played for log files\nACTIONS = 2 # number of valid actions\nGAMMA = 0.99 # decay rate of past observations\nOBSERVE = 10000\nREPLAY_MEMORY = 50000 # number of previous transitions to remember\nBATCH = 32 # size of minibatch\nFRAME_PER_ACTION = 1\n\ndef CreateWeightVariable(shape):\n initial = TensorFlow.truncated_normal(shape, stddev = 0.01)\n return TensorFlow.Variable(initial)\n\ndef CreateBiasVariable(shape):\n initial = TensorFlow.constant(0.01, shape = shape)\n return TensorFlow.Variable(initial)\n\ndef Convolution2D(x, W, stride):\n return TensorFlow.nn.conv2d(x, W, strides = [1, stride, stride, 1], padding = \"SAME\")\n\ndef MaxPool2x2(x):\n return TensorFlow.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = \"SAME\")\n\ndef CreateNetwork():\n # network weights\n convolutionWeights1 = CreateWeightVariable([8, 8, 4, 32])\n convolutionBias1 = CreateBiasVariable([32])\n\n convolutionWeights2 = CreateWeightVariable([4, 4, 32, 64])\n convolutionBias2 = CreateBiasVariable([64])\n\n convolutionWeights3 = CreateWeightVariable([3, 3, 64, 64])\n convolutionBias3 = CreateBiasVariable([64])\n\n fullyConnectedWeights1 = CreateWeightVariable([1600, 512])\n fullyConnectedBias1 = CreateBiasVariable([512])\n\n fullyConnectedWeights2 = CreateWeightVariable([512, ACTIONS])\n fullyConnectedBias2 = CreateBiasVariable([ACTIONS])\n\n # input layer\n inputStates = TensorFlow.placeholder(\"float\", [None, 80, 80, 4])\n\n # hidden layers\n convolutionHiddenLayer1 = TensorFlow.nn.relu(Convolution2D(inputStates, convolutionWeights1, 4) + convolutionBias1)\n hiddenLayer1Pool = MaxPool2x2(convolutionHiddenLayer1)\n\n convolutionHiddenLayer2 = TensorFlow.nn.relu(Convolution2D(hiddenLayer1Pool, convolutionWeights2, 2) + convolutionBias2)\n #h_pool2 = max_pool_2x2(h_conv2)\n\n convolutionHiddenLayer3 = TensorFlow.nn.relu(Convolution2D(convolutionHiddenLayer2, convolutionWeights3, 1) + convolutionBias3)\n #h_pool3 = max_pool_2x2(h_conv3)\n\n #h_pool3_flat = tf.reshape(h_pool3, [-1, 256])\n reshapedConvolutionHiddenLayer3 = TensorFlow.reshape(convolutionHiddenLayer3, [-1, 1600])\n\n fullyConnectedHiddenLayer1 = TensorFlow.nn.relu(TensorFlow.matmul(reshapedConvolutionHiddenLayer3, fullyConnectedWeights1) + fullyConnectedBias1)\n\n # readout layer\n outputs = TensorFlow.matmul(fullyConnectedHiddenLayer1, fullyConnectedWeights2) + fullyConnectedBias2\n\n return inputStates, outputs, fullyConnectedHiddenLayer1\n\ndef TrainNetwork(inputStates, outputs, network, interactiveSession):\n # define the cost function\n a = TensorFlow.placeholder(\"float\", [None, ACTIONS])\n y = TensorFlow.placeholder(\"float\", [None])\n valueOutputs = TensorFlow.reduce_sum(TensorFlow.multiply(outputs, a), reduction_indices=1)\n cost = TensorFlow.reduce_mean(TensorFlow.square(y - valueOutputs))\n train_step = TensorFlow.train.AdamOptimizer(1e-6).minimize(cost)\n\n # open up a game state to communicate with emulator\n gameState = Game.GameState()\n\n # store the previous observations in replay memory\n gameRecordDqueue = deque();\n gameRecord = deque();\n scores = deque();\n currentScore = 0.;\n \n globalMax = 0;\n gameCount = 1;\n\n # get the first state by doing nothing and preprocess the image to 80x80x4\n do_nothing = Numpy.zeros(ACTIONS)\n do_nothing[0] = 1\n x_t, r_0, terminal = gameState.frame_step(do_nothing)\n x_t = cv2.cvtColor(cv2.resize(x_t, (80, 80)), cv2.COLOR_BGR2GRAY)\n ret, x_t = cv2.threshold(x_t,1,255,cv2.THRESH_BINARY)\n currentStates = Numpy.stack((x_t, x_t, x_t, x_t), axis=2)\n\n # saving and loading networks\n #saver = TensorFlow.train.Saver()\n interactiveSession.run(TensorFlow.global_variables_initializer())\n saver = TensorFlow.train.Saver()\n saver.restore(interactiveSession, \"SavedNetwork/InitialModel.ckpt\")\n print(\"Model restored.\")\n\n # start training\n t = 0\n \n while True:\n # choose an action epsilon greedily\n outputValues = outputs.eval(feed_dict={inputStates : [currentStates]})[0]\n actions = Numpy.zeros([ACTIONS])\n actionIndex = 0\n if t % FRAME_PER_ACTION == 0:\n actionIndex = Numpy.argmax(outputValues)\n actions[actionIndex] = 1\n else:\n actions[0] = 1 # do nothing\n\n # run the selected action and observe next state and reward\n coloredAfterState, reward, terminal = gameState.frame_step(actions)\n afterState = cv2.cvtColor(cv2.resize(coloredAfterState, (80, 80)), cv2.COLOR_BGR2GRAY)\n ret, afterState = cv2.threshold(afterState, 1, 255, cv2.THRESH_BINARY)\n afterState = Numpy.reshape(afterState, (80, 80, 1))\n #s_t1 = np.append(x_t1, s_t[:,:,1:], axis = 2)\n afterStates = Numpy.append(afterState, currentStates[:, :, :3], axis=2)\n reward = int(reward)\n currentScore += reward\n\n # store the transition in Dequeue\n gameRecord.append((currentStates, actions, reward, afterStates, terminal))\n\n if terminal:\n averageScore = currentScore / len(gameRecord)\n print(\"Game\", gameCount, \" score: \", currentScore, \"average score: \", averageScore, \" t: \", t);\n with open('result.txt', 'a') as file:\n file.writelines(str(currentScore) + \"\\n\")\n for i in range(0, len(gameRecord)):\n x = gameRecord.popleft()\n sameRecord = (x[0], x[1], averageScore, x[3], x[4])\n gameRecordDqueue.append(sameRecord);\n if len(gameRecordDqueue) > REPLAY_MEMORY:\n gameRecordDqueue.popleft()\n scores.append(currentScore);\n if len(scores) > 100:\n scores.popleft();\n if currentScore > globalMax:\n globalMax = currentScore\n currentScore = 0;\n if gameCount % 1000 == 0:\n savePath = saver.save(interactiveSession, \"SavedNetwork/model.ckpt\")\n print(\"Model saved in file: %s\" % savePath)\n if gameCount % 100 == 0:\n print(\"=========================\");\n print(\"AverageScore: \", Numpy.mean(numpyScores), \", Deviation: \", Numpy.std(numpyScores));\n print(\"MaxScore: \", Numpy.max(scores));\n print(\"GlobalMaxScore: \", globalMax);\n print(\"=========================\");\n gameCount = gameCount + 1;\n\n if t > OBSERVE:\n # sample a minibatch to train on\n batch = random.sample(gameRecordDqueue, BATCH)\n\n # get the batch variables\n currentStatesBatch = [d[0] for d in batch]\n actionsBatch = [d[1] for d in batch]\n rewardBatch = [d[2] for d in batch]\n afterStateBatch = [d[3] for d in batch]\n\n valueBatch = []\n afterStateBatchOutput = outputs.eval(feed_dict = {inputStates : afterStateBatch})\n for i in range(0, len(batch)):\n terminal = batch[i][4]\n # if terminal, only equals reward\n if terminal:\n valueBatch.append(-1)\n else:\n valueBatch.append(rewardBatch[i] + GAMMA * Numpy.max(afterStateBatchOutput[i]))\n\n # perform gradient step\n train_step.run(feed_dict = {\n y : valueBatch,\n a : actionsBatch,\n inputStates : currentStatesBatch}\n )\n\n # update the old values\n currentStates = afterStates\n t += 1\n\ndef PlayGame():\n interactiveSession = TensorFlow.InteractiveSession()\n inputStates, outputs, network = CreateNetwork()\n TrainNetwork(inputStates, outputs, network, interactiveSession)\n\ndef main():\n PlayGame()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"DeepQ_Network.py","file_name":"DeepQ_Network.py","file_ext":"py","file_size_in_byte":8072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"343247518","text":"import pygame\nfrom debugmodule import * #debugging asjad\n\ndb(\"CLASS: Loading AICar\")\n\nclass AICar(pygame.sprite.Sprite): #LOOK COIN\n\tdef __init__(self, img, group, speed, pos): \n\t\tself.image = pygame.image.load(img).convert_alpha()\n\t\tself.rect = self.image.get_rect()\n \n\t\tself.x = pos[0] + pos[2] #correction thingi\n\t\tself.y = pos[1]\n\t\tself.rect.x = self.x\n\t\tself.rect.y = self.y\n\t\tself.spd = speed #speed given to AI\n\t\t\n\t\tpygame.sprite.Sprite.__init__(self, group)\n \n\tdef Think(self, surf, obj, group): #screen, object, group\n\t\tself.drawObj(surf) #screen\n\t\tself.move()\n\t\tself.checkPos(obj, group) #class, group\n\t\t\n\tdef drawObj(self, area):\n\t\tarea.blit(self.image, (self.x, self.y))\n\n\tdef move(self):\n\t\tself.y = self.y + self.spd\n\t\tself.rect.y = self.y\n\t\n\tdef checkPos(self, obj, group):\n\t\tif self.rect.y > 590:\n\t\t\tself.kill()","sub_path":"src/class_ai.py","file_name":"class_ai.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"375459366","text":"from django.db import models\n\n# Create your models here.\nclass Doctor(models.Model):\n nombre = models.CharField(max_length=100, null=False, blank=False, verbose_name='Nombre')\n rut = models.CharField(max_length=10, unique=True, verbose_name='RUT')\n direccion = models.CharField(max_length=100)\n fecha_nacimiento = models.DateField(auto_now_add=False, auto_now=False, verbose_name='Fecha de Nacimiento')\n fecha_ingreso_clinica = models.DateField(auto_now_add=True, verbose_name='Fecha de ingreso a la clínica')\n edad = models.PositiveSmallIntegerField(verbose_name='Edad del doctor')\n\n objects = models.Manager\n\n def __str__(self):\n return self.nombre\n\n","sub_path":"src/doctor/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"556752419","text":"# -*- coding: utf-8 -*-\nimport utils, os, pyprind, pandas, numpy, matrix_builder\nfrom scipy.sparse import find\nimport ILCD_reader as ILCD\nfrom copy import copy\n\nversion = 'chemicals_corrected'\nsystem_model = 'Allocation, cut-off'\nfolder = utils.version_system_model_path(version, system_model)\nA, B, C, indexes, Z = utils.load_matrices(folder)\nA_old, B_old, C, indexes_old, Z_old = utils.load_matrices(folder)\n#add ID irrigation in indexes\nie = ('irrigation', 'ID', 'irrigation')\nindexes.add_index('ie', ie, 'm3')\n\n#make the A matrix larger\nrows, columns, coefficients = find(A)\nrows = rows.tolist()\ncolumns = columns.tolist()\ncoefficients = coefficients.tolist()\nA = matrix_builder.matrix_from_list(rows, columns, coefficients, len(indexes.ie), len(indexes.ie))\n\n#copy PH irrigation in ID irrigation in A\ncol = indexes.toggle['ie'][ie]\nie = ('irrigation', 'PH', 'irrigation')\ncol_ = indexes.toggle['ie'][ie]\nrows, columns, coefficients = find(A.getcol(col_))\nfor r, c in zip(rows, coefficients):\n if r != col_:\n A[r, col] = c\n#set diagonal to 1\nA[col, col] = 1.\n\n#link ID activities to ID irrigation\nRoW_irrigation_index = indexes.toggle['ie'][('market for irrigation', 'RoW', 'irrigation')]\nID_irrigation_index = indexes.toggle['ie'][('irrigation', 'ID', 'irrigation')]\nfor ie in indexes.ie:\n if ie[1] == 'ID':\n col = indexes.toggle['ie'][ie]\n if A[RoW_irrigation_index, col] and RoW_irrigation_index != col:\n A[ID_irrigation_index, col] = copy(A[RoW_irrigation_index, col])\n A[RoW_irrigation_index, col] = 0.\n\n#all electricity comes from RAS w/o CN\nie = ('Electricity grid mix 1kV-60kV', 'CN', 'Electricity')\nie_ = ('Electricity grid mix 1kV-60kV', 'RAS w/o CN', 'Electricity')\nA[indexes.toggle['ie'][ie_], ID_irrigation_index] += A[indexes.toggle['ie'][ie], ID_irrigation_index]\nA[indexes.toggle['ie'][ie], ID_irrigation_index] = 0.\n\n#make B larger\nrows, columns, coefficients = find(B)\nrows = rows.tolist()\ncolumns = columns.tolist()\ncoefficients = coefficients.tolist()\nB = matrix_builder.matrix_from_list(rows, columns, coefficients, \n len(indexes.ee), len(indexes.ie))\n#copy the emissions of PH irrigation, but change the country specific ones for ID\nrows, columns, coefficients = find(B.getcol(col_))\nfor r, c in zip(rows, coefficients):\n ee = indexes.ee[r]\n if 'PH' in ee[0]:\n ee = (ee[0].replace('PH', 'ID'), ee[1], ee[2])\n r = indexes.toggle['ee'][ee]\n B[r, col] = c\n\n#remove water emissions in RoW irrigation in each country that already has irrigation\n#and scale the water up for the other countries\nnot_in_RoW = set()\nfor ie in indexes.ie:\n if ie[0] == 'irrigation':\n not_in_RoW.add(ie[1])\nscaling = {}\nie = ('irrigation', 'RoW', 'irrigation')\ncol = indexes.toggle['ie'][ie]\nrows, columns, coefficients = find(B.getcol(col))\nfor r, c in zip(rows, coefficients):\n ee = indexes.ee[r]\n if 'regionalized' in ee[0]:\n geo = ee[0].split(', ')[-1]\n if geo in not_in_RoW:\n ee_ = (ee[0].split(', regionalized')[0], ee[1], ee[2])\n B[indexes.toggle['ee'][ee_], col] += B[r, col]\n B[r, col] = 0.\n\nZ = matrix_builder.Z_from_A(A)\ndelta = A[:len(indexes_old.ie), :len(indexes_old.ie)] - A_old\nrows, columns, coefficients = find(delta)\ndf = []\nfor r, c in zip(rows, columns):\n to_add = dict(zip(['demanding activityName', 'demanding geography', 'demanding product'], indexes.ie[c]))\n to_add.update(dict(zip(['supplying activityName', 'supplying geography', 'supplying product'], indexes.ie[r])))\n to_add['before'] = A_old[r, c]\n to_add['after'] = A[r, c]\n to_add['matrix'] = 'A'\n df.append(to_add)\nrows, columns, coefficients = find(A.getcol(ID_irrigation_index))\nfor r in rows:\n if r != ID_irrigation_index:\n to_add = dict(zip(['demanding activityName', 'demanding geography', 'demanding product'], indexes.ie[ID_irrigation_index]))\n to_add.update(dict(zip(['supplying activityName', 'supplying geography', 'supplying product'], indexes.ie[r])))\n to_add['before'] = 0.\n to_add['after'] = A[r, ID_irrigation_index]\n to_add['matrix'] = 'A'\n df.append(to_add)\nrows, columns, coefficients = find(A.getrow(ID_irrigation_index))\nfor c in columns:\n if c != ID_irrigation_index:\n to_add = dict(zip(['demanding activityName', 'demanding geography', 'demanding product'], indexes.ie[c]))\n to_add.update(dict(zip(['supplying activityName', 'supplying geography', 'supplying product'], indexes.ie[ID_irrigation_index])))\n to_add['before'] = 0.\n to_add['after'] = A[ID_irrigation_index, c]\n to_add['matrix'] = 'A'\n df.append(to_add)\n\nfolder = r'C:\\Dropbox (ecoinvent)\\ei-int\\technical\\external\\PEF\\PEF_chemicals\\technical\\input'\nfilename = 'water_correction_20171220.xlsx'\ncorrections = utils.read_excel(folder, filename, 'Sheet1')\nfor i, sel in corrections.iterrows():\n ie = tuple(sel[['dataset activityName', 'dataset geography', 'dataset reference product']])\n col = indexes.toggle['ie'][ie]\n ee = tuple(sel[['name', 'compartment', 'subcompartment']])\n row = indexes.toggle['ee'][ee]\n B[row, col] = sel['new amount']\n\nies = [ie for ie in indexes.ie if ie[0] == 'irrigation']\nfor ie in pyprind.prog_bar(ies):\n col = indexes.toggle['ie'][ie]\n rows, columns, coefficients = find(B.getcol(col))\n for r in rows:\n ee = indexes.ee[r]\n if 'water' in ee[0] and 'water' in ee[2]:\n B[r, col] = B[r, col]*1000.\n\ndelta = B[:, :len(indexes_old.ie)] - B_old\nrows, columns, coefficients = find(delta)\nfor r, c in zip(rows, columns):\n to_add = dict(zip(['demanding activityName', 'demanding geography', 'demanding product'], indexes.ie[c]))\n to_add.update(dict(zip(['supplying activityName', 'supplying geography', 'supplying product'], indexes.ee[r])))\n to_add['before'] = B_old[r, c]\n to_add['after'] = B[r, c]\n to_add['matrix'] = 'B'\n df.append(to_add)\nrows, columns, coefficients = find(B.getcol(ID_irrigation_index))\nfor r in rows:\n if r != ID_irrigation_index:\n to_add = dict(zip(['demanding activityName', 'demanding geography', 'demanding product'], indexes.ie[ID_irrigation_index]))\n to_add.update(dict(zip(['supplying activityName', 'supplying geography', 'supplying product'], indexes.ee[r])))\n to_add['before'] = 0.\n to_add['after'] = B[r, ID_irrigation_index]\n to_add['matrix'] = 'B'\n df.append(to_add)\n\ndf = utils.list_to_df(df)\ncolumns = ['matrix', 'demanding activityName', 'demanding geography', 'demanding product', \n 'supplying activityName', 'supplying geography', 'supplying product', \n 'before', 'after']\ndfs = [(df, 'Sheet1', columns)]\nfolder = r'C:\\Dropbox (ecoinvent)\\ei-int\\technical\\external\\PEF\\PEF_chemicals\\technical\\output'\nfilename = 'new_matrix change.xlsx'\nutils.dataframe_to_excel(folder, filename, dfs, feedback = True)\nversion = 'chemicals_corrected - 20171227'\nsystem_model = 'Allocation, cut-off'\nfolder = utils.version_system_model_path(version, system_model)\nZ = matrix_builder.Z_from_A(A)\nfor m, n in [(A, 'A'), (B, 'B'), (C, 'C'), (indexes, 'indexes'), (Z, 'Z')]:\n utils.pkl_dump(os.path.join(folder, 'pkl'), n, m)\nmatrix_builder.calculate_scalings(indexes, A, Z, folder)\nmatrix_builder.calculate_g(folder, indexes, B)\nmatrix_builder.calculate_h(folder, indexes, C)","sub_path":"projects/PEF/new_matrices_20121222.py","file_name":"new_matrices_20121222.py","file_ext":"py","file_size_in_byte":7366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"531643577","text":"\"\"\"Place to eat http handler \"\"\"\nfrom tornado.web import RequestHandler\nfrom tornado.gen import coroutine\nfrom tornado.gen import Task\nfrom tornado_test_django import settings\nimport AsyncDjango\n\n\nclass SuggestedDateHandler(RequestHandler):\n \"\"\" Handler Class \"\"\"\n\n @coroutine\n def get(self, id):\n a = AsyncDjango()\n sg = yield Task(a.get_suggested_date, id)\n self.write(sg)\n\n @coroutine\n def put(self, dt, user_id, place_id):\n a = AsyncDjango()\n sg = yield Task(a.insert_suggested_date, dt, user_id, place_id)\n self.write(sg)\n\n @coroutine\n def post(self, dt, user_id, place_id, id):\n a = AsyncDjango()\n sg = yield Task(a.update_suggested_date, dt, user_id, place_id, id)\n self.write(sg)\n\n @coroutine\n def delete(self, id):\n a = AsyncDjango()\n sg = yield Task(a.delete_suggested_date, id)\n self.write(sg)","sub_path":"tornado_test_django/SuggestedDateHandler.py","file_name":"SuggestedDateHandler.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"601150060","text":"# -*- coding: utf-8 -*-\n\n'''\nCopyright (c) 2013 Colin Curtain\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\nAuthor: Colin Curtain (ccbogel)\nhttps://github.com/ccbogel/PyQDA\n'''\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n#ADDIN\nimport datetime\nfrom .CodeColors import CodeColors\nfrom .ColorSelector import Ui_Dialog_colorselect\nfrom .Memo import Ui_Dialog_memo\nfrom .AddItem import Ui_Dialog_addItem\nfrom .ConfirmDelete import Ui_Dialog_confirmDelete\nfrom .SelectFile import Ui_Dialog_selectfile\nfrom .ViewCodeFrequencies import Ui_Dialog_vcf\n\n# requires python-igraph (0.6.5)\ntry:\n import igraph # use this module only if it is installed\nexcept:\n pass\n#END ADDIN\n\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtWidgets.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtWidgets.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtWidgets.QApplication.translate(context, text, disambig)\n\nclass Ui_Dialog_cats(object):\n \"\"\"\n Code Category management.\n Shows a list of code categories which can be added to or deleted from.\n Show a list of codes which can be dragged into code categories\n Clicking on a category shows the linked codes.\n Several displays of codes and categories are available: network graphs and code frequencies\n \"\"\"\n\n #ADDIN\n CODE_NAME_COLUMN = 0\n CODE_COLOR_COLUMN = 1\n CODE_MEMO_COLUMN = 2\n CODE_ID_COLUMN = 3\n CAT_NAME_COLUMN = 0\n CAT_MEMO_COLUMN = 1\n CAT_VIEW_COLUMN = 2\n CAT_ID_COLUMN = 3\n\n settings = None\n freecode = [] # the codes\n codeColors = CodeColors()\n cats = [] # codecategories\n treecode = [] # links codes to categories\n selectedCategoryId = -1 # if -1 all categories and codes are shown, if a category id then only that category and its codes are shown\n\n def __init__(self, settings):\n self.freecode = []\n self.cats = []\n self.treecode = []\n self.settings = settings\n\n cur = self.settings['conn'].cursor()\n cur.execute(\"select name, memo, owner, date, dateM, id, status, color from freecode\")\n result = cur.fetchall()\n for row in result:\n self.freecode.append({'name':row[0], 'memo':row[1], 'owner':row[2], 'date':row[3], 'dateM':row[4], 'id':row[5], 'status':row[6], 'color':row[7]})\n\n cur.execute(\"select name, cid, catid, owner, date, dateM, memo, status from codecat\")\n result = cur.fetchall()\n for row in result:\n self.cats.append({'name':row[0],'cid':row[1], 'catid':row[2], 'owner':row[3], 'date':row[4], 'dateM':row[5], 'memo':row[6], 'status':row[7]})\n\n cur.execute(\"select cid, catid, date, dateM, memo, status, owner from treecode\")\n result = cur.fetchall()\n for row in result:\n self.treecode.append({'cid':row[0], 'catid':row[1], 'date':row[2], 'dateM':row[3], 'memo':row[4], 'status':row[5], 'owner':row[6]})\n\n def comboView(self):\n \"\"\" Select code and category view options \"\"\"\n\n if len(self.tableWidget_cats.selectedItems()) == 0:\n QtWidgets.QMessageBox.warning(None, \"No Categories\",\"No categories selected.\")\n return\n selection = str(self.comboBox.currentText())\n if selection[0:12] == \"View graph: \":\n self.viewGraph(selection[12:])\n if selection == \"View Code Frequency Table\":\n self.viewFrequencyTable()\n\n def viewFrequencyTable(self):\n \"\"\" Create a table headed by selected categories, codes for each category are listed from most frequent to least \"\"\"\n\n selectedCats = \"\"\n headers = []\n for itemWidget in self.tableWidget_cats.selectedItems():\n catid = str(self.tableWidget_cats.item(itemWidget.row(), self.CAT_ID_COLUMN).text())\n headers.append(str(self.tableWidget_cats.item(itemWidget.row(), self.CAT_NAME_COLUMN).text()))\n selectedCats += \",\" + catid\n selectedCats = selectedCats[1:]\n\n cur = self.settings['conn'].cursor()\n #sql = \"select count(treecode.cid) as count, treecode.cid, freecode.name, treecode.catid, codecat.name from treecode \"\\\n sql = \"select count(treecode.cid) as count, freecode.name, codecat.name from treecode \"\\\n \"join codecat on treecode.catid=codecat.catid join freecode on freecode.id=treecode.cid \"\\\n \" join \"+ self.settings['codertable'] + \" on \" + self.settings['codertable'] + \".cid = treecode.cid \"\\\n \" where treecode.catid in (\"+ selectedCats +\") \"\\\n \" group by freecode.name, treecode.cid \"\\\n \" order by codecat.name asc, count desc\"\n\n cur.execute(sql)\n result = cur.fetchall()\n results = []\n for row in result:\n results.append(row)\n #print results\n\n listDictionaryResults = {}\n for heading in headers:\n listDictionaryResults[heading] = []\n for row in results:\n if heading == row[2]:\n listDictionaryResults[heading].append(row[1] + \" (\" + str(row[0]) + \")\")\n\n Dialog_vcf = QtWidgets.QDialog()\n ui = Ui_Dialog_vcf(listDictionaryResults)\n ui.setupUi(Dialog_vcf)\n Dialog_vcf.exec_()\n\n def viewGraph(self, layout):\n \"\"\" View node graph of selected codes and categories \"\"\"\n\n try:\n tmp = igraph.Graph(0)\n except:\n QtWidgets.QMessageBox.warning(None, \"igraph\",\"igraph not installed.\\nCannot create network graphs.\")\n return\n\n selectedCats = \"\"\n vertices = []\n maxCatNum = 0\n for vnum, itemWidget in enumerate(self.tableWidget_cats.selectedItems()):\n catid = str(self.tableWidget_cats.item(itemWidget.row(), self.CAT_ID_COLUMN).text())\n name = str(self.tableWidget_cats.item(itemWidget.row(), self.CAT_NAME_COLUMN).text())\n selectedCats += \",\" + catid\n vertices.append({'vnum':vnum,'catid': int(catid), 'cid':-1, 'catname':name, 'codename':\"\", 'name':name.upper()})\n maxCatNum = vnum\n selectedCats = selectedCats[1:]\n maxCatNum += 1\n\n # get treecode with code and category names\n cur = self.settings['conn'].cursor()\n cur.execute(\"select treecode.cid, freecode.name, treecode.catid, codecat.name from treecode \"\\\n \"join codecat on treecode.catid=codecat.catid join freecode on freecode.id=treecode.cid \"\\\n \"where treecode.catid in (\"+ selectedCats +\")\")\n result = cur.fetchall()\n edges = []\n e1NumAdjuster = 0 # decrease the vum is the same code appears more than once\n for vnum, row in enumerate(result):\n duplicateCode = False\n for code in vertices:\n if row[0] == code['cid']:\n #print(\"have a duplicate: \" + row[1])\n e1NumAdjuster -= 1\n duplicateCode = True\n tmpEdge = {'e1':code['vnum'], 'e2': 0, 'cid':row[0], 'codename':row[1], 'catid':row[2], 'catname':row[3]}\n # look at ONLY the category vertices\n for catVertex in range(0, maxCatNum):\n if vertices[catVertex]['catid'] == tmpEdge['catid']:\n tmpEdge['e2'] = catVertex\n edges.append(tmpEdge)\n\n if duplicateCode == False:\n #remove catname and code name from below and just keep name\n vertices.append({'vnum':vnum + maxCatNum + e1NumAdjuster ,'catid': int(row[2]), 'cid': int(row[0]), 'catname':\"\", 'codename':row[1], 'name':row[1]})\n tmpEdge = {'e1':vnum + maxCatNum + e1NumAdjuster, 'e2': 0, 'cid':row[0], 'codename':row[1], 'catid':row[2], 'catname':row[3]}\n # look at ONLY the category vertices\n for catVertex in range(0, maxCatNum):\n if vertices[catVertex]['catid'] == tmpEdge['catid']:\n tmpEdge['e2'] = catVertex\n edges.append(tmpEdge)\n\n vnames = []\n for item in vertices:\n vnames.append(item['name'])\n finalEdges = []\n for edge in edges:\n finalEdges.append((edge['e1'], edge['e2']))\n g = igraph.Graph(0)\n g.add_vertices(len(vertices))\n g.vs[\"name\"] = vnames\n g.add_edges(finalEdges)\n #g.vs[\"label\"] = g.vs[\"name\"]\n visual_style = {}\n visual_style[\"vertex_label\"] = g.vs[\"name\"]\n visual_style[\"layout\"] = g.layout(layout)\n visual_style[\"vertex_size\"] = 20\n visual_style[\"vertex_label_size\"] = 12\n visual_style[\"vertex_color\"] = \"yellow\"\n visual_style[\"margin\"] = [100,20,100,20] # t r b l\n visual_style[\"edge_color\"] = \"gray\"\n visual_style[\"bbox\"] = (900, 650)\n igraph.plot(g, **visual_style)\n\n def codesCellSelected(self):\n \"\"\" When colour or memo cells are selected in the table widget,\n open a memo dialog or colour selector dialog \"\"\"\n\n x = self.tableWidget_codes.currentRow()\n y = self.tableWidget_codes.currentColumn()\n\n if y == self.CODE_COLOR_COLUMN:\n Dialog_colorselect = QtWidgets.QDialog()\n ui = Ui_Dialog_colorselect(self.freecode[x]['color'])\n ui.setupUi(Dialog_colorselect)\n ok = Dialog_colorselect.exec_()\n if ok:\n selectedColor = ui.getColor()\n if selectedColor!=None:\n item = QtWidgets.QTableWidgetItem() # an empty item, used to have color name\n item.setBackground(QtGui.QBrush(QtGui.QColor(selectedColor['hex'])))\n self.tableWidget_codes.setItem(x, self.CODE_COLOR_COLUMN, item)\n self.tableWidget_codes.clearSelection()\n\n #update freecode list and database\n self.freecode[x]['color'] = selectedColor['colname']\n cur = self.settings['conn'].cursor()\n cur.execute(\"update freecode set color=? where id=?\", (self.freecode[x]['color'], self.freecode[x]['id']))\n self.settings['conn'].commit()\n\n if y == self.CODE_MEMO_COLUMN:\n Dialog_memo = QtWidgets.QDialog()\n ui = Ui_Dialog_memo(self.freecode[x]['memo'])\n ui.setupUi(Dialog_memo, \"Code memo \" + self.freecode[x]['name'])\n Dialog_memo.exec_()\n memo = ui.getMemo()\n\n if memo == \"\":\n self.tableWidget_codes.setItem(x, self.CODE_MEMO_COLUMN, QtWidgets.QTableWidgetItem())\n else:\n self.tableWidget_codes.setItem(x, self.CODE_MEMO_COLUMN, QtWidgets.QTableWidgetItem(\"Yes\"))\n\n #update freecode list and database\n self.freecode[x]['memo'] = str(memo)\n cur = self.settings['conn'].cursor()\n cur.execute(\"update freecode set memo=? where id=?\", (self.freecode[x]['memo'], self.freecode[x]['id']))\n self.settings['conn'].commit()\n\n def codesCellModified(self):\n \"\"\" When a code name is changed in the table widget update the details in model and database \"\"\"\n\n x = self.tableWidget_codes.currentRow()\n y = self.tableWidget_codes.currentColumn()\n if y == self.CODE_NAME_COLUMN:\n newCodeText = str(self.tableWidget_codes.item(x, y).text())\n # check that no other code has this text and this is is not empty\n update = True\n if newCodeText == \"\":\n update = False\n for c in self.freecode:\n if c['name'] == newCodeText:\n update = False\n if update:\n # update freecode list and database\n cur = self.settings['conn'].cursor()\n cur.execute(\"update freecode set name=? where id=?\", (newCodeText, self.freecode[x]['id']))\n self.settings['conn'].commit()\n self.freecode[x]['name'] = newCodeText\n\n else: # put the original text in the cell\n self.tableWidget_codes.item(x, y).setText(self.freecode[x]['name'])\n\n def catsCellSelected(self):\n \"\"\" Open a memo dialog if a category memo cell is selected \"\"\"\n\n x = self.tableWidget_cats.currentRow()\n y = self.tableWidget_cats.currentColumn()\n\n # category memo column\n if y == self.CAT_MEMO_COLUMN:\n Dialog_memo = QtWidgets.QDialog()\n ui = Ui_Dialog_memo(self.cats[x]['memo'])\n ui.setupUi(Dialog_memo, \"Category memo \" + self.cats[x]['name'])\n Dialog_memo.exec_()\n memo = ui.getMemo()\n\n if memo == \"\":\n self.tableWidget_cats.setItem(x, self.CAT_MEMO_COLUMN, QtWidgets.QTableWidgetItem())\n else:\n self.tableWidget_cats.setItem(x, self.CAT_MEMO_COLUMN, QtWidgets.QTableWidgetItem(\"Yes\"))\n\n #update cats list and database\n self.cats[x]['memo'] = str(memo)\n cur = self.settings['conn'].cursor()\n cur.execute(\"update codecat set memo=? where catid=?\", (self.cats[x]['memo'], self.cats[x]['catid']))\n self.settings['conn'].commit()\n\n # view codes for this category\n if y == self.CAT_VIEW_COLUMN:\n # important need to unselect all codes in tableWidget\n\n if self.selectedCategoryId == -1: # all categories currently displayed, so change this to selected category\n self.pushButton_link.setEnabled(False)\n self.pushButton_unlink.setEnabled(True)\n self.selectedCategoryId = int(self.tableWidget_cats.item(x, self.CAT_ID_COLUMN).text())\n for (row, item) in enumerate(self.cats):\n if self.selectedCategoryId != int(self.tableWidget_cats.item(row, self.CAT_ID_COLUMN).text()):\n self.tableWidget_cats.hideRow(row) # hide other categories\n\n # now show codes associated with this category\n for(row, item) in enumerate(self.freecode):\n hide = True\n for treeCodeItem in self.treecode:\n #print(str(treeCodeItem['catid'])+\" \"+str(self.selectedCategoryId)+\" co:\"+str(treeCodeItem['cid'])+\" \"+str(item['id']))\n if int(treeCodeItem['catid']) == self.selectedCategoryId and treeCodeItem['cid'] == item['id']:\n hide = False\n if hide:\n self.tableWidget_codes.hideRow(row)\n else:\n self.selectedCategoryId = -1\n self.pushButton_link.setEnabled(True)\n self.pushButton_unlink.setEnabled(False)\n for (row, item) in enumerate(self.cats):\n self.tableWidget_cats.showRow(row)\n for(row, item) in enumerate(self.freecode):\n self.tableWidget_codes.showRow(row)\n\n # need to clear selection in category table when showing all rows\n # as there are no selected items but the previous view cell appears selected\n self.tableWidget_cats.clearSelection()\n\n def catsCellModified(self):\n \"\"\" When a category name is modified, update the model and database \"\"\"\n\n x = self.tableWidget_cats.currentRow()\n y = self.tableWidget_cats.currentColumn()\n if y == self.CAT_NAME_COLUMN:\n newCatText = str(self.tableWidget_cats.item(x, y).text())\n # check that no other category has this text and this is is not empty\n update = True\n if newCatText == \"\":\n update = False\n for c in self.cats:\n if c['name'] == newCatText:\n update = False\n if update:\n #update category list and database\n cur = self.settings['conn'].cursor()\n cur.execute(\"update codecat set name=? where catid=?\", (newCatText, self.cats[x]['catid']))\n self.settings['conn'].commit()\n self.cats[x]['name'] = newCatText\n else: #put the original text in the cell\n self.tableWidget_cats.item(x, y).setText(self.cats[x]['name'])\n\n def addCat(self):\n \"\"\" When button pressed, add a new category.\n Note: the addItem dialog does the checking for duplicate category names \"\"\"\n\n Dialog_addCat = QtWidgets.QDialog()\n ui = Ui_Dialog_addItem(self.cats)\n ui.setupUi(Dialog_addCat, \"Category\")\n Dialog_addCat.exec_()\n newCatText = ui.getNewItem()\n if newCatText is not None:\n #add to database\n # need to generate a new id as the RQDA database does not have an autoincrement id field\n newid = 1\n for cat in self.cats:\n if cat['catid'] >= newid:\n newid = cat['catid']+1\n item = {'name':newCatText,'cid':None, 'catid':newid, 'memo':\"\", 'owner':self.settings['codername'], 'date':datetime.datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\"), 'dateM':\"\", 'status':1}\n self.cats.append(item)\n cur = self.settings['conn'].cursor()\n cur.execute(\"insert into codecat (name, cid, catid, memo, owner, date, dateM, status) values(?,?,?,?,?,?,?,?)\"\n ,(item['name'], item['cid'], item['catid'],item['memo'],item['owner'],item['date'],item['dateM'],item['status']))\n self.settings['conn'].commit()\n\n #update widget\n self.tableWidget_cats.insertRow(0)\n newItem = QtWidgets.QTableWidgetItem(item['name'])\n self.tableWidget_cats.setItem(0, self.CAT_NAME_COLUMN, newItem)\n newItem = QtWidgets.QTableWidgetItem(item['memo'])\n self.tableWidget_cats.setItem(0, self.CAT_MEMO_COLUMN, newItem)\n newItem = QtWidgets.QTableWidgetItem(str(item['catid']))\n self.tableWidget_cats.setItem(0, self.CAT_ID_COLUMN, newItem)\n self.tableWidget_cats.resizeColumnsToContents()\n self.tableWidget_cats.resizeRowsToContents()\n\n def deleteCat(self):\n \"\"\" When category highlighted and Delete button pressed. Delete category from model and database \"\"\"\n\n tableRowsToDelete = [] # for table widget ids\n idsToDelete = [] # for ids for cats and db\n catNamesToDelete = \"\" # for confirmDelete Dialog\n\n for itemWidget in self.tableWidget_cats.selectedItems():\n tableRowsToDelete.append(int(itemWidget.row()))\n idsToDelete.append(int(self.tableWidget_cats.item(itemWidget.row(), self.CAT_ID_COLUMN).text()))\n catNamesToDelete = catNamesToDelete+\"\\n\" + str(self.tableWidget_cats.item(itemWidget.row(), self.CAT_NAME_COLUMN).text())\n #print(\"X:\"+ str(itemWidget.row()) + \" y:\"+str(itemWidget.column()) +\" \"+itemWidget.text() +\" id:\"+str(self.tableWidget_codes.item(itemWidget.row(),3).text()))\n if catNamesToDelete == \"\":\n return\n tableRowsToDelete.sort(reverse=True)\n\n Dialog_confirmDelete = QtWidgets.QDialog()\n ui = Ui_Dialog_confirmDelete(catNamesToDelete)\n ui.setupUi(Dialog_confirmDelete)\n ok = Dialog_confirmDelete.exec_()\n if ok:\n for r in tableRowsToDelete:\n self.tableWidget_cats.removeRow(r)\n\n if self.selectedCategoryId != -1: # show all other categories and codes again\n self.selectedCategoryId = -1\n for (row, item) in enumerate(self.cats):\n self.tableWidget_cats.showRow(row)\n for(row, item) in enumerate(self.freecode):\n self.tableWidget_codes.showRow(row)\n\n for catid in idsToDelete:\n for item in self.cats:\n if item['catid'] == catid:\n self.cats.remove(item)\n cur = self.settings['conn'].cursor()\n #print(str(id) + \" \"+ str(type(id)))\n cur.execute(\"delete from treecode where catid = ?\", [catid])\n cur.execute(\"delete from codecat where catid = ?\", [catid])\n self.settings['conn'].commit()\n\n def link(self):\n \"\"\" Link one or more selected codes to one selected category when link button pressed\"\"\"\n\n if self.selectedCategoryId != -1:\n return\n catId = None\n codeIds = []\n\n # get the last (only) selected cat item\n for itemWidget in self.tableWidget_cats.selectedItems():\n catId = int(self.tableWidget_cats.item(itemWidget.row(), self.CAT_ID_COLUMN).text())\n if catId == None: return\n\n for itemWidget in self.tableWidget_codes.selectedItems():\n codeIds.append(int(self.tableWidget_codes.item(itemWidget.row(), self.CODE_ID_COLUMN).text()))\n if len(codeIds) == 0: return\n\n # update Db and treecode variable\n cur = self.settings['conn'].cursor()\n theDate = datetime.datetime.now().strftime(\"%a %b %d %H:%M:%S %Y\")\n for cid in codeIds:\n #check the link is not already in the Db\n cur.execute(\"select count(*) from treecode where cid=? and catid=?\",(cid, catId))\n result = cur.fetchone()[0]\n self.settings['conn'].commit()\n if result == 0:\n cur.execute(\"insert into treecode (cid, catid, date, dateM, memo, status, owner) values(?,?,?,?,?,?,?)\",\n (cid, catId, theDate, theDate, \"\", 1, self.settings['codername']))\n else:\n return\n\n # update treecode list\n self.treecode = []\n cur.execute(\"select cid, catid, date, dateM, memo, status, owner from treecode\")\n result = cur.fetchall()\n for row in result:\n self.treecode.append({'cid':row[0], 'catid':row[1], 'date':row[2], 'dateM':row[3], 'memo':row[4], 'status':row[5], 'owner':row[6]})\n self.settings['conn'].commit()\n\n def unlink(self):\n \"\"\" When button pressed, all selected codes are unlinked from the selected category \"\"\"\n\n codeIds = []\n if self.selectedCategoryId == -1:\n return\n for itemWidget in self.tableWidget_codes.selectedItems():\n codeIds.append(int(self.tableWidget_codes.item(itemWidget.row(), self.CODE_ID_COLUMN).text()))\n if len(codeIds) == 0:\n return\n #print(\"Unlink: selCatView:\"+str(self.selectedCategoryId)+\" codes:\"+str(codeIds)) #temp\n # update Db and treecode variable\n cur = self.settings['conn'].cursor()\n for cid in codeIds:\n cur.execute(\"delete from treecode where cid=? and catid=?\",(cid, self.selectedCategoryId))\n\n self.treecode = []\n cur.execute(\"select cid, catid, date, dateM, memo, status, owner from treecode\")\n result = cur.fetchall()\n for row in result:\n self.treecode.append({'cid':row[0], 'catid':row[1], 'date':row[2], 'dateM':row[3], 'memo':row[4], 'status':row[5], 'owner':row[6]})\n self.settings['conn'].commit()\n\n def mergeCodes(self):\n \"\"\"When merge codes button is pressed, merge two or more codes into one code.\n Note: there is no undo for this \"\"\"\n\n removeCodes = []\n for itemWidget in self.tableWidget_codes.selectedItems():\n removeTemp = {'name':self.tableWidget_codes.item(itemWidget.row(), self.CODE_NAME_COLUMN).text(),'cid':int(self.tableWidget_codes.item(itemWidget.row(), self.CODE_ID_COLUMN).text())}\n # remove duplicate selections, have duplicates because tableWidget_codes is not row selection only\n addCode = True\n for remCode in removeCodes:\n if removeTemp == remCode:\n addCode = False\n if addCode:\n removeCodes.append(removeTemp)\n if len(removeCodes) < 2:\n return\n\n Dialog_selectcode = QtWidgets.QDialog()\n ui = Ui_Dialog_selectfile(removeCodes)\n ui.setupUi(Dialog_selectcode, \"Merging, Select code to keep\", \"single\")\n ok = Dialog_selectcode.exec_()\n if not(ok):\n return\n keepCode = ui.getSelected()\n #print(keepCode)\n #print(str(removeCodes))\n for code in removeCodes:\n if code['cid'] == keepCode['cid']:\n removeCodes.remove(code) # exclude the kept code from the remove list\n #print(str(removeCodes))\n cur = self.settings['conn'].cursor()\n for code in removeCodes:\n cur.execute(\"update treecode set cid=? where cid=?\", (keepCode['cid'] ,code['cid']))\n cur.execute(\"update coding set cid=? where cid=?\", (keepCode['cid'] ,code['cid']))\n cur.execute(\"update coding2 set cid=? where cid=?\", (keepCode['cid'] ,code['cid']))\n cur.execute(\"delete from freecode where id=?\", (code['cid'],))\n\n #have to refresh self.tableWidget_codes and freecode list\n for row in self.freecode:\n self.tableWidget_codes.removeRow(0)\n\n cur.execute(\"select name, memo, owner, date, dateM, id, status, color from freecode\")\n result = cur.fetchall()\n self.freecode = []\n for row in result:\n self.freecode.append({'name':row[0], 'memo':row[1], 'owner':row[2], 'date':row[3], 'dateM':row[4], 'id':row[5], 'status':row[6], 'color':row[7]})\n self.settings['conn'].commit()\n self.fillCodesTable()\n\n def mergeCats(self):\n \"\"\"When merge categories button is pressed, merge two or more categories into one category.\n Note: there is no undo for this \"\"\"\n\n removeCats = []\n for itemWidget in self.tableWidget_cats.selectedItems():\n removeTemp = {'name':self.tableWidget_cats.item(itemWidget.row(), self.CAT_NAME_COLUMN).text(),'catid':int(self.tableWidget_cats.item(itemWidget.row(), self.CAT_ID_COLUMN).text())}\n # remove duplicate selections, have duplicates because tableWidget_cats is not row selection only\n addCat = True\n for remCat in removeCats:\n if removeTemp == remCat:\n addCat = False\n if addCat: removeCats.append(removeTemp)\n\n if len(removeCats) < 2:\n return\n\n Dialog_selectcat = QtWidgets.QDialog()\n ui = Ui_Dialog_selectfile(removeCats)\n ui.setupUi(Dialog_selectcat, \"Merging, Select category to keep\", \"single\")\n ok = Dialog_selectcat.exec_()\n if not(ok):\n return\n keepCat = ui.getSelected()\n print(\"Keeping category: \" + str(keepCat))\n for cat in removeCats:\n if cat['catid'] == keepCat['catid']:\n removeCats.remove(cat) # exclude the kept category from the remove list\n print(\"Removing categories: \" + str(removeCats))\n\n cur = self.settings['conn'].cursor()\n for cat in removeCats:\n cur.execute(\"update treecode set catid=? where catid=?\", (keepCat['catid'] ,cat['catid']))\n cur.execute(\"delete from codecat where catid=?\", (cat['catid'],))\n\n # Refresh categories, treecat and self.tableWidget_cats\n for row in self.cats:\n self.tableWidget_cats.removeRow(0)\n\n self.cats = []\n cur.execute(\"select name, cid, catid, owner, date, dateM, memo, status from codecat\")\n result = cur.fetchall()\n for row in result:\n self.cats.append({'name':row[0],'cid':row[1], 'catid':row[2], 'owner':row[3], 'date':row[4], 'dateM':row[5], 'memo':row[6], 'status':row[7]})\n\n self.treecode = []\n cur.execute(\"select cid, catid, date, dateM, memo, status, owner from treecode\")\n result = cur.fetchall()\n for row in result:\n self.treecode.append({'cid':row[0], 'catid':row[1], 'date':row[2], 'dateM':row[3], 'memo':row[4], 'status':row[5], 'owner':row[6]})\n self.settings['conn'].commit()\n self.fillCatsTable()\n\n def fillCodesTable(self):\n \"\"\" Fill the codes table \"\"\"\n\n self.tableWidget_codes.setColumnCount(4)\n self.tableWidget_codes.setHorizontalHeaderLabels([\"Code\",\"Color\",\"Memo\",\"Id\"])\n for row, code in enumerate(self.freecode):\n self.tableWidget_codes.insertRow(row)\n self.tableWidget_codes.setItem(row, self.CODE_NAME_COLUMN, QtWidgets.QTableWidgetItem(code['name']))\n colnametmp = code['color']\n if colnametmp is None:\n colnametmp = \"\"\n item = QtWidgets.QTableWidgetItem()\n colorHex = self.codeColors.getHexFromName(colnametmp)\n if colorHex != \"\":\n item.setBackground(QtGui.QBrush(QtGui.QColor(colorHex)))\n self.tableWidget_codes.setItem(row, self.CODE_COLOR_COLUMN, item)\n mtmp = code['memo']\n if mtmp is not None and mtmp != \"\":\n self.tableWidget_codes.setItem(row, self.CODE_MEMO_COLUMN, QtWidgets.QTableWidgetItem(\"Yes\"))\n cid = code['id']\n if cid is None:\n cid = \"\"\n self.tableWidget_codes.setItem(row, self.CODE_ID_COLUMN, QtWidgets.QTableWidgetItem(str(cid)))\n\n self.tableWidget_codes.verticalHeader().setVisible(False)\n self.tableWidget_codes.resizeColumnsToContents()\n self.tableWidget_codes.resizeRowsToContents()\n if not self.settings['showIDs']:\n self.tableWidget_codes.hideColumn(self.CODE_ID_COLUMN) # hide code ids\n\n def fillCatsTable(self):\n \"\"\" Fill categories table \"\"\"\n\n self.tableWidget_cats.setColumnCount(4)\n self.tableWidget_cats.setHorizontalHeaderLabels([\"Category\", \"Memo\", \"View linked\", \"CatID\"])\n for row, code in enumerate(self.cats):\n self.tableWidget_cats.insertRow(row)\n self.tableWidget_cats.setItem(row, self.CAT_NAME_COLUMN, QtWidgets.QTableWidgetItem(code['name']))\n mtmp = code['memo']\n if mtmp is not None and mtmp != \"\":\n self.tableWidget_cats.setItem(row, self.CAT_MEMO_COLUMN, QtWidgets.QTableWidgetItem(\"Yes\"))\n catid = code['catid']\n if catid is None:\n catid = \"\"\n self.tableWidget_cats.setItem(row, self.CAT_ID_COLUMN, QtWidgets.QTableWidgetItem(str(catid)))\n\n self.tableWidget_cats.verticalHeader().setVisible(False)\n self.tableWidget_cats.resizeColumnsToContents()\n self.tableWidget_cats.resizeRowsToContents()\n if not self.settings['showIDs']:\n self.tableWidget_cats.hideColumn(self.CAT_ID_COLUMN) # hide category ids\n\n #END ADDIN\n\n def setupUi(self, Dialog_cats):\n Dialog_cats.setObjectName(_fromUtf8(\"Dialog_cats\"))\n #ADDIN\n sizeObject = QtWidgets.QDesktopWidget().screenGeometry(-1)\n h = sizeObject.height() * 0.8\n w = sizeObject.width() * 0.8\n h = min([h, 1000])\n w = min([w, 2000])\n Dialog_cats.resize(w, h)\n Dialog_cats.move(20, 20)\n #END ADDIN\n self.pushButton_add = QtWidgets.QPushButton(Dialog_cats)\n self.pushButton_add.setGeometry(QtCore.QRect(10, 10, 98, 27))\n self.pushButton_add.setObjectName(_fromUtf8(\"pushButton_add\"))\n self.pushButton_delete = QtWidgets.QPushButton(Dialog_cats)\n self.pushButton_delete.setGeometry(QtCore.QRect(130, 10, 98, 27))\n self.pushButton_delete.setObjectName(_fromUtf8(\"pushButton_delete\"))\n self.pushButton_mergeCodes = QtWidgets.QPushButton(Dialog_cats)\n self.pushButton_mergeCodes.setGeometry(QtCore.QRect(570, 10, 111, 27))\n self.pushButton_mergeCodes.setObjectName(_fromUtf8(\"pushButton_mergeCodes\"))\n self.pushButton_mergeCats = QtWidgets.QPushButton(Dialog_cats)\n self.pushButton_mergeCats.setGeometry(QtCore.QRect(690, 10, 151, 27))\n self.pushButton_mergeCats.setObjectName(_fromUtf8(\"pushButton_mergeCats\"))\n self.pushButton_link = QtWidgets.QPushButton(Dialog_cats)\n self.pushButton_link.setGeometry(QtCore.QRect(10, 50, 98, 27))\n self.pushButton_link.setObjectName(_fromUtf8(\"pushButton_link\"))\n self.pushButton_unlink = QtWidgets.QPushButton(Dialog_cats)\n self.pushButton_unlink.setGeometry(QtCore.QRect(130, 50, 98, 27))\n self.pushButton_unlink.setObjectName(_fromUtf8(\"pushButton_unlink\"))\n self.comboBox = QtWidgets.QComboBox(Dialog_cats)\n self.comboBox.setGeometry(QtCore.QRect(240, 50, 301, 27))\n self.comboBox.setObjectName(_fromUtf8(\"comboBox\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.comboBox.addItem(_fromUtf8(\"\"))\n self.splitter = QtWidgets.QSplitter(Dialog_cats)\n #self.splitter.setGeometry(QtCore.QRect(10, 90, 831, 471))\n self.splitter.setGeometry(QtCore.QRect(10, 90, w - 20, h - 100)) # addin\n self.splitter.setOrientation(QtCore.Qt.Horizontal)\n self.splitter.setObjectName(_fromUtf8(\"splitter\"))\n self.tableWidget_codes = QtWidgets.QTableWidget(self.splitter)\n self.tableWidget_codes.setObjectName(_fromUtf8(\"tableWidget_codes\"))\n self.tableWidget_codes.setColumnCount(0)\n self.tableWidget_codes.setRowCount(0)\n self.tableWidget_cats = QtWidgets.QTableWidget(self.splitter)\n self.tableWidget_cats.setObjectName(_fromUtf8(\"tableWidget_cats\"))\n self.tableWidget_cats.setColumnCount(0)\n self.tableWidget_cats.setRowCount(0)\n self.label = QtWidgets.QLabel(Dialog_cats)\n self.label.setGeometry(QtCore.QRect(260, 20, 261, 17))\n self.label.setObjectName(_fromUtf8(\"label\"))\n\n #ADDIN\n self.fillCodesTable()\n self.fillCatsTable()\n\n self.tableWidget_codes.cellClicked.connect(self.codesCellSelected)\n self.tableWidget_cats.cellClicked.connect(self.catsCellSelected)\n self.tableWidget_cats.itemChanged.connect(self.catsCellModified)\n self.tableWidget_codes.itemChanged.connect(self.codesCellModified)\n self.pushButton_add.clicked.connect(self.addCat)\n self.pushButton_delete.clicked.connect(self.deleteCat)\n self.pushButton_link.clicked.connect(self.link)\n self.pushButton_unlink.clicked.connect(self.unlink)\n self.pushButton_mergeCodes.clicked.connect(self.mergeCodes)\n self.pushButton_mergeCats.clicked.connect(self.mergeCats)\n #self.comboBox.activated[str].connect(self.comboView)\n self.comboBox.activated.connect(self.comboView)\n #END ADDIN\n\n self.retranslateUi(Dialog_cats)\n QtCore.QMetaObject.connectSlotsByName(Dialog_cats)\n\n def retranslateUi(self, Dialog_cats):\n Dialog_cats.setWindowTitle(_translate(\"Dialog_cats\", \"Categories\", None))\n self.pushButton_add.setText(_translate(\"Dialog_cats\", \"Add\", None))\n self.pushButton_delete.setText(_translate(\"Dialog_cats\", \"Delete\", None))\n self.pushButton_mergeCodes.setText(_translate(\"Dialog_cats\", \"Merge Codes\", None))\n self.pushButton_mergeCats.setText(_translate(\"Dialog_cats\", \"Merge Categories\", None))\n self.pushButton_link.setText(_translate(\"Dialog_cats\", \"Link\", None))\n self.pushButton_unlink.setText(_translate(\"Dialog_cats\", \"Unlink\", None))\n self.comboBox.setItemText(0, _translate(\"Dialog_cats\", \"View graph: circle\", None))\n self.comboBox.setItemText(1, _translate(\"Dialog_cats\", \"View graph: kamada_kawai\", None))\n self.comboBox.setItemText(2, _translate(\"Dialog_cats\", \"View graph: lgl\", None))\n self.comboBox.setItemText(3, _translate(\"Dialog_cats\", \"View graph: fruchterman_reingold\", None))\n self.comboBox.setItemText(4, _translate(\"Dialog_cats\", \"View graph: random\", None))\n self.comboBox.setItemText(5, _translate(\"Dialog_cats\", \"View graph: reingold_tilford\", None))\n self.comboBox.setItemText(6, _translate(\"Dialog_cats\", \"View graph: reingold_tilford_circular\", None))\n self.comboBox.setItemText(7, _translate(\"Dialog_cats\", \"View Code Frequency Table\", None))\n self.label.setText(_translate(\"Dialog_cats\", \"View codes of selected categories\", None))\n\n\nif __name__ == \"__main__\":\n import sys\n app = QtWidgets.QApplication(sys.argv)\n Dialog_cats = QtWidgets.QDialog()\n ui = Ui_Dialog_cats()\n ui.setupUi(Dialog_cats)\n Dialog_cats.show()\n sys.exit(app.exec_())\n","sub_path":"Py3QDA-0.1/Py3QDA/Categories.py","file_name":"Categories.py","file_ext":"py","file_size_in_byte":37604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"640312321","text":"\ndef pathway (model,fluxes,outputfile_name):\n import csv\n import pandas as pd\n flux = open(outputfile_name, 'w')\n for r,v in fluxes.iteritems():\n if abs(v)>1e-6:\n flux.write(r +'\\t' + str(round(v,4)) + '\\t' + model.reactions.get_by_id(r).build_reaction_string(use_metabolite_names=True) +'\\n')\n flux.close()\n \n\n'''\ndef pathway (fluxes,outputfile_name):\n import csv\n import pandas as pd\n flux = open(outputfile_name, 'w')\n modelname = 'SEED-name.txt'\n s = csv.reader(open(modelname), delimiter=\"\\t\")\n realist = []\n realist.extend(s)\n for r,v in fluxes.iteritems():\n if abs(v)>1e-6:\n #print (r,v)\n for i in realist:\n if i[0]==r:\n flux.write(i[0] +'\\t' + str(v) + '\\t' + i[1] +'\\n')\n flux.close()\n \n''' \n'''\ndef pathway (fluxes,inputfile_name,outputfile_name):\n import csv\n import pandas as pd\n flux = open(outputfile_name, 'w')\n modelname = pd.read_excel(inputfile_name, sheet_name=2)\n for r,v in fluxes.iteritems():\n if abs(v)>1e-6:\n #print (r,v)\n for i in modelname.id:\n if i==r:\n flux.write(i[0] +'\\t' + str(v) + '\\t' + str(modelname[modelname['id']==i]['reaction_eq_name']) +'\\n')\n flux.close()\n'''\n","sub_path":"qualitycontrol-workflow/need/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"50072477","text":"\n\ndef get_environment_variable(*args, **kwargs):\n \"\"\"Mock function to return env variable.\"\"\"\n var = None\n default = None\n\n # import sys, pdb; pdb.Pdb(stdout=sys.__stdout__).set_trace()\n var = args[0]\n if len(args) == 2:\n default = args[1]\n\n if var == \"HOME\":\n value = \"/home/robot/\"\n else:\n value = None\n if default:\n value = default\n\n return value\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"463409583","text":"# -*- coding: UTF-8 -*-\nimport numpy as np\nimport math\nimport pandas as pd\nimport statsmodels.formula.api as smf\n\nclass FactorData(object):\n def __init__(self, name, stocks, mean_ret, cum_ret):\n self.name = name\n self.stocks=stocks\n self.mean_ret=mean_ret\n self.cum_ret=cum_ret\n\ndef single_analyze(name,all_data,alpha,top):\n df = alpha[name]\n\n stocks = df.groupby(level=0).apply(\n lambda x: x.T.nlargest(top, x.T.columns[0]) / x.T.nlargest(top, x.T.columns[0]).sum())\n stocks.columns = ['weights']\n stocks.index.names=['dt','tick']\n\n inc = all_data['period_inc'].shift(-1)\n if isinstance(inc,pd.DataFrame):\n inc=inc['period_inc']\n inc.name = 'period_inc'\n combine = stocks.join(inc)\n mean_ret = combine.groupby(level=0).apply(lambda x: (x['weights'] * x['period_inc']).sum())\n cum_ret = (mean_ret + 1).cumprod() - 1\n\n factor_data= FactorData(name=name,\n stocks=stocks,\n mean_ret=mean_ret,\n cum_ret=cum_ret)\n\n return factor_data\n\ndef risk_rejust(df,fac):\n \"\"\"风格因子:个股Beta、流通市值、BP;\n 行业因子:中信一级行业哑变量\"\"\"\n df.mkt=np.log10((df.mkt+0.000000000001).values.tolist())\n cols=[col for col in df.columns if col not in [fac]]\n formula='Y~'+'+'.join(cols)\n ret=pd.DataFrame(smf.ols(formula.replace('Y', fac), data=df.loc[df[fac].dropna().index, :].fillna(0)).fit().resid,\n index=df[fac].dropna().index, columns=[fac]).loc[df.index, :]\n return ret","sub_path":"freshquant/factors/util_world_alpha.py","file_name":"util_world_alpha.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"374251695","text":"from cassandra_ops import CassandraDBManagement\nfrom datetime import date\nimport time\nimport os\n\nBUNDLE_PATH = os.path.join(\"src\", \"secure-connect-ai14predictivemaintenance.zip\")\nCLIENT_ID = \"rwQwrUoTqtCSDQxfJTCYmRKz\"\nCLIENT_SECRET = \"ExLBPzzNWZYPGTE7+s3djY7HGferjymf5DejRt3zbsC_+70ObwrHv7+-WKUcQq0wrglZWM-t7c,\" \\\n \"on5TWNmtsttQOW,d.M8ZbN+o0OnZJSCBUZqe2Sgxec8DhEOz,8YC6\"\nKEYSPACE = \"logged_data\"\nTABLE_NAME = \"log\"\n\n\ndef get_manager():\n manager = CassandraDBManagement(BUNDLE_PATH, CLIENT_ID, CLIENT_SECRET)\n return manager\n\n\ndef log_detail(manager, messages):\n values = []\n for i in messages:\n today = date.today().strftime(\"%y-%m-%d\")\n now = time.localtime()\n now = time.strftime(\"%H:%M:%S\", now)\n values.append([i, today, now])\n manager.insert_values(KEYSPACE, TABLE_NAME, values)\n","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"224913058","text":"#!/usr/bin/python\n\nimport ansible_runner\nimport argparse\nimport os\n\n#global parser var\nparser = argparse.ArgumentParser(description='gluster-ansible-runner')\n\ndef setup_args():\n parser.add_argument('-p', '--playbook', required=True, help='Specify the playbook you want ansible to use')\n #--playbook brick_setup.yml\n\n parser.add_argument('-i', '--inventory', required=True, help='Specify the inventory you want ansible to use. Check code for format examples')\n #inventory input examples\n #--inventory [vdos:192.168.122.158,192.168.122.159,192.168.122.160],[other:192.168.122.158,192.168.122.159],[more:192.168.122.158]\n #--inventory [vdos:192.168.122.158,192.168.122.158,192.168.122.158],[other:192.168.122.158]\n #--inventory [vdos:192.168.122.158,192.168.122.158,192.168.122.158]\n #--inventory [vdos:172.28.128.10,172.28.128.11,172.28.128.12,172.28.128.13]\n\ndef parse_args():\n active_args = {}\n args = parser.parse_args()\n\n # convert parsed-Namespace into a key value pairing\n arg_vars = vars(args)\n\n # toggled settings are placed into dictionary of active arguments\n for foo in arg_vars:\n if arg_vars[foo]:\n active_args[foo] = arg_vars[foo]\n\n # remove redundant inventory and playbook keys from dictionary\n active_args.pop('inventory')\n active_args.pop('playbook')\n\n return active_args\n\n\n# unpack flat string into flat list\ndef string_to_list(foo):\n # remove brackets and delimt by CSVs\n temp_string = foo[1:-1]\n temp_string = temp_string.split(\",\")\n new = []\n # remove extra spaces and add to list or return values\n for x in temp_string:\n x = x.replace(' ', '')\n new.append(x)\n return new\n\n\n# unpack nested lists from input string into valid list format\ndef unpack_list(foo):\n for key, value in foo.iteritems():\n if value[0] == '[':\n foo[key] = string_to_list(value)\n return foo\n\n\ndef get_inventory():\n #Get inventory\n args = parser.parse_args()\n\n #create inventroy\n inventory = {}\n #break up groups\n groups = args.inventory.split('],[')\n #go thru groups\n for group in groups:\n #remove extra '[' & ']'\n group = group.replace('[', '')\n group = group.replace(']', '')\n #split group name from ips\n split = group.split(':')\n #creat inner dicts\n hosts = {}\n ips = {}\n #split ips\n ip_list = split[1].split(',')\n #fill ip dict with ips\n for ip in ip_list:\n ips[ip] = ''\n #put ip dict in host dict\n hosts['hosts'] = ips\n #put host in group in inventory dict\n inventory[split[0]] = hosts\n\n return inventory\n\n\n# remove generated files\ndef clean_up():\n files = ['./ansible/env/extravars', './ansible/env/settings', './ansible/inventory/hosts.json']\n for filename in files:\n try:\n os.remove(filename)\n except OSError:\n pass\n\n\ndef main():\n #setup command line args\n setup_args()\n\n #get args back and reformat them to work with ansible\n arg_vars = unpack_list(parse_args())\n\n #get inventory\n inventory = get_inventory()\n\n #playbook\n args = parser.parse_args()\n playbook = args.playbook\n\n #no output\n settings = {\"suppress_ansible_output\": False}\n\n #get private data dir\n directory = os.getcwd() + \"/ansible\"\n\n #run playbook wiht inventory\n r = ansible_runner.run(private_data_dir = directory,\n playbook = playbook,\n inventory = inventory,\n extravars = arg_vars,\n verbosity = 0,\n settings = settings)\n #clean_up()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":3741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"361482047","text":"import pandas as pd\n\nseries = pd.Series([4,5,6,7])\n#print(series)\n\n#print(\"values=\", series.values)\n#print(\"indexes=\",series.index)\n\n#print(series[2])\n#print(series[1:3])\n\n'''index need not be integers'''\n\ndata = pd.Series([12,24,36,48], index=['a','b','c','d'])\n\n#print(data)\n#print(\"Value at index b:\",data['b'])\n\n'''creating a series from a dictionary'''\n\nfruits_dict = {'apples':10,'oranges':8,'bananas':3,'strawberries':20}\nfruits = pd.Series(fruits_dict)\nprint(fruits)\nprint(\"value for apples : \",fruits['apples'])\n'''series also supports slicing'''\n\nprint(fruits['oranges':'strawberries'])\n","sub_path":"pandas_tut.py","file_name":"pandas_tut.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"250350641","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n url(r'^get/(.+)$', 'bm_handler.views.get_time'),\n url(r'^update/url/(.+)/time/(.+)$', 'bm_handler.views.update_time'),\n # Examples:\n # url(r'^$', 'BM_Server.views.home', name='home'),\n # url(r'^BM_Server/', include('BM_Server.foo.urls')),\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":"BM_Server/BM_Server/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"202753463","text":"class TileGroup(object):\n \n def __init__(self, tile):\n \n self.topLeft = tile.rect.topleft\n self.bottomRight = tile.rect.bottomright\n self.rows = 1\n self.columns = 1\n self.size = (0, 0)\n\n self.getSize()\n \n self.groupId = tile.groupId\n self.solidity = tile.solidity\n self.material = tile.material\n\n def update(self, tile):\n \n if tile.rect.topleft[0] < self.topLeft[0]:\n \n self.columns += 1\n self.topLeft = (tile.rect.topleft[0], self.topLeft[1])\n self.getSize()\n \n if tile.rect.topleft[1] < self.topLeft[1]:\n \n self.rows += 1\n self.topLeft = (self.topLeft[0], tile.rect.topleft[1])\n self.getSize()\n \n if tile.rect.bottomright[0] > self.bottomRight[0]:\n \n self.columns += 1\n self.bottomRight = (tile.rect.bottomright[0], self.bottomRight[1])\n self.getSize()\n \n if tile.rect.bottomright[1] > self.bottomRight[1]:\n \n self.rows += 1\n self.bottomRight = (self.bottomRight[0], tile.rect.bottomright[1])\n self.getSize()\n \n def getSize(self):\n \n width = abs(self.bottomRight[0] - self.topLeft[0])\n height = abs(self.bottomRight[1] - self.topLeft[1])\n self.size = (width, height)\n","sub_path":"App/TileGroup.py","file_name":"TileGroup.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"139064201","text":"import mysql.connector\nimport time\nfrom mysql.connector import Error\n\ndef cleanUp():\n \n db = mysql.connector.connect(\n host=\"localhost\",\n user=\"webadmin\",\n passwd=\"password\",\n database=\"sensoro\"\n )\n sql = \"DELETE FROM temperature WHERE DATEDIFF(day, NOW()) <= %s\"\n\n curser = db.cursor(prepared=True)\n days = '7'\n\n\n while True:\n try:\n curser.execute(sql, days, True)\n db.commit()\n print (\"Data deleted\")\n \n except mysql.connector.Error as error:\n print(\"parameterized query failed {}\".format(error))\n db.rollback() \n time.sleep(2500000)\n\n curser.close()\n db.close()\n\ncleanUp()","sub_path":"cleanUpDatabse.py","file_name":"cleanUpDatabse.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"558730757","text":"import requests\n\nfrom .models import ExchangeRate\nfrom .serializers import ExchangeRateSerializer\n\n\nclass Singleton(type):\n _instances = {}\n\n def __call__(cls, *args, **kwargs):\n if cls not in cls._instances:\n cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)\n return cls._instances[cls]\n\n\nclass ExchangeRateService(metaclass=Singleton):\n def __init__(self, api_token):\n print('ExchangeRateService init')\n self.api_token = api_token\n self.endpoint = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE'\n self.target_currency = 'USD'\n\n def get_currency_exchange_rate_in_usd(self, currency):\n response = requests.get('{}&from_currency={}&to_currency={}&apikey={}'.format(\n self.endpoint,\n currency,\n self.target_currency,\n self.api_token\n ))\n if response.status_code == 200:\n return response.json()['Realtime Currency Exchange Rate']['5. Exchange Rate']\n return None\n\n def update_currency_exchange_rate_in_usd(self, currency):\n exchange_rate = self.get_currency_exchange_rate_in_usd(currency)\n\n exchange_rate_model = ExchangeRate()\n exchange_rate_model.currency = currency\n exchange_rate_model.price = exchange_rate\n exchange_rate_model.save()\n\n @staticmethod\n def get_latest_quote():\n print(\"get latest quote\")\n exchange_rate = ExchangeRate.objects.latest('date')\n return ExchangeRateSerializer(exchange_rate).data\n\n def update_latest_quote(self):\n self.update_currency_exchange_rate_in_usd('BTC')\n","sub_path":"coinmenaenv/lib/python3.8/site-packages/btc_calculator_redis_celery_django-1.0-py3.8.egg/exchange_service/exchange_rate_service.py","file_name":"exchange_rate_service.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"126317256","text":"import json\nfrom collections import Sized\nfrom typing import Dict\nfrom py4j.java_gateway import get_field\nfrom py4j.java_collections import SetConverter\n\nfrom neuralogic import get_neuralogic, get_gateway\nfrom neuralogic.nn.base import AbstractNeuraLogic\nfrom neuralogic.core.settings import SettingsProxy\nfrom neuralogic.core.enums import Backend\n\n\nclass Loss:\n def __init__(self, loss):\n self.loss = loss\n\n def backward(self):\n self.loss.backward()\n\n def value(self) -> float:\n return get_field(self.loss.getError(), \"value\")\n\n def output(self) -> float:\n return get_field(self.loss.getOutput(), \"value\")\n\n def target(self) -> float:\n return get_field(self.loss.getTarget(), \"value\")\n\n\nclass NeuraLogic(AbstractNeuraLogic):\n class HookHandler:\n def __init__(self, module: \"NeuraLogic\"):\n self.module = module\n\n def handleHook(self, hook, value):\n self.module.run_hook(hook, json.loads(value))\n\n class Java:\n implements = [\"cz.cvut.fel.ida.neural.networks.computation.iteration.actions.PythonHookHandler\"]\n\n def __init__(self, model, template, settings: SettingsProxy):\n super().__init__(Backend.JAVA, template, settings)\n\n self.namespace = get_neuralogic().cz.cvut.fel.ida.neural.networks.computation.training.strategies\n self.do_train = True\n self.need_sync = False\n\n self.neural_model = model\n self.strategy = self.namespace.PythonTrainingStrategy(settings.settings, model)\n self.samples_len = 0\n\n self.hook_handler = NeuraLogic.HookHandler(self)\n self.reset_parameters()\n\n def reset_parameters(self):\n self.strategy.resetParameters()\n\n def train(self):\n self.do_train = True\n\n def test(self):\n self.do_train = False\n\n def set_training_samples(self, samples):\n self.samples_len = len(samples)\n self.strategy.setSamples(samples)\n\n def __call__(self, samples=None, train: bool = None, auto_backprop: bool = False, epochs: int = 1):\n self.hooks_set = len(self.hooks) != 0\n\n if self.hooks_set:\n self.strategy.setHooks(\n SetConverter().convert(set(self.hooks.keys()), get_gateway()._gateway_client), self.hook_handler\n )\n\n if train is not None:\n self.do_train = train\n\n if samples is None:\n return self.strategy.learnSamples(epochs), self.samples_len\n\n if not isinstance(samples, Sized):\n if self.do_train:\n if auto_backprop:\n return self.strategy.learnSample(samples), 1\n result = self.strategy.evaluateSample(samples)\n return Loss(result)\n\n if self.do_train:\n return self.strategy.learnSamples(samples, epochs), len(samples)\n\n results = self.strategy.evaluateSamples(samples)\n return [(get_field(result.getTarget(), \"value\"), get_field(result.getOutput(), \"value\")) for result in results]\n\n def state_dict(self) -> Dict:\n weights = self.neural_model.getAllWeights()\n weights_dict = {}\n\n for weight in weights:\n if get_field(weight, \"isLearnable\"):\n value = get_field(weight, \"value\")\n\n size = list(value.size())\n\n if len(size) == 0 or size[0] == 0:\n weights_dict[get_field(weight, \"index\")] = get_field(value, \"value\")\n elif len(size) == 1 or size[0] == 1 or size[1] == 1:\n weights_dict[get_field(weight, \"index\")] = list(get_field(value, \"values\"))\n else:\n weights_dict[get_field(weight, \"index\")] = json.loads(value.toString())\n return {\n \"weights\": weights_dict,\n }\n\n def load_state_dict(self, state_dict: Dict):\n self.sync_template(state_dict, self.neural_model.getAllWeights())\n","sub_path":"neuralogic/nn/java.py","file_name":"java.py","file_ext":"py","file_size_in_byte":3902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"245257342","text":"\"\"\"Emoji\nAvailable Commands:\n.support\nCredits to noone\n\"\"\"\n\nfrom telethon import events\n\nimport asyncio\n\nfrom userbot.utils import admin_cmd\n\n@borg.on(admin_cmd(\"gabut\"))\nasync def _(event):\n if event.fwd_from:\n return\n animation_interval = 4\n animation_ttl = range(0,3)\n #input_str = event.pattern_match.group(1)\n # if input_str == \"support\":\n await event.edit(\"Gabut?\")\n animation_chars = [\n \"Gabung Sini Aja\",\n \"[Kerabat Online](https://t.me/KerabatOnline)\"\n ]\n \n\n for i in animation_ttl:\n \t\n await asyncio.sleep(animation_interval)\n await event.edit(animation_chars[i % 18])\n","sub_path":"userbot/plugins/supportgroup.py","file_name":"supportgroup.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"451215865","text":"#Warning: this code may cause TLE\nclass Solution(object):\n \n def criticalConnections(self, n, connections):\n \"\"\"\n :type n: int\n :type connections: List[List[int]]\n :rtype: List[List[int]]\n \"\"\"\n \n def tarjan(x,fa):\n #print(x,fa)\n self.top += 1\n self.vim[x] = self.top\n self.dfn[x] = self.top\n for i in mp[x]:\n if i == fa: continue\n if self.dfn[i] == 0:\n tarjan(i,x)\n self.vim[x] = min(self.vim[i],self.vim[x])\n if self.vim[i] > self.dfn[x]:\n res.append([i,x])\n else:\n self.vim[x] = min(self.vim[x],self.dfn[i])\n self.top = 0\n res = []\n mp = {i:[] for i in range(n)}\n self.dfn = [0 for i in range(n)]\n self.vim = [0 for i in range(n)]\n for a,b in connections:\n mp[a].append(b)\n mp[b].append(a)\n for i in range(n):\n if self.dfn[i] == 0:\n tarjan(i,-1)\n return res\n \n \n","sub_path":"154/5192.py","file_name":"5192.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"156962805","text":"# -*- coding: utf-8 -*-\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.core.urlresolvers import reverse\nfrom django.utils.safestring import mark_safe\nfrom django.utils.encoding import force_text\nfrom django.conf import settings\nfrom django.forms import extras\nfrom django.utils import timezone\n\nfrom .models import User\n\nfrom smart_selects.form_fields import ChainedModelChoiceField\nfrom smart_selects.widgets import ChainedSelect\nfrom smart_selects.utils import unicode_sorter\n\nURL_PREFIX = getattr(settings, \"SMART_SELECTS_URL_PREFIX\", \"\")\n\ntry:\n from django.apps import apps\n get_model = apps.get_model\nexcept ImportError:\n from django.db.models.loading import get_model\n\nimport locale\n\n\nclass CustomChainedSelect(ChainedSelect):\n\n def render(self, name, value, attrs=None, choices=()):\n if len(name.split('-')) > 1: # formset\n chain_field = '-'.join(name.split('-')[:-1] + [self.chain_field])\n else:\n chain_field = self.chain_field\n if not self.view_name:\n if self.show_all:\n view_name = \"chained_filter_all\"\n else:\n view_name = \"chained_filter\"\n else:\n view_name = self.view_name\n kwargs = {'app': self.app_name, 'model': self.model_name,\n 'field': self.model_field, 'value': \"1\"}\n if self.manager is not None:\n kwargs.update({'manager': self.manager})\n url = URL_PREFIX + (\"/\".join(reverse(view_name, kwargs=kwargs).split(\"/\")[:-2]))\n if self.auto_choose:\n auto_choose = 'true'\n else:\n auto_choose = 'false'\n iterator = iter(self.choices)\n if hasattr(iterator, '__next__'):\n empty_label = iterator.__next__()[1]\n else:\n empty_label = iterator.next()[1] # Hacky way to getting the correct empty_label from the field instead of a hardcoded '--------'\n js = \"\"\"\n \n\n \"\"\"\n js = js % {\"chainfield\": chain_field,\n \"url\": url,\n \"id\": attrs['id'],\n 'value': value,\n 'auto_choose': auto_choose,\n 'empty_label': empty_label}\n final_choices = []\n\n if value:\n item = self.queryset.filter(pk=value)[0]\n try:\n pk = getattr(item, self.model_field + \"_id\")\n filter = {self.model_field: pk}\n except AttributeError:\n try: # maybe m2m?\n pks = getattr(item, self.model_field).all().values_list('pk', flat=True)\n filter = {self.model_field + \"__in\": pks}\n except AttributeError:\n try: # maybe a set?\n pks = getattr(item, self.model_field + \"_set\").all().values_list('pk', flat=True)\n filter = {self.model_field + \"__in\": pks}\n except: # give up\n filter = {}\n filtered = list(get_model(self.app_name, self.model_name).objects.filter(**filter).distinct())\n filtered.sort(key=lambda x: unicode_sorter(force_text(x)))\n for choice in filtered:\n final_choices.append((choice.pk, force_text(choice)))\n if len(final_choices) > 1:\n final_choices = [(\"\", (empty_label))] + final_choices\n if self.show_all:\n final_choices.append((\"\", (empty_label)))\n self.choices = list(self.choices)\n self.choices.sort(cmp=locale.strcoll, key=lambda x: unicode_sorter(x[1]))\n for ch in self.choices:\n if ch not in final_choices:\n final_choices.append(ch)\n self.choices = ()\n final_attrs = self.build_attrs(attrs, name=name)\n if 'class' in final_attrs:\n final_attrs['class'] += ' chained'\n else:\n final_attrs['class'] = 'chained'\n output = super(ChainedSelect, self).render(name, value, final_attrs, choices=final_choices)\n # output += js\n return mark_safe(output)\n\n\nclass CustomRegistrationForm(UserCreationForm):\n birthday = forms.DateField(label=u'Дата рождения', widget=extras.SelectDateWidget(years=range(1970, timezone.now().year)), required=False)\n storage = ChainedModelChoiceField(label=u'Новая почта', app_name='accounts', model_name='storage', chain_field='city', model_field='city', show_all=False, auto_choose=False, required=False, widget=CustomChainedSelect(app_name='accounts', model_name='storage', chain_field='city', model_field='city', show_all=False, auto_choose=False))\n\n class Meta:\n model = User\n fields = (\"first_name\", \"last_name\", \"avatar\", \"birthday\",\n \"email\", \"city\", \"storage\", \"phone\", \"unsubscribe\")\n\n def clean_username(self):\n # Since User.username is unique, this check is redundant,\n # but it sets a nicer error message than the ORM. See #13147.\n username = self.cleaned_data[\"username\"]\n try:\n User._default_manager.get(username=username)\n except User.DoesNotExist:\n return username\n raise forms.ValidationError(\n self.error_messages['duplicate_username'],\n code='duplicate_username',\n )\n\n def clean_email(self):\n \"\"\"\n Validate that the supplied email address is unique for the\n site.\n \"\"\"\n if User.objects.filter(email__iexact=self.cleaned_data['email']):\n raise forms.ValidationError(_(\"This email address is already in use. Please supply a different email address.\"))\n return self.cleaned_data['email']\n\n\nclass ProfileForm(forms.ModelForm):\n birthday = forms.DateField(label=u'Дата рождения', widget=extras.SelectDateWidget(years=range(1970, timezone.now().year)), required=False)\n storage = ChainedModelChoiceField(label=u'Новая почта', app_name='accounts', model_name='storage', chain_field='city', model_field='city', show_all=False, auto_choose=False, required=False, widget=CustomChainedSelect(app_name='accounts', model_name='storage', chain_field='city', model_field='city', show_all=False, auto_choose=False))\n\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'avatar', 'birthday', 'email',\n 'phone', 'city', 'storage', 'unsubscribe')\n widgets = {\n 'avatar': forms.FileInput\n }\n","sub_path":"apps/accounts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":10258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"277969274","text":"import math\nimport torch\nimport torch.nn as nn\n\ncfg = {'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512,\n 512, 'M', 512, 512, 512, 'M']}\n\n\nclass VGG(nn.Module):\n def __init__(self, net_name):\n super(VGG, self).__init__()\n\n # 构建网络的卷积层和池化层,最终输出命名features,原因是通常认为经过这些操作的输出\n # 为包含图像空间信息的特征层\n self.features = self._make_layers(cfg[net_name])\n\n # 构建卷积层之后的全连接层以及分类器\n self.classifier = nn.Sequential(\n nn.Dropout(), # 防止或减少过拟合采用的函数 函数会在训练过程中随机扔掉一部分神经元 按照概率使某个神经元不更新权重\n nn.Linear(512, 512), # fc1\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(512, 512), # fc2\n nn.ReLU(True),\n nn.Linear(512, 10) # fc3 最终Cifar10的输出是10分类\n )\n\n # 初始化权重\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n m.bias.data.zero_()\n\n def forward(self, x):\n x = self.features(x) # 前向传播的时候先经过卷积层和池化层\n x = x.view(x.size(0), -1)\n x = self.classifier(x) # 再将features(得到网络输出的特征层)的结果拼接到分类器上\n return x\n\n def _make_layers(self, cfg):\n layers = []\n in_channels = 3\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n else:\n # conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)\n # layers += [conv2d, nn.ReLU(inplace=True)]\n layers += [nn.Conv2d(in_channels, v, kernel_size=3, padding=1),\n nn.BatchNorm2d(v),\n nn.ReLU(inplace=True)]\n in_channels = v\n return nn.Sequential(*layers)\n\n\nnet = VGG('VGG16')\n","sub_path":"Pytorch_VGG16/VGG16.py","file_name":"VGG16.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"600215256","text":"from Util.Import import load_new_file, load_original_file, get_files\nimport unicodedata as ud\nimport re\nimport json\nimport math\n\nclass Vectoriser:\n \"\"\"\n Class for building vectors from tweets\n \"\"\"\n def __init__(self):\n self.dictionary = {}\n self.id_reference = {}\n self.idf = {}\n self.n_dt = {}\n self.document_count = 0\n self._id = 0\n\n def generate_id(self):\n \"\"\"\n :return: numbers incrementing by 1 each time function is called\n \"\"\"\n self._id += 1\n return self._id\n\n def count(self, string):\n \"\"\"\n Counts documents containing each word in string and builds id/term dictionaries\n :param string: text sentence\n :return: null\n \"\"\"\n self.document_count += 1\n string = self.tokeniser(string)\n processed = []\n for word in string:\n try:\n id = self.dictionary[word]\n except KeyError:\n id = self.generate_id()\n self.dictionary[word] = id\n self.id_reference[id] = word\n if word not in processed:\n try:\n self.n_dt[id] += 1\n except KeyError:\n self.n_dt[id] = 1\n\n def build_idf(self):\n \"\"\"\n Computes inverse document frequency as a class attribute\n :return: null\n \"\"\"\n self.idf = {term_id: math.log(self.document_count / self.n_dt[term_id], 2) for term_id in self.n_dt.keys()}\n\n def vectorise(self, string):\n \"\"\"\n convert string into a bag of words vector\n :param string: text sentence\n :return: sparse vector in dictionary format\n \"\"\"\n sentence = self.tokeniser(string)\n vector = {}\n\n for word in sentence:\n id = self.dictionary[word]\n try:\n vector[id] += 1\n except KeyError:\n vector[id] = 1\n\n for k in vector.keys():\n vector[k] *= self.idf[k]\n\n return vector\n\n def add_vector(self, df):\n \"\"\"\n add vector to dataframe\n :param df: dataframe with no vector\n :return: dataframe with vector\n \"\"\"\n df['vector'] = df['text'].map(lambda text: self.vectorise())\n return df\n\n def tokeniser(self, string):\n \"\"\"\n split full sentence into list of tokens\n :param string: text sentence\n :return: list of tokens\n \"\"\"\n # TODO: develop tokeniser\n string = string.lower()\n list = string.split()\n return list\n\n# get filenames for original data and new processed data\nfiles = get_files('./Twitter')\nnew_files = get_files()\n\n# initialise vectoriser tool\nvec = Vectoriser()\nno_files = len(files)\n\n# loop over original data to build term dictionaries and count term frequencies\nfor i, file in enumerate(files):\n if i % 20 == 0:\n print(\"Building IDF: {}/{} files\\r\".format(i+1, no_files), end='\\r')\n data = load_original_file(file)\n data = data[['username', 'date', 'text', 'profileLocation', 'latitude', 'longitude']]\n data.text.map(lambda tweet: vec.count(tweet))\n if i == no_files - 1:\n print(\"Building IDF: Complete\")\n\n# save id/term dictionaries in json format\nwith open('term_to_id_dictionary.txt', 'w') as fp:\n json.dump(vec.dictionary, fp)\n\nwith open('id_to_term_dictionary.txt', 'w') as fp:\n json.dump(vec.id_reference, fp)\n\n# calculate inverse document frequency from documents\nvec.build_idf()\n\n# add vector to data, drop unnecessary columns and save data to new path\nfor i, file in enumerate(files):\n if i % 20 == 0:\n print(\"Adding vector to data: {}/{} files\\r\".format(i+1, no_files), end='\\r')\n data = load_original_file(file)\n data = data[['username', 'date', 'text', 'profileLocation', 'latitude', 'longitude']]\n data = vec.add_vector(data)\n if i == no_files - 1:\n print(\"Vectorising: Complete\")\n data.to_json(new_files[i], orient='index')\n\n\n\n","sub_path":"ProcessData.py","file_name":"ProcessData.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"97588679","text":"import requests\nimport json\nimport os\n\nfrom bottle import run, route, request, response, static_file\n\nfrom oom_api import zipper_tools\n\nserver_utilities = {}\nerror_texts = {}\n\n\n# defining the handler\n@route('/oom', method='POST')\ndef modeling_handler():\n try:\n received = request.json\n except Exception as e:\n print(e)\n response.status = 401\n return error_texts['wrong_input_format']\n\n for required_field in server_utilities['required_fields']:\n if required_field not in received:\n response.status = 401\n return error_texts['required_field_missing'] % required_field\n\n received_text = received['text']\n received_language = received['language']\n\n if type(received_text) is not str or type(received_language) is not str:\n response.status = 401\n return error_texts['wrong_input_format']\n if received_language not in server_utilities['languages']:\n response.status = 401\n return error_texts['language_not_supported'] % received_language\n\n try:\n processor_response = requests.post(server_utilities['text_processor_uri'], data=received_text)\n except Exception as exception:\n print(exception)\n response.status = 500\n return error_texts['unhandled exception'] % \"Text processor\"\n else:\n if processor_response.status_code != 200:\n response.status = processor_response.status_code\n return processor_response.text\n print(processor_response.json())\n print(server_utilities['languages'][received_language])\n try:\n generator_response = requests.post(server_utilities['languages'][received_language],\n json=processor_response.json())\n except Exception as exception:\n print(exception)\n response.status = 500\n return error_texts['unhandled exception'] % \"Code generator\"\n else:\n if generator_response.status_code != 200:\n response.status = generator_response.status_code\n return generator_response.text\n\n zipping_input = {\n \"text\": received_text,\n \"language\": received_language,\n \"entities\": generator_response.json()\n }\n\n try:\n zipper_tools.validate(zipping_input)\n except zipper_tools.BadInputForZipper as bad_input_exception:\n response.status = 412\n return bad_input_exception.args\n try:\n response.status = 200\n zip_file_to_return = zipper_tools.return_zip(zipping_input)\n except Exception as e:\n print(e)\n response.status = 500\n return \"There was an unhandled exception during the zip-file-creation.\"\n\n return {\"entities\": generator_response.json(), \"zip-uri\": zip_file_to_return}\n\n\n@route('/downloading/')\ndef server_static(filename):\n return static_file(filename, root='./zips/')\n\n\ndef main():\n global server_utilities\n global error_texts\n with open('server_utilities.json') as server_utilities_json:\n server_utilities = json.load(server_utilities_json)\n error_texts = {\n 'wrong_input_format': 'The format of the request is not processable',\n 'required_field_missing': 'The %s field was not find in your request.',\n 'language_not_supported': 'The language %s is not supported',\n 'unhandled exception': 'Unhandled exception.[%s]'\n }\n if 'languages' not in server_utilities \\\n or 'text_processor_uri' not in server_utilities \\\n or 'required_fields' not in server_utilities:\n print('The server can not start with a invalid server_utilities.json')\n\n if not os.path.exists(\"zips\"):\n os.makedirs(\"zips\")\n\n run(host='0.0.0.0', port='2000')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"oom_python/oom_api/oom_api_server.py","file_name":"oom_api_server.py","file_ext":"py","file_size_in_byte":3754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"255554023","text":"#! /usr/bin/python3\n\nimport logging\nlogging.basicConfig(level=logging.DEBUG,\n format=\"{asctime} {name} {levelname} - {message}\", style=\"{\")\nlog = logging.getLogger()\n\nempty_dict = {}\nlog.debug(empty_dict)\n\ndict_origin = {\n \"seconds\": \"1\",\n \"minutes\": \"2\",\n \"hour\": \"3\",\n \"day\": \"4\",\n \"month\": \"5\",\n \"year\": \"5\"\n}\nprint(dict_origin)\n\nlol = [ ['a', 'b'], ['c', 'd'], ['e', 'f'] ]\nprint(dict(lol))\n\nlot = [ ('a', 'b'), ('c', 'd'), ('e', 'f') ]\nprint(dict(lot))\n\ntos = ('ab', 'cd', 'ef')\nprint(dict(tos))\n\ndict_origin[\"year\"] = 2019\nprint(dict_origin)\n\nothers = {\n \"century\": \"6\",\n \"millennium\": \"7\",\n \"month\":\"February\"\n}\n\ndict_origin.update(others)\nprint(\"Update:\", dict_origin)\n\ndel dict_origin[\"seconds\"]\nprint(\"Delete element:\", dict_origin)\n\nprint(\"Checks whether 'seconds' key was deleted from collection:\", \"seconds\" in dict_origin)\n\nprint(\"Current month:\", dict_origin.get(\"month\", \"January\"))\n\nprint(dict_origin.keys())\nprint(dict_origin.values())\nprint(dict_origin.items(), end=\"\\n\\n\")\n\ndictCopy = dict_origin.copy()\ndictCopy[\"minutes\"] = \"47\"\ndictCopy[\"hours\"] = \"17\"\nprint(\"Origin:\", dict_origin)\nprint(\"Copy:\", dictCopy, end=\"\\n\\n\")\n\ndef iteration():\n test_dict = dict(a=1, c=3, b=2)\n for k in test_dict:\n log.debug(f\"key: {k} {test_dict[k]}\")\n\n for k in sorted(test_dict):\n log.debug(f\"sorted key: {k} {test_dict[k]}\")\n\ndef my_dict_assignment():\n my_dict = {}\n my_dict[\"key\"] = my_dict.get(\"key\", None) or 10\n log.debug(f\"{my_dict}\")\n\ndef main():\n iteration()\n my_dict_assignment()\n\nif __name__ == \"__main__\":\n main()","sub_path":"py_containers/py_dict.py","file_name":"py_dict.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"422781301","text":"import os, glob, sys\n\nhome = os.path.expanduser('~')\n\ntarget_directory = os.path.join(home, 'workspace/python/diveintopython3/examples/')\n\nanother_target_directory = os.path.join(home, 'workspace/python/python_exercises/1/')\n\nsys.path.insert(0, another_target_directory)\n\nimport humansize\n\ndef empty_line(): \n\t''' \n\tThis function will return an empty line by\n\tprinting an empty string it allows these \n\texercises to be more readable.\n\t'''\n\tprint('')\n\n\nos.chdir(target_directory)\n\n# Create a variable metadata = list that finds a\n# all .py files with test in their name and then\n# constructs a tuple of the file name and the file\n# metadata using the os.stat function on each item\n# in the list.\nmetadata = [(f, os.stat(f)) for f in glob.glob('*test*.py')]\n\nempty_line()\n\n# Print the first item in the tuple \n# created by metadata\nprint(metadata[0])\n\nempty_line()\n\n# Create the variable metadata_dict which creates\n# a dictionary. The key for the dictionary will be\n# the name of the file in this case. The value will\n# be the file metadata found by os.stat() function.\nmetadata_dict = {f:os.stat(f) for f in glob.glob('*test*.py')}\n\n# A dictionary comprehension will return a dictionary\nprint(type(metadata_dict))\n\nempty_line()\n\n# Returns a list of the keys that were found \n# using glob.glob('*test*'). In this case, it would\n# just return a list of the file names. \nprint(list(metadata_dict.keys()))\n\nempty_line()\n\n# We can use the key we created with metadata_dict \n# to return the metadata of the entire file (the\n# value of the dictionary key.) If we want to return\n# just one piece of metadata, we can do that with\n# using the .st_size() function on the returned value\n# from the dictionary key.\nprint(metadata_dict['alphameticstest.py'].st_size)\n\nempty_line()\n\n# Creating a dictionary has the key that is the file\n# name and value as the metadata of the file. This\n# is for the files in the current directory.\nmetadata_dict_2 = {f:os.stat(f) for f in glob.glob('*')}\n\n# We create a new dictionary called humansize_dict\n# in which the key is with the file name split from\n# it's extension. The files this dictionary will \n# filter out must also be greater than 6000 bytes.\n# The value will be converted using the humasize \n# approximate_size() function using the variable\n# meta and using the st_size() function. We will\n# then use a for loop for the variable f and meta\n# to create the list of keys and values from the\n# metadata_dict_2 items in the dictionary we created.\nhumansize_dict = {os.path.splitext(f)[0]:humansize.approximate_size(meta.st_size) for f, meta in metadata_dict_2.items() if meta.st_size > 6000}\n\n# This print's a list of the dictionary keys for\n# our new humansize_dict dictionary.\nprint(list(humansize_dict.keys()))\n\nempty_line()\n\n# This will print the value for the dictionary key\n# 'romantest9' inside the humansize_dict dictionary.\nprint(humansize_dict['romantest9'])\n\n","sub_path":"3/Dictionary_Comprehensions/dictionary_comprehensions.py","file_name":"dictionary_comprehensions.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"226499758","text":"#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: dchanna\n#\n# Created: 25/07/2020\n# Copyright: (c) dchanna 2020\n# Licence: \n#-------------------------------------------------------------------------------\n\nimport cv2\nimport pytesseract\nimport matplotlib.pyplot as plt\n\nfilename = 'Full.png'\n\n# read the image and get the dimensions\nimg = cv2.imread(filename)\nh, w, _ = img.shape # assumes color image\n\n# run tesseract, returning the bounding boxes\nboxes = pytesseract.image_to_boxes(img) #use\nprint(pytesseract.image_to_string(img)) #print identified text\n\n# draw the bounding boxes on the image\nfor b in boxes.splitlines():\n b = b.split()\n cv2.rectangle(img, ((int(b[1]), h - int(b[2]))), ((int(b[3]), h - int(b[4]))), (0, 255, 0), 2)\n\nplt.imshow(img)","sub_path":"ImageHighlighter.py","file_name":"ImageHighlighter.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"190573599","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\n\n\n# Hyper-parameters\ninput_size = 3 * 32 * 32\nnum_classes = 10\nvalues = [0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007, 0.0008, 0.0009]\n\nnum_epochs = 10\nbatch_size = 32\nfor j in range(4):\n for num in values:\n learning_rate = num * (10**j)\n\n # MNIST dataset (images and labels)\n train_dataset = torchvision.datasets.CIFAR10(root='../../data',\n train=True,\n transform=transforms.ToTensor(),\n download=True)\n\n test_dataset = torchvision.datasets.CIFAR10(root='../../data',\n train=False,\n transform=transforms.ToTensor())\n\n # Data loader (input pipeline)\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size,\n shuffle=True)\n\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset,\n batch_size=batch_size,\n shuffle=False)\n\n # Logistic regression model\n model = nn.Linear(input_size, num_classes)\n\n # Loss annn.Lid optimizer\n # nn.CrossEntropyLoss() computes softmax internally\n criterion = nn.CrossEntropyLoss() # Read About this Loss + Try Other Losses\n optimizer = torch.optim.Adagrad(model.parameters(), lr=learning_rate) # Read About This Try different opt\n\n strLoss = \"CrossEntropyLoss\"\n strOptimizer = \"Ada\"\n\n # Train the model\n total_step = len(train_loader)\n for epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n # Reshape images to (batch_size, input_size)\n images = images.reshape(-1, input_size)\n\n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n\n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if (i + 1) % 100 == 0:\n print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'\n .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))\n\n # Test the model\n # In test phase, we don't need to compute gradients (for memory efficiency)\n with torch.no_grad():\n correct = 0\n total = 0\n for images, labels in test_loader:\n images = images.reshape(-1, input_size)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n\n accuracy = 100 * correct / total\n print('Accuracy of the model on the 10000 test images: {} %'.format(accuracy))\n\n # Plotting:\n # 1. Append data to text file:\n # loss, optimizer, batch_size, num_epochs, learning_rate, accuracy\n # 2. Plot using data in the file\n f = open(\"learning_rate.txt\", \"a\")\n f.write(\n \"{} {} {} {} {} {}%\\n\".format(strLoss, strOptimizer, batch_size, num_epochs, learning_rate, accuracy))\n f.close()\n\n # Save the model checkpoint\n torch.save(model.state_dict(), 'model.ckpt')\n","sub_path":"cifar_10_no_layers.py","file_name":"cifar_10_no_layers.py","file_ext":"py","file_size_in_byte":3643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"401476272","text":"plotvar = 'F0'\n\ndef make_RLN_SLN_plot():\n\n colorbarlabel = label_dict[plotvar]\n\n for leftRLNnum in range(Nlevels):\n # fig, ax = plt.subplots(figsize = (16, 12))\n fig, ax = plt.subplots()\n ax.set_title('left RLN %d' % leftRLNnum)\n\n axim = ax.imshow(var_plot[plotvar][leftRLNnum, :, :])\n\n axim.set_clim(np.nanmin(var_plot[plotvar]), np.nanmax(var_plot[plotvar]))\n ax.relim()\n\n co = ax.contour(axim.get_array(), \n 6, \n colors = 'w')\n ax.clabel(co, fmt = '%.0f', fontsize = 10, inline = True)\n\n ax.axis([-0.5, 4.5, -0.5, 7.5])\n\n ax.set_ylabel('right RLN')\n\n ax.grid(False)\n\n if leftRLNnum == 0:\n cb = fig.colorbar(axim, ax = ax)\n cb.set_label(colorbarlabel)\n\n if leftRLNnum == Nlevels - 1:\n ax.set_xlabel('SLN')\n\n if False:\n plt.savefig('.pdf', orientation = 'landscape',\n papertype = 'letter', format = 'pdf',\n bbox_inches = 'tight', pad_inches = 0.1)\n plt.show()\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"578733603","text":"import requests\n\nBASE_URL = \"http://127.0.0.1:5000/\"\n\n\ndef test_get_method_return_first_video_from_table():\n stubber = {\n 'id': 1,\n \"title\": \"Intégral de Cabrel\",\n \"views\": 1,\n \"likes\": 1,\n }\n response = requests.get(BASE_URL + 'video/%d' % 1)\n print(\"response : \", response.json())\n assert response.json() == stubber\n\n\ndef test_get_method_return_full_list_of_video_from_table():\n stubber1 = {\n 'id': 1,\n \"title\": \"Intégral de Cabrel\",\n \"views\": 1,\n \"likes\": 1,\n }\n response = requests.get((BASE_URL + 'video'))\n print(\"response : \", response.json())\n \n assert response.json()[0] == stubber1\n\ndef test_post_method_signup_activate():\n response = requests.post(BASE_URL + \"/signup/activate/test1\")\n assert response.json() == \"test1\"\n","sub_path":"tests/test_video_api.py","file_name":"test_video_api.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"410673257","text":"# Copyright 2017 D-Wave Systems Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\nimport os\nimport time\nimport multiprocessing\nimport itertools\n\nimport networkx as nx\nimport penaltymodel.core as pm\nimport dimod\n\nimport penaltymodel.cache as pmc\n\ntmp_database_name = 'tmp_test_database_manager_{}.db'.format(time.time())\n\n\nclass TestInterfaceFunctions(unittest.TestCase):\n def setUp(self):\n self.database = pmc.cache_file(filename=tmp_database_name)\n\n def test_typical(self):\n dbfile = self.database\n\n # insert a penalty model\n graph = nx.path_graph(3)\n decision_variables = (0, 2)\n feasible_configurations = {(-1, -1): 0., (+1, +1): 0.}\n spec = pm.Specification(graph, decision_variables, feasible_configurations, dimod.SPIN)\n linear = {v: 0 for v in graph}\n quadratic = {edge: -1 for edge in graph.edges}\n model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN)\n widget = pm.PenaltyModel.from_specification(spec, model, 2., -2)\n\n # cache the penaltymodel\n pmc.cache_penalty_model(widget, database=dbfile)\n\n # retrieve it\n widget_ = pmc.get_penalty_model(spec, database=dbfile)\n\n self.assertEqual(widget_, widget)\n\n def test_arbitrary_labels(self):\n dbfile = self.database\n\n # set up a specification and a corresponding penaltymodel\n graph = nx.Graph()\n for i in 'abcd':\n for j in 'efgh':\n graph.add_edge(i, j)\n\n decision_variables = ('a', 'e')\n feasible_configurations = ((-1, -1), (1, 1)) # equality\n\n spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.SPIN)\n\n linear = {v: 0 for v in graph}\n quadratic = {edge: 0 for edge in graph.edges}\n if decision_variables in quadratic:\n quadratic[decision_variables] = -1\n else:\n u, v = decision_variables\n assert (v, u) in quadratic\n quadratic[(v, u)] = -1\n model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN)\n pmodel = pm.PenaltyModel.from_specification(spec, model, 2, -1)\n\n # now cache the pmodel to make sure there is something to find\n pmc.cache_penalty_model(pmodel, database=dbfile)\n\n # now try to retrieve it\n retreived_pmodel = pmc.get_penalty_model(spec, database=dbfile)\n\n self.assertIs(retreived_pmodel.model.vartype, dimod.SPIN)\n\n # check that the specification is equal to the retreived_pmodel\n self.assertTrue(spec.__eq__(retreived_pmodel))\n\n def test_binary_specification(self):\n dbfile = self.database\n\n # set up a specification and a corresponding penaltymodel\n graph = nx.Graph()\n for i in 'abcd':\n for j in 'efgh':\n graph.add_edge(i, j)\n\n decision_variables = ('a', 'e')\n feasible_configurations = ((0, 0), (1, 1)) # equality\n\n spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.BINARY)\n\n linear = {v: 0 for v in graph}\n quadratic = {edge: 0 for edge in graph.edges}\n if decision_variables in quadratic:\n quadratic[decision_variables] = -1\n else:\n u, v = decision_variables\n assert (v, u) in quadratic\n quadratic[(v, u)] = -1\n model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN)\n pmodel = pm.PenaltyModel.from_specification(spec, model, 2, -1)\n\n # now cache the pmodel to make sure there is something to find\n pmc.cache_penalty_model(pmodel, database=dbfile)\n\n # now try to retrieve it\n retreived_pmodel = pmc.get_penalty_model(spec, database=dbfile)\n\n self.assertIs(retreived_pmodel.model.vartype, dimod.BINARY)\n\n # check that the specification is equal to the retreived_pmodel\n self.assertTrue(spec.__eq__(retreived_pmodel))\n\n def test_arbitrary_labels_on_k44(self):\n dbfile = self.database\n\n graph = nx.Graph()\n for i in range(3):\n for j in range(3, 6):\n graph.add_edge(i, j)\n\n decision_variables = (0, 5)\n feasible_configurations = ((0, 0), (1, 1)) # equality\n\n spec = pm.Specification(graph, decision_variables, feasible_configurations, vartype=dimod.BINARY)\n\n linear = {v: 0 for v in graph}\n quadratic = {edge: 0 for edge in graph.edges}\n if decision_variables in quadratic:\n quadratic[decision_variables] = -1\n else:\n u, v = decision_variables\n assert (v, u) in quadratic\n quadratic[(v, u)] = -1\n model = dimod.BinaryQuadraticModel(linear, quadratic, 0.0, vartype=dimod.SPIN)\n pmodel = pm.PenaltyModel.from_specification(spec, model, 2, -1)\n\n # now cache the pmodel to make sure there is something to find\n\n for thingy in itertools.permutations(range(6)):\n mapping = dict(enumerate(thingy))\n pmodel = pmodel.relabel_variables(mapping, inplace=False)\n pmc.cache_penalty_model(pmodel, database=dbfile)\n\n # now relabel some variables\n mapping = {1: '1', 2: '2', 3: '3', 4: '4'}\n\n new_spec = spec.relabel_variables(mapping, inplace=True)\n\n # retrieve from the new_spec\n # now try to retrieve it\n retreived_pmodel = pmc.get_penalty_model(new_spec, database=dbfile)\n\n def test_insert_retrieve(self):\n dbfile = self.database\n\n linear = {'1': 0.0, '0': -0.5, '3': 1.0, '2': -0.5}\n quadratic = {('0', '3'): -1.0, ('1', '2'): 1.0, ('0', '2'): 0.5, ('1', '3'): 1.0}\n offset = 0.0\n model = dimod.BinaryQuadraticModel(linear, quadratic, offset, vartype=dimod.SPIN)\n\n graph = nx.Graph()\n graph.add_edges_from(quadratic)\n decision_variables = ('0', '2', '3')\n feasible_configurations = ((-1, -1, -1), (-1, 1, -1), (1, -1, -1), (1, 1, 1))\n spec = pm.Specification(graph, decision_variables, feasible_configurations, dimod.SPIN)\n\n classical_gap = 2\n ground = -2.5\n\n pmodel = pm.PenaltyModel.from_specification(spec, model, classical_gap, ground)\n\n pmc.cache_penalty_model(pmodel, database=dbfile)\n\n # print(spec.feasible_configurations)\n # print(spec.decision_variables)\n\n # get it back\n ret_pmodel = pmc.get_penalty_model(spec, database=dbfile)\n\n # now get back one with a different decision_variables\n spec2 = pm.Specification(graph, ('3', '0', '2'), feasible_configurations, dimod.SPIN)\n try:\n ret_pmodel = pmc.get_penalty_model(spec2, database=dbfile)\n self.assertNotEqual(ret_pmodel, pmodel)\n except:\n pass\n\n def test_one_variable_insert_retrieve(self):\n \"\"\"Test case when there is no quadratic contribution (i.e. cache will\n receive an empty value for the quadratic contribution)\n \"\"\"\n dbfile = self.database\n\n # generate one variable model (i.e. no quadratic terms)\n spec = pm.Specification(graph=nx.complete_graph(1),\n decision_variables=[0],\n feasible_configurations=[(-1,)],\n min_classical_gap=2, vartype='SPIN')\n pmodel = pm.get_penalty_model(spec)\n\n # insert model into cache\n pmc.cache_penalty_model(pmodel, database=dbfile)\n\n # retrieve model back from cache\n retrieved_model = pmc.get_penalty_model(spec, database=dbfile)\n self.assertEqual(pmodel, retrieved_model)\n\n def test_no_linear_bias_insert_retrieve(self):\n \"\"\"Test case when there is no linear bias\"\"\"\n dbfile = self.database\n\n # define specifications\n spec = pm.Specification(graph=nx.complete_graph(2),\n decision_variables=[0, 1],\n feasible_configurations=[(-1, +1), (+1, -1)],\n min_classical_gap=2, vartype='SPIN')\n\n # make a model\n # note: model must satisfy specifications and not have a nonzero linear bias\n linear = {}\n quadratic = {(0, 1): 1}\n offset = 0.0\n model = dimod.BinaryQuadraticModel(linear, quadratic, offset, vartype=dimod.SPIN)\n pmodel = pm.PenaltyModel.from_specification(spec, model, 2, -1)\n\n # insert model into cache\n pmc.cache_penalty_model(pmodel, database=dbfile)\n\n # retrieve model back from cache\n retrieved_model = pmc.get_penalty_model(spec, database=dbfile)\n self.assertEqual(pmodel, retrieved_model)\n","sub_path":"penaltymodel_cache/tests/test_interface.py","file_name":"test_interface.py","file_ext":"py","file_size_in_byte":9203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"131149920","text":"from astropy import units as u\nfrom astropy.io import fits\nfrom astropy.wcs import wcs\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates import match_coordinates_sky\nimport matplotlib.pyplot as plt \nimport numpy as np \n\n#first step is to get the CO values\nhdulist=fits.open('/Users/amandaquirk/Documents/AsymmetricDrift/Data/m31_iram/m31_iram.mom1.fits')\n\n#read in header info for astropy's coordinate converter\nw = wcs.WCS(hdulist[0].header, naxis = 2)\n\n#read in Av value\ndata=hdulist[0].data \n\n#pixel values of dust map\nx_vals=np.linspace(0, 549, 550)\ny_vals=np.linspace(0, 649, 650)\n\nCO_v=[]\nRA=[]\nDec=[]\nfor i in range(len(x_vals)):\n\tfor j in range(len(y_vals)):\n\t\tx=int(x_vals[i]) #gets x coord of pixel\n\t\ty=int(y_vals[j]) #gets y coord of pixel\n\t\tCO_v.append(data[y,x]) #adds the velocity vales\n\t\tcoord=np.array([[x, y]], np.float_) #puts coords into an array\n\t\tworld=w.wcs_pix2world(coord, 1) #converts the coordinate into world coordinate\n\t\tRA.append(world[0][0])\n\t\tDec.append(world[0][1])\n\nRA_good = [a for a, b in zip(RA, CO_v) if np.isnan(b)==False]\nDec_good = [a for a, b in zip(Dec, CO_v) if np.isnan(b)==False]\nCO_v_good = [b for b in zip(CO_v) if np.isnan(b)==False]\n\n#convert the dust coordinates to xi and eta\ndef m31_coord(RA, Dec, x=True):\n\tm31 = SkyCoord(10.6847083*u.deg, 41.26875*u.deg, frame='icrs')\n\tc=SkyCoord(RA, Dec, frame='icrs', unit=(u.deg,u.deg))\n\tc_inm31=c.transform_to(m31.skyoffset_frame())\n\txi, eta=c_inm31.lon, c_inm31.lat\n\tif x==True:\n\t\treturn xi*13.67 \n\tif x==False:\n\t\treturn eta*13.67 \n\nCO_xi=m31_coord(RA_good, Dec_good, x=True)\nCO_eta=m31_coord(RA_good, Dec_good, x=False)\n\n#importing the star data\n#xi (kpc), eta (kpc), average v(km/s), v err,var, n, HI main, HI close <-- header of data file to be read in \nMS_xi, MS_eta=np.loadtxt('/Users/amandaquirk/Documents/AsymmetricDrift/Data/MS_smoothed_chemin.txt', usecols=(0,1,), unpack=True)\n\n#line to see where CO data ends\ndef y(x):\n\treturn 16.8 - 0.8 * x\n\nx = np.linspace(0,13, 10)\n\nplt.scatter(CO_xi, CO_eta, c=CO_v_good)\nim = plt.scatter(MS_xi, MS_eta, c= 'b', alpha=0.4)\nplt.plot(x, y(x))\nplt.gca().invert_xaxis()\nplt.xlabel('xi (kpc)')\nplt.ylabel('eta (kpc)')\nplt.show()\nplt.close()\n\n#truncating the star data to just inside the CO field\nCO_field = MS_eta < 16.8 - 0.8 * MS_xi\nMS_xi = MS_xi[CO_field]\nMS_eta = MS_eta[CO_field]\n\n#turning xi and eta into a coordinate pair\ndef coords(xi, eta):\n\treturn SkyCoord(xi/13.67, eta/13.67, unit=(u.deg, u.deg)) #dividing by 13.67 to convert to degrees\n\nCO_coords=coords(CO_xi, CO_eta)\nMS_coords=coords(MS_xi, MS_eta)\n\n#function finds the closest CO\ndef find_closest(star, data):\n\tidx,d2d,d3d=star.match_to_catalog_sky(data)\n\treturn idx\n\nindices = find_closest(MS_coords, CO_coords)\n\n#write oMSinial coordinates of CO\ndef CO_coords_deg(RA, Dec, x=True):\n\tc = SkyCoord(RA, Dec, unit=(u.deg, u.deg))\n\tif x==True:\n\t\treturn c.ra.deg \n\tif x==False:\n\t\treturn c.dec.deg\n\nCO_RA = CO_coords_deg(RA_good, Dec_good, x=True) \nCO_Dec = CO_coords_deg(RA_good, Dec_good, x=False)\n\n\nMS_CO_v = []\nMS_RA = []\nMS_Dec = []\nfor i in indices:\n\tMS_CO_v.append(CO_v_good[i])\n\tMS_RA.append(CO_RA[i])\n\tMS_Dec.append(CO_Dec[i])\n\nplt.scatter(MS_RA, MS_Dec, c=MS_CO_v)\nplt.gca().invert_xaxis()\nplt.xlabel('xi (kpc)')\nplt.ylabel('eta (kpc)')\nplt.colorbar()\nplt.show()\n\nnp.savetxt('/Users/amandaquirk/Desktop/MS_CO.txt', np.c_[MS_xi, MS_eta, MS_CO_v, MS_RA, MS_Dec], fmt='%1.16f', delimiter=' ', header='xi (kpc), eta (kpc), CO v, RA (deg), Dec (deg)')\n","sub_path":"matching_CO.py","file_name":"matching_CO.py","file_ext":"py","file_size_in_byte":3472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"478901195","text":"\n\"\"\"\nEach ListNode holds a reference to its previous node\nas well as its next node in the List.\n\"\"\"\nclass ListNode:\n def __init__(self, value, prev=None, next=None):\n self.prev = prev\n self.value = value\n self.next = next\n \n\"\"\"\nOur doubly-linked list class. It holds references to \nthe list's head and tail nodes.\n\"\"\"\nclass DoublyLinkedList:\n def __init__(self, node=None):\n self.head = node\n self.tail = node\n self.length = 1 if node is not None else 0\n\n def __len__(self):\n return self.length\n \n \"\"\"\n Wraps the given value in a ListNode and inserts it \n as the new head of the list. Don't forget to handle \n the old head node's previous pointer accordingly.\n \"\"\"\n def add_to_head(self, value):\n # probably need to add conditional logic for \n # when their is no head etc.\n new_node = ListNode(value, None, None)\n if self.tail == None and self.head == None:\n self.head = new_node\n self.tail = new_node\n self.length += 1\n elif self.head.next == None:\n old_head = self.head\n old_head.prev = new_node\n new_node.next = old_head\n self.head = new_node\n self.tail = old_head\n self.length += 1\n \n else: \n old_head = self.head\n old_head.prev = new_node\n new_node.next = old_head\n self.head = new_node\n self.length += 1\n\n\n \n \"\"\"\n Removes the List's current head node, making the\n current head's next node the new head of the List.\n Returns the value of the removed Node.\n \"\"\"\n def remove_from_head(self):\n if self.tail == None and self.head == None:\n return\n\n elif self.head.next == None:\n old_head = self.head\n self.head = None\n self.tail = None\n self.length = 0\n return old_head.value\n\n else:\n old_head = self.head\n self.head = old_head.prev\n # old_head = None\n self.length -= 1\n return old_head.value\n \n \"\"\"\n Wraps the given value in a ListNode and inserts it \n as the new tail of the list. Don't forget to handle \n the old tail node's next pointer accordingly.\n \"\"\"\n def add_to_tail(self, value):\n new_node = ListNode(value, None, None)\n if self.tail == None and self.head == None:\n # create the new head.\n self.head = new_node\n self.tail = new_node\n self.length += 1\n\n elif self.head.next == None:\n #add to the (head tail combonation) and set the new tail\n new_node.prev = self.head\n self.head.next = new_node\n self.tail = new_node\n self.length += 1\n\n else:\n old_tail = self.tail\n self.tail = new_node\n self.tail.prev = old_tail\n old_tail.next = new_node\n self.length += 1\n\n \n \n \"\"\"\n Removes the List's current tail node, making the \n current tail's previous node the new tail of the List.\n Returns the value of the removed Node.\n \"\"\"\n def remove_from_tail(self):\n # checks to see if it is the first element in the list\n if self.tail == None and self.head == None:\n return\n\n elif self.head.next == None:\n # case where there is only one element in the linked list\n old_head_tail = self.tail\n self.head = None\n self.tail = None\n self.length = 0\n return old_head_tail.value\n\n else:\n old_tail = self.tail\n self.tail = old_tail.prev\n self.length -= 1\n return old_tail.value\n \n \"\"\"\n Removes the input node from its current spot in the \n List and inserts it as the new head node of the List.\n \"\"\"\n def move_to_front(self, node):\n if self.tail == None and self.head == None:\n return\n \n elif self.head.next == None:\n return\n\n else:\n if self.tail == node:\n old_tail = self.tail\n self.tail = old_tail.prev\n old_head = self.head\n old_head.prev = old_tail\n self.head = old_tail\n old_tail.next = old_head\n old_tail.prev = None\n else: \n node.next = None\n node.prev = None\n old_head = self.head\n old_head.prev = node\n self.head = node\n node.next = old_head\n\n \n \"\"\"\n Removes the input node from its current spot in the \n List and inserts it as the new tail node of the List.\n \"\"\"\n def move_to_end(self, node):\n if self.tail == None and self.head == None:\n return\n \n elif self.head.next == None:\n return\n\n else:\n if self.head == node:\n old_head = self.head\n self.head = old_head.next\n old_tail = self.tail\n old_tail.next = old_head\n self.tail = old_head\n old_head.next = None\n old_head.prev = old_tail\n\n else:\n node.next = None\n node.prev = None\n old_tail = self.tail\n old_tail.next = node\n self.tail = node\n node.prev = old_tail\n \n\n \"\"\"\n Deletes the input node from the List, preserving the \n order of the other elements of the List.\n \"\"\"\n def delete(self, node):\n if self.tail == None and self.head == None:\n self.length = 0\n return None\n\n elif self.head.next == None:\n self.head = None\n self.tail = None\n self.length = 0\n return None\n\n elif self.head == node or self.tail == node:\n if self.head == node:\n old_head = self.head\n self.head = old_head.next\n self.length -= 1\n # old_head.next = None\n return old_head\n \n elif self.tail == node:\n old_tail = self.tail\n self.tail = old_tail.prev\n self.length -= 1\n return old_tail\n\n else:\n previous_node = node.prev\n next_node = node.next\n previous_node.next = next_node\n next_node.previous = previous_node\n self.length -= 1\n return node\n \"\"\"\n Finds and returns the maximum value of all the nodes \n in the List.\n \"\"\"\n def get_max(self):\n value = self.head.value\n current = self.head\n\n while current is not None:\n if current.value > value:\n value = current.value\n\n current = current.next\n return value\n \n","sub_path":"doubly_linked_list/doubly_linked_list.py","file_name":"doubly_linked_list.py","file_ext":"py","file_size_in_byte":7005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"386593026","text":"# MRO - Method Resolution Order\n\n# Inheritance\n# User\n# - Wizard\n# - Archer\n# - Swardsman\n\n# parent class or parent object\nclass User():\n def sign_in(self):\n print(\"User Signed In.\")\n\n# children classes or sub-classes or derived classes\n# child objects Inherits all the attributes and methods of the parent object\n\n# child object Wizard\nclass Wizard(User):\n def __init__(self, name, power):\n self._name = name\n self._power = power\n\n def attack(self):\n print(f'attacking with power of {self._power}')\n\n# child object Archer\nclass Archer(User):\n def __init__(self, name, num_arrows = 0):\n self._name = name\n self._num_arrows = num_arrows\n\n def attack(self):\n print(f'attacking with arrows: {self._num_arrows}')\n\n def run(self):\n print(f'ran really fast')\n\n# child object Swardsman\nclass Swardsman(User):\n def __init__(self, name, power):\n self._name = name\n self._power = power\n\n def attack(self):\n print(f'attacking with sward power of {self._power}')\n\n# child object Hybrid\nclass Hybrid(Wizard, Archer):\n def __init__(self, name, power, arrows):\n Wizard.__init__(self, name, power)\n Archer.__init__(self, name, arrows)\n \n def attack(self):\n Wizard.attack(self)\n Archer.attack(self)\n\n# Instantiating the wizard object\nwizard1 = Wizard('Merlin', 50)\n\n# Instantiating the archer object\narcher1 = Archer('Robin', 100)\n\n# Instantiating the swardsman object\nswardsman1 = Swardsman('Hercules', 80)\n\n# Instantiating the hybrid object\nhybridborg = Hybrid(\"Hyena\", 50, 50)\n\n# using method in wizard object inheritted from parent object\nwizard1.sign_in()\n\n# using method in archer object inheritted from parent object\narcher1.sign_in()\n\n# using method in swardsman object inheritted from parent object\nswardsman1.sign_in()\n\n# using method in hycrid object inheritted from User object\nhybridborg.sign_in()\n\n# using method of wizard object\nwizard1.attack()\n\n# using method of archer object\narcher1.attack()\n\n# using method of swardsman object\nswardsman1.attack()\n\n# check if an object is an instance of a class or of a sub-class\nprint(f'is wizard1 is an instance of Wizard? : {isinstance(wizard1, Wizard)}')\nprint(f'is archer1 is an instance of Archer? : {isinstance(archer1, Archer)}')\nprint(f'is swardsman1 is an instance of Swardsman? : {isinstance(swardsman1, Swardsman)}')\nprint(f'is archer1 is an instance of Wizard? : {isinstance(archer1, Wizard)}')\nprint(f'is wizard1 is an instance of User? : {isinstance(wizard1, User)}')\nprint(f'is archer1 is an instance of User? : {isinstance(archer1, User)}')\nprint(f'is swardsman1 is an instance of User? : {isinstance(swardsman1, User)}')\nprint(f'is hybridborg is an instance of User? : {isinstance(hybridborg, User)}')\nprint(f'is hybridborg is an instance of Wizard? : {isinstance(hybridborg, Wizard)}')\nprint(f'is hybridborg is an instance of Archer? : {isinstance(hybridborg, Archer)}')\nprint(f'is hybridborg is an instance of Swardsman? : {isinstance(hybridborg, Swardsman)}')\n\n# check if an object is an instance of a base class\nprint(f'is wizard1 is an instance of base class? : {isinstance(wizard1, object)}')\nprint(f'is archer1 is an instance of base class? : {isinstance(archer1, object)}')\nprint(f'is swardsman1 is an instance of base class? : {isinstance(swardsman1, object)}')\nprint(f'is hybridborg is an instance of base class? : {isinstance(hybridborg, object)}')\n\n# using method of archer with Hybrid object\nhybridborg.run()\nhybridborg.attack()\n\n# check MRO for Wizard Class\nprint(f'Wizard.mro(): {Wizard.mro()}')\n\n# check MRO for Archer Class\nprint(f'Archer.mro(): {Archer.mro()}')\n\n# check MRO for Swardsman Class\nprint(f'Swardsman.mro(): {Swardsman.mro()}')\n\n# check MRO for Hybrid Class\nprint(f'Hybrid.mro(): {Hybrid.mro()}')","sub_path":"Object Oriented Programming/Method_Resolution_Order.py","file_name":"Method_Resolution_Order.py","file_ext":"py","file_size_in_byte":3819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"593346228","text":"# -*- coding: utf-8 -*-\n# @Time : 19-4-9\n# @Author : hay\nfrom django_rq import job\nfrom core.redisHelper import RedisHelper\nfrom core.filehelper import FileBase\nfrom core.zipfileHelper import ZipFileHelper, os\nfrom core.excelHelper import ExcelEmail\nfrom clienteleOA.settings import UPLPAD_FILTER_EMAIL\n\nfileobj = FileBase()\nexcel = ExcelEmail()\n\n\n@job\ndef distinctEmail(key, params, files):\n DistinctEmail(key, params, files)\n\n\nclass DistinctEmail(RedisHelper):\n\n def __init__(self, key, params, files):\n self.key = key\n self.params = params\n self.files = files\n self.redisobj = RedisHelper()\n self.db6 = self.redisobj.selectDb(6)\n self.jobinfo = self.json_loads(self.db6.get(key))\n self.file_path = '{}/{}'.format(UPLPAD_FILTER_EMAIL, self.jobinfo.get('uuid'))\n\n self.run()\n\n def run(self):\n\n # 创建目录\n fileobj.mkdir(self.file_path)\n\n if self.jobinfo.get('lfile') and self.jobinfo.get('rfile'):\n # print(self.jobinfo)\n self.main(self.jobinfo)\n else:\n lfile = fileobj.save_file(self.files.get('lfile'), self.file_path)\n rfile = fileobj.save_file(self.files.get('rfile'), self.file_path)\n\n self.jobinfo.update({'lfile': lfile.get('file_save_path'), 'rfile': rfile.get('file_save_path')})\n\n self.db6.set(self.key, self.json_dumps(self.jobinfo))\n self.main(self.jobinfo)\n\n def main(self, jobinfo):\n\n # 创建目录\n lfile_path = '{}/lfile'.format(self.file_path)\n rfile_path = '{}/rfile'.format(self.file_path)\n zipfile = [\n {'extract_path': lfile_path, 'file_path': jobinfo.get('lfile')},\n {'extract_path': rfile_path, 'file_path': jobinfo.get('rfile')},\n ]\n\n # 解压1\n for f in zipfile:\n fileobj.mkdir(f.get('file_path'))\n zhelp = ZipFileHelper()\n zhelp.openFile(f.get('file_path'))\n zhelp.extractall(f.get('extract_path'))\n\n # 获取去重邮箱集合\n remail = []\n for root_path, dir_names, file_names in os.walk(rfile_path):\n for fn in file_names:\n path = os.path.join(root_path, fn)\n if os.path.exists(path):\n print('获取{}数据--'.format(fn))\n rm = excel.getExcelEmail(path)\n remail.extend(rm)\n\n # 获取保留的数据\n remail_set = set(remail)\n remail_dict = dict(zip(remail_set, remail_set))\n print('去重的邮箱共:{}'.format(len(remail_set)))\n after_file = []\n for root_path, dir_names, file_names in os.walk(lfile_path):\n for fn in file_names:\n path = os.path.join(root_path, fn)\n if os.path.exists(path):\n if 'after-' in path:\n continue\n rd = excel.getExcelFristSheetDatas(path)\n print('去重{}--{}'.format(fn, len(rd)))\n emaillist = self.distinctEmail(remail_dict, rd)\n filename = os.path.join(root_path, 'after-{}'.format(fn))\n print('生成文件{}'.format(fn))\n self.save_excel(emaillist, filename)\n after_file.append(filename)\n # print(rd)\n\n # 重新打包\n print('打包中---')\n zhelp = ZipFileHelper()\n output_path_name = zhelp.zip_files(after_file, self.jobinfo.get('uuid'), self.jobinfo.get('job_name'))\n\n # 更新\n self.jobinfo.update({'dow_full_path': output_path_name, 'job_status': 3})\n self.db6.set(self.key, self.json_dumps(self.jobinfo))\n print('done.')\n\n def distinctEmail(self, remail, rd):\n new_list = []\n for i, row in enumerate(rd):\n try:\n email = row[0].lower()\n except:\n continue\n if email not in remail:\n new_list.append(row)\n return new_list\n\n def save_excel(self, emaillist, savefile):\n wrok_xlxs = excel.create_xlsx(savefile)\n worksheet = wrok_xlxs.add_worksheet('Sheet1')\n for row, email in enumerate(emaillist):\n for i, v in enumerate(email):\n worksheet.write(row, i, v)\n\n worksheet.name = 'Sheet1 ({})'.format(len(emaillist))\n print('generate {} done.'.format(savefile))\n # self.detele_file(self.save_file_name)\n wrok_xlxs.close()","sub_path":"emails/rq/emailtools.py","file_name":"emailtools.py","file_ext":"py","file_size_in_byte":4513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"14343349","text":"\"\"\"Implement quick sort in Python.\nInput a list.\nOutput a sorted list.\"\"\"\n\ndef partition(array, low, high):\n\n i = low - 1 #index of smaller element\n pivot = array[high] #pivot element\n\n for j in range(low, high):\n\n if array[j] <= pivot: #if current element smaller or equal to pivot\n i = i + 1 #increment index of smaller element\n array[i], array[j] = array[j], array[i]\n\n array[i+1], array[high] = array[high], array[i+1]\n return i+1\n\n\ndef quickSort(array):\n quickSortHelper(array, 0, len(array)-1)\n return array\n\n\ndef quickSortHelper(array, low, high):\n\n if low < high:\n\n pi = partition(array, low, high) #partitioning index, array[p] is at right place\n #sort elements before and after parition\n quickSortHelper(array, low, pi-1)\n quickSortHelper(array, pi+1, high)\n\n\"Test cases\"\ntest = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]\ntest1 = [10, 7, 8, 9, 1, 5]\nprint(quickSort(test))","sub_path":"quickSort.py","file_name":"quickSort.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"159193705","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 23 16:19:15 2013\n\n\nStiff ODE Systems\n\n\n@author: jspineda\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\n\n\ndef set_grid(tmax,nzones):\n # set up the grid and return the\n # radius array and dr\n dt = tmax / nzones\n times = dt*np.arange(0,nzones)# in cm\n return (times,dt)\n\n\ndef stiff_ode(t,data):\n \"Stiff ODE from problem\"\n # y1 -> 0\n # y2 -> 1\n rhs = np.zeros(len(data))\n rhs[0] = -99*data[0]\n rhs[1] = 99*data[0] - data[1] \n return rhs\n\ndef eq_sol(t):\n \"analytic solution to problem\"\n y1 = np.exp(-99*t)\n y2 = -99*np.exp(-99*t)/98 + 99*np.exp(-t)/98.\n return (y1,y2)\n\n\ndef RK2(old_data,t,dt,func):\n \"RK2 integrator set up taking function handle as input, function should be vectorized RHS of ODE\"\n k1 = np.zeros(2)\n k2 = np.zeros(2)\n k1 = dt*func(t,old_data)\n k2 = dt*func(t+0.5*dt,old_data+0.5*k1)\n\n new_data = old_data + k2\n\n return new_data\n \n \ndef RK4(old_data,t,dt,func):\n \"RK4 integrator set up taking function handle as input, function should be vectorized RHS of ODE\"\n n = len(old_data)\n\n\n k1 = np.zeros(n)\n k2 = np.zeros(n)\n k3 = np.zeros(n)\n k1 = dt*func(t,old_data)\n k2 = dt*func(t+0.5*dt,old_data+ 0.5*k1)\n k3 = dt*func(t+0.5*dt,old_data+ 0.5*k2)\n k4 = dt*func(t+dt,old_data+ k3)\n\n new_data = old_data + (k1 + 2*k2 + 2*k3 + k4)/6.\n\n return new_data\n\n\ndef back_euler(old_data,t,dt,func):\n \"Back euler set up for stiff ode, problem specific\"\n new_data = np.zeros(len(old_data))\n new_data[0] = old_data[0]/(1 + 99*dt) \n new_data[1] = (old_data[1] + 99*dt*new_data[0])/(1. + dt)\n return new_data\n\n\ndef stiff_integrate(tmax,nzones,y_init,func):\n \"For carrying out numerical integration, func is handle for chosen integrator\"\n \n (times,dt)=set_grid(tmax,nzones)\n \n ys = np.zeros((nzones,2))\n\n ys[0,0] = y_init[0]\n ys[0,1] = y_init[1]\n\n \n for i in range(nzones-1):\n ys[i+1,:] = func(ys[i,:],times[i],dt,stiff_ode)\n\n \n return (ys,dt)\n\n\n\ndef quest(intname):\n \"Main Question b routine,intname is name of integration method\"\n #integrate from 0, 4\n initial = [1,0]\n tmax = 4.\n na = [80,100,160,200,225,256,320,640,1280]\n ys = []\n ts = []\n\n for i in range(len(na)):\n (yout,dt) = stiff_integrate(tmax,na[i],initial,intname)\n ys.append(yout)\n ts.append(dt*np.arange(0,na[i]))\n \n\n\n\n fig1 = plt.figure(1)\n plt.ylabel('Y1')\n plt.xlabel('t')\n plt.xlim([-.1,4.1])\n plt.ylim([-.1,1.1])\n #plt.xscale('log') \n for j in range(len(na)):\n plt.plot(ts[j],ys[j][:,0],label=\"Resolution: {0}\".format(tmax/na[j]),color='black')\n plt.plot(ts[-1],eq_sol(ts[-1])[0],label='Y1 - Solution',color='cyan')\n\n\n #plt.legend(loc='upper right')\n\n pp = PdfPages('ws6_probb_1.pdf')\n pp.savefig(fig1)\n pp.close() \n \n fig2 = plt.figure(2)\n plt.ylabel('Y2')\n plt.xlabel('t')\n plt.xlim([-.1,4.1])\n plt.ylim([-.1,1.1])\n #plt.xscale('log')\n #plt.yscale('log')\n for j in range(len(na)):\n plt.plot(ts[j],ys[j][:,1],label=\"Resolution: {0}\".format(tmax/na[j]),color='black')\n plt.plot(ts[-1],eq_sol(ts[-1])[1],label='Y2 - Solution',color='cyan')\n \n\n #plt.legend(loc='lower center')\n\n pp2 = PdfPages('ws6_probb_2.pdf')\n pp2.savefig(fig2)\n pp2.close() \n \n return (ts,ys)\n\n\n#fig2 = plt.figure(2)\n#plt.ylabel('Y2')\n#plt.xlabel('t')\n#plt.plot(out2[0][4],out2[1][4][:,1],color='blue',label='RK2')\n#plt.plot(out4[0][4],out4[1][4][:,1],color='orange',label='RK4')\n#plt.plot(back[0][4],back[1][4][:,1],color='red',label='Back Euler')\n#plt.plot(back[0][4],eq_sol(back[0][4])[1],label='Y2 - Solution',color='darkgreen')\n#plt.xlim([-.1,4.1])\n#plt.ylim([-.1,1.1])\n#plt.legend(loc='upper right')\n#pp2 = PdfPages('ws6_probb_4.pdf')\n#pp2.savefig(fig2)\n#pp2.close() \n","sub_path":"ws6_hw6/ws6_probb.py","file_name":"ws6_probb.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"275649117","text":"#!/usr/bin/python3\n\nimport requests\nimport json\nimport re\n\nRUSSIA_URL = \"http://covid19.bvn13.com/stats/all\"\nDatasetsDir = './Datasets/Russia'\nregions_filename = \"./russia-regions.json\"\n\nrussia_regions_mapping = None # I'll assign later.\nfileToHandlerMap = dict()\n\n\ndef getData():\n response = requests.get(RUSSIA_URL)\n jsonData = response.json()\n\n return jsonData\n\n\ndef mapRussianNameToEnglish(russinaName):\n for regionObject in russia_regions_mapping:\n if regionObject[\"Region\"] == russinaName:\n return regionObject[\"Region_eng\"]\n\n\ndef prepareRussiaRegions():\n global russia_regions_mapping\n with open(regions_filename) as regionsHandler:\n russia_regions_mapping = json.load(regionsHandler)\n\n\ndef replaceSpecialCharacters(filename):\n filename = re.sub(r'\\s+', ' ', filename)\n filename = filename.replace(' ', '-')\n filename = filename.replace('(', '')\n filename = filename.replace('.', '')\n filename = filename.replace(')', '')\n\n return filename\n\n\ndef prepareFileHandlers():\n headerLine = \"Day,Date,Confirmed,Recovered,Deaths\\n\"\n global russia_regions_mapping\n for regionObject in russia_regions_mapping:\n regionName = regionObject[\"Region_eng\"]\n filename = replaceSpecialCharacters(regionName)\n filename += \".csv\"\n fileHandler = open(DatasetsDir + '/' + filename, 'w')\n fileHandler.write(headerLine)\n fileToHandlerMap[regionName] = fileHandler\n\n\nprepareRussiaRegions()\nprepareFileHandlers()\n# print(russia_regions_mapping)\n\njsonData = getData()\nregionsInRussian = jsonData[\"regions\"]\nprogress = jsonData[\"progress\"]\n# print(regionsInRussian)\nday = 0\nstartDate = \"2020-05-05\"\nfoundStartDate = False\nprevDate = None\nfor dayObject in progress:\n datetime = dayObject[\"datetime\"]\n date = datetime.split(\"T\")[0]\n\n if prevDate != None and prevDate == date:\n continue\n prevDate = date\n\n if date == startDate:\n foundStartDate = True\n\n if not foundStartDate:\n continue\n\n # print(date)\n timeSeries = dayObject[\"stats\"]\n\n day += 1\n for regionObject in timeSeries:\n previousDay = regionObject[\"previous\"]\n russianRegion = regionObject[\"region\"]\n englishRegion = mapRussianNameToEnglish(russianRegion)\n if englishRegion == None:\n continue\n\n activeCases = regionObject[\"sick\"] + previousDay['sick']\n recoveredCases = regionObject[\"healed\"] + previousDay['healed']\n deaths = regionObject[\"died\"] + previousDay['died']\n # print(\"\\t\", russianRegion, englishRegion, activeCases, recoveredCases, deaths)\n fileHandler = fileToHandlerMap[englishRegion]\n thingsToBeWritten = [day, date, activeCases, recoveredCases, deaths]\n line = ', '.join(list(map(str, thingsToBeWritten)))\n fileHandler.write(line + '\\n')\n","sub_path":"World-Wide-Covid19/russia-pull.py","file_name":"russia-pull.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"517803720","text":"import numpy as np\nfrom model.StarModel import StarModel\n\ndef findBlackHole(number, coordenates):\n success = []\n cases = np.split(np.array(coordenates), number)\n for i, case in enumerate(cases):\n star_1 = StarModel(case[0], case[2])\n star_2 = StarModel(case[1], case[3])\n position_black_hole = star_1.get_line().intersection(star_2.get_line())[0]\n msg = \"Caso {0}#: ({1:.2f},{2:.2f})\".format(i+1, float(position_black_hole[0]), float(position_black_hole[1]))\n success.append(msg)\n return success","sub_path":"Challenge/src/service/BlackHoleService.py","file_name":"BlackHoleService.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"220335259","text":"#!/usr/bin/env python\n\nfrom collections import defaultdict, namedtuple, deque\nfrom itertools import product, repeat, permutations, chain, tee\nimport sys\nimport operator\n\n\n# Used similar to the built-in StopIteration.\nclass StOp99(Exception):\n pass\n\n\nclass Operand(object):\n def __init__(self, arg, mode):\n self.arg = arg\n self.mode = mode\n\n def __str__(self):\n prefixes = [\"$\", \"\", \"~\"]\n return f\"{prefixes[self.mode]}{self.arg}\"\n\n\nclass Computer(object):\n def __init__(self, mem, inp=None, name=None):\n \"\"\"A computer.\n\n mem should be a list representing memory (i.e. opcodes).\n inp should be an iterator returning ints.\n \"\"\"\n self.pc = 0\n self.relbase = 0\n # support virtual memory by the easiest means possible: just make\n # memory lookups in a hashtable defaulting to zero for unknown keys.\n # this should be pretty slow, but fast enough: part 2 takes less than\n # 2 seconds on my machine.\n self.mem = defaultdict(int, {ix: val for ix, val in enumerate(mem)})\n self.inp = inp if inp is not None else iter(())\n self.name = name if name is not None else \"\" # for debugging\n\n def run(self):\n \"\"\"Run the program, yielding the results of output instructions.\"\"\"\n while True:\n fullop = self.get()\n op, modes = parse_fullop(fullop)\n opers = [Operand(self.get(), mode) for mode in modes]\n try:\n result = self.exec_op(op, opers)\n if result is not None:\n yield result\n except StOp99:\n break\n\n def get(self):\n val = self.mem[self.pc]\n self.pc += 1\n return val\n\n def get_argval(self, oper):\n if oper.mode == 0:\n return self.mem[oper.arg]\n elif oper.mode == 1:\n return oper.arg\n elif oper.mode == 2:\n return self.mem[oper.arg + self.relbase]\n else:\n raise ValueError(f\"bad mode {oper.mode}\")\n\n def get_addr(self, oper):\n if oper.mode == 0:\n return oper.arg\n elif oper.mode == 1:\n raise ValueError(\"get_addr immediate mode\")\n elif oper.mode == 2:\n return oper.arg + self.relbase\n else:\n raise ValueError(f\"bad mode {oper.mode}\")\n\n def exec_binop(self, binop, operands):\n arg1 = self.get_argval(operands[0])\n arg2 = self.get_argval(operands[1])\n dst = self.get_addr(operands[2])\n self.mem[dst] = int(binop(arg1, arg2))\n\n def exec_op(self, op, opers):\n if op == 1:\n # add\n self.exec_binop(operator.add, opers)\n elif op == 2:\n # multiply\n self.exec_binop(operator.mul, opers)\n elif op == 3:\n # input\n val = next(self.inp)\n dst = self.get_addr(opers[0])\n self.mem[dst] = val\n elif op == 4:\n # output\n val = self.get_argval(opers[0])\n return val\n elif op == 5:\n # jump-if-true\n val = self.get_argval(opers[0])\n jmp_to = self.get_argval(opers[1])\n if val:\n self.pc = jmp_to\n elif op == 6:\n # jump-if-false\n val = self.get_argval(opers[0])\n jmp_to = self.get_argval(opers[1])\n if not val:\n self.pc = jmp_to\n elif op == 7:\n # less than\n self.exec_binop(operator.lt, opers)\n elif op == 8:\n # equals\n self.exec_binop(operator.eq, opers)\n elif op == 9:\n # adjust relative base\n val = self.get_argval(opers[0])\n self.relbase += val\n elif op == 99:\n raise StOp99()\n else:\n raise ValueError(f\"exec_op bad op {op}\")\n\n\ndef op_arglen(op):\n if op == 1:\n return 3\n elif op == 2:\n return 3\n elif op == 3:\n return 1\n elif op == 4:\n return 1\n elif op == 5:\n return 2\n elif op == 6:\n return 2\n elif op == 7:\n return 3\n elif op == 8:\n return 3\n elif op == 9:\n return 1\n elif op == 99:\n return 0\n else:\n return 0\n\n\ndef parse_fullop(fullop):\n op = fullop % 100\n fullop //= 100\n arglen = op_arglen(op)\n modes = []\n for _ in range(arglen):\n modes.append(fullop % 10)\n fullop //= 10\n return op, modes\n\n\n# For debugging purposes.\ndef op_to_str(op):\n if op == 1:\n return \"add\"\n elif op == 2:\n return \"mul\"\n elif op == 3:\n return \"inp\"\n elif op == 4:\n return \"out\"\n elif op == 5:\n return \"jt \"\n elif op == 6:\n return \"jf \"\n elif op == 7:\n return \"lt \"\n elif op == 8:\n return \"eq \"\n elif op == 9:\n return \"rel\"\n elif op == 99:\n return \"hlt\"\n else:\n return str(op)\n\n\ndef print_program(opcodes):\n opcodes = deque(opcodes)\n full_len = len(opcodes)\n while opcodes:\n offset = full_len - len(opcodes)\n fullop = opcodes.popleft()\n op, modes = parse_fullop(fullop)\n opers = [Operand(opcodes.popleft(), mode) for mode in modes]\n print(\n f\"{offset:>3}: {op_to_str(op)} \"\n + \" \".join(str(oper) for oper in opers)\n )\n\n\ndef part1(opcodes):\n com = Computer(opcodes, inp=iter([1]))\n return list(com.run())[-1]\n\n\ndef part2(opcodes):\n com = Computer(opcodes, inp=iter([2]))\n return list(com.run())[-1]\n\n\n# fmt: off\ndef test1():\n t1 = [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]\n com1 = Computer(t1)\n assert list(com1.run()) == t1\n\n t2 = [1102, 34915192, 34915192, 7, 4, 7, 99, 0]\n com2 = Computer(t2)\n out2 = list(com2.run())\n assert len(out2) == 1\n assert len(str(out2[0])) == 16\n\n t3 = [104, 1125899906842624, 99]\n com3 = Computer(t3)\n out3 = list(com3.run())\n assert len(out3) == 1\n assert out3[0] == t3[1]\n# fmt: on\n\n\nif __name__ == \"__main__\":\n test1()\n with open(sys.argv[1]) as f:\n contents = f.read()\n opcodes = [int(opcode) for opcode in contents.strip().split(\",\")]\n # print_program(opcodes)\n\n print(f\"part 1: {part1(opcodes)}\")\n print(f\"part 2: {part2(opcodes)}\")\n","sub_path":"aoc2019/day09.py","file_name":"day09.py","file_ext":"py","file_size_in_byte":6337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"86250182","text":"from difflib import SequenceMatcher\nimport serbian_stemmer as stemmer\nimport boto3\nfrom boto3.dynamodb.conditions import Attr\nfrom os import environ as env\nimport env_helper\n\n\ndef handle(event, context):\n env_helper.check_env(['FILTERED_ADVERTS_TABLE', 'SCRAPED_ADVERTS_TABLE'])\n dynamo_db = boto3.resource('dynamodb')\n scraped_adverts_table = dynamo_db.Table(env['SCRAPED_ADVERTS_TABLE'])\n filtered_adverts_table = dynamo_db.Table(env['FILTERED_ADVERTS_TABLE'])\n scraped_adverts = scraped_adverts_table.scan(FilterExpression=Attr('processed').eq(False))\n if scraped_adverts and 'Items' in scraped_adverts:\n filtered_items = get_all_filtered(filtered_adverts_table)\n for scraped_advert in scraped_adverts['Items']:\n process_scraped(scraped_advert, filtered_items)\n with filtered_adverts_table.batch_writer(overwrite_by_pkeys=['title_hash']) as batch:\n for item in filtered_items:\n batch.put_item(Item=item)\n with scraped_adverts_table.batch_writer(overwrite_by_pkeys=['title_hash']) as batch:\n for item in scraped_adverts['Items']:\n batch.put_item(Item=item)\n\n\ndef process_scraped(scraped_advert, filtered_adverts):\n scraped_advert['processed'] = True\n for filtered_advert in filtered_adverts:\n if similar(scraped_advert, filtered_advert):\n if scraped_advert['link'] == filtered_advert['link']:\n return\n if 'similar_adverts' not in filtered_advert:\n filtered_advert['similar_adverts'] = []\n add_to_similar = True\n for similar_advert in filtered_advert['similar_adverts']:\n if similar_advert['link'] == filtered_advert['link']:\n add_to_similar = False\n break\n if add_to_similar:\n filtered_advert['similar_adverts'].append({\n 'title': filtered_advert['title'],\n 'link': filtered_advert['link']})\n filtered_advert['title'] = scraped_advert['title']\n filtered_advert['link'] = scraped_advert['link']\n filtered_advert['timestamp'] = scraped_advert['timestamp']\n filtered_advert['area'] = scraped_advert['area']\n filtered_advert['price'] = scraped_advert['price']\n filtered_advert['text'] = scraped_advert['text']\n filtered_advert['advertiser'] = scraped_advert['advertiser']\n filtered_advert['metadata'] = scraped_advert['metadata']\n filtered_advert['images'] = scraped_advert['images']\n return\n filtered_adverts.append(scraped_advert)\n\n\ndef get_all_filtered(filtered_adverts_table):\n items = []\n res = filtered_adverts_table.scan()\n if 'Items' in res:\n items = res['Items']\n while 'LastEvaluatedKey' in res:\n res = filtered_adverts_table.scan(ExclusiveStartKey=res['LastEvaluatedKey'])\n items.extend(res['Items'])\n return items\n\n\ndef similar(a, b):\n if a['location'] == b['location'] and a['area'] == b['area'] and a['price'] == b['price']:\n print('{} is similar to {}, the location, area and price matches'.format(a['link'], b['link']))\n return True\n ratio = SequenceMatcher(None,\n stemmer.stem_str(a['text'].replace('.', '').replace(',', '').replace('!', '')).strip(),\n stemmer.stem_str(\n b['text'].replace('.', '').replace(',', '').replace('!', '')).strip()).ratio()\n if (0 <= abs(a['area'] - b['area']) < 5) and ratio >= 0.75:\n print('{} is similar to {}, area delta {}, similarity {}'.format(a['link'], b['link'],\n (abs(a['area'] - b['area'])), ratio))\n return True\n return False\n","sub_path":"aggregator/lambda_handler.py","file_name":"lambda_handler.py","file_ext":"py","file_size_in_byte":3852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"5272577","text":"\nclass Flight(TimeStampedModel, IndestructibleModel):\n\n \"\"\"\n A flight is a collection of :py:class:`~Advertisement` objects.\n\n Effectively a flight is a single \"ad buy\". So if an advertiser wants to\n buy $2000 worth of ads at $2 CPC and run 5 variations, they would have 5\n :py:class:`~Advertisement` objects in a single :py:class:`~Flight`.\n Flights are associated with a :py:class:`~Campaign` and so they have a\n single advertiser.\n\n At this level, we control:\n\n * Sold clicks (maximum clicks across all ads in this flight)\n * CPC/CPM which could be 0\n * Targeting parameters (programming language, geo, etc)\n * Start and end date (the end date is a soft target)\n * Whether the flight is live or not\n\n Since flights contain important historical data around tracking how we bill\n and report to customers, they cannot be deleted once created.\n \"\"\"\n\n HIGHEST_PRIORITY_MULTIPLIER = 1000000\n LOWEST_PRIORITY_MULTIPLIER = 1\n\n name = models.CharField(_(\"Name\"), max_length=200)\n slug = models.SlugField(_(\"Flight Slug\"), max_length=200, unique=True)\n start_date = models.DateField(\n _(\"Start Date\"),\n default=datetime.date.today,\n db_index=True,\n help_text=_(\"This ad will not be shown before this date\"),\n )\n end_date = models.DateField(\n _(\"End Date\"),\n default=default_flight_end_date,\n help_text=_(\"The target end date for the ad (it may go after this date)\"),\n )\n live = models.BooleanField(_(\"Live\"), default=False)\n priority_multiplier = models.IntegerField(\n _(\"Priority Multiplier\"),\n default=LOWEST_PRIORITY_MULTIPLIER,\n validators=[\n MinValueValidator(LOWEST_PRIORITY_MULTIPLIER),\n MaxValueValidator(HIGHEST_PRIORITY_MULTIPLIER),\n ],\n help_text=\"Multiplies chance of showing this flight's ads [{},{}]\".format(\n LOWEST_PRIORITY_MULTIPLIER, HIGHEST_PRIORITY_MULTIPLIER\n ),\n )\n\n # CPC\n cpc = models.DecimalField(\n _(\"Cost Per Click\"), max_digits=5, decimal_places=2, default=0\n )\n sold_clicks = models.PositiveIntegerField(_(\"Sold Clicks\"), default=0)\n\n # CPM\n cpm = models.DecimalField(\n _(\"Cost Per 1k Impressions\"), max_digits=5, decimal_places=2, default=0\n )\n sold_impressions = models.PositiveIntegerField(_(\"Sold Impressions\"), default=0)\n\n campaign = models.ForeignKey(\n Campaign, related_name=\"flights\", on_delete=models.PROTECT\n )\n\n targeting_parameters = JSONField(\n _(\"Targeting parameters\"),\n blank=True,\n null=True,\n validators=[TargetingParametersValidator()],\n )\n\n # Denormalized fields\n total_views = models.PositiveIntegerField(\n default=0, help_text=_(\"Views across all ads in this flight\")\n )\n total_clicks = models.PositiveIntegerField(\n default=0, help_text=_(\"Clicks across all ads in this flight\")\n )\n\n # Connect to Stripe invoice data\n # There can be multiple invoices for a flight\n # (say a 3 month flight billed monthly)\n # and an invoice can cover multiple flights\n invoices = models.ManyToManyField(\n djstripe_models.Invoice,\n verbose_name=_(\"Stripe invoices\"),\n blank=True,\n )\n\n history = HistoricalRecords()\n\n class Meta:\n ordering = (\"name\",)\n\n def __str__(self):\n \"\"\"Simple override.\"\"\"\n return self.name\n\n @property\n def included_countries(self):\n if not self.targeting_parameters:\n return []\n return self.targeting_parameters.get(\"include_countries\", [])\n\n @property\n def included_state_provinces(self):\n if not self.targeting_parameters:\n return []\n return self.targeting_parameters.get(\"include_state_provinces\", [])\n\n @property\n def included_metro_codes(self):\n if not self.targeting_parameters:\n return []\n return self.targeting_parameters.get(\"include_metro_codes\", [])\n\n @property\n def excluded_countries(self):\n if not self.targeting_parameters:\n return []\n return self.targeting_parameters.get(\"exclude_countries\", [])\n\n @property\n def included_keywords(self):\n if not self.targeting_parameters:\n return []\n return self.targeting_parameters.get(\"include_keywords\", [])\n\n @property\n def excluded_keywords(self):\n if not self.targeting_parameters:\n return []\n return self.targeting_parameters.get(\"exclude_keywords\", [])\n\n @property\n def state(self):\n today = get_ad_day().date()\n if self.live and self.start_date <= today:\n return FLIGHT_STATE_CURRENT\n if self.end_date > today:\n return FLIGHT_STATE_UPCOMING\n return FLIGHT_STATE_PAST\n\n def get_absolute_url(self):\n return reverse(\n \"flight_detail\",\n kwargs={\n \"advertiser_slug\": self.campaign.advertiser.slug,\n \"flight_slug\": self.slug,\n },\n )\n\n def get_include_countries_display(self):\n included_country_codes = self.included_countries\n return [COUNTRY_DICT.get(cc, \"Unknown\") for cc in included_country_codes]\n\n def get_exclude_countries_display(self):\n excluded_country_codes = self.excluded_countries\n return [COUNTRY_DICT.get(cc, \"Unknown\") for cc in excluded_country_codes]\n\n def show_to_geo(self, geo_data):\n \"\"\"\n Check if a flight is valid for a given country code.\n\n A ``country_code`` of ``None`` (meaning the user's country is unknown)\n will not match a flight with any ``include_countries`` but wont be\n excluded from any ``exclude_countries``\n \"\"\"\n if self.included_countries and geo_data.country not in self.included_countries:\n return False\n if (\n self.included_state_provinces\n and geo_data.region not in self.included_state_provinces\n ):\n return False\n if (\n self.included_metro_codes\n and geo_data.metro not in self.included_metro_codes\n ):\n return False\n if self.excluded_countries and geo_data.country in self.excluded_countries:\n return False\n\n return True\n\n def show_to_keywords(self, keywords):\n \"\"\"\n Check if a flight is valid for a given keywords.\n\n If *any* keywords match the included list, it should be shown.\n If *any* keywords are in the excluded list, it should not be shown.\n \"\"\"\n keyword_set = set(keywords)\n if self.included_keywords:\n # If no keywords from the page in the include list, don't show this flight\n if not keyword_set.intersection(self.included_keywords):\n return False\n\n if self.excluded_keywords:\n # If any keyworks from the page in the exclude list, don't show this flight\n if keyword_set.intersection(self.excluded_keywords):\n return False\n\n return True\n\n def show_to_mobile(self, is_mobile):\n \"\"\"Check if a flight is valid for this traffic based on mobile/non-mobile.\"\"\"\n if not self.targeting_parameters:\n return True\n\n mobile_traffic_targeting = self.targeting_parameters.get(\"mobile_traffic\")\n if mobile_traffic_targeting == \"exclude\" and is_mobile:\n return False\n if mobile_traffic_targeting == \"only\" and not is_mobile:\n return False\n\n return True\n\n def sold_days(self):\n # Add one to count both the start and end day\n return max(0, (self.end_date - self.start_date).days) + 1\n\n def days_remaining(self):\n \"\"\"Number of days left in a flight.\"\"\"\n return max(0, (self.end_date - get_ad_day().date()).days)\n\n def views_today(self):\n # Check for a cached value that would come from an annotated queryset\n if hasattr(self, \"flight_views_today\"):\n return self.flight_views_today or 0\n\n aggregation = AdImpression.objects.filter(\n advertisement__in=self.advertisements.all(), date=get_ad_day().date()\n ).aggregate(total_views=models.Sum(\"views\"))[\"total_views\"]\n\n # The aggregation can be `None` if there are no impressions\n return aggregation or 0\n\n def clicks_today(self):\n # Check for a cached value that would come from an annotated queryset\n if hasattr(self, \"flight_clicks_today\"):\n return self.flight_clicks_today or 0\n\n aggregation = AdImpression.objects.filter(\n advertisement__in=self.advertisements.all(), date=get_ad_day().date()\n ).aggregate(total_clicks=models.Sum(\"clicks\"))[\"total_clicks\"]\n\n # The aggregation can be `None` if there are no impressions\n return aggregation or 0\n\n def views_needed_today(self):\n if (\n not self.live\n or self.views_remaining() <= 0\n or self.start_date > get_ad_day().date()\n ):\n return 0\n\n if self.days_remaining() > 0:\n flight_remaining_percentage = self.days_remaining() / self.sold_days()\n\n # This is how many views should be remaining this far in the flight\n flight_views_pace = int(self.sold_impressions * flight_remaining_percentage)\n\n return max(0, self.views_remaining() - flight_views_pace)\n\n return self.views_remaining()\n\n def clicks_needed_today(self):\n \"\"\"Calculates clicks needed based on the impressions this flight's ads have.\"\"\"\n if (\n not self.live\n or self.clicks_remaining() <= 0\n or self.start_date > get_ad_day().date()\n ):\n return 0\n\n if self.days_remaining() > 0:\n flight_remaining_percentage = self.days_remaining() / self.sold_days()\n\n # This is how many clicks we should have remaining this far in the flight\n flight_clicks_pace = int(self.sold_clicks * flight_remaining_percentage)\n\n return max(0, self.clicks_remaining() - flight_clicks_pace)\n\n return self.clicks_remaining()\n\n def weighted_clicks_needed_today(self, publisher=None):\n \"\"\"\n Calculates clicks needed taking into account a flight's priority.\n\n For the purpose of clicks needed, 1000 impressions = 1 click (for CPM ads)\n Takes into account value of the flight,\n which causes higher paid and better CTR ads to be prioritized.\n Uses the passed publisher for a better CTR estimate if passed.\n \"\"\"\n impressions_needed = 0\n\n # This is naive but we are counting a click as being worth 1,000 views\n impressions_needed += math.ceil(self.views_needed_today() / 1000.0)\n impressions_needed += self.clicks_needed_today()\n\n if self.cpc:\n # Use the publisher CTR if available\n # Otherwise, use this flight's average CTR\n estimated_ctr = float(self.ctr())\n if publisher and publisher.sampled_ctr > 0.01:\n estimated_ctr = publisher.sampled_ctr\n\n # Note: CTR is in percent (eg. 0.1 means 0.1% not 0.001)\n estimated_ecpm = float(self.cpc) * estimated_ctr * 10\n else:\n # CPM ads\n estimated_ecpm = float(self.cpm)\n\n # This prioritizes an ad with estimated eCPM=$1 at the normal rate\n # An ad with estimated eCPM=$2 at 2x the normal rate, eCPM=$3 => 3x normal\n price_priority_value = estimated_ecpm\n\n # Keep values between 1-10 so we don't penalize the value for lower performance\n # but add value for higher performance without overweighting\n price_priority_value = max(float(price_priority_value), 1.0)\n price_priority_value = min(price_priority_value, 10.0)\n\n return int(impressions_needed * self.priority_multiplier * price_priority_value)\n\n def clicks_remaining(self):\n return max(0, self.sold_clicks - self.total_clicks)\n\n def views_remaining(self):\n return max(0, self.sold_impressions - self.total_views)\n\n def value_remaining(self):\n \"\"\"Value ($) remaining on this ad flight.\"\"\"\n value_clicks_remaining = float(self.clicks_remaining() * self.cpc)\n value_views_remaining = float(self.views_remaining() * self.cpm) / 1000.0\n return value_clicks_remaining + value_views_remaining\n\n def projected_total_value(self):\n \"\"\"Total value ($) assuming all sold impressions and clicks are delivered.\"\"\"\n projected_value_clicks = float(self.sold_clicks * self.cpc)\n projected_value_views = float(self.sold_impressions * self.cpm) / 1000.0\n return projected_value_clicks + projected_value_views\n\n def total_value(self):\n \"\"\"Total value ($) so far based on what's been delivered.\"\"\"\n value_clicks = float(self.total_clicks * self.cpc)\n value_views = float(self.total_views * self.cpm) / 1000.0\n return value_clicks + value_views\n\n def percent_complete(self):\n projected_total = self.projected_total_value()\n if projected_total > 0:\n return self.total_value() / projected_total * 100\n return 0\n\n def ctr(self):\n clicks = self.total_clicks\n views = self.total_views\n return calculate_ctr(clicks, views)\n\n @cached_property\n def active_invoices(self):\n \"\"\"Get invoices excluding drafts, void, and uncollectable ones.\"\"\"\n return self.invoices.filter(status__in=(InvoiceStatus.open, InvoiceStatus.paid))\n","sub_path":"ads/modelz/flight.py","file_name":"flight.py","file_ext":"py","file_size_in_byte":13558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"328031406","text":"\"\"\"\nMichael S. Emanuel\nSat Apr 21 22:49:56 2018\n\nCounting fractions in a range\nProblem 73\n\nConsider the fraction, n/d, where n and d are positive integers.\nIf n int:\n \"\"\"How many fractions with denominator <= qMax have alpha < f < beta?\"\"\"\n fracs: Set[Fraction] = set()\n for q in range_inc(2, qMax):\n # Candidate fractions\n cf = [Fraction(p, q) for p in range(1, q)]\n fracs.update(x for x in cf if alpha < x and x < beta)\n return len(fracs)\n\n\ndef countFracs(alpha: Fraction, beta: Fraction, qMax: int) -> int:\n \"\"\"How many fractions with denominator <= qMax have alpha < f < beta?\"\"\"\n # Do NOT carry around a big object in memory! Unnecessary and very slow.\n # Much more efficient to just count up the number of fractions.\n count: int = 0\n # Set dispay interval\n displayInt: int = 500\n for q in range_inc(2, qMax):\n if q % displayInt == 0:\n # found: int = len(fracs)\n print(f'Processing q = {q}; found {count} fractions.')\n # Fraction to right of alpha\n f0 = fracToRight(alpha, q)\n p0 = int(f0 * q)\n # Fraction to left of beta\n f1 = fracToLeft(beta, q)\n p1 = int(f1 * q)\n # Fractions to add range from p0 to p1 with shared denominator q\n # Only add fractions that are in lowest terms to avoid duplicates!\n count += sum(1 for p in range_inc(p0, p1) if gcd(p, q) == 1)\n return count\n\n\ndef main() -> int:\n # Fraction at the left and right ends of the range\n alpha: Fraction = Fraction(1, 3)\n beta: Fraction = Fraction(1, 2)\n # Maximum denominator\n qMax: int = 12000\n # Compute the answer\n ans: int = countFracs(alpha, beta, qMax)\n # Print the answer\n print(f'The answer is {ans}.')\n return ans\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob073_CountingFractionsInRange.py","file_name":"Prob073_CountingFractionsInRange.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"229745139","text":"# This code is part of Qiskit.\n#\n# (C) Copyright IBM 2022.\n#\n# This code is licensed under the Apache License, Version 2.0. You may\n# obtain a copy of this license in the LICENSE.txt file in the root directory\n# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.\n#\n# Any modifications or derivative works of this code must retain this\n# copyright notice, and modified files need to carry a notice indicating\n# that they have been altered from the originals.\n\"\"\"\nGradient of probabilities with parameter shift\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Sequence\n\nimport numpy as np\n\nfrom qiskit.algorithms import AlgorithmError\nfrom qiskit.circuit import Parameter, QuantumCircuit\nfrom qiskit.opflow import PauliSumOp\nfrom qiskit.primitives import BaseEstimator\nfrom qiskit.providers import Options\nfrom qiskit.quantum_info.operators.base_operator import BaseOperator\n\nfrom .base_estimator_gradient import BaseEstimatorGradient\nfrom .estimator_gradient_result import EstimatorGradientResult\nfrom .utils import _make_param_shift_parameter_values, _param_shift_preprocessing\n\n\nclass ParamShiftEstimatorGradient(BaseEstimatorGradient):\n \"\"\"\n Compute the gradients of the expectation values by the parameter shift rule [1].\n\n **Reference:**\n [1] Schuld, M., Bergholm, V., Gogolin, C., Izaac, J., and Killoran, N. Evaluating analytic\n gradients on quantum hardware, `DOI `_\n \"\"\"\n\n def __init__(self, estimator: BaseEstimator, options: Options | None = None):\n \"\"\"\n Args:\n estimator: The estimator used to compute the gradients.\n options: Primitive backend runtime options used for circuit execution.\n The order of priority is: options in ``run`` method > gradient's\n default options > primitive's default setting.\n Higher priority setting overrides lower priority setting\n \"\"\"\n self._gradient_circuits = {}\n super().__init__(estimator, options)\n\n def _run(\n self,\n circuits: Sequence[QuantumCircuit],\n observables: Sequence[BaseOperator | PauliSumOp],\n parameter_values: Sequence[Sequence[float]],\n parameters: Sequence[Sequence[Parameter] | None],\n **options,\n ) -> EstimatorGradientResult:\n \"\"\"Compute the estimator gradients on the given circuits.\"\"\"\n jobs, result_indices_all, coeffs_all, metadata_ = [], [], [], []\n for circuit, observable, parameter_values_, parameters_ in zip(\n circuits, observables, parameter_values, parameters\n ):\n # a set of parameters to be differentiated\n if parameters_ is None:\n param_set = set(circuit.parameters)\n else:\n param_set = set(parameters_)\n metadata_.append({\"parameters\": [p for p in circuit.parameters if p in param_set]})\n\n if self._gradient_circuits.get(id(circuit)):\n gradient_circuit, base_parameter_values_all = self._gradient_circuits[id(circuit)]\n else:\n gradient_circuit, base_parameter_values_all = _param_shift_preprocessing(circuit)\n self._gradient_circuits[id(circuit)] = (\n gradient_circuit,\n base_parameter_values_all,\n )\n\n (\n gradient_parameter_values_plus,\n gradient_parameter_values_minus,\n result_indices,\n coeffs,\n ) = _make_param_shift_parameter_values(\n gradient_circuit_data=gradient_circuit,\n base_parameter_values=base_parameter_values_all,\n parameter_values=parameter_values_,\n param_set=param_set,\n )\n n = 2 * len(gradient_parameter_values_plus)\n job = self._estimator.run(\n [gradient_circuit.gradient_circuit] * n,\n [observable] * n,\n gradient_parameter_values_plus + gradient_parameter_values_minus,\n **options,\n )\n jobs.append(job)\n result_indices_all.append(result_indices)\n coeffs_all.append(coeffs)\n\n # combine the results\n try:\n results = [job.result() for job in jobs]\n except Exception as exc:\n raise AlgorithmError(\"Estimator job failed.\") from exc\n\n gradients = []\n for i, result in enumerate(results):\n n = len(result.values) // 2 # is always a multiple of 2\n gradient_ = result.values[:n] - result.values[n:]\n values = np.zeros(len(metadata_[i][\"parameters\"]))\n for grad_, idx, coeff in zip(gradient_, result_indices_all[i], coeffs_all[i]):\n values[idx] += coeff * grad_\n gradients.append(values)\n\n opt = self._get_local_options(options)\n return EstimatorGradientResult(gradients=gradients, metadata=metadata_, options=opt)\n","sub_path":"qiskit/algorithms/gradients/param_shift_estimator_gradient.py","file_name":"param_shift_estimator_gradient.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"370665978","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport fauxfactory\nimport hashlib\nimport random\nimport re\nimport command\nfrom django.core.cache import cache\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.mail import send_mail\nfrom django.db import transaction\nfrom django.utils import timezone\nfrom celery import chain, chord, shared_task\nfrom celery.exceptions import MaxRetriesExceededError\nfrom datetime import timedelta\nfrom functools import wraps\nfrom novaclient.exceptions import OverLimit as OSOverLimit\n\nfrom appliances.models import (\n Provider, Group, Template, Appliance, AppliancePool, DelayedProvisionTask,\n MismatchVersionMailer, User)\nfrom sprout import settings, redis\nfrom sprout.log import create_logger\n\nfrom utils.appliance import Appliance as CFMEAppliance\nfrom utils.path import project_path\nfrom utils.providers import get_mgmt\nfrom utils.timeutil import parsetime\nfrom utils.trackerbot import api, parse_template\n\n\nLOCK_EXPIRE = 60 * 15 # 15 minutes\nVERSION_REGEXPS = [\n r\"^cfme-(\\d)(\\d)(\\d)(\\d)(\\d{2})\", # 1.2.3.4.11\n # newer format\n r\"cfme-(\\d)(\\d)(\\d)[.](\\d{2})-\", # cfme-524.02- -> 5.2.4.2\n r\"cfme-(\\d)(\\d)(\\d)[.](\\d{2})[.](\\d)-\", # cfme-524.02.1- -> 5.2.4.2.1\n # 4 digits\n r\"cfme-(\\d)(\\d)(\\d)(\\d)-\", # cfme-5242- -> 5.2.4.2\n r\"cfme-(\\d)(\\d)(\\d)-(\\d)-\", # cfme-520-1- -> 5.2.0.1\n # 5 digits (not very intelligent but no better solution so far)\n r\"cfme-(\\d)(\\d)(\\d)(\\d{2})-\", # cfme-53111- -> 5.3.1.11, cfme-53101 -> 5.3.1.1\n]\nVERSION_REGEXPS = map(re.compile, VERSION_REGEXPS)\n\n\ndef retrieve_cfme_appliance_version(template_name):\n \"\"\"If possible, retrieve the appliance's version from template's name.\"\"\"\n for regexp in VERSION_REGEXPS:\n match = regexp.search(template_name)\n if match is not None:\n return \".\".join(map(str, map(int, match.groups())))\n\n\ndef trackerbot():\n return api()\n\n\ndef none_dict(l):\n \"\"\"\"If the parameter passed is None, returns empty dict. Otherwise it passes through\"\"\"\n if l is None:\n return {}\n else:\n return l\n\n\ndef provider_error_logger():\n return create_logger(\"provider_errors\")\n\n\ndef logged_task(*args, **kwargs):\n kwargs[\"bind\"] = True\n\n def f(task):\n @wraps(task)\n def wrapped_task(self, *args, **kwargs):\n self.logger = create_logger(task)\n self.logger.info(\n \"Entering with arguments: {} / {}\".format(\", \".join(map(str, args)), str(kwargs)))\n try:\n return task(self, *args, **kwargs)\n finally:\n self.logger.info(\"Leaving\")\n return shared_task(*args, **kwargs)(wrapped_task)\n return f\n\n\ndef singleton_task(*args, **kwargs):\n kwargs[\"bind\"] = True\n\n def f(task):\n @wraps(task)\n def wrapped_task(self, *args, **kwargs):\n self.logger = create_logger(task)\n # Create hash of all args\n digest_base = \"/\".join(str(arg) for arg in args)\n keys = sorted(kwargs.keys())\n digest_base += \"//\" + \"/\".join(\"{}={}\".format(key, kwargs[key]) for key in keys)\n digest = hashlib.sha256(digest_base).hexdigest()\n lock_id = '{0}-lock-{1}'.format(self.name, digest)\n\n if cache.add(lock_id, 'true', LOCK_EXPIRE):\n self.logger.info(\n \"Entering with arguments: {} / {}\".format(\n \", \".join(map(str, args)), str(kwargs)))\n try:\n return task(self, *args, **kwargs)\n finally:\n cache.delete(lock_id)\n self.logger.info(\"Leaving\")\n else:\n self.logger.info(\"Already running, ignoring.\")\n\n return shared_task(*args, **kwargs)(wrapped_task)\n return f\n\n\n@singleton_task()\ndef kill_unused_appliances(self):\n \"\"\"This is the watchdog, that guards the appliances that were given to users. If you forget\n to prolong the lease time, this is the thing that will take the appliance off your hands\n and kill it.\"\"\"\n with transaction.atomic():\n for appliance in Appliance.objects.filter(marked_for_deletion=False, ready=True):\n if appliance.leased_until is not None and appliance.leased_until <= timezone.now():\n self.logger.info(\"Watchdog found an appliance that is to be deleted: {}/{}\".format(\n appliance.id, appliance.name))\n kill_appliance.delay(appliance.id)\n\n\n@singleton_task()\ndef kill_appliance(self, appliance_id, replace_in_pool=False, minutes=60):\n \"\"\"As-reliable-as-possible appliance deleter. Turns off, deletes the VM and deletes the object.\n\n If the appliance was assigned to pool and we want to replace it, redo the provisioning.\n \"\"\"\n self.logger.info(\"Initiated kill of appliance {}\".format(appliance_id))\n workflow = [\n disconnect_direct_lun.si(appliance_id),\n appliance_power_off.si(appliance_id),\n kill_appliance_delete.si(appliance_id),\n ]\n if replace_in_pool:\n appliance = Appliance.objects.get(id=appliance_id)\n if appliance.appliance_pool is not None:\n workflow.append(\n replace_clone_to_pool.si(\n appliance.template.version, appliance.template.date,\n appliance.appliance_pool.id, minutes, appliance.template.id))\n workflow = chain(*workflow)\n workflow()\n\n\n@singleton_task()\ndef kill_appliance_delete(self, appliance_id):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n if appliance.provider_api.does_vm_exist(appliance.name):\n appliance.set_status(\"Deleting the appliance from provider\")\n appliance.provider_api.delete_vm(appliance.name)\n appliance.delete()\n except ObjectDoesNotExist:\n # Appliance object already not there\n return\n except Exception as e:\n try:\n appliance.set_status(\"Could not delete appliance. Retrying.\")\n except UnboundLocalError:\n return # The appliance is not there any more\n self.retry(args=(appliance_id,), exc=e, countdown=10, max_retries=5)\n\n\n@singleton_task()\ndef poke_trackerbot(self):\n \"\"\"This beat-scheduled task periodically polls the trackerbot if there are any new templates.\n \"\"\"\n template_usability = []\n # Extract data from trackerbot\n objects = trackerbot().providertemplate().get(limit=10000)[\"objects\"]\n per_group = {}\n for obj in objects:\n if obj[\"template\"][\"group\"][\"name\"] not in per_group:\n per_group[obj[\"template\"][\"group\"][\"name\"]] = []\n\n per_group[obj[\"template\"][\"group\"][\"name\"]].append(obj)\n # Sort them using the build date\n for group in per_group.iterkeys():\n per_group[group] = sorted(\n per_group[group],\n reverse=True, key=lambda o: o[\"template\"][\"datestamp\"])\n objects = []\n # And interleave the the groups\n while any(per_group.values()):\n for key in per_group.iterkeys():\n if per_group[key]:\n objects.append(per_group[key].pop(0))\n for template in objects:\n template_usability.append(\n (\n template[\"provider\"][\"key\"],\n template[\"template\"][\"name\"],\n template[\"usable\"]\n )\n )\n if not template[\"usable\"]:\n continue\n group, create = Group.objects.get_or_create(id=template[\"template\"][\"group\"][\"name\"])\n # Check if the template is already obsolete\n if group.template_obsolete_days is not None:\n build_date = parsetime.from_iso_date(template[\"template\"][\"datestamp\"])\n if build_date <= (parsetime.today() - timedelta(days=group.template_obsolete_days)):\n # It is already obsolete, so ignore it\n continue\n provider, create = Provider.objects.get_or_create(id=template[\"provider\"][\"key\"])\n if not provider.working:\n continue\n if \"sprout\" not in provider.provider_data:\n continue\n if not provider.provider_data.get(\"use_for_sprout\", False):\n continue\n template_name = template[\"template\"][\"name\"]\n # Preconfigured one\n try:\n Template.objects.get(\n provider=provider, template_group=group, original_name=template_name,\n preconfigured=True)\n except ObjectDoesNotExist:\n if template_name in provider.templates:\n create_appliance_template.delay(provider.id, group.id, template_name)\n # Original one\n try:\n Template.objects.get(\n provider=provider, template_group=group, original_name=template_name,\n name=template_name, preconfigured=False)\n except ObjectDoesNotExist:\n if template_name in provider.templates:\n date = parse_template(template_name).datestamp\n if date is None:\n self.logger.warning(\n \"Ignoring template {} because it does not have a date!\".format(\n template_name))\n continue\n template_version = retrieve_cfme_appliance_version(template_name)\n with transaction.atomic():\n tpl = Template(\n provider=provider, template_group=group, original_name=template_name,\n name=template_name, preconfigured=False, date=date,\n version=template_version, ready=True, exists=True, usable=True)\n tpl.save()\n self.logger.info(\"Created a new template #{}\".format(tpl.id))\n # If any of the templates becomes unusable, let sprout know about it\n # Similarly if some of them becomes usable ...\n for provider_id, template_name, usability in template_usability:\n provider, create = Provider.objects.get_or_create(id=provider_id)\n with transaction.atomic():\n for template in Template.objects.filter(provider=provider, original_name=template_name):\n template.usable = usability\n template.save()\n # Kill all shepherd appliances if they were acidentally spun up\n if not usability:\n for appliance in Appliance.objects.filter(\n template=template, ready=True, marked_for_deletion=False,\n appliance_pool=None):\n Appliance.kill(appliance)\n\n\n@logged_task()\ndef create_appliance_template(self, provider_id, group_id, template_name):\n \"\"\"This task creates a template from a fresh CFME template. In case of fatal error during the\n operation, the template object is deleted to make sure the operation will be retried next time\n when poke_trackerbot runs.\"\"\"\n provider = Provider.objects.get(id=provider_id)\n provider.cleanup() # Precaution\n group = Group.objects.get(id=group_id)\n with transaction.atomic():\n # Limit the number of concurrent template configurations\n if provider.remaining_configuring_slots == 0:\n return False # It will be kicked again when trackerbot gets poked\n try:\n Template.objects.get(\n template_group=group, provider=provider, original_name=template_name,\n preconfigured=True)\n return False\n except ObjectDoesNotExist:\n pass\n # Fire off the template preparation\n date = parse_template(template_name).datestamp\n if not date:\n raise ValueError(\"Could not parse template name {} properly\".format(template_name))\n template_version = retrieve_cfme_appliance_version(template_name)\n new_template_name = settings.TEMPLATE_FORMAT.format(\n group=group.id, date=date.strftime(\"%y%m%d\"), rnd=fauxfactory.gen_alphanumeric(8))\n if provider.template_name_length is not None:\n allowed_length = provider.template_name_length\n # There is some limit\n if len(new_template_name) > allowed_length:\n # Cut it down\n randoms_length = len(new_template_name.rsplit(\"_\", 1)[-1])\n minimum_length = (len(new_template_name) - randoms_length) + 1 # One random must be\n if minimum_length <= allowed_length:\n # Just cut it\n new_template_name = new_template_name[:allowed_length]\n else:\n # Another solution\n new_template_name = settings.TEMPLATE_FORMAT.format(\n group=group.id[:2], date=date.strftime(\"%y%m%d\"), # Use only first 2 of grp\n rnd=fauxfactory.gen_alphanumeric(2)) # And just 2 chars random\n # TODO: If anything larger comes, do fix that!\n template = Template(\n provider=provider, template_group=group, name=new_template_name, date=date,\n version=template_version, original_name=template_name)\n template.save()\n workflow = chain(\n prepare_template_deploy.si(template.id),\n prepare_template_verify_version.si(template.id),\n prepare_template_configure.si(template.id),\n prepare_template_seal.si(template.id),\n prepare_template_poweroff.si(template.id),\n prepare_template_finish.si(template.id),\n )\n workflow.link_error(prepare_template_delete_on_error.si(template.id))\n workflow()\n\n\n@singleton_task()\ndef prepare_template_deploy(self, template_id):\n template = Template.objects.get(id=template_id)\n try:\n if not template.exists_in_provider:\n template.set_status(\"Deploying the template.\")\n provider_data = template.provider.provider_data\n kwargs = provider_data[\"sprout\"]\n kwargs[\"power_on\"] = True\n if \"allowed_datastores\" not in kwargs and \"allowed_datastores\" in provider_data:\n kwargs[\"allowed_datastores\"] = provider_data[\"allowed_datastores\"]\n self.logger.info(\"Deployment kwargs: {}\".format(repr(kwargs)))\n template.provider_api.deploy_template(\n template.original_name, vm_name=template.name, **kwargs)\n else:\n template.set_status(\"Waiting for deployment to be finished.\")\n template.provider_api.wait_vm_running(template.name)\n except Exception as e:\n template.set_status(\"Could not properly deploy the template. Retrying.\")\n self.retry(args=(template_id,), exc=e, countdown=10, max_retries=5)\n else:\n template.set_status(\"Template deployed.\")\n\n\n@singleton_task()\ndef prepare_template_verify_version(self, template_id):\n template = Template.objects.get(id=template_id)\n template.set_status(\"Verifying version.\")\n appliance = CFMEAppliance(template.provider_name, template.name)\n appliance.ipapp.wait_for_ssh()\n try:\n true_version = str(appliance.version).strip()\n except Exception as e:\n template.set_status(\"Some SSH error happened during appliance version check.\")\n self.retry(args=(template_id,), exc=e, countdown=20, max_retries=5)\n supposed_version = template.version if template.version is not None else \"master\"\n if true_version != supposed_version:\n # SPAM SPAM SPAM!\n with transaction.atomic():\n mismatch_in_db = MismatchVersionMailer.objects.filter(\n provider=template.provider,\n template_name=template.original_name,\n supposed_version=supposed_version,\n actual_version=true_version)\n if not mismatch_in_db:\n mismatch = MismatchVersionMailer(\n provider=template.provider,\n template_name=template.original_name,\n supposed_version=supposed_version,\n actual_version=true_version)\n mismatch.save()\n # Run the task to mail the problem\n mailer_version_mismatch.delay()\n raise Exception(\"Detected version mismatch!\")\n\n\n@singleton_task()\ndef prepare_template_configure(self, template_id):\n template = Template.objects.get(id=template_id)\n template.set_status(\"Customization started.\")\n appliance = CFMEAppliance(template.provider_name, template.name)\n try:\n appliance.configure(\n setup_fleece=False,\n log_callback=lambda s: template.set_status(\"Customization progress: {}\".format(s)))\n except Exception as e:\n template.set_status(\"Could not properly configure the CFME. Retrying.\")\n self.retry(args=(template_id,), exc=e, countdown=10, max_retries=5)\n else:\n template.set_status(\"Template configuration was done.\")\n\n\n@singleton_task()\ndef prepare_template_seal(self, template_id):\n template = Template.objects.get(id=template_id)\n template.set_status(\"Sealing template.\")\n try:\n with template.cfme.ipapp.ssh_client() as ssh:\n ssh.run_command(\"rm -rf /etc/ssh/ssh_host_*\")\n if ssh.run_command(\"grep '^HOSTNAME' /etc/sysconfig/network\").rc == 0:\n # Replace it\n ssh.run_command(\n \"sed -i -r -e 's/^HOSTNAME=.*$/HOSTNAME=localhost.localdomain/' \"\n \"/etc/sysconfig/network\")\n else:\n # Set it\n ssh.run_command(\"echo HOSTNAME=localhost.localdomain >> /etc/sysconfig/network\")\n ssh.run_command(\"sed -i -r -e '/^HWADDR/d' /etc/sysconfig/network-scripts/ifcfg-eth0\")\n ssh.run_command(\"sed -i -r -e '/^UUID/d' /etc/sysconfig/network-scripts/ifcfg-eth0\")\n ssh.run_command(\"rm -f /etc/udev/rules.d/70-*\")\n # Fix SELinux things\n ssh.run_command(\"restorecon -R /etc/sysconfig/network-scripts\")\n ssh.run_command(\"restorecon /etc/sysconfig/network\")\n except Exception as e:\n template.set_status(\"Could not seal the template. Retrying.\")\n self.retry(\n args=(template_id,), exc=e, countdown=10, max_retries=5)\n else:\n template.set_status(\"Template sealed.\")\n\n\n@singleton_task()\ndef prepare_template_poweroff(self, template_id):\n template = Template.objects.get(id=template_id)\n template.set_status(\"Powering off\")\n try:\n template.provider_api.stop_vm(template.name)\n template.provider_api.wait_vm_stopped(template.name)\n except Exception as e:\n template.set_status(\"Could not power off the appliance. Retrying.\")\n self.retry(args=(template_id,), exc=e, countdown=10, max_retries=5)\n else:\n template.set_status(\"Powered off.\")\n\n\n@singleton_task()\ndef prepare_template_finish(self, template_id):\n template = Template.objects.get(id=template_id)\n template.set_status(\"Finishing template creation.\")\n try:\n if template.temporary_name is None:\n tmp_name = \"templatize_{}\".format(fauxfactory.gen_alphanumeric(8))\n Template.objects.get(id=template_id).temporary_name = tmp_name\n else:\n tmp_name = template.temporary_name\n template.provider_api.mark_as_template(\n template.name, temporary_name=tmp_name, delete_on_error=False)\n with transaction.atomic():\n template = Template.objects.get(id=template_id)\n template.ready = True\n template.exists = True\n template.save()\n del template.temporary_name\n except Exception as e:\n template.set_status(\"Could not mark the appliance as template. Retrying.\")\n self.retry(args=(template_id,), exc=e, countdown=10, max_retries=5)\n else:\n template.set_status(\"Template preparation finished.\")\n\n\n@singleton_task()\ndef prepare_template_delete_on_error(self, template_id):\n try:\n template = Template.objects.get(id=template_id)\n except ObjectDoesNotExist:\n return True\n template.set_status(\"Template creation failed. Deleting it.\")\n try:\n if template.provider_api.does_vm_exist(template.name):\n template.provider_api.delete_vm(template.name)\n if template.provider_api.does_template_exist(template.name):\n template.provider_api.delete_template(template.name)\n if (template.temporary_name is not None and\n template.provider_api.does_template_exist(template.temporary_name)):\n template.provider_api.delete_template(template.temporary_name)\n template.delete()\n except Exception as e:\n self.retry(args=(template_id,), exc=e, countdown=10, max_retries=5)\n\n\n@logged_task()\ndef request_appliance_pool(self, appliance_pool_id, time_minutes):\n \"\"\"This task gives maximum possible amount of spinned-up appliances to the specified pool and\n then if there is need to spin up another appliances, it spins them up via clone_template_to_pool\n task.\"\"\"\n self.logger.info(\n \"Appliance pool {} requested for {} minutes.\".format(appliance_pool_id, time_minutes))\n pool = AppliancePool.objects.get(id=appliance_pool_id)\n n = Appliance.give_to_pool(pool)\n for i in range(pool.total_count - n):\n tpls = pool.possible_provisioning_templates\n if tpls:\n template_id = tpls[0].id\n clone_template_to_pool(template_id, pool.id, time_minutes)\n else:\n with transaction.atomic():\n task = DelayedProvisionTask(pool=pool, lease_time=time_minutes)\n task.save()\n apply_lease_times_after_pool_fulfilled.delay(appliance_pool_id, time_minutes)\n\n\n@singleton_task()\ndef apply_lease_times_after_pool_fulfilled(self, appliance_pool_id, time_minutes):\n pool = AppliancePool.objects.get(id=appliance_pool_id)\n if pool.fulfilled:\n for appliance in pool.appliances:\n apply_lease_times.delay(appliance.id, time_minutes)\n # TODO: Renaming disabled until orphaning and killing resolved\n # rename_appliances_for_pool.delay(pool.id)\n with transaction.atomic():\n pool.finished = True\n pool.save()\n else:\n # Look whether we can swap any provisioning appliance with some in shepherd\n unfinished = list(Appliance.objects.filter(appliance_pool=pool, ready=False).all())\n random.shuffle(unfinished)\n if len(unfinished) > 0:\n n = Appliance.give_to_pool(pool, len(unfinished))\n with transaction.atomic():\n for _ in range(n):\n appl = unfinished.pop()\n appl.appliance_pool = None\n appl.save()\n try:\n self.retry(args=(appliance_pool_id, time_minutes), countdown=30, max_retries=120)\n except MaxRetriesExceededError: # Bad luck, pool fulfillment failed. So destroy it.\n pool.logger.error(\"Waiting for fulfillment failed. Initiating the destruction process.\")\n pool.kill()\n\n\n@singleton_task()\ndef process_delayed_provision_tasks(self):\n \"\"\"This picks up the provisioning tasks that were delayed due to ocncurrency limit of provision.\n\n Goes one task by one and when some of them can be provisioned, it starts the provisioning and\n then deletes the task.\n \"\"\"\n for task in DelayedProvisionTask.objects.order_by(\"id\"):\n if task.pool.not_needed_anymore:\n task.delete()\n continue\n # Try retrieve from shepherd\n appliances_given = Appliance.give_to_pool(task.pool, 1)\n if appliances_given == 0:\n # No free appliance in shepherd, so do it on our own\n tpls = task.pool.possible_provisioning_templates\n if task.provider_to_avoid is not None:\n filtered_tpls = filter(lambda tpl: tpl.provider != task.provider_to_avoid, tpls)\n if filtered_tpls:\n # There are other providers to provision on, so try one of them\n tpls = filtered_tpls\n # If there is no other provider to provision on, we will use the original list.\n # This will cause additional rejects until the provider quota is met\n if tpls:\n clone_template_to_pool(tpls[0].id, task.pool.id, task.lease_time)\n task.delete()\n else:\n # Try freeing up some space in provider\n for provider in task.pool.possible_providers:\n appliances = provider.free_shepherd_appliances.exclude(\n **task.pool.appliance_filter_params)\n if appliances:\n Appliance.kill(random.choice(appliances))\n break # Just one\n else:\n # There was a free appliance in shepherd, so we took it and we don't need this task more\n task.delete()\n\n\n@logged_task()\ndef replace_clone_to_pool(\n self, version, date, appliance_pool_id, time_minutes, exclude_template_id):\n appliance_pool = AppliancePool.objects.get(id=appliance_pool_id)\n if appliance_pool.not_needed_anymore:\n return\n exclude_template = Template.objects.get(id=exclude_template_id)\n templates = Template.objects.filter(\n ready=True, exists=True, usable=True, template_group=appliance_pool.group, version=version,\n date=date).all()\n templates_excluded = filter(lambda tpl: tpl != exclude_template, templates)\n if templates_excluded:\n template = random.choice(templates_excluded)\n else:\n template = exclude_template # :( no other template to use\n clone_template_to_pool(template.id, appliance_pool_id, time_minutes)\n\n\ndef clone_template_to_pool(template_id, appliance_pool_id, time_minutes):\n template = Template.objects.get(id=template_id)\n new_appliance_name = settings.APPLIANCE_FORMAT.format(\n group=template.template_group.id,\n date=template.date.strftime(\"%y%m%d\"),\n rnd=fauxfactory.gen_alphanumeric(8))\n with transaction.atomic():\n pool = AppliancePool.objects.get(id=appliance_pool_id)\n if pool.not_needed_anymore:\n return\n # Apply also username\n new_appliance_name = \"{}_{}\".format(pool.owner.username, new_appliance_name)\n appliance = Appliance(template=template, name=new_appliance_name, appliance_pool=pool)\n appliance.save()\n # Set pool to these params to keep the appliances with same versions/dates\n pool.version = template.version\n pool.date = template.date\n pool.save()\n clone_template_to_appliance.delay(appliance.id, time_minutes, pool.yum_update)\n\n\n@logged_task()\ndef apply_lease_times(self, appliance_id, time_minutes):\n self.logger.info(\n \"Applying lease time {} minutes on appliance {}\".format(time_minutes, appliance_id))\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.datetime_leased = timezone.now()\n appliance.leased_until = appliance.datetime_leased + timedelta(minutes=time_minutes)\n appliance.save()\n\n\n@logged_task()\ndef clone_template(self, template_id):\n self.logger.info(\"Cloning template {}\".format(template_id))\n template = Template.objects.get(id=template_id)\n new_appliance_name = settings.APPLIANCE_FORMAT.format(\n group=template.template_group.id,\n date=template.date.strftime(\"%y%m%d\"),\n rnd=fauxfactory.gen_alphanumeric(8))\n appliance = Appliance(template=template, name=new_appliance_name)\n appliance.save()\n clone_template_to_appliance.delay(appliance.id)\n\n\n@singleton_task()\ndef clone_template_to_appliance(self, appliance_id, lease_time_minutes=None, yum_update=False):\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.set_status(\"Beginning deployment process\")\n tasks = [\n clone_template_to_appliance__clone_template.si(appliance_id, lease_time_minutes),\n clone_template_to_appliance__wait_present.si(appliance_id),\n appliance_power_on.si(appliance_id),\n ]\n if yum_update:\n tasks.append(appliance_yum_update.si(appliance_id))\n tasks.append(appliance_reboot.si(appliance_id, if_needs_restarting=True))\n if appliance.preconfigured:\n tasks.append(wait_appliance_ready.si(appliance_id))\n else:\n tasks.append(mark_appliance_ready.si(appliance_id))\n workflow = chain(*tasks)\n if Appliance.objects.get(id=appliance_id).appliance_pool is not None:\n # Case of the appliance pool\n if Appliance.objects.get(id=appliance_id).appliance_pool.not_needed_anymore:\n return\n workflow.link_error(\n kill_appliance.si(appliance_id, replace_in_pool=True, minutes=lease_time_minutes))\n else:\n # Case of shepherd\n workflow.link_error(kill_appliance.si(appliance_id))\n workflow()\n\n\n@singleton_task()\ndef clone_template_to_appliance__clone_template(self, appliance_id, lease_time_minutes):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n # source objects are not present, terminating the chain\n self.request.callbacks[:] = []\n return\n if appliance.appliance_pool is not None:\n if appliance.appliance_pool.not_needed_anymore:\n # Terminate task chain\n self.request.callbacks[:] = []\n kill_appliance.delay(appliance_id)\n return\n appliance.provider.cleanup()\n try:\n if not appliance.provider_api.does_vm_exist(appliance.name):\n appliance.set_status(\"Beginning template clone.\")\n provider_data = appliance.template.provider.provider_data\n kwargs = provider_data[\"sprout\"]\n kwargs[\"power_on\"] = False\n if \"allowed_datastores\" not in kwargs and \"allowed_datastores\" in provider_data:\n kwargs[\"allowed_datastores\"] = provider_data[\"allowed_datastores\"]\n self.logger.info(\"Deployment kwargs: {}\".format(repr(kwargs)))\n appliance.provider_api.deploy_template(\n appliance.template.name, vm_name=appliance.name,\n progress_callback=lambda progress: appliance.set_status(\n \"Deploy progress: {}\".format(progress)),\n **kwargs)\n except Exception as e:\n messages = {\"limit\", \"cannot add\", \"quota\"}\n if isinstance(e, OSOverLimit):\n appliance.set_status(\"Hit OpenStack provisioning quota, trying putting it aside ...\")\n elif any(message in str(e).lower() for message in messages):\n appliance.set_status(\"Provider has some troubles, putting it aside ... {}/{}\".format(\n type(e).__name__, str(e)\n ))\n provider_error_logger().exception(e)\n else:\n # Something got screwed really bad\n appliance.set_status(\"Error happened: {}({})\".format(type(e).__name__, str(e)))\n self.retry(args=(appliance_id, lease_time_minutes), exc=e, countdown=60, max_retries=5)\n\n # Ignore that and provision it somewhere else\n if appliance.appliance_pool:\n # We can put it aside for a while to wait for\n self.request.callbacks[:] = [] # Quit this chain\n pool = appliance.appliance_pool\n try:\n if appliance.provider_api.does_vm_exist(appliance.name):\n # Better to check it, you never know when does that fail\n appliance.provider_api.delete_vm(appliance.name)\n except:\n pass # Diaper here\n appliance.delete(do_not_touch_ap=True)\n with transaction.atomic():\n new_task = DelayedProvisionTask(\n pool=pool, lease_time=lease_time_minutes,\n provider_to_avoid=appliance.template.provider)\n new_task.save()\n return\n else:\n # We cannot put it aside, so just try that again\n self.retry(args=(appliance_id, lease_time_minutes), exc=e, countdown=60, max_retries=5)\n else:\n appliance.set_status(\"Template cloning finished.\")\n\n\n@singleton_task()\ndef clone_template_to_appliance__wait_present(self, appliance_id):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n # source objects are not present, terminating the chain\n self.request.callbacks[:] = []\n return\n if appliance.appliance_pool is not None:\n if appliance.appliance_pool.not_needed_anymore:\n # Terminate task chain\n self.request.callbacks[:] = []\n kill_appliance.delay(appliance_id)\n return\n try:\n appliance.set_status(\"Waiting for the appliance to become visible in provider.\")\n if not appliance.provider_api.does_vm_exist(appliance.name):\n self.retry(args=(appliance_id,), countdown=20, max_retries=30)\n except Exception as e:\n provider_error_logger().error(\"Exception {}: {}\".format(type(e).__name__, str(e)))\n self.retry(args=(appliance_id,), exc=e, countdown=20, max_retries=30)\n else:\n appliance.set_status(\"Template was successfully cloned.\")\n\n\n@singleton_task()\ndef mark_appliance_ready(self, appliance_id):\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.ready = True\n appliance.save()\n Appliance.objects.get(id=appliance_id).set_status(\"Appliance was marked as ready\")\n\n\n@singleton_task()\ndef appliance_power_on(self, appliance_id):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n # source objects are not present\n return\n try:\n if appliance.provider_api.is_vm_running(appliance.name):\n Appliance.objects.get(id=appliance_id).set_status(\"Appliance was powered on.\")\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.set_power_state(Appliance.Power.ON)\n appliance.save()\n return\n elif not appliance.provider_api.in_steady_state(appliance.name):\n appliance.set_status(\"Waiting for appliance to be steady (current state: {}).\".format(\n appliance.provider_api.vm_status(appliance.name)))\n self.retry(args=(appliance_id, ), countdown=20, max_retries=40)\n else:\n appliance.set_status(\"Powering on.\")\n appliance.provider_api.start_vm(appliance.name)\n self.retry(args=(appliance_id, ), countdown=20, max_retries=40)\n except Exception as e:\n provider_error_logger().error(\"Exception {}: {}\".format(type(e).__name__, str(e)))\n self.retry(args=(appliance_id, ), exc=e, countdown=20, max_retries=30)\n\n\n@singleton_task()\ndef appliance_reboot(self, appliance_id, if_needs_restarting=False):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n # source objects are not present\n return\n try:\n if if_needs_restarting:\n with appliance.ssh as ssh:\n if int(ssh.run_command(\"needs-restarting | wc -l\").output.strip()) == 0:\n return # No reboot needed\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.set_power_state(Appliance.Power.REBOOTING)\n appliance.ready = False\n appliance.save()\n appliance.ipapp.reboot(wait_for_web_ui=False, log_callback=appliance.set_status)\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.set_power_state(Appliance.Power.ON)\n appliance.save()\n except Exception as e:\n provider_error_logger().error(\"Exception {}: {}\".format(type(e).__name__, str(e)))\n self.retry(args=(appliance_id, ), exc=e, countdown=20, max_retries=30)\n\n\n@singleton_task()\ndef appliance_power_off(self, appliance_id):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n # source objects are not present\n return\n try:\n if appliance.provider_api.is_vm_stopped(appliance.name):\n Appliance.objects.get(id=appliance_id).set_status(\"Appliance was powered off.\")\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.set_power_state(Appliance.Power.OFF)\n appliance.ready = False\n appliance.save()\n return\n elif appliance.provider_api.is_vm_suspended(appliance.name):\n appliance.set_status(\"Starting appliance from suspended state to properly off it.\")\n appliance.provider_api.start_vm(appliance.name)\n self.retry(args=(appliance_id,), countdown=20, max_retries=40)\n elif not appliance.provider_api.in_steady_state(appliance.name):\n appliance.set_status(\"Waiting for appliance to be steady (current state: {}).\".format(\n appliance.provider_api.vm_status(appliance.name)))\n self.retry(args=(appliance_id,), countdown=20, max_retries=40)\n else:\n appliance.set_status(\"Powering off.\")\n appliance.provider_api.stop_vm(appliance.name)\n self.retry(args=(appliance_id,), countdown=20, max_retries=40)\n except Exception as e:\n provider_error_logger().error(\"Exception {}: {}\".format(type(e).__name__, str(e)))\n self.retry(args=(appliance_id,), exc=e, countdown=20, max_retries=40)\n\n\n@singleton_task()\ndef appliance_suspend(self, appliance_id):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n # source objects are not present\n return\n try:\n if appliance.provider_api.is_vm_suspended(appliance.name):\n Appliance.objects.get(id=appliance_id).set_status(\"Appliance was suspended.\")\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.set_power_state(Appliance.Power.SUSPENDED)\n appliance.ready = False\n appliance.save()\n return\n elif not appliance.provider_api.in_steady_state(appliance.name):\n appliance.set_status(\"Waiting for appliance to be steady (current state: {}).\".format(\n appliance.provider_api.vm_status(appliance.name)))\n self.retry(args=(appliance_id,), countdown=20, max_retries=30)\n else:\n appliance.set_status(\"Suspending.\")\n appliance.provider_api.suspend_vm(appliance.name)\n self.retry(args=(appliance_id,), countdown=20, max_retries=30)\n except Exception as e:\n provider_error_logger().error(\"Exception {}: {}\".format(type(e).__name__, str(e)))\n self.retry(args=(appliance_id,), exc=e, countdown=20, max_retries=30)\n\n\n@singleton_task()\ndef retrieve_appliance_ip(self, appliance_id):\n \"\"\"Updates appliance's IP address.\"\"\"\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.set_status(\"Retrieving IP address.\")\n ip_address = appliance.provider_api.current_ip_address(appliance.name)\n if ip_address is None:\n self.retry(args=(appliance_id,), countdown=30, max_retries=20)\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.ip_address = ip_address\n appliance.save()\n except ObjectDoesNotExist:\n # source object is not present, terminating\n return\n else:\n appliance.set_status(\"IP address retrieved.\")\n\n\n@singleton_task()\ndef refresh_appliances(self):\n \"\"\"Dispatches the appliance refresh process among the providers\"\"\"\n self.logger.info(\"Initiating regular appliance provider refresh\")\n for provider in Provider.objects.all():\n refresh_appliances_provider.delay(provider.id)\n\n\n@singleton_task(soft_time_limit=180)\ndef refresh_appliances_provider(self, provider_id):\n \"\"\"Downloads the list of VMs from the provider, then matches them by name or UUID with\n appliances stored in database.\n \"\"\"\n self.logger.info(\"Refreshing appliances in {}\".format(provider_id))\n provider = Provider.objects.get(id=provider_id)\n vms = provider.api.all_vms()\n dict_vms = {}\n uuid_vms = {}\n for vm in vms:\n dict_vms[vm.name] = vm\n if vm.uuid:\n uuid_vms[vm.uuid] = vm\n for appliance in Appliance.objects.filter(template__provider=provider):\n if appliance.uuid is not None and appliance.uuid in uuid_vms:\n vm = uuid_vms[appliance.uuid]\n # Using the UUID and change the name if it changed\n appliance.name = vm.name\n appliance.ip_address = vm.ip\n appliance.set_power_state(Appliance.POWER_STATES_MAPPING.get(\n vm.power_state, Appliance.Power.UNKNOWN))\n appliance.save()\n elif appliance.name in dict_vms:\n vm = dict_vms[appliance.name]\n # Using the name, and then retrieve uuid\n appliance.uuid = vm.uuid\n appliance.ip_address = vm.ip\n appliance.set_power_state(Appliance.POWER_STATES_MAPPING.get(\n vm.power_state, Appliance.Power.UNKNOWN))\n appliance.save()\n self.logger.info(\"Retrieved UUID for appliance {}/{}: {}\".format(\n appliance.id, appliance.name, appliance.uuid))\n else:\n # Orphaned :(\n appliance.set_power_state(Appliance.Power.ORPHANED)\n appliance.save()\n\n\n@singleton_task()\ndef check_templates(self):\n self.logger.info(\"Initiated a periodic template check\")\n for provider in Provider.objects.all():\n check_templates_in_provider.delay(provider.id)\n\n\n@singleton_task(soft_time_limit=180)\ndef check_templates_in_provider(self, provider_id):\n self.logger.info(\"Initiated a periodic template check for {}\".format(provider_id))\n provider = Provider.objects.get(id=provider_id)\n # Get templates and update metadata\n try:\n templates = map(str, provider.api.list_template())\n except:\n provider.working = False\n provider.save()\n else:\n provider.working = True\n provider.save()\n with provider.edit_metadata as metadata:\n metadata[\"templates\"] = templates\n if not provider.working:\n return\n # Check Sprout template existence\n # expiration_time = (timezone.now() - timedelta(**settings.BROKEN_APPLIANCE_GRACE_TIME))\n for template in Template.objects.filter(provider=provider):\n with transaction.atomic():\n tpl = Template.objects.get(pk=template.pk)\n exists = tpl.name in templates\n tpl.exists = exists\n tpl.save()\n # if not exists:\n # if len(Appliance.objects.filter(template=template).all()) == 0\\\n # and template.status_changed < expiration_time:\n # # No other appliance is made from this template so no need to keep it\n # with transaction.atomic():\n # tpl = Template.objects.get(pk=template.pk)\n # tpl.delete()\n\n\n@singleton_task()\ndef delete_nonexistent_appliances(self):\n \"\"\"Goes through orphaned appliances' objects and deletes them from the database.\"\"\"\n expiration_time = (timezone.now() - timedelta(**settings.ORPHANED_APPLIANCE_GRACE_TIME))\n for appliance in Appliance.objects.filter(ready=True).all():\n if appliance.name in redis.renaming_appliances:\n continue\n if appliance.power_state == Appliance.Power.ORPHANED:\n if appliance.power_state_changed > expiration_time:\n # Ignore it for now\n continue\n self.logger.info(\n \"I will delete orphaned appliance {}/{}\".format(appliance.id, appliance.name))\n try:\n appliance.delete()\n except ObjectDoesNotExist as e:\n if \"AppliancePool\" in str(e):\n # Someone managed to delete the appliance pool before\n appliance.appliance_pool = None\n appliance.save()\n appliance.delete()\n else:\n raise # No diaper pattern here!\n # If something happened to the appliance provisioning process, just delete it to remove\n # the garbage. It will be respinned again by shepherd.\n # Grace time is specified in BROKEN_APPLIANCE_GRACE_TIME\n expiration_time = (timezone.now() - timedelta(**settings.BROKEN_APPLIANCE_GRACE_TIME))\n for appliance in Appliance.objects.filter(ready=False, marked_for_deletion=False).all():\n if appliance.status_changed < expiration_time:\n self.logger.info(\"Killing broken appliance {}/{}\".format(appliance.id, appliance.name))\n Appliance.kill(appliance) # Use kill because the appliance may still exist\n # And now - if something happened during appliance deletion, call kill again\n for appliance in Appliance.objects.filter(\n marked_for_deletion=True, status_changed__lt=expiration_time).all():\n with transaction.atomic():\n appl = Appliance.objects.get(pk=appliance.pk)\n appl.marked_for_deletion = False\n appl.save()\n self.logger.info(\n \"Trying to kill unkilled appliance {}/{}\".format(appliance.id, appliance.name))\n Appliance.kill(appl)\n\n\ndef generic_shepherd(self, preconfigured):\n \"\"\"This task takes care of having the required templates spinned into required number of\n appliances. For each template group, it keeps the last template's appliances spinned up in\n required quantity. If new template comes out of the door, it automatically kills the older\n running template's appliances and spins up new ones. Sorts the groups by the fulfillment.\"\"\"\n for grp in sorted(\n Group.objects.all(), key=lambda g: g.get_fulfillment_percentage(preconfigured)):\n group_versions = Template.get_versions(\n template_group=grp, ready=True, usable=True, preconfigured=preconfigured)\n group_dates = Template.get_dates(\n template_group=grp, ready=True, usable=True, preconfigured=preconfigured)\n if group_versions:\n # Downstream - by version (downstream releases)\n version = group_versions[0]\n # Find the latest date (one version can have new build)\n dates = Template.get_dates(\n template_group=grp, ready=True, usable=True, version=group_versions[0],\n preconfigured=preconfigured)\n if not dates:\n # No template yet?\n continue\n date = dates[0]\n filter_keep = {\"version\": version, \"date\": date}\n filters_kill = []\n for kill_date in dates[1:]:\n filters_kill.append({\"version\": version, \"date\": kill_date})\n for kill_version in group_versions[1:]:\n filters_kill.append({\"version\": kill_version})\n elif group_dates:\n # Upstream - by date (upstream nightlies)\n filter_keep = {\"date\": group_dates[0]}\n filters_kill = [{\"date\": v} for v in group_dates[1:]]\n else:\n continue # Ignore this group, no templates detected yet\n\n # Keeping current appliances\n # Retrieve list of all templates for given group\n # I know joins might be a bit better solution but I'll leave that for later.\n possible_templates = list(\n Template.objects.filter(\n usable=True, ready=True, template_group=grp, preconfigured=preconfigured,\n **filter_keep).all())\n # If it can be deployed, it must exist\n possible_templates_for_provision = filter(lambda tpl: tpl.exists, possible_templates)\n appliances = []\n for template in possible_templates:\n appliances.extend(\n Appliance.objects.filter(\n template=template, appliance_pool=None, marked_for_deletion=False))\n # If we then want to delete some templates, better kill the eldest. status_changed\n # says which one was provisioned when, because nothing else then touches that field.\n appliances.sort(key=lambda appliance: appliance.status_changed)\n pool_size = grp.template_pool_size if preconfigured else grp.unconfigured_template_pool_size\n if len(appliances) < pool_size and possible_templates_for_provision:\n # There must be some templates in order to run the provisioning\n # Provision ONE appliance at time for each group, that way it is possible to maintain\n # reasonable balancing\n new_appliance_name = settings.APPLIANCE_FORMAT.format(\n group=template.template_group.id,\n date=template.date.strftime(\"%y%m%d\"),\n rnd=fauxfactory.gen_alphanumeric(8))\n with transaction.atomic():\n # Now look for templates that are on non-busy providers\n tpl_free = filter(\n lambda t: t.provider.free,\n possible_templates_for_provision)\n if tpl_free:\n appliance = Appliance(\n template=sorted(tpl_free, key=lambda t: t.provider.appliance_load)[0],\n name=new_appliance_name)\n appliance.save()\n if tpl_free:\n self.logger.info(\n \"Adding an appliance to shepherd: {}/{}\".format(appliance.id, appliance.name))\n clone_template_to_appliance.delay(appliance.id, None)\n elif len(appliances) > pool_size:\n # Too many appliances, kill the surplus\n for appliance in appliances[:len(appliances) - pool_size]:\n self.logger.info(\"Killing an extra appliance {}/{} in shepherd\".format(\n appliance.id, appliance.name))\n Appliance.kill(appliance)\n\n # Killing old appliances\n for filter_kill in filters_kill:\n for template in Template.objects.filter(\n ready=True, usable=True, template_group=grp, preconfigured=preconfigured,\n **filter_kill):\n for a in Appliance.objects.filter(\n template=template, appliance_pool=None, marked_for_deletion=False):\n self.logger.info(\n \"Killing appliance {}/{} in shepherd because it is obsolete now\".format(\n a.id, a.name))\n Appliance.kill(a)\n\n\n@singleton_task()\ndef free_appliance_shepherd(self):\n generic_shepherd(self, True)\n generic_shepherd(self, False)\n\n\n@singleton_task()\ndef wait_appliance_ready(self, appliance_id):\n \"\"\"This task checks for appliance's readiness for use. The checking loop is designed as retrying\n the task to free up the queue.\"\"\"\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n if appliance.appliance_pool is not None:\n if appliance.appliance_pool.not_needed_anymore:\n # Terminate task chain\n self.request.callbacks[:] = []\n kill_appliance.delay(appliance_id)\n return\n if appliance.power_state == Appliance.Power.UNKNOWN or appliance.ip_address is None:\n self.retry(args=(appliance_id,), countdown=30, max_retries=45)\n if Appliance.objects.get(id=appliance_id).cfme.ipapp.is_web_ui_running():\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.ready = True\n appliance.save()\n appliance.set_status(\"The appliance is ready.\")\n else:\n with transaction.atomic():\n appliance = Appliance.objects.get(id=appliance_id)\n appliance.ready = False\n appliance.save()\n appliance.set_status(\"Waiting for UI to appear.\")\n self.retry(args=(appliance_id,), countdown=30, max_retries=45)\n except ObjectDoesNotExist:\n # source object is not present, terminating\n return\n\n\n@singleton_task()\ndef anyvm_power_on(self, provider, vm):\n provider = get_mgmt(provider)\n provider.start_vm(vm)\n\n\n@singleton_task()\ndef anyvm_power_off(self, provider, vm):\n provider = get_mgmt(provider)\n provider.stop_vm(vm)\n\n\n@singleton_task()\ndef anyvm_suspend(self, provider, vm):\n provider = get_mgmt(provider)\n provider.suspend_vm(vm)\n\n\n@singleton_task()\ndef anyvm_delete(self, provider, vm):\n provider = get_mgmt(provider)\n provider.delete_vm(vm)\n\n\n@singleton_task()\ndef delete_template_from_provider(self, template_id):\n template = Template.objects.get(id=template_id)\n template.provider_api.delete_template(template.name)\n with transaction.atomic():\n template = Template.objects.get(pk=template.pk)\n template.exists = False\n template.save()\n\n\n@singleton_task()\ndef appliance_rename(self, appliance_id, new_name):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n return None\n if appliance.name == new_name:\n return None\n with redis.appliances_ignored_when_renaming(appliance.name, new_name):\n self.logger.info(\"Renaming {}/{} to {}\".format(appliance_id, appliance.name, new_name))\n appliance.name = appliance.provider_api.rename_vm(appliance.name, new_name)\n appliance.save()\n return appliance.name\n\n\n@singleton_task()\ndef rename_appliances_for_pool(self, pool_id):\n with transaction.atomic():\n try:\n appliance_pool = AppliancePool.objects.get(id=pool_id)\n except ObjectDoesNotExist:\n return\n appliances = [\n appliance\n for appliance\n in appliance_pool.appliances\n if appliance.provider_api.can_rename\n ]\n for appliance in appliances:\n new_name = \"{}-{}-{}\".format(\n appliance_pool.owner.username,\n appliance_pool.group.id,\n appliance.template.date.strftime(\"%y%m%d\")\n )\n if appliance.template.version:\n new_name += \"-{}\".format(appliance.template.version)\n new_name += \"-{}\".format(fauxfactory.gen_alphanumeric(length=4))\n appliance_rename.apply_async(\n countdown=10, # To prevent clogging with the transaction.atomic\n args=(appliance.id, new_name))\n\n\n@singleton_task(soft_time_limit=60)\ndef check_update(self):\n sprout_sh = project_path.join(\"sprout\").join(\"sprout.sh\")\n try:\n result = command.run([sprout_sh.strpath, \"check-update\"])\n except command.CommandException as e:\n result = e\n needs_update = result.output.strip().lower() != \"up-to-date\"\n redis.set(\"sprout-needs-update\", needs_update)\n\n\n@singleton_task()\ndef scavenge_managed_providers(self):\n chord_tasks = []\n for appliance in Appliance.objects.exclude(appliance_pool=None):\n chord_tasks.append(scavenge_managed_providers_from_appliance.si(appliance.id))\n chord(chord_tasks)(calculate_provider_management_usage.s())\n\n\n@singleton_task(soft_time_limit=180)\ndef scavenge_managed_providers_from_appliance(self, appliance_id):\n try:\n appliance = Appliance.objects.get(id=appliance_id)\n except ObjectDoesNotExist:\n return None\n try:\n managed_providers = appliance.ipapp.managed_providers\n appliance.managed_providers = managed_providers\n except Exception as e:\n # To prevent single appliance messing up whole result\n provider_error_logger().error(\"{}: {}\".format(type(e).__name__, str(e)))\n return None\n return appliance.id\n\n\n@singleton_task()\ndef calculate_provider_management_usage(self, appliance_ids):\n results = {}\n for appliance_id in filter(lambda id: id is not None, appliance_ids):\n appliance = Appliance.objects.get(id=appliance_id)\n for provider in appliance.managed_providers:\n if provider not in results:\n results[provider] = []\n results[provider].append(appliance.id)\n for provider in Provider.objects.all():\n provider.appliances_manage_this_provider = results.get(provider.id, [])\n\n\n@singleton_task()\ndef mailer_version_mismatch(self):\n \"\"\"This is usually called per-mismatch, but as the mismatches are stored in database and the\n mail can fail sending, so this can send the mismatches in a batch in this case.\"\"\"\n with transaction.atomic():\n mismatches = MismatchVersionMailer.objects.filter(sent=False)\n if not mismatches:\n return\n email_body = \"\"\"\\\nHello,\n\nI am Sprout template version mismatch spammer. I think there are some version mismatches.\n\nHere is the list:\n\n{}\n\nSincerely,\nSprout template version mismatch spammer™\n \"\"\".format(\n \"\\n\".join(\n \"* {} @ {} : supposed {} , true {}\".format(\n mismatch.template_name, mismatch.provider.id, mismatch.supposed_version,\n mismatch.actual_version)\n for mismatch in mismatches\n )\n )\n user_mails = []\n for user in User.objects.filter(is_superuser=True):\n if user.email:\n user_mails.append(user.email)\n result = send_mail(\n \"Template version mismatches detected\",\n email_body,\n \"sprout-template-version-mismatch@example.com\",\n user_mails,\n )\n if result > 0:\n for mismatch in mismatches:\n mismatch.sent = True\n mismatch.save()\n\n\n@singleton_task()\ndef obsolete_template_deleter(self):\n for group in Group.objects.all():\n if group.template_obsolete_days_delete:\n # We can delete based on the template age\n obsolete_templates = group.obsolete_templates\n if obsolete_templates is not None:\n for template in obsolete_templates:\n if template.can_be_deleted:\n delete_template_from_provider.delay(template.id)\n\n\n@singleton_task()\ndef connect_direct_lun(self, appliance_id):\n appliance = Appliance.objects.get(id=appliance_id)\n if not hasattr(appliance.provider_api, \"connect_direct_lun_to_appliance\"):\n return False\n try:\n appliance.provider_api.connect_direct_lun_to_appliance(appliance.name, False)\n except Exception as e:\n appliance.set_status(\"LUN: {}: {}\".format(type(e).__name__, str(e)))\n return False\n else:\n appliance.reload()\n with transaction.atomic():\n appliance.lun_disk_connected = True\n appliance.save()\n return True\n\n\n@singleton_task()\ndef disconnect_direct_lun(self, appliance_id):\n appliance = Appliance.objects.get(id=appliance_id)\n if not appliance.lun_disk_connected:\n return False\n if not hasattr(appliance.provider_api, \"connect_direct_lun_to_appliance\"):\n return False\n try:\n appliance.provider_api.connect_direct_lun_to_appliance(appliance.name, True)\n except Exception as e:\n appliance.set_status(\"LUN: {}: {}\".format(type(e).__name__, str(e)))\n return False\n else:\n appliance.reload()\n with transaction.atomic():\n appliance.lun_disk_connected = False\n appliance.save()\n return True\n\n\n@singleton_task()\ndef appliance_yum_update(self, appliance_id):\n appliance = Appliance.objects.get(id=appliance_id)\n if appliance.preconfigured:\n appliance.ipapp.update_rhel(setup_repos=False, reboot=False)\n else:\n appliance.ipapp.update_rhel(setup_repos=True, reboot=False)\n","sub_path":"sprout/appliances/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":59882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"266364036","text":"from collections import namedtuple\nfrom unittest.mock import patch\n\nfrom factory import Factory, Sequence\nfrom factory.alchemy import SQLAlchemyModelFactory\nimport pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom service import load_config, model, app as ThriftApp\nfrom service.dispatcher import ServiceDispatcher\n\n\nTestSession = sessionmaker()\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef config():\n load_config()\n\n\n@pytest.fixture(scope='session')\ndef db(request):\n from service import config as config_\n\n database_url = config_['service']['db_uri']\n engine = create_engine(database_url)\n\n model.initialize(database_url)\n model.Base.metadata.create_all(engine)\n request.addfinalizer(model.Base.metadata.drop_all)\n\n return engine\n\n\n@pytest.fixture(autouse=True)\ndef session(request, db):\n conn = db.connect()\n transaction = conn.begin()\n _session = TestSession(bind=conn)\n model.SessionRegistry = lambda: _session\n\n def teardown():\n _session.close()\n transaction.rollback()\n conn.close()\n\n request.addfinalizer(teardown)\n return _session\n\n\n@pytest.fixture(scope='session', autouse=True)\ndef no_monitoring(request):\n patcher = patch('service.monitoring', return_value=lambda n: n)\n patcher.start()\n request.addfinalizer(patcher.stop)\n\n\n@pytest.fixture\ndef App(request, config):\n return ThriftApp.create_app\n\n\n@pytest.fixture\ndef dispatcher(request):\n return ServiceDispatcher()\n\n\nclass ModelFactory(SQLAlchemyModelFactory):\n class Meta:\n model = model.ServiceModel\n\n id = Sequence(int)\n date_created = None\n date_updated = None\n\n\n@pytest.fixture\ndef model_factory(request, session):\n ModelFactory._meta.sqlalchemy_session = session\n request.addfinalizer(ModelFactory.reset_sequence)\n return ModelFactory\n\n\nModelCreateParams = namedtuple('ModelCreateParams', [\n # Add your model's creation parameters here\n # 'name',\n])\n\n\nclass ModelCreateParamsFactory(Factory):\n class Meta:\n model = ModelCreateParams\n\n # Mirror those create params here\n # name = Sequence(lambda n: 'name_{}'.format(n))\n\n\n@pytest.fixture\ndef model_create_params_factory():\n return ModelCreateParamsFactory\n","sub_path":"app/templates/tests/_conftest.py","file_name":"_conftest.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"149010798","text":"import unittest\n\nimport six\n\nimport conan.tools.qbs.qbs as qbs\n\nfrom conans.client import tools\nfrom conans.errors import ConanException\nfrom conans.test.utils.mocks import MockConanfile, MockSettings\nfrom conans.test.utils.test_files import temp_folder\n\n\nclass RunnerMock(object):\n def __init__(self, return_ok=True, output=None):\n self.command_called = None\n self.return_ok = return_ok\n self.output = output\n\n def __call__(self, command, output, win_bash=False, subsystem=None):\n self.command_called = command\n self.win_bash = win_bash\n self.subsystem = subsystem\n if self.output and output and hasattr(output, 'write'):\n output.write(self.output)\n return 0 if self.return_ok else 1\n\n\nclass QbsTest(unittest.TestCase):\n def test_generating_config_command_line(self):\n name = 'default'\n flag_dict = {\n 'modules.cpp.cxxFlags': ['-frtti', '-fexceptions'],\n 'modules.cpp.ldFlags': '--defsym=hello_world',\n 'products.App.myIntProperty': 13,\n 'products.App.myBoolProperty': True\n }\n expected_config_line = [\n 'config:%s' % name,\n ]\n for key, value in flag_dict.items():\n if type(value) is bool:\n if value:\n value = 'true'\n else:\n value = 'false'\n expected_config_line.append('%s:%s' % (key, value))\n self.assertEqual(\n qbs._configuration_dict_to_commandlist(name, flag_dict),\n expected_config_line)\n\n def test_construct_build_helper_without_project_file(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}))\n conanfile.folders.set_base_source('.')\n build_helper = qbs.Qbs(conanfile)\n self.assertEqual(build_helper.jobs, tools.cpu_count())\n self.assertEqual(build_helper._project_file, conanfile.source_folder)\n\n def test_construct_build_helper_with_project_file(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}))\n # just asume that the test is called from repo root\n profile_file_path = temp_folder()\n build_helper = qbs.Qbs(conanfile, project_file=profile_file_path)\n self.assertEqual(build_helper._project_file, profile_file_path)\n\n def test_construct_build_helper_with_wrong_project_file_path(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}))\n with self.assertRaises(ConanException):\n qbs.Qbs(conanfile, project_file='random/file/path')\n\n def test_add_configuration(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}))\n conanfile.folders.set_base_source('.')\n build_helper = qbs.Qbs(conanfile)\n configurations = {\n 'debug': {'products.MyLib.specialFlags': ['-frtti',\n '-fexceptions']},\n 'release': {'products.MyLib.specialFlags': ['-fno-exceptions',\n '-fno-rtti']}\n }\n for name, config in configurations.items():\n build_helper.add_configuration(name, config)\n self.assertEqual(build_helper._configuration, configurations)\n\n def test_build(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}),\n runner=RunnerMock())\n conanfile.folders.set_base_source('.')\n conanfile.folders.set_base_build('.')\n build_helper = qbs.Qbs(conanfile)\n\n build_helper.build()\n self.assertEqual(\n conanfile.runner.command_called,\n ('qbs build --no-install --build-directory %s '\n '--file %s --jobs %s profile:%s') % (\n conanfile.build_folder, build_helper._project_file,\n build_helper.jobs, build_helper.profile))\n\n build_helper.build(products=['app1', 'app2', 'lib'])\n self.assertEqual(\n conanfile.runner.command_called,\n ('qbs build --no-install --build-directory %s '\n '--file %s --products app1,app2,lib --jobs %s profile:%s') % (\n conanfile.build_folder, build_helper._project_file,\n build_helper.jobs, build_helper.profile))\n\n def test_build_all(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}),\n runner=RunnerMock())\n conanfile.folders.set_base_source('.')\n conanfile.folders.set_base_build('.')\n build_helper = qbs.Qbs(conanfile)\n\n build_helper.build_all()\n self.assertEqual(\n conanfile.runner.command_called,\n ('qbs build --no-install --build-directory %s '\n '--file %s --all-products --jobs %s profile:%s') % (\n conanfile.build_folder, build_helper._project_file,\n build_helper.jobs, build_helper.profile))\n\n @unittest.skipIf(six.PY2, \"Order of qbs output is defined only for PY3\")\n def test_build_with_custom_configuration(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}),\n runner=RunnerMock())\n conanfile.folders.set_base_source('.')\n conanfile.folders.set_base_build('.')\n build_helper = qbs.Qbs(conanfile)\n config_name = 'debug'\n config_values = {\n 'product.App.boolProperty': True,\n 'product.App.intProperty': 1337,\n 'product.App.stringProperty': 'Hello World',\n 'product.App.stringListProperty': ['Hello', 'World']\n }\n build_helper.add_configuration(config_name, config_values)\n build_helper.build()\n self.assertEqual(\n conanfile.runner.command_called,\n ('qbs build --no-install --build-directory %s '\n '--file %s --jobs %s profile:%s '\n 'config:%s %s:%s %s:%s %s:%s %s:%s') % (\n conanfile.build_folder, build_helper._project_file,\n build_helper.jobs, build_helper.profile,\n config_name,\n 'product.App.boolProperty',\n 'true',\n 'product.App.intProperty',\n config_values['product.App.intProperty'],\n 'product.App.stringProperty',\n config_values['product.App.stringProperty'],\n 'product.App.stringListProperty',\n config_values['product.App.stringListProperty']))\n\n def test_install(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}),\n runner=RunnerMock())\n conanfile.folders.set_base_source('.')\n conanfile.folders.set_base_package(\"pkg\")\n build_helper = qbs.Qbs(conanfile)\n\n build_helper.install()\n self.assertEqual(\n conanfile.runner.command_called,\n ('qbs install --no-build --install-root %s '\n '--file %s') % (\n conanfile.package_folder, build_helper._project_file))\n\n def test_install_with_custom_configuration(self):\n conanfile = MockConanfile(\n MockSettings({'os': 'Linux', 'compiler': 'gcc'}),\n runner=RunnerMock())\n conanfile.folders.set_base_source('.')\n conanfile.folders.set_base_package(\"pkg\")\n build_helper = qbs.Qbs(conanfile)\n config_name = 'debug'\n config_values = {\n 'product.App.boolProperty': True,\n 'product.App.intProperty': 1337,\n 'product.App.stringProperty': 'Hello World',\n 'product.App.stringListProperty': ['Hello', 'World']\n }\n build_helper.add_configuration(config_name, config_values)\n\n build_helper.install()\n self.assertEqual(\n conanfile.runner.command_called,\n ('qbs install --no-build --install-root %s '\n '--file %s config:%s') % (\n conanfile.package_folder, build_helper._project_file,\n config_name))\n","sub_path":"conans/test/unittests/tools/qbs/test_qbs.py","file_name":"test_qbs.py","file_ext":"py","file_size_in_byte":8147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"155313893","text":"\"\"\"\nImplements custom permissions for API access.\n\nImplements IsOwnerOrAnonOrReadOnly for Upload API access.\n\"\"\"\n\n\nfrom rest_framework import permissions\n\n\nclass IsOwnerOrAnonOrReadOnly(permissions.BasePermission):\n \"\"\"\n The upload must have an attribute uploads_owner which may be null.\n Edit permissions are given only when request.user is owner\n or uploads_owner is null.\n\n Usage is not defined fo upload which is not of type frontend.models.Upload\n \"\"\"\n\n def has_object_permission(self, request, view, upload):\n \"\"\"\n Grant permissions for all SAFE_METHODS.\n Grant permissions if uploads_owner is None.\n Grant permissions only to owner of file.\n \"\"\"\n if request.method in permissions.SAFE_METHODS:\n return True\n\n if upload.uploads_owner is None:\n return True\n\n return upload.uploads_owner == request.user\n","sub_path":"frontend/permissions.py","file_name":"permissions.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"24284588","text":"# -*- coding: utf-8 -*-\n# ---------------------------------------------------------------------\n# Qtech.QSW.get_version\n# ---------------------------------------------------------------------\n# Copyright (C) 2007-2017 The NOC Project\n# See LICENSE for details\n# ---------------------------------------------------------------------\n\n# Python modules\nimport re\n# NOC modules\nfrom noc.core.script.base import BaseScript\nfrom noc.sa.interfaces.igetversion import IGetVersion\n\n\nclass Script(BaseScript):\n name = \"Qtech.QSW2800.get_version\"\n interface = IGetVersion\n cache = True\n\n rx_ver = re.compile(\n r\"^\\s*(?:Device: )?(?P\\S+)(?: Device|, sysLocation\\:).+\\n\"\n r\"^\\s*SoftWare(?: Package)? Version\\s+(?P\\S+(?:\\(\\S+\\))?)\\n\"\n r\"^\\s*BootRom Version\\s+(?P\\S+)\\n\"\n r\"^\\s*HardWare Version\\s+(?P\\S+).+\"\n r\"^\\s*(?:Device serial number |Serial No.:)(?P\\S+)\\n\",\n re.MULTILINE | re.DOTALL)\n\n def execute(self):\n ver = self.cli(\"show version\", cached=True)\n match = self.rx_ver.search(ver)\n if match:\n platform = match.group(\"platform\")\n version = match.group(\"version\")\n bootprom = match.group(\"bootprom\")\n hardware = match.group(\"hardware\")\n serial = match.group(\"serial\")\n\n return {\n \"vendor\": \"Qtech\",\n \"platform\": platform,\n \"version\": version,\n \"attributes\": {\n \"Boot PROM\": bootprom,\n \"HW version\": hardware,\n \"Serial Number\": serial\n }\n }\n else:\n return {\n \"vendor\": \"Qtech\",\n \"platform\": \"Unknown\",\n \"version\": \"Unknown\"\n }\n","sub_path":"sa/profiles/Qtech/QSW2800/get_version.py","file_name":"get_version.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"79914308","text":"import pandas as pd\nimport sqlite3\n\n\nif __name__ == '__main__':\n df = pd.read_csv('./school_info.csv', encoding='GBK')\n print(df.head(5))\n conn = sqlite3.connect(\"../db.sqlite3\")\n cursor = conn.cursor()\n df = df.fillna(value='--')\n for i in range(len(df)):\n a = int(df.iloc[i, 0])\n b = df.iloc[i, 1]\n c = df.iloc[i, 2]\n d = df.iloc[i, 3]\n e = df.iloc[i, 4]\n f = df.iloc[i, 5]\n g = df.iloc[i, 6]\n h = df.iloc[i, 7]\n\n print(a, b, c,d,e,f,g,h)\n sql = \"insert into school_school_info values ('%d','%s','%s', '%s','%s','%s', '%s', '%s')\" % (a, b, c,d,e,f,g,h)\n x = cursor.execute(sql)\n\n conn.commit()\n","sub_path":"test/insert_school.py","file_name":"insert_school.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"597561532","text":"\n\n#calss header\nclass _AUDITION():\n\tdef __init__(self,): \n\t\tself.name = \"AUDITION\"\n\t\tself.definitions = [u'to give a short performance in order to show that you are suitable for a part in a film, play, show, etc., or to make someone do this: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_audition.py","file_name":"_audition.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"538617056","text":"__author__ = \"Chaddle\"\n\nimport masterclass\n\n\nclass Player(masterclass.Master):\n\n def __init__(self):\n super().__init__(self)\n self.ability_scores = []\n self.class_dict = {}\n self.ability_dict = {}\n self.ability_scores = []\n self.class_name = ''\n\n def roll_abilities(self):\n if self.ability_scores != []:\n pass\n else:\n for i in range(6):\n\n results = []\n for j in range(4):\n\n from random import randint\n temp = randint(1, 6)\n results.append(temp)\n\n results.remove(min(results))\n self.ability_scores.append(sum(results))\n\n def get_class(self):\n self.class_lookup()\n self.create_class()\n\n def class_lookup(self):\n class_list = ['barbarian', 'bard', 'cleric', 'druid', 'fighter',\n 'monk', 'paladin', 'ranger', 'rogue', 'sorcerer',\n 'wizard']\n self.class_name = input(\"Pick a class:\\n\"\n \"1. barbarian,\\n\"\n \"2. bard,\\n\"\n \"3. cleric,\\n\"\n \"4. druid,\\n\"\n \"5. fighter,\\n\"\n \"6. monk,\\n\"\n \"7. paladin,\\n\"\n \"8. ranger,\\n\"\n \"9. rogue,\\n\"\n \"10. sorcerer, or\\n\"\n \"11. wizard\\n\\n\")\n self.class_name = self.class_name.strip()\n if self.class_name not in class_list:\n print(\"This is not a valid class. Please try again.\")\n self.class_lookup()\n else:\n return self.class_name\n\n def create_class(self):\n if self.class_name == \"barbarian\":\n from classclass import Barbarian\n self.name = Barbarian()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"bard\":\n from classclass import Bard\n self.name = Bard()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"cleric\":\n from classclass import Cleric\n self.name = Cleric()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"druid\":\n from classclass import Druid\n self.name = Druid()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"fighter\":\n from classclass import Fighter\n self.name = Fighter()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"monk\":\n from classclass import Monk\n self.name = Monk()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"paladin\":\n from classclass import Paladin\n self.name = Paladin()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"ranger\":\n from classclass import Ranger\n self.name = Ranger()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"rogue\":\n from classclass import Rogue\n self.name = Rogue()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"sorcerer\":\n from classclass import Sorcerer\n self.name = Sorcerer()\n self.name.build_table()\n self.class_dict = self.name.class_table\n elif self.class_name == \"wizard\":\n from classclass import Wizard\n self.name = Wizard()\n self.name.build_table()\n self.class_dict = self.name.class_table\n else:\n raise Exception\n","sub_path":"playerclass.py","file_name":"playerclass.py","file_ext":"py","file_size_in_byte":4152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"40861649","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication, QWidget,QLabel\n\nfrom PyQt5.QtCore import pyqtSignal\n\nfrom PyQt5.QtGui import QMouseEvent, QFont\n\n\n## 自定义标签类,自定义了doubleClicked()信号\nclass QmyLabel(QLabel): \n doubleClicked = pyqtSignal() ##自定义信号\n \n def mouseDoubleClickEvent(self,event): ##双击事件的处理\n self.doubleClicked.emit()\n \n\nclass QmyWidget(QWidget):\n def __init__(self, parent=None):\n super().__init__(parent) \n self.resize(280,150) \n self.setWindowTitle(\"Demo5_2,事件与信号\")\n\n LabHello = QmyLabel(self) \n LabHello.setText(\"双击我啊\")\n\n font = LabHello.font()\n font.setPointSize(14) \n font.setBold(True) \n LabHello.setFont(font) \n size=LabHello.sizeHint() \n LabHello.setGeometry(70, 60, size.width(), size.height())\n \n LabHello.doubleClicked.connect(self.do_doubleClicked)\n\n def do_doubleClicked(self): ##标签的槽函数\n print(\"标签被双击了\")\n\n def mouseDoubleClickEvent(self,event): ##双击事件的处理\n print(\"窗口双击事件响应\")\n \n \n \n## ============窗体测试程序 =================\nif __name__ == \"__main__\": \n app = QApplication(sys.argv) \n form=QmyWidget() \n form.show()\n sys.exit(app.exec_())\n","sub_path":"pyqt/DemoUIonly-PythonQt/chap05Events/Demo5_2EventSignal/demo5_2EventSignal.py","file_name":"demo5_2EventSignal.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"35096293","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn import model_selection, metrics\nimport xgboost\nfrom functools import partial\nfrom skopt import space, gp_minimize\n\n\ndf = pd.read_csv(\"datasets_train.csv\")\nX = df.drop(\"price_range\", axis=1).values # input feature\ny = df.price_range.values # target feature\n\n\ndef optimize(params, param_names, x, y):\n params = dict(zip(param_names, params))\n xgb_opt = xgboost.XGBClassifier(**params, tree_method=\"gpu_hist\")\n kfold = model_selection.StratifiedKFold(n_splits=5, shuffle=True)\n acc = []\n for train_ix, test_ix in kfold.split(X, y):\n train_X, test_X = X[train_ix], X[test_ix]\n train_y, test_y = y[train_ix], y[test_ix]\n\n xgb_opt.fit(train_X, train_y)\n preds = xgb_opt.predict(test_X)\n fold_acc = metrics.accuracy_score(test_y, preds)\n acc.append(fold_acc)\n\n return -1.0 * np.mean(acc)\n\n\nparam_space = [\n space.Integer(3, 15, name=\"max_depth\"),\n space.Integer(1, 10, name=\"min_child_weight\"),\n space.Real(0.1, 0.3, prior=\"uniform\", name=\"eta\"),\n space.Real(0.5, 0.7, prior=\"uniform\", name=\"subsample\"),\n space.Real(0.1, 0.5, prior=\"uniform\", name=\"gamma\"),\n]\n\nparam_names = [\"max_depth\", \"min_child_weight\", \"eta\", \"subsample\", \"gamma\"]\noptimization_function = partial(optimize, param_names=param_names, x=X, y=y)\n\nresult = gp_minimize(\n optimization_function,\n dimensions=param_space,\n n_calls=15,\n n_random_starts=10,\n verbose=10,\n)\n\nprint(dict(zip(param_names, result.x)))\n\n","sub_path":"scikit_opt.py","file_name":"scikit_opt.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"111819783","text":"import torch\nfrom torch import nn\nfrom d2l import torch as d2l\n\ndef pool2d(X, pool_size, mode='max'):\n p_h, p_w = pool_size\n Y = torch.zeros((X.shape[0] - p_h + 1, X.shape[1] - p_w + 1))\n s = 1\n for i in range(Y.shape[0]):\n for j in range(Y.shape[1]):\n if mode == 'max':\n Y[i, j] = X[i:i+p_h, j:j+p_w].max()\n elif mode == 'avg':\n Y[i, j] = X[i:i+p_h, j:j+p_w].mean()\n return Y \n\nX = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]])\nY = pool2d(X, (2, 2), mode='avg')\n\nX = torch.arange(16, dtype=torch.float32).reshape((1, 1, 4, 4))\npool2d = nn.MaxPool2d(3)\nY = pool2d(X)","sub_path":"convolutional-neural-networks/poolling.py","file_name":"poolling.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"386497988","text":"# -*- coding: utf-8 -*-\n\"\"\"\n scap.git\n ~~~~~~~~\n Helpers for git operations and interacting with .git directories\n\n\"\"\"\nfrom datetime import datetime\nimport errno\nimport re\nimport os\nimport socket\nimport subprocess\n\nfrom . import utils\n\nimport yaml\n\n# All tags created by scap use this prefix\nTAG_PREFIX = 'scap/sync'\n\n# Key is the pattern for .gitignore, value is a test for that pattern.\nDEFAULT_IGNORE = {\n '*~',\n '*.swp',\n '*/cache/l10n/*.cdb',\n 'scap/log/*',\n}\n\n\ndef info_filename(directory, install_path, cache_path):\n \"\"\"Compute the path for a git_info cache file related to a given\n directory.\n\n >>> info_filename('foo', 'foo', '')\n 'info.json'\n >>> info_filename('foo/bar/baz', 'foo', 'xyzzy')\n 'xyzzy/info-bar-baz.json'\n \"\"\"\n path = directory\n if path.startswith(install_path):\n path = path[len(install_path):]\n return os.path.join(cache_path, 'info%s.json' % path.replace('/', '-'))\n\n\ndef sha(location, rev):\n \"\"\"Returns SHA1 for things like HEAD or HEAD~~\"\"\"\n ensure_dir(location)\n with utils.cd(location):\n cmd = '/usr/bin/git rev-parse --verify {}'.format(rev)\n return subprocess.check_output(cmd, shell=True).strip()\n\n\ndef describe(location):\n \"\"\"Returns a convenient label for the current state of the git repo.\"\"\"\n ensure_dir(location)\n with utils.cd(location):\n cmd = '/usr/bin/git describe --always'\n return subprocess.check_output(cmd, shell=True).strip()\n\n\ndef fat_init(location):\n \"\"\"Initializes the given directory for git-fat use.\"\"\"\n\n with utils.cd(location):\n subprocess.check_call('/usr/bin/git fat init', shell=True)\n\n\ndef fat_isinitialized(location):\n \"\"\"Returns whether git-fat has been initialized for the given directory.\"\"\"\n\n with utils.cd(location):\n with open(os.devnull, 'w') as devnull:\n try:\n cmd = '/usr/bin/git config --local --get filter.fat.smudge'\n subprocess.check_call(cmd, stdout=devnull, shell=True)\n return True\n except subprocess.CalledProcessError as e:\n if e.returncode == 1:\n return False\n raise e\n\n\ndef fat_pull(location):\n \"\"\"Syncs all git-fat objects for the given repo directory.\"\"\"\n\n with utils.cd(location):\n subprocess.check_call('/usr/bin/git fat pull', shell=True)\n\n\ndef info(directory):\n \"\"\"Compute git version information for a given directory that is\n compatible with MediaWiki's GitInfo class.\n\n :param directory: Directory to scan for git information\n :returns: Dict of information about current repository state\n \"\"\"\n git_dir = os.path.join(directory, '.git')\n if not os.path.exists(git_dir):\n raise IOError(errno.ENOENT, '.git not found', directory)\n\n if os.path.isfile(git_dir):\n # submodules\n with open(git_dir, 'r') as f:\n git_ref = f.read().strip()\n\n if not git_ref.startswith('gitdir: '):\n raise IOError(errno.EINVAL, 'Unexpected .git contents', git_dir)\n git_ref = git_ref[8:]\n if git_ref[0] != '/':\n git_ref = os.path.abspath(os.path.join(directory, git_ref))\n git_dir = git_ref\n\n head_file = os.path.join(git_dir, 'HEAD')\n with open(head_file, 'r') as f:\n head = f.read().strip()\n if head.startswith('ref: '):\n head = head[5:]\n\n if head.startswith('refs/heads/'):\n branch = head[11:]\n elif head.startswith('refs/tags/'):\n branch = head[10:]\n else:\n branch = head\n\n head_sha1 = get_disclosable_head(directory, branch)\n if head_sha1:\n commit_date = subprocess.check_output(\n ('/usr/bin/git', 'show', '-s', '--format=%ct', head_sha1),\n cwd=git_dir).strip()\n else:\n commit_date = ''\n\n # Requires git v1.7.5+\n try:\n remote_url = subprocess.check_output(\n ('/usr/bin/git', 'ls-remote', '--get-url'),\n cwd=git_dir).strip()\n except subprocess.CalledProcessError:\n remote_url = ''\n utils.get_logger().info(\"Unable to find remote URL for %s\", git_dir)\n\n return {\n '@directory': directory,\n 'head': head,\n 'headSHA1': head_sha1,\n 'headCommitDate': commit_date,\n 'branch': branch,\n 'remoteURL': remote_url,\n }\n\n\ndef default_ignore(location):\n \"\"\"Create a default .gitignore file.\"\"\"\n ignore = '\\n'.join(DEFAULT_IGNORE)\n with utils.cd(location):\n with open('.gitignore', 'w+') as f:\n f.write(ignore)\n\n\ndef clean_tags(location, max_tags):\n \"\"\"Make sure there aren't more than max_tags.\"\"\"\n git = '/usr/bin/git'\n ensure_dir(location)\n with utils.cd(location):\n cmd = [\n git,\n 'for-each-ref',\n '--sort=taggerdate',\n '--format=%(refname)',\n 'refs/tags'\n ]\n\n tags = subprocess.check_output(cmd).splitlines()\n old_tags = []\n while len(tags) > max_tags:\n tag = tags.pop(0)\n if tag.startswith('refs/tags/'):\n tag = tag[10:]\n\n # Don't delete tags that aren't ours\n if not tag.startswith(TAG_PREFIX):\n continue\n\n old_tags.append(tag)\n\n # if there aren't any old tags, bail early\n if len(old_tags) == 0:\n return\n\n cmd = [git, 'tag', '-d']\n cmd += old_tags\n subprocess.check_call(cmd)\n\n\ndef gc(location):\n \"\"\"Clean up a repo.\"\"\"\n git = '/usr/bin/git'\n ensure_dir(location)\n with utils.cd(location):\n cmd = [git, 'gc', '--quiet', '--auto']\n subprocess.check_call(cmd)\n\n\ndef add_all(location, message='Update'):\n \"\"\"Add everything to repo at location as user.\"\"\"\n git = '/usr/bin/git'\n with utils.cd(location):\n # Initialize repo if it isn't already\n if not is_dir(location):\n cmd = [git, 'init']\n subprocess.check_call(cmd)\n\n cmd = [git, 'add', '--all']\n subprocess.check_call(cmd)\n\n # None of these values can be unset or empty strings because we use\n # them as git envvars below. Unset values and empty strings will\n # cause git to shout about ident errors.\n host = socket.getfqdn() or 'localhost'\n euid = utils.get_username() or 'unknown'\n ruid = utils.get_real_username() or 'unknown'\n ename = utils.get_user_fullname() or 'Unknown User'\n rname = utils.get_real_user_fullname() or 'Unknown User'\n\n os.environ['GIT_COMMITTER_EMAIL'] = '{}@{}'.format(euid, host)\n os.environ['GIT_AUTHOR_EMAIL'] = '{}@{}'.format(ruid, host)\n\n os.environ['GIT_COMMITTER_NAME'] = ename\n os.environ['GIT_AUTHOR_NAME'] = rname\n\n cmd = [git, 'commit', '-m', message]\n\n # Soft errors if nothing new to commit\n subprocess.call(cmd)\n\n\ndef next_deploy_tag(location):\n \"\"\"Calculates the scap/sync/{date}/{n} tag to use for this deployment\"\"\"\n ensure_dir(location)\n with utils.cd(location):\n timestamp = datetime.utcnow()\n date = timestamp.strftime('%F')\n cmd = ['/usr/bin/git', 'tag', '--list']\n tag_fmt = os.path.join(TAG_PREFIX, '{}', '*')\n cmd.append(tag_fmt.format(date))\n seq = len(subprocess.check_output(cmd).splitlines()) + 1\n tag_fmt = os.path.join(TAG_PREFIX, '{0}', '{1:04d}')\n return tag_fmt.format(date, seq)\n\n\ndef ensure_dir(location):\n if location is None or not is_dir(location):\n raise IOError(errno.ENOENT, 'Location is not a git repo', location)\n\n\ndef is_dir(path):\n \"\"\"Checks if path is a git, doesn't count submodule directories\"\"\"\n git_path = os.path.join(\n os.path.abspath(os.path.expandvars(os.path.expanduser(path))),\n '.git'\n )\n return (\n os.path.isdir(git_path) and\n os.path.isdir(os.path.join(git_path, 'objects')) and\n os.path.isdir(os.path.join(git_path, 'refs')) and\n os.path.isfile(os.path.join(git_path, 'HEAD')))\n\n\ndef remote_exists(location, remote):\n \"\"\"Check if remote exists in location\"\"\"\n ensure_dir(location)\n with utils.cd(location):\n cmd = '/usr/bin/git config --local --get remote.{}.url'.format(remote)\n return subprocess.call(cmd, shell=True) == 0\n\n\ndef remote_set(location, repo, remote='origin'):\n \"\"\"set the remote at location to repo\"\"\"\n ensure_dir(location)\n with utils.cd(location):\n if remote_exists(location, remote):\n cmd = '/usr/bin/git remote rm {}'.format(remote)\n subprocess.check_call(cmd, shell=True)\n\n cmd = '/usr/bin/git remote add {} {}'.format(remote, repo)\n subprocess.check_call(cmd, shell=True)\n\n\ndef fetch(location, repo):\n \"\"\"Fetch a git repo to a location\n \"\"\"\n if is_dir(location):\n remote_set(location, repo)\n with utils.cd(location):\n cmd = '/usr/bin/git fetch'\n subprocess.check_call(cmd, shell=True)\n else:\n cmd = '/usr/bin/git clone {0} {1}'.format(repo, location)\n subprocess.check_call(cmd, shell=True)\n\n\ndef checkout(location, rev):\n \"\"\"Checkout a git repo sha at a location\n \"\"\"\n ensure_dir(location)\n\n logger = utils.get_logger()\n\n with utils.cd(location):\n logger.debug(\n 'Checking out rev: {} at location: {}'.format(rev, location))\n cmd = '/usr/bin/git checkout --force --quiet {}'.format(rev)\n subprocess.check_call(cmd, shell=True)\n\n\ndef sync_submodules(location):\n \"\"\"Sync git submodules on target machines\"\"\"\n\n ensure_dir(location)\n\n logger = utils.get_logger()\n\n with utils.cd(location):\n logger.debug('Syncing out submodules')\n cmd = '/usr/bin/git submodule sync --recursive'\n subprocess.check_call(cmd, shell=True)\n\n\ndef update_submodules(location, git_remote=None, use_upstream=False):\n \"\"\"Update git submodules on target machines\"\"\"\n\n if not use_upstream and git_remote is None:\n raise ValueError(\"Must set git_remote if not using upstream\")\n\n ensure_dir(location)\n\n logger = utils.get_logger()\n\n with utils.cd(location):\n logger.debug('Checking out submodules')\n if not use_upstream:\n remap_submodules(location, git_remote)\n cmd = '/usr/bin/git submodule update --init --recursive'\n subprocess.check_call(cmd, shell=True)\n\n\n@utils.log_context('git_update_server_info')\ndef update_server_info(has_submodules=False, location=os.getcwd(),\n logger=None):\n \"\"\"runs git update-server-info and tags submodules\"\"\"\n\n with utils.cd(location):\n cmd = '/usr/bin/git update-server-info'\n subprocess.check_call(cmd, shell=True)\n logger.debug('Update server info')\n\n if has_submodules:\n cmd = \"/usr/bin/git submodule foreach --recursive '{}'\".format(cmd)\n subprocess.check_call(cmd, shell=True)\n\n\ndef update_deploy_head(deploy_info, location):\n \"\"\"updates .git/DEPLOY_HEAD file\n\n :param deploy_info: current deploy info to write to file as YAML\n :param (optional) location: git directory location (default cwd)\n \"\"\"\n logger = utils.get_logger()\n ensure_dir(location)\n\n with utils.cd(location):\n deploy_file = os.path.join(location, '.git', 'DEPLOY_HEAD')\n logger.debug('Creating {}'.format(deploy_file))\n with open(deploy_file, 'w+') as f:\n f.write(yaml.dump(deploy_info, default_flow_style=False))\n f.close()\n\n\ndef tag_repo(deploy_info, location=os.getcwd()):\n \"\"\"creates new tag in deploy repo\"\"\"\n\n ensure_dir(location)\n with utils.cd(location):\n cmd = \"\"\"\n /usr/bin/git tag -fa \\\\\n -m 'user {0}' \\\\\n -m 'timestamp {1}' -- \\\\\n {2} {3}\n \"\"\".format(\n deploy_info['user'],\n deploy_info['timestamp'],\n deploy_info['tag'],\n deploy_info['commit']\n )\n subprocess.check_call(cmd, shell=True)\n\n\ndef remap_submodules(location, server):\n \"\"\"Remap all submodules to new server (tin)\n\n This function supports remapping submodules available on the deployment\n server. Since the remote is a non-bare repo (as of git 1.7.8) all\n submodules should be available over http under the remote server\n checkout's git dir:\n [server]/[repo]/.git/modules/[submodule_path]\n\n :param location: String path to local git checkout containing a\n `.gitmodules` file\n :param server: String path to remote, non-bare, repo gitdir\n \"\"\"\n ensure_dir(location)\n\n logger = utils.get_logger()\n\n with utils.cd(location):\n gitmodule = os.path.join(os.getcwd(), '.gitmodules')\n if not os.path.isfile(gitmodule):\n return\n\n logger.info('Updating .gitmodule: {}'.format(\n os.path.dirname(gitmodule)))\n\n # ensure we're working with a non-modified .gitmodules file\n subprocess.check_call(['/usr/bin/git', 'checkout', '.gitmodules'])\n\n # get .gitmodule info\n modules = subprocess.check_output([\n '/usr/bin/git', 'config', '--list', '--file', '.gitmodules'])\n\n submodules = {}\n for line in modules.split('\\n'):\n if not line.startswith('submodule.'):\n continue\n\n module_conf = line.split('=')\n module_name = module_conf[0].strip()\n\n if module_name.endswith('.path'):\n name = module_name[len('submodule.'):-len('.path')]\n submodules[name] = module_conf[1].strip()\n\n with open(gitmodule, 'w') as module:\n for submodule_name, submodule_path in submodules.iteritems():\n # Since we're using a non-bare http remote, map the submodule\n # to the submodule path under $GIT_DIR/modules subdirectory of\n # the superproject (git documentation: https://git.io/v4W9F).\n remote_path = '{}/modules/{}'.format(server, submodule_name)\n module.write('[submodule \"{}\"]\\n'.format(submodule_name))\n module.write('\\tpath = {}\\n'.format(submodule_path))\n module.write('\\turl = {}\\n'.format(remote_path))\n\n\ndef get_disclosable_head(repo_directory, remote_thing):\n \"\"\"\n Get the SHA1 of the most recent commit that can be publicly disclosed.\n If a commit only exists locally, it is considered private. This function\n will try to get the tip of the remote tracking branch, and fall back to\n the common ancestor of HEAD and the remote version of the local branch\n we're ostensibly tracking.\n\n :param repo_directory: Directory to look into\n :param remote_thing: If you're not actively tracking a remote branch, you\n need to provide something remote for this function to\n look for a common ancestor with. Otherwise, this\n function has no way of knowing what common tree\n you could possibly care about. This could be a branch,\n a tag, or a plain sha1\n :returns: str\n \"\"\"\n \"\"\" \"\"\"\n with open(os.devnull, 'wb') as dev_null:\n try:\n return subprocess.check_output(\n ('/usr/bin/git', 'rev-list', '-1', '@{upstream}'),\n cwd=repo_directory, stderr=dev_null).strip()\n except subprocess.CalledProcessError:\n try:\n if not re.match('[a-f0-9]{40}', remote_thing):\n remote = subprocess.check_output(\n ('/usr/bin/git', 'remote'),\n cwd=repo_directory, stderr=dev_null).strip()\n remote_thing = '%s/%s' % (remote, remote_thing)\n return subprocess.check_output(\n ('/usr/bin/git', 'merge-base', 'HEAD', remote_thing),\n cwd=repo_directory, stderr=dev_null).strip()\n except subprocess.CalledProcessError:\n utils.get_logger().info(\n 'Unable to find remote tracking branch/tag for %s' %\n repo_directory)\n return ''\n\n\ndef list_submodules(repo):\n ensure_dir(repo)\n submodules = []\n res = subprocess.check_output(\n ('/usr/bin/git', 'submodule', 'status'), cwd=repo)\n for line in res.splitlines():\n submodules.append(re.sub(r'-[a-f0-9]{40} ', '', line))\n return submodules\n","sub_path":"scap/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":16407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"650958411","text":"#!/bin/env python2\nclass Solution:\n # @return a tuple, (index1, index2)\n def twoSum(self, num, target):\n dict = {}\n for i in range(len(num)):\n dict[num[i]] = i\n\n for i in range(len(num)):\n if dict.has_key(target - num[i]):\n j = dict[target - num[i]]\n if j != i:\n return (i + 1, j + 1)\n\nif __name__ == '__main__':\n sol = Solution()\n num = [2, 7, 11, 15]\n target = 18\n print(sol.twoSum(num, target))\n","sub_path":"python/two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"308119357","text":"\"\"\"Run wanted tests on Markov. Modified to run easily from bash script on Markov.\"\"\"\nimport sys\nfrom systematic_tests4_test_functions import *\n\n# Get filename and function name from command line.\nfilename = sys.argv[2]\nfunction_name = sys.argv[1]\nsgd_or_not = sys.argv[3]\n\nfunction_dict = {\n \"training_test_function1\": training_test_function1,\n \"testing_test_function1\": testing_test_function1,\n \"training_test_function2\": training_test_function2,\n \"testing_test_function2\": testing_test_function2,\n \"training_test_function3\": training_test_function3,\n \"testing_test_function3\": testing_test_function3, \n \"training_test_function4\": training_test_function4,\n \"testing_test_function4\": testing_test_function4,\n}\n\nif sgd_or_not == \"t\":\n sgd = True\nelse:\n sgd = False\n\nfunction_dict[function_name](filename, sgd = sgd)\n","sub_path":"Project2/run_systematic_tests.py","file_name":"run_systematic_tests.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"399497601","text":"\"\"\"\nWrite a function named find_sum_pairs. It takes two arguments:\n\nA list of ints to search\nA sum to find\nGo through the search list and find all pairs of numbers that would add together to the sum.\n\n1. get (limited) list of numbers\n2. choose a sum\n3. find pairs of numbers in the list that add up to sum\n4. display pairs\n\"\"\"\n\nimport random\n\nconfig = {\n 'lo_num': -2,\n 'hi_num': 2,\n 'min_length': 4,\n 'max_length': 10\n}\n\n\ndef find_sum_pairs(num_list, desired_sum):\n # tests are obviously cribbed from the document\n # not sure why people don't copy/paste this legwork more often\n \"\"\"\n >>> find_sum_pairs([-1, 0, 1, 2], 3)\n [[1, 2]]\n >>> find_sum_pairs([-1, 0, 1, 2], 1)\n [[-1, 2], [0, 1]]\n >>> find_sum_pairs([2, -1, 2], 1)\n [[2, -1], [-1, 2]]\n >>> find_sum_pairs([-1, 1, 2, 2], 3)\n [[1, 2], [1, 2]]\n \"\"\"\n\n pairs = list()\n for i, first_num in enumerate(num_list):\n for test_num in num_list[i + 1:]:\n if first_num + test_num == desired_sum:\n pairs.append([first_num, test_num])\n\n return pairs\n\n\ndef choose_numbers(lo_num, hi_num, min_length, max_length):\n \"\"\" selects a random \"\"\"\n random.seed()\n length = random.randrange(min_length, max_length)\n num_list = [random.randrange(lo_num, hi_num) for i in range(length)]\n sum_value = random.randrange(lo_num, hi_num)\n return_value = (num_list, sum_value)\n\n # returning a tuple would otherwise be ambiguous\n return return_value\n\n\ndef display_pairs(all_nums, sum_pairs, sum_value):\n \"\"\" simple display routine \"\"\"\n\n nums_str = [str(x) for x in all_nums]\n print('Numbers in set: ' + ', '.join(nums_str))\n\n if len(sum_pairs) > 0:\n print('Pairs equal to ' + str(sum_value) + ': ' + str(sum_pairs))\n else:\n print('(no matching pairs equal to ' + str(sum_value))\n\n\ndef main():\n \"\"\" main routine \"\"\"\n response = ''\n while response == '':\n all_nums, sum_value = choose_numbers(\n config['lo_num'], config['hi_num'] + 1,\n config['min_length'], config['max_length'] + 1\n )\n\n sum_pairs = find_sum_pairs(all_nums, sum_value)\n display_pairs(all_nums, sum_pairs, sum_value)\n \n response = input('Enter q to quit')\n\n\nmain()\n","sub_path":"practice/sum-pairs.py","file_name":"sum-pairs.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"296846463","text":"# customer\r\n\r\nimport socket\r\n\r\ndef client1():\r\n ip, port = \"loopback\", 30008\r\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n sock.connect((ip, port)) # loopback and 30008\r\n while True:\r\n\r\n response = sock.recv(1024)\r\n if b\"exit\" in response:\r\n print(response.decode().strip('exit'))\r\n break\r\n else:\r\n print(response.decode())\r\n\r\n reply = input(\">>\")\r\n sock.sendall(reply.encode())\r\n\r\n sock.close()\r\nif __name__ == \"__main__\":\r\n client1()\r\n","sub_path":"cmdmodel.py","file_name":"cmdmodel.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"70672403","text":"#! -*- coding: utf-8 -*-\n__author__ = 'Yan.zhe 2021.2.18'\n\n# from script_collection.import_share import *\nfrom start_the_service.app_instance import *\nfrom script_collection.setting import *\nimport typing\n\n\nclass APPJointFrameStore(AppStore):\n \"\"\"\n The frame test, app_type:\n photo、music、video、alarm、weather、calender、setting、wizard\n \"\"\"\n\n def create_app(self, app_type) -> APPJointFrame:\n app: typing.Optional[APPJointFrame] = None\n\n # Start the Photo module's app\n if app_type == 'JointFrame':\n app = APPJointFrame()\n\n return app\n\n\nclass JointFrame(object):\n\n def __init__(self):\n # Instantiate app\n app_store = APPJointFrameStore()\n order_app_dict = app_store.order_app('JointFrame')\n # get frame driver\n self.frame_driver = order_app_dict['driver']\n self.app = order_app_dict['app']\n self.udid = order_app_dict['udid'][0]\n\n def joint_frame_login_page(self):\n self.app.joint_frame_login(self.frame_driver, self.udid)\n\n\nif __name__ == '__main__':\n logger.info(\"Start JointFrame\")\n joint_frame = JointFrame()\n joint_frame.joint_frame_login_page()\n logger.info(\"End setting\")\n","sub_path":"jointframe/script_collection/app/login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"375259190","text":"#imprimir lo m numeros restados en 2, mutiplicados por 3 y divididos entre 2\r\nimport os\r\n\r\n#input\r\nm=int(os.sys.argv[1])\r\n#inicio_rango\r\nfor m in range(m):\r\n print((m-2)*3/2)\r\n\r\n#fin_rango\r\nprint(\"fin del bucle\")\r\n","sub_path":"rango05.py","file_name":"rango05.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"320989384","text":"\"\"\"For now, the code is contained in a single file.\n\"\"\"\n\n\nimport os\nimport psycopg2\n\n\nCHECK_SCHEMA = \"\"\"SELECT EXISTS (\n SELECT\n schema_name\n FROM\n information_schema.schemata\n WHERE\n schema_name = 'lamarck'\n);\n\"\"\"\n\nCREATE_SYSTEM = \"\"\"CREATE SCHEMA lamarck;\n\nCREATE TABLE lamarck.ddl_evolutions (\n stage INT NOT NULL,\n _occurred_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),\n\n PRIMARY KEY (stage, _occurred_at)\n);\n\"\"\"\n\nGET_LAST_DDL_EVOLUTION = \"\"\"SELECT\n stage\nFROM\n lamarck.ddl_evolutions\nWHERE\n _occurred_at = (\n SELECT\n max(_occurred_at)\n FROM\n lamarck.ddl_evolutions\n )\n;\n\"\"\"\n\nMARK_DDL_EVOLUTION = \"\"\"INSERT INTO lamarck.ddl_evolutions (stage) VALUES (%d)\"\"\"\n\n\nclass DDLController(object):\n\n def __init__(self, sql_dirpath, credentials, logger):\n self.sql_dirpath = sql_dirpath\n self.credentials = credentials\n self.logger = logger\n\n def evolve(self):\n conn = psycopg2.connect(**self.credentials)\n cur = conn.cursor()\n\n cur.execute(CHECK_SCHEMA)\n exists = cur.fetchone()[0]\n\n if not exists:\n self.logger.info('Creating DDL evolution system.')\n\n cur.execute(CREATE_SYSTEM)\n conn.commit()\n\n self.logger.info('DDL evolution system created.')\n\n cur.execute(GET_LAST_DDL_EVOLUTION)\n result = cur.fetchone()\n\n sql_files = os.listdir(self.sql_dirpath)\n last_stage = sorted([int(sql_file.split('-')[0]) for sql_file in sql_files])[-1]\n cur_stage = 0 if result is None else result[0]\n\n for stage in range(cur_stage + 1, last_stage + 1):\n self.logger.info('Evolving to stage {}'.format(stage))\n\n evolution_filepath = '{}/{}-ups.sql'.format(self.sql_dirpath, stage)\n evolution_script = open(evolution_filepath).read()\n\n cur.execute(evolution_script)\n cur.execute(MARK_DDL_EVOLUTION % stage)\n conn.commit()\n\n self.logger.info('Evolved.')\n\n cur.close()\n\n def devolve(self):\n pass\n","sub_path":"lamarck.py","file_name":"lamarck.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"30510587","text":"from flask import Flask, render_template, request, url_for, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom datetime import datetime\nfrom extract_mitre import *\nfrom mitre_map import *\nimport pandas as pd\nfrom itertools import zip_longest\nimport requests\nimport json\n\nmitre_info = extract_mitre()\nmitre_map = mitre_map()\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n#database class to store playbook data\nclass playbook(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\tplay_name = db.Column(db.String(200), nullable=False)\n\tplaybook_description = db.Column(db.String(500), default=\" \")\n\tplaybook_owner = db.Column(db.String(200), default=\"SGS\")\n\tplaybook_type = db.Column(db.String(500), default=\" \")\n\tdate_added = db.Column(db.DateTime, default=datetime.utcnow())\n\tdate_updated = db.Column(db.DateTime)\n\tdetection_technology = db.Column(db.String(500), default=\" \")\n\tcategory = db.Column(db.String(500), default=\" \")\n\tsubcategory = db.Column(db.String(500), default=\" \")\n\tmitre_tactic = db.Column(db.String(300), default=\" \")\n\tmitre_id = db.Column(db.String(200), default=\" \")\n\tmitre_os = db.Column(db.String(500), default=\" \")\n\tsplunk_query = db.Column(db.String, default=\" \")\n\trun_frequency = db.Column(db.String(200), default=\" \")\n\tanalyst_action = db.Column(db.String(), default=\" \")\n\tdeleted = db.Column(db.Integer, default=0)\n\n\t#mitre data tables to be stored after pulled from mitre github\n\tmitre_info_description = db.Column(db.String(), default=\" \")\n\tmitre_info_name = db.Column(db.String(), default=\" \")\n\tmitre_info_url = db.Column(db.String(), default=\" \")\n\tmitre_info_tactic = db.Column(db.String(), default=\" \")\n\n\tdef __repr__(self):\n\t\treturn \"\" % self.id\n\n@app.route('/', methods=['GET'])\ndef index():\n\tplays = playbook.query.filter_by(deleted=0).all()\n\treturn render_template('index.html', plays=plays)\n\n@app.route('/play/', methods=['GET'])\ndef play(id):\n\tplays = playbook.query.get_or_404(id)\n\treturn render_template('play.html', plays=plays)\n\n@app.route('/add_play.html', methods=['GET', 'POST'])\ndef add_play():\n\tdetection_technology = [\n\t\t\t\"splunk1\",\n\t\t\t\"splunk2\",\n\t\t\t\"splunk3\",\n\t\t\t\"Micro... No\"\n\t\t\t]\n\tcategory = [\n\t\t\t\"category1\",\n\t\t\t\"category2\",\n\t\t\t\"category3\"\n\t\t\t]\n\tplaybook_type = [\n\t\t\t\t\"type1\",\n\t\t\t\t\"type2\",\n\t\t\t\t\"type3\"\n\t\t\t\t]\n\tsubcategory = [\n\t\t\t\t\"subcategory1\",\n\t\t\t\t\"subcategory2\",\n\t\t\t\t\"subcategory3\"\n\t\t\t\t]\n\tif request.method == 'POST':\n\t\t#storing form fields in variable to add to database\n\t\tplay_name = request.form['play_name']\n\t\tplaybook_owner = request.form['playbook_owner']\n\t\tdetection_technology = request.form['detection_technology']\n\t\tplaybook_description = request.form['playbook_description']\n\t\tplaybook_type = request.form['playbook_type']\n\t\tcategory = request.form['category']\n\t\tsubcategory = request.form['subcategory']\n\t\tmitre_id = request.form['mitre_id']\n\t\tsplunk_query = request.form['splunk_query']\n\t\trun_frequency = request.form['run_frequency']\n\t\tanalyst_action = request.form['analyst_action']\n\t\tdeleted = 0\n\n\t\t#try to get mitre info unless there is an error\n\t\t#github might be not working or the data might be changed to wrong format\n\t\ttry:\n\t\t\tmitre_info_name = mitre_info.get_name(mitre_id)\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tmitre_info_description = mitre_info.get_description(mitre_id)\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tmitre_info_url = mitre_info.get_url(mitre_id)\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tmitre_info_tactic = mitre_info.get_kill_chain_phase(mitre_id)\n\t\texcept:\n\t\t\tpass\n\t\ttry:\n\t\t\tmitre_os = mitre_info.get_platforms(mitre_id)\n\t\texcept:\n\t\t\tpass\n\n\t\t#adding fields to database\n\t\tnew_play = playbook(play_name=play_name, \n\t\t\t\t\t\t\tplaybook_owner=playbook_owner,\n\t\t\t\t\t\t\tdetection_technology=detection_technology,\n\t\t\t\t\t\t\tplaybook_description=playbook_description,\n\t\t\t\t\t\t\tplaybook_type=playbook_type,\n\t\t\t\t\t\t\tcategory=category,\n\t\t\t\t\t\t\tsubcategory=subcategory,\n\t\t\t\t\t\t\tmitre_id=mitre_id,\n\t\t\t\t\t\t\tmitre_os=mitre_os,\n\t\t\t\t\t\t\tsplunk_query=splunk_query,\n\t\t\t\t\t\t\trun_frequency=run_frequency,\n\t\t\t\t\t\t\tanalyst_action=analyst_action,\n\t\t\t\t\t\t\tmitre_info_name=mitre_info_name,\n\t\t\t\t\t\t\tmitre_info_description=mitre_info_description,\n\t\t\t\t\t\t\tmitre_info_url=mitre_info_url,\n\t\t\t\t\t\t\tmitre_info_tactic=mitre_info_tactic,\n\t\t\t\t\t\t\tdeleted=deleted\n\t\t\t\t\t\t\t)\n\n\t\tdb.session.add(new_play)\n\t\tdb.session.commit()\n\n\t\treturn redirect('add_play.html')\n\telse:\n\t\tplays = playbook.query.order_by(playbook.date_added).all()\n\t\treturn render_template(\"add_play.html\", category=category, subcategory=subcategory, playbook_type=playbook_type, detection_technology=detection_technology)\n\n#function to update a play if needed. All user input fields can be updated as necessary.\n@app.route('/update/', methods=['POST', 'GET'])\ndef update_play(id):\n\tdetection_technology = [\n\t\t\t\"splunk1\",\n\t\t\t\"splunk2\",\n\t\t\t\"splunk3\",\n\t\t\t\"Micro... No\"\n\t\t\t]\n\tcategory = [\n\t\t\t\"category1\",\n\t\t\t\"category2\",\n\t\t\t\"category3\"\n\t\t\t]\n\tplaybook_type = [\n\t\t\t\t\"type1\",\n\t\t\t\t\"type2\",\n\t\t\t\t\"type3\"\n\t\t\t\t]\n\tsubcategory = [\n\t\t\t\t\"subcategory1\",\n\t\t\t\t\"subcategory2\",\n\t\t\t\t\"subcategory3\"\n\t\t\t\t]\n\tplays = playbook.query.get_or_404(id)\n\n\tif request.method == 'POST':\n\t\tplays.play_name = request.form['play_name']\n\t\tplays.playbook_owner = request.form['playbook_owner']\n\t\tplays.detection_technology = request.form['detection_technology']\n\t\tplays.date_updated = datetime.utcnow()\n\t\tplays.playbook_description = request.form['playbook_description']\n\t\tplays.playbook_type = request.form['playbook_type']\n\t\tplays.category = request.form['category']\n\t\tplays.subcategory = request.form['subcategory']\n\t\tplays.mitre_id = request.form['mitre_id']\n\t\tplays.splunk_query = request.form['splunk_query']\n\t\tplays.run_frequency = request.form['run_frequency']\n\t\tplays.analyst_action = request.form['analyst_action']\n\n\t\ttry:\n\t\t\tdb.session.commit()\n\t\t\treturn redirect('../play/'+str(id))\n\t\texcept:\n\t\t\treturn \"There was an issue with your request\"\n\n\telse:\n\t\treturn render_template('update.html', plays=plays, category=category, subcategory=subcategory, playbook_type=playbook_type, detection_technology=detection_technology)\n\n@pb.route('/map.html', methods=['GET','POST'])\ndef map():\n\ttactics = mitre_map.get_tactics()\n\t#creating pandas dataframe\n\tdf = pd.DataFrame.from_dict(tactics, orient='index').T\n\tdf.replace(to_replace=[None], value=\" \", inplace=True)\n\n\t#function to find Mitre IDs in database and highlight cells with IDs present\n\tdef custom_styles(val):\n\t\tplays = Playbook.query.filter_by(deleted=0).all()\n\t\tfor play in plays:\n\t\t\tmitre_id = play.mitre_id.split(\",\")\n\t\t\t# price column styles\n\t\t\tfor mitre_id1 in mitre_id:\n\t\t\t\t#extracting mitre IDs from playbook string\n\t\t\t\ttry:\n\t\t\t\t\tid_list = re.findall(r\"(TA\\d+|T\\d+)[^\\d+\\.\\d+]\", mitre_id1)\n\t\t\t\t\tid_sub_list = re.findall(r\"\\d+\\.\\d+\", mitre_id1)\n\t\t\t\t\tval_id = re.findall(r\"(TA\\d+|T\\d+)[^\\d+\\.\\d+]\", val)\n\t\t\t\t\tval_sub_id = re.findall(r\"\\d+\\.\\d+\", val)\n\t\t\t\t\t#iterating through the list of IDs in id_list\n\t\t\t\t\tfor item in id_list:\n\t\t\t\t\t\t#if an ID is found, turn the background blue\n\t\t\t\t\t\tif item == val_id[0]:\n\t\t\t\t\t\t\treturn \"background-color: #3498DB\"\n\t\t\t\t\tfor item in id_sub_list:\n\t\t\t\t\t\tif item == val_sub_id[0]:\n\t\t\t\t\t\t\treturn \"background-color: #3498DB\"\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t#if there is no ID in database, turn background white\n\t\treturn \"background-color: white\"\n\t#defining table format\n\tdf = df.style.set_properties(**{'white-space': 'pre-wrap','font-size': '11pt','background-color': '#edeeef','border-color': 'black','border-style' :'solid' ,'border-width': '1px','border-collapse':'collapse'}).applymap(custom_styles).render()\n\n\treturn render_template('map.html', tables=[df])\n\n#delete play by ID name. Delete button added to play page\n@app.route('/deleted/', methods=['GET','POST'])\ndef deleted(id):\n\tplays = playbook.query.get_or_404(id)\n\tif request.method == 'POST':\n\t\tupdated_deleted = playbook.query.filter_by(id=plays.id).update(dict(deleted=1))\n\t\tdb.session.commit()\n\t\treturn redirect('/')\n\n@app.route('/archive.html', methods=['GET','POST'])\ndef archive():\n\tplays = playbook.query.filter_by(deleted=1).all()\n\treturn render_template('archive.html', plays=plays)\n\n@app.route('/unarchive/', methods=['GET','POST'])\ndef unarchive(id):\n\tplays = playbook.query.get_or_404(id)\n\tif request.method == 'POST':\n\t\tupdated_deleted = playbook.query.filter_by(id=plays.id).update(dict(deleted=0))\n\t\tdb.session.commit()\n\t\treturn redirect('/')\n\nif __name__ == '__main__':\n\tapp.run(debug=True)\n","sub_path":"playbook.py","file_name":"playbook.py","file_ext":"py","file_size_in_byte":8439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"169459541","text":"import random\nimport numpy as np\nimport math\nfrom Role import Role\n\n\ndef create_game(args):\n number_of_user, number_of_edge, epsilon = args.user, args.edge, args.epsilon\n number_of_chs = np.array([random.randint(args.min_chs, args.max_chs) for x in range(number_of_edge)])\n cpu = np.array([random.uniform(args.min_cpu, args.max_cpu) * math.pow(10, 9) for x in range(number_of_edge)])\n H = [[round(np.random.rayleigh(np.sqrt(2 / np.pi) * math.pow(10, -3)), 5) for y in range(number_of_edge)] for x\n in range(number_of_user)]\n d_cpu = np.array([random.uniform(1.5, 2.5) * math.pow(10, 9) for x in range(number_of_user)])\n player = Role(number_of_edge=number_of_edge, number_of_user=number_of_user, epsilon=epsilon,\n number_of_chs=number_of_chs, cpu=cpu, d_cpu=d_cpu, H=H)\n player.initial_DAG()\n # player.initial_config_DAG()\n return player\n\n","sub_path":"MOBIHOC/game_generate.py","file_name":"game_generate.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"63597056","text":"\n\n#calss header\nclass _TREMOLO():\n\tdef __init__(self,): \n\t\tself.name = \"TREMOLO\"\n\t\tself.definitions = [u'when singing or playing an instrument, a shaking sound that is achieved by repeating the same note extremely quickly or by playing two notes very quickly, one after the other']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_tremolo.py","file_name":"_tremolo.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"70823369","text":"import numpy as np\nimport pygame\nclass TargetSystem():\n def __init__(self, manager):\n self.manager = manager\n manager.archetypes[('vel','pos','target')] = 'targetSystem'\n manager.collections['targetSystem'] = []\n\n def execute(self):\n dt = self.manager.clock.get_time()/1000\n for i in self.manager.collections['targetSystem']:\n vel = i.get('vel')\n pos = i.get('pos')\n target = i.get('target')\n\n vec = target.value - pos.value\n\n\n vecnorm = np.linalg.norm(vec)\n\n # vec is less-than or equal to 10\n if vecnorm > 50:\n vec = vec * 50 / vecnorm\n\n vel.value = vec\n","sub_path":"animation/systems/target_system.py","file_name":"target_system.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"165658576","text":"import asyncio\nfrom itertools import chain\nfrom logging import getLogger\n\nimport discord\n\nfrom .exceptions import VoiceClientNotFound\nfrom .node.client import Node as OriginNode\n\nlog = getLogger(\"discodo.DPYClient\")\n\n\nclass NodeClient(OriginNode):\n def __init__(self, DPYClient, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.DPYClient = DPYClient\n\n async def destroy(self, *args, **kwargs):\n log.infmo(f\"destroying Node {self.URL}\")\n await super().destroy(*args, **kwargs)\n\n if self in self.DPYClient.Nodes:\n self.DPYClient.Nodes.remove(self)\n\n\nclass DPYClient:\n def __init__(self, client):\n self.client = client\n self.loop = client.loop or asyncio.get_event_loop()\n\n self.Nodes = []\n self.__register_event()\n\n def __register_event(self):\n if hasattr(self.client, \"on_socket_response\"):\n originFunc = self.client.on_socket_response\n else:\n originFunc = None\n\n @self.client.event\n async def on_socket_response(*args, **kwargs):\n self.loop.create_task(self.discord_socket_response(*args, **kwargs))\n\n if originFunc:\n return await originFunc()\n\n async def discord_socket_response(self, payload):\n if payload[\"t\"] == \"VOICE_SERVER_UPDATE\":\n VC = self.getVC(payload[\"d\"][\"guild_id\"])\n SelectNodes = [VC.Node] if VC else [self.getBestNode()]\n else:\n SelectNodes = self.Nodes\n\n if SelectNodes:\n await asyncio.wait(\n [Node.discordDispatch(payload) for Node in SelectNodes],\n return_when=\"ALL_COMPLETED\",\n )\n\n def register_node(self, *args, **kwargs):\n return self.loop.create_task(self._register_event(*args, **kwargs))\n\n async def _register_event(self, *args, **kwargs):\n await self.client.wait_until_ready()\n\n kwargs[\"user_id\"] = self.client.user.id\n Node = NodeClient(self, *args, **kwargs)\n log.info(f\"registering Node {Node.URL}\")\n\n self.Nodes.append(Node)\n\n Node.emitter.on(\"VC_DESTROYED\", self._vc_destroyed)\n\n return self\n\n async def _vc_destroyed(self, Data):\n guild = self.client.get_guild(int(Data[\"guild_id\"]))\n ws = self.__get_websocket(guild.shard_id)\n\n await ws.voice_state(guild.id, None)\n\n def getBestNode(self):\n SortedWithPerformance = sorted(\n [Node for Node in self.Nodes if Node.connected.is_set()],\n key=lambda Node: len(Node.voiceClients),\n )\n\n return SortedWithPerformance[0]\n\n @property\n def voiceClients(self):\n return {\n ID: Value\n for ID, Value in list(\n chain.from_iterable(\n [\n Node.voiceClients.items()\n for Node in self.Nodes\n if Node.connected.is_set()\n ]\n )\n )\n }\n\n def getVC(self, guild):\n if isinstance(guild, discord.Guild):\n guild = guild.id\n\n return self.voiceClients.get(int(guild))\n\n def __get_websocket(self, id):\n if isinstance(self.client, discord.AutoShardedClient):\n return self.client.shards[id].ws\n elif not self.client.shard_id or self.client.shard_id == id:\n return self.client.ws\n\n async def connect(self, channel):\n log.info(f\"connecting to {channel.id} of {channel.guild.id}\")\n if not hasattr(channel, \"guild\"):\n raise ValueError\n\n ws = self.__get_websocket(channel.guild.shard_id)\n\n await ws.voice_state(channel.guild.id, channel.id)\n\n async def disconnect(self, guild):\n log.info(f\"disconnecting voice of {guild.id} without destroying\")\n ws = self.__get_websocket(guild.shard_id)\n\n await ws.voice_state(guild.id, None)\n\n async def destroy(self, guild):\n log.info(f\"destroying voice client of {guild.id}\")\n if not guild.id in self.voiceClients:\n raise VoiceClientNotFound\n\n vc = self.getVC(guild.id)\n ws = self.__get_websocket(guild.shard_id)\n\n await ws.voice_state(guild.id, None)\n await vc.destroy()\n","sub_path":"discodo/DPYClient.py","file_name":"DPYClient.py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"316295269","text":"\"\"\"\n This instrument description contains information\n that is instrument-specific and abstracts out how we obtain\n information from the data file\n\"\"\"\n#pylint: disable=invalid-name, too-many-instance-attributes, line-too-long, bare-except\nfrom __future__ import absolute_import, division, print_function\nimport sys\nimport os\nimport math\nimport logging\n\n# Import mantid according to the application configuration\nfrom . import ApplicationConfiguration\napplication_conf = ApplicationConfiguration()\nsys.path.insert(0, application_conf.mantid_path)\nimport mantid.simpleapi as api\n\n# Option to use the slow flipper logs rather than the Analyzer/Polarizer logs\nUSE_SLOW_FLIPPER_LOG = True\n\n# Constants\nh = 6.626e-34 # m^2 kg s^-1\nm = 1.675e-27 # kg\n\n\nclass Instrument(object):\n \"\"\"\n Instrument class. Holds the data handling that is unique to a specific instrument.\n \"\"\"\n n_x_pixel = 304\n n_y_pixel = 256\n huber_x_cut = 6.5\n peak_range_offset = 50\n tolerance = 0.05\n pixel_width = 0.0007\n instrument_name = \"REF_M\"\n instrument_dir = \"/SNS/REF_M\"\n file_search_template = \"/SNS/REF_M/*/nexus/REF_M_%s\"\n legacy_search_template = \"/SNS/REF_M/*/data/REF_M_%s\"\n\n # Filtering\n pol_state = 'SF1'\n pol_veto = 'SF1_Veto'\n ana_state = 'SF2'\n ana_veto = 'SF2_Veto'\n\n def __init__(self):\n logging.debug(\"Creating instrument\")\n\n def dummy_filter_cross_sections(self, ws):\n \"\"\"\n Filter events according to an aggregated state log.\n :param str file_path: file to read\n\n BL4A:SF:ICP:getDI\n\n 015 (0000 1111): SF1=OFF, SF2=OFF, SF1Veto=OFF, SF2Veto=OFF\n 047 (0010 1111): SF1=ON, SF2=OFF, SF1Veto=OFF, SF2Veto=OFF\n 031 (0001 1111): SF1=OFF, SF2=ON, SF1Veto=OFF, SF2Veto=OFF\n 063 (0011 1111): SF1=ON, SF2=ON, SF1Veto=OFF, SF2Veto=OFF\n \"\"\"\n state_log = \"BL4A:SF:ICP:getDI\"\n states = {'Off_Off': 15,\n 'On_Off': 47,\n 'Off_On': 31,\n 'On_On': 63}\n cross_sections = []\n\n for pol_state in states:\n try:\n _ws = api.FilterByLogValue(InputWorkspace=ws, LogName=state_log, TimeTolerance=0.1,\n MinimumValue=states[pol_state],\n MaximumValue=states[pol_state], LogBoundary='Left',\n OutputWorkspace='%s_entry-%s' % (ws.getRunNumber(), pol_state))\n _ws.getRun()['cross_section_id'] = pol_state\n cross_sections.append(_ws)\n except:\n logging.error(\"Could not filter %s: %s\", pol_state, sys.exc_info()[1])\n\n return cross_sections\n\n def load_data(self, file_path):\n \"\"\"\n Load a data set according to the needs ot the instrument.\n Returns a WorkspaceGroup with any number of cross-sections.\n\n :param str file_path: path to the data file\n \"\"\"\n # Be careful with legacy data\n is_legacy = file_path.endswith(\".nxs\")\n if is_legacy or not USE_SLOW_FLIPPER_LOG:\n base_name = os.path.basename(file_path)\n _xs_list = api.MRFilterCrossSections(Filename=file_path,\n PolState=self.pol_state,\n AnaState=self.ana_state,\n PolVeto=self.pol_veto,\n AnaVeto=self.ana_veto,\n CrossSectionWorkspaces=\"%s_entry\" % base_name)\n # Only keep good workspaced and get rid of the rejected events\n xs_list = [ws for ws in _xs_list if not ws.getRun()['cross_section_id'].value == 'unfiltered']\n else:\n ws = api.LoadEventNexus(Filename=file_path, OutputWorkspace=\"raw_events\")\n xs_list = self.dummy_filter_cross_sections(ws)\n\n return xs_list\n\n @classmethod\n def scattering_angle(cls, ws, peak_position=None):\n \"\"\"\n Determine the scattering angle in degrees\n \"\"\"\n return api.MRGetTheta(ws, SpecularPixel=peak_position) * 180.0 / math.pi\n\n @classmethod\n def mid_q_value(cls, ws):\n \"\"\"\n Get the mid q value, at the requested wl mid-point.\n :param workspace ws: Mantid workspace\n \"\"\"\n wl = ws.getRun().getProperty('LambdaRequest').value[0]\n theta_d = Instrument.scattering_angle(ws) * math.pi / 180.0\n return 4.0*math.pi*math.sin(theta_d) / wl\n\n @classmethod\n def mid_q_value_from_data(cls, data_object):\n \"\"\"\n Get the mid q value, at the requested wl mid-point.\n :param workspace ws: Mantid workspace\n \"\"\"\n theta_d = (data_object.dangle - data_object.dangle0) / 2.0 * math.pi / 180.0\n return 4.0*math.pi*math.sin(theta_d) / data_object.lambda_center\n\n @classmethod\n def scattering_angle_from_data(cls, data_object):\n \"\"\"\n Compute the scattering angle from a CrossSectionData object, in degrees.\n #TODO: this will go away once we keep the workspace\n\n @param data_object: CrossSectionData object\n \"\"\"\n theta_d = (data_object.dangle - data_object.dangle0) / 2.0\n theta_d += ((data_object.dpix - data_object.configuration.peak_position) * cls.pixel_width) * 180.0 / math.pi / (2.0 * data_object.dist_sam_det)\n return theta_d\n\n def check_direct_beam(self, ws, peak_position=None):\n \"\"\"\n Determine whether this data is a direct beam\n \"\"\"\n sangle = ws.getRun().getProperty(\"SANGLE\").getStatistics().mean\n theta = self.scattering_angle(ws, peak_position)\n huber_x = ws.getRun().getProperty(\"HuberX\").getStatistics().mean\n return not ((theta > self.tolerance or sangle > self.tolerance) and huber_x < self.huber_x_cut)\n\n def direct_beam_match(self, scattering, direct_beam, skip_slits=False):\n \"\"\"\n Verify whether two data sets are compatible.\n \"\"\"\n if scattering.number == direct_beam.number \\\n or ((direct_beam.scattering_angle > self.tolerance \\\n or direct_beam.sangle > self.tolerance) and direct_beam.huber_x < self.huber_x_cut):\n logging.error(\"Run %s may not be a direct beam\", direct_beam.number)\n\n if math.fabs(scattering.lambda_center-direct_beam.lambda_center) < self.tolerance \\\n and (skip_slits or \\\n (math.fabs(scattering.slit1_width-direct_beam.slit1_width) < self.tolerance \\\n and math.fabs(scattering.slit2_width-direct_beam.slit2_width) < self.tolerance \\\n and math.fabs(scattering.slit3_width-direct_beam.slit3_width) < self.tolerance)):\n return True\n return False\n\n @classmethod\n def get_info(cls, workspace, data_object):\n \"\"\"\n Retrieve information that is specific to this particular instrument\n\n @param workspace: Mantid workspace\n @param data_object: CrossSectionData object\n \"\"\"\n data = workspace.getRun()\n data_object.lambda_center = data['LambdaRequest'].value[0]\n data_object.dangle = data['DANGLE'].value[0]\n data_object.dangle0 = data['DANGLE0'].value[0]\n data_object.dpix = data['DIRPIX'].value[0]\n data_object.slit1_width = data['S1HWidth'].value[0]\n data_object.slit2_width = data['S2HWidth'].value[0]\n data_object.slit3_width = data['S3HWidth'].value[0]\n data_object.huber_x = data['HuberX'].getStatistics().mean\n\n data_object.sangle = data['SANGLE'].value[0]\n\n data_object.dist_sam_det = data['SampleDetDis'].value[0]*1e-3\n data_object.dist_mod_det = data['ModeratorSamDis'].value[0]*1e-3+data_object.dist_sam_det\n data_object.dist_mod_mon = data['ModeratorSamDis'].value[0]*1e-3-2.75\n\n # Get these from instrument\n data_object.pixel_width = float(workspace.getInstrument().getNumberParameter(\"pixel-width\")[0]) / 1000.0\n data_object.n_det_size_x = int(workspace.getInstrument().getNumberParameter(\"number-of-x-pixels\")[0]) # 304\n data_object.n_det_size_y = int(workspace.getInstrument().getNumberParameter(\"number-of-y-pixels\")[0]) # 256\n data_object.det_size_x = data_object.n_det_size_x * data_object.pixel_width # horizontal size of detector [m]\n data_object.det_size_y = data_object.n_det_size_y * data_object.pixel_width # vertical size of detector [m]\n\n # The following active area used to be taken from instrument.DETECTOR_REGION\n data_object.active_area_x = (8, 295)\n data_object.active_area_y = (8, 246)\n\n # Convert to standard names\n data_object.direct_pixel = data_object.dpix\n data_object.angle_offset = data_object.dangle0\n\n def integrate_detector(self, ws, specular=True):\n \"\"\"\n Integrate a workspace along either the main direction (specular=False) or\n the low-resolution direction (specular=True.\n\n :param ws: Mantid workspace\n :param specular bool: if True, the low-resolution direction is integrated over\n \"\"\"\n ws_summed = api.RefRoi(InputWorkspace=ws, IntegrateY=specular,\n NXPixel=self.n_x_pixel, NYPixel=self.n_y_pixel,\n ConvertToQ=False,\n OutputWorkspace=\"ws_summed\")\n\n integrated = api.Integration(ws_summed)\n integrated = api.Transpose(integrated)\n return integrated\n","sub_path":"reflectivity_ui/interfaces/data_handling/instrument.py","file_name":"instrument.py","file_ext":"py","file_size_in_byte":9630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"46017853","text":"##import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom openpyxl import load_workbook\r\nimport os\r\nos.chdir('C:/Users/bag019/Desktop')\r\nwb = load_workbook('Database Fo Real.xlsx',data_only=True)\r\nws_from = wb.get_sheet_by_name('WP AI')\r\n##data = 'Database Fo Real.csv'\r\n##x = pd.read_csv(data, header = 0, usecols = ['S.ID'])\r\n##y = pd.read_csv(data,header = 0, usecols = ['Average 1'], index_col = ['Average 1'])\r\n##\r\nmy_list_y = []\r\nmy_list_x = []\r\nfor j in range(3,1837):\r\n data_from1 = ws_from.cell(row = j, column = 5).value\r\n my_list_x.append(data_from1)\r\nfor j in range(3,1837):\r\n data_from2 = ws_from.cell(row = j, column = 2).value\r\n my_list_y.append(data_from2)\r\nind = np.arange[len(my_list_x)]\r\nplt.bar(ind, my_list_y)\r\nplt.show()\r\n##print (my_list_x)\r\n##print (my_list_y)\r\n##plt.bar(my_list_x,my_list_y,label = 'Yah doode')\r\n##plt.show()\r\n\r\n","sub_path":"Pandas read CSV.py","file_name":"Pandas read CSV.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"579372523","text":"#!/usr/bin/env python\nimport os\nfrom app import create_app,db\nfrom app.models import User,Role,Permission,Post,Comment\nfrom flask_script import Manager,Shell\nfrom flask_migrate import Migrate,MigrateCommand,upgrade\n\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nmanager = Manager(app)\nmigrate = Migrate(app,db)\n\ndef make_shell_context():\n return dict(app=app,db=db,User=User,Role=Role,Post=Post,Comment=Comment)\n\nmanager.add_command('shell',Shell(make_context=make_shell_context))\nmanager.add_command('db',MigrateCommand)\n\n@app.cli.command()\ndef deploy():\n \"\"\"Run deployment tasks.\"\"\"\n # migrate database to latest revision\n upgrade()\n\n # create or update user roles\n Role.insert_roles()\n\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"549775288","text":"from ..database import database\n\n\nclass Settings(database.Model):\n\n __tablename__ = 'urs_settings'\n\n id_setting = database.Column(\n database.Integer,\n primary_key=True,\n autoincrement=True\n )\n setting = database.Column(\n database.String(50),\n nullable=False\n )\n value = database.Column(\n database.String(50),\n nullable=True\n )\n\n def __init__(self, setting, value):\n self.id_setting = None\n self.setting = setting\n self.value = value\n\n def __repr__(self):\n print(f'')\n","sub_path":"client_side/desktop/backend/memory/model/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"396274673","text":"# Copyright (C) 2017 Google Inc.\n# Licensed under http://www.apache.org/licenses/LICENSE-2.0 \n\n\"\"\"Create missing snapshot revisions.\n\nCreate Date: 2017-01-05 23:10:37.257161\n\"\"\"\n# disable Invalid constant name pylint warning for mandatory Alembic variables.\n# pylint: disable=invalid-name\n\nfrom ggrc.migrations.utils.snapshot_revisions import handle_objects\n\n\n# revision identifiers, used by Alembic.\nrevision = '579239d161e1'\ndown_revision = '353e5f281799'\n\n\ndef upgrade():\n \"\"\"Create missing revisions for snapshottable objects.\"\"\"\n\n # copy pasted from ggrc.snapshoter.rules.Types.all\n snapshot_objects = sorted([\n \"AccessGroup\",\n \"Clause\",\n \"Control\",\n \"DataAsset\",\n \"Facility\",\n \"Market\",\n \"Objective\",\n \"OrgGroup\",\n \"Product\",\n \"Section\",\n \"Vendor\",\n\n \"Policy\",\n \"Regulation\",\n \"Standard\",\n \"Contract\",\n\n \"System\",\n \"Process\",\n\n \"Risk\",\n \"Threat\",\n ])\n\n handle_objects(snapshot_objects)\n\n\ndef downgrade():\n \"\"\"Data correction migrations can not be downgraded.\"\"\"\n","sub_path":"src/ggrc/migrations/versions/20170105231037_579239d161e1_create_missing_snapshot_revisions.py","file_name":"20170105231037_579239d161e1_create_missing_snapshot_revisions.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"228105497","text":"import sys\nt = int(sys.stdin.readline().rstrip())\n\ndef dfs(start):\n visit[start] = True\n for i in range(n+2):\n if adj[start][i] == 1 and visit[i] == False:\n dfs(i)\n\nfor _ in range(t):\n n = int(sys.stdin.readline().rstrip())\n node = [list(map(int, sys.stdin.readline().rstrip().split())) for i in range(n + 2)]\n adj = [ [0] * (n+2) for _ in range(n+2)]\n visit = [False]*(n+2)\n for i in range(n+2):\n for j in range(n+2):\n if i==j:\n continue\n if abs(node[i][0]-node[j][0])+abs(node[i][1]-node[j][1])<=1000:\n adj[i][j] = 1\n adj[j][i] = 1\n dfs(0)\n if visit[n+1] == True:\n print(\"happy\")\n else:\n print(\"sad\")","sub_path":"class3/9205-1.py","file_name":"9205-1.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"72242882","text":"'''\nWrite a script that creates a list of all unique values in a list. For example:\n\nlist_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]\nunique_list = [55, 'hi', 4, 13]\n\n'''\n\nunique_list = []\nlist_ = [1, 2, 6, 55, 2, 'hi', 4, 6, 1, 13]\n\nprint(\"This is the original list: \" + str(list_))\n\nfor item in range(len(list_)):\n if list_.count(list_[item]) == 1:\n unique_list.append(list_[item])\n\n# [unique_list.append(item) for item in list_ if list_.count(list_[item]) == 1]\n# not sure why this list comprehension does not work\n\nprint(\"This is the unique list: \" + str(unique_list))\n","sub_path":"03_more_datatypes/2_lists/03_10_unique.py","file_name":"03_10_unique.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"358252556","text":"import math\n\ndef toAngle(D, V):\n constant = (D*9.8)/(V**2)\n try:\n answer = (math.asin(constant)/2.0)*(180.0/math.pi)\n except Exception:\n return 'Impossible'\n return answer\n\ndef parseLine(string, lineNumber):\n numbers = string.split(\" \")\n V = float(numbers[0].strip())\n D = float(numbers[1].strip())\n answer = toAngle(D,V)\n return \"Case #\" + str(lineNumber) + \": \" + str(answer)+'\\n'\n\n#read and handle input\nf = open('slater.txt')\nout = open('slateroutput.txt','w')\nnumtests = int(f.readline())\ni=1\nfor line in f:\n out.write(parseLine(line,i))\n i+=1","sub_path":"googlegames13/slater/slater.py","file_name":"slater.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"255757175","text":"#\n#introdução a programação de computadores\n#Professor: Jucimar JR\n#EQUIPE 3\n#\n#Antonio Rodrigues de Souza Neto - 1615310028\n#Caio de Oliveira Martins - 1615310031\n#Calebe Roberto Chaves da Silva Rebello - 1615310043\n#Felipe Henrique Bastos Costa - 1615310032\n#Lorene da Silva Marques - 1615310013\n#\n\nnome = (\"Informe seu nome: \")\n\nwhile (len(nome) <=3):\n print (\"Seu nome deve ter mais de 3 caracteres!\")\n nome = input(\"Informe seu nome: \")\n\nidade = int(input(\"Informe sua idade: \"))\n\nwhile (idade <0 or idade >150):\n print (\"A idade deve ser entre 0 e 150!\")\n nome = input(\"Informe seu nome: \")\n \nsalario = float(input(\"Informe seu salario: \"))\n\nwhile (salario <=0):\n print (\"Seu salario deve ser maior que 0\")\n salario = float(input(\"Informe seu salario: \"))\n\nsexo = input(\"Informe seu sexo:(m/f)\")\n\nwhile (sexo != \"m\" or sexo != \"f\"):\n print(\"Informação Errada!\")\n sexo = input(\"Informe seu sexo:(m/f)\")\n \nestado_civil = input(\"Informe seu estado civil: (s,c,d,v)\")\n\nwhile (estado_civil !=\"s\" or estado_civil !=\"c\" or estado_civil !=\"d\" or estado_civil !=\"v\"):\n print(\"Informação Errada!\")\n estado_civil = input(\"Informe seu estado civil: (s,c,d,v)\")\n \nprint (\"Informações aceitas!\")\nprint (\"Nome: \",nome, \"Idade: \",idade, \"Salario: \", salario, \"Sexo: \",sexo, \"Estado_Civil: \",estado_civil)\n","sub_path":"lista3/ipc_lista3.03.py","file_name":"ipc_lista3.03.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"287141695","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process(\"corr\")\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\n### conditions\nprocess.load(\"Configuration.StandardSequences.FrontierConditions_GlobalTag_cff\")\nprocess.GlobalTag.globaltag = 'GR_R_53_LV6::All'\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(500)\n)\n\nfrom HeavyIonsAnalysis.Configuration.CommonFunctions_cff import *\noverrideCentrality(process)\nprocess.HeavyIonGlobalParameters = cms.PSet(\n centralityVariable = cms.string(\"HFtowers\"),\n# nonDefaultGlauberModel = cms.string(\"Hydjet_2760GeV\"),\n centralitySrc = cms.InputTag(\"hiCentrality\")\n )\n\n#Trigger Selection\n### Comment out for the timing being assuming running on secondary dataset with trigger bit selected already\nimport HLTrigger.HLTfilters.hltHighLevel_cfi\nprocess.hltHIMB = HLTrigger.HLTfilters.hltHighLevel_cfi.hltHighLevel.clone()\nprocess.hltHIMB.HLTPaths = ['HLT_HIMinBiasHfOrBSC_*'] # for allphysics\nprocess.hltHIMB.andOr = cms.bool(True)\nprocess.hltHIMB.throw = cms.bool(False)\n\nprocess.hltHIUCC = HLTrigger.HLTfilters.hltHighLevel_cfi.hltHighLevel.clone()\nprocess.hltHIUCC.HLTPaths = ['HLT_HIUCC*_*'] # for allphysics\nprocess.hltHIUCC.andOr = cms.bool(True)\nprocess.hltHIUCC.throw = cms.bool(False)\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n#'/store/user/davidlw/HIMinBiasUPC/PR2011_MBUCC_TRKANASKIM_official_v1/71a7d203fff2b3f389673e6fdd587ee0/hiGoodColl_1023_1_S52.root'\n#'root://xrootd.unl.edu//store/user/appeltel/HIMinBiasUPC/pixelTrackReco_devel_v0/a236e4501225ae15b3601563d612abb5/pixeltrackreco_6_1_qSR.root'\n'/store/user/davidlw/HIMinBiasUPC/Skim_rereco_pixeltracks_v1/4b65ef5aa7a26abf1f962cd25f7df02d/hiMB_88_1_qbI.root'\n )\n# secondaryFileNames = cms.untracked.vstring('')\n )\nprocess.load(\"FlowCorrAna.DiHadronCorrelationAnalyzer.epetadeco_cff\")\n\nprocess.options = cms.untracked.PSet(\n wantSummary = cms.untracked.bool(True)\n)\n\n# Additional output definition\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string('epetadeco.root')\n )\n\nprocess.epetadeco_ana_HI_UCC_nocorr = process.epetadeco_ana_HI_nocorr.clone()\n\n#process.ana_hfp_cent002 = cms.Path(process.hltHIUCC*process.epetadeco_ana_HI_hfp_cent002)\n#process.ana_hfm_cent002 = cms.Path(process.hltHIUCC*process.epetadeco_ana_HI_hfm_cent002)\n#process.ana_hfp_cent05 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfp_cent05)\n#process.ana_hfm_cent05 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfm_cent05)\nprocess.ana_hfp_cent510 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfp_cent510)\nprocess.ana_hfm_cent510 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfm_cent510)\n#process.ana_hfp_cent1020 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfp_cent1020)\n#process.ana_hfm_cent1020 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfm_cent1020)\n#process.ana_hfp_cent2030 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfp_cent2030)\n#process.ana_hfm_cent2030 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfm_cent2030)\n#process.ana_hfp_cent3040 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfp_cent3040)\n#process.ana_hfm_cent3040 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfm_cent3040)\n#process.ana_hfp_cent4050 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfp_cent4050)\n#process.ana_hfm_cent4050 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfm_cent4050)\n#process.ana_hfp_cent5060 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfp_cent5060)\n#process.ana_hfm_cent5060 = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_hfm_cent5060)\n#process.ana_nocorr = cms.Path(process.hltHIMB*process.epetadeco_ana_HI_nocorr)\n#process.ana_nocorr_ucc = cms.Path(process.hltHIUCC*process.epetadeco_ana_HI_UCC_nocorr)\n","sub_path":"DiHadronCorrelationAnalyzer/cfg/epetadeco_cfg.py","file_name":"epetadeco_cfg.py","file_ext":"py","file_size_in_byte":3978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"3351366","text":"\"\"\"\nCopyright:tncet.com\nAuthor:crayon\nDate:2021-06-11\n与采集箱通信程序\n\"\"\"\n\n\nimport socket\nimport datetime\nimport time\nimport queue\nimport threading\nimport os\nimport configparser\nimport signal\nfrom binascii import *\nfrom tsdbutils import input_data\nimport numpy as np\nimport math as m\n\ndir_root = os.path.dirname(os.path.abspath(__file__)) \ncf = configparser.ConfigParser()\ncf.read(dir_root+'/config.cfg')\nq = queue.Queue(maxsize=0)\n\ndef crc16Add(raw_cmd):\n #计算数据长度、地址码、命令字和数据域的和\n crc = int(raw_cmd[2:4],16) + int(raw_cmd[4:6],16) + int(raw_cmd[6:8],16) + int(raw_cmd[8:10],16)\n crc = hex(crc)\n crc = crc[2:].zfill(2)\n res = '{}{}'.format(raw_cmd,crc)\n return res\n\ndef run(work_status_num):\n #与采集箱通信发送指令\n try:\n while True:\n if work_status_num.value == 0:\n print('kill current pid')\n pid = os.getpid()\n os.kill(pid, signal.SIGKILL)\n s = socket.socket()\n tcp_address = (cf.get('dbox','ip'),int(cf.get('dbox','port'))) \n s.connect(tcp_address)\n channel_code = cf.get('channel-conf','channel_code')\n channel_code = channel_code.split(',')\n for channel in channel_code:\n channel = hex(int(channel))[2:]\n channel = channel.upper()\n raw_cmd = '770500{:0>2}04'.format(channel)\n begin_sample_cmd = crc16Add(raw_cmd)\n s.send(bytes.fromhex(str(begin_sample_cmd)))\n time.sleep(0.04)\n s.close()\n except Exception as e:\n print(e)\n\n\n\n\ndef recv(work_status_num,target_period_num):\n #接收数据\n s = socket.socket()\n tcp_address = (cf.get('dbox','ip'),int(cf.get('dbox','port'))) \n s.connect(tcp_address)\n s.settimeout(40)\n saveQdata_thread = threading.Thread(target=saveQdata,args=(target_period_num, ))\n saveQdata_thread.start()\n while True:\n try:\n if work_status_num.value == 0:\n print('kill current pid')\n pid = os.getpid()\n os.kill(pid, signal.SIGKILL)\n buff = s.recv(10240)\n response = buff\n responseList = response.split(b'w\\x11')\n responseList = [x for x in responseList if x != b'']\n for response in responseList:\n # channelSignal = response[0:2].hex()\n if len(response) != 16:\n print('数据发生错误',response.hex())\n continue\n else:\n dataDict = data_process(response)\n q.put(dataDict)\n except Exception as e:\n print(e)\n\ndef saveQdata(target_period_num):\n #聚合与储存数据\n dataBufferList = []\n key = int(datetime.datetime.now().timestamp())\n while True:\n try:\n if q.empty():\n time.sleep(0.01)\n continue\n data = q.get()\n dataBufferList.append(data)\n #判断数据聚合在target_period时间中\n channel_code = cf.get('channel-conf','channel_code')\n channel_code = channel_code.split(',')\n target_period = target_period_num.value\n if (int(data['sampleTime'] / 1000) - key) < int(target_period):\n continue\n if len(dataBufferList) == 0:\n continue\n saveDataList = []\n for channel in channel_code:\n dataChannelDict = {}\n datax = []\n datay = []\n for dataDict in dataBufferList:\n # print('dataDict',dataDict)\n dataSDict = {}\n if dataDict['channelId'] == int(channel):\n datax.append(dataDict['xData'])\n datay.append(dataDict['yData'])\n dataChannelDict['sampleTime'] = dataDict['sampleTime'] \n if (len(datax) == 0 or len(datay) == 0):\n continue\n dataChannelDict['channelId'] = channel \n dataChannelDict['xData'] = np.around(np.average(datax), 5)\n dataChannelDict['yData'] = np.around(np.average(datay), 5)\n saveDataList.append(dataChannelDict)\n input_data(saveDataList)\n key = int(datetime.datetime.now().timestamp())\n dataBufferList = []\n except Exception as e:\n print(e)\n\n \n\n\n\ndef getSingleData(channel,work_status_num):\n #获取单通道数据\n s = socket.socket()\n tcp_address = (cf.get('dbox','ip'),int(cf.get('dbox','port'))) \n s.connect(tcp_address)\n \n channel = hex(int(channel))[2:]\n channel = channel.upper()\n raw_cmd = '770500{:0>2}04'.format(channel)\n begin_sample_cmd = crc16Add(raw_cmd)\n s.send(bytes.fromhex(str(begin_sample_cmd)))\n s.settimeout(15)\n rawData = s.recv(10240)\n dataNewDict = {}\n dataDict = data_process(rawData)\n dataNewDict['1'] = dataDict['xData']\n dataNewDict['2'] = dataDict['yData']\n dataNewDict = str(dataNewDict)\n res = str(dataDict['xData']) + ',' + str(dataDict['yData'])\n return res\n\n\n\n\n\ndef data_process(data):\n #解析数据\n channelStartPoint = 1\n channelId = data[channelStartPoint - 1: channelStartPoint+ 1].hex()\n dataDict = {}\n xDataSymbol = data[channelStartPoint + 2:channelStartPoint+3].hex()\n xDataInt = data[channelStartPoint+ 3:channelStartPoint + 4].hex()\n xDataFloat = data[channelStartPoint+ 4:channelStartPoint+ 6].hex()\n xData = '{}.{}'.format(xDataInt,xDataFloat)\n xData = m.radians(float(xData))\n xData = round(xData,5)\n if xDataSymbol == '00':\n xData = float(xData)\n elif xDataSymbol == '10':\n xData = -float(xData)\n yDataSymbol = data[channelStartPoint + 6:channelStartPoint + 7].hex()\n yDataInt = data[channelStartPoint + 7:channelStartPoint + 8].hex()\n yDataFloat = data[channelStartPoint + 8:channelStartPoint + 10].hex()\n yData = '{}.{}'.format(yDataInt,yDataFloat)\n yData = m.radians(float(yData))\n yData = round(yData,5)\n if yDataSymbol == '00':\n yData = float(yData)\n elif yDataSymbol == '10':\n yData = -float(yData)\n dataDict['channelId'] = int(channelId, 16)\n dataDict['xData'] = xData\n dataDict['yData'] = yData\n dataDict['sampleTime'] = int(datetime.datetime.now().timestamp()*1000)\n return dataDict\n","sub_path":"data_box.py","file_name":"data_box.py","file_ext":"py","file_size_in_byte":6479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"421905833","text":"import numpy as np\n\n\ndef unpickle(datafile):\n import pickle\n with open('./Cifar/cifar/cifar/' + datafile, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n\ndef Cifar_data():\n data1 = unpickle('data_batch_1')\n data2 = unpickle('data_batch_2')\n data3 = unpickle('data_batch_3')\n data4 = unpickle('data_batch_4')\n data5 = unpickle('data_batch_5')\n\n # 读取5次data-batch 然后将五个数据整合到一个矩阵\n X1 = data1[b'data']\n label1 = data1[b'labels']\n X1 = np.array(X1)\n np.set_printoptions(threshold='nan')\n new1 = X1.reshape(-1, 3, 32, 32).transpose([0,2,3,1]).astype(\"float\")\n\n X2 = data2[b'data']\n label2 = data2[b'labels']\n X2 = np.array(X2)\n np.set_printoptions(threshold='nan')\n new2 = X2.reshape(-1, 3, 32, 32).transpose([0,2,3,1]).astype(\"float\")\n\n X3 = data3[b'data']\n label3 = data3[b'labels']\n X3 = np.array(X3)\n np.set_printoptions(threshold='nan')\n new3 = X3.reshape(-1, 3, 32, 32).transpose([0,2,3,1]).astype(\"float\")\n\n X4 = data4[b'data']\n label4 = data4[b'labels']\n X4 = np.array(X4)\n np.set_printoptions(threshold='nan')\n new4 = X4.reshape(-1, 3, 32, 32).transpose([0,2,3,1]).astype(\"float\")\n\n X5 = data5[b'data']\n label5 = data5[b'labels']\n X5 = np.array(X5)\n np.set_printoptions(threshold='nan')\n new5 = X5.reshape(-1, 3, 32, 32).transpose([0,2,3,1]).astype(\"float\")\n\n X_train = np.concatenate([new1, new2, new3, new4, new5])\n Y_train = np.concatenate([label1, label2, label3, label4, label5])\n\n test = unpickle('test_batch')\n test_x = test[b'data']\n test_y = test[b'labels']\n X_test = np.array(test_x)\n Y_test = np.array(test_y)\n X_test = X_test.reshape(-1, 3, 32, 32).transpose([0,2,3,1]).astype(\"float\")\n\n Y_temp_train = np.zeros((50000, 10), np.float32)\n for i in range(50000):\n cls = Y_train[i]\n Y_temp_train[i, cls] = 1\n\n Y_temp_test = np.zeros((10000, 10), np.float32)\n for i in range(10000):\n cls = Y_test[i]\n Y_temp_test[i, cls] = 1\n\n Y_test = Y_temp_test\n Y_train = Y_temp_train\n\n return X_train, Y_train, X_test, Y_test\n","sub_path":"lab2/Cifar.py","file_name":"Cifar.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"55823273","text":"import cv2\nimport os\nimport numpy as np\n\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\ndatapath = 'dataset'\n\n\ndef getFaceWithId(path):\n imagepaths = [os.path.join(datapath, f) for f in os.listdir(datapath) if os.path.isfile(os.path.join(datapath, f))]\n faces, Ids = [], []\n for imagepath in imagepaths:\n faceimg = cv2.imread(imagepath, cv2.IMREAD_GRAYSCALE)\n faces.append(np.asarray(faceimg, dtype=np.uint8))\n id = os.path.split(imagepath)[1].split('.')[1]\n Ids.append(id)\n return faces, Ids\n\n\ndef train():\n faces, Ids = getFaceWithId(datapath)\n recognizer.train(faces, np.asarray(Ids, dtype=np.int32))\n recognizer.save('trainningDataset/trainningdata.yml')\n print(\"Trainning complete!!!\")\n cv2.destroyAllWindows()\n\n#train()\n\n\n\n","sub_path":"trainner.py","file_name":"trainner.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"495796812","text":"def last2(str):\n if len(str) <= 2: \n return 0\n last = str[len(str)-2:]\n count = 0\n \n for i in range(len(str)-2) :\n if str[i] + str[i+1] == last:\n count += 1\n \n return count\n\nif __name__ == '__main__':\n print(last2(\"aaaaa\"))\n","sub_path":"Warmup2/last2.py","file_name":"last2.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"349341062","text":"\"\"\"\n##### Task 1\nCreate a \"Madlib\" that has the users enter in a variety of noun/verb/adjectives.\nWhen they press a button, it should update the contents of a label to display\nthe completed madlib.\nWhat is a madlib? Visit https://www.madlibs.com/printables/ to see some Madlibs\nyou might use in your assignment\n\"\"\"\n\n# Space exploration Madlib\n\nimport tkinter as tk \nfrom tkinter import *\n\nwindow = tk.Tk()\n\nout1 = StringVar()\nout1.set(\"(name)\")\nout2 = StringVar()\nout2.set(\"(silly word)\")\nout3 = StringVar()\nout3.set(\"(number)\")\nout4 = StringVar()\nout4.set(\"(adjective)\")\nout5 = StringVar()\nout5.set(\"(noun)\")\nout6 = StringVar()\nout6.set(\"(adjective)\")\nout7 = StringVar()\nout7.set(\"(relative)\")\nout8 = StringVar()\nout8.set(\"(adjective)\")\nout9 = StringVar()\nout9.set(\"(verb)\")\nout10 = StringVar()\nout10.set(\"(adjective)\")\nout11 = StringVar()\nout11.set(\"(adjective)\")\n\n\ndef fill():\n d1 = e1.get()\n \n f1.delete(0,END)\n f1.insert(0,d1)\n\n d2 = e2.get()\n \n f2.delete(0,END)\n f2.insert(0,d2)\n\n d3 = e3.get()\n \n f3.delete(0,END)\n f3.insert(0,d3)\n\n d4 = e4.get()\n \n f4.delete(0,END)\n f4.insert(0,d4)\n\n d5 = e5.get()\n \n f5.delete(0,END)\n f5.insert(0,d5)\n\n d6 = e6.get()\n \n f6.delete(0,END)\n f6.insert(0,d6)\n\n d7 = e7.get()\n \n f7.delete(0,END)\n f7.insert(0,d7)\n\n d8 = e8.get()\n \n f8.delete(0,END)\n f8.insert(0,d8)\n\n d9 = e9.get()\n \n f9.delete(0,END)\n f9.insert(0,d9)\n\n d10 = e10.get()\n \n f10.delete(0,END)\n f10.insert(0,d10)\n\n d11 = e11.get()\n \n f11.delete(0,END)\n f11.insert(0,d11)\n\n\ne1 = Entry(window, width = 15)\ne2 = Entry(window, width = 15)\ne3 = Entry(window, width = 15)\ne4 = Entry(window, width = 15)\ne5 = Entry(window, width = 15)\ne6 = Entry(window, width = 15)\ne7 = Entry(window, width = 15)\ne8 = Entry(window, width = 15)\ne9 = Entry(window, width = 15)\ne10 = Entry(window, width = 15)\ne11 = Entry(window, width = 15)\n\nf1 = Entry(window, width = 15, textvariable=out1)\nf2 = Entry(window, width = 15, textvariable=out2)\nf3 = Entry(window, width = 15, textvariable=out3)\nf4 = Entry(window, width = 15, textvariable=out4)\nf5 = Entry(window, width = 15, textvariable=out5)\nf6 = Entry(window, width = 15, textvariable=out6)\nf7 = Entry(window, width = 15, textvariable=out7)\nf8 = Entry(window, width = 15, textvariable=out8)\nf9 = Entry(window, width = 15, textvariable=out9)\nf10 = Entry(window, width = 15, textvariable=out10)\nf11 = Entry(window, width = 15, textvariable=out11)\n\nt1 = Label(window, text = \"(name)\")\nt2 = Label(window, text = \"(silly word)\")\nt3 = Label(window, text = \"(number)\")\nt4 = Label(window, text = \"(adjective)\")\nt5 = Label(window, text = \"(noun)\")\nt6 = Label(window, text = \"(adjective)\")\nt7 = Label(window, text = \"(relative)\")\nt8 = Label(window, text = \"(adjective)\")\nt9 = Label(window, text = \"(verb)\")\nt10 = Label(window, text = \"(adjective)\")\nt11 = Label(window, text = \"(adjective)\")\n\np1 = Label(window, text =\"Hello my name is astronaut\")\np2 = Label(window, text =\"I am on my way to planet\")\np3 = Label(window, text =\"I will be gone for\")\np4 = Label(window, text =\"days\")\np5 = Label(window, text =\"I am very\")\np6 = Label(window, text =\"about the trip but I will miss my\")\np7 = Label(window, text =\"I have heard that the atmosphere there is\")\np8 = Label(window, text =\"Luckily my\")\np9 = Label(window, text =\"packed me a jacket to keep me\")\np10 = Label(window, text =\"When I land on the planet I will\")\np11 = Label(window, text =\"for joy\")\np12 = Label(window, text =\"I am\")\np13 = Label(window, text =\"to walk on another planet.\")\np14 = Label(window, text =\"I could not be more\")\np15 = Label(window, text =\"for this trip!\")\n\n\nb1 = Button(window, text=\"Click to see complete story!\", command=fill)\n\n\n\nt1.grid(row = 1, column = 1)\ne1.grid(row = 1, column = 2)\nt2.grid(row = 2, column = 1)\ne2.grid(row = 2, column = 2)\nt3.grid(row = 3, column = 1)\ne3.grid(row = 3, column = 2)\nt4.grid(row = 4, column = 1)\ne4.grid(row = 4, column = 2)\nt5.grid(row = 5, column = 1)\ne5.grid(row = 5, column = 2)\nt6.grid(row = 6, column = 1)\ne6.grid(row = 6, column = 2)\nt7.grid(row = 7, column = 1)\ne7.grid(row = 7, column = 2)\nt8.grid(row = 8, column = 1)\ne8.grid(row = 8, column = 2)\nt9.grid(row = 9, column = 1)\ne9.grid(row = 9, column = 2)\nt10.grid(row = 10, column = 1)\ne10.grid(row = 10, column = 2)\nt11.grid(row = 11, column = 1)\ne11.grid(row = 11, column = 2)\n\nb1.grid(row = 6, column = 3)\n\n\np1.grid(row = 1, column = 4, sticky = E)\nf1.grid(row = 1, column = 5, sticky = W)\n\np2.grid(row = 2, column = 4, sticky = E)\nf2.grid(row = 2, column = 5, sticky = W)\n\np3.grid(row = 3, column = 4, sticky = E)\nf3.grid(row = 3, column = 5, sticky = W)\np4.grid(row = 3, column = 6, sticky = W)\n\np5.grid(row = 4, column = 4, sticky = E)\nf4.grid(row = 4, column = 5, sticky = W)\np6.grid(row = 4, column = 6, sticky = W)\nf5.grid(row = 4, column = 7, sticky = W)\n\np7.grid(row = 5, column = 4, sticky = E)\nf6.grid(row = 5, column = 5, sticky = W)\n\np8.grid(row = 6, column = 4, sticky = E)\nf7.grid(row = 6, column = 5, sticky = W)\np9.grid(row = 6, column = 6, sticky = W)\nf8.grid(row = 6, column = 7, sticky = W)\n\np10.grid(row = 7, column = 4, sticky = E)\nf9.grid(row = 7, column = 5, sticky = W)\np11.grid(row = 7, column = 6, sticky = W)\n\np12.grid(row = 8, column = 4, sticky = E)\nf10.grid(row = 8, column = 5, sticky = W)\np13.grid(row = 8, column = 6, sticky = W)\n\np14.grid(row = 9, column = 4, sticky = E)\nf11.grid(row = 9, column = 5, sticky = W)\np15.grid(row = 9, column = 6, sticky = W)\n\n\n\nwindow.mainloop()","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":5534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"144982597","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.home, name='home'),\n\n url(r'^tree/(?P[0-9]+)$', views.TreeView.as_view(), name='one_tree'),\n url(r'^trees$', views.list_tree, name='list_tree'),\n url(r'^tree/create$', views.create_tree, name='create_tree'),\n url(r'^tree/edit/(?P[0-9]+)$', views.edit_tree, name='edit_tree'),\n url(r'^tree/(?P[0-9]+)/delete$', views.delete_tree, name='delete_tree'),\n\n url(r'^people/add/(?P[0-9]+)', views.add_people, name='add_people'),\n url(r'^people/edit/(?P[0-9]+)', views.edit_people, name='edit_people'),\n url(r'^people/delete/(?P[0-9]+)', views.delete_people, name='delete_people'),\n]\n","sub_path":"genealogy/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"411164884","text":"from __future__ import division\nimport os\nimport sys\nimport tempfile\nimport typing\nimport warnings\n\nimport numpy as np\nimport soundfile\n\nimport audeer\n\nfrom audiofile.core.convert import convert_to_wav\nfrom audiofile.core.info import sampling_rate\nfrom audiofile.core.utils import (\n file_extension,\n MAX_CHANNELS,\n SNDFORMATS,\n)\n\n\ndef read(\n file: str,\n duration: float = None,\n offset: float = 0,\n always_2d: bool = False,\n dtype: str = 'float32',\n **kwargs,\n) -> typing.Tuple[np.array, int]:\n \"\"\"Read audio file.\n\n It uses :func:`soundfile.read` for WAV, FLAC, and OGG files.\n All other audio files are\n first converted to WAV by sox or ffmpeg.\n\n Args:\n file: file name of input audio file\n duration: return only a specified duration in seconds\n offset: start reading at offset in seconds\n always_2d: if ``True`` it always returns a two-dimensional signal\n even for mono sound files\n dtype: data type of returned signal,\n select from\n ``'float64'``,\n ``'float32'``,\n ``'int32'``,\n ``'int16'``\n kwargs: pass on further arguments to :func:`soundfile.read`\n\n Returns:\n * a two-dimensional array in the form\n ``[channels, samples]``.\n If the sound file has only one channel\n and ``always_2d=False``,\n a one-dimensional array is returned\n * sample rate of the audio file\n\n \"\"\"\n file = audeer.safe_path(file)\n tmpdir = None\n if file_extension(file) not in SNDFORMATS:\n # Convert file formats not recognized by soundfile to WAV first.\n #\n # NOTE: this is faster than loading them with librosa directly.\n # In addition, librosa seems to have an issue with the precission of\n # the returned magnitude\n # (https://github.com/librosa/librosa/issues/811).\n #\n # It might be the case that MP3 files will be supported by soundfile in\n # the future as well. For a discussion on MP3 support in the underlying\n # libsndfile see https://github.com/erikd/libsndfile/issues/258.\n with tempfile.TemporaryDirectory(prefix='audiofile') as tmpdir:\n tmpfile = os.path.join(tmpdir, 'tmp.wav')\n convert_to_wav(file, tmpfile, offset, duration)\n signal, sample_rate = soundfile.read(\n tmpfile,\n dtype=dtype,\n always_2d=always_2d,\n **kwargs,\n )\n else:\n if duration is not None or offset > 0:\n sample_rate = sampling_rate(file)\n if offset > 0:\n offset = np.ceil(offset * sample_rate) # samples\n if duration is not None:\n duration = int(np.ceil(duration * sample_rate) + offset) # samples\n signal, sample_rate = soundfile.read(\n file,\n start=int(offset),\n stop=duration,\n dtype=dtype,\n always_2d=always_2d,\n **kwargs,\n )\n # [samples, channels] => [channels, samples]\n signal = signal.T\n return signal, sample_rate\n\n\ndef write(\n file: str,\n signal: np.array,\n sampling_rate: int,\n bit_depth: int = 16,\n normalize: bool = False,\n **kwargs,\n):\n \"\"\"Write (normalized) audio files.\n\n Save audio data provided as an array of shape ``[channels, samples]``\n to a WAV, FLAC, or OGG file.\n ``channels`` can be up to 65535 for WAV,\n 255 for OGG,\n and 8 for FLAC.\n For monaural audio the array can be one-dimensional.\n\n It uses :func:`soundfile.write` to write the audio files.\n\n Args:\n file: file name of output audio file.\n The format (WAV, FLAC, OGG) will be inferred from the file name\n signal: audio data to write\n sampling_rate: sample rate of the audio data\n bit_depth: bit depth of written file in bit,\n can be 8, 16, 24 for WAV and FLAC files,\n and in addition 32 for WAV files\n normalize: normalize audio data before writing\n kwargs: pass on further arguments to :func:`soundfile.write`\n\n Raises:\n RuntimeError: for non-supported bit depth or number of channels\n\n \"\"\"\n file = audeer.safe_path(file)\n file_type = file_extension(file)\n\n # Check for allowed precisions\n if file_type == 'wav':\n depth_mapping = {\n 8: 'PCM_U8',\n 16: 'PCM_16',\n 24: 'PCM_24',\n 32: 'PCM_32',\n }\n elif file_type == 'flac':\n depth_mapping = {\n 8: 'PCM_S8',\n 16: 'PCM_16',\n 24: 'PCM_24',\n }\n if file_type in ['wav', 'flac']:\n bit_depths = sorted(list(depth_mapping.keys()))\n if bit_depth not in bit_depths:\n raise RuntimeError(\n f'\"bit_depth\" has to be one of '\n f'{\", \".join([str(b) for b in bit_depths])}.'\n )\n subtype = depth_mapping[bit_depth]\n else:\n subtype = None\n # Check if number of channels is allowed for chosen file type\n if signal.ndim > 1:\n channels = np.shape(signal)[0]\n else:\n channels = 1\n if channels > MAX_CHANNELS[file_type]:\n if file_type != 'wav':\n hint = \" Consider using 'wav' instead.\"\n else:\n hint = ''\n raise RuntimeError(\n \"The maximum number of allowed channels \"\n f\"for '{file_type}' is {MAX_CHANNELS[file_type]}.{hint}\"\n )\n if normalize:\n signal = signal / np.max(np.abs(signal))\n soundfile.write(file, signal.T, sampling_rate, subtype=subtype, **kwargs)\n","sub_path":"audiofile/core/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"305572692","text":"import math\nfrom operator import *\nimport pandas as pd\nimport numpy as np\nimport xlwt\nimport csv\nimport collections\n\ndef handle():\n return None\ndic1={}#放推荐列表的字典\ndic2={}#放真实观影记录\nif __name__ == '__main__':\n file1 = \"D:\\\\experiment\\\\第三次豆瓣\\\\测试4_K近邻=30\\\\对比实验\\\\热门_推荐结果_K-means.csv\"#推荐结果\n tmp_lst = []\n with open(file1, 'r', encoding='gbk', errors='ignore') as f:\n reader = csv.reader(f)\n for row in reader:\n tmp_lst.append(row)\n data1 = pd.DataFrame(tmp_lst[1:], columns=tmp_lst[0])\n #print(data1)\n\n train_data1 = np.array(data1) # np.ndarray()每个姓名转换为一个list[]\n # print(train_data)\n all_list1 = train_data1.tolist() # 转换list\n # print(all_list)\n for item in all_list1:\n # print(item)\n dic1.setdefault(int(item[2]), []).append(item[0]) # 将电影名加入对应用户的字典内,键为用户名,值为电影列表\n #这里的用户id读进来是str型需要强制转换为int型与dic2保持一致,并且方便后续用键取值\n print(dic1)\n\n\n file2 = \"D:\\\\experiment\\\\第三次豆瓣\\\\测试4_K近邻=30\\\\test\\\\热门_测试数据.csv\"\n data2=pd.read_csv(file2, encoding='gbk')\n #print(data2)\n\n train_data2 = np.array(data2) # np.ndarray()每个姓名转换为一个list[]\n # print(train_data)\n all_list2 = train_data2.tolist() # 转换list\n # print(all_list)\n for item in all_list2:\n # print(item)\n dic2.setdefault(item[0], []).append(item[2]) # 将电影名加入对应用户的字典内,键为用户名,值为电影列表\n print(dic2)\n precision_all=0\n recall_all=0\n all_num = 0\n for i in range(1,183,1):\n R_num=0\n T_num=0\n R_T=0\n if dic2.get(i) and dic1.get(i) is not None:\n all_num += 1\n for item in dic2[i]:#真实记录列表\n T_num+=1\n for item1 in dic1[i]:#推荐列表\n R_num+=1\n if item1 in dic2[i]:\n R_T+=1\n if R_num == 25:\n break\n else:\n continue\n precision = R_T/R_num*1.0\n recall = R_T/T_num*1.0\n print(\"第\", i, \"位用户的推荐准确率为:\", precision, \"召回率为:\", recall, \"一共中了:\", R_T)\n\n precision_all+=precision\n recall_all+=recall\n precision_all/=all_num\n recall_all/=all_num\n print(\"平均推荐准确率为:\", precision_all, \"平均召回率为:\", recall_all)\n #print(\"测试人数:\", num, \"准确率:\", precision_test, \"召回率:\", recall_test)\n #改变每位用户推荐列表的N值\n","sub_path":"recommend——豆瓣/对比实验——评测.py","file_name":"对比实验——评测.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"207723102","text":"#!/home/users/nedman/bin/python\r\n#encoding: iso-8859-2\r\n#\r\n# Polish SPOJ projects\r\n# \r\n# Marcin Niedziela \r\n\r\n\"\"\"\r\nNapisz funkcję:\r\n\r\nchar* string_merge(char *, char *);\r\nktóra sklei ze sobą dwa łańcuchy biorąc na przemian po jednym znaku z każdego łańcucha i umieści\r\nw nowej dynamicznie alokowanej tablicy znaków, do której zwróci wskaźnik. Należy wziąć po tyle\r\nznaków ile jest w krótszym łańcuchu. \r\n\r\nInput\r\nW pierwszej linii liczba testów t, w kolejnych liniach po dwa łańcuchy znaków odzielone spacją.\r\n\r\nOutput\r\nW każdej linii jeden łańcuch, wynik działania funkcji string_merge.\r\n\r\nExample\r\n\r\nInput:\r\n4\r\na bb\r\nabs sfd\r\newr w\r\nwqeqweqweq eqweqwe\r\n\r\nOutput:\r\nab\r\nasbfsd\r\new\r\nweqqewqewqewqe\r\n\"\"\"\r\n\r\nfrom sys import stdin, stdout\r\n\r\n__version__ = 0.4\r\n\r\nclass Main:\r\n def __init__(self):\r\n data = []\r\n data_append = data.append\r\n\r\n t = int(stdin.readline())\r\n while t:\r\n text = stdin.readline()\r\n data_append(self.string_merge(text))\r\n t -= 1\r\n\r\n stdout.write(''.join(data))\r\n\r\n\r\n def string_merge(self, text):\r\n a, b = text.split()\r\n length = len(a)\r\n if len(a) > len(b):\r\n length = len(b)\r\n\r\n merged = []\r\n merged_append = merged.append\r\n for i in range(0, length):\r\n merged_append(\"%s%s\" % (a[i], b[i]))\r\n\r\n return ''.join(merged)\r\n\r\n\r\nif __name__ == '__main__':\r\n Main()\r\n#end if\r\n","sub_path":"Python/spoj/617/617.py","file_name":"617.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"311050847","text":"#gofud gofudan cuyyy\nfrom bayarGoPay import BayarGopay\nfrom routeFind import Jarak, Location\n\ntotal = 0\nsaldo = 1000\n\ndef goFood(gopay):\n #array menu dan merchant\n menu = [[16000, 20500, 14000, 13000],\n [24000, 15500, 18000, 30000],\n [16000, 13000, 16000, 17500]]\n\n #array nama makanan\n menu2 = [['Geprek Crispy','Geprek Tomat','Geprek Matah','Geprek Mozzarella'],\n ['Takol','Kuro','Go-Milk','Siomay'],\n ['Si Eko','Roti Bakar','Cireng','Indomie']]\n\n #fungsi nama merchant\n def RestaurantFind(i):\n tempat = [\"Crisbar\", \"Salman\", \"Upnormal\"]\n return tempat[i]\n\n #interface awal\n print('GO-FOOD')\n print()\n print('Silahkan memilih merchant :')\n for i in range(3):\n print(str(i+1)+'. '+RestaurantFind(i))\n print()\n\n #pilih merchant\n merchant = int(input('Pilih merchant : '))\n n = merchant - 1\n\n #display menu dari merchant yang telah dipilih\n print('Restaurant yang dipilih :'+RestaurantFind(merchant-1))\n for i in range(4):\n print(str(i+1)+'. '+str(menu2[n][i])+': '+str(menu[n][i]))\n\n selesai = False\n while selesai == False:\n makan = int(input('Pilih makanan :'))\n m = makan - 1\n\n #menentukan jumlah makanan yang ingin dipesan\n jumlah = int(input('Tentukan jumlah :'))\n totalBayar = 0\n totalBayar += (menu[n][m]*jumlah)\n done = str(input('Apakah anda ingin memilih lagi? (Y/N) :'))\n if done == \"N\":\n selesai = True\n elif done == \"Y\":\n selesai = False\n print()\n\n #Input tujuan pengiriman\n listTujuan = Location()\n print(\"Nearby...\")\n for i in range(len(listTujuan)):\n print(\"[\", i+1, \"]\", listTujuan[i])\n \n #Input indeks tujuan pengiriman \n tujuan = int(input(\"Delivery location index: \"))-1 \n #Ongkos kirim adalah 1250/km\n ongkos = 1250\n\n biayaAntar = Jarak(n, tujuan)*ongkos\n totalBayar += biayaAntar\n\n print('Biaya makanan = ', totalBayar - biayaAntar) \n print('Biaya antar = ', biayaAntar)\n \n gopay = BayarGopay(gopay, totalBayar) \n \n return gopay\n\n\n ","sub_path":"goFood.py","file_name":"goFood.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"132948237","text":"import numpy\nimport re\n\ndef loadDataSet():\n\tpostingList = [\n\t\t['my','dog','has','flea','problems','help','please'],\n\t\t['maybe','not','take','him','to','dog','park','stupid'],\n\t\t['my','dalmation','is','so','cute','I','love','him'],\n\t\t['stop','posting','stupid','worthless','garbage'],\n\t\t['mr','licks','ate','my','steak','how','to','stop','him'],\n\t\t['quit','buying','worthless','dog','food','stupid']]\n\tclassVec = [0,1,0,1,0,1]\n\treturn postingList, classVec\n\ndef textParse(text):\n\t# regEx = re.compile('\\\\W*')\n\t# listOfToken = regEx.split(text)\n\tlistOfToken = re.split(r'\\W*',text)\n\treturn [tok.lower() for tok in listOfToken if len(tok) > 2]\n\ndef createVocabList(dataSet):\n\tvocabSet = set([])\n\tfor document in dataSet:\n\t\tvocabSet = vocabSet | set(document)\n\treturn list(vocabSet)\n\ndef setofWord2Vec(vocabList, inputSet):\n\treturnVec = [0] * len(vocabList)\n\tfor word in inputSet:\n\t\tif word in vocabList:\n\t\t\treturnVec[vocabList.index(word)] = 1\n\t\telse:\n\t\t\tprint(\"the word: %s is not in my Vocabulary\" % word)\n\treturn returnVec\n\ndef bagofWord2VecMN(vocabList, inputSet):\n\treturnVec = [0] * len(vocabList)\n\tfor word in inputSet:\n\t\tif word in vocabList:\n\t\t\treturnVec[vocabList.index(word)] += 1\n\t\telse:\n\t\t\tprint(\"the word: %s is not in my Vocabulary\" % word)\n\treturn returnVec\n\ndef naiveBayesTrainer(trainMatrix, trainCategoy):\n\tnumTrainDocs = len(trainMatrix)\n\tnumWords = len(trainMatrix[0])\n\tpAbusive = sum(trainCategoy) / float(numTrainDocs)\n\tp0Num = numpy.ones(numWords)\n\tp1Num = numpy.ones(numWords)\n\tp0Denom = 2.0\n\tp1Denom = 2.0\n\tfor i in range(numTrainDocs):\n\t\tif trainCategoy[i] == 1:\n\t\t\tp1Num += trainMatrix[i]\n\t\t\tp1Denom += sum(trainMatrix[i])\n\t\telse:\n\t\t\tp0Num += trainMatrix[i]\n\t\t\tp0Denom += sum(trainMatrix[i])\n\tp1Vec = numpy.log(p1Num / p1Denom)\n\tp0Vec = numpy.log(p0Num / p0Denom)\n\treturn p0Vec, p1Vec, pAbusive\n\ndef naiveBayesClassify(vec2Classify, p0Vec, p1Vec, pClass1):\n\tp1 = sum(vec2Classify * p1Vec) + numpy.log(pClass1)\n\tp0 = sum(vec2Classify * p0Vec) + numpy.log(1.0 - pClass1)\n\tif p1 > p0:\n\t\treturn 1\n\telse:\n\t\treturn 0\n\n\nif __name__ == '__main__':\n\tpostingList, classVec = loadDataSet()\n\tvocabList = createVocabList(postingList)\n\t# vec = setofWord2Vec(vocabList, posting[0])\n\ttrainMat = []\n\tfor postingDoc in postingList:\n\t\ttrainMat.append(setofWord2Vec(vocabList, postingDoc))\n\tp0V, p1V, pAb = naiveBayesTrainer(trainMat, classVec)\n\t# testEntry = ['love', 'my', 'dalmation']\n\ttestEntry = ['stupid', 'garbage']\n\ttestVec = numpy.array(setofWord2Vec(vocabList, testEntry))\n\tprint(testEntry, 'calssifed as:', naiveBayesClassify(testVec, p0V, p1V, pAb))\n","sub_path":"bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"137535157","text":"import pandas as pd\nimport haziris as hz\n\ndf = pd.DataFrame([\n [ 8, 12],\n [ 4, 5],\n [ 11, 14],\n [ 4, 5],\n [ 3, 3],\n [ 6, 7]\n ],\n columns = ['Age', 'Weight']\n)\n\noptions = {\n 'title': 'Age vs. Weight comparison',\n 'hAxis': {'title': 'Age', 'minValue': 0, 'maxValue': 15},\n 'vAxis': {'title': 'Weight', 'minValue': 0, 'maxValue': 15},\n 'legend': 'none'\n}\n\nhz.google_material_scatter_chart( df, \"google_material_scatter.html\", options )\n","sub_path":"haziris/examples/google_material_scatter.py","file_name":"google_material_scatter.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"236218362","text":"# https://www.reddit.com/r/dailyprogrammer/comments/75p1cs/20171011_challenge_335_intermediate_scoring_a/\nfrom itertools import combinations\n\n\nclass Hand(object):\n\n def __init__(self, str_cards, score=0):\n self.cards = [Card.parse_card(s) for s in str_cards.split(',')]\n self.score = score\n\n def __str__(self):\n return '{} {}'.format(self.cards, self.score)\n\n def calc_score(self):\n return self.fifteens_score() + self.run_score() + self.pairs_score() + self.flush_score() + self.nobs_score()\n\n def fifteens_score(self):\n fifteens = 0\n card_values = [min(c.value, 10) for c in self.cards]\n for x in range(1, len(self.cards) + 1):\n fifteens += 2 * len([c for c in combinations(card_values, x) if sum(c) == 15])\n return fifteens\n\n def run_score(self):\n sc = sorted(self.cards, key=lambda c: c.value)\n current_connection = 1\n best_connection = 1\n last_value = None\n\n for c in sc:\n if last_value is None:\n last_value = c.value\n continue\n\n if last_value + 1 != c.value:\n best_connection = current_connection\n current_connection = 1\n else:\n current_connection += 1\n\n last_value = c.value\n\n # If we've seen more than our previous best connection then update!\n if current_connection > best_connection:\n best_connection = current_connection\n\n return best_connection if best_connection >= 3 else 0\n\n def pairs_score(self):\n value_map = {}\n for c in self.cards:\n if c.value not in value_map:\n value_map[c.value] = 0\n value_map[c.value] += 1\n\n # 12 pts for four of a kind\n if 4 in value_map.values():\n return 12\n\n # 6 pts for three of a kind\n elif 3 in value_map.values():\n return 6\n\n # 2 pts for two of a kind\n elif 2 in value_map.values():\n return 2\n\n else:\n return 0\n\n def flush_score(self):\n suit_map = {}\n for c in self.cards:\n if c.suit not in suit_map:\n suit_map[c.suit] = 0\n suit_map[c.suit] += 1\n\n four_flush = len([c for c in self.cards[:-1] if c.suit == self.cards[0].suit]) == 4\n five_flush = 5 in suit_map.values()\n return 5 if five_flush else 4 if four_flush else 0\n\n def nobs_score(self):\n nob_suit = self.cards[-1].suit\n jacks = [c for c in self.cards[:-1] if c.value == Value.Jack and c.suit == nob_suit]\n return 1 if len(jacks) > 0 else 0\n\n\nclass Suit(object):\n Spade, Diamond, Heart, Club = range(1, 5)\n\n @staticmethod\n def parse_suit(s):\n suit_map = {'S': Suit.Spade, 'D': Suit.Diamond, 'H': Suit.Heart, 'C': Suit.Club}\n return suit_map[s]\n\n\nclass Value(object):\n Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King = range(1, 14)\n\n @staticmethod\n def parse_value(s):\n card_map = {'A': Value.Ace, '2': Value.Three, '3': Value.Three, '4': Value.Four, '5': Value.Five,\n '6': Value.Six, '7': Value.Seven, '8': Value.Eight, '9': Value.Nine, '10': Value.Ten,\n 'J': Value.Jack, 'Q': Value.Queen, 'K': Value.King}\n return card_map[s]\n\n\nclass Card(object):\n\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n\n def __repr__(self):\n return 'Value: {} Suit: {}'.format(self.value, self.suit)\n\n @staticmethod\n def parse_card(s):\n value = Value.parse_value(s[:-1])\n suit = Suit.parse_suit(s[-1])\n\n return Card(value, suit)\n\n\nh1 = Hand('5D,QS,JC,KH,AC', 0)\nh2 = Hand('8C,AD,10C,6H,7S', 0)\nh3 = Hand('AC,6D,5C,10C,8C', 0)\nprint(h1.calc_score()) # 10\nprint(h2.calc_score()) # 7\nprint(h3.calc_score()) # 4\n","sub_path":"medium/335i.py","file_name":"335i.py","file_ext":"py","file_size_in_byte":3899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"607018143","text":"#!/usr/bin/python\n# Solved by Bogdan Trif @ Completed on Thu, 13 Oct 2016, 20:53\n#The Euler Project https://projecteuler.net\n'''\nPath sum: two ways - Problem 81\nIn the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right,\nby only moving to the right and down, is indicated in red and is equal to 2427.\n\n 131 673 234 103 18\n 201 96 342 965 150\n 630 803 746 422 111\n 537 699 497 121 956\n 805 732 524 37 331\n\nFind the minimal path sum, in matrix.txt, a 31K text file containing a 80 by80 matrix,\nfrom the top left to the bottom right by only moving right and down.\n'''\nimport time\nfrom math import factorial\n# import pandas as pd\n# matrix=pd.read_csv('pb081_matrix.txt', sep=',',header=None)\n# print(matrix.values)\n#print(matrix)\n\ndef load_file(filename=\"pb081_matrix.txt\"):\n with open(filename) as f:\n matrix = [list(map(int, line.split(\",\"))) for line in f.readlines()]\n f.close()\n return matrix\n\nfrom numpy import genfromtxt\ndef load(filename):\n M = genfromtxt(filename, delimiter=',')\n rows = M.shape[0]\n cols = M.shape[1]\n return M\n\nprint(load(\"pb081_matrix.txt\"))\n\n# Get the file into the python matrix\nf = open ( 'pb081_matrix.txt' , 'r')\ntext = f.read()\n#print(text)\nf.close()\nmatrix=[]\nfor row in text.split('\\n'):\n matrix.append(list(map(int, row.split(',')))) # This maps the strings into ints on the run, SMART TECHNIQUE\n\n\ndef combinations(n , k):\n result = factorial(n)//(factorial(k)*factorial(n-k))\n return result\n\nprint('Path possibilities , huge huge number ',combinations(79*2,79),' ; ' ,len(str(combinations(79*2,79))), 'digits')\n\nprint('\\n----------------- TEST FOR Smaller MaTriX -----------------------\\n')\n\n# m =[[150, 650, 250, 100, 50], \\\n# [200, 100, 350, 950, 150],\\\n# [650, 800, 750, 400, 100],\\\n# [550, 700, 500, 150, 950],\\\n# [800, 750, 500, 50, 350]]\n\nm=[[131, 673, 234, 103, 18], \\\n [201, 96, 342, 965, 150],\\\n [630, 803, 746, 422, 111],\\\n [537, 699, 497, 121, 956],\\\n [805, 732, 524, 37, 331]]\n\n\nfor i in range(0,len(m)):\n for j in range(0, len(m)):\n if i ==0 and j==0 :\n #print(m[i][j])\n continue\n elif i == 0 and j > 0 :\n #print ( m[i][j-1] )\n m[i][j] += m[i][j-1]\n elif j == 0 and i > 0 :\n #print(m[i][j])\n m[i][j] += m[i-1][j]\n else:\n #print(m[i][j-1], m[i-1][j])\n m[i][j] += min( m[i][j-1], m[i-1][j] )\n print(m[i])\n\nprint('\\nThe minimum path sum is : ',m[-1][-1])\n\n\n\nprint ('\\n-------------------------- MY SOLUTION, DYNAMIC PROGRAMMING , pb67--------------------------------------\\n')\n\nt1 = time.time()\n\nfor i in range(0,len(matrix)):\n for j in range(0, len(matrix)):\n if i ==0 and j==0 :\n #print(matrix[i][j])\n continue\n elif i == 0 and j > 0 :\n #print ( matrix[i][j-1] )\n matrix[i][j] += matrix[i][j-1]\n elif j == 0 and i > 0 :\n #print(matrix[i][j])\n matrix[i][j] += matrix[i-1][j]\n else:\n #print(matrix[i][j-1], matrix[i-1][j])\n matrix[i][j] += min( matrix[i][j-1], matrix[i-1][j] )\n #print(matrix[i])\n\nprint('\\nThe minimum path sum is : ',matrix[-1][-1]) # 427337\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\nprint('\\n===============OTHER SOLUTIONS FROM THE EULER FORUM ==============')\nprint('\\n--------------------------SOLUTION 1 , VERY NICE , ELEGANT way to load a file, mmanimath, England --------------------------')\n\nt1 = time.time()\n\nfrom numpy import genfromtxt\n\ndef EP_81(filename):\n M = genfromtxt(filename, delimiter=',')\n rows = M.shape[0]\n cols = M.shape[1]\n for i in range(cols - 2, -1, -1):\n M[cols-1][i] += M[cols-1][i+1]\n M[i][cols-1] += M[i+1][cols-1]\n for i in range(rows-2, -1, -1):\n for j in range(cols-2, -1, -1):\n M[i][j] += min(M[i+1][j], M[i][j+1])\n return M[0][0]\n\nprint(EP_81('pb081_matrix.txt'))\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\nprint('\\n--------------------------SOLUTION 2 , NICE LOAD of file , jpulgarin , Columbia--------------------------')\n\nt1 = time.time()\n\n\ndef get(matrix, x, y):\n if x < 0 or y < 0:\n return 9999999999\n return matrix[x][y]\n\nmatrix = []\n\nwith open('pb081_matrix.txt', 'r') as f:\n for line in f:\n matrix.append([int(n) for n in line.split(',')])\n\nfor n in range(1, len(matrix)):\n for i in range(n):\n matrix[i][n] += min(get(matrix, i-1, n), get(matrix, i, n-1))\n matrix[n][i] += min(get(matrix, n-1, i), get(matrix, n, i-1))\n matrix[n][n] += min(matrix[n-1][n], matrix[n][n-1])\n\nprint (matrix[-1][-1])\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\nprint('\\n--------------------------SOLUTION 3 , FAST, markus.obi, Germany-------------------------')\n\n\nt1 = time.time()\n\n# Almost the same algorithm as used in Maximum path sum I & II.\n# Pretty straight forward and runs in 4 ms. For this algorithm c++ would be much more appropriate,\n# but python is so fast to code and for this small matrix fast enough.\n\ndef solve():\n filename = \"pb081_matrix.txt\"\n with open(filename) as f:\n matrix = [list(map(int, line.split(\",\"))) for line in f.readlines()]\n n_rows = len(matrix)\n n_columns = len(matrix[0])\n for i in range(n_rows):\n for j in range(n_columns):\n if i == j == 0:\n continue\n if i == 0:\n matrix[i][j] += matrix[i][j - 1]\n elif j == 0:\n matrix[i][j] += matrix[i - 1][j]\n else:\n matrix[i][j] += min(matrix[i - 1][j], matrix[i][j - 1])\n print(matrix[-1][-1])\n\n\nsolve()\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\n\n\nprint('\\n--------------------------SOLUTION 4 , -------------------------')\nt1 = time.time()\n\nfilename = \"pb081_matrix.txt\"\nwith open(filename) as f:\n matrix = [list(map(int, line.split(\",\"))) for line in f.readlines()]\n\n\nHEIGHT = len(matrix)\nWIDTH = len(matrix[0])\n\nfor h in range(HEIGHT - 1, -1, -1):\n for w in range(WIDTH - 1, -1, -1):\n add_list = []\n if w != WIDTH - 1:\n add_list.append(matrix[h][w + 1])\n if h != HEIGHT - 1:\n add_list.append(matrix[h+1][w])\n if len(add_list):\n matrix[h][w] += min(add_list)\n\nprint(add_list)\nprint (\"Result: \", matrix[0][0])\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\nprint('\\n--------------------------SOLUTION 5 , j123, Canada-------------------------')\n\n\nt1 = time.time()\n\nimport numpy as np\nwith open('pb081_matrix.txt', 'r') as f:\n V = np.add.accumulate(np.fromstring(next(f), sep=',', dtype=int))\n n = len(V)\n for R in f:\n R = np.add.accumulate(np.fromstring(R, sep=',', dtype=int, count=n))\n np.minimum(V[:-1], V[1:] - R[:-1], V[1:])\n V += R\nprint(V[-1])\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\nprint('\\n--------------------------SOLUTION 6 , -------------------------')\n\n\nt1 = time.time()\n\nfilename = \"pb081_matrix.txt\"\nwith open(filename) as f:\n matrix = [list(map(int, line.split(\",\"))) for line in f.readlines()]\n\nfor i in range(1,80):\n matrix[0][i] += matrix[0][i-1]\n matrix[i][0] += matrix[i-1][0]\n\nfor i in range(1,80):\n for j in range(1,80):\n matrix[i][j] += min(matrix[i-1][j], matrix[i][j-1])\n\nprint(matrix[79][79])\n\nt2 = time.time()\nprint('\\nCompleted in :', round((t2-t1)*1000,6), 'ms\\n\\n')\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Project EULER/pb081 Path sum - two ways.py","file_name":"pb081 Path sum - two ways.py","file_ext":"py","file_size_in_byte":7766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"37234089","text":"from __future__ import print_function\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass TwoLayerNet(object):\n \"\"\"\n A two-layer fully-connected neural network. The net has an input dimension of\n N, a hidden layer dimension of H, and performs classification over C classes.\n We train the network with a softmax loss function and L2 regularization on the\n weight matrices. The network uses a ReLU nonlinearity after the first fully\n connected layer.\n\n In other words, the network has the following architecture:\n\n input - fully connected layer - ReLU - fully connected layer - softmax\n\n The outputs of the second fully-connected layer are the scores for each class.\n \"\"\"\n\n def __init__(self, input_size, hidden_size, output_size, std=1e-4):\n \"\"\"\n Initialize the model. Weights are initialized to small random values and\n biases are initialized to zero. Weights and biases are stored in the\n variable self.params, which is a dictionary with the following keys:\n\n W1: First layer weights; has shape (D, H)\n b1: First layer biases; has shape (H,)\n W2: Second layer weights; has shape (H, C)\n b2: Second layer biases; has shape (C,)\n\n Inputs:\n - input_size: The dimension D of the input data.\n - hidden_size: The number of neurons H in the hidden layer.\n - output_size: The number of classes C.\n \"\"\"\n self.params = {}\n self.params['W1'] = std * np.random.randn(input_size, hidden_size)\n self.params['b1'] = np.zeros(hidden_size)\n self.params['W2'] = std * np.random.randn(hidden_size, output_size)\n self.params['b2'] = np.zeros(output_size)\n\n def loss(self, X, y=None, reg=0.0):\n \"\"\"\n Compute the loss and gradients for a two layer fully connected neural\n network.\n\n Inputs:\n - X: Input data of shape (N, D). Each X[i] is a training sample.\n - y: Vector of training labels. y[i] is the label for X[i], and each y[i] is\n an integer in the range 0 <= y[i] < C. This parameter is optional; if it\n is not passed then we only return scores, and if it is passed then we\n instead return the loss and gradients.\n - reg: Regularization strength.\n\n Returns:\n If y is None, return a matrix scores of shape (N, C) where scores[i, c] is\n the score for class c on input X[i].\n\n If y is not None, instead return a tuple of:\n - loss: Loss (data loss and regularization loss) for this batch of training\n samples.\n - grads: Dictionary mapping parameter names to gradients of those parameters\n with respect to the loss function; has the same keys as self.params.\n \"\"\"\n # Unpack variables from the params dictionary\n W1, b1 = self.params['W1'], self.params['b1']\n W2, b2 = self.params['W2'], self.params['b2']\n N, D = X.shape\n\n # Compute the forward pass\n scores = None\n #############################################################################\n # TODO: Perform the forward pass, computing the class scores for the input. #\n # Store the result in the scores variable, which should be an array of #\n # shape (N, C). #\n #############################################################################\n\n # The network is architected to have 2 layers, and each layer has the form of:\n # output = input * weight + bias\n\n # For layer 1 the \"input\" is the raw training data, and the output is a vector of\n # activated scores.\n\n # We take the dot product here because X is a matrix of NxD dimension and the weight \n # matrix is a matrix of DxH dimension, resulting in a matrix of NxH dimension\n layer1Output = X.dot(W1) + b1\n\n # Now we must use the ReLU to cull any negative values befor sending the layer 1\n # values off to layer 2.\n # Note this NP function operates on the entire vector of layer1Output\n layer2Input = np.maximum(0, layer1Output)\n\n # For layer 2 the \"input\" is the output from layer 1, and the output\n # is the final scores for the classification.\n\n # The dot product here works because layer2Input is a matrix of NxH dimension and the \n # weight matrix is a matrix of HxC dimension, resulting in a vector of NxC dimension\n layer2Output = layer2Input.dot(W2) + b2\n\n scores = layer2Output\n \n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n \n # If the targets are not given then jump out, we're done\n if y is None:\n return scores\n\n # Compute the loss\n loss = None\n #############################################################################\n # TODO: Finish the forward pass, and compute the loss. This should include #\n # both the data loss and L2 regularization for W1 and W2. Store the result #\n # in the variable loss, which should be a scalar. Use the Softmax #\n # classifier loss. #\n #############################################################################\n\n # First let us compute the softmax loss\n # Softmax loss has a formula where the loss for any individual data point is \n # L_i = -log(e^data_i/sumforallData(e^data_i))\n # To get loss for an entire set then, we sum all softmaxes, take the log after\n # and divide by the number of data points to get the average\n\n # Note we subtract the max off of the data set to ensure numeric stablity\n # See slide 34 of the w3-2_ML_logistic_regression deck from class\n\n exps = np.exp(scores - np.max(scores))\n # The keep axis and dimiension ensures we are summing across the right values in scores\n softMax = exps / np.sum(exps, axis=1, keepdims=True)\n\n # This arrange function just allows us to access the correct indices of softMax\n # in an efficient way\n loss = np.sum(-np.log(softMax[np.arange(N), y]))\n\n # To take the average, divide by the number of data points\n loss /= N\n\n # Now to add the L2 regulation\n # L2 regulation is calculated using the sum of the square of all the individual\n # elements of the weight matrix, and python does nice matrix squaring by just\n # multiplying the two matrices together!\n\n # Since we have two weight matrices, we can just calculate the L2 regulation for\n # both and sum them together\n W1Reg = np.sum(W1 * W1)\n W2Reg = np.sum(W2 * W2)\n\n totalReg = W1Reg + W2Reg\n\n # Now we just scale this by the given regulation hyper parameter 'reg' and add\n # it to the loss scalar.\n\n loss += reg * totalReg\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n # Backward pass: compute gradients\n grads = {}\n #############################################################################\n # TODO: Compute the backward pass, computing the derivatives of the weights #\n # and biases. Store the results in the grads dictionary. For example, #\n # grads['W1'] should store the gradient on W1, and be a matrix of same size #\n #############################################################################\n\n # We must work backwards from the softmax loss all the way back to the input, \n # taking partial derivatives along the way. \n\n ######################################\n # THE DERIVATIVE OF SOFTMAX LOSS WRT SCORES\n ######################################\n\n # This derivative was found to be computed according to this resource \n # https://deepnotes.io/softmax-crossentropy\n # The code snippet was also inspired from that resource\n\n # start by copying it over\n diLossdiScore = softMax\n diLossdiScore[np.arange(N) ,y] -= 1\n diLossdiScore /= N\n\n ######################################\n # THE DERIVATIVE OF LOSS WRT W2\n ######################################\n\n # We note that the scores are calculated as Score = W2*layer2Input + b2\n # The partial derrivative is then: \n # d Loss/d Score * d Score/d W2\n\n # We find d Score/d W2 as just the layer2Input vector! To calculate the \n # sum of all products of d Loss/d Score * d Score/d W2 across all elements, \n # we can transpose layer2Input and multiply it with diLossdiScore\n diLossdiW2 = layer2Input.T.dot(diLossdiScore)\n\n\n ######################################\n # THE DERIVATIVE OF LOSS WRT B2\n ######################################\n\n # We again note that the scores are calculated as Score = W2*layer2Input + b2\n # The partial derrivative is then: \n # d Loss/d Score * d Score/d B2\n\n # We find d Score/d B2 as just 1. To calculate the \n # sum of all products of d Loss/d Score * d Score/d W2 across all elements\n # we actually just end up summing d Loss/d Score\n\n diLossdiB2 = np.sum(diLossdiScore, axis=0)\n\n ######################################\n # THE DERIVATIVE OF LOSS WRT W1\n ######################################\n\n # We again note that the scores are calculated as Score = W2*layer2Input + b2\n # We also note that layer2Input is calculated as layer2Input = max(0, W1*inputData + B1)\n # The partial derivative then is \n # d Loss/d Score * d Score/d layer2Input * d layer2Input/d W1\n\n # We find d Loss/d Score * d Score/d layer2Input as just d Loss/d Score multiplied by W2\n\n # We find d layer2Input/d W1 as inputData, while also culling the negative values\n # because we did the ReLU between the two layers. Again we use transpose and multiply\n # do do an efficient sum.\n\n diLossdiW1 = softMax.dot(W2.T)\n positiveCull = diLossdiW1 * (layer1Output > 0)\n diLossdiW1 = X.T.dot(positiveCull)\n\n ######################################\n # THE DERIVATIVE OF LOSS WRT B2\n ######################################\n\n # Following the same observations as above, we find the partial derivative breakdown.\n # The partial derivative then is \n # d Loss/d Score * d Score/d layer2Input * d layer2Input/d B1\n\n # We find d Loss/d Score * d Score/d layer2Input as just d Loss/d Score multiplied by W2\n\n # We find d layer2Input/d W1 as 1, and end up finding the whole partial derivative as \n # just the sum of positive culled values of d Loss/d Score * d Score/d layer2Input using \n # transpost and multiply. \n\n diLossdiB1 = positiveCull.sum(axis=0)\n\n ######################################\n # ACCOUNTING FOR REGULATION\n ######################################\n\n # Because we added regulations to the losses, and they are functions of W1 and W2 respectively,\n # we must add these to diLossdiW1 and diLossdiW2. The derivates are trivial, and found to just\n # be solved using power rule. \n\n diLossdiW1 += reg * 2 * W1\n diLossdiW2 += reg * 2 * W2\n\n # Now we just append to the dictionary and return!\n grads = {'W1':diLossdiW1, 'b1':diLossdiB1, 'W2':diLossdiW2, 'b2':diLossdiB2}\n #############################################################################\n # END OF YOUR CODE #\n #############################################################################\n\n return loss, grads\n\n def train(self, X, y, X_val, y_val,\n learning_rate=1e-3, learning_rate_decay=0.95,\n reg=5e-6, num_iters=100,\n batch_size=200, verbose=False):\n \"\"\"\n Train this neural network using stochastic gradient descent.\n\n Inputs:\n - X: A numpy array of shape (N, D) giving training data.\n - y: A numpy array f shape (N,) giving training labels; y[i] = c means that\n X[i] has label c, where 0 <= c < C.\n - X_val: A numpy array of shape (N_val, D) giving validation data.\n - y_val: A numpy array of shape (N_val,) giving validation labels.\n - learning_rate: Scalar giving learning rate for optimization.\n - learning_rate_decay: Scalar giving factor used to decay the learning rate\n after each epoch.\n - reg: Scalar giving regularization strength.\n - num_iters: Number of steps to take when optimizing.\n - batch_size: Number of training examples to use per step.\n - verbose: boolean; if true print progress during optimization.\n \"\"\"\n num_train = X.shape[0]\n iterations_per_epoch = max(num_train / batch_size, 1)\n\n # Use SGD to optimize the parameters in self.model\n loss_history = []\n train_acc_history = []\n val_acc_history = []\n\n for it in range(num_iters):\n X_batch = None\n y_batch = None\n\n #########################################################################\n # TODO: Create a random minibatch of training data and labels, storing #\n # them in X_batch and y_batch respectively. #\n #########################################################################\n pass\n #########################################################################\n # END OF YOUR CODE #\n #########################################################################\n\n # Compute loss and gradients using the current minibatch\n loss, grads = self.loss(X_batch, y=y_batch, reg=reg)\n loss_history.append(loss)\n\n #########################################################################\n # TODO: Use the gradients in the grads dictionary to update the #\n # parameters of the network (stored in the dictionary self.params) #\n # using stochastic gradient descent. You'll need to use the gradients #\n # stored in the grads dictionary defined above. #\n #########################################################################\n pass\n #########################################################################\n # END OF YOUR CODE #\n #########################################################################\n\n if verbose and it % 100 == 0:\n print('iteration %d / %d: loss %f' % (it, num_iters, loss))\n\n # Every epoch, check train and val accuracy and decay learning rate.\n if it % iterations_per_epoch == 0:\n # Check accuracy\n train_acc = (self.predict(X_batch) == y_batch).mean()\n val_acc = (self.predict(X_val) == y_val).mean()\n train_acc_history.append(train_acc)\n val_acc_history.append(val_acc)\n\n # Decay learning rate\n learning_rate *= learning_rate_decay\n\n return {\n 'loss_history': loss_history,\n 'train_acc_history': train_acc_history,\n 'val_acc_history': val_acc_history,\n }\n\n def predict(self, X):\n \"\"\"\n Use the trained weights of this two-layer network to predict labels for\n data points. For each data point we predict scores for each of the C\n classes, and assign each data point to the class with the highest score.\n\n Inputs:\n - X: A numpy array of shape (N, D) giving N D-dimensional data points to\n classify.\n\n Returns:\n - y_pred: A numpy array of shape (N,) giving predicted labels for each of\n the elements of X. For all i, y_pred[i] = c means that X[i] is predicted\n to have class c, where 0 <= c < C.\n \"\"\"\n y_pred = None\n\n ###########################################################################\n # TODO: Implement this function; it should be VERY simple! #\n ###########################################################################\n pass\n ###########################################################################\n # END OF YOUR CODE #\n ###########################################################################\n\n return y_pred\n\n\n","sub_path":"BasicNeuralNet/neural_net.py","file_name":"neural_net.py","file_ext":"py","file_size_in_byte":15878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"239548930","text":"import itertools\nwhile 1==1:\n\n mismatches = []\n firstfile = input(\"file 1 :\")\n secondfile = input(\"file 2 :\")\n outputfilepath = input(\"output file path : \")\n\n with open(firstfile) as f1, open(secondfile) as f2:\n for lineno, (line1, line2) in enumerate(itertools.zip_longest(f1, f2), 1):\n if line1 != line2:\n mismatches.append(lineno)\n\n with open(firstfile, 'r') as file1:\n with open(secondfile, 'r') as file2:\n differencefrom1 = set(file1).difference(file2)\n with open(secondfile, 'r') as file1:\n with open(firstfile, 'r') as file2:\n differencefrom2 = set(file1).difference(file2)\n\n differencefrom1.discard('\\n')\n\n filename = firstfile.rsplit('\\\\', 1)[-1]\n output = \"/\"+filename\n output_path = outputfilepath + output\n\n with open(output_path, 'w') as file_out:\n file_out.write(\"Differences from file staging :\")\n for line in differencefrom1:\n for line_number in mismatches:\n file_out.write('\\n'+\"Is different : \"+str(line)+\", line number : \"+str(line_number))\n with open(output_path, 'a') as file_out:\n file_out.write(\"\\r\\nDifferences from file production :\")\n for line in differencefrom2:\n file_out.write('\\n'+\"Is different : \"+str(line)+\", line number : \"+str(line_number))\n \n \n print(\"Differences done in \"+ filename)","sub_path":"differences.py","file_name":"differences.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"42316719","text":"# -*- coding:utf-8 -*-\n# @Desc: \n# @Author: Administrator\n# @Date: 2018-04-29 13:23\n\n### 递归函数:\n# - 在函数内部调用自己本身\n# - 递归函数本质上是一个函数的循环调用,注意:有可能出现死循环\n# - 一定要定义递归的边界(什么时候退出循环)\n\n### 练习:计算阶乘 n! = 1 * 2 * 3 * 4 * 5 * ... * n\n\"\"\"\n1! = 1\n2! = 2 * 1 = 2 * 1!\n3! = 3 * 2 * 1 = 3 * 2!\n4! = 4 * 3 * 2 * 1 = 4 * 3!\n...\nn! = n * (n-1)!\n\"\"\"\n\n# 第一种方法: while 循环\nn = 4\nresult = 1\ni = 1\nwhile i <= n:\n result = result * i\n i += 1\nprint(result)\n\n# 第二种方法: 递归函数\ndef test(n):\n if n == 1:\n return 1\n return n * test(n-1)\nprint(test(5))\n\n\n\n\n\n","sub_path":"01.PythonDoc/04.变量-函数-返回值-参数/20.递归函数-计算阶乘案例.py","file_name":"20.递归函数-计算阶乘案例.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"42536195","text":"import torch\nimport os.path\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass Serializable():\n \"\"\"\n Stateful objects that can be saved and loaded\n \"\"\"\n\n def save(self, filename):\n \"\"\"Save any state collected during the run (excludes data given at construction time for simplicity)\"\"\"\n state = self.state_dict()\n base_dir = os.path.dirname(filename)\n if not os.path.isdir(base_dir):\n os.makedirs(base_dir, exist_ok=True)\n torch.save(state, filename)\n logger.info(\"saved checkpoint to %s\", filename)\n\n def load(self, filename) -> bool:\n \"\"\"Load state previously saved, returning loading success\"\"\"\n if not os.path.isfile(filename):\n return False\n try:\n checkpoint = torch.load(filename)\n except RuntimeError as e:\n logger.warning(e)\n checkpoint = torch.load(filename, map_location=torch.device('cpu'))\n try:\n if not self.load_state_dict(checkpoint):\n logger.info(\"failed to load checkpoint from %s\", filename)\n logger.info(checkpoint)\n return False\n except KeyError as e:\n logger.error(e)\n logger.info(checkpoint)\n return False\n logger.info(\"loaded checkpoint from %s\", filename)\n return True\n\n def state_dict(self) -> dict:\n \"\"\"State collected during the run\"\"\"\n return {}\n\n def load_state_dict(self, state: dict) -> bool:\n return True\n","sub_path":"src/arm_pytorch_utilities/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"212001132","text":"import pandas as pd\nimport fnmatch\nimport json\nimport os\nimport re\nimport numpy as np\n\nUNSET_PORT=0\nUNSET_MAC=\"0x020000000000\"\nUNSET_IP=\"00.00.0.0\"\nUSER=\"pulsar\"\nPASSWORD=\"\"\n\n\ninet = {\n \"10.17.0.1\" : \"pacifix0\",\n \"10.17.0.2\" : \"pacifix0\",\n \"10.17.1.1\" : \"pacifix1\",\n \"10.17.1.2\" : \"pacifix1\",\n \"10.17.2.1\" : \"pacifix2\",\n \"10.17.2.2\" : \"pacifix2\",\n \"10.17.3.1\" : \"pacifix3\",\n \"10.17.3.2\" : \"pacifix3\",\n \"10.17.4.1\" : \"pacifix4\",\n \"10.17.4.2\" : \"pacifix4\",\n \"10.17.5.1\" : \"pacifix5\",\n \"10.17.5.2\" : \"pacifix5\",\n \"10.17.6.1\" : \"pacifix6\",\n \"10.17.6.2\" : \"pacifix6\",\n \"10.17.7.1\" : \"pacifix7\",\n \"10.17.7.2\" : \"pacifix7\",\n \"10.17.8.1\" : \"pacifix8\",\n \"10.17.8.2\" : \"pacifix8\"\n}\n\n# Used for test purposes on edd01\n# inet = {\n# \"10.17.0.1\" : \"edd01\",\n# \"10.17.0.2\" : \"edd01\",\n# \"10.17.1.1\" : \"edd01\",\n# \"10.17.1.2\" : \"edd01\",\n# \"10.17.2.1\" : \"edd01\",\n# \"10.17.2.2\" : \"edd01\",\n# \"10.17.3.1\" : \"edd01\",\n# \"10.17.3.2\" : \"edd01\",\n# \"10.17.4.1\" : \"edd01\",\n# \"10.17.4.2\" : \"edd01\",\n# \"10.17.5.1\" : \"edd01\",\n# \"10.17.5.2\" : \"edd01\",\n# \"10.17.6.1\" : \"edd01\",\n# \"10.17.6.2\" : \"edd01\",\n# \"10.17.7.1\" : \"edd01\",\n# \"10.17.7.1\" : \"edd01\",\n# \"10.17.8.1\" : \"edd01\",\n# \"10.17.8.1\" : \"edd01\"\n# }\n\nclass ConfigError(Exception):\n pass\n\nclass Config:\n def __init__(self, dir, fname):\n self.fname = fname\n self.dir = dir\n if self.dir[-1] != \"/\":\n self.dir += \"/\"\n self.conf_path = self.dir + self.fname\n print(self.conf_path)\n # Load all config files\n try:\n self.config_file = open(self.conf_path, 'r')\n self.data = json.load(self.config_file)\n except Exception as e:\n raise ConfigError(\"Failed to init json config: \" + str(e.__class__) + str(e))\n try:\n self.rt_path = self.dir + self.data[\"routing_table\"]\n self.df = pd.read_csv(self.rt_path)\n self.rt = self.df.T.to_dict()\n except Exception as e:\n raise ConfigError(\"Failed to load routing table: \" + str(e.__class__) + str(e))\n # Parse them\n # Parse routing table, determine which mac, ip corresponse to which ports\n numa_id = \"numa0\"\n self.numa_dict = {numa_id:{}}\n self.mac_list = []\n self.nof_nodes = 0\n for key_out in self.rt.keys():\n for key_in,val in self.rt[key_out].items():\n if \"MAC\" in key_in and val != UNSET_MAC:#\n beamid = int(key_in.replace(\"MAC\",\"\"))\n if val not in self.mac_list:\n self.mac_list.append(val)\n numa_id = re.sub(r'\\d', \"\", numa_id)\n numa_id += str(str(int(self.nof_nodes)))\n self.numa_dict[numa_id] = {}\n self.numa_dict[numa_id][\"beams\"] = []\n self.nof_nodes += 1\n self.numa_dict[numa_id][\"mac\"] = val\n self.numa_dict[numa_id][\"ip\"] = self.rt[key_out][\"IP\"+str(beamid)]\n self.numa_dict[numa_id][\"beams\"].append([beamid,self.rt[key_out][\"PORT\"+str(beamid)]])\n self.numa_dict[numa_id][\"bandid\"] = self.rt[key_out][\"BANDID\"]\n # print(self.numa_dict)\n f = open('config/parsed_numa_config.json', 'w')\n json.dump(self.numa_dict, f, indent=4)\n # construct command line pattern for argument 'c' of capture_main program (ip_port_expectedbeams_actualbeams_cpu)\n self.numa_list = []\n for idx, key in enumerate(self.numa_dict.keys()):\n self.numa_list.append(NumaNode(idx, key, self.data, self.numa_dict[key]))\n self.numa_list[-1].construct_pattern()\n\nclass NumaNode:\n def __init__(self, id, node_name, config, dictionary):\n self.id = id%2\n self.node_name = node_name\n self.dockername = config[\"dockername\"]+self.node_name\n self.config = config\n self.mac = dictionary[\"mac\"]\n self.ip = dictionary[\"ip\"]\n self.host = inet[self.ip]\n self.bandid = dictionary[\"bandid\"]\n self.freq = float(config[\"center_freq\"] + (self.bandid - config[\"band_groups\"]/2)*config[\"bandwidth_group\"]) +config[\"bandwidth_group\"]/2\n self.beam_port = np.asarray(dictionary[\"beams\"])\n self.storage_dir = config[\"root_storage_dir\"] + self.node_name + \"/\"\n self.cmd_pattern = config[\"capture_main\"][\"directory\"] + config[\"capture_main\"][\"name\"]\n if self.id%2:\n self.start_cpu = self.config[\"cpus_per_node\"]\n self.key = self.config[\"dada_key_odd\"]\n else:\n self.start_cpu = 0\n self.key = self.config[\"dada_key_even\"]\n def construct_pattern(self):\n self.cmd_pattern += \" -a \" + self.key\n self.cmd_pattern += \" -b \" + str(self.config[\"packet_start\"])\n self.ports = np.unique(self.beam_port[:,1])\n for idx in range(self.ports.shape[0]):\n self.cmd_pattern += \" -c \"+str(self.ip)+\"_\"\n self.cmd_pattern += str(self.ports[idx]) + \"_\"\n self.cmd_pattern += str(np.count_nonzero(self.beam_port[:,1] == self.ports[idx])) + \"_\"\n self.cmd_pattern += str(np.count_nonzero(self.beam_port[:,1] == self.ports[idx])) + \"_\"\n self.cmd_pattern += str(idx+2+self.start_cpu) + \" \"\n self.cmd_pattern += \" -e \" + str(self.config[\"center_freq\"])\n self.cmd_pattern += \" -g \" + self.config[\"log_dir\"]\n self.cmd_pattern += \" -i \" + str(self.start_cpu)\n self.cmd_pattern += \" -j \" + str(self.config[\"capture_control\"]) + \"_\" + str(self.start_cpu + 1)\n self.cmd_pattern += \" -k \" + str(self.config[\"bind_cpu\"])\n self.cmd_pattern += \" -l \" + str(self.config[\"nof_data_frame_per_block\"])\n self.cmd_pattern += \" -m \" + str(self.config[\"nof_data_frame_tmp_buffer\"])\n self.cmd_pattern += \" -n \" + self.config[\"docker_config_dir\"] + self.config[\"template_dada_header\"]\n self.cmd_pattern += \" -o \" + self.config[\"soure_information\"]\n self.cmd_pattern += \" -p \" + str(self.config[\"padding\"])\n self.cmd_pattern += \" -q \" + str(self.freq)\n self.cmd_pattern += \" -r \" + str(self.config[\"nof_data_frame_per_capture\"])\n # print(self.cmd_pattern)\n","sub_path":"inc/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"96529973","text":"\"\"\"\nFile description\n\"\"\"\n\n# import modules\nimport numpy as np\nimport pickle\nfrom obspy.taup.tau import TauPyModel\nimport mysql.connector\nimport math\n\n__author__ = \"Vaclav Kuna\"\n__copyright__ = \"\"\n__license__ = \"\"\n__version__ = \"1.0\"\n__maintainer__ = \"Vaclav Kuna\"\n__email__ = \"kuna.vaclav@gmail.com\"\n__status__ = \"\"\n\n\ndef make_grid(lat_min, lat_max, lon_min, lon_max, step):\n\n lat = np.arange(start=lat_min, stop=lat_max, step=step)\n lon = np.arange(start=lon_min, stop=lon_max, step=step)\n\n xv, yv = np.meshgrid(lat, lon, sparse=False, indexing=\"ij\")\n\n return (xv, yv)\n\n\ndef calculate_tt(tt_precalc, grid, sta_lat, sta_lon, eq_depth):\n\n xv = grid[0]\n yv = grid[1]\n\n nx = grid[0].shape[0]\n ny = grid[0].shape[1]\n\n tt = np.zeros_like(xv)\n\n for i in range(nx):\n for j in range(ny):\n\n point_lat = xv[i, j]\n point_lon = yv[i, j]\n\n # using mine\n distance_in_degree = globe_distance(point_lat, point_lon, sta_lat, sta_lon)\n\n # find the closest time from the tt_precalc and place it in the grid\n tt[i, j] = tt_precalc[\"travel_time\"][\n np.argmin(np.abs(tt_precalc[\"dist\"] - distance_in_degree))\n ]\n\n # time_out = model.get_travel_times(source_depth_in_km=eq_depth, distance_in_degree=distance_in_degree, phase_list=[\"p\",\"P\"])\n\n return tt\n\n\ndef globe_distance(lat1, lon1, lat2, lon2):\n\n # approximate radius of earth in km\n R = 6373.0\n deg2km = 111.3\n\n lat1 = math.radians(lat1)\n lon1 = math.radians(lon1)\n lat2 = math.radians(lat2)\n lon2 = math.radians(lon2)\n\n dlon = lon2 - lon1\n dlat = lat2 - lat1\n\n a = (\n math.sin(dlat / 2) ** 2\n + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2\n )\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n\n distance = R * c / deg2km\n\n return distance\n\n\ndef fetch_all_devices(db):\n\n # connect to the database\n mydb = mysql.connector.connect(\n host=db[\"host\"], user=db[\"user\"], passwd=db[\"passwd\"], database=db[\"db_name\"]\n )\n\n # set the database pointer\n cur = mydb.cursor()\n\n # get all the devices\n sql = \"SELECT device_id, latitude, longitude FROM devices\"\n cur.execute(sql)\n\n # fetch the result\n devices = cur.fetchall()\n\n # return all stations\n return devices\n\n\ndef precalculate_times(max_dist, step, eq_depth, model):\n\n # to ensure small tt errors the step for precalculation of travel times\n # has to be <= 1/10 of grid step\n step = step / 10\n\n dist = np.arange(start=0, stop=max_dist, step=step)\n tt = np.zeros_like(dist)\n\n for i, distance_in_degree in enumerate(dist):\n\n time_out = model.get_travel_times(\n source_depth_in_km=eq_depth,\n distance_in_degree=distance_in_degree,\n phase_list=[\"p\", \"P\"],\n )\n tt[i] = time_out[0].time\n\n print(tt)\n\n tt_precalc = {\"dist\": dist, \"travel_time\": tt}\n\n return tt_precalc\n\n\ndef calculate_trave_times(db, params):\n\n # set params from params\n lat_min = params[\"lat_min\"]\n lat_max = params[\"lat_max\"]\n lon_min = params[\"lon_min\"]\n lon_max = params[\"lon_max\"]\n step = params[\"step\"]\n calculate_open = params[\"calculate_open\"]\n vel_model = params[\"vel_model\"]\n eq_depth = params[\"eq_depth\"]\n\n max_dist = ((lat_max - lat_min) ** 2 + (lon_max - lon_min) ** 2) ** (1 / 2)\n\n model_name = \"travel_time_d\" + str(eq_depth)\n\n if calculate_open == \"calculate\":\n\n print(\"\")\n print(\"----------\")\n print(\"CALCULATING TRAVEL TIMES\")\n print(\"----------\")\n\n print(\"Precalculationg tt\")\n # define velocity model\n model = TauPyModel(model=vel_model)\n # precalculate times\n tt_precalc = precalculate_times(max_dist, step, eq_depth, model)\n\n # connect to the database\n mydb = mysql.connector.connect(\n host=db[\"host\"],\n user=db[\"user\"],\n passwd=db[\"passwd\"],\n database=db[\"db_name\"],\n )\n\n devices = fetch_all_devices(db)\n grid = make_grid(\n lat_min=lat_min,\n lat_max=lat_max,\n lon_min=lon_min,\n lon_max=lon_max,\n step=step,\n )\n\n travel_time = {\"grid_lat\": grid[0], \"grid_lon\": grid[1], \"vector\": tt_precalc}\n\n print(\"Calculating for stations\")\n for device in devices:\n\n sta_name = device[0]\n print(\"Station: {}\".format(sta_name))\n\n sta_lat = device[1]\n sta_lon = device[2]\n\n travel_time[sta_name] = calculate_tt(\n tt_precalc, grid, sta_lat, sta_lon, eq_depth\n )\n\n with open(\"obj/travel_time/\" + model_name + \".pkl\", \"wb\") as f:\n pickle.dump(travel_time, f, pickle.HIGHEST_PROTOCOL)\n\n return travel_time\n\n elif calculate_open == \"open\":\n\n with open(\"obj/travel_time/\" + model_name + \".pkl\", \"rb\") as f:\n travel_time = pickle.load(f)\n\n return travel_time\n","sub_path":"src/travel_time.py","file_name":"travel_time.py","file_ext":"py","file_size_in_byte":5027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"462727807","text":"from tkinter import *\nfrom youtubemodule import Youtube\nimport requests\nimport re\nimport os\n\n\n\nyt = Youtube()\nYTsearch = Tk()\n \nsearchQuery = Entry(YTsearch)\nsearchQuery.pack()\n\ndef queried():\n yt.getFirst(searchQuery.get())\n\ndef write_video_to_file():\n with open('downloaded.txt', 'w') as f:\n f.write(str(yt.getFirst(searchQuery.get())))\n searcher.create_text(500, 10, text='...Done!')\n\ndownload = Button(YTsearch, text='Download Video', command=write_video_to_file)\nsendquery = Button(YTsearch, text='Search!', command=queried)\nsearcher = Canvas(YTsearch, width=1000, height=500)\n\nsearcher.create_text(300, 50, text='The program opens a tab with the first result of a YouTube query', font=('Times', 11))\nsearcher.create_text(256, 70, text='Type something in the search box and hit \\'Search!\\'', font=('Times', 11))\nsearcher.create_text(150, 20, text='YouTube Searcher', font=('Courier', 20))\n\nyoutubelogo = PhotoImage(file='C:\\\\Users\\\\leeso\\\\OneDrive\\\\Pictures\\\\source.gif')\nsearcher.create_image(500, 300, image=youtubelogo)\n\ndownload.pack()\nsendquery.pack()\nsearcher.pack()\n","sub_path":"YouTubeGUI.py","file_name":"YouTubeGUI.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"457677626","text":"from django.urls import path\n\nfrom orochi.users.views import (\n user_plugins_view,\n user_bookmarks_view,\n user_redirect_view,\n user_yara_view,\n)\n\napp_name = \"users\"\nurlpatterns = [\n path(\"~redirect/\", view=user_redirect_view, name=\"redirect\"),\n path(\"/plugins/\", view=user_plugins_view, name=\"plugins\"),\n path(\"/bookmarks/\", view=user_bookmarks_view, name=\"bookmarks\"),\n path(\"/rules/\", view=user_yara_view, name=\"rules\"),\n]","sub_path":"orochi/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"228796835","text":"# 4.4 实现迭代器协议\n# 你想构建一个能支持迭代操作的自定义对象,并希望找到一个能实现迭代协议的\n# 简单方法。\n\n# 目前为止,在一个对象上实现迭代最简单的方式是使用一个生成器函数。在 4.2 小\n# 节中,使用 Node 类来表示树形数据结构。你可能想实现一个以深度优先方式遍历树形\n# 节点的生成器。下面是代码示例:\n\nclass Node:\n def __init__(self,value):\n self._value = value\n self._children = []\n\n def __repr__(self):\n return 'Node({!r})'.format(self._value)\n\n def add_child(self,node):\n self._children.append(node)\n\n def __iter__(self):\n return iter(self._children)\n\n def depth_first(self):\n yield self\n for c in self:\n yield from c.depth_first()\n\n\n# Example\nif __name__ == '__name__':\n root = Node(0)\n child1 = Node(1)\n child2 = Node(2)\n root.add_child(child1)\n root.add_child(child2)\n child1.add_child(Node(3))\n child1.add_child(Node(4))\n child2.add_child(Node(5))\n print(\"=\"*20)\n for ch in root.depth_first():\n print(ch)\n\nimport datetime\ns = datetime.datetime.now()\nprint(s)","sub_path":"Chapter4.4.py","file_name":"Chapter4.4.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"512248412","text":"# 클라이언트 서버로 자료전달\r\n\r\nimport cgi\r\n\r\n# 사용자(client)가 입력한 자료를 받기 - get\r\nform = cgi.FieldStorage() \r\nirum = form['name'].value # 자바의 request.getparameter(\"name\")라고 생각하면됨\r\nnai = form['age'].value\r\n\r\nprint('Content-Type:text/html;charset=utf-8\\n')\r\n\r\nprint(\"\"\"\r\n\r\n\r\n사용자가 입력한 자료는 \r\n이름은 {0}\r\n나이는 {1}\r\n\r\n\r\n\r\n\"\"\".format(irum, nai))","sub_path":"python_net/pack4_http/cgi-bin/my.py","file_name":"my.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"508648352","text":"from airflow.contrib.hooks.aws_hook import AwsHook\nfrom airflow.hooks.postgres_hook import PostgresHook\nfrom airflow.models import BaseOperator\nfrom airflow.utils.decorators import apply_defaults\n\n\"\"\"\n StageToRedshiftOperator:\n \n Loads the data from the S3 to Redshift table.\n \n Inputs:\n \n redshift_conn_id: str -> reshift connection id saved in the airflow connections\n aws_credentials_id: str -> aws credentials id saved in the airflow connections\n table:str -> table name in redshift\n s3_bucket:str -> s3 bucket name\n s3_key:str -> s3 key name\n file_format:str -> Defining the File Format\n optional_parameters:list(str) -> Additionla parameters for the copy statement\n \n\"\"\"\n\n\nclass StageToRedshiftOperator(BaseOperator):\n ui_color = '#358140'\n template_fields = (\"s3_key\",)\n FF_SET = [\"CSV\", \"AVRO\", \"JSON\", \\\n \"FIXEDWIDTH\", \"SHAPEFILE\", \\\n \"PARQUET\", \"ORC\", \"DELIMITER\"]\n \n copy_sql = \"\"\"\n COPY {}\n FROM '{}'\n ACCESS_KEY_ID '{}'\n SECRET_ACCESS_KEY '{}'\n {}\n \"\"\"\n \n @apply_defaults\n def __init__(self,\n redshift_conn_id=\"\",\n aws_credentials_id=\"\",\n table=\"\",\n s3_bucket=\"\",\n s3_key=\"\",\n file_format=\"\",\n optional_parameters=[],\n *args, **kwargs):\n\n super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\n self.table = table\n self.redshift_conn_id = redshift_conn_id\n self.s3_bucket = s3_bucket\n self.s3_key = s3_key\n self.aws_credentials_id = aws_credentials_id\n self.file_format = file_format\n self.optional_parameters = optional_parameters\n\n\n def execute(self, context):\n self.log.info('Starting to implement StageToRedshiftOperator')\n \n if self.file_format not in StageToRedshiftOperator.FF_SET:\n raise ValueError(f\"InValid file format {self.file_format}. It should be any of {StageToRedshiftOperator.FF_SET}\")\n \n aws_hook = AwsHook(self.aws_credentials_id)\n credentials = aws_hook.get_credentials()\n redshift = PostgresHook(postgres_conn_id=self.redshift_conn_id)\n\n self.log.info(\"Clearing data from destination Redshift table\")\n redshift.run(\"DELETE FROM {}\".format(self.table))\n\n self.log.info(\"Copying data from S3 to Redshift\")\n rendered_key = self.s3_key.format(**context)\n s3_path = \"s3://{}/{}\".format(self.s3_bucket, rendered_key)\n formatted_sql = StageToRedshiftOperator.copy_sql.format(\n self.table,\n s3_path,\n credentials.access_key,\n credentials.secret_key,\n \"\\n\\t\".join(self.optional_parameters)\n )\n self.log.info(f\"Copy SQL: {formatted_sql}\")\n redshift.run(formatted_sql)\n self.log.info(f'Successful execution of StageToRedshiftOperator for {self.table}')\n\n \n \n \n \n \n\n\n\n\n\n","sub_path":"plugins/operators/stage_redshift.py","file_name":"stage_redshift.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"168895177","text":"class Solution:\n def canCross(self, stones: List[int]) -> bool:\n dp={i:set() for i in stones}\n i=stones.pop(0)\n if i+1 in dp:\n dp[i+1].add(1)\n del dp[0]\n for i,ks in dp.items():\n for k in ks:\n if k>1 and i+k-1 in dp:\n dp[i+k-1].add(k-1)\n if k>0 and i+k in dp:\n dp[i+k].add(k)\n if i+k+1 in dp:\n dp[i+k+1].add(k+1)\n if dp[stones[-1]]:\n return True\n return False","sub_path":"403. Frog Jump.py","file_name":"403. Frog Jump.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"597176614","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport common\n\nimport numpy as np\nimport unittest\n\nfrom measurements import get_measurements, create_mask\nfrom other_algorithms import least_squares_lm, cost_function, error_measure\nfrom other_algorithms import pointwise_srls, get_grid, pointwise_rls\nfrom solvers import trajectory_recovery\nfrom trajectory import Trajectory\n\neps = 1e-10\n\n\nclass TestOthers(unittest.TestCase):\n def setUp(self):\n np.random.seed(2)\n n_complexity = 5\n self.traj = Trajectory(model='bandlimited')\n self.traj.set_n_complexity(n_complexity)\n self.traj.set_coeffs(1)\n\n self.anchors = np.random.rand(self.traj.dim, 10) * 10 # between 0 and 10.\n\n self.times = self.traj.get_times(n_samples=200)\n self.basis, self.D_gt = get_measurements(self.traj, self.anchors[:2, :], times=self.times)\n\n points_gt = self.traj.get_sampling_points(self.times)\n self.indices = range(len(self.times))[::self.traj.dim + 1]\n self.points_sub = points_gt[:, self.indices]\n\n def test_least_squares_lm(self):\n mask = create_mask(*self.D_gt.shape, strategy='single_time')\n D_sparse = self.D_gt * mask\n\n C_gt_vec = self.traj.coeffs.reshape((-1, ))\n cost_gt = cost_function(C_gt_vec, D_sparse, self.anchors[:2, :], self.basis)\n self.assertTrue(np.sum(np.abs(cost_gt)) < eps)\n\n Chat = self.traj.coeffs\n x0 = Chat.copy().reshape((-1, ))\n Cref = least_squares_lm(D_sparse, self.anchors, self.basis, x0)\n self.assertLess(error_measure(Cref, self.traj.coeffs), eps)\n\n def test_pointwise_srls(self):\n points, __ = pointwise_srls(self.D_gt, self.anchors, self.traj, self.indices)\n points = np.array(points).T\n self.assertTrue(np.allclose(self.points_sub, points))\n\n def test_pointwise_rls(self):\n grid_size = 1.0\n grid = get_grid(self.points_sub, grid_size)\n\n points, __ = pointwise_rls(self.D_gt, self.anchors, self.traj, self.indices, grid=grid)\n points = points.T\n np.testing.assert_allclose(points, self.points_sub, atol=grid_size, rtol=grid_size)\n\n def test_single_rls_srls(self):\n from other_algorithms import RLS\n from pylocus.lateration import SRLS\n\n anchors = np.random.uniform(0, 10, size=(2, 4))\n grid_size = 0.1\n grid = get_grid(anchors, grid_size=grid_size)\n chosen_idx = np.random.choice(range(grid.shape[0]))\n pos_real = grid[chosen_idx, :]\n r2_real = np.linalg.norm(anchors - pos_real[:, None], axis=0)**2\n\n np.testing.assert_allclose(pos_real, RLS(anchors.T, r2_real, grid))\n r2_real = r2_real.reshape((-1, 1))\n weights = np.ones(r2_real.shape)\n np.testing.assert_allclose(pos_real, SRLS(anchors.T, weights, r2_real))\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"test/test_other_algorithms.py","file_name":"test_other_algorithms.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"84611527","text":"from sDetailsHTMLTemplate import sDetailsHTMLTemplate;\n\nclass cBugReport_CdbTerminatedUnexpectedly(object):\n def __init__(oBugReport, oCdbWrapper, uExitCode):\n oBugReport.sBugTypeId = \"CdbTerminated:%d\" % uExitCode;\n oBugReport.sBugDescription = \"Cdb terminated unexpectedly\";\n oBugReport.sBugLocation = None;\n oBugReport.sSecurityImpact = None;\n oBugReport.oException = None;\n oBugReport.oStack = None;\n \n if oCdbWrapper.bGetDetailsHTML:\n oBugReport.sImportantOutputHTML = oCdbWrapper.sImportantOutputHTML;\n oBugReport.sProcessBinaryName = \"cdb.exe\";\n \n oBugReport.sId = oBugReport.sBugTypeId;\n oBugReport.sStackId = None;\n oBugReport.sBugLocation = None;\n \n if oCdbWrapper.bGetDetailsHTML:\n # Turn cdb output into formatted HTML. It is separated into blocks, one for the initial cdb output and one for each\n # command executed.\n sCdbStdIOHTML = '
'.join(oCdbWrapper.asCdbStdIOBlocksHTML);\n del oCdbWrapper.asCdbStdIOBlocksHTML;\n # Create HTML details\n oBugReport.sDetailsHTML = sDetailsHTMLTemplate % {\n \"sId\": oCdbWrapper.fsHTMLEncode(oBugReport.sId),\n \"sBugDescription\": oCdbWrapper.fsHTMLEncode(oBugReport.sBugDescription),\n \"sBugLocation\": oCdbWrapper.fsHTMLEncode(oBugReport.sBugLocation or \"Unknown\"),\n \"sSecurityImpact\": oBugReport.sSecurityImpact and \\\n '%s' % oCdbWrapper.fsHTMLEncode(oBugReport.sSecurityImpact) or \"None\",\n \"sOptionalBlocks\": \"\",\n \"sCdbStdIO\": sCdbStdIOHTML,\n };\n","sub_path":"src/cBugReport_CdbTerminatedUnexpectedly.py","file_name":"cBugReport_CdbTerminatedUnexpectedly.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"229673033","text":"## TensorFlow control flow\nimport tensorflow as tf\n\n\nx, y = 1.0, 2.0\n\ng = tf.Graph()\nwith g.as_default():\n tf_x = tf.compat.v1.placeholder(dtype=tf.float32, \n shape=None, name='tf_x')\n tf_y = tf.compat.v1.placeholder(dtype=tf.float32, \n shape=None, name='tf_y')\n res = tf.cond(tf_x < tf_y, \n lambda: tf.add(tf_x, tf_y, \n name='result_add'),\n lambda: tf.subtract(tf_x, tf_y, \n name='result_sub'))\n print('Object:', res)\n \nwith tf.compat.v1.Session(graph=g) as sess:\n print('x < y: %s -> Result:' % (x < y), \n res.eval(feed_dict={'tf_x:0': x, \n 'tf_y:0': y}))\n x, y = 2.0, 1.0\n print('x < y: %s -> Result:' % (x < y), \n res.eval(feed_dict={'tf_x:0': x,\n 'tf_y:0': y})) \n\n file_writer = tf.compat.v1.summary.FileWriter(logdir='./logs/tf-cond/', graph=g)\n","sub_path":"ch14/tensorflow_control_flow.py","file_name":"tensorflow_control_flow.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"564505619","text":"import pytesseract\nimport asyncio\n\n\nasync def read_image(img_path, lang='eng'):\n try:\n text = pytesseract.image_to_string(img_path, lang=lang)\n await asyncio.sleep(2)\n return text\n except:\n return \"[ERROR] Unable to process file: {0}\".format(img_path)\n\n\n","sub_path":"ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"537157772","text":"# Here, we provide an example of a minimally staggered curvilinear mesh.\n# In this case, the y-faces have normal vectors that are\n# primarily along the x-direction.\n\nfrom discretize import CurvilinearMesh\nfrom discretize.utils import example_curvilinear_grid, mkvc\nfrom matplotlib import pyplot as plt\n\nx, y = example_curvilinear_grid([10, 10], \"rotate\")\nmesh1 = CurvilinearMesh([x, y])\ny_faces = mesh1.faces_y\n\nfig1 = plt.figure(figsize=(5, 5))\nax1 = fig1.add_subplot(111)\nmesh1.plot_grid(ax=ax1)\nax1.scatter(y_faces[:, 0], y_faces[:, 1], 30, 'r')\nax1.legend(['Mesh', 'Y-faces'], fontsize=16)\nplt.plot()\n\n# Here, we provide an example of a highly irregular curvilinear mesh.\n# In this case, the y-faces are not defined by normal vectors along\n# a particular direction.\n\nx, y = example_curvilinear_grid([10, 10], \"sphere\")\nmesh2 = CurvilinearMesh([x, y])\ny_faces = mesh2.faces_y\n\nfig2 = plt.figure(figsize=(5, 5))\nax2 = fig2.add_subplot(111)\nmesh2.plot_grid(ax=ax2)\nax2.scatter(y_faces[:, 0], y_faces[:, 1], 30, 'r')\nax2.legend(['Mesh', 'Y-faces'], fontsize=16)\nplt.plot()\n","sub_path":"html/api/generated/discretize-CurvilinearMesh-faces_y-1.py","file_name":"discretize-CurvilinearMesh-faces_y-1.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"36789450","text":"import os, pytest\nfrom oanda_backtest import Backtest\n\nclass TestBacktest(object):\n\n def setup_method(self, method):\n token = os.environ['oanda_backtest_token']\n self.bt = Backtest(token=token)\n\n def test_run_basic(self):\n\n self.bt.get(\"EUR_USD\")\n fast_ma = self.bt.sma(period=5)\n slow_ma = self.bt.sma(period=25)\n self.bt.sell_exit = self.bt.buy_entry = ((fast_ma > slow_ma) & (fast_ma.shift() <= slow_ma.shift())).values\n self.bt.buy_exit = self.bt.sell_entry = ((fast_ma < slow_ma) & (fast_ma.shift() >= slow_ma.shift())).values\n actual = self.bt.run()\n expected = 11\n assert expected == len(actual)\n\n def test_run_advanced(self):\n\n filepath='usd-jpy-h1.csv'\n if self.bt.exists(filepath):\n self.bt.read_csv(filepath)\n else:\n self.bt.get(\"USD_JPY\", {\"granularity\": \"H1\", \"count\": 5000})\n self.bt.to_csv(filepath)\n\n fast_ma = self.bt.sma(period=10)\n slow_ma = self.bt.sma(period=30)\n exit_ma = self.bt.sma(period=5)\n self.bt.buy_entry = ((fast_ma > slow_ma) & (fast_ma.shift() <= slow_ma.shift())).values\n self.bt.sell_entry = ((fast_ma < slow_ma) & (fast_ma.shift() >= slow_ma.shift())).values\n self.bt.buy_exit = ((self.bt.C < exit_ma) & (self.bt.C.shift() >= exit_ma.shift())).values\n self.bt.sell_exit = ((self.bt.C > exit_ma) & (self.bt.C.shift() <= exit_ma.shift())).values\n\n self.bt.initial_deposit = 100000\n self.bt.point = 0.01\n self.bt.spread = 0.08\n self.bt.limit = 20\n self.bt.stop_loss = 50\n self.bt.lots = 10000\n self.bt.take_profit = 100\n\n actual = self.bt.run()\n self.bt.plot(\"backtest.png\")\n expected = 11\n assert expected == len(actual)\n","sub_path":"tests/test_oanda_backtest.py","file_name":"test_oanda_backtest.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"336172014","text":"#Train same setup multiple times\nimport sys\nimport os\nfrom multiprocessing import Pool\n\n\ndef trainNets(inpt):\n\tgpu = inpt % 4\n\trun = inpt\n\tmodelTypes = [\"vc\"]\n\t# modelTypes = ['vc', \"ds\", \"op\", \"cc\"]\n\t# if run > 12:\n\t# \tmodelTypes = ['vc', \"op\", \"cc\"]\n\t# else:\n\t# \tmodelTypes = [\"op\", \"cc\"]\n\tfor modelType in modelTypes:\n\t\tos.system(\"CUDA_VISIBLE_DEVICES=\"+str(gpu)+\" python3 trainOnMultipleGPUs.py \"+modelType+\" \"+str(run))\n\nfor s in range(1):\n\tprint(\"Doing s=\"+str(s))\n\truns = [i for i in range(s*4+1,s*4+5)]\n\tp = Pool(4)\n\tres = p.map(trainNets, runs)\n\tp.close()\n\tp.join()\n\nprint(\"Done!\")\n","sub_path":"netowrks/trainMultipleNetworks.py","file_name":"trainMultipleNetworks.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"135442059","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport numpy as np\nimport random\nimport networkx as nx\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import metrics\nfrom graph import *\nimport line\nimport csv\n\nimport time\n\n\ndef parse_args():\n parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter,\n conflict_handler='resolve')\n parser.add_argument('--input',\n help='Input graph file',\n default='soc-wiki-Vote.edges')\n parser.add_argument('--output',\n help='Output representation file',\n default='resultat1.emb')\n parser.add_argument('--number-walks',\n default=10,\n type=int,\n help='Number of random walks to start at each node')\n parser.add_argument('--walk-length',\n default=80,\n type=int,\n help='Length of the random walk started at each node')\n parser.add_argument('--workers',\n default=8,\n type=int,\n help='Number of parallel processes.')\n parser.add_argument(\n '--representation-size',\n default=128,\n type=int,\n help='Number of latent dimensions to learn for each node.')\n parser.add_argument('--window-size',\n default=10,\n type=int,\n help='Window size of skipgram model.')\n parser.add_argument('--epochs',\n default=5,\n type=int,\n help='The training epochs of LINE and GCN')\n parser.add_argument('--method', default='line', help='The learning method')\n parser.add_argument('--graph-format',\n default='edgelist',\n help='Input graph format')\n parser.add_argument('--negative-ratio',\n default=5,\n type=int,\n help='the negative ratio of LINE')\n parser.add_argument('--weighted',\n action='store_true',\n help='Treat graph as weighted')\n parser.add_argument(\n '--order',\n default=3,\n type=int,\n help=\n 'Choose the order of LINE, 1 means first order, 2 means second order, 3 means first order + second order'\n )\n parser.add_argument('--no-auto-save',\n action='store_true',\n help='no save the best embeddings when training LINE')\n args = parser.parse_args()\n if args.method != 'gcn' and not args.output:\n print(\"No output filename. Exit.\")\n exit(1)\n return args\n\n\ndef main(args, samplegraph):\n t1 = time.time()\n g = Graph()\n print(\"Reading...\")\n g.read_edgelist(samplegraph, weighted=args.weighted)\n model = line.LINE(g,\n epoch=args.epochs,\n rep_size=args.representation_size,\n order=args.order)\n t2 = time.time()\n print(t2 - t1)\n print(\"Saving embeddings...\")\n model.save_embeddings(args.output)\n\n\ndef cosine_similarity(vector1, vector2):\n dot_product = 0.0\n normA = 0.0\n normB = 0.0\n for a, b in zip(vector1, vector2):\n dot_product += a * b\n normA += a**2\n normB += b**2\n if normA == 0.0 or normB == 0.0:\n return 0\n else:\n return round(dot_product / ((normA**0.5) * (normB**0.5)) * 100, 2)\n\n\n# node embedding得到向量表示\ndef read_embedding(file_path):\n vector_dic = {}\n with open(file_path, 'r') as f:\n for line_num, eachline in enumerate(f):\n if line_num == 1:\n continue\n for line in f:\n node = str(line.split(' ')[0])\n vector = []\n list_1 = line.split(' ')[1:]\n for i in list_1:\n vector.append(float(i))\n vector_dic[node] = vector\n return vector_dic\n\n\n# 创建样本\ndef create_sample(file_path):\n G = nx.Graph()\n with open(file_path, 'r') as csvFile:\n for line in csvFile:\n node1 = str(line[:-1].split('\\t')[0])\n node2 = str(line[:-1].split('\\t')[1])\n G.add_edge(node1, node2)\n num = int(G.number_of_edges() / 2) # 取样数目\n positive_sample = random.sample(G.edges(), num) # 从list中随机获取一半的边作为一个片断返回\n neg_sample = random.sample(list(nx.non_edges(G)), num)\n for u, v in positive_sample:\n G.remove_edge(u, v)\n for edge in G.edges():\n G[edge[0]][edge[1]]['weight'] = 1\n tagetlist = [positive_sample, neg_sample, num, G]\n return tagetlist\n\n\ndef print_metrics(samlist):\n result = open('soc_wiki.csv', 'a+', newline='')\n writer = csv.writer(result)\n emb_path = 'resultat1.emb'\n num = samlist[2]\n positive_sample = samlist[0]\n neg_sample = samlist[1]\n pos_list = [1] * num\n pos_list.extend([0] * num)\n y_true = np.array(pos_list)\n y_scores = []\n vvdict = read_embedding(emb_path)\n for i in positive_sample:\n y_scores.append(cosine_similarity(vvdict.get(i[0]), vvdict.get(i[1])))\n for i in neg_sample:\n y_scores.append(cosine_similarity(vvdict.get(i[0]), vvdict.get(i[1])))\n y_score = np.array(y_scores)\n print(\"AUC is\", metrics.roc_auc_score(y_true, y_score))\n threshold = np.median(y_score)\n y_score2 = [int(item > threshold) for item in y_score]\n\n\nif __name__ == \"__main__\":\n i = 0\n while i < 1:\n tmplist = create_sample('.\\\\Dataset\\\\bio-HS-HT.edges')\n tarG = tmplist[3]\n print(len(tarG.edges()), tarG.edges())\n print(tarG.number_of_nodes())\n args = parse_args()\n main(args, tarG)\n print_metrics(tmplist)\n i = i + 1\n # main(parse_args())\n","sub_path":"BaseCode/line/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"290532061","text":"#\n# mr-dfs.py\n#\n# Created by Geoffrey Sheir on 21/05/2020\n#\n#\n\nimport cases \nfrom rob import robot\nfrom plotTools import plotter\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n### SET PARAMETERS HERE ###\nk = 1 # number of robots\ncase = cases.case10(k)\nprob = case.gr\n\n# initialise robots\nrobots = []\nfor rID in range(k):\n robots.append(robot(rID))\n\n# tell robots what the problem is\n# CHANGE\nfor rID in range(k):\n robots[rID].setProb(prob)\n \n#%% run algorithm\n\n# initial step for all robots\nfor rID in range(k):\n print(\"rob{} starting at v{}\".format(rID,robots[rID].vNow))\n E = len(prob.v[0].e)\n robots[rID].updatePos(0, rID%E)\n\nendExp = False\nwhile endExp == False:\n \n\n for rID in range(k):\n robots[rID].mrdfs()\n \n algoFinished = True\n for i in range(len(prob.v[0].e)):\n if prob.v[0].e[i].finished == False:\n algoFinished = False\n break\n \n allHome = True\n for rID in range(k):\n if robots[rID].vNow != 0:\n allHome = False\n break\n \n if (algoFinished == True) and (allHome == True):\n print(\"Exploration complete\")\n endExp = True\n break\n\n# create animation\n\nanim = plotter(robots,case)\nanim.playAnim()\n\nimport time\ntime.sleep(100)","sub_path":"Pathfinding/MR-DFS/mr-dfs.py","file_name":"mr-dfs.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"116830474","text":"\"\"\"\n集合-Nim游戏\n给定 n 堆石子以及一个由 k 个不同正整数构成的数字集合 S。\n\n现在有两位玩家轮流操作,每次操作���以从任意一堆石子中拿取石子,每次拿取的石子数量必须包含于集合 S,最后无法进行操作的人视为失败。\n\n问如果两人都采用最优策略,先手是否必胜。\n\n输入格式\n第一行包含整数 k,表示数字集合 S 中数字的个数。\n\n第二行包含 k 个整数,其中第 i 个整数表示数字集合 S 中的第 i 个数 si。\n\n第三行包含整数 n。\n\n第四行包含 n 个整数,其中第 i 个整数表示第 i 堆石子的数量 hi。\n\n输出格式\n如果先手方必胜,则输出 Yes。\n\n否则,输出 No。\n\n数据范围\n1≤n,k≤100,\n1≤si,hi≤10000\n输入样例:\n2\n2 5\n3\n2 4 7\n输出样例:\nYes\n=====================================\n博弈论\n\n 有向图游戏\n\n 给定一个有向无环图,图中有一个唯一的起点,在起点上放有一枚棋子。\n 两名玩家交替地把这枚棋子沿有向边进行移动,每次可以移动一步.无法移动者判负,该游戏被称为有向图游戏。\n 任何一个公平组合游戏都可以转化为有向图游戏。\n 具体方法是,把每个局面看成图中的一个节点,并且从每个局面向沿着合法行动能够到达的下一个局面连有向边。\n\n Mex运算\n\n 设 S表示一个非负整数集合,定义 mex(S)为求出不属于集合 S的最小非负整数的运算,\n 即 mex(S) = min(x), x属于自然数,且x不属于S\n\n SG函数\n\n 在有向图游戏中,对于每个节点 x,设从 x出发共有 k条有向边,分别到达节点 y1, y2 ... yk\n 定义 SG(x)为 x的后继节点 y1, y2 ... yk的 SG函数值构成的集合再执行 mex(S)运算的结果,\n 即 SG(x) = mex({SG(y1), SG(y2), ... , SG(yk)})\n 特别地,整个有向图游戏 G的 SG函数值被定义为有向图游戏起点 s的 SG函数值,即SG(G) = SG(s)\n SG(end) = 0\n\n\n 有向图游戏的和\n\n 设G1, G2, ..., Gm是 m个有向图游戏,定义有向图游戏 G,它的行动规则是任选某个有向图游戏 Gi,\n 并在 Gi上行动一步,G被称为有向图游戏 G1, G2, ..., Gm的和\n 有向图游戏的和的 SG函数值等于它包含的各个子游戏 SG函数值的异或和\n 即:SG(G) = SG(G1) ^ SG(G2) ^ ... ^ SG(Gm)\n\n\n\"\"\"\nN, M = 100 + 10, 10000 + 10\n# S存储的是可供选择的集合, F存储的是所有可能出现过的情况的 SG值, 初始化 F均为 -1,方便查看 SG(x)是否被记录过\nS, F = [], [-1] * M\n\n\ndef SG(x):\n # 因为取石子数目的集合 S是已经确定了的, 所以在递归条件下,每个数的 SG值也都是确定的, 如果F[x]已经存储过了, 直接返回即可\n if F[x] != -1:\n return F[x]\n SET = set()\n for i in range(k):\n _op = S[i]\n if x >= _op: # 尝试当前 x值允许的操作\n SET.add(SG(x - _op)) # 先延伸到终点的 SG值后,再从后往前排查出所有数的 SG值\n\n i = 0\n while True: # 循环完之后, 可以选出没有出现的最小自然数\n if not SET.__contains__(i):\n F[x] = i # 对F[x]赋值\n return i\n i += 1\n\n\nif __name__ == '__main__':\n k = int(input()) # 表示数字集合 S 中数字的个数\n S = list(map(int, input().split())) # 数字集合 S 中的第 i 个数 si\n n = int(input()) # 整数 n\n H = list(map(int, input().split())) # 第 i 堆石子的数量 hi\n\n res = 0\n for i in range(n):\n res ^= SG(H[i]) # 计算所有堆的异或值,基本原理与Nim游戏相同\n\n print('Yes' if res >= 1 else 'No') # res != 0\n","sub_path":"2021/Algorithm/Python/Base/4_math_knowledge/893.py","file_name":"893.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"131594307","text":"from threading import Thread\nfrom time import sleep\n\n#含有参数的线程函数\ndef fun(sec,name):\n print('%s线程开始执行'%name)\n sleep(sec)\n print('%s执行完毕'%name)\n\n#创建多个线程\njobs=[]\nfor i in range(5):\n t=Thread(target=fun,args=(2,),\\\n kwargs={'name':'T%d'%i})\n jobs.append(t)#存储线程对象\n t.start()\n \nfor i in jobs:\n i.join()","sub_path":"mounth001/day29/thread2.py","file_name":"thread2.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"564636542","text":"# this contains all the function that will be used for html update and format\n\n\nimport os\nimport pandas as pd\nimport time\n#from app import User\nimport app\nimport math\nimport json\nimport numpy as np\n\n\n\n\ndef remove_windows_key_word(show_title:str, replace:str) -> str:\n # format is ugly\n condition = True\n while condition:\n if \":\" in show_title:\n show_title = show_title[:show_title.index(\":\")] + replace + show_title[show_title.index(\":\") + 1:]\n #return show_title\n\n elif \"<\" in show_title:\n show_title = show_title[:show_title.index(\"<\")] + replace + show_title[show_title.index(\"<\") + 1:]\n #return show_title\n\n elif \">\" in show_title:\n show_title = show_title[:show_title.index(\">\")] + replace + show_title[show_title.index(\">\") + 1:]\n #return show_title\n\n elif '\"' in show_title:\n show_title = show_title[:show_title.index('\"')] + replace + show_title[show_title.index('\"') + 1:]\n #return show_title\n\n elif \"/\" in show_title:\n show_title = show_title[:show_title.index(\"/\")] + replace + show_title[show_title.index(\"/\") + 1:]\n #return show_title\n\n elif \"\\\\\" in show_title:\n show_title = show_title[:show_title.index(\"\\\\\")] + replace + show_title[show_title.index(\"\\\\\") + 1:]\n #return show_title\n\n elif \"|\" in show_title:\n show_title = show_title[:show_title.index(\"|\")] + replace + show_title[show_title.index(\"|\") + 1:]\n #return show_title\n\n elif \"?\" in show_title:\n show_title = show_title[:show_title.index(\"?\")] + replace + show_title[show_title.index(\"?\") + 1:]\n #return show_title\n\n elif \"*\" in show_title:\n show_title = show_title[:show_title.index(\"*\")] + replace + show_title[show_title.index(\"*\") + 1:]\n #return show_title\n\n else:\n condition = False\n return show_title\n\n\n\n\n\n# the pandas dataframe that contains all anime basic data information\nall_shows_list = pd.read_json(os.path.join(os.getcwd(), \"data_collection\", \"all_shows.json\"), lines=True)\n\n\nprint(all_shows_list)\n# the following is returning different sub pandas dataframe of all_shows_list according to each alphabetical\ndef return_a_list_panda():\n # generate all a list\n a_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"A\") | (all_shows_list[\"showName\"].str[0] == \"a\" )]\n return a_category_panda\n\n\ndef return_other_list_panda():\n a_category_panda = all_shows_list.loc[\n (all_shows_list[\"showName\"].str[0] == \"A\") | (all_shows_list[\"showName\"].str[0] == \"a\")]\n\n\n # generate the all other list\n # all other list will be everything before the first index of a list\n first_a_index = a_category_panda.head(1).index\n\n\n other_category_panda = (all_shows_list.iloc[: first_a_index[0]])\n return other_category_panda\n\n\ndef return_b_list_panda():\n # generate all b list\n b_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"B\") | (all_shows_list[\"showName\"].str[0] == \"b\" )]\n return b_category_panda\n\n\ndef return_c_list_panda():\n # generate all c list\n c_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"C\") | (all_shows_list[\"showName\"].str[0] == \"c\" )]\n return c_category_panda\n\n\ndef return_d_list_panda():\n\n # generate all d list\n d_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"D\") | (all_shows_list[\"showName\"].str[0] == \"d\" )]\n return d_category_panda\n\n\ndef return_e_list_panda():\n # generate all e list\n e_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"E\") | (all_shows_list[\"showName\"].str[0] == \"e\" )]\n return e_category_panda\n\n\ndef return_f_list_panda():\n # generate all f list\n f_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"F\") | (all_shows_list[\"showName\"].str[0] == \"f\" )]\n return f_category_panda\n\n\ndef return_g_list_panda():\n # generate all g list\n g_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"G\") | (all_shows_list[\"showName\"].str[0] == \"g\" )]\n return g_category_panda\n\n\ndef return_h_list_panda():\n # generate all h list\n h_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"H\") | (all_shows_list[\"showName\"].str[0] == \"h\" )]\n return h_category_panda\n\n\ndef return_i_list_panda():\n\n # generate all i list\n i_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"I\") | (all_shows_list[\"showName\"].str[0] == \"i\" )]\n return i_category_panda\n\n\ndef return_j_list_panda():\n # generate all j list\n j_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"J\") | (all_shows_list[\"showName\"].str[0] == \"j\" )]\n return j_category_panda\n\n\ndef return_k_list_panda():\n # generate all k list\n k_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"K\") | (all_shows_list[\"showName\"].str[0] == \"k\" )]\n return k_category_panda\n\n\ndef return_l_list_panda():\n\n # generate all l list\n l_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"L\") | (all_shows_list[\"showName\"].str[0] == \"l\" )]\n return l_category_panda\n\n\ndef return_m_list_panda():\n # generate all m list\n m_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"M\") | (all_shows_list[\"showName\"].str[0] == \"m\" )]\n return m_category_panda\n\n\ndef return_n_list_panda():\n # generate all n list\n n_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"N\") | (all_shows_list[\"showName\"].str[0] == \"n\" )]\n return n_category_panda\n\n\ndef return_o_list_panda():\n # generate all o list\n o_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"O\") | (all_shows_list[\"showName\"].str[0] == \"o\" )]\n return o_category_panda\n\n\ndef return_p_list_panda():\n # generate all p list\n p_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"P\") | (all_shows_list[\"showName\"].str[0] == \"p\" )]\n return p_category_panda\n\n\ndef return_q_list_panda():\n # generate all q list\n q_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"Q\") | (all_shows_list[\"showName\"].str[0] == \"q\" )]\n return q_category_panda\n\n\ndef return_r_list_panda():\n # generate all r list\n r_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"R\") | (all_shows_list[\"showName\"].str[0] == \"r\" )]\n return r_category_panda\n\n\ndef return_s_list_panda():\n\n # generate all s list\n s_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"S\") | (all_shows_list[\"showName\"].str[0] == \"s\" )]\n return s_category_panda\n\n\ndef return_t_list_panda():\n # generate all t list\n t_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"T\") | (all_shows_list[\"showName\"].str[0] == \"t\" )]\n return t_category_panda\n\n\ndef return_u_list_panda():\n\n # generate all u list\n u_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"U\") | (all_shows_list[\"showName\"].str[0] == \"u\" )]\n return u_category_panda\n\n\ndef return_v_list_panda():\n # generate all v list\n v_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"V\") | (all_shows_list[\"showName\"].str[0] == \"v\" )]\n return v_category_panda\n\n\ndef return_w_list_panda():\n # generate all w list\n w_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"W\") | (all_shows_list[\"showName\"].str[0] == \"w\" )]\n return w_category_panda\n\n\ndef return_x_list_panda():\n # generate all x list\n x_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"X\") | (all_shows_list[\"showName\"].str[0] == \"x\" )]\n return x_category_panda\n\n\ndef return_y_list_panda():\n # generate all Y list\n y_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"Y\") | (all_shows_list[\"showName\"].str[0] == \"y\" )]\n return y_category_panda\n\n\ndef return_z_list_panda():\n # generate all Z list\n z_category_panda = all_shows_list.loc[(all_shows_list[\"showName\"].str[0] == \"Z\") | (all_shows_list[\"showName\"].str[0] == \"z\" )]\n return z_category_panda\n\n\ndef add_hightlight(showName:str, searchKey=\"\"):\n if searchKey == \"\":\n return \"\"+showName+\"\"\n else:\n searchKeyIndex = showName.find(searchKey)\n print(searchKeyIndex)\n return showName[0:searchKeyIndex] + \"\" + showName[searchKeyIndex:] + \"\"\n\ndef write_html_click(animeId:int, showname:str, ):\n # the function help to generate the clickable button in the encyclopedia page\n # html format of encyclopedia list\n # putting the id of each show in the panda dataframe\n\n return \"\"\"\n
\n \n \n
\n \n \"\"\".format(animeId, showname)\n\n\ndef write_to_html_form(anime_list_panda, type=\"\", searchKey=\"\"):\n # used for the encyclopedia and search page\n # anime_list_panda is a pandas dataframe contains basic information of anime\n #\n # this function is going to call write_htl_click() to generate a list of clickable buttom by the show_name in anime_list_panda\n # This is used to the encyclopedia page of html\n html_message = \"\"\n if type == \"search\":\n for index, rows in anime_list_panda.iterrows():\n html_message += write_html_click(str(rows[\"animeId\"]), rows[\"showName\"],type, searchKey)\n # html_message += write_html_click( str(rows[\"show_name\"]).replace(\" \", \"%20\"), rows[\"show_name\"])\n else:\n for index, rows in anime_list_panda.iterrows():\n\n html_message += write_html_click(str(rows[\"animeId\"]), rows[\"showName\"])\n #html_message += write_html_click( str(rows[\"show_name\"]).replace(\" \", \"%20\"), rows[\"show_name\"])\n # replace // with space, since query cannot have space inside\n return html_message\n\ndef load_viewdetail_file(animeId:int):\n # this is for the detail view of this specific anime\n # return the path of this anime data\n\n # remember, all anime folder and information is named with its id\n\n # getting the name of this anime correspond to this id,\n\n if all_shows_list.loc[all_shows_list.animeId == animeId].empty:\n # means when this path is not exist in the system, means this anime id is not exist\n return \"error\"\n else:\n\n path = os.path.join(os.getcwd(), \"anime_data\",\n str(animeId),\n \"{}.json\".format(animeId))\n return path\n\n\ndef write_to_detailview_htmlform(path:str, userId:int, animeId:int):\n # this function is generate and return all different part of detailview html page in html\n with open(path, \"r\") as file:\n fileInfo = json.loads(file.read())\n\n return fileInfo[\"show_name\"], image_htmlformat(fileInfo[\"image\"]), alternativetitle_htmlform(fileInfo[\"other_title\"]), genres_htmlform(fileInfo['genre']), plot_htmlform(fileInfo[\"plot\"]), rating_htmlform(userId, animeId), episodeAndRunningtime_htmlform(fileInfo[\"episode\"]), vintage_htmlform(fileInfo[\"vintage\"]), openingTheme_htmlform(fileInfo[\"opening_theme\"]), endingTheme_htmlform(fileInfo[\"ending_theme\"]), type_htmlform(fileInfo['type'])\n\n\ndef image_htmlformat(image_url:str):\n # the image part of detailview html\n return \"\"\"\n
\n \"\"\".format(image_url)\n\n\ndef alternativetitle_htmlform(other_title:list):\n #the alternative title part of detailview html\n if len(other_title) == 0:\n print(\"here\")\n return \"\"\n else:\n return_message = \"\"\"\n
\nAlternative title:\"\"\"\n\n for value in other_title:\n return_message += \"\"\"\n
{}
\"\"\".format(value)\n\n return_message += \"\"\"\n
\"\"\"\n return return_message\n\n\ndef genres_htmlform(genres:list):\n # the genere type of detailview html\n # mayshould update more variety of genre\n return_message = \"\"\"\n
\nGenres:\\n\"\"\"\n if len(genres) == 0:\n return \"\"\n else:\n return_message += \",\\n\".join([\"\"\"\t\t{0}\"\"\".format(genre) for genre in genres])\n return_message += \"\\n
\"\n return return_message\n\n\ndef theme_htmlform(themes:list):\n # the theme part of detailview html\n if len(themes) == 0:\n return \"\"\n else:\n return_message = \"\"\"\n
\nThemes:\\n\"\"\"\n return_message += \",\\n\".join([ \"\"\"\t{}\"\"\".format(theme) for theme in themes])\n return_message += \"\\n
\"\n return return_message\n\n\ndef plot_htmlform(description:str):\n # the plot part of detailview html\n if description == \"\":\n return description\n else:\n return \"\"\"\n
\nPlot Summary:\n\t{}\n
\n \"\"\".format(description)\n\n\ndef episodeAndRunningtime_htmlform(runningtime:str):\n # the running time/episode part of viewdetail html\n print(runningtime)\n if str(runningtime).isdigit() and int(runningtime) == 0:\n # means there is no available data, the program automatically sets to 0\n # for it is impossible to have any running time to be 0\n return \"\"\n elif str(runningtime).isdigit():\n # means this is a tv show, contain number of episode\n return \"\"\"\n
\nNumber of episodes:\n\t{}\n
\"\"\".format(runningtime)\n\n elif runningtime == \"\":\n return \"\"\n else:\n # means this is a movive, a total running time\n return \"\"\"\n
\nRunning time: \n\t{}\n
\n \"\"\".format(runningtime)\n\n\ndef vintage_htmlform(vintage:list):\n # the vintage part of viewdetail html\n if len(vintage) == 0:\n # the vintage part should be a data, therefore should contain something\n # if len(vintage) == 0, means this data was not availabe when the system generat the file\n return \"\"\n else:\n return_message = \"\"\"\n
\nVintage:\n {}\n \"\"\".format(vintage)\n return_message +=\"\"\"\\n
\"\"\"\n return return_message\n\n\ndef officialWebsite_htmlform(url:str):\n if url == \"\":\n return \"\"\n else:\n return \"\"\"\n
\nOfficial website:\n\t\n
\"\"\".format(url)\n\ndef type_htmlform(types:str):\n if types == \"\":\n return ''\n else:\n return \"\"\"\n ({})\n \"\"\".format(types)\n\ndef openingTheme_htmlform(op:list):\n # the opening theme part of this anime\n if len(op) == 0:\n return \"\"\n else:\n return_message = \"\"\"\n
\nOpening Theme:\"\"\"\n\n for i in range(len(op)):\n return_message += \"\"\"\n
#{}: {}
\"\"\".format(i+1, op[i])\n return_message += \"\"\"\\n
\"\"\"\n return return_message\n\n\ndef endingTheme_htmlform(ed:list):\n # the ending part of this anime\n if len(ed) == 0:\n return \"\"\n else:\n return_message = \"\"\"\n
\nEnding Theme:\"\"\"\n\n for i in range(len(ed)):\n return_message += \"\"\"\n
#{}: {}
\"\"\".format(i + 1, ed[i])\n return_message += \"\"\"\\n
\"\"\"\n return return_message\n\n\ndef insertSong_htmlform(insertSong:list):\n # the inserting song part of this anime\n if len(insertSong) == 0:\n # when not song is available\n return \"\"\n else:\n return_message = \"\"\"\n
\nInsert Song:\"\"\"\n\n for i in range(len(insertSong)):\n return_message += \"\"\"\n
#{}: {}
\"\"\".format(i + 1, insertSong[i])\n return_message += \"\"\"\\n
\"\"\"\n return return_message\n\n# a unused function\n\ndef search_by_genre(searchGenre:str):\n\n\n result = pd.DataFrame(columns=[\"show_name\", \"genre\", \"file_category\"])\n for row in all_shows_list.itertuples(index=False):\n if searchGenre in row[1]:\n result = result.append({'show_name':row[0], 'genre':row[1], 'file_category':row[2]}, ignore_index=True)\n return result\n\n\n# used when user returned a rating\ndef update_userRating(userId:int, animeId:int, rating:int, comment:str, time, ):\n # open the rating file data tha contains all the ratings\n filePath = os.path.join(os.getcwd(), \"data_collection\", \"rating_data.json\")\n # load to pandas dataframe\n userRating = pd.read_json(filePath, lines=True)\n\n if ( userRating.loc[(userRating[\"userId\"] == userId) & (userRating[\"animeId\"] == animeId)].empty ) and rating != \"\":\n # when is not find, means this user has not rate this anime\n\n newRow = pd.DataFrame([{\"userId\":userId, \"animeId\":animeId, \"rating\":rating, \"comment\":comment, \"time\":time}])\n\n userRating = userRating.append(newRow, ignore_index=True)\n #print(userRating)\n\n # write back to the file\n userRating.to_json(filePath, orient=\"records\", lines=True)\n else:\n # to prevent the repeat rating when user refresh the page\n #print(\"rated\")\n pass\n\n\ndef rating_htmlform(userId:int, animeId:int):\n # return the rating information, after and before rated in viewdetail part\n ratingFile = pd.read_json(os.path.join(os.getcwd(), \"data_collection\", \"rating_data.json\"), lines=True)\n\n df = (ratingFile.loc[(ratingFile[\"userId\"] == userId) & (ratingFile[\"animeId\"] == animeId)])\n\n return_html = \"\"\n if df.empty:\n # means is has not been rated by current user\n # return a extra rating form\n # this is the rating form with 1 to 5 stars of rating\n return_html += \"\"\"\n
\n

Rating

\n
1(low) to 5(high)
\n
\n
\n \n Comment\n \n \n
\n
\n
\n \"\"\".format(animeId)\n\n # rating info of this animeId\n # a pandas dataframe\n animeRatingInfo = ratingFile.loc[ratingFile[\"animeId\"] == animeId]\n #print(animeRatingInfo)\n return_html += \"\"\"\\\n \n \n
\n\n {}\n\t\t
\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t\n\n\t\t\t\t{}\n\t\t\t\t
\n\t\t\t
\n\t\t
\n
\n \n \"\"\".format(generate_general_review_form(animeId), generate_detail_review_form(animeRatingInfo))\n\n return return_html\n\ndef generate_average_rating_score(animeId:int):\n\n # this function generate the average rating score and each number of 5,4,3,2,1 start rating with bar size of rating form in html\n ratingFile = pd.read_json(os.path.join(os.getcwd(), \"data_collection\", \"rating_data.json\"), lines=True)\n animeRatingInfo = ratingFile.loc[ratingFile[\"animeId\"] == animeId]\n # this return the general rating information of this anime\n totalRatingNumber = len(animeRatingInfo)\n fiveStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 5])\n fourStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 4])\n threeStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 3])\n twoStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 2])\n oneStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 1])\n #print(fiveStarRatingNumber, twoStarRatingNumber, \"here\")\n\n if totalRatingNumber != 0:\n averageRating = (5*fiveStarRatingNumber + 4*fourStarRatingNumber + 3*threeStarRatingNumber + 2*twoStarRatingNumber + 1*oneStarRatingNumber)/totalRatingNumber\n averageRating = round(averageRating,2)\n fiveStarRatingBarPercentage = (fiveStarRatingNumber/totalRatingNumber) * 100\n fiveStarRatingBarPercentage = round(fiveStarRatingBarPercentage,2)\n fourStarRatingBarPercentage = (fourStarRatingNumber/totalRatingNumber) * 100\n fourStarRatingBarPercentage = round(fourStarRatingBarPercentage, 2)\n threeStarRatingBarPercentage = (threeStarRatingNumber/totalRatingNumber) * 100\n threeStarRatingBarPercentage = round(threeStarRatingBarPercentage, 2)\n twoStarRatingBarPercentage = (twoStarRatingNumber / totalRatingNumber) * 100\n twoStarRatingBarPercentage = round(twoStarRatingBarPercentage, 2)\n oneStarRatingBarPercentage = (oneStarRatingNumber / totalRatingNumber) * 100\n oneStarRatingBarPercentage = round(oneStarRatingBarPercentage, 2)\n else:\n # means no user has rate this anime yet\n # means need to set all things to zero, avoid zerodivision error\n averageRating = 0\n fiveStarRatingBarPercentage = 0\n fourStarRatingBarPercentage = 0\n threeStarRatingBarPercentage = 0\n twoStarRatingBarPercentage = 0\n oneStarRatingBarPercentage = 0\n\n return averageRating, fiveStarRatingBarPercentage, fiveStarRatingNumber, fourStarRatingBarPercentage, fourStarRatingNumber, threeStarRatingBarPercentage,threeStarRatingNumber, twoStarRatingBarPercentage, twoStarRatingNumber, oneStarRatingBarPercentage, oneStarRatingNumber\ndef generate_general_review_form(animeId):\n # this return the general rating information of this anime\n # means the total average rating and each 5,4,3,2,1, star rating's bar size\n \"\"\"\n totalRatingNumber = len(animeRatingInfo)\n fiveStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 5])\n fourStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 4])\n threeStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 3])\n twoStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 2])\n oneStarRatingNumber = len(animeRatingInfo.loc[animeRatingInfo[\"rating\"] == 1])\n #print(fiveStarRatingNumber, twoStarRatingNumber, \"here\")\n\n if totalRatingNumber != 0:\n averageRating = (5*fiveStarRatingNumber + 4*fourStarRatingNumber + 3*threeStarRatingNumber + 2*twoStarRatingNumber + 1*oneStarRatingNumber)/totalRatingNumber\n averageRating = round(averageRating,2)\n fiveStarRatingBarPercentage = (fiveStarRatingNumber/totalRatingNumber) * 100\n fiveStarRatingBarPercentage = round(fiveStarRatingBarPercentage,2)\n fourStarRatingBarPercentage = (fourStarRatingNumber/totalRatingNumber) * 100\n fourStarRatingBarPercentage = round(fourStarRatingBarPercentage, 2)\n threeStarRatingBarPercentage = (threeStarRatingNumber/totalRatingNumber) * 100\n threeStarRatingBarPercentage = round(threeStarRatingBarPercentage, 2)\n twoStarRatingBarPercentage = (twoStarRatingNumber / totalRatingNumber) * 100\n twoStarRatingBarPercentage = round(twoStarRatingBarPercentage, 2)\n oneStarRatingBarPercentage = (oneStarRatingNumber / totalRatingNumber) * 100\n oneStarRatingBarPercentage = round(oneStarRatingBarPercentage, 2)\n else:\n # means no user has rate this anime yet\n # means need to set all things to zero, avoid zerodivision error\n averageRating = 0\n fiveStarRatingBarPercentage = 0\n fourStarRatingBarPercentage = 0\n threeStarRatingBarPercentage = 0\n twoStarRatingBarPercentage = 0\n oneStarRatingBarPercentage = 0\n \"\"\"\n averageRating, fiveStarRatingBarPercentage, fiveStarRatingNumber, fourStarRatingBarPercentage, fourStarRatingNumber, threeStarRatingBarPercentage, threeStarRatingNumber, twoStarRatingBarPercentage, twoStarRatingNumber, oneStarRatingBarPercentage, oneStarRatingNumber = generate_average_rating_score(animeId)\n\n return_html = \"\"\"\n\t\t
\n\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t

Average user rating

\n\t\t\t\t\t

{} / 5

\n\t\t\t\t
\n\t\t\t
\n\t\t\t
\n\t\t\t\t

Rating breakdown

\n\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
5
\n\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t80% Complete (danger)\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t
{}
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
4
\n\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t80% Complete (danger)\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t
{}
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
3
\n\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t80% Complete (danger)\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t
{}
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
2
\n\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t80% Complete (danger)\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t
{}
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
1
\n\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t80% Complete (danger)\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t
{}
\n\t\t\t\t
\n\t\t\t
\n\t\t
\n \"\"\".format(averageRating,\n fiveStarRatingBarPercentage, fiveStarRatingNumber,\n fourStarRatingBarPercentage, fourStarRatingNumber,\n threeStarRatingBarPercentage, threeStarRatingNumber,\n twoStarRatingBarPercentage, twoStarRatingNumber,\n oneStarRatingBarPercentage, oneStarRatingNumber)\n\n return return_html\n\n\ndef generate_detail_review_form(animeRatingInfo):\n return_html = \"\"\n for id in list(animeRatingInfo[\"userId\"].values):\n # user id start with 1\n\n\n currentUser = animeRatingInfo.loc[animeRatingInfo[\"userId\"] == id]\n\n if currentUser.empty:\n # means this user has not rate this anime yet\n continue\n user = app.User.query.filter_by(id=int(id)).first()\n if user.iconUrl == \"\":\n # means no image url\n iconUrl = \"data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==\"\n else:\n iconUrl - user.iconUrl\n return_html += \"\"\"\n\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t
{}
\n\t\t\t\t\t\t\t
{}
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n\t\t\t\t\t\t
\n \"\"\".format(iconUrl, user.username ,currentUser[\"time\"].values[0])\n\n # here is for the number of star rating icon that user give to this anime\n for x in range(1,5+1):\n # start with 1, since 1 is the lowest score one can give\n if x <= int(currentUser[\"rating\"].values[0]):\n # button with yellow color\n return_html += \"\"\"\n\t\t\t\t\t\t\t\t\n \"\"\"\n else:\n # rating button with gray color\n return_html += \"\"\"\n\t\t\t\t\t\t\t\t\n \"\"\"\n\n return_html += \"\"\"\n
\n\n\t\t\t\t\t\t\t
{}
\n\t\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t
\n \"\"\".format(currentUser[\"comment\"].values[0])\n\n return return_html\n\n\n\ndef generate_recommend_carousel(recommendAnimeId):\n # carousel is the slide show at the recommendation html page\n # recommendAnimeId is a pandas datafreame, all anime id that was not view by user\n return_SGDcarousel = \"\" # this is for the carousel view, the personalize recommendation\n return_ratingcarousel = \"\" # this is for the generatl rating form\n\n animeAverageRating = pd.DataFrame( data=[[generate_average_rating_score(id), id] for id in recommendAnimeId[\"animeId\"]], columns=[\"averageScore\", \"animeId\"])\n\n animeAverageRating = animeAverageRating.sort_values(by=\"averageScore\", ascending=False) # a sorted pandas dataframe with highest averageScore\n\n\n #for animeId in recommendAnimeId.animeId:\n for i in range(recommendAnimeId.shape[0]):\n\n\n animeId_SGD = recommendAnimeId.iloc[i, 1] # the anime id order for applying SGD\n animeId_averageRating = animeAverageRating.iloc[i,1] # the anime id order for the highest average rating score\n path_SGD = os.path.join(os.getcwd(), \"anime_data\",\n str(animeId_SGD),\n \"{}.json\".format(animeId_SGD, '@'))\n path_averageRating = os.path.join(os.getcwd(), \"anime_data\",\n str(animeId_averageRating),\n \"{}.json\".format(animeId_averageRating, '@'))\n #print(path)\n with open(path_SGD) as file:\n animeInfo_SGD = json.loads(file.read())\n with open(path_averageRating) as files:\n animeInfo_averageRating = json.loads(files.read())\n\n\n imageUrl_SGD = animeInfo_SGD[\"image\"]\n name_SGD = animeInfo_SGD[\"show_name\"]\n\n imageUrl_averageRating = animeInfo_averageRating[\"image\"]\n name_averageRating = animeInfo_averageRating[\"show_name\"]\n\n\n if imageUrl_averageRating == \"\":\n # means not picture availabe\n # set to a default picture\n imageUrl_averageRating = \"https://causeofaction.org/wp-content/uploads/2013/09/Not-available-300x300.gif\"\n if imageUrl_SGD == \"\":\n # means not picture availabe\n # set to a default picture\n imageUrl_SGD = \"https://causeofaction.org/wp-content/uploads/2013/09/Not-available-300x300.gif\"\n\n # the first carousel is different code with the rest\n if return_SGDcarousel == \"\":\n return_SGDcarousel += \"\"\"\n
\n
\n
\n
\n\n \"...\"\n
Top {} recommendation
\n
\n
{}
\n

{}/5

\n \n
\n
\n\n
\n
\n
\n\n \"\"\".format( imageUrl_SGD, i+1, name_SGD, generate_average_rating_score(animeId_SGD)[0], '/viewdetail/{}'.format(animeId_SGD) )\n\n return_ratingcarousel += \"\"\"\n
\n
\n
\n
\n\n \"...\"\n
Top {} recommendation
\n
\n
{}
\n

{}/5

\n \n
\n
\n\n
\n
\n
\n\n \"\"\".format( imageUrl_averageRating, i+1, name_averageRating, generate_average_rating_score(animeId_averageRating)[0], '/viewdetail/{}'.format(animeId_averageRating) )\n\n # the rest of the code for the carousel slide show\n else:\n return_SGDcarousel += \"\"\"\n
\n
\n
\n
\n\n \"...\"\n
Top {} recommendation
\n
\n
{}
\n

{}/5

\n \n
\n
\n\n
\n
\n
\n\n \"\"\".format( imageUrl_SGD, i+1, name_SGD, generate_average_rating_score(animeId_SGD)[0], '/viewdetail/{}'.format(animeId_SGD) )\n\n return_ratingcarousel += \"\"\"\n
\n
\n
\n
\n\n \"...\"\n
Top {} recommendation
\n
\n
{}
\n

{}/5

\n \n
\n
\n\n
\n
\n
\n\n \"\"\".format( imageUrl_averageRating, i+1, name_averageRating, generate_average_rating_score(animeId_averageRating)[0], '/viewdetail/{}'.format(animeId_averageRating) )\n\n #print(return_html)\n return return_SGDcarousel, return_ratingcarousel\n\n\n\ndef generate_search_result(searchWord:str):\n # search by anime title\n searchByTitle = all_shows_list.loc[all_shows_list[\"showName\"].str.contains(searchWord, case=False, regex=False)]\n\n # returned a pandas dataframe with matched anime's basic information\n return searchByTitle\n\ndef generate_genre_search_result(genre:str):\n # will use about 6 to 7 seconds\n # returned the pandas dataframe of anime's basic information that matched to this genre type\n searchByGenre = pd.DataFrame(columns=['showName', 'genre', 'category', 'animeId'])\n\n for index, rows in all_shows_list.iterrows():\n #print(rows[\"genre\"])\n if genre in rows[\"genre\"]:\n\n searchByGenre = searchByGenre.append(rows)\n\n return searchByGenre\n\n\n\n\n# all are some test cases\n\ndef test_genre_search_result():\n print(generate_genre_search_result(\"action\"))\n\n\ndef test_alternativetitle_htmlform():\n print(alternativetitle_htmlform([\"\"\"セブンゴースト (Japanese)\"\"\", \"\"\"神幻拍檔 (Chinese (Taiwan))\"\"\"]))\n\ndef test_image_htmlform():\n print(image_htmlformat(\"https://cdn.animenewsnetwork.com/thumbnails/fit200x200/encyc/A792-26.jpg\"))\n\ndef test_genres_htmlform():\n print(genres_htmlform([\"adventure\", \"horror\", \"supernatural\"]))\n\ndef test_theme_htmlform():\n print(theme_htmlform(['amnesia', 'bishounen']))\n\ndef test_plot_htmlform():\n print(plot_htmlform(\"hello\"))\n\ndef test_episodeAndRunningtime_htmlform():\n print(episodeAndRunningtime_htmlform(\"26\"))\n print(episodeAndRunningtime_htmlform(\" 25 minutes\"))\n\ndef test_vintage_htmlform():\n print(vintage_htmlform([\"2007-01-22 (production completed)\", \"2007-02-16 to 2007-02-19 (ep 1 net premiere to Yahoo! Premium members)\", \"2018-03-28 (Se\\u00f1al Colombia - Colombia)\"]))\n\ndef test_officialWebsite_htmlform():\n print(officialWebsite_htmlform(\"http://www.cwfilms.jp/5cm/index.htm\"))\n\ndef test_openingTheme_htmlform():\n print(openingTheme_htmlform([\"\\\"My Soul, Your Beats!\\\" by Lia\", \"\\\"My Soul, Your Beats! (Gldemo ver.)\\\" by Girls Dead Monster (ep 4)\"]))\n\ndef test_endingTheme_htmlform():\n print(endingTheme_htmlform( [\"\\\"Brave Song\\\" by Aoi Tada\", \"\\\"Ichiban no Takaramono ~Yui final ver.~ (\\u4e00\\u756a\\u306e\\u5b9d\\u7269\\uff5eYui final ver.\\uff5e)\\\" by LiSA (ep 10)\", \"\\\"Ichiban no Takaramono\\\" (\\u4e00\\u756a\\u306e\\u5b9d\\u7269) by Karuta (ep 13)\"]))\n\ndef test_insertSong_htmlform():\n print(insertSong_htmlform([\"\\\"Kamado Tanjir\\u014d no Uta\\\" (\\u7ac8\\u9580\\u70ad\\u6cbb\\u90ce\\u306e\\u3046\\u305f) by Go Shiina featuring Nami Nakagawa (ep 19)\"]))\n\ndef test_search():\n print(generate_search_result(\"date\"))\n\ndef test_add_highlight():\n print(add_hightlight(\"hello\", \"lo\"))\n\n\"\"\"\"\nother = return_other_list_panda()\nfor index, rows in other.iterrows():\n print(rows['file_category'],rows['show_name'])\n\"\"\"\n#print([str(row) for row in all_shows_list[\"show_name\"]])\n#all_shows_list[\"id\"] = [i+1 for i in range(len(all_shows_list[\"show_name\"]))]\n#for show in all_shows_list[\"show_name\"]:\n # print(show)\n#print(remove_windows_key_word(\"009 Re:Cyborg (movie)\", \"@\"))\n\"\"\"\nx = (all_shows_list.loc[all_shows_list.id ==3])\nprint(x.show_name.item())\n#print(return_o_list_panda())\nrating_htmlform(1,5)\n\"\"\"\n#print(all_shows_list[\"id\"])\n\nprint(return_o_list_panda())","sub_path":"load_anime_to_html.py","file_name":"load_anime_to_html.py","file_ext":"py","file_size_in_byte":41527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"163441389","text":"#!/usr/bin/python\n\nfrom field import Field\nfrom tetromino import Tetromino\n\nfrom collections import defaultdict\nfrom functools import cmp_to_key\n\nclass Optimizer():\n\n @staticmethod\n def get_optimal_drop(field, tetromino):\n rotations = [\n tetromino,\n tetromino.copy().rotate_right(),\n tetromino.copy().flip(),\n tetromino.copy().rotate_left(),\n ]\n drops = []\n for rotation, tetromino_ in enumerate(rotations):\n for column in range(Field.WIDTH):\n try:\n f = field.copy()\n row = f.drop(tetromino_, column)\n drops.append({\n 'field': f,\n 'field_gaps': f.count_gaps(),\n 'field_height': f.height(),\n 'tetromino_rotation': rotation,\n 'tetromino_column': column,\n 'tetromino_row': row,\n 'lines_cleared_points': f.lines_cleared_points(),\n 'heuristic': f.lines_cleared_points() - f.height() - 5 * f.count_gaps() + 2 *row - 1 * f.bumpiness()\n })\n # if f.lines_cleared_points()!= 0:\n # print(f.lines_cleared_points())\n # print(f.lines_cleared_points(), f.height(), f.count_gaps(), row,f.lines_cleared_points() + f.height() + f.count_gaps() - row)\n except AssertionError:\n continue\n\n # # First, we pick out all the drops that will produce the least\n # # amount of gaps.\n # lowest_gaps = min([drop['field_gaps'] for drop in drops])\n # drops = list(filter(\n # lambda drop: drop['field_gaps'] == lowest_gaps, drops))\n # # Next we sort for the ones with the lowest field height.\n #\n # lowest_height = min([drop['field_height'] for drop in drops])\n # drops = list(filter(\n # lambda drop: drop['field_height'] == lowest_height, drops))\n # # Finally, we sort for the ones that drop the tetromino in the lowest\n # # row. Since rows increase from top to bottom, we use max() instead.\n # lowest_row = max([drop['tetromino_row'] for drop in drops])\n # drops = list(filter(\n # lambda drop: drop['tetromino_row'] == lowest_row, drops))\n # assert len(drops) > 0\n drops.sort(key = lambda x: x[\"heuristic\"], reverse = True)\n return drops[0]\n\n @staticmethod\n def get_keystrokes(rotation, column, keymap):\n keys = []\n # First we orient the tetronimo\n if rotation == 1:\n keys.append(keymap['rotate_right'])\n elif rotation == 2:\n keys.append(keymap['rotate_right'])\n keys.append(keymap['rotate_right'])\n elif rotation == 3:\n keys.append(keymap['rotate_left'])\n # Then we move it all the way to the the left that we are guaranteed\n # that it is at column 0. The main reason for doing this is that when\n # the tetromino is rotated, the bottom-leftmost piece in the tetromino\n # may not be in the 3rd column due to the way Tetris rotates the piece\n # about a specific point. There are too many edge cases so instead of\n # implementing tetromino rotation on the board, it's easier to just\n # flush all the pieces to the left after orienting them.\n for i in range(4):\n keys.append(keymap['move_left'])\n # Now we can move it back to the correct column. Since pyautogui's\n # typewrite is instantaneous, we don't have to worry about the delay\n # from moving it all the way to the left.\n for i in range(column):\n keys.append(keymap['move_right'])\n keys.append(keymap['drop'])\n return keys\n\nif __name__ == '__main__':\n f = Field()\n f.drop(Tetromino.TTetromino(), 3)\n opt = Optimizer.get_optimal_drop(\n f['tetromino_rotation'], f['tetromino_column'], Tetromino.ITetromino())\n print(opt['field'])\n","sub_path":"codeitsuisse/challenges/tetris/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"451196762","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\ndef get_last_pages(site, url):\n result = requests.get(url)\n soup = BeautifulSoup(result.text, \"html.parser\")\n if site == \"happydesign\":\n pagination = soup.find(\"div\", {\"class\": \"paging\"})\n links = pagination.find_all(\"a\")\n pages = []\n for link in links[2:-2]:\n pages.append(int(link.string))\n max_pages = pages[-1]\n return max_pages\n elif site == \"inhouse\":\n pagination = soup.find(\"span\", {\"class\": \"pg\"})\n links = pagination.find_all(\"a\")\n pages = []\n for link in links[:-7]:\n pages.append(int(link[\"href\"][-1]))\n max_pages = pages[-1]\n return max_pages\n elif site == \"homedesigning\":\n pagination = soup.find(\"div\", {\"class\": \"wp-pagenavi\"})\n links = pagination.find_all(\"a\")\n pages = []\n for link in links[:-1]:\n pages.append(int(link.string))\n max_pages = pages[-1]\n return max_pages\n else:\n return 0\n\n\ndef each_page(site, html):\n if site == \"happydesign\":\n link = (\n \"http://happy.designhouse.co.kr/\" + html.find(\"a\", {\"class\": \"txt\"})[\"href\"]\n )\n title = html.find(\"span\", {\"class\": \"mark2\"}).text.strip()\n img = (\n html.find(\"a\")[\"style\"]\n .replace(\"background-image:url(\", \"\")\n .replace(\");\", \"\")\n )\n return {\"title\": title, \"img\": img, \"link\": link}\n elif site == \"inhouse\":\n link = html.find(\"a\")[\"href\"]\n title = html.find(\"li\", {\"class\": \"gall_text_href\"}).find(\"a\").text\n img = html.find(\"img\")[\"src\"]\n return {\"link\": link, \"img\": img, \"title\": title}\n elif site == \"homedesigning\":\n link = html.find(\"a\")[\"href\"]\n title = html.find(\"a\")[\"title\"]\n img = html.find(\"img\")[\"src\"]\n return {\"title\": title, \"img\": img, \"link\": link}\n else:\n return {}\n\n\ndef extract_items(site, url, last_page=0):\n homes = []\n result = requests.get(url)\n soup = BeautifulSoup(result.text, \"html.parser\")\n if site == \"ohouse\":\n items = soup.find(\"div\", {\"class\": \"container\"}).find_all(\n \"article\", {\"class\": \"project-feed__item\"}\n )\n for item in items:\n link = (\n \"https://ohou.se\"\n + item.find(\"a\", {\"class\": \"project-feed__item__link\"})[\"href\"]\n )\n title = item.find(\"h1\", {\"class\": \"project-feed__item__title\"}).text\n img = item.find(\"img\")[\"src\"]\n # img = info.find(\"img\")[\"data-src\"]\n home_item = {\"title\": title, \"img\": img, \"link\": link}\n homes.append(home_item)\n elif site == \"happydesign\":\n for page in range(last_page):\n result = requests.get(f\"{url}/magazine_list/00010002/0/{page+1}\")\n soup = BeautifulSoup(result.text, \"html.parser\")\n items = soup.find(\"div\", {\"class\": \"list-Wrap\"}).find_all(\"li\")\n for item in items:\n home = each_page(site, item)\n homes.append(home)\n elif site == \"maison\":\n items = soup.find(\"div\", {\"id\": \"posts-container\"}).find_all(\n \"article\", {\"class\": \"post\"}\n )\n for item in items:\n img = item.find(\"img\")[\"src\"]\n link = item.find(\"a\")[\"href\"]\n title = item.find(\"h2\").text\n home_item = {\"title\": title, \"link\": link, \"img\": img}\n homes.append(home_item)\n elif site == \"livingsense\":\n items = soup.find(\"div\", {\"class\": \"viewModeWrap unfold\"}).find_all(\"li\")\n for item in items:\n link = (\n \"https://www.smlounge.co.kr\"\n + item.find(\"a\", {\"class\": \"viewWrap\"})[\"href\"]\n )\n title = item.find(\"p\", {\"class\": \"vTitle\"}).text.strip()\n img = \"https://www.smlounge.co.kr\" + item.find(\"img\")[\"src\"]\n home_item = {\"title\": title, \"link\": link, \"img\": img}\n homes.append(home_item)\n elif site == \"inhouse\":\n for page in range(last_page):\n result = requests.get(f\"{url}&page={page+1}\")\n soup = BeautifulSoup(\n result.content.decode(\"utf-8\", \"replace\"), \"html.parser\"\n )\n items = soup.find_all(\"li\", {\"class\": \"gall_li\"})\n for item in items:\n home = each_page(site, item)\n homes.append(home)\n elif site == \"betterhomes\":\n items = soup.find_all(\"div\", {\"class\": \"category-page-item\"})\n for item in items:\n link = item.find(\"a\")[\"href\"]\n title = item.find(\"a\")[\"data-tracking-content-headline\"]\n img = item.find(\"img\")[\"src\"]\n home_item = {\"title\": title, \"link\": link, \"img\": img}\n homes.append(home_item)\n elif site == \"interiordesign\":\n items_top = soup.find_all(\"div\", {\"class\": \"category-top-item\"})\n items_middle = soup.find_all(\"div\", {\"class\": \"category-middle-item\"})\n for item in items_top:\n link = \"https://www.interiordesign.net\" + item.find(\"a\")[\"href\"]\n title = item.find(\"div\", {\"class\": \"title\"}).text.strip()\n img = item.find(\"img\")[\"src\"]\n home_item = {\"title\": title, \"link\": link, \"img\": img}\n homes.append(home_item)\n for item in items_middle:\n link = \"https://www.interiordesign.net\" + item.find(\"a\")[\"href\"]\n title = item.find(\"div\", {\"class\": \"title\"}).text.strip()\n img = item.find(\"img\")[\"src\"]\n home_item = {\"title\": title, \"link\": link, \"img\": img}\n homes.append(home_item)\n elif site == \"idealhome\":\n items = soup.find_all(\"li\", {\"class\": \"listing-item\"})\n for item in items:\n link = item.find(\"a\")[\"href\"]\n title = item.find(\"h3\").text.strip()\n img = item.find(\"img\")[\"data-src\"]\n home_item = {\"title\": title, \"link\": link, \"img\": img}\n homes.append(home_item)\n elif site == \"homedesigning\":\n for page in range(last_page):\n result = requests.get(f\"{url}/page/{page}\")\n soup = BeautifulSoup(result.text, \"html.parser\")\n items = soup.find_all(\"div\", {\"class\": \"figure post-image\"})\n for item in items:\n home = each_page(site, item)\n homes.append(home)\n elif site == \"trendir\":\n items = soup.find(\"div\", {\"class\": \"list-articles\"}).find_all(\n \"article\", {\"class\": \"post\"}\n )\n for item in items:\n link = item.find(\"a\")[\"href\"]\n title = item.find(\"a\")[\"title\"]\n img = item.find(\"img\")[\"src\"]\n home_item = {\"title\": title, \"img\": img, \"link\": link}\n homes.append(home_item)\n elif site == \"homesandgardens\":\n items = soup.find(\"ul\", {\"class\": \"listing__list\"}).find_all(\n \"li\", {\"class\": \"listing__item listing__item--alternate\"}\n )\n for item in items:\n link = item.find(\"a\")[\"href\"]\n title = item.find(\"h2\").text.strip()\n img = item.find(\"img\").get(\"data-srcset\").split(\",\")[0][:-5]\n home_item = {\"title\": title, \"img\": img, \"link\": link}\n homes.append(home_item)\n else:\n home_item = {}\n homes.append(home_item)\n return homes\n\n\ndef get_site(site):\n if site == \"ohouse\":\n url = \"https://ohou.se/projects?writer=pro\"\n homes = extract_items(site, url)\n elif site == \"happydesign\":\n url = \"http://happy.designhouse.co.kr/magazine\"\n last_page = get_last_pages(site, url)\n homes = extract_items(site, url, last_page)\n elif site == \"maison\":\n url = \"https://www.maisonkorea.com/category/interior/\"\n homes = extract_items(site, url)\n elif site == \"livingsense\":\n url = \"https://www.smlounge.co.kr/article/list?cc=319&mId=NPM0002&ord=1&fold=\"\n homes = extract_items(site, url)\n elif site == \"inhouse\":\n url = \"https://uujj.co.kr/bbs/board.php?bo_table=living\"\n last_page = get_last_pages(site, url)\n homes = extract_items(site, url, last_page)\n elif site == \"betterhomes\":\n url = \"https://www.bhg.com/decorating/\"\n homes = extract_items(site, url)\n elif site == \"interiordesign\":\n url = \"https://www.interiordesign.net/news/residential/\"\n homes = extract_items(site, url)\n elif site == \"idealhome\":\n url = \"https://www.idealhome.co.uk/living-room/living-room-ideas\"\n homes = extract_items(site, url)\n elif site == \"homedesigning\":\n url = \"http://www.home-designing.com/category/living-room-design\"\n last_page = get_last_pages(site, url)\n homes = extract_items(site, url, last_page)\n elif site == \"trendir\":\n url = \"https://www.trendir.com/interiors/\"\n homes = extract_items(site, url)\n elif site == \"homesandgardens\":\n url = \"https://www.homesandgardens.com/interior-design\"\n homes = extract_items(site, url)\n else:\n homes = []\n return homes\n","sub_path":"d_scrapper/idea_scrapper.py","file_name":"idea_scrapper.py","file_ext":"py","file_size_in_byte":9106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"125580665","text":"import unittest\n\n\nclass AssertionExamples(unittest.TestCase):\n\n def test_lists_exact(self):\n list_a = [0, 1]\n list_b = [0, 1]\n #lists must be exactly the same\n #assertEqual calls type specific equality function\n #if args are the same type in python 2.7\n self.assertEqual(list_a, list_b)\n\n def test_lists_order(self):\n list_a = [0, 1]\n list_b = [1, 0]\n #same elements in same quantity but order not checked\n self.assertItemsEqual(list_a, list_b)\n\n def test_lists_dupes(self):\n list_a = [0, 1, 2]\n list_b = [2, 2, 1, 2, 0, 0, 1]\n #set contents are unordered and unique\n self.assertEqual(set(list_a), set(list_b))\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"unittest_demo/test_asserts.py","file_name":"test_asserts.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"312830717","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nclass Freq_Counter:\n '''\n 閾値電圧に対する立ち下がりを検知し、周波数を測定する\n '''\n\n def __init__(self,Vthr):\n self.V_prev=None\n self.counter=0\n self.detected=[]\n self.Vthr=Vthr\n\n def update(self,V):\n if self.V_prev is None:\n self.V_prev=V\n elif (self.V_prev>self.Vthr and V 0] += np.pi\n alpha[alpha < 0] += 2*np.pi\n beta = -np.arctan(1.0*np.asarray(np.sqrt(points[:,1]**2+points[:,0]**2))/(points[:,2]))\n #print(np.round(1.0*r*(points[:,2])/np.asarray(np.sqrt(points[:,1]**2+points[:,0]**2))))\n #beta = 1.*points[:,2]/np.linalg.norm(points[:,2])\n #beta[points[:,0] > 0] += np.pi\n beta[beta < 0] += np.pi\n return np.vstack((np.round(alpha*r*1.0),np.round(1.0*r*beta)))\n \n\n#%%\ndef align(t1, t2):\n return [[i, np.argmin(np.abs(t2-t1[i]))] for i in range(len(t1))]\n\n\n#%%\nimport matplotlib.pyplot as plt\npic_3d = sep2world()\ntime_pair = align(cam_data['ts'][0], vicon_data['ts'][0])\nr = 500\ncount = 0\npic = np.zeros((2500,int(np.floor(2*np.pi*r))+10, 3), dtype='uint8')\nfor item in time_pair[::]:\n img = cam_data['cam'][..., item[0]].reshape(-1,3)\n q = vicon_data['rots'][...,item[1]]\n #q1 = q[item[1]]\n #print(item[1])\n rotate = np.transpose(q.dot(pic_3d))\n #rotate = np.transpose(q.dot(pic_3d))\n X_2d = np.transpose(car2Cyl(rotate,r))\n #print(X_2d)\n X_2d = np.asarray(X_2d, dtype='int')\n X_2d = (X_2d + np.asarray([[0,800]]))\n if np.max(X_2d[:,1]) > 2500 or np.min(X_2d[:,1])<=0:\n count += 1\n continue\n pic[X_2d[:,1], X_2d[:,0], :] = img\nplt.figure(figsize=(18,5))\nplt.imshow(pic[::-1,:,:])","sub_path":"ece276_pandrome/Chunyi_Lyu/ece276a_as2.py","file_name":"ece276a_as2.py","file_ext":"py","file_size_in_byte":16971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"418215171","text":"# -×- coding:utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport dataprocess.FeatureSelect as fs\n\n\n# get the wind direct, old version\ndef windDriectold(pooling_mat):\n \"\"\"\n 根据 4.5km 高度处的图像求解风向(图像最大值), 根据风向裁剪 6×6\n :param pooling_mat: (15*4*10*10)\n :return: (15*4*6*6)\n \"\"\"\n direct_mat = np.zeros((15, 4, 6, 6))\n xx = np.arange(15)\n yy = np.arange(15)\n # 分别存储四个方向\n windDrirct = np.zeros(4) # [0. 0. 0. 0.]\n sumx = 0\n sumy = 0\n\n for i in range(15):\n # 获取高度为 3.5km 图像\n wind_mat = pooling_mat[i, 3] # forth level\n raw, column = wind_mat.shape # 10×10\n # 展成一维 返回最大数值的索引\n positon = np.argmax(wind_mat)\n # 最大值的坐标\n m, n = divmod(positon, column) # position of the max value point\n xx[i] = m\n yy[i] = n\n\n for i in range(0, 3): # 0,1,2\n sumx += xx[i]\n sumy += yy[i]\n # 前三个时刻横坐标平均值\n sumx = sumx/3\n # 前三个时刻纵坐标平均值\n sumy = sumy/3\n\n for i in range(3, 15):\n # 向右移动\n if xx[i] > sumx: # north wind\n windDrirct[2] += 1\n if xx[i] < sumx:\n windDrirct[3] += 1\n # 向上移动\n if yy[i] > sumy: # west wind\n windDrirct[0] += 1\n if yy[i] < sumy:\n windDrirct[1] += 1\n # 获取移动的最大距离\n direct = np.argmax(windDrirct)\n\n for i in range(15):\n for j in range(4):\n temp_mat = pooling_mat[i, j] # 获取池化图像(10×10)\n # 最大移动范围 12\n if direct == 0: # 上移\n if windDrirct[2] > 6: # west north 右移动\n direct_mat1 = temp_mat[1:7, 0:6]\n elif windDrirct[3] > 6: # west south 左边移动\n direct_mat1 = temp_mat[3:9, 0:6]\n else:\n direct_mat1 = temp_mat[2:8, 0:6]\n\n elif direct == 1: # 向下移动\n if windDrirct[2] > 6: # east\n direct_mat1 = temp_mat[1:7, 4:10]\n elif windDrirct[3] > 6: # east south\n direct_mat1 = temp_mat[3:9, 4:10]\n else:\n direct_mat1 = temp_mat[2:8, 4:10]\n\n elif direct == 2:\n if windDrirct[0] > 6: # west north\n direct_mat1 = temp_mat[0:6, 1:7]\n elif windDrirct[1] > 6: # east north\n direct_mat1 = temp_mat[0:6, 3:9]\n else:\n direct_mat1 = temp_mat[0:6, 2:8]\n\n elif direct == 3:\n if windDrirct[0] > 6: # west south\n direct_mat1 = temp_mat[4:10, 1:7]\n elif windDrirct[1] > 6: # east south\n direct_mat1 = temp_mat[4:10, 3:9]\n else:\n direct_mat1 = temp_mat[4:10, 2:8]\n else:\n direct_mat1 = temp_mat[2:8, 2:8]\n\n direct_mat[i][j] = direct_mat1\n\n return direct_mat.reshape(2160)\n\n\n# get wind direct, new version\ndef windDriect1ave(pooling_mat):\n\n direct_mat = np.zeros((15, 4, 6, 6))\n xx = np.arange(15)\n yy = np.arange(15)\n windDrirct = np.zeros(4)\n\n for i in range(15):\n wind_mat = pooling_mat[i, 3]\n raw, column = wind_mat.shape\n sumx = 0\n sumy = 0\n temp = wind_mat.reshape(1,100)\n paramsort = np.argsort(-temp)\n\n for j in range(5):\n sumx += paramsort[0][j]//column\n sumy += paramsort[0][j]%column\n\n xx[i] = sumx//5\n yy[i] = sumy//5\n\n for i in range(1,15):\n if (xx[i] > xx[0]):\n windDrirct[2] += 1\n if (xx[i] < xx[0]):\n windDrirct[3] += 1\n if (yy[i] > yy[0]):\n windDrirct[0] += 1\n if (yy[i] < yy[0]):\n windDrirct[1] += 1\n\n direct=np.argmax(windDrirct)\n\n for i in range(15):\n\n for j in range(4):\n\n temp_mat = pooling_mat[i,j]\n\n if(direct == 0):\n if(windDrirct[2]>7):\n direct_mat1 = temp_mat[1:7,0:6]\n elif(windDrirct[3]>7):\n direct_mat1 = temp_mat[3:9,0:6]\n else:\n direct_mat1 = temp_mat[2:8,0:6]\n\n elif(direct == 1):\n if (windDrirct[2] > 7):\n direct_mat1 = temp_mat[1:7,4:10]\n elif (windDrirct[3] > 7):\n direct_mat1 = temp_mat[3:9,4:10]\n else:\n direct_mat1 = temp_mat[2:8,4:10]\n\n elif(direct==2):\n if (windDrirct[0] > 7):\n direct_mat1 = temp_mat[0:6,1:7]\n elif (windDrirct[1] > 7):\n direct_mat1 = temp_mat[0:6,3:9]\n else:\n direct_mat1 = temp_mat[0:6,2:8]\n\n elif (direct == 3):\n if (windDrirct[0] > 7):\n direct_mat1 = temp_mat[4:10,1:7]\n elif (windDrirct[1] > 7):\n direct_mat1 = temp_mat[4:10,3:9]\n else:\n direct_mat1 = temp_mat[4:10,2:8]\n\n else:\n direct_mat1 = temp_mat[2:8, 2:8]\n\n direct_mat[i][j]=direct_mat1\n\n return direct_mat\n\n#extend data in eight directions\ndef extendData(pooling_mat):\n\n return_value=np.zeros((8, 15, 4, 6, 6))\n\n for i in range(15):\n\n for j in range(4):\n\n temp_mat = pooling_mat[i,j]\n\n #topdown\n temp_mat1 = np.flipud(temp_mat)\n #leftright\n temp_mat2 = np.fliplr(temp_mat)\n #topdown-leftright\n temp_mat3 = np.fliplr(temp_mat1)\n #turn 90\n temp_mat4 = np.rot90(temp_mat)\n #turn 270\n temp_mat5 = np.rot90(temp_mat, 3)\n #turn 90-topdown\n temp_mat6 = np.flipud(temp_mat4)\n #tun 90-leftright\n temp_mat7 = np.fliplr(temp_mat4)\n\n return_value[0][i][j] = temp_mat\n return_value[1][i][j] = temp_mat1\n return_value[2][i][j] = temp_mat2\n return_value[3][i][j] = temp_mat3\n return_value[4][i][j] = temp_mat4\n return_value[5][i][j] = temp_mat5\n return_value[6][i][j] = temp_mat6\n return_value[7][i][j] = temp_mat7\n\n return return_value\n\n\n# convolution 5*5\ndef train_convolution(line, data_type):\n \"\"\"\n :param line: 数据集的每一行 train_i, y, data\n :param data_type: train or test\n :return: id_lable(train_i, y) data(15*4*20*20)\n \"\"\"\n cate = line[0].split(',')\n id_label = [cate[0]]\n\n if data_type == 'train':\n id_label.append(float(cate[1])) # 获取降水值\n\n record = [int(cate[2])] # 雷达图像素\n length = len(line)\n\n for i in range(1, length):\n record.append(int(line[i]))\n # 数据格式 101×101 分张, 101×101×4 四张属于同一个高度, 15×4×10×101 15个属于一个样本\n mat = np.array(record).reshape(15, 4, 101, 101) # 转互成 [15×[4×[101×101]]]矩阵\n con_mat = np.zeros((15, 4, 20, 20))\n\n # 使用卷积核 5×5 将 100×100 图像变换成 20×20\n for i in range(15):\n for j in range(4):\n temp_mat = mat[i, j] # 获取时序为 i 高度为 j 的图像 101*101\n temp_mat = np.delete(temp_mat, 0, axis=0) # 删除第一行\n temp_mat = np.delete(temp_mat, 0, axis=1) # 删除第一列 100*100\n for m in range(20):\n for n in range(20):\n # 用 5*5 的矩阵逐行扫描\n avg_mat = temp_mat[m*5:m*5+5, n*5:n*5+5] # 5×5\n # 卷积求平均值\n con_mat[i, j, m, n] = np.average(avg_mat)\n\n return id_label, con_mat\n\n\n# max pooling\ndef max_pooling(con_mat):\n\n pooling_mat = np.zeros((15, 4, 10, 10)) # 10,10\n\n for i in range(15):\n for j in range(4):\n temp_mat = con_mat[i, j]\n for m in range(10): # 10\n for n in range(10): # 10\n max_mat = temp_mat[2*m:2*m+2, n*2:n*2+2]\n pooling_mat[i, j, m, n] = np.max(max_mat)\n\n return pooling_mat\n\n\n# process wind data\ndef dataprocess(filename, data_type, windversion):\n\n header_list = ['id']\n\n for i in range(432): # 6000\n feature = 'thxy_' + str(i+1)\n header_list.append(feature)\n\n if data_type == 'train':\n header_list += ['label']\n\n # header_list : id thxy_1 thxy_2 hxy_3 ... thxy_431 thxy_432 label\n df = pd.DataFrame(columns=header_list)\n\n with open(filename) as fr:\n if data_type == 'train':\n sample_num = 10000\n elif data_type == 'testB':\n sample_num = 2000\n\n for i in range(1, sample_num + 1):\n\n line = fr.readline().strip().split(' ')\n # 得到标签和降水数值 数据卷积处理(15*4*101*101)->(15×4×20×20)\n id_label, con_mat = train_convolution(line, data_type)\n # 数据进行池化 2×2 (15×4×20×20)->(15*4*10*10)\n pooling_mat = max_pooling(con_mat)\n\n if windversion == 'new' and data_type == 'train':\n eightValue = extendData(windDriect1ave(pooling_mat))\n for j in range(8):\n value = eightValue[j].reshape((15, 4, 36))\n value = fs.slice_h(value, time=15, m=6, n=6, h=1, asd=1)\n value = fs.slice_t(value, time_sum=15, time_slice=12, m=6, n=6, h=1)\n simp = list(value)\n temp = [id_label[0]]\n temp += simp\n\n if data_type == 'train':\n temp += [id_label[1]]\n\n # print(temp)\n df_temp = pd.DataFrame([temp], columns=header_list)\n df = df.append(df_temp, ignore_index=True)\n\n else:\n\n if windversion == 'old':\n # 根据风向进行裁剪\n value = windDriectold(pooling_mat)\n else: # new test\n value = windDriect1ave(pooling_mat).reshape(2160)\n\n value = value.reshape((15, 4, 36)) # value 15*4*6*6\n value = fs.slice_h(value, time=15, m=6, n=6, h=1, asd=1) # value (15, 1, 36) 截取 1.5km 的高度的图像\n value = fs.slice_t(value, time_sum=15, time_slice=12, m=6, n=6, h=1) # value(1, 12*1*6*6) 截取后 12 张\n simp = list(value) # 12*6*6 = 432\n temp = [id_label[0]] # train_i\n temp += simp # train_i value\n\n if data_type == 'train':\n temp += [id_label[1]] # train_i value label\n\n #print(temp)\n df_temp = pd.DataFrame([temp], columns=header_list)\n df = df.append(df_temp, ignore_index=True)\n\n print(df.head())\n\n if windversion == 'old': \n df.to_csv('../data/'+data_type+'_'+windversion+'_wind_4240.csv', index=False, float_format='%.3f')\n else:\n df.to_csv('../data/'+data_type+'_'+windversion+'_wind_1ave_8extend.csv',index=False,float_format='%.3f')\n\n return df\n\n\n#the path of train set & the path of testB set\n#trainfile = '../data/train.txt'\n#testBfile = '../data/testB.txt'\n\n#produces the train set of 'old' wind\n#dataprocess(trainfile, data_type='train',windversion='old')\n#proceces the testB set of 'old' wind\n#dataprocess(testBfile, data_type='testB',windversion='old')\n\n#produces the extended train set\n#dataprocess(trainfile, data_type='train',windversion='new')\n#produces the extended testB set\n#dataprocess(testBfile, data_type='testB',windversion='new')\n","sub_path":"private/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":11853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"325736896","text":"from os import write\nfrom flask import Flask, jsonify, request\nfrom flask_cors import CORS\nimport json\n\n# configuration\nDEBUG = True\n\n# instantiate the app\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n# enable CORS\nCORS(app, resources={r'/*': {'origins': '*'}})\n\n\ndb = {}\n\n\ndef load_db():\n with open('db.json', 'r') as db_file:\n db = json.loads(db_file.read())\n\n\ndef save_db():\n with open('db.json', 'w') as db_file:\n db_file.write(json.dumps(db))\n\n\ndef add_db(word, color):\n if word in db:\n db[word].append(color)\n else:\n db[word] = [color]\n save_db()\n\n\nload_db()\n\n\n@app.route('/ping', methods=['GET'])\ndef ping_pong():\n return jsonify('PONG! -- from flask')\n\n\n@app.route('/add', methods=['POST'])\ndef add_books():\n response_object = {'status': 'success'}\n post_data = request.get_json()\n word = post_data['word']\n color = post_data['color']\n add_db(word, color)\n response_object['message'] = 'word/color added!'\n return jsonify(response_object)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"560783875","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 4 10:36:57 2019\n\n@author: LaurencT\n\"\"\"\n\nfrom argparse import ArgumentParser\n\ndef ltli_argument_parser(DATA_DIR, GRAPH_DIR, OUTPUTS_DIR, BACKUP_DIR, SLIDES_DIR,\n PARAM_CSV_NAME, ESTIMATES_CSV_NAME, POPULATION_CSV_NAME,\n BURDEN_CSV_NAME, COVERAGE_XLS_NAME, COVERAGE_SHEET_NAME,\n PPT_TEMPLATE_NAME):\n \"\"\"Takes strings reflecting directories and file names and returns an \n argument that contains user overrides of those strings where relevant\n \"\"\"\n parser = ArgumentParser(description = 'Input strings to override the default ' +\n 'folder locations required to get data and write outputs')\n\n parser.add_argument('--DATA_DIR', \n type = str, \n help = 'A string indicating the folder containing the' +\n ' model data. The default is ' + DATA_DIR, \n default = DATA_DIR,\n required = False)\n parser.add_argument('--GRAPH_DIR', \n type = str, \n help = 'A string indicating the folder where the graphs' +\n ' should be exported. The default is ' + GRAPH_DIR, \n default = GRAPH_DIR,\n required = False)\n parser.add_argument('--OUTPUTS_DIR', \n type = str, \n help = 'A string indicating the folder where the outputs' +\n ' should be exported. The default is ' + OUTPUTS_DIR, \n default = OUTPUTS_DIR,\n required = False)\n parser.add_argument('--BACKUP_DIR', \n type = str, \n help = 'A string indicating the folder where the parameters' +\n ' should be backed up. The default is ' + BACKUP_DIR, \n default = BACKUP_DIR,\n required = False)\n parser.add_argument('--SLIDES_DIR', \n type = str, \n help = 'A string indicating the folder where the ppt slides' +\n ' should be exported. The default is ' + SLIDES_DIR, \n default = SLIDES_DIR,\n required = False)\n parser.add_argument('--PARAM_CSV_NAME', \n type = str, \n help = 'A string indicating the file name for the model' +\n ' parameters. The default is ' + PARAM_CSV_NAME, \n default = PARAM_CSV_NAME,\n required = False)\n parser.add_argument('--ESTIMATES_CSV_NAME', \n type = str, \n help = 'A string indicating the file name for the output' +\n ' estimates. The default is ' + ESTIMATES_CSV_NAME, \n default = ESTIMATES_CSV_NAME,\n required = False)\n parser.add_argument('--POPULATION_CSV_NAME', \n type = str, \n help = 'A string indicating the file name for the population' +\n ' data. The default is ' + POPULATION_CSV_NAME, \n default = POPULATION_CSV_NAME,\n required = False)\n parser.add_argument('--BURDEN_CSV_NAME', \n type = str, \n help = 'A string indicating the file name for the burden' +\n ' data. The default is ' + BURDEN_CSV_NAME, \n default = BURDEN_CSV_NAME,\n required = False)\n parser.add_argument('--COVERAGE_XLS_NAME', \n type = str, \n help = 'A string indicating the file name for the coverage' +\n ' data. The default is ' + COVERAGE_XLS_NAME, \n default = COVERAGE_XLS_NAME,\n required = False)\n parser.add_argument('--COVERAGE_SHEET_NAME', \n type = str, \n help = 'A string indicating the excel sheet name for the' +\n ' coverage data. The default is ' + COVERAGE_SHEET_NAME, \n default = COVERAGE_SHEET_NAME,\n required = False)\n parser.add_argument('--PPT_TEMPLATE_NAME', \n type = str, \n help = 'A string indicating the file name for the ppt template ' +\n ' to use for the slides. The default is ' + PPT_TEMPLATE_NAME, \n default = PPT_TEMPLATE_NAME,\n required = False)\n \n args = parser.parse_args()\n \n return args\n\ndef print_selected_arguments(DATA_DIR, GRAPH_DIR, OUTPUTS_DIR, BACKUP_DIR, SLIDES_DIR,\n PARAM_CSV_NAME, ESTIMATES_CSV_NAME, POPULATION_CSV_NAME,\n BURDEN_CSV_NAME, COVERAGE_XLS_NAME, COVERAGE_SHEET_NAME,\n PPT_TEMPLATE_NAME):\n \"\"\"Prints strings indicating the directories / file names selected by the user\n \"\"\"\n print('You selected', DATA_DIR, 'as the DATA_DIR', sep = ' ')\n print('You selected', GRAPH_DIR, 'as the GRAPH_DIR', sep = ' ')\n print('You selected', OUTPUTS_DIR, 'as the OUTPUTS_DIR', sep = ' ')\n print('You selected', BACKUP_DIR, 'as the BACKUP_DIR', sep = ' ')\n print('You selected', SLIDES_DIR, 'as the SLIDES_DIR', sep = ' ')\n print('You selected', PARAM_CSV_NAME, 'as the PARAM_CSV_NAME', sep = ' ')\n print('You selected', ESTIMATES_CSV_NAME, 'as the ESTIMATES_CSV_NAME', sep = ' ')\n print('You selected', POPULATION_CSV_NAME, 'as the POPULATION_CSV_NAME', sep = ' ')\n print('You selected', BURDEN_CSV_NAME, 'as the BURDEN_CSV_NAME', sep = ' ')\n print('You selected', COVERAGE_XLS_NAME, 'as the COVERAGE_XLS_NAME', sep = ' ')\n print('You selected', COVERAGE_SHEET_NAME, 'as the COVERAGE_SHEET_NAME', sep = ' ')\n print('You selected', PPT_TEMPLATE_NAME, 'as the PPT_TEMPLATE_NAME', sep = ' ')","sub_path":"argument_parser.py","file_name":"argument_parser.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"92004138","text":"# maximum value of 3 integers\r\nprint('find maximum with 3 integers')\r\na = int(input('a: '))\r\nb = int(input('b: '))\r\nc = int(input('c: '))\r\n\r\nmaximum = a\r\nif b > maximum: maximum = b\r\nif c > maximum: maximum = c\r\n\r\nprint(f'maximum value is {maximum}')","sub_path":"1.01 maximum.py","file_name":"1.01 maximum.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"362375454","text":"import sys\nimport csv\n\n\ndef inside_bounds(lon, lat):\n min_lat, max_lat = (39.86966235384007, 45.79239431452086)\n min_lon, max_lon = (-75.49804687250003, 73.80615234125003)\n return (min_lon <= lon <= max_lon) and (min_lat <= lat <= max_lat)\n\n\ndef parse_old(lines):\n coord_index = 75\n obs_index = 155\n inside_bounds(2,2)\n results = []\n\n\n for line in lines[1:]:\n if line[coord_index] == \"\":\n continue\n\n lat, lon = map(float, line[coord_index].split(\",\"))\n if not inside_bounds(lon, lat):\n continue\n\n observed = line[obs_index] == \"Positive\"\n results.append([lat, lon, observed])\n\n return results\n\ndef parse_new(lines):\n lon_index = 0\n lat_index = 1\n obs_index = 10\n results = []\n for line in lines[1:]:\n lon, lat = map(float, [line[lon_index], line[lat_index]])\n observed = line[obs_index] == \"present\"\n\n if not inside_bounds(lon, lat):\n continue\n\n results.append([lat, lon, observed])\n return results\n\n\ndef parse_csv(file):\n csvreader = csv.reader(file, delimiter=\",\", quotechar='\"')\n lines = [line for line in csvreader]\n if lines[0][0] == \"objectid\":\n return parse_old(lines)\n\n else:\n return parse_new(lines)\n\n\n\ndef write_results(results):\n with open(\"glossy_observations.csv\", \"w\") as f:\n f.write(\"lon,lat,present\\n\")\n joined = \"\\n\".join(map(lambda x: \",\".join(map(str, x)), results))\n f.write(joined + \"\\n\")\n\n\nif __name__ == '__main__':\n final_results = []\n for file in sys.argv[1:]:\n with open(file, encoding=\"latin-1\") as f:\n final_results.extend(parse_csv(f))\n\n write_results(final_results)\n\n\n\n","sub_path":"scripts/python/parse_observations.py","file_name":"parse_observations.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"289509744","text":"import ConfigParser\nimport os\nfrom StringIO import StringIO\n\nhomedir = os.getenv('APPDATA' if os.name.lower() == 'nt' else 'HOME', None)\ndefault_cfg = StringIO(\"\"\"\n[visual]\nbackground = black\nforeground = white\nheight = 800\nwidth = 800\ncortex = classic\ndefault_view = lateral\n\n[overlay]\nmin_thresh = 2.0\nmax_thresh = robust_max\n\n[options]\nlogging_level = INFO\nsubjects_dir =\n\"\"\")\n\nconfig = ConfigParser.ConfigParser()\nconfig.readfp(default_cfg)\nconfig.read([os.path.expanduser('~/.surfer.cfg'), 'surfer.cfg'])\n","sub_path":"surfer/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"607771388","text":"import numpy as np\nfrom itertools import compress\nimport cv2\nimport h5py\nfrom glob import glob\nimport os\nimport pickle\nIMG_DIR = 'card_images'\nWIDTH = 620\nHEIGHT = 450\nCHANNELS = 3\n\n\ndef collapse_types(types_file, out):\n types = np.load(types_file, allow_pickle=True)\n col_types = []\n for list in types:\n col_types.append(list[0])\n np.save(out, col_types)\n\n\ndef generate_labels(label_file):\n labels = np.load(label_file)\n label_dict = {}\n label_num = 0\n for label in labels:\n if label not in label_dict.keys():\n label_dict[label] = label_num\n label_num += 1\n return label_dict\n\n\ndef types_tally(col_types_file):\n col_types = np.load(col_types_file)\n types_count = {}\n for single_type in col_types:\n if single_type not in types_count.keys():\n types_count[single_type] = 1\n else:\n types_count[single_type] += 1\n return types_count\n\n\ndef cmc_to_int(cmc_file, out):\n cmc = np.load(cmc_file)\n int_cmc = []\n for f in cmc:\n int_cmc.append(int(f))\n np.save(out, int_cmc)\n\n\ndef color_to_int(color_file, out, label_out):\n color = np.load(color_file, allow_pickle=True)\n int_color = []\n color_labels = {}\n label = 0\n for c in color:\n c_str = \"\"\n for el in c:\n c_str = c_str + el\n if c_str not in color_labels:\n color_labels[c_str] = label\n label = label + 1\n int_color.append(color_labels[c_str])\n # np.save(out, int_color)\n print(color_labels)\n if label_out:\n with open(label_out, 'wb') as handle:\n pickle.dump(color_labels, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\ndef filter_data(colors_file, ids_file, cmc_file, types_file, names_file, boolean_list, colors_out=None, ids_out=None,\n cmc_out=None, types_out=None, names_out=None):\n colors = np.load(colors_file, allow_pickle=True)\n ids = np.load(ids_file)\n cmc = np.load(cmc_file)\n types = np.load(types_file, allow_pickle=True)\n names = np.load(names_file)\n colors = list(compress(colors, boolean_list))\n ids = list(compress(ids, boolean_list))\n cmc = list(compress(cmc, boolean_list))\n types = list(compress(types, boolean_list))\n names = list(compress(names, boolean_list))\n if colors_out:\n np.save(colors_out, colors)\n else:\n np.save(colors_file, colors)\n if ids_out:\n np.save(ids_out, ids)\n else:\n np.save(ids_file, ids)\n if cmc_out:\n np.save(cmc_out, cmc)\n else:\n np.save(cmc_file, cmc)\n if types_out:\n np.save(types_out, types)\n else:\n np.save(types_file, types)\n if names_out:\n np.save(names_out, names)\n else:\n np.save(names_file, names)\n\n\ndef filter_process(colors_file, ids_file, cmc_file, types_file, names_file, boolean_list, colors_out=None, ids_out=None,\n cmc_out=None, types_out=None, names_out=None, label_out=None):\n filter_data(colors_file, ids_file, cmc_file, types_file, names_file, boolean_list, colors_out=colors_out, ids_out=ids_out,\n cmc_out=cmc_out, types_out=types_out, names_out=names_out)\n if colors_out:\n color_to_int(colors_out, colors_out, label_out)\n else:\n color_to_int(colors_file, colors_out, label_out)\n if cmc_out:\n cmc_to_int(cmc_out, cmc_out)\n else:\n cmc_to_int(cmc_file, cmc_out)\n if types_out:\n collapse_types(types_out, types_out)\n else:\n collapse_types(types_file, types_file)\n\n\ndef to_h5(data_dir, label_type):\n labels = np.load(os.path.join(data_dir, label_type + '.npy'))\n ids = np.load(os.path.join(data_dir, 'ids.npy'))\n names = np.load(os.path.join(data_dir, 'names.npy'))\n with h5py.File(data_dir + '/data.h5', 'w') as hf:\n for (i, id) in enumerate(ids):\n image = cv2.imread(os.path.join(IMG_DIR, id+'.png'))\n image = cv2.resize(image, (HEIGHT, WIDTH), interpolation=cv2.INTER_CUBIC)\n Xset = hf.create_dataset(\n name='X_' + id,\n data=image,\n shape=(HEIGHT, WIDTH, CHANNELS),\n maxshape=(HEIGHT, WIDTH, CHANNELS),\n compression=\"gzip\",\n compression_opts=9)\n yset = hf.create_dataset(\n name='y_' + id,\n data=labels[i],\n shape=(1, ),\n maxshape=(None,),\n compression=\"gzip\",\n compression_opts=9)\n\n\ndef reduce_images(height, width, in_dir, out_dir):\n images = glob(os.path.join(in_dir, \"*.png\"))\n for img in images:\n image = cv2.imread(img)\n image = cv2.resize(image, (width, height), interpolation=cv2.INTER_CUBIC)\n fname = img.split('\\\\')[1]\n cv2.imwrite(out_dir + '\\\\' + fname, image)\n\n\ndef test_train_split(label_dir, label_type, test_train_split):\n ids = np.load(label_dir + '/ids.npy')\n labels = np.load(label_dir + '/' + label_type + '.npy')\n indices = np.arange(ids.shape[0])\n np.random.shuffle(indices)\n train_indices = indices[:int(len(indices) * test_train_split)]\n np.save(label_dir + '\\\\' + 'ids_train.npy', ids[train_indices])\n np.save(label_dir + '\\\\' + label_type + '_train.npy', labels[train_indices])\n test_indices = indices[int(len(indices) * test_train_split):]\n np.save(label_dir + '\\\\' + 'ids_test.npy', ids[test_indices])\n np.save(label_dir + '\\\\' + label_type + '_test.npy', labels[test_indices])\n\n\ncolors = np.load('raw_data_new/colors.npy', allow_pickle=True)\n\nfilter_process('raw_data_new/colors.npy', 'raw_data_new/ids.npy', 'raw_data_new/cmc.npy', 'raw_data_new/types.npy', 'raw_data_new/names.npy', list(map(lambda c: len(c) < 2, colors)),\n colors_out='monocolor_new/colors.npy', ids_out='monocolor_new/ids.npy', cmc_out='monocolor_new/cmc.npy', types_out='monocolor_new/types.npy', names_out='monocolor_new/names.npy')\n# types_count = types_tally('monocolor_new/types.npy')\n# types = np.load('monocolor_new/types.npy')\n# filter_data('monocolor_new/colors.npy', 'monocolor_new/ids.npy', 'monocolor_new/cmc.npy', 'monocolor_new/types.npy', 'monocolor_new/names.npy', list(map(lambda t: types_count[t] >= 100, types)),\n# colors_out='monocolor_new/types_100/colors.npy', ids_out='monocolor_new/types_100/ids.npy', cmc_out='monocolor_new/types_100/cmc.npy', types_out='monocolor_new/types_100/types.npy', names_out='monocolor_new/types_100/names.npy')\n# reduce_images(315, 434, 'card_images_new', 'extra_reduced_images_new')\n#dict = generate_labels('monocolor_new/colors.npy')\nprint(\"hello\")\n# with open('monocolor_new/colors.pickle', 'wb') as handle:\n# pickle.dump(dict, handle, protocol=pickle.HIGHEST_PROTOCOL)\nfilter_process('raw_data_new/colors.npy', 'raw_data_new/ids.npy', 'raw_data_new/cmc.npy', 'raw_data_new/types.npy', 'raw_data_new/names.npy', list(map(lambda c: len(c) < 3, colors)),\n colors_out='dualcolor_new/colors.npy', ids_out='dualcolor_new/ids.npy', cmc_out='dualcolor_new/cmc.npy', types_out='dualcolor_new/types.npy', names_out='dualcolor_new/names.npy')\n# filter_data('dualcolor_new/colors.npy', 'dualcolor_new/ids.npy', 'dualcolor_new/cmc.npy', 'dualcolor_new/types.npy', 'dualcolor_new/names.npy', list(map(lambda t: types_count[t] >= 100, types)),\n# colors_out='dualcolor_new/types_100/colors.npy', ids_out='dualcolor_new/types_100/ids.npy', cmc_out='dualcolor_new/types_100/cmc.npy', types_out='dualcolor_new/types_100/types.npy', names_out='dualcolor_new/types_100/names.npy')\n# filter_data('dualcolor_new/colors.npy', 'dualcolor_new/ids.npy', 'dualcolor_new/cmc.npy', 'dualcolor_new/types.npy', 'dualcolor_new/names.npy', list(map(lambda t: types_count[t] >= 400, types)),\n# colors_out='dualcolor_new/types_400/colors.npy', ids_out='dualcolor_new/types_400/ids.npy', cmc_out='dualcolor_new/types_400/cmc.npy', types_out='dualcolor_new/types_400/types.npy', names_out='dualcolor_new/types_400/names.npy')\n# test_train_split('monocolor_new', 'colors', .8)\n# test_train_split('monocolor_new/types_100', 'types', .8)\n# test_train_split('dualcolor_new', 'colors', .8)\n# test_train_split('dualcolor_new/types_100', 'types', .8)\n\n","sub_path":"process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":8229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"3069239","text":"# Created by Chenye Yang, Haokai Zhao, Zhuoyue Xing on 2019/9/28.\n# Copyright © 2019 Chenye Yang, Haokai Zhao, Zhuoyue Xing . All rights reserved.\n\nfrom machine import I2C, Pin\nimport ssd1306\nimport time\n\n\ni2c = I2C(-1, scl=Pin(5), sda=Pin(4)) # initialize access to the I2C bus\ni2c.scan()\noled = ssd1306.SSD1306_I2C(128, 32, i2c) # the width=128 and height=32\nredLED = Pin(15, Pin.OUT, value = 0)\n\nweekday = {0:'Monday', 1:'Tuesday', 2:'Wednesday', 3:'Thursday', 4:'Friday', 5:'Saturday', 6:'Sunday'}\nmonthdays = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31, }\n\n# When the button A,B,C on OLED is pressed, OLED Pin A,B,C will generate a LOW voltage\nswitchA = Pin(2, Pin.IN) # GPIO#2 has a pullup resistor connected to it\nswitchB = Pin(13, Pin.IN) # GPIO#13 is the same as the MOSI 'SPI' pin\nswitchC = Pin(0, Pin.IN) # GPIO#0 does not have an internal pullup\n# We have to give Pin0 Pin13 a outer pullup resistor, but be aware the maximum current drawn per pin is 12mA\n# minimum resistor is 250 ohm\n\n# switch A is the function menu switch (short press) and confirm changed time switch (long press)\n# switch B is the increasing number switch\n# switch C is the moving and confirming function switch\n\n'''\nCurrent Time --A(Short)--> Menu --A(Short)--> Nothing Happen\n\t\t\t\t\t \t\t--A(Long)--> Back to Current Time \n\t\t\t\t\t \t\t--B--> Move arrow and select function\n\t\t\t\t\t\t\t --C--> Enter function \t\t\t\t\t--Function 1--> N/A\n\t\t\t\t\t\t\t \t\t\t\t\t \t\t\t\t\t--Function 2--> --A(Long)--> Save alarm time and return to current time [Highly recommend way for press switch A]\n\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t--A(Short)--> Back to menu ----> If you do this, please choose the Func 3 many times or long press Switch A, then program will back to normal\n\t\t\t\t\t\t\t \t\t\t\t\t \t\t\t\t\t\t\t\t\t--B--> Add number, step = 1\n\t\t\t\t\t\t\t \t\t\t\t\t \t\t\t\t\t\t\t\t\t--C--> Move cursor forward\n\t\t\t\t\t\t\t \t\t\t\t\t \t\t\t\t\t--Function 3--> Back to current time\n\n'''\n\n\nrtc = machine.RTC() # real time clock\nrtc.datetime((2019, 9, 8, 1, 4, 7, 2, 0)) # initialize, set a specific date and time\n# (year, month, day, weekday, hours, minutes, seconds, mseconds)\n# weekday is automatically computed and value=0-6\n# 2019.13 => 2020.1 automatically\n\n# The first function - show current time\ndef FuncSCT():\n\t# Storeage the current date and time to list\n\tdateList = [int(rtc.datetime()[0]), int(rtc.datetime()[1]), int(rtc.datetime()[2]), int(rtc.datetime()[3])]\n\ttimeList = [int(rtc.datetime()[4]), int(rtc.datetime()[5]), int(rtc.datetime()[6])]\n\t# Covert list to \n\tdateStr = \"{:0>4d}\".format(dateList[0])+'-'+\"{:0>2d}\".format(dateList[1])+'-'+\"{:0>2d}\".format(dateList[2])\n\tweekStr = weekday[dateList[3]]\n\ttimeStr = \"{:0>2d}\".format(timeList[0])+':'+\"{:0>2d}\".format(timeList[1])+':'+\"{:0>2d}\".format(timeList[2])\n\t# Put string to OLED\n\toled.text(dateStr, 0, 0)\t# (message, x, y, color)\n\toled.text(weekStr, 0, 11)\n\toled.text(timeStr, 0, 22) \n\tprint (dateStr+' '+timeStr)\n\t# # alarm count down\n\t# global alarmTime\n\t# oled.text(str(alarmTime - time.time()), 64, 11)\n\n# debouncing\n# Return 1: equal, means NOT a bounce and the key is stable now\n# Return 0: NOT equal, means it's just a bounce\ndef Debounce(pin):\n\tcurrentValue = pin.value()\t\t\t\t# once called, read a value and record as current value\n\ttime.sleep_ms(20)\t\t\t\t\t\t# after 20ms, which means waiting for the bouncing end\n\treturn pin.value() == currentValue\t\t# check if the pin value equals to that 20ms ago\n\n# In the function choose menu, show the arrow\ndef Arrow(item):\n\toled.text('>', 0, int(item)*10+0)\n\n# Show the function choose menu\ndef Menu():\n\toled.text('1. Change time', 7, 0)\t# (message, x, y, color)\n\toled.text('2. Set alarm', 7, 11)\n\toled.text('3. Curt time', 7, 22)\n\n\n# In the set time function, show the cursor under text\ndef Cursor(x,y):\n\toled.text('_', x, y)\n\n# In the set time function, show the changed time\ndef FuncChgT(changeTime):\n\t# Covert list to \n\tdateStr = \"{:0>4d}\".format(changeTime[0])+'-'+\"{:0>2d}\".format(changeTime[1])+'-'+\"{:0>2d}\".format(changeTime[2])\n\ttimeStr = \"{:0>2d}\".format(changeTime[3])+':'+\"{:0>2d}\".format(changeTime[4])+':'+\"{:0>2d}\".format(changeTime[5])\n\t# Put string to OLED\n\toled.text(dateStr, 0, 0)\t# (message, x, y, color)\n\toled.text(timeStr, 0, 11) \n\n\n# refresh the OLED, remove residue\ndef Refresh(rate):\n\ttime.sleep_ms(int(1000/rate))\t# every 1000/rate ms\n\toled.fill(0)\t\t\t\t# To fill the entire screen with black, that is, refresh the screen\n\n\n# interrupt handler\ndef Interrupt(pin):\n\toled.fill(0) # clear\n\titem = 0 # select which item in menu. 0-first item; 1-second item; 2-current time\n\twhile 1:\n\t\tRefresh(10) # OLED refresh at 10Hz\n\t\tArrow(item)\n\t\tMenu()\n\t\toled.show()\n\t\t\n\t\t# in case user press the switch A in the menu, not cause another interrupt\n\t\t# also to cancel the interrupt caused by \"back to the main menu and save change\" in the change time screen\n\t\tif switchA.value() == 0:\n\t\t\tif Debounce(switchA):\n\t\t\t\treturn\n\n\t\t# Change the arrow pointing, change the choosed item\n\t\tif switchB.value() == 0:\n\t\t\tif Debounce(switchB):\n\t\t\t\titem += 1\n\t\t\t\tif item > 2:\n\t\t\t\t\titem = 0\n\n\t\t# From the menu, go forward\n\t\tif switchC.value() == 0:\n\t\t\tif Debounce(switchC):\n\t\t\t\t# choosing the first function\n\t\t\t\t# if item == 0:\t\n\n\t\t\t\t# choosing the second function\n\t\t\t\tif item == 1:\t\t\t\n\t\t\t\t\tprint('2. Set alarm')\n\t\t\t\t\t# Storeage the current date and time to list, year month day hour minute second\n\t\t\t\t\tchangeTime = [int(rtc.datetime()[0]), int(rtc.datetime()[1]), int(rtc.datetime()[2]), int(rtc.datetime()[4]), int(rtc.datetime()[5]), int(rtc.datetime()[6])]\n\t\t\t\t\tindexCT = 0\n\n\t\t\t\t\twhile 1:\n\t\t\t\t\t\tRefresh(10) \t\t\t# clear OLED\n\t\t\t\t\t\tFuncChgT(changeTime) \t# show changed time\n\t\t\t\t\t\tif indexCT > 2:\n\t\t\t\t\t\t\tCursor(9+(indexCT-3)*23, 13)\t# show cursor in second line (time)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tCursor(24+indexCT*23, 2)\t\t# show cursor in first line (date)\n\t\t\t\t\t\toled.show()\n\n\t\t\t\t\t\t# in the change time screen, switch A is LONG pressed, back to the main menu and save change\n\t\t\t\t\t\t# ATTENTION, short press switch A will lead to the interrupt handler, and show the menu.\n\t\t\t\t\t\t# long press switch A will first quit the second interrupt, and then exec the code here\n\t\t\t\t\t\tif switchA.value() == 0:\n\t\t\t\t\t\t\tif Debounce(switchA): \n\t\t\t\t\t\t\t\tglobal alarmTime\n\n\t\t\t\t\t\t\t\t# year can't carry\n\t\t\t\t\t\t\t\tyearChangeSecs = (changeTime[0]-int(rtc.datetime()[0]))*31536000\n\n\t\t\t\t\t\t\t\t# if month carry to year, first translate it to changed days\n\t\t\t\t\t\t\t\tmonthChangeSecs = 0\n\t\t\t\t\t\t\t\tif changeTime[1]-int(rtc.datetime()[1]) > 0: # Not carry to another year\n\t\t\t\t\t\t\t\t\tfor i in range(changeTime[1]-int(rtc.datetime()[1])):\n\t\t\t\t\t\t\t\t\t\tmonthChangeSecs += monthdays[int(rtc.datetime()[1])+i]\n\t\t\t\t\t\t\t\telse: # carry to another\n\t\t\t\t\t\t\t\t\tfor i in range(int(rtc.datetime()[1])-changeTime[1]):\n\t\t\t\t\t\t\t\t\t\tmonthChangeSecs = monthChangeSecs - monthdays[changeTime[1]+i]\n\t\t\t\t\t\t\t\t# then translate it to changed secs\n\t\t\t\t\t\t\t\tmonthChangeSecs = monthChangeSecs*86400\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t# if days carry to month or not carry to month\n\t\t\t\t\t\t\t\tdayChangeSecs = (changeTime[2]-int(rtc.datetime()[2]))*86400\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t# if hours carry to day or not carry to day\n\t\t\t\t\t\t\t\thourChangeSecs = (changeTime[3]-int(rtc.datetime()[4]))*3600\n\n\t\t\t\t\t\t\t\t# if mins carry to hour or not carry to hour\n\t\t\t\t\t\t\t\tminChangeSecs = (changeTime[4]-int(rtc.datetime()[5]))*60\n\n\t\t\t\t\t\t\t\t# if secs carry to min or not carry to min\n\t\t\t\t\t\t\t\tsecChangeSecs = (changeTime[5]-int(rtc.datetime()[6]))\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\talarmTime = time.time() + (yearChangeSecs+monthChangeSecs+dayChangeSecs+hourChangeSecs+minChangeSecs+secChangeSecs)\n\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t# in the change time screen, switch C is pressed, move the cursor\n\t\t\t\t\t\tif switchC.value() == 0: \n\t\t\t\t\t\t\tif Debounce(switchC): \n\t\t\t\t\t\t\t\tindexCT += 1\n\t\t\t\t\t\t\t\tif indexCT > 5: indexCT = 0 # only have 6 parameters to change\n\t\t\t\t\t\t\n\t\t\t\t\t\t# in the change time screen, switch B is pressed, add 1 to the value corresponding to the cursor\n\t\t\t\t\t\tif switchB.value() == 0:\n\t\t\t\t\t\t\tif Debounce(switchB): \n\t\t\t\t\t\t\t\tchangeTime[indexCT] += 1\n\t\t\t\t\t\t\t\tif changeTime[5] > 59: # second carry to minute\n\t\t\t\t\t\t\t\t\tchangeTime[5] = changeTime[5] - 60\n\t\t\t\t\t\t\t\t\tchangeTime[4] += 1\n\t\t\t\t\t\t\t\tif changeTime[4] > 59: # minute carry to hour\n\t\t\t\t\t\t\t\t\tchangeTime[4] = changeTime[4] - 60\n\t\t\t\t\t\t\t\t\tchangeTime[3] += 1\n\t\t\t\t\t\t\t\tif changeTime[3] > 23: # hour carry to day\n\t\t\t\t\t\t\t\t\tchangeTime[3] = changeTime[3] - 24\n\t\t\t\t\t\t\t\t\tchangeTime[2] += 1\n\t\t\t\t\t\t\t\tif changeTime[2] > monthdays[changeTime[1]]: # day carry to month\n\t\t\t\t\t\t\t\t\tchangeTime[2] = changeTime[2] - monthdays[changeTime[1]]\n\t\t\t\t\t\t\t\t\tchangeTime[1] += 1\n\t\t\t\t\t\t\t\tif changeTime[1] > 12: # month carry to year\n\t\t\t\t\t\t\t\t\tchangeTime[1] = changeTime[1] - 12\n\t\t\t\t\t\t\t\t\tchangeTime[0] += 1\n\n\t\t\t\t# choose the third function i.e. return to the current time, quit interrupt handler\n\t\t\t\telse:\n\t\t\t\t\treturn\n\n\n# use falling edge as interupt\nswitchA.irq(trigger = Pin.IRQ_FALLING, handler = Interrupt)\n\n\nglobal alarmTime\nalarmTime = time.time() -1\t\t# initial alarmtime = -1, to ensure the alarm not burst when program starts\n\n\nrunTime = time.time() + 180\t\t\t\t# program life time is 20s\n\nwhile (runTime - time.time()) > 0:\t\t# main function\n\tFuncSCT()\n\toled.show()\n\tRefresh(10) # OLED refresh at 10Hz\n\tif (alarmTime - time.time()) == 0:\n\t\tredLED.value(1)\n\tif (alarmTime - time.time()) == -3:\n\t\tredLED.value(0)\n\n\n\n","sub_path":"Lab/Lab3/lab3_group12_check3.py","file_name":"lab3_group12_check3.py","file_ext":"py","file_size_in_byte":9253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"220059081","text":"import nltk\nimport dj_database_url\nimport reddit\nimport psycopg2\nimport time\nfrom math import sqrt\nfrom string import lower\nfrom consts import TITLE, SELF, COMMENT\n\nclass DocCollection:\n\n def __init__ (self):\n db = dj_database_url.config()\n self.conn = psycopg2.connect(database=db.get('NAME', 'redditsearch2'), user=db.get('USER', 'andrew'), password=db.get('PASSWORD', 'password'), host=db.get('HOST', 'localhost'))\n self.conn.autocommit = False\n self.cur = self.conn.cursor() \n\n def wilson (self, ups, downs):\n n = ups + downs\n z = 1.6 #1.0 = 85%, 1.6 = 95%\n \n if n > 0:\n phat = float(ups) / n\n else:\n return 0\n\n return sqrt(phat+z*z/(2*n)-z*((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)\n \n\n def build_dist (self, body, wilson):\n stemmer = nltk.stem.porter.PorterStemmer()\n\n stopwords = [x.strip() for x in open(\"stopwords.txt\", \"r\").readlines()]\n clean = [w.lower() for w in nltk.word_tokenize(body) if not w.lower() in stopwords]\n \n stems = []\n for word in clean:\n if len(word) < 20:\n stems.append(stemmer.stem(lower(word)))\n\n freqs = nltk.probability.FreqDist(stems)\n\n for key in freqs:\n if freqs[key] > 0:\n freqs[key] = freqs[key] #*= wilson\n else:\n del(freqs[key])\n \n return freqs\n\n def insert_dist (self, dist, parent_id):\n for word in dist:\n if dist[word] > 0:\n# print(\"test\")\n self.cur.execute(\"insert into word (string, freq, text_of) values (%s, %s, %s);\",\n [word, dist[word], parent_id])\n\n def add (self, post):\n post_wilson = self.wilson(post.ups, post.downs)\n\n self.cur.execute(\"select count(*) from post where thing_id=%s;\", [post.id])\n if self.cur.fetchone()[0] == 1:\n self.cur.execute(\"update post set ups=%s, downs=%s, wilson=%s where thing_id=%s;\", [post.ups, post.downs, post_wilson, post.id])\n else:\n self.cur.execute(\"insert into text_block values (%s);\", [post.id]);\n self.cur.execute(\"insert into post values (%s, %s, %s, %s, %s, %s);\", [post.id, post.title, post.url, post.ups, post.downs, post_wilson])\n\n dist = self.build_dist(post.title, post_wilson)\n self.insert_dist(dist, post.id)\n\n comment_text = \"\"\n comment_wilson = 0\n for idx in range(len(post.comments) - 1):\n comment = post.comments[idx]\n comment_wilson = self.wilson(comment.ups, comment.downs)\n\n comment_text += \" \" + comment.body\n\n self.cur.execute(\"delete from word where text_of = %s\", [post.id + \"c\"])\n self.cur.execute(\"delete from comment where thing_id = %s\", [post.id + \"c\"])\n self.cur.execute(\"delete from text_block where thing_id = %s\", [post.id + \"c\"])\n\n self.cur.execute(\"insert into text_block values (%s);\", [post.id + \"c\"])\n self.cur.execute(\"insert into comment values (%s, %s);\", [post.id + \"c\", post.id]) \n\n dist = self.build_dist(comment_text, comment_wilson)\n self.insert_dist(dist, post.id + \"c\")\n \n self.conn.commit()\n","sub_path":"doc.py","file_name":"doc.py","file_ext":"py","file_size_in_byte":3113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"226343530","text":"import pathlib,sys\nfrom os import listdir\nfrom PIL import Image\n\nfiles = listdir()\nfor i in range(len(files)):\n image = Image.open(files[i])\n w,h = image.size\n x1 = 80\n y1 = 80\n x2 = w-80\n y2 = h-80\n image = image.crop([x1,y1,x2,y2])\n image.save(files[i])\n print('successfully processed',files[i])\n","sub_path":"groundtruthsegmentation/groundtruth_dataset/crop.py","file_name":"crop.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"572185778","text":"\n#\n# Copyright 2010-2012 Fabric Technologies Inc. All rights reserved.\n#\n\nfrom FabricEngine.CreationPlatform.RT.Math import *\nfrom FabricEngine.CreationPlatform.Nodes.Rendering import *\nfrom FabricEngine.CreationPlatform.Nodes.Lights import *\nfrom FabricEngine.CreationPlatform.Nodes.Manipulation import *\nfrom FabricEngine.CreationPlatform.Nodes.Kinematics import *\nfrom FabricEngine.CreationPlatform.Nodes.Primitives import *\nfrom FabricEngine.CreationPlatform.Managers.Exporters.AlembicExporterImpl import AlembicExporter\n\nfrom FabricEngine.CreationPlatform.PySide import *\n\n\nclass DemoApplication(CreationPlatformApplication):\n \n def __init__(self):\n \n super(DemoApplication, self).__init__(\n basicRenderPasses = False,\n menuNames = ['File', 'Edit', 'Tools', 'Help']\n )\n\n self.setWindowTitle(\"Creation Platform Primitives\")\n \n # Setup Application Services. \n self.setupUndoRedo()\n self.setupExport()\n\n self.setupSunlight(sunlightCastShadows=True, areaLightAngle=3.0)\n self.setupViewports()\n self.setupCamera(cameraPosition=Vec3(40, 70, 100))\n self.setupGrid()\n self.setupSelection()\n \n # query the constructed components\n scene = self.getScene()\n\n # create the shaders\n phongMaterial = Material(scene, xmlFile='PhongMaterial')\n phongMaterial.addPreset(name='red',diffuseColor=Color(1.0,0.0,0.0))\n phongMaterial.addPreset(name='green', diffuseColor=Color(0.0,1.0,0.0))\n phongMaterial.addPreset(name='blue', diffuseColor=Color(0.0,0.0,1.0))\n\n flatMaterial = Material(scene, xmlFile='FlatMaterial')\n flatMaterial.addPreset(name='red', color=Color(1.0, 0.0, 0.0))\n flatMaterial.addPreset(name='green', color=Color(0.0,1.0,0.0))\n flatMaterial.addPreset(name='blue', color=Color(0.0,0.0,1.0))\n flatMaterial.addPreset(name='babyblue', color=Color(0.0,1.0,1.0))\n flatMaterial.addPreset(name='yellow', color=Color(1.0,1.0,0.0))\n\n\n flatPointsMaterial = Material(scene, xmlFile='FlatPointsMaterial')\n flatPointsMaterial.addPreset(name='redPoints', color=Color(1.0, 0.0, 0.0))\n flatPointsMaterial.addPreset(name='greenPoints', color=Color(0.0,1.0,0.0), pointSize = 3.0)\n flatPointsMaterial.addPreset(name='bluePoints', color=Color(0.0,0.0,1.0), pointSize = 3.0)\n\n flatLinesMaterial = Material(scene, xmlFile='FlatLinesMaterial')\n flatLinesMaterial.addPreset(name='redLines', color=Color(1.0, 0.0, 0.0), lineWidth = 1.0)\n flatLinesMaterial.addPreset(name='greenLines', color=Color(0.0,1.0,0.0), lineWidth = 1.0)\n flatLinesMaterial.addPreset(name='blueLines', color=Color(0.0,0.0,1.0), lineWidth = 1.0)\n flatLinesMaterial.addPreset(name='babyblueLines', color=Color(0.0,1.0,1.0), lineWidth = 1.0)\n flatLinesMaterial.addPreset(name='yellowLines', color=Color(1.0,1.0,0.0), lineWidth = 1.0)\n\n\n vertexColorLinesMaterial = Material(scene, xmlFile='FlatVertexColorLinesMaterial')\n vertexColorLinesMaterial.addPreset(name='vertexColors' )\n\n imageLib = Image2DLibrary(scene)\n imageLib.addImage(name='BuildingTexture4Mask', filePath=FabricEngine.CreationPlatform.buildAbsolutePath( '..', 'Resources', 'Samples', 'BuildingTexture4Mask.jpg'), glRepeat=True, forceRefresh=False)\n imageLib.addImage(name='latlonggradient', filePath=FabricEngine.CreationPlatform.buildAbsolutePath( '..', 'Resources', 'Samples', 'latlonggradient.jpg'), glRepeat=True, forceRefresh=False)\n\n texturedMaterial = Material(scene, xmlFile='PhongTexturedMaterial')\n texturedMaterial.addPreset(name='gridTexture', texture=(imageLib, 0) )\n texturedMaterial.addPreset(name='gradientTexture', texture=(imageLib, 1) )\n\n\n # create the instances\n #########################################\n # Points\n GeometryInstance(scene,\n name='PointsPlaneInstance',\n geometry=PointsPlane(scene,\n length=10.0,\n width=10.0,\n lengthSections=10,\n widthSections=10\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(-30, 10, 40),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=flatPointsMaterial,\n materialPreset='redPoints'\n )\n #########################################\n # Lines\n GeometryInstance(scene,\n name='LinesCrossInstance',\n geometry=LinesCross(scene,\n size=7.0\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(-30, 10, 20),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=flatLinesMaterial,\n materialPreset='redLines'\n )\n GeometryInstance(scene,\n name='LinesCircleInstance',\n geometry=LinesCircle(scene,\n radius=7.0\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(-10, 10, 20),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=flatLinesMaterial,\n materialPreset='greenLines'\n )\n GeometryInstance(scene,\n name='LinesRectangleInstance',\n geometry=LinesRectangle(scene,\n length=7.0,\n width=3.0\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(10, 10, 20),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=flatLinesMaterial,\n materialPreset='blueLines'\n )\n GeometryInstance(scene,\n name='LinesAxesInstance',\n geometry=LinesAxes(scene,\n size=7.0\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(30, 10, 20),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=vertexColorLinesMaterial,\n materialPreset='vertexColors'\n )\n GeometryInstance(scene,\n name='LinesGridInstance',\n geometry=LinesGrid(scene,\n size_x=15.0,\n size_z=15.0,\n sections_x=5,\n sections_y=1,\n sections_z=5\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(50, 10, 20),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=flatLinesMaterial,\n materialPreset='babyblueLines'\n )\n GeometryInstance(scene,\n name='LinesBoundingBoxInstance',\n geometry=LinesBoundingBox(scene,\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(70, 10, 20),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=flatLinesMaterial,\n materialPreset='yellowLines'\n )\n\n ########################################\n # Polygon Meshes\n GeometryInstance(scene,\n name='PolygonMeshPlaneInstance',\n geometry=PolygonMeshPlane(scene,\n length= 15.0,\n width= 15.0,\n lengthSections=3,\n widthSections=3\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(-70, 10, 0),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=texturedMaterial,\n materialPreset='gridTexture'\n )\n GeometryInstance(scene,\n name='PolygonMeshCuboidInstance',\n geometry=PolygonMeshCuboid(scene,\n length= 15.0,\n width= 15.0,\n height=15.0\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(-50, 10, 0),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=texturedMaterial,\n materialPreset='gridTexture'\n )\n GeometryInstance(scene,\n name='PolygonMeshConeInstance',\n geometry=PolygonMeshCone(scene,\n radius= 4.0,\n height=16.0,\n detail=100\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(-30, 10, 0),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=phongMaterial,\n materialPreset='blue'\n )\n\n GeometryInstance(scene,\n name='PolygonMeshSphereInstance',\n geometry=PolygonMeshSphere(scene,\n radius= 10.0,\n detail=100\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(-10, 10, 0),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=texturedMaterial,\n materialPreset='gradientTexture'\n )\n\n GeometryInstance(scene,\n name='PolygonMeshTorusInstance',\n geometry=PolygonMeshTorus(scene,\n innerRadius=3.0,\n outerRadius=6.0,\n detail=100\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(10, 10, 0),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=phongMaterial,\n materialPreset='blue'\n )\n\n GeometryInstance(scene,\n name='PolygonMeshCylinderInstance',\n geometry=PolygonMeshCylinder(scene,\n radius=4.0,\n height=16.0,\n sides=240,\n loops=2,\n caps=True\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(30, 10, 0),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=texturedMaterial,\n materialPreset='gridTexture'\n )\n\n GeometryInstance(scene,\n name='PolygonMeshTeapotInstance',\n geometry=PolygonMeshTeapot(scene,\n size= 7,\n detail=10\n ),\n transform=Transform(scene,\n globalXfo=Xfo(Vec3(50, 10, 0),Quat(),Vec3(1.0,1.0,1.0))\n ),\n material=texturedMaterial,\n materialPreset='gridTexture'\n )\n \n instanceInspector = SGNodeInspectorDockWidget(None, title=\"Instance\")\n geometryInspector = SGNodeInspectorDockWidget(None, title=\"Geometry\")\n transformInspector = SGNodeInspectorDockWidget(None, title=\"Transform\")\n materialInspector = SGNodeInspectorDockWidget(None, title=\"Material\")\n self.addDockWidget(QtCore.Qt.RightDockWidgetArea, instanceInspector)\n self.addDockWidget(QtCore.Qt.RightDockWidgetArea, geometryInspector)\n self.addDockWidget(QtCore.Qt.RightDockWidgetArea, transformInspector)\n self.addDockWidget(QtCore.Qt.RightDockWidgetArea, materialInspector)\n\n\n selectionManager = self.getSelectionManager()\n def selectionChanged(event):\n selection = selectionManager.getSelection()\n if len(selection) == 1:\n instanceNode, instanceId, metaData = selection[0]\n instanceInspector.setNode(instanceNode)\n geometryInspector.setNode(instanceNode.getInPort('Geometry').getConnectedNode())\n materialInspector.setNode(instanceNode.getInPort('Geometry').getConnectedNode())\n transformInspector.setNode(instanceNode.getInPort('Transform').getConnectedNode())\n else:\n instanceInspector.setNode(None)\n geometryInspector.setNode(None)\n materialInspector.setNode(None)\n transformInspector.setNode(None)\n \n selectionManager.addEventListener('instanceSelected', selectionChanged)\n selectionManager.addEventListener('instanceDeselected', selectionChanged)\n\n # Add a ground plane (to see shadows)\n phongMaterial.addPreset(name = 'gray', diffuseColor = Color(0.5,0.5,0.5), specularFactor=0.2)\n GeometryInstance( scene,\n material=phongMaterial,\n materialPreset='gray',\n transform=Transform(scene, globalXfo=Xfo(tr=Vec3(0, -1, 0))),\n geometry=PolygonMeshPlane(scene, length = 200.0, width = 200.0),\n enableRaycasting=False\n )\n \n self.constructionCompleted() \n\n\n def getStartupText(self):\n return \"\\\nDescription: This sample shows how to build each of the basic primitives. \\n\\\nNote: each of the primitives is an example of procedural geometry generation\\n\\n\" + super(DemoApplication, self).getStartupText()\n\nif __name__ == '__main__': \n app = DemoApplication()\n app.exec_()\n","sub_path":"PIBrowser/Primitives.py","file_name":"Primitives.py","file_ext":"py","file_size_in_byte":10898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"87360450","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nfrom keras.utils import to_categorical\nimport os\nimport config\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nimport pickle\n\n\nclass Model:\n def __init__(self):\n # batch, maxnum, 4096\n self.input = tf.placeholder(shape=[None, 24, 112, 112], dtype=tf.float32)\n # batch, type_num\n self.label = tf.placeholder(shape=[None, None], dtype=tf.float32)\n self.is_training = tf.placeholder(dtype=tf.bool)\n self.MODEL_PATH = '../result/model/LipNet/lstm_resnet/model'\n self.MODEL_DIC = '../result/model/LipNet/lstm_resnet'\n self.ACC_DIC = '../result/pic/LipNet/lstm_resnet'\n self.LOSS_DIC = '../result/pic/LipNet/lstm_resnet'\n self.PIC_DIC = '../result/pic/LipNet/lstm_resnet'\n self.id2label = self.load_table('../data/id2label.pkl')\n self.label2lid = self.load_table('../data/label2lid.pkl')\n self.score, self.acc, self.loss, self.train_step, self.t = self.create_graph()\n\n def conv3d_layer(self, inputs, filters, kernel, strides, pool_kernel, pool_stride):\n conv = tf.layers.conv3d(inputs, filters, kernel, strides, padding='SAME')\n conv_bn = tf.layers.batch_normalization(conv, training=self.is_training)\n conv_a = tf.nn.relu(conv_bn)\n pool = tf.layers.max_pooling3d(conv_a, pool_kernel, pool_stride, padding='SAME')\n return pool\n\n def conv2d_layer(self, inputs, filters, kernel_size, strides, pool_size, pool_strides):\n conv2d = tf.layers.conv2d(inputs, filters, kernel_size, strides, padding='same')\n conv2d_bn = tf.layers.batch_normalization(conv2d, training=self.is_training)\n conv2d_a = tf.nn.relu(conv2d_bn)\n pool = tf.layers.max_pooling2d(conv2d_a, pool_size, pool_strides, padding='same')\n return pool\n\n def resnet_block(self, inputs, filters, kernel_size, is_first):\n if inputs.shape[-1] * 2 == filters:\n increase_dim = True\n strides = (2, 2)\n elif inputs.shape[-1] == filters:\n increase_dim = False\n strides = (1, 1)\n else:\n raise ValueError('Output and input channel does not match in residual blocks!!!')\n if is_first is False:\n # bn+relu\n inputs = tf.layers.batch_normalization(inputs, training=self.is_training)\n inputs = tf.nn.relu(inputs)\n conv1 = tf.layers.conv2d(inputs, filters, kernel_size, strides, padding='same')\n # bn + relu\n temp = tf.layers.batch_normalization(conv1, training=self.is_training)\n temp = tf.nn.relu(temp)\n conv2 = tf.layers.conv2d(temp, filters, kernel_size, (1, 1), padding='same')\n\n if increase_dim is True:\n inputs = tf.layers.conv2d(inputs, filters, 1, (2, 2), padding='same')\n # print('inputs+conv2', inputs.shape, conv2.shape)\n return inputs + conv2\n\n def attention_layer(self, inputs):\n q = tf.layers.dense(inputs=inputs, units=config.ATT_SIZE)\n k = tf.layers.dense(inputs=inputs, units=config.ATT_SIZE)\n v = tf.layers.dense(inputs=inputs, units=config.ATT_SIZE)\n k = tf.transpose(k, perm=[0, 2, 1])\n s = tf.einsum('aij,ajk->aik', q, k)\n s = s/tf.sqrt(float(config.ATT_SIZE))\n s = tf.nn.softmax(s, axis=2)\n att_output = tf.einsum('aij,ajk->aik', s, v)\n return att_output\n\n def create_graph(self):\n cnn_input = self.input\n print('cnn_input shape:', cnn_input.shape)\n cnn_input_ex = tf.expand_dims(cnn_input, axis=-1)\n print('cnn_input_ex shape:', cnn_input_ex.shape)\n conv_1 = self.conv3d_layer(cnn_input_ex, 64, (5, 7, 7), (1, 2, 2), (3, 5, 5), (1, 2, 2))\n print('conv_1', conv_1.shape)\n\n # ResNet\n conv1_reshape = tf.reshape(conv_1, shape=[-1, conv_1.shape[2], conv_1.shape[3], conv_1.shape[4]])\n print('conv_1 reshape', conv1_reshape.shape)\n conv_2 = self.conv2d_layer(conv1_reshape, 64, 7, (2, 2), 3, (1, 1))\n\n res_input = conv_2\n print('res_input', res_input.shape)\n for i in range(3):\n if i == 0:\n conv_r1 = self.resnet_block(res_input, 64, 3, True)\n conv_r1 = self.resnet_block(res_input, 64, 3, False)\n res_input = conv_r1\n print('ResNet 1', res_input.shape)\n for i in range(4):\n conv_r2 = self.resnet_block(res_input, 128, 3, False)\n res_input = conv_r2\n print('ResNet 2', res_input.shape)\n for i in range(6):\n conv_r3 = self.resnet_block(res_input, 256, 3, False)\n res_input = conv_r3\n print('ResNet 3', res_input.shape)\n\n for i in range(3):\n conv_r4 = self.resnet_block(res_input, 512, 3, False)\n res_input = conv_r4\n print('ResNet 4', res_input.shape)\n\n dense = tf.layers.dense(conv_r4, 256)\n print('dense', dense.shape)\n\n lstm_input = tf.reshape(dense, shape=[-1, 24, dense.shape[1] * dense.shape[2] * dense.shape[3]])\n lstm_reverse = lstm_input[:, ::-1, :]\n print('lstm_input', lstm_input.shape)\n\n # BILSTM1\n with tf.variable_scope('bilstm1'):\n for index in range(config.LSTMS):\n with tf.variable_scope('lstm{}'.format(index)):\n cell_fw = tf.contrib.rnn.BasicLSTMCell(config.LSTM_HIDDEN_SIZE)\n cell_bw = tf.contrib.rnn.BasicLSTMCell(config.LSTM_HIDDEN_SIZE)\n lstm_out, _ = tf.nn.bidirectional_dynamic_rnn(cell_fw=cell_fw, cell_bw=cell_bw, inputs=lstm_input,\n dtype=tf.float32)\n lstm_output = tf.concat(lstm_out, 2)\n if self.is_training is not None:\n lstm_output = tf.nn.dropout(lstm_output, config.LSTMDROP)\n lstm_input = lstm_output\n\n with tf.variable_scope('bilstm2'):\n # BILSTM2\n for index in range(config.LSTMS):\n with tf.variable_scope('lstm{}'.format(index)):\n cell_fw = tf.contrib.rnn.BasicLSTMCell(config.LSTM_HIDDEN_SIZE)\n cell_bw = tf.contrib.rnn.BasicLSTMCell(config.LSTM_HIDDEN_SIZE)\n lstm_reverse_out, _ = tf.nn.bidirectional_dynamic_rnn(cell_fw=cell_fw, cell_bw=cell_bw,\n inputs=lstm_reverse,\n dtype=tf.float32)\n lstm_reverse_output = tf.concat(lstm_reverse_out, 2)\n if self.is_training is not None:\n lstm_reverse_output = tf.nn.dropout(lstm_reverse_output, config.LSTMDROP)\n lstm_reverse = lstm_reverse_output\n\n lstm_output_re = lstm_reverse_output[:, ::-1, :]\n lstm_final = tf.concat([lstm_output, lstm_output_re], axis=-1)\n print('lstm final', lstm_final.shape)\n\n att = self.attention_layer(lstm_final)\n dense_input = tf.reduce_mean(att, axis=1)\n print('dense_input shape:', dense_input.shape)\n # dense\n score = tf.layers.dense(dense_input, units=config.TYPE_NUM)\n print('score:', score.shape)\n t = tf.nn.softmax(score)\n # optimizer\n acc = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(score, 1), tf.argmax(self.label, 1)), dtype=tf.float32))\n loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=self.label, logits=score))\n train_step = tf.train.AdamOptimizer(config.LR).minimize(loss)\n return score, acc, loss, train_step, t\n\n def train(self, train_path):\n saver = tf.train.Saver()\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n acc_train = []\n acc_dev = []\n loss_train = []\n loss_dev = []\n should_stop = False\n step = 0\n es_step = 0\n loss_stop = 99999\n n = 0\n while step < config.EPOCH and should_stop is False:\n print('Epoch:{}'.format(step))\n acc_total = 0\n loss_total = 0\n acc_dev_total = 0\n loss_dev_total = 0\n train_step = 0\n train_num = 0\n train_list, dev_list = train_test_split(os.listdir(train_path), test_size=0.2)\n for input, label in self.prepare_data(train_path, train_list):\n _, acc_t, loss_t, t = sess.run([self.train_step, self.acc, self.loss, self.t],\n {self.input: input, self.label: label,\n self.is_training: True})\n train_num += len(input)\n acc_total += acc_t\n loss_total += loss_t\n print('step{} [{}/{}] --acc:{}, --loss:{}'.format(train_step, train_num, len(train_list),\n round(acc_t, 2), round(loss_t, 4)))\n train_step += 1\n acc_t = acc_total / train_step\n loss_t = loss_total / train_step\n acc_train.append(acc_t)\n loss_train.append(loss_t)\n # dev\n dev_step = 0\n for input, label in self.prepare_data(train_path, dev_list):\n acc_d, loss_d = sess.run([self.acc, self.loss], {self.input: input, self.label: label,\n self.is_training: False})\n dev_step += 1\n acc_dev_total += acc_d\n loss_dev_total += loss_d\n acc_dd = acc_dev_total / dev_step\n loss_dd = loss_dev_total / dev_step\n acc_dev.append(acc_dd)\n loss_dev.append(loss_dd)\n print('Epoch{}----acc:{},loss:{},val_acc:{},val_loss:{}'.format(step, acc_t, loss_t, round(acc_dd, 2),\n round(loss_dd, 4)))\n if loss_dd > loss_stop:\n if n >= config.EARLY_STEP:\n should_stop = True\n else:\n n += 1\n else:\n if not os.path.exists(self.MODEL_DIC):\n os.makedirs(self.MODEL_DIC)\n saver.save(sess, self.MODEL_PATH)\n es_loss = loss_dd\n es_acc = acc_dd\n es_step = step\n n = 0\n loss_stop = loss_dd\n step += 1\n if should_stop:\n print('Early Stop at Epoch{} acc:{} loss:{}'.format(es_step, es_acc, es_loss))\n if not os.path.exists(self.PIC_DIC):\n os.makedirs(self.PIC_DIC)\n plt.plot(acc_train)\n plt.plot(acc_dev)\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig(os.path.join(self.PIC_DIC, 'acc_cf.png'))\n plt.close()\n\n plt.plot(loss_train)\n plt.plot(loss_dev)\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig(os.path.join(self.PIC_DIC, 'loss_cf.png'))\n plt.close()\n\n def predict(self, test_path):\n saver = tf.train.Saver()\n with tf.Session() as sess:\n ckpt = tf.train.latest_checkpoint(self.MODEL_DIC) # 找到存储变量值的位置\n saver.restore(sess, ckpt)\n test_list = os.listdir(test_path)\n pre_list = []\n for input in self.prepare_test_data(test_path, test_list):\n predict = sess.run(self.score, {self.input: input, self.is_training: False})\n pre_list.extend(predict)\n result = np.array(pre_list)\n return result\n\n def prepare_data(self, path, file_list):\n if len(file_list) % config.BATCH_SIZE == 0:\n num = len(file_list) // config.BATCH_SIZE\n else:\n num = len(file_list) // config.BATCH_SIZE + 1\n begin = 0\n for i in range(num):\n end = begin + config.BATCH_SIZE\n if end > len(file_list):\n end = len(file_list)\n data_list = file_list[begin:end]\n begin = end\n label = []\n input = []\n for d in data_list:\n plabel = self.id2label[d]\n plabel = self.label2lid[plabel]\n plabel = to_categorical(plabel, 313)\n pinput = []\n file_path = os.path.join(path, d)\n\n for ff in os.listdir(file_path):\n pic_path = os.path.join(file_path, ff)\n im = Image.open(pic_path)\n im = im.convert(\"L\")\n im = im.resize((config.WIDTH, config.HEIGHT))\n matrix = np.asarray(im)\n\n matrix = matrix / 255\n\n pinput.append(matrix)\n\n while len(pinput) < config.PIC_NUM:\n pinput.append(np.zeros(shape=(config.WIDTH, config.HEIGHT)))\n\n pinput = np.array(pinput)\n\n label.append(plabel)\n\n input.append(pinput)\n\n label = np.array(label)\n\n input = np.array(input)\n\n yield input, label\n\n def prepare_test_data(self, path, file_list):\n if len(file_list) % config.BATCH_SIZE == 0:\n num = len(file_list) // config.BATCH_SIZE\n else:\n num = len(file_list) // config.BATCH_SIZE + 1\n begin = 0\n for i in range(num):\n end = begin + config.BATCH_SIZE\n if end > len(file_list):\n end = len(file_list)\n data_list = file_list[begin:end]\n begin = end\n input = []\n for d in data_list:\n pinput = []\n file_path = os.path.join(path, d)\n for ff in os.listdir(file_path):\n pic_path = os.path.join(file_path, ff)\n im = Image.open(pic_path)\n im = im.convert(\"L\")\n im = im.resize((config.WIDTH, config.HEIGHT))\n matrix = np.asarray(im)\n matrix = matrix / 255\n pinput.append(matrix)\n while len(pinput) < config.PIC_NUM:\n pinput.append(np.zeros(shape=(config.WIDTH, config.HEIGHT)))\n pinput = np.array(pinput)\n input.append(pinput)\n input = np.array(input)\n yield input\n\n def load_table(self, table_path):\n with open(table_path, 'rb') as f:\n result = pickle.load(f)\n return result\n\n\nif __name__ == '__main__':\n m = Model()","sub_path":"code/resnet_lstm.py","file_name":"resnet_lstm.py","file_ext":"py","file_size_in_byte":15055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"336542551","text":"from unittest import TestCase\n\nfrom crypto.cyphers.RC4 import RC4\n\n\nclass TestRC4(TestCase):\n test = {\n \"Key\" : [\"EB\", \"9F\", \"77\", \"81\", \"B7\", \"34\", \"CA\", \"72\", \"A7\", \"19\"],\n \"Wiki\": [\"60\", \"44\", \"DB\", \"6D\", \"41\", \"B7\"],\n \"Secret\": [\"04\", \"D4\", \"6B\", \"05\", \"3C\", \"A8\", \"7B\", \"59\"],\n \"Passw\" : [\"D9\", \"05\", \"46\", \"66\", \"AB\"],\n \"P\\x17*{ê\": ['82', 'BD', 'FE', 'C0', 'EE', '84', 'D8', '84', '52', 'AD'] # HW1 exercise 3 key\n }\n\n def convert_key(self, key: list):\n if type(key[0]) is str:\n return [ord(char) for char in key]\n else:\n return key\n\n # def test_swap(self):\n # self.fail()\n #\n def test_generate(self):\n for key, output in self.test.items():\n key = self.convert_key(key)\n\n rc4 = RC4(key)\n for c in output:\n result = rc4.generate()\n self.assertEqual(format(result, '02X'), str.upper(c))\n\n def test_generate_multiple(self):\n for key, output in self.test.items():\n key = self.convert_key(key)\n\n rc4_1 = RC4(key)\n rc4_2 = RC4(key)\n\n amount = len(output)\n output_1 = rc4_1.generate_multiple(amount)\n output_2 = rc4_2.generate_multiple(amount)\n\n self.assertEqual(output_1, output_2)\n\n # def test_get_s_index(self):\n # self.fail()\n","sub_path":"crypto/test/cyphers/test_RC4.py","file_name":"test_RC4.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"168254169","text":"\"\"\"This module takes care of character related functions\"\"\"\n# Assignment 3\n# Kate Lu\n# A01062775\n# February 27, 2019\n\n\nimport json\nimport os\nimport map\n\n\nplayer = {'name': '', \"wealth\": 0, \"current_location\": [1, 0]}\n\n\ndef create_player():\n \"\"\"Write the json file of a new user\n POST-COND: new player's json file is created\"\"\"\n\n global player\n player = {'name': '', \"wealth\": 0, 'current_location': []}\n name = input('please enter your name')\n\n player['name'] = name\n player['wealth'] = 10\n player['current_location'] = [2, 0]\n filename = name + '.json'\n with open(filename, 'w') as f_obj:\n json.dump(player, f_obj)\n return player\n\n\ndef update_player():\n \"\"\" Write to exiting json file.\n\n update player's json file\n POST-COND: player's json file rewritten(updated)\"\"\"\n filename = player['name'] + '.json'\n with open(filename, 'w') as f_obj:\n json.dump(player, f_obj)\n print('your profile has been saved')\n\n\ndef change_wealth(number):\n \"\"\"Change player's wealth level.\n PARAM: number is an integer added to player's wealth level\n PRE-COND: number must be an integer\n POST-COND: player's wealth level is changed\n \"\"\"\n\n global player\n player['wealth'] += number\n\n\ndef get_wealth():\n \"\"\"Return player's wealth level.\"\"\"\n return player['wealth']\n\n\ndef change_current_location():\n \"\"\"Change the player's current location.\n POST-COND: change the player's current location\n POST-COND: show current_location indicator on map\"\"\"\n\n global player\n current_location = map.set_new_location(player[\"current_location\"])\n if current_location is not None:\n player['current_location'] = current_location\n\n map.set_current_location_indicator(player['current_location'])\n\n else:\n update_player()\n player['current_location'] = None\n\n\ndef get_current_location():\n \"\"\" Return player's current location as a list.\"\"\"\n if player:\n return player['current_location']\n\n\ndef get_stored_player():\n \"\"\"Open the existing json file and return the stored player\n POST-COND: print error message if cannot find the json file\"\"\"\n\n global player\n user_name = input('what is your name?')\n filename = user_name + '.json'\n try:\n with open(filename) as f_obj:\n player = json.load(f_obj)\n except FileNotFoundError:\n print('we cannot find your file. will create a new file for you.')\n return None\n else:\n return player\n\n\ndef greet_player():\n \"\"\"Print greetings to player\n POST-COND: global variable player is changed to newly created player or restored from saved json file\"\"\"\n\n global player\n returning = input('are you a returning player?')\n returning = returning.strip().lower()[0]\n if returning == 'y':\n player = get_stored_player()\n if player: # if found player's stored json file\n print('welcome back,', player['name'])\n\n else:\n player = create_player() # create new json file if not found\n print('welcome to the game,', player['name'])\n elif returning == 'q': # if player decides to 'quit'\n player = None\n else:\n player = create_player() # create new json file if player is not returning player\n print('welcome to the game,', player['name'])\n\n\ndef get_player():\n \"\"\"Return player as a dictionary object\"\"\"\n return player\n\n\ndef delete_json_file():\n \"\"\"Remove player's json file.\"\"\"\n\n file_name = player['name'] + '.json'\n if os.path.exists(file_name):\n print('your profile is deleted, please create a new profile next time')\n os.remove(file_name)\n\n# change_current_location()\n","sub_path":"A3/character.py","file_name":"character.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"395353420","text":"import atexit\nimport psycopg2\nfrom datetime import datetime\nfrom config import config\n\n\"\"\"\nDatabase Info: the database is a postgresql 12 database hosted on google cloudsql. Credentials are hidden but stored in database.ini\nconfig.py parses the credentials and allows the DataManager class to access the database directly\n\nDatabase: database\nUser: postgres\n\nTable: parties\n- code\n- name\n- date\n\nTable: party_images\n- code\n- image_url\n\n\"\"\"\n\nclass DataManager:\n def __init__(self):\n \"\"\"\n Summary: Class for managing the database\n \"\"\"\n\n print('Starting DB Manager')\n # Obtain the configuration parameters\n params = config()\n # Connect to the PostgreSQL database\n self.conn = psycopg2.connect(**params)\n # Create a new cursor\n self.cur = self.conn.cursor()\n # Define cleanup function\n atexit.register(self.cleanup)\n\n def addEvent(self, data):\n \"\"\"\n Summary: Adds a new event to the database\n \"\"\"\n\n code = data['code']\n name = data['name']\n date = data['date']\n images = data['images']\n\n print(code, name, date, images)\n # add event to parties table\n self.cur.execute(\"INSERT INTO parties (code, name, date) VALUES (%s, %s, %s)\", (code, name, date))\n # add all the image urls to the party_images table\n for image in images:\n self.cur.execute(\"INSERT INTO party_images (code, image_url) VALUES (%s, %s)\", (code, image))\n # update db\n self.conn.commit()\n\n def getEventImages(self, code):\n \"\"\"\n Summary: retreives image urls for a particular event code\n \"\"\"\n\n # execute SQL command and retreive results\n self.cur.execute(\"SELECT image_url FROM party_images WHERE code = (%s)\", (code,))\n rawResult = self.cur.fetchall()\n print(\"RAW:\", rawResult)\n # parse results into a list of urls\n result = []\n for tpl in rawResult:\n result.append(tpl[0])\n print(\"RESULT:\", result)\n\n return result\n\n def testCode(self, code):\n \"\"\"\n Summary: tests an event code for uniqueness in the database\n \"\"\"\n\n self.cur.execute(\"SELECT code FROM parties\")\n result = self.cur.fetchall()\n for tpl in result:\n if tpl[0] == code:\n return False\n return True\n\n def cleanup(self):\n \"\"\"\n Summary: close the connection to the database on termination\n \"\"\"\n\n print(\"Running cleanup...\")\n self.conn.close()\n","sub_path":"server/dataManager.py","file_name":"dataManager.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"351103262","text":"'''\nName:\t\tProblem 4\nProblem:\tA palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 x 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n\n1. Determine range of 3 digit products (10000, 998001)\n2. For range, make a list of palindromes\n3. Factor palindromes\n\n'''\nimport math\n\ndef getFactors(number):\n\tfactors=[]\n\troot=int(math.sqrt(number))\n\tfor i in range(100,root):\n\t\tif str(i)[-1]:\n\t\t\tif (number%i)==0:\n\t\t\t\tif(len(str(i))==3) and(len(str(number/i))==3):\n\t\t\t\t\tfactors.append(i)\n\t\t\t\t\tfactors.append(number/i)\n\treturn len(factors)\n\npalindrome=True\n#for i in reversed(range(998000,998002)):\nfor i in reversed(range(10000,998002)):\n\tlength=str(int(len(str(i))/2))\n\tfor x in range(0,(int(length))):\n\t\tif (str(i)[x]!=str(i)[(len(str(i))-x-1):(len(str(i))-x)]):\n\t\t\tpalindrome = False\n\tif palindrome:\n\t\tif(getFactors(i)>0):\n\t\t\tprint(str(i))\n\tpalindrome=True","sub_path":"problem4.py","file_name":"problem4.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"300093456","text":"import rospy\nimport random\nfrom scout.msg import RL_input_msgs\nfrom geometry_msgs.msg import Twist\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport time\nimport math \nimport os\nimport csv\n\nimport subprocess\nimport ppo_algo\nimport ppo_env\n\n\nEP_MAX = 1000000\nEP_LEN = 256\nBATCH = 32\nGAMMA = 0.9\n\nMETHOD = [\n dict(name='kl_pen', kl_target=0.01, lam=0.5), # KL penalty\n dict(name='clip', epsilon=0.2), # Clipped surrogate objective, find this is better\n][1]\n\ndef save_plot(ep, ep_r, TRAIN_TIME, PLOT_EPISODE, PLOT_REWARD):\n plot_path = '/home/xyw/BUAA/Graduation/src/scout/plot/simple/PPO_%i.npy' %(TRAIN_TIME)\n PLOT_EPISODE = np.append(PLOT_EPISODE, ep)\n PLOT_REWARD = np.append(PLOT_REWARD, ep_r)\n PLOT_RESULT = np.concatenate([[PLOT_EPISODE], [PLOT_REWARD]])\n np.save(plot_path, PLOT_RESULT)\n return PLOT_EPISODE, PLOT_REWARD\n\ndef update(ppo, s_, buffer_r, buffer_s, buffer_a):\n\n v_s_ = ppo.get_v(s_)\n discounted_r = []\n for r in buffer_r[::-1]:\n v_s_ = r + GAMMA * v_s_\n discounted_r.append(v_s_)\n discounted_r.reverse()\n\n bs, ba, br = np.vstack(buffer_s), np.vstack(buffer_a), np.array(discounted_r)[:, np.newaxis]\n buffer_s = []\n buffer_a = []\n buffer_r = []\n \n ppo.update(bs, ba, br)\n \nif __name__ == '__main__':\n rospy.init_node('RL', anonymous=True)\n\n for TRAIN_TIME in range(50):\n\n PLOT_EPISODE = np.array([],dtype = int)\n PLOT_REWARD = np.array([], dtype = int)\n\n # if BREAK = 0, means action is not 'nan'.\n # if BREAK = 1, means action is 'nan', reset ppo and env to another train.\n BREAK = 0\n\n ppo = ppo_algo.ppo()\n print('\\n Training Start')\n\n ppo.restore(TRAIN_TIME)\n\n env = ppo_env.env()\n\n all_ep_r = []\n\n suc_time = 0\n\n for ep in range(EP_MAX):\n a_init = [0, 0]\n s = env.set_init_pose()\n\n buffer_s = []\n buffer_a = []\n buffer_r = []\n\n ep_r = 0\n time.sleep(0.3)\n \n dis_temp = math.hypot(env.goal_x, env.goal_y)\n a_temp = [0,0]\n\n for t in range(EP_LEN):\n\n a = ppo.choose_action(s)\n # print(ppo.get_v(s))\n if np.isnan(a[0]) or np.isnan(a[1]):\n BREAK = 1\n print('Warning: Action is nan. Restart Train')\n break\n # os._exit(0)\n env.set_action(a)\n\n s_= env.compute_state()\n\n collide = env.get_collision_info()\n current_dis_from_des_point = env.compute_param()\n\n r = env.compute_reward(collide, current_dis_from_des_point, dis_temp)\n\n dis_temp = current_dis_from_des_point\n\n buffer_s.append(s)\n buffer_a.append(a)\n buffer_r.append((r+8)/8) # normalize reward, find to be useful\n s = s_\n ep_r += r\n\n if (t+1) % BATCH == 0 or t == EP_LEN-1:\n update(ppo, s_, buffer_r, buffer_s, buffer_a)\n # print(ppo.alossr, ppo.clossr)\n \n # When robot is nearby the goal, skip to next episode\n if collide == 1:\n update(ppo, s_, buffer_r, buffer_s, buffer_a)\n # print(ppo.alossr, ppo.clossr)\n print('Collision')\n break\n \n if current_dis_from_des_point < env.reach_goal_circle:\n update(ppo, s_, buffer_r, buffer_s, buffer_a)\n if not (suc_time > 30):\n ppo.save_suc(suc_time)\n suc_time += 1\n # print(ppo.alossr, ppo.clossr)\n print('Sucess')\n break\n elif current_dis_from_des_point > env.limit_circle:\n update(ppo, s_, buffer_r, buffer_s, buffer_a)\n # print(ppo.alossr, ppo.clossr)\n print('Over-area')\n break\n \n # Set the beginning action of robot in next episode, or it would be set by last time\n env.set_action(a_init)\n\n # Print the result of episode reward\n if ep == 0: all_ep_r.append(ep_r)\n else: all_ep_r.append(all_ep_r[-1]*0.9 + ep_r*0.1)\n print(\n 'Ep: %i' % ep,\n \"|Ep_r: %f\" % ep_r,\n (\"|Lam: %.4f\" % METHOD['lam']) if METHOD['name'] == 'kl_pen' else '',\n )\n \n # Save model and plot\n PLOT_EPISODE, PLOT_REWARD = save_plot(ep, ep_r, TRAIN_TIME+1, PLOT_EPISODE, PLOT_REWARD)\n \n if ep % 50 == 0:\n ppo.save(TRAIN_TIME+1)\n\n # Reset gazebo environment\n env.reset_env()\n \n if BREAK == 1:\n print(ppo.alossr, ppo.clossr)\n break\n \n ppo.resetgraph()\n","sub_path":"Sim/src/scout/src/simple/ppo_train.py","file_name":"ppo_train.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"7538884","text":"import os\nimport sys\nfrom IPython.core.magic import Magics, magics_class, line_magic\nfrom IPython.utils.warn import warn\nfrom IPython.utils.py3compat import str_to_unicode\nfrom IPython.core.magics.logging import LoggingMagics\nfrom IPython.core.magic import Magics, magics_class, line_magic\nimport time\n\n\nclass RedirectStdStreams(object):\n def __init__(self, stdout=None, stderr=None):\n self._stdout = stdout or sys.stdout\n self._stderr = stderr or sys.stderr\n\n def __enter__(self):\n self.old_stdout, self.old_stderr = sys.stdout, sys.stderr\n self.old_stdout.flush()\n self.old_stderr.flush()\n sys.stdout, sys.stderr = self._stdout, self._stderr\n\n def __exit__(self, exc_type, exc_value, traceback):\n self._stdout.flush()\n self._stderr.flush()\n sys.stdout = self.old_stdout\n sys.stderr = self.old_stderr\n\n\n@magics_class\nclass LogDiaryMagics(LoggingMagics):\n \"\"\"Magics related to all logging machinery.\"\"\"\n\n @line_magic\n def logdiary(self, parameter_s=''):\n logdir = os.path.expanduser(time.strftime(\"~/notes/history/ipython/%Y/%m/\"))\n logfile = os.path.join(logdir, time.strftime(\"%d.py\"))\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n\n devnull = open(os.devnull, \"w\")\n with RedirectStdStreams(stdout=devnull, stderr=devnull):\n self.logstart(logfile)\n\n\ndef load_ipython_extension(ip):\n \"\"\"Load the extension in IPython.\"\"\"\n ip.register_magics(LogDiaryMagics)\n","sub_path":".config-base/ipython/extensions/logdiary.py","file_name":"logdiary.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"202751121","text":"import cv2\nimport numpy as np\n\ndef vflip(img):\n if isinstance(img, np.ndarray):\n img = img.tolist()\n elif isinstance(img, list):\n img = img\n else:\n raise TypeError(\"Only support ndarray or list type img\")\n\n H, W, C = len(list_img), len(list_img[0]), len(list_img[0][0])\n tmp_img = [[[0]*C for _ in range(W)] for _ in range(H)]\n for x in range(H):\n for y in range(W):\n for c in range(C):\n tmp_img[x][y][c] = img[H-1-x][y][c]\n return tmp_img\n\n\nif __name__ == \"__main__\": \n img_path = \"./img/python_logo.png\"\n np_img = cv2.imread(img_path)\n list_img = np_img.tolist()\n\n vflip_img = vflip(list_img)\n rot_img = np.array(vflip_img).astype(np.uint8)\n cv2.imshow(\"Horizontal Flipped Img\", rot_img)\n cv2.imshow(\"Original Img\", np_img)\n cv2.waitKey()\n cv2.destroyAllWindows()","sub_path":"vertical_flip.py","file_name":"vertical_flip.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"465277632","text":"## Python3.4\nfrom tkinter import *\nfrom math import *\nfrom KValueFugacityCoefficient import *\n\ndef k_fugacity():\n init=initial.get()\n ini=float(init)\n te=tempe.get()\n t=float(te)\n pr=pressure.get()\n p=float(pr)\n xl=compe.get().split()\n tcl=tcvalue.get().split()\n pcl=pcvalue.get().split()\n x=[]\n tc=[]\n pc=[]\n for i in range(2):\n x.append(float(xl[i]))\n tc.append(float(tcl[i]))\n pc.append(float(pcl[i]))\n a=[]\n b=[]\n for i in range(2):\n a.append(float(0.42748/pc[i]*(tc[i]**2.5)*(R**2)))\n b.append(float(0.08664/pc[i]*tc[i]*R))\n aa=[]\n bb=[]\n for i in range(2):\n aa.append(float((sqrt(a[i])*x[i]+sqrt(a[1-i])*(1-x[i]))**2))\n bb.append(float(b[i]*x[i]+b[1-i]*(1-x[i])))\n v=[]\n for i in range(2):\n v.append(get_root(ini,p,t,aa[i],bb[i]))#ini为迭代初始值\n v[0]=float(v[0])\n v[1]=float(v[1])\n fl=[]\n z=float(p*v[0]/(R*t))\n show.insert(\"1.0\",\"liquid z=\"+str(z)+\"\\n\")\n for i in range(2):\n fl.append(exp(float(b[i]*(z-1)/bb[0]-log(z*(1-bb[0]/v[0]))+(aa[0]*b[i]/bb[0]-2*sqrt(aa[0]*a[i]))/(bb[0]*R*t**1.5)*log(1+bb[0]/v[0])))) \n fv=[]\n z=float(p*v[1]/(R*t))\n show.insert(\"1.0\",\"gas z=\"+str(z)+\"\\n\")\n for i in range(2):\n fv.append(exp(float(b[i]*(z-1)/bb[1]-log(z*(1-bb[1]/v[1]))+(aa[1]*b[i]/bb[1]-2*sqrt(aa[1]*a[i]))/(bb[1]*R*t**1.5)*log(1+bb[1]/v[1])))) \n k=[]\n for i in range(2):\n k.append(float(fl[i]/fv[i]))\n flag=[\"liquid:\",\"gas:\"]\n for i in range(2):\n show.insert(\"1.0\",\"a=\"+str(a[i])+\"\\n\"+\"b=\"+str(b[i])+\"\\n\"+flag[i]+'\\n')\n show.insert(\"1.0\",\"aa=\"+str(aa[i])+\"\\n\"+\"bb=\"+str(bb[i])+\"\\n\"+\"V=\"+str(v[i])+\"m^3 \\n\")\n show.insert(\"1.0\",\"liqui Φ1=\"+str(fl[0])+\"\\n\"+'liquid Φ2='+str(fl[1])+'\\n')\n show.insert(\"1.0\",\"gas Φ1=\"+str(fv[0])+\"\\n\"+'gas Φ2='+str(fv[1])+'\\n')\n show.insert(\"1.0\",\"k1=\"+str(k[0])+'\\n'+'k2='+str(k[1])+'\\n')\n show.insert(\"1.0\",\"y1/x1=\"+str(x[1]/x[0])+'\\n'+'y2/x2='+str((1-x[1])/(1-x[0]))+'\\n')\n show.insert(\"1.0\",\"initial value is:\"+str(ini)+'\\n')\n show.insert(\"1.0\",'\\n\\n')\n initial.delete(0,END)\n \napp=Tk()\napp.title(\"R-k equation calculates K value and fugacity coefficient\")\napp.geometry(\"600x400+200+100\")\n\nLabel(app,text=\"temperature(K):\",bg='Red').pack()\ntempe=Entry(app,width=50)\ntempe.pack()\n\nLabel(app,text=\"pressure(Pa):\",bg='Orange').pack()\npressure=Entry(app,width=50)\npressure.pack()\n\nLabel(app,text=\"component(mol fraction x1 y1):\",bg='Green').pack()\ncompe=Entry(app,width=50)\ncompe.pack()\n\nLabel(app,text=\"input Tc value(k):\",bg='Cyan').pack()\ntcvalue=Entry(app,width=50)\ntcvalue.pack()\n\nLabel(app,text=\"input Pc value(Pa):\",bg='green').pack()\npcvalue=Entry(app,width=50)\npcvalue.pack()\n\nLabel(app,text='initial value of getting root:',bg='green').pack()\ninitial=Entry(app,width=50)\ninitial.pack()\n\nButton(app,text=\"calculate:\",command=k_fugacity,bg='cyan').pack()\n\nLabel(app,text=\"showin:\",bg='green').pack()\nshow=Text(app)\nshow.pack()\n\napp.mainloop()\n","sub_path":"programmingLanguages/python/KValueAndFugacityCoefficient/calculateKvalueAndFugacityCoefficient.py","file_name":"calculateKvalueAndFugacityCoefficient.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"390999157","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 11 08:35:58 2020\n\n@author: andres\n\"\"\"\n\nimport numpy as np\n\nimport scipy\n\nimport os\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn import linear_model\n\nfrom sklearn.metrics import mean_squared_error, r2_score\n\nimport statsmodels.api as sm\n\n\n\n# Code to deal with statistics in data post-processing\n\ndef t_test(result, reference):\n \n \"\"\"\n Compute the t statistic and p-value given the flow results from the neural\n network and the reference results from Segment.\n \n Params:\n - result: 1D array with flow results from neural network segmentation\n - reference: 1D array with reference flow results from software Segment\n \n Returns:\n - t_statistic and p_value\n \n \"\"\"\n \n # Check that result and reference are 1D and that they have the same length\n \n print('\\nChecking that result and reference are 1D and that they have the same length\\n')\n \n if (len(result.shape) == 1) and (len(reference.shape) == 1):\n \n if len(result) == len(reference):\n \n print('Performing t test\\n')\n \n t_stat, p_value = scipy.stats.ttest_ind(result, reference)\n \n print('t test completed successfully!\\n')\n \n print('t statistic: {} // p value: {}'.format(t_stat, p_value))\n \n return t_stat, p_value\n \n else:\n \n print('Result and reference vectors do not have the same length. Please input them so that they have the same length')\n \n else:\n \n print('Result or reference vectors are not 1D. Please reformat them to be 1D')\n \n \n\n\ndef wilcoxon_test(result, reference):\n \n \"\"\"\n Compute the sum of rank differences and p-value given the flow results \n from the neural network and the reference results from Segment.\n \n Params:\n - result: 1D array with flow results from neural network segmentation\n - reference: 1D array with reference flow results from software Segment\n \n Returns:\n - sum and p_value\n \n \"\"\"\n \n print('\\nChecking that result and reference are 1D and that they have the same length\\n')\n \n if (len(result.shape) == 1) and (len(reference.shape) == 1):\n \n if len(result) == len(reference):\n \n print('Performing Wilcoxon test\\n')\n \n s, p_value = scipy.stats.wilcoxon(result, reference)\n \n print('Wilcoxon test completed successfully!\\n')\n \n print('Sum of rank differences: {} // p value: {}'.format(s, p_value))\n \n return s, p_value\n \n else:\n \n print('Result and reference vectors do not have the same length. Please input them so that they have the same length')\n \n else:\n \n print('Result or reference vectors are not 1D. Please reformat them to be 1D')\n \n \n\ndef figure_saving(dest_path, filename, figure):\n \n \"\"\"\n Saves figure in specified folder with a given file name\n \n Params:\n \n - dest_path: destination folder\n \n - filename: given filename (must be .png)\n \n - figure: given figure from Matplotlib\n \n \"\"\"\n \n print('Checking that a destination path has been given\\n')\n \n if dest_path is not None:\n \n if filename[-3:] == 'png' or filename[-3:] == 'PNG':\n \n print('Saving figure as PNG in: {}'.format(dest_path))\n \n # Check that folder exists. Otherwise, create it\n \n print('\\nChecking if folder exists\\n')\n \n exist = os.path.isdir(dest_path)\n \n if not exist:\n \n os.makedirs(dest_path)\n \n print('Non existing folder. Created\\n')\n \n # Checking if file exists\n \n files = os.listdir(dest_path)\n \n if filename in files:\n \n inp = input('File already exists. Do you want to overwrite or rename or abort? [o/r/a]:')\n \n if (inp == 'o') or (inp == 'O'):\n \n figure.savefig(dest_path + filename)\n \n elif (inp == 'r') or (inp == 'R'):\n \n cont = 0 # Filename counter\n \n while (filename in files):\n \n filename = filename[:-4] + '_' + str(cont) + '.png'\n \n cont += 1\n \n figure.savefig(dest_path + filename)\n \n print('Figure successfully saved as PNG in {} after file renaming'.format(dest_path))\n \n else:\n \n print('Operation aborted\\n')\n else:\n \n figure.savefig(dest_path + filename)\n \n print('Figure successfully saved as PNG in {}'.format(dest_path))\n \n else:\n \n print('Filename given was not PNG. Please specify a PNG filename')\n \n else:\n \n print('Tried to save figure as PNG, but folder has not been specified')\n\n\n\ndef linear_regression_test(result, reference, plotting = True, save = False, dest_path = os.getcwd() + '/', filename = 'regression_plot.png'):\n \n \"\"\"\n Compute a scatter plot with points and with linear regression equation\n given the flow results from the neural network and the reference results \n from Segment.\n \n Params:\n - result: 1D array with flow results from neural network segmentation\n - reference: 1D array with reference flow results from software Segment\n - plotting: flag to state whether the user wants to get a plot of the result or not (default True)\n - save: flag indicating whether to save linear regression plot as .png file or not (default False)\n - dest_path: folder where to save the linear regression plot if save is True (default current folder)\n - filename: file name of regression plot (PNG file) (default: 'regression_plot.png')\n \n Returns:\n - linear regression plot and linear regression parameters\n - Return also squared error and R2\n \n \"\"\"\n \n print('\\nChecking that result and reference are 1D and that they have the same length\\n')\n \n if (len(result.shape) == 1) and (len(reference.shape) == 1):\n \n if len(result) == len(reference):\n \n print('Computing linear regression model\\n')\n \n # Create linear regression object\n \n regr = linear_model.LinearRegression()\n \n # Train the model\n \n # Add a column of ones to the reference\n \n ref_aux = np.ones((len(reference), 2))\n \n ref_aux[:,0] = reference\n \n regr.fit(ref_aux, result)\n \n # Make predictions using the reference \n \n pred = regr.predict(ref_aux)\n \n print('Linear regression model completed successfully!\\n')\n \n print('Resulting coefficients: {}\\n'.format(regr.coef_))\n\n # The mean squared error\n \n print('Mean squared error: {}\\n'.format(mean_squared_error(result, pred)))\n \n # The coefficient of determination: 1 is perfect prediction\n \n print('Coefficient of determination: {}\\n'.format(r2_score(result, pred)))\n \n if plotting:\n \n fig = plt.figure()\n \n # Points\n \n plt.scatter(reference, result, color = 'black', label = 'Measured points')\n \n # Regression line\n \n plt.plot(reference, pred, color='blue', linewidth=3, label = 'Regression line')\n \n plt.title('Linear regression plot')\n \n plt.xlabel('Reference values')\n \n plt.ylabel('Computed values')\n \n plt.legend()\n \n plt.xticks(())\n \n plt.yticks(())\n \n plt.show()\n \n if save:\n \n figure_saving(dest_path, filename, fig)\n \n return regr.coef_, mean_squared_error(result, pred), r2_score(result, pred)\n \n else:\n \n print('Result and reference vectors do not have the same length. Please input them so that they have the same length')\n \n else:\n \n print('Result or reference vectors are not 1D. Please reformat them to be 1D')\n \n\n\n\ndef bland_altman_plot(result, reference, save = False, dest_path = os.getcwd() + '/', filename = 'bland_altman_plot.png'):\n \n \"\"\"\n Compute the Bland-Altman plot for the flow results from the neural network \n and the reference results from Segment.\n \n Params:\n - result: 1D array with flow results from neural network segmentation\n - reference: 1D array with reference flow results from software Segment\n - save: flag indicating whether to save linear regression plot as .png file or not (default False)\n - dest_path: folder where to save the linear regression plot if save is True (default current folder)\n - filename: file name of regression plot (PNG file) (default bland_altman_plot.png) \n \n \n \n \"\"\"\n \n print('\\nChecking that result and reference are 1D and that they have the same length\\n')\n \n if (len(result.shape) == 1) and (len(reference.shape) == 1):\n \n if len(result) == len(reference):\n \n print('Computing Bland-Altman plot\\n')\n \n f, ax = plt.subplots(1)\n \n sm.graphics.mean_diff_plot(result, reference, ax = ax)\n \n plt.title('Bland-Altman plot')\n \n plt.xlabel('Average values')\n \n plt.ylabel('Difference values')\n \n plt.show()\n \n if save:\n \n figure_saving(dest_path, filename, f)\n \n else:\n \n print('Result and reference vectors do not have the same length. Please input them so that they have the same length')\n \n else:\n \n print('Result or reference vectors are not 1D. Please reformat them to be 1D')\n \n \ndef correlation(result, reference):\n \n \"\"\"\n Compute Pearson correlation coefficient (r) between network result and ground-truth\n \n Params:\n \n - result: network result\n \n - reference: ground-truth\n \n Returns:\n \n - r: Pearson correlation coefficient\n\n \"\"\"\n \n r = np.corrcoef(result, reference)[0,1]\n \n return r","sub_path":"Data_postprocessing/flowStatistics.py","file_name":"flowStatistics.py","file_ext":"py","file_size_in_byte":11266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"171894813","text":"import os\nimport datetime\nimport codecs\n\ntotalSites = 0\ntotalBCH = 0\n\nmissingList = [\"File, Tag\"]\nfailedPaths = 0\nmissingEntries = 0\n\nindex = 1\n\ndirPath = os.path.join(\"..\",\"..\",\"_data\")\nfilename = os.listdir(dirPath)\n\ndef countFile(dir, filename):\n path = os.path.join(dir, filename)\n #print(\"Testing site: \" + path)\n if \".yml\" in path:\n file = codecs.open(path, 'r', \"utf-8\")\n processed = True\n prevName = ''\n\n pathFail = False\n global index\n\n global missingList\n missingList.append(filename + \": \\n\")\n for line in file:\n #print(line)\n\n if \"- name:\" in line:\n global totalSites\n totalSites+= 1\n #check if the previous file has been processed, this accounts for if the BTC support tag does not exist\n if processed == False:\n\n nameLine = line.replace(\"- name:\", \"\")\n nameLine = nameLine.replace(\"\\n\", \"\")\n nameLine = nameLine.replace(\"\\r\", \"\")\n nameLine = nameLine.replace(\" \", \"\")\n nameLine = nameLine.replace(\"&\", \"&\")\n missingList[index] = missingList[index] + \" \" + nameLine + \",\"\n global missingEntries\n missingEntries += 1\n if pathFail == False:\n pathFail = True\n global failedPaths\n failedPaths += 1\n processed = False\n\n if \"bch: \" in line:\n if \"Yes\" in line:\n global totalBCH\n totalBCH += 1\n processed = True\n index += 1\n\nfor file in filename:\n #print(\"Testing path: \" + path)\n countFile(dirPath, file)\n\n#create log\ntimestamp = datetime.datetime.utcnow()\n\noutputPath = os.path.join(\".\", \"output\")\ntry:\n\tos.mkdir(outputPath)\nexcept Exception as e:\n\tpass\n\noutput = codecs.open(os.path.join(outputPath, \"missingBCH_log.csv\"), \"a\", \"utf-8\")\n\noutput.write(str(timestamp) + \", \" + str(failedPaths) + \", \" + str(missingEntries) + \"\\n\")\n\noutput.close()\n\noutput = codecs.open(os.path.join(\".\",\"output\",\"missingBCH.txt\"), \"w+\", \"utf-8\")\n\nfor string in missingList:\n #print(string + \"\\n\")\n output.write(string + \"\\n\")\n\n#print()\noutput.write(\"\\n\")\n\n#print(\"Total websites found: \" + str(totalSites))\n#output.write(\"Total websites found: \" + str(totalSites) + \". \\n\")\n\n#print(\"Total BCH supported sites \" + str(totalBCH))\n#output.write(\"Total BCH supported sites \" + str(totalBCH) + \". \\n\")\n\nprint(str(failedPaths) + \" files have entries missing the bch tag\")\noutput.write(str(failedPaths) + \" files have entries missing the bch tag \\n\")\n\nprint(str(missingEntries) + \" entries are missing the bch tag\")\noutput.write(str(missingEntries) + \" entries are missing the bch tag \\n\")\n\noutput.close()\n","sub_path":"scripts/python/missingBCH.py","file_name":"missingBCH.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"15557147","text":"\"\"\"\nhttps://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/\n\nGet prefix sum of [nums + nums], then find the minimum subarray such that prefix[j] - prefix[i] == x.\n\nMake sure (i, j) covers head or tail, and does not exceed len(nums)\n\nTime complexity: O(N)\n\"\"\"\nclass Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n pre_fix = [0]\n ref = {0:0}\n ans = float('inf')\n\n for i, c in enumerate(nums + nums):\n pre_fix.append(pre_fix[-1] + c)\n ref[pre_fix[-1]] = i + 1\n if pre_fix[-1] - x >= 0 and pre_fix[-1] - x in ref:\n l = ref[pre_fix[-1] - x]\n tmp = i + 1 - l\n if tmp > len(nums):\n continue\n if l == 0 or i == len(nums) - 1 or l <= len(nums) - 1 < i:\n ans = min(ans, tmp)\n \n return ans if ans < float('inf') else -1","sub_path":"1658_MinimumOperationsToReduceXToZero.py","file_name":"1658_MinimumOperationsToReduceXToZero.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"21561998","text":"#!/usr/bin/env python3\n\n\nimport time\n\nfrom .simulation_interface import WebotsInterface\n\n\nARM_JOINT_NAMES = [\n \"shoulder_pan_joint\",\n \"shoulder_lift_joint\",\n \"elbow_joint\",\n \"wrist_1_joint\",\n \"wrist_2_joint\",\n \"wrist_3_joint\",\n]\n\nGRIPPER3F_JOINT_NAMES = [\n \"palm_finger_1_joint\",\n \"finger_1_joint_1\",\n \"finger_1_joint_2\",\n \"finger_1_joint_3\",\n \"palm_finger_2_joint\",\n \"finger_2_joint_1\",\n \"finger_2_joint_2\",\n \"finger_2_joint_3\",\n \"finger_middle_joint_1\",\n \"finger_middle_joint_2\",\n \"finger_middle_joint_3\",\n]\n\nCYLINDER_NAMES = [\n \"cylinder_1\",\n \"cylinder_2_1\",\n \"cylinder_2_2\",\n \"cylinder_2_3\",\n \"cylinder_2_4\",\n \"cylinder_2_5\",\n \"cylinder_2_6\",\n \"cylinder_2_7\",\n \"cylinder_2_8\",\n \"cylinder_3_1\",\n \"cylinder_3_2\",\n \"cylinder_3_3\",\n \"cylinder_3_4\",\n \"cylinder_3_5\",\n \"cylinder_3_6\",\n \"cylinder_3_7\",\n \"cylinder_3_8\",\n \"cylinder_3_9\",\n \"cylinder_3_10\",\n \"cylinder_3_11\",\n \"cylinder_3_12\",\n]\n\nINIT_POS = {\n ARM_JOINT_NAMES[0]: {\"joint_index\": 0, \"target\": 1.411872641811951},\n ARM_JOINT_NAMES[1]: {\"joint_index\": 1, \"target\": -0.8420041879132294},\n ARM_JOINT_NAMES[2]: {\"joint_index\": 2, \"target\": 1.0565325644929087},\n ARM_JOINT_NAMES[3]: {\"joint_index\": 3, \"target\": -1.7859626190435058},\n ARM_JOINT_NAMES[4]: {\"joint_index\": 4, \"target\": -1.5704882948679586},\n ARM_JOINT_NAMES[5]: {\"joint_index\": 5, \"target\": 1.4109012658608595},\n}\n\n\nclass RobotEnv_webots:\n def __init__(self, render=False):\n\n self.simulation = WebotsInterface()\n self.sim_interface = self.simulation.sim_interface\n self.timestep = int(self.sim_interface.getBasicTimeStep())\n\n # ------------init Gripper---------\n self.GripperPos = 0.0\n self.gripper_minPos = []\n self.gripper_maxPos = []\n self.gripper_maxTorque = []\n self.gripper_motors = []\n self.gripper_sensors = []\n self.gripper3f_jointNames = GRIPPER3F_JOINT_NAMES\n self.arm_JointNames = ARM_JOINT_NAMES\n self.cylinder_names = CYLINDER_NAMES\n\n for name in self.gripper3f_jointNames:\n self.gripper_motors.append(self.sim_interface.getMotor(name))\n try:\n self.gripper_minPos.append(\n self.gripper_motors[-1].getMinPosition())\n except:\n self.gripper_minPos.append(0)\n self.gripper_maxPos.append(\n self.gripper_motors[-1].getMaxPosition())\n self.gripper_maxTorque.append(\n self.gripper_motors[-1].getMaxTorque())\n self.gripper_sensors.append(\n self.sim_interface.getPositionSensor(name + \"_sensor\")\n )\n self.gripper_sensors[-1].enable(self.timestep)\n\n gt = [100] * 11\n # middle finger\n gt[8] = 8 # joint 1\n gt[10] = 8 # joint 3\n # finger 1 and finger 2\n gt[1] = gt[5] = 4\n gt[3] = gt[7] = 8\n gv = [2] * 11\n for i in range(len(self.gripper_motors)):\n self.gripper_motors[i].setAvailableTorque(gt[i])\n self.gripper_motors[i].setVelocity(gv[i])\n # ------------init Robot---------\n self.motors = []\n self.arm_sensors = []\n for name in self.arm_JointNames:\n self.motors.append(self.sim_interface.getMotor(name))\n self.arm_sensors.append(\n self.sim_interface.getPositionSensor(name + \"_sensor\")\n )\n self.arm_sensors[-1].enable(self.timestep)\n\n # ------------init cylinders---------\n self.cylinder_nodes = []\n for name in self.cylinder_names:\n self.cylinder_nodes.append(self.sim_interface.getFromDef(name))\n\n # ----------- Start Timer -----------\n self.sys_start_time = time.perf_counter()\n self.sim_time = 0.0\n\n def execute_n_timesteps(self, n=1):\n \"\"\" Performing simulation step and keeping track on simulation time\n\n Args:\n n (int, optional): Amount of simulation steps to be performed. Defaults to 1.\n \"\"\"\n\n self.sim_interface.step(n * self.timestep)\n self.sim_time = self.sim_interface.getTime()\n\n def set_arm_pos(self, positions):\n \"\"\" Set target joint positions of robot arm\n\n Args:\n pos_percent (list): List of 6 joint positions\n \"\"\"\n\n for i in range(len(positions)):\n self.motors[i].setPosition(positions[i])\n\n def set_gripper_pos(self, pos_percent):\n \"\"\" Set target joint positions of 3fGripper\n\n Args:\n pos_percent (list): List of 11 joint positions between 0 and 1\n \"\"\"\n # make sure, pos_percent and torque_percent are values between 0 and 1\n # pos_percent = min(1, max(0, pos_percent))\n\n # convert percentage to actual position based on min and max position of joint\n for i in range(len(pos_percent)):\n self.gripper_motors[i].setPosition(\n self.gripper_minPos[i]\n + pos_percent[i] *\n (self.gripper_maxPos[i] - self.gripper_minPos[i])\n )\n\n def reset(self):\n \"\"\" Reset simulation \"\"\"\n\n self.simulation.resetSim()\n\n # Get observation\n obs = self.get_obs()\n self.simulation.execute_n_timesteps(1)\n self.simulation.execute_n_timesteps(1)\n\n # Reset simulation and sim time\n self.simulation.resetSim()\n self.sim_time = 0.0\n self.sys_timer_start = time.perf_counter()\n\n return obs\n\n def set_timestep(self, timestep):\n \"\"\" Define simulation timestep\n\n Args:\n timestep (int): Simulation timestep value\n \"\"\"\n\n self.simulation.WorldInfo.getField(\n \"basicTimeStep\").setSFFloat(timestep)\n self.simulation.timestep = timestep\n\n def get_obs(self):\n \"\"\" Get observation from simulation\n\n Returns:\n list: Timer and observation data\n \"\"\"\n\n # Time\n sys_time = time.perf_counter()\n sys_timer = sys_time - self.sys_start_time\n\n self.sim_time = self.sim_interface.getTime()\n\n # Arm joints\n arm_positions = []\n for sensor in self.arm_sensors:\n arm_positions.append(sensor.getValue())\n\n # Gripper joints\n gripper_positions = []\n for sensor in self.gripper_sensors:\n gripper_positions.append(sensor.getValue())\n\n # Cylinder positions\n cylinder_states = []\n for cylinder in self.cylinder_nodes:\n pos = cylinder.getPosition()\n rot = cylinder.getOrientation()\n\n # state = position [3] and orientation as quaternion [4]\n state = [pos, rot]\n cylinder_states.append(state)\n\n return [\n sys_timer,\n self.sim_time,\n arm_positions,\n gripper_positions,\n cylinder_states,\n ]\n","sub_path":"environments/WeBots/controller/robot_env.py","file_name":"robot_env.py","file_ext":"py","file_size_in_byte":6951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"314423851","text":"from datetime import timedelta, datetime\nimport requests\nfrom private import FLIGHT_TOKEN\nfrom flight_data import FlightData\n\nNIGHTS_FROM = '7'\nNIGHTS_TO = '28'\nSEARCH_LIMIT = '1'\nCURRENCY = 'USD'\n\n\nclass FlightSearch:\n def __init__(self):\n self.headers = {'apikey': FLIGHT_TOKEN}\n self.locations_endpoint = f'https://tequila-api.kiwi.com/locations/query'\n self.flights_endpoint = f'https://tequila-api.kiwi.com/v2/search'\n\n def check_destinations(self, destinations_list: list[FlightData]) -> list[FlightData]:\n results = []\n for flight in destinations_list:\n params = {'fly_from': flight.from_airport_code,\n 'fly_to': flight.to_airport_code,\n 'curr': CURRENCY,\n 'date_from': flight.from_date,\n 'date_to': flight.to_date,\n 'nights_in_dst_from': NIGHTS_FROM,\n 'nights_in_dst_to': NIGHTS_TO,\n 'price_to': flight.price,\n 'limit': SEARCH_LIMIT}\n r = requests.get(self.flights_endpoint, headers=self.headers, params=params)\n if r.status_code == 200 and r.json()['data']:\n data = r.json()['data'][0]\n from_date = datetime.strptime(data['local_departure'].split('T')[0], '%Y-%m-%d')\n to_date = from_date + timedelta(days=int(data['nightsInDest']))\n results.append(FlightData(from_airport_code=data['flyFrom'],\n from_city=data['cityFrom'],\n from_date=from_date.strftime('%d/%m/%Y'),\n to_city=data['cityTo'],\n to_airport_code=data['flyTo'],\n to_date=to_date.strftime('%d/%m/%Y'),\n price=data['price'],\n link=data['deep_link']))\n return results\n\n def get_iata_codes(self, cities_list: list) -> dict:\n iata_codes = {}\n for city in cities_list:\n r = requests.get(self.locations_endpoint, headers=self.headers, params={'term': f'{city}'})\n iata_codes[city] = r.json()['locations'][0]['code']\n return iata_codes\n\n","sub_path":"day39-40/flight_search.py","file_name":"flight_search.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"486660094","text":"NAMESPACES = {'media':'http://search.yahoo.com/mrss/'}\n\nNICK_ROOT = 'http://www.nickjr.com'\nNICK_SHOWS_LIST = 'http://www.nickjr.com/common/data/kids/get-kids-config-data.jhtml?fsd=/dynaboss&urlAlias=kids-video-landing&af=false'\nRSS_FEED = 'http://www.nickjr.com/dynamo/video/data/mrssGen.jhtml?type=network&loc=default&hub=kids&mode=playlist&dartSite=nickjr.playtime.nol&mgid=mgid:cms:item:nickjr.com:%s&demo=null&block=true'\n\nNAME = 'Nick Jr.'\nART = 'art-default.jpg'\nICON = 'icon-default.png'\n\nRE_CMSID = Regex('KIDS\\.add\\(\"cmsId\", \"(\\d+)\"\\)')\n\n####################################################################################################\ndef Start():\n\n\tPlugin.AddPrefixHandler('/video/nickjr', MainMenu, NAME, ICON, ART)\n\tPlugin.AddViewGroup('InfoList', viewMode='InfoList', mediaType='items')\n\n\tObjectContainer.title1 = NAME\n\tObjectContainer.view_group = 'InfoList'\n\tObjectContainer.art = R(ART)\n\n\tHTTP.CacheTime = CACHE_1HOUR\n\tHTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:15.0) Gecko/20100101 Firefox/15.0.1'\n\n####################################################################################################\ndef MainMenu():\n\n\toc = ObjectContainer()\n\tcontent = JSON.ObjectFromURL(NICK_SHOWS_LIST)\n\n\tfor item in content['config']['promos'][0]['items']:\n\t\ttitle = item['title'].replace('&', '&')\n\n\t\tif title == 'Featured Nick Jr. Videos':\n\t\t\tcontinue\n\n\t\tthumb = NICK_ROOT + item['thumbnail']\n\t\turl = NICK_ROOT + item['link']\n\n\t\toc.add(DirectoryObject(key=Callback(ShowList, title=title, thumb=thumb, url=url), title=title, thumb=Resource.ContentsOfURLWithFallback(url=thumb, fallback=R(ICON))))\n\n\treturn oc\n\n####################################################################################################\ndef ShowList(title, thumb, url):\n\n\toc = ObjectContainer(title2=title)\n\n\tshow_page = HTTP.Request(url).content\n\tcmsid = RE_CMSID.search(show_page).group(1)\n\tfeed = XML.ElementFromURL(RSS_FEED % cmsid)\n\n\tfor item in feed.xpath('//item'):\n\n\t\ttitle = item.xpath('.//media:title', namespaces=NAMESPACES)[0].text\n\t\tsummary = item.xpath('.//media:description', namespaces=NAMESPACES)[0].text\n\t\turl = item.xpath('.//media:player', namespaces=NAMESPACES)[0].get('url')\n\n\t\tthumb = item.xpath('.//media:thumbnail', namespaces=NAMESPACES)[0].get('url')\n\n\t\tif 'dynaboss' not in thumb:\n\t\t\tthumb = thumb.replace('assets', 'dynaboss/assets')\n\n\t\ttry:\n\t\t\tduration = int(item.xpath('.//media:content', namespaces=NAMESPACES)[0].get('duration')) * 1000\n\t\texcept:\n\t\t\tduration = None\n\n\t\toc.add(VideoClipObject(\n\t\t\turl = url,\n\t\t\ttitle = title,\n\t\t\tsummary = summary,\n\t\t\tduration = duration,\n\t\t\tthumb = Resource.ContentsOfURLWithFallback(url=thumb, fallback=R(ICON))\n\t\t))\n\n\treturn oc\n","sub_path":"Contents/Code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"528729204","text":"# KIANA\n# -*- coding: utf-8 -*-\n# from create_eval_metadata import get_spk_dict, mix_data_with_overlap, normalizeLoudness, extend_noise\nimport h5py\nimport soundfile as sf\nimport glob\nimport os\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torch.nn.utils.rnn import pack_padded_sequence\nfrom torch.autograd import Variable\nimport sys\nimport scipy\nimport scipy.signal\nimport librosa\nimport torchvision.transforms as transforms\nimport random\nimport pyloudnorm as pyln\nimport warnings\nfrom constants import *\nimport pandas as pd\nimport timeit\n\nMIN_LENGTH = 2\nMAX_LENGTH = 3\n\n\ndef to_tensor(x):\n return torch.from_numpy(x).float()\n\n\ndef extend_noise(noise, max_length):\n \"\"\" Concatenate noise using hanning window\"\"\"\n noise_ex = noise\n window = np.hanning(SRATE + 1)\n # Increasing window\n i_w = window[: len(window) // 2 + 1]\n # Decreasing window\n d_w = window[len(window) // 2 :: -1]\n # Extend until max_length is reached\n while len(noise_ex) < max_length:\n noise_ex = np.concatenate(\n (\n noise_ex[: len(noise_ex) - len(d_w)],\n np.multiply(noise_ex[len(noise_ex) - len(d_w) :], d_w)\n + np.multiply(noise[: len(i_w)], i_w),\n noise[len(i_w) :],\n )\n )\n noise_ex = noise_ex[:max_length]\n return noise_ex\n\n\ndef normalizeLoudness(x, x_loudness, target_loudness):\n # normalize loudness\n delta_loudness = target_loudness - x_loudness\n gain = np.power(10.0, delta_loudness / 20.0)\n x = x * gain\n\n # avoid clipping\n if np.max(np.abs(x)) >= 1.0:\n scale = MAX_WAV_AMP / np.max(np.abs(x))\n gain *= scale\n x *= scale\n return x, gain\n\n\ndef get_spk_dict(speech_list):\n spk_id_to_path = {}\n path_to_spk_id = {}\n for speech_file in speech_list:\n lst = speech_file.split(\"/\")\n spk_id = lst[1]\n # print(spk_id)\n if spk_id in spk_id_to_path:\n spk_id_to_path[spk_id].add(speech_file)\n else:\n spk_id_to_path[spk_id] = set([speech_file])\n path_to_spk_id[speech_file] = spk_id\n return spk_id_to_path, path_to_spk_id\n\n\ndef pad_and_mix(\n speech_list,\n speech_length_list,\n speech_gain_list,\n pad_left_list,\n max_size,\n spk_pattern,\n return_targets=False,\n):\n pad_right_list = []\n mixture = 0\n final_speech_dict = {}\n for i, pad_left in enumerate(pad_left_list):\n pad_right = max_size - pad_left - speech_length_list[i]\n speech = speech_list[i]\n final_speech = np.pad(speech, (pad_left, pad_right), mode=\"constant\")\n key = spk_pattern[i]\n if key in final_speech_dict:\n final_speech_dict[key] += final_speech\n else:\n final_speech_dict[key] = final_speech\n\n pad_right_list.append(pad_right)\n mixture += final_speech\n\n # avoid clipping\n scale = 1.0\n max_amp = np.max(np.abs(mixture))\n for key, value in final_speech_dict.items():\n max_amp = max(max_amp, np.max(np.abs(value)))\n\n if max_amp >= 1.0:\n scale = MAX_WAV_AMP / max_amp\n mixture *= scale\n\n updated_gain_list = []\n for i, gain in enumerate(speech_gain_list):\n updated_gain_list.append(gain * scale)\n\n if return_targets:\n spk_keys = list(set(spk_pattern))\n spk_keys.sort()\n target_list = []\n for spk_key in spk_keys:\n target_list.append(final_speech_dict[spk_key] * scale)\n return pad_left_list, pad_right_list, updated_gain_list, mixture, target_list\n\n return pad_left_list, pad_right_list, updated_gain_list, mixture\n\n\ndef mix_data_with_no_overlap(\n speech_list, speech_length_list, speech_gain_list, spk_pattern, return_targets=False\n):\n\n pad_left_list = []\n max_size = 0\n for i, _ in enumerate(spk_pattern):\n speech_length = speech_length_list[i]\n # print(speech_length, speech_list[i].size)\n if i == 0:\n pad_left = 0\n else:\n gap = int(random.uniform(MIN_GAP, MAX_GAP) * SRATE)\n pad_left = prev_end + gap\n pad_left_list.append(pad_left)\n prev_end = pad_left + speech_length\n max_size = max(prev_end, max_size)\n\n return pad_and_mix(\n speech_list,\n speech_length_list,\n speech_gain_list,\n pad_left_list,\n max_size,\n spk_pattern,\n return_targets,\n )\n\n\ndef mix_data_with_overlap(\n speech_list,\n speech_length_list,\n speech_gain_list,\n spk_pattern,\n overlap_type,\n return_targets=False,\n min_offset=16000,\n):\n\n end_list = []\n key_to_prev_end = {}\n max_size = 0\n pad_left_list = []\n for i, key in enumerate(spk_pattern):\n if i == 0:\n pad_left = 0\n else:\n if key in key_to_prev_end and end_list[-1] == key_to_prev_end[key]:\n pad_left = key_to_prev_end[key] + int(\n random.uniform(MIN_GAP, MAX_GAP) * SRATE\n )\n else:\n if overlap_type == \"random\":\n if random.uniform(0, 1) < OVERLAP_PROB:\n if i == 1:\n pad_left = random.randint(\n min_offset, max(end_list[-1], min_offset)\n )\n else:\n gap = int(MIN_GAP * SRATE)\n left = end_list[-2] + gap\n right = max(left, end_list[-1])\n pad_left = random.randint(left, right)\n else:\n pad_left = end_list[-1] + int(\n random.uniform(MIN_GAP, MAX_GAP) * SRATE\n )\n elif overlap_type == \"max\":\n if i == 1:\n pad_left = min_offset\n else:\n pad_left = end_list[-2] + int(MIN_GAP * SRATE)\n elif overlap_type == \"half\":\n if i == 1:\n pad_left = int((min_offset + end_list[-1]) // 2)\n\n else:\n gap = int(random.uniform(MIN_GAP, MAX_GAP) * SRATE)\n left = end_list[-2] + gap\n right = max(left, end_list[-1])\n pad_left = int((left + right) // 2)\n curr_end = pad_left + speech_length_list[i]\n end_list.append(curr_end)\n end_list.sort()\n end_list = end_list[-2:]\n key_to_prev_end[key] = curr_end\n max_size = max(curr_end, max_size)\n pad_left_list.append(pad_left)\n return pad_and_mix(\n speech_list,\n speech_length_list,\n speech_gain_list,\n pad_left_list,\n max_size,\n spk_pattern,\n return_targets,\n )\n\n\ndef sample_spk_pattern(num_spk, num_iter=4):\n tmp_set = set([1])\n spk_pattern = []\n seen_set = set([])\n for i in range(num_iter):\n curr = random.choice(list(tmp_set))\n seen_set.add(curr)\n\n spk_pattern.append(str(curr))\n if len(tmp_set) < num_spk:\n tmp_set.add(len(seen_set) + 1)\n return \"\".join(spk_pattern)\n\n\nclass TrainingDataset(Dataset):\n r\"\"\"Training dataset.\"\"\"\n\n def __init__(\n self,\n speech_list,\n speech_dir,\n noise_list=None,\n noise_dir=None,\n num_spk=2,\n num_out_stream=1,\n num_chunks=4,\n nsamples=160000,\n length=100000,\n overlap_type=\"random\",\n min_offset=1.0,\n ):\n self.num_out_stream = num_out_stream\n with open(speech_list, \"r\") as f:\n speech_list = [\n line.strip().replace(\".flac\", \".samp\") for line in f.readlines()\n ]\n self.speech_list = speech_list\n self.speech_dir = speech_dir\n self.noise_list = noise_list\n if self.noise_list is not None:\n assert noise_dir is not None\n self.noise_dir = noise_dir\n with open(self.noise_list, \"r\") as f:\n noise_list = [line.strip() for line in f.readlines()]\n self.noise_list = noise_list\n\n self.spk_id_to_path, self.path_to_spk_id = get_spk_dict(self.speech_list)\n self.spk_set = set(self.spk_id_to_path.keys())\n print(\"number of training speakers\", len(self.spk_set))\n self.num_spk = num_spk\n self.num_out_stream = num_out_stream\n self.num_chunks = num_chunks\n self.nsamples = nsamples\n self.length = length\n self.overlap_type = overlap_type\n self.min_offset = int(min_offset * SRATE)\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, index):\n feature, target, num_spk = self.generate_data(index)\n\n feature *= FEAT_SCALE\n target *= FEAT_SCALE\n\n feature = to_tensor(feature + 1e-6)\n target = to_tensor(target + 1e-6)\n\n return feature, target, torch.tensor(num_spk).long()\n\n def generate_data(self, index):\n spk_pattern = sample_spk_pattern(self.num_spk, self.num_chunks)\n\n spk_keys = set(spk_pattern)\n num_spk = len(spk_keys)\n spk_ids = random.sample(self.spk_set, num_spk)\n key_to_id = {}\n key_to_files = {}\n for key, spk_id in zip(spk_keys, spk_ids):\n key_to_id[key] = spk_id\n key_to_files[key] = random.sample(\n self.spk_id_to_path[spk_id], spk_pattern.count(key)\n )\n\n speech_list = []\n speech_length_list = []\n speech_gain_list = []\n for key in spk_pattern:\n curr_file = key_to_files[key].pop()\n reader = h5py.File(os.path.join(self.speech_dir, curr_file), \"r\")\n speech = reader[\"speech\"][:]\n speech_loudness = reader[\"loudness\"][()]\n reader.close()\n\n start, end = librosa.effects.trim(\n speech,\n top_db=TOP_DB,\n frame_length=int(FRAME_SIZE * SRATE) // 1000,\n hop_length=int(FRAME_SHIFT * SRATE) // 1000,\n )[1]\n speech_length = int(random.uniform(MIN_LENGTH, MAX_LENGTH) * SRATE)\n end = min(end, start + speech_length)\n speech_length = end - start\n speech = speech[start:end]\n target_speech_loudness = random.uniform(MIN_LOUDNESS, MAX_LOUDNESS)\n speech, speech_gain = normalizeLoudness(\n speech, speech_loudness, target_speech_loudness\n )\n speech_list.append(speech)\n speech_length_list.append(speech_length)\n speech_gain_list.append(speech_gain)\n\n _, _, _, mix_speech, target_list = mix_data_with_overlap(\n speech_list,\n speech_length_list,\n speech_gain_list,\n spk_pattern,\n self.overlap_type,\n return_targets=True,\n min_offset=self.min_offset,\n )\n\n mix_speech = mix_speech[: self.nsamples]\n for i in range(len(target_list)):\n target_list[i] = target_list[i][: self.nsamples]\n\n if self.noise_list is not None:\n mix_speech = self.add_noise(mix_speech)\n scale = 1.0\n if np.max(np.abs(mix_speech)) >= 1.0:\n scale = MAX_WAV_AMP / np.max(np.abs(mix_speech))\n mix_speech *= scale\n for i in range(len(target_list)):\n target_list[i] *= scale\n\n num_spk = len(target_list)\n feature = np.reshape(mix_speech, [1, -1])\n if self.num_out_stream == 1:\n target = np.reshape(target_list[0], [1, -1])\n elif self.num_out_stream == 2:\n target = np.reshape(target_list[0], [1, -1])\n if num_spk > 1:\n background = np.stack(target_list[1:], axis=0)\n background = np.sum(background, axis=0, keepdims=True)\n else:\n assert num_spk <= self.num_out_stream\n background = np.zeros_like(target)\n target = np.concatenate([target, background], axis=0)\n else:\n assert num_spk <= self.num_out_stream\n target = np.stack(target_list, axis=0)\n pad = self.num_out_stream - target.shape[0]\n if pad > 0:\n target = np.pad(target, ((0, pad), (0, 0)), mode=\"constant\")\n return feature, target, num_spk\n\n def add_noise(self, mix_speech):\n mix_speech_size = mix_speech.size\n noise_ind = random.randint(0, len(self.noise_list) - 1)\n noise_file = self.noise_list[noise_ind]\n reader = h5py.File(os.path.join(self.noise_dir, noise_file), \"r\")\n noise = reader[\"noise\"][:]\n noise_loudness = reader[\"loudness\"][()]\n reader.close()\n assert np.sum(noise ** 2) > 0.0\n\n if noise.size < mix_speech_size:\n noise = extend_noise(noise, mix_speech_size)\n else:\n noise_start = random.randint(0, noise.size - mix_speech_size)\n noise = noise[noise_start : noise_start + mix_speech_size]\n\n target_noise_loudness = random.uniform(NOISE_MIN_LOUDNESS, NOISE_MAX_LOUDNESS)\n\n noise, _ = normalizeLoudness(noise, noise_loudness, target_noise_loudness)\n\n mix_speech += noise\n\n return mix_speech\n\n\nclass EvalDataset(Dataset):\n r\"\"\"Evaluation dataset.\"\"\"\n\n def __init__(\n self,\n metadata_file,\n speech_dir,\n noise_dir=None,\n spk_pattern_list=None,\n overlap_type_list=None,\n ):\n self.df = pd.read_csv(metadata_file)\n # print(type(self.df.iloc[0][\"spk_pattern\"]))\n self.speech_dir = speech_dir\n self.noise_dir = noise_dir\n self.spk_pattern_list = spk_pattern_list\n self.overlap_type_list = overlap_type_list\n if self.spk_pattern_list is not None:\n assert type(self.spk_pattern_list) == list\n self.spk_pattern_list = [int(_) for _ in self.spk_pattern_list]\n print(\"speaker_pattern_list\", self.spk_pattern_list)\n self.df = self.df[self.df[\"spk_pattern\"].isin(self.spk_pattern_list)]\n\n if self.overlap_type_list is not None:\n assert type(self.overlap_type_list) == list\n self.df = self.df[self.df[\"overlap_type\"].isin(self.overlap_type_list)]\n\n self.length = len(self.df)\n\n def __len__(self):\n return self.length\n\n def __getitem__(self, index):\n curr_row = self.df.iloc[index]\n spk_pattern = str(curr_row[\"spk_pattern\"])\n speech_path_list = curr_row[\"speech_path_list\"].split(\" \")\n speech_start_list = [int(_) for _ in curr_row[\"speech_start_list\"].split(\" \")]\n speech_length_list = [int(_) for _ in curr_row[\"speech_length_list\"].split(\" \")]\n pad_left_list = [int(_) for _ in curr_row[\"pad_left_list\"].split(\" \")]\n pad_right_list = [int(_) for _ in curr_row[\"pad_right_list\"].split(\" \")]\n speech_gain_list = [float(_) for _ in curr_row[\"speech_gain_list\"].split(\" \")]\n\n target_dict = {}\n mix_speech = 0\n for i, spk_id in enumerate(spk_pattern):\n reader = h5py.File(os.path.join(self.speech_dir, speech_path_list[i]), \"r\")\n speech = reader[\"speech\"][:]\n reader.close()\n\n speech = speech[\n speech_start_list[i] : speech_start_list[i] + speech_length_list[i]\n ]\n speech = np.pad(\n speech, (pad_left_list[i], pad_right_list[i]), mode=\"constant\"\n )\n speech *= speech_gain_list[i]\n\n mix_speech += speech\n if spk_id in target_dict:\n target_dict[spk_id] += speech\n else:\n target_dict[spk_id] = speech\n\n keys = list(target_dict.keys())\n num_spk = len(keys)\n keys.sort()\n target_list = []\n for i, key in enumerate(keys):\n target_list.append(target_dict[key])\n\n if self.noise_dir is not None:\n noise_path = curr_row[\"noise_path\"]\n reader = h5py.File(os.path.join(self.noise_dir, noise_path), \"r\")\n noise = reader[\"noise\"][:]\n reader.close()\n\n noise_start = curr_row[\"noise_start\"]\n noise_gain = curr_row[\"noise_gain\"]\n ext_noise = bool(curr_row[\"extend_noise\"])\n if ext_noise:\n noise = extend_noise(noise, mix_speech.size)\n else:\n noise = noise[noise_start : noise_start + mix_speech.size]\n\n noise *= noise_gain\n mix_speech += noise\n\n feature = np.reshape(mix_speech, [1, -1])\n target = np.reshape(target_list[0], [1, -1])\n\n # amplify as during training\n feature = feature * FEAT_SCALE\n target = target * FEAT_SCALE\n\n feature = to_tensor(feature + 1e-6)\n label = to_tensor(target + 1e-6)\n\n d = dict(curr_row)\n\n return feature, label, torch.tensor(num_spk).long(), d\n\n\nclass TrainCollate(object):\n def __init__(self):\n self.name = \"collate\"\n\n def __call__(self, batch):\n if isinstance(batch, list):\n feat_nchannels = batch[0][0].shape[0]\n label_nchannels = batch[0][1].shape[0]\n sorted_batch = sorted(batch, key=lambda x: x[0].shape[1], reverse=True)\n lengths = list(map(lambda x: (x[0].shape[1], x[1].shape[1]), sorted_batch))\n\n padded_feature_batch = torch.zeros(\n (len(lengths), feat_nchannels, lengths[0][0])\n )\n padded_label_batch = torch.zeros(\n (len(lengths), label_nchannels, lengths[0][1])\n )\n lengths1 = torch.zeros((len(lengths),), dtype=torch.int32)\n num_spks = torch.zeros((len(lengths),), dtype=torch.int32)\n for i in range(len(lengths)):\n padded_feature_batch[i, :, 0 : lengths[i][0]] = sorted_batch[i][0]\n padded_label_batch[i, :, 0 : lengths[i][1]] = sorted_batch[i][1]\n lengths1[i] = lengths[i][1]\n num_spks[i] = sorted_batch[i][2]\n\n return padded_feature_batch, padded_label_batch, num_spks, lengths1\n else:\n raise TypeError(\"`batch` should be a list.\")\n\n\nclass EvalCollate(object):\n def __init__(self):\n self.name = \"TestCollate\"\n\n def __call__(self, batch):\n if isinstance(batch, list):\n\n feat_nchannels = batch[0][0].shape[0]\n label_nchannels = batch[0][1].shape[0]\n sorted_batch = sorted(batch, key=lambda x: x[0].shape[1], reverse=True)\n lengths = list(map(lambda x: (x[0].shape[1], x[1].shape[1]), sorted_batch))\n\n padded_feature_batch = torch.zeros(\n (len(lengths), feat_nchannels, lengths[0][0])\n )\n padded_label_batch = torch.zeros(\n (len(lengths), label_nchannels, lengths[0][1])\n )\n lengths1 = torch.zeros((len(lengths),), dtype=torch.int32)\n num_spks = torch.zeros((len(lengths),), dtype=torch.int32)\n dicts = []\n for i in range(len(lengths)):\n padded_feature_batch[i, :, 0 : lengths[i][0]] = sorted_batch[i][0]\n padded_label_batch[i, :, 0 : lengths[i][1]] = sorted_batch[i][1]\n lengths1[i] = lengths[i][1]\n num_spks[i] = sorted_batch[i][2]\n dicts.append(sorted_batch[i][3])\n\n return padded_feature_batch, padded_label_batch, num_spks, lengths1, dicts\n else:\n raise TypeError(\"`batch` should be a list.\")\n","sub_path":"Librispeech/scripts/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":19579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"491918281","text":"\nfrom millerrabin import mr_test\ndef eratosthenes(n):\n\tsieve = list(range(n + 1))\n\tsieve[1] = 0 \n\tfor i in sieve:\n\t\tif i > 1:\n\t\t\tfor j in range(i + i, len(sieve), i):\n\t\t\t\tsieve[j] = 0\n\tres=[]\n\tfor x in sieve:\n\t\tif x:\n\t\t\tres.append(x)\n\treturn res\n\nSIMPLE_EVENS=eratosthenes(1000000)\ndef isSimple(g):\n\t\t#return mr_test(g)\n\t\treturn True if g in SIMPLE_EVENS else False\n\ndef extended_euclidean_algorithm(a, b):\n \"\"\"\n Возвращает кортеж из трёх элементов (gcd, x, y), такой, что\n a * x + b * y == gcd, где gcd - наибольший\n общий делитель a и b.\n\n В этой функции реализуется расширенный алгоритм\n Евклида и в худшем случае она выполняется O(log b).\n \"\"\"\n s, old_s = 0, 1\n t, old_t = 1, 0\n r, old_r = b, a\n\n while r != 0:\n quotient = old_r // r\n old_r, r = r, old_r - quotient * r\n old_s, s = s, old_s - quotient * s\n old_t, t = t, old_t - quotient * t\n\n return old_r, old_s, old_t\n\n\ndef exgcd(a, b):\n if a == 0:\n return (b, 0, 1)\n else:\n g, y, x = exgcd(b % a, a)\n return (g, x - (b // a) * y, y)\n\n\ndef inverse_of(a, m):\n g, x, y = exgcd(abs(a), m)\n if g != 1:\n raise Exception('Обратного элемента не существует')\n else:\n if a > 0:\n return x % m\n else:\n return -x % m\n \ndef OK(value=\"\"):\n\treturn {\"status\":True,\"value\":value}\n\ndef ERR(value=\"\"):\n\treturn {\"status\":False,\"value\":value}","sub_path":"sugar.py","file_name":"sugar.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"464818473","text":"from Vector2f import Vector2f\nfrom BoundingBox import BoundingBox\nfrom Bitmap import Bitmap\nimport math, pygame\nfrom pygame import gfxdraw\n\nBLACK = ( 0, 0, 0, 255)\nWHITE = (255, 255, 255, 255)\nBLUE = ( 0, 0, 255, 255)\nGREEN = ( 0, 255, 0, 255)\nRED = (255, 0, 0, 255)\nYELLOW = (255, 255, 0, 255)\n\nclass PacmanEntity:\n\n\tdef __init__(self):\n\t\tself.vel = Vector2f(0, 0)\n\t\tself.spawn = Vector2f(303 - 16, 529 - 17)\n\t\tself.pos = self.spawn\n\t\tself.radius = 10\n\n\t\tself.bg = Bitmap(\"./resources/player_boundaries.png\")\n\n\t\t# self.spawn = Vector2f.Vector2f(0, 0)\n\t\t# for x in range(0, self.bg.width):\n\t\t# \tfor y in range(0, self.bg.height):\n\t\t# \t\tif self.bg.getColourAt(x, y) == YELLOW:\n\t\t# \t\t\tself.spawn.set(x, y)\n\t\t# \t\t\tbreak\n\n\t\tself.alive = True\n\n\t\tself.bounds = BoundingBox(\n\t\t\tself.pos.x, self.pos.y, \n\t\t\t2 * self.radius, 2 * self.radius)\n\n\t\tself.theta = 0\n\t\tself.dir = 0\n\n\tdef setPosition(self, pos):\n\t\tself.pos = pos\n\n\tdef setVelocity(self, vel):\n\t\tself.vel = vel\n\n\tdef kill(self):\n\t\tif self.alive == True:\n\n\t\t\tself.alive = False\n\n\tdef update(self, delta, elapsedTime):\n\n\t\tif self.alive == True:\n\n\t\t\tif self.vel.x > 0 and self.vel.y == 0:\n\t\t\t\tself.dir = 0\n\t\t\telif self.vel.x < 0 and self.vel.y == 0:\n\t\t\t\tself.dir = 180\n\t\t\telif self.vel.y > 0 and self.vel.x == 0:\n\t\t\t\tself.dir = 90\n\t\t\telif self.vel.y < 0 and self.vel.x == 0:\n\t\t\t\tself.dir = 270\n\n\t\t\tself.theta = 45 * math.fabs(math.sin(5 * elapsedTime))\n\n\t\t\tnextPos = self.pos.add(self.vel.mulS(delta))\n\t\t\tself.bounds = BoundingBox(\n\t\t\t\tnextPos.x, nextPos.y, \n\t\t\t\t2*self.radius, 2*self.radius)\n\n\t\t\tisValidMove = True\n\t\t\tfor x in range(int(self.bounds.xMin), int(self.bounds.xMax)):\n\t\t\t\tfor y in range(int(self.bounds.yMin), int(self.bounds.yMax)):\n\n\t\t\t\t\tcolour = self.bg.getColourAt(x, y)\n\n\t\t\t\t\tif colour == WHITE:\n\t\t\t\t\t\tisValidMove = False\n\t\t\t\t\t\tbreak\n\t\t\t\n\t\t\tif isValidMove:\n\t\t\t\tself.pos = nextPos\n\n\t\telif self.theta < 180:\n\t\t\tself.theta += 100 * delta\n\t\t\tif self.theta > 180:\n\t\t\t\tself.alive = True\n\t\t\t\tself.theta = 0\n\t\t\t\tself.pos = self.spawn\n\n\n\tdef render(self, screen):\n\n\t\tfor r in range(1, self.radius):\n\t\t\tfor t in range(int(self.theta), 180):\n\t\t\t\tpygame.gfxdraw.pie(\n\t\t\t\t\tscreen.screen, \n\t\t\t\t\tint(self.pos.x + self.radius), \n\t\t\t\t\tint(self.pos.y + self.radius), \n\t\t\t\t\tr, t + self.dir, -t + self.dir, (255, 255, 0))","sub_path":"Pacman1/PacmanEntity.py","file_name":"PacmanEntity.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"253628012","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#from __future__ import division\nimport os\nimport sys\nimport numpy as np\nfrom string import punctuation\n\n##########################################################################################################\n# Function definition \n##########################################################################################################\n\n# 2. Sentiment dictionary analysis basic function\n# Function of matching adverbs of degree and set weights\ndef match(word, sentiment_value):\n# print word\n \n if word in mostdict:\n sentiment_value *= 2.0\n# print \"2\"\n elif word in verydict:\n# print \"1.5\"\n sentiment_value *= 1.5\n elif word in moredict:\n# print \"1.25\"\n sentiment_value *= 1.25\n elif word in ishdict:\n# print \"0.5\"\n sentiment_value *= 0.5\n elif word in insufficientdict:\n# print \"0.25\"\n sentiment_value *= 0.25\n elif word in inversedict:\n # print \"-1\"\n sentiment_value *= -1\n # print word\n \n return sentiment_value\n\n# Function of transforming negative score to positive score\n# Example: [5, -2] → [7, 0]; [-4, 8] → [0, 12]\ndef transform_to_positive_num(poscount, negcount):\n pos_count = 0\n neg_count = 0\n if poscount < 0 and negcount >= 0:\n neg_count += negcount - poscount\n pos_count = 0\n elif negcount < 0 and poscount >= 0:\n pos_count = poscount - negcount\n neg_count = 0\n elif poscount < 0 and negcount < 0:\n neg_count = -poscount\n pos_count = -negcount\n else:\n pos_count = poscount\n neg_count = negcount\n return [pos_count, neg_count]\n\n\n# 3.1 Single review's positive and negative score\n# Function of calculating review's every sentence sentiment score\ndef sumup_sentence_sentiment_score(score_list):\n\tscore_array = np.array(score_list) # Change list to a numpy array\n\tPos = np.sum(score_array[:,0]) # Compute positive score\n\tNeg = np.sum(score_array[:,1])\n\n\treturn [Pos, Neg] #, AvgPos, AvgNeg, StdPos, StdNeg]\n\ndef single_review_sentiment_score(seg_sent):\n single_review_senti_score = []\n# punctuation_bits = []\n word_posit = 1 # word position counter for whole seg_sent\n group_start_bit = 0 # start position for each meaning group\n start_bit = 0 # sentiment word position\n stop_bit = 0 # word position counter for slice of seg_sent[a:i]\n poscount = 0 # count a positive score\n negcount = 0 # count a negative score\n pos_flag = 0\n neg_flag = 0\n\n for word in seg_sent: \n # seperate into different meaning group \n if word == \"and\" or word == \"or\" or word in list(punctuation): \n start_bit = stop_bit = group_start_bit \n for x in seg_sent[ group_start_bit : word_posit ]:\n stop_bit += 1 \n if x in posdict:\n # print x\n poscount += 1\n pos_flag = 1\n neg_flag = 0\n for w in seg_sent[start_bit:word_posit]:\n poscount = match(w, poscount)\n start_bit = stop_bit + 1\n elif x in negdict:\n negcount += 1\n pos_flag = 0\n neg_flag = 1\n for w in seg_sent[start_bit:word_posit]:\n negcount = match(w, negcount)\n start_bit = stop_bit + 1\n elif stop_bit == word_posit: \n if pos_flag == 1:\n for w in seg_sent[start_bit:word_posit]:\n poscount = match(w, poscount)\n elif neg_flag == 1:\n for w in seg_sent[start_bit:word_posit]:\n negcount = match(w, negcount)\n \n group_start_bit = word_posit + 1\n pos_flag = 0\n neg_flag = 0\n # if one meaning group has negative words, it means positive sentiment even if having positive words\n if negcount > 0:\n poscount = 0\n# print poscount\n# print negcount \n # arriving at the end of the seg_sent\n elif word_posit == len(seg_sent): \n start_bit = stop_bit = group_start_bit \n for x in seg_sent[ group_start_bit : word_posit ]:\n stop_bit += 1 \n if x in posdict:\n # print x\n poscount += 1\n pos_flag = 1\n neg_flag = 0\n for w in seg_sent[start_bit:word_posit]:\n poscount = match(w, poscount)\n start_bit = stop_bit + 1\n elif x in negdict:\n negcount += 1\n pos_flag = 0\n neg_flag = 1\n for w in seg_sent[start_bit:word_posit]:\n negcount = match(w, negcount)\n start_bit = stop_bit + 1\n elif stop_bit == word_posit: \n if pos_flag == 1:\n for w in seg_sent[start_bit:word_posit]:\n poscount = match(w, poscount)\n elif neg_flag == 1:\n for w in seg_sent[start_bit:word_posit]:\n negcount = match(w, negcount)\n \n \n # if one meaning group has negative words, it means positive sentiment even if having positive words\n if negcount > 0:\n poscount = 0\n# print poscount\n# print negcount\n \n word_posit += 1\n \n single_review_senti_score.append(transform_to_positive_num(poscount, negcount))\n review_sentiment_score = sumup_sentence_sentiment_score(single_review_senti_score)\n \n return review_sentiment_score\n \ndef review_sentiment_analysis(review):\n \n ##########################################################################################################\n # Sentiment analysis and output \n ##########################################################################################################\n \n tweet_processed=review.lower()\n tweet_processed=tweet_processed.replace(\"'\",'')\n tweet_processed=tweet_processed.replace('\"','')\n \n for p in list(punctuation):\n temp_str=' '+p\n tweet_processed=tweet_processed.replace(p,temp_str)\n \n tweet_processed=tweet_processed.replace(\"1\",'')\n tweet_processed=tweet_processed.replace(\"5\",'')\n tweet_processed=tweet_processed.replace(\"\\t\",'')\n tweet_processed=tweet_processed.replace(\"\\r\",'')\n \n words=tweet_processed.split(' ')\n sentiment_score = single_review_sentiment_score(words)\n \n \n if sentiment_score[0] > sentiment_score[1]:\n# print \"positive\"\n# print sentiment_score[0]\n return 'positive'\n\n elif sentiment_score[0] <= sentiment_score[1]:\n # print \"negative\"\n # print sentiment_score[1]\n return 'negative'\n\n \n \n##########################################################################################################\n# Documents reading \n##########################################################################################################\n\nfilelist=['negative.txt','positive.txt','mostdict.txt', 'verydict.txt', 'moredict.txt','ishdict.txt','insufficientdict.txt','inversedict.txt','stopwords.txt','24kData2.txt']\n\nfor num in range(0, 10):\n filelist[num] = os.path.join(os.getcwd(), filelist[num]) \n\nnegative_word = file(filelist[0], \"r\").read()\nnegative_word=negative_word.replace(\"\\r\",'')\nnegdict = negative_word.split('\\n')\n\n\npositive_word = file(filelist[1], \"r\").read()\npositive_word=positive_word.replace(\"\\r\",'')\nposdict = positive_word.split('\\n')\n\n\nmost_word = file(filelist[2], \"r\").read()\nmost_word=most_word.replace(\"\\r\",'')\nmostdict = most_word.split('\\n')\n\n\nvery_word = file(filelist[3], \"r\").read()\nvery_word=very_word.replace(\"\\r\",'')\nverydict = very_word.split('\\n')\n\n\nmore_word = file(filelist[4], \"r\").read()\nmore_word=more_word.replace(\"\\r\",'')\nmoredict = more_word.split('\\n')\n\n\nish_word = file(filelist[5], \"r\").read()\nish_word=ish_word.replace(\"\\r\",'')\nishdict = ish_word.split('\\n')\n\n\ninsufficient_word = file(filelist[6], \"r\").read()\ninsufficient_word=insufficient_word.replace(\"\\r\",'')\ninsufficientdict = insufficient_word.split('\\n')\n\ninverse_word=file(filelist[7],\"r\").read()\ninverse_word=inverse_word.replace(\"\\r\",'')\ninversedict=inverse_word.split('\\n')\n\nstopwords_contain = file(filelist[8], \"r\").read()\nstopwords_list = stopwords_contain.split(',')\n\nrecommend_contain = file(filelist[9], \"r\").read()\nrecommend_list = recommend_contain.split('\\n')\n\n\n\n##########################################################################################################\n# Documents processing \n########################################################################################################## \n\nfor i in range(0, len(recommend_list)): \n recommend_list[i] = review_sentiment_analysis(recommend_list[i]) + ' ' + recommend_list[i] + \"\\n\"\nfp = file(os.path.join(os.getcwd(), \"output.txt\"), \"w\")\nfp.writelines(recommend_list)\nfp.close()\n\n\n\n\n\n\n \n\n\n\n\n \n\n\n\n\n\n\n","sub_path":"Python-big data challenge/Big data challenge/sentiment analysis(reading from 24K).py","file_name":"sentiment analysis(reading from 24K).py","file_ext":"py","file_size_in_byte":9743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"630597905","text":"from django import template\nimport re\n\nregister = template.Library()\na = re.compile(r'http://[^?]+\\?id=([^&]+).*')\n\n@register.filter\ndef extract_id(url):\n match = a.match(url)\n if match:\n return match.groups()[0]\n return url","sub_path":"mysite/templatetags/connectiontags.py","file_name":"connectiontags.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"122092673","text":"import os\nimport json\n\nclass CostOptimizer:\n '''\n Cost optimizer class which reads the configurations of regions devices & costs\n and calculates the optimized resource allocation.\n\n Methods:\n --------------------------------\n read_config()\n reads the configuration files\n get_machines()\n returns the machines associated with regions\n get_machine_order()\n return the order of machines to be allocated\n remove_highcost_machines()\n removes the machines which charges high fare\n optimize()\n returns the optimized output for all regions\n '''\n\n __config_path = ''\n __capacities = None\n __region_costs = None\n __region_machines = {}\n __machine_order = []\n\n def __new__(cls, *args, **kwargs):\n '''\n Restricts the creation of instance if the config file(s) are not available\n '''\n config_path = '../config'\n if 'config_path' in kwargs.keys():\n config_path = kwargs['config_path']\n kwargs['config_path'] = config_path\n if (not os.path.exists(os.path.join(os.path.abspath(config_path), 'capacities.json'))) \\\n or (not os.path.exists(os.path.join(os.path.abspath(config_path), 'region_cost.json'))):\n print('Path/file(s) does not exist!')\n raise FileNotFoundError\n return super(CostOptimizer, cls).__new__(cls)\n\n def __init__(self, config_path='../config'):\n '''\n Initializes class with the required values\n\n Parameters\n --------------------------------\n config_path: \n path to config directory\n '''\n super().__init__()\n self.__config_path = config_path\n self.read_configs()\n self.__region_machines = self.get_machines()\n self.__machine_order = self.get_machine_order()\n self.remove_highcost_machines()\n\n def read_configs(self):\n '''\n Reads the config file\n '''\n try:\n with open(os.path.join(os.path.abspath(self.__config_path), 'capacities.json'), 'r') as capacities_file:\n self.__capacities = json.load(capacities_file)\n with open(os.path.join(os.path.abspath(self.__config_path), 'region_cost.json'), 'r') as cost_file:\n self.__region_costs = json.load(cost_file)\n except Exception as e:\n raise e\n\n def get_machines(self):\n '''\n Returns the machines associated with region\n\n Return\n --------------------------------\n machines: \n '''\n return {region: list(machines.keys()) for region, machines in self.__region_costs.items()}\n\n def get_machine_order(self):\n '''\n Returns the machine order\n\n Return\n --------------------------------\n machine_order: \n '''\n return sorted(list(self.__capacities.keys()), key = lambda x: self.__capacities[x], reverse = True)\n\n def remove_highcost_machines(self):\n '''\n Removes the machines that cost more from regions\n '''\n for region in self.__region_machines.keys():\n prev_cost = -1\n multiplier = 1\n for machine in self.__machine_order[::-1]:\n if machine in self.__region_machines[region]:\n if prev_cost == -1:\n prev_cost = self.__region_costs[region][machine]\n elif ((prev_cost * multiplier * 2) >= self.__region_costs[region][machine]):\n prev_cost = self.__region_costs[region][machine]\n multiplier = 1\n else:\n self.__region_machines[region].remove(machine)\n multiplier += 1\n else:\n multiplier += 1\n\n def optimize(self, capacity, hours):\n '''\n Optimizes the resources with the given capacity and hours\n\n Parameters\n --------------------------------\n capacity: \n hours: \n\n Return\n --------------------------------\n optimized_output: \n '''\n if (capacity % 10 != 0):\n print('Capacity can only be multiples of 10!')\n return\n result = []\n for region in self.__region_machines.keys():\n region_optimized_data = {\n 'region': region,\n 'total_cost': 0,\n 'machines': []\n }\n reg_capacity = capacity\n for machine in self.__machine_order:\n if machine in self.__region_machines[region]:\n count = reg_capacity // self.__capacities[machine]\n if count == 0:\n continue\n reg_capacity = reg_capacity % self.__capacities[machine]\n region_optimized_data['machines'].append((machine, count))\n region_optimized_data['total_cost'] += (count * self.__region_costs[region][machine])\n if reg_capacity == 0:\n break\n \n region_optimized_data['total_cost'] = '$' + str(region_optimized_data['total_cost'] * hours)\n result.append(region_optimized_data)\n return {'Output': result}\n","sub_path":"src/cost_optimizer.py","file_name":"cost_optimizer.py","file_ext":"py","file_size_in_byte":5293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"222643640","text":"'''\n************************************************\n*Time:2017.9.11 \n*Target:All movies' information of IMDB TOP_250\n*Resources:http://www.imdb.cn/IMDB250/\n************************************************\n'''\n\nimport re\nimport requests\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom bs4 import BeautifulSoup\n\nnum = 1 #电影计数\nAll_txt = [] #全部电影的信息\nheaders={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'}#浏览器代理\ndef getHTMLText(url):\n try:\n #print(url)\n r = requests.get( url,headers = headers )\n #print(r)\n r.encoding = 'utf-8'\n return r.text\n except:\n return \"错误\"\n\n\ndef get_all_information(url,page):\n '''\n 从每一部电影的页面中获取全部信息\n '''\n global num,All_txt\n txt = getHTMLText(url)\n if txt != \"错误\":\n print('page'+str(page)+' NO.'+str(num)+' Get it!')\n if num == 10:\n print('Finished!!!')\n soup = BeautifulSoup(txt,\"html.parser\")\n Cname,Ename,Score,title,Actor,Starring,Infor = '','','','','','',''\n\n #TOP250-film_Chinese_name&Score\n infor_1 = soup.find_all('div',class_ = 'hdd')\n rel = '

'+'[\\s\\S]*?'+'

'\n pattern = re.compile(rel)\n Cname = ''.join(pattern.findall(str(infor_1[0])))\n Cname = Cname.replace('

','').replace('

','')\n #print(Cname)\n #find_the_year & save\n rel = '('+'[\\s\\S]*?'+')'\n pattern = re.compile(rel)\n time_ = ''.join(pattern.findall(Cname))\n #print(time_)\n with open('time.txt','a',encoding='utf-8') as t:\n t.write( time_.replace('(','').replace(')','') + '\\n' )\n #find_Score\n rel = ''+'[\\s\\S]*?'+''\n pattern = re.compile(rel)\n Score = ''.join(pattern.findall(str(infor_1[0])))\n Score = Score.replace('','').replace('','')\n #print(Cname,Score)\n\n #TOP250-film_many_infor\n now = soup.find_all('div',class_ = 'bdd clear')\n #print(now[0])\n a = BeautifulSoup(str(now[0]), \"html.parser\")\n many_infor = a.find_all('li')\n\n #TOP250-film_Ename\n Ename = str(many_infor[0]).replace('
  • ','').replace('','').replace('','').replace('
  • ','').replace('','').replace('','')\n #TOP250-film_Actor\n Actor_temp = BeautifulSoup(str(many_infor[2]), \"html.parser\").find_all('a')\n Actor = Actor_temp[0].get_text().replace('导演:','')\n #TOP250-film_Starring\n Starring_temp = BeautifulSoup(str(many_infor[3]), \"html.parser\").find_all('a')\n for i in Starring_temp:\n Starring += i.get_text().replace(' ','') + ' '\n #print(Starring)\n\n #Top-film_Infor\n for j in range(4,7):\n Infor_temp = BeautifulSoup(str(many_infor[j]), \"html.parser\")\n for i in Infor_temp.children:\n Infor += i.get_text().replace(' ','') + ' '\n Infor += '\\n'\n #print(Infor)\n\n #TOP250-film_Synopsis\n content = soup.find_all('div',class_ = 'fk-4 clear')\n #print(content)\n soup_con = BeautifulSoup(str(content[0]), \"html.parser\")\n title = soup_con.find_all('div',class_ = 'hdd')\n title = str(title[0]).replace('
    ','').replace('
    ','\\n')\n #print(title)\n content_1 = soup_con.find_all('div',class_ = 'bdd clear')\n content_1 = str(content_1[0]).replace('
    ','').replace('
    ','')\n content_1 = content_1.replace('','').replace('
    ','\\n')\n\n #Save_all_information\n All_txt.append('第'+str(num)+'部'+'\\n')\n All_txt.append( Cname+'\\n' )\n All_txt.append( '【英文名】'+Ename+'\\n' )\n All_txt.append( '【评分】'+Score+'\\n' )\n All_txt.append( '【导演】'+Actor+'\\n' )\n All_txt.append( '【主演】'+Starring+'\\n' )\n All_txt.append( Infor+'\\n' )\n All_txt.append( title+'\\n'+content_1+'\\n' )\n All_txt.append('\\n')\n num += 1\n\n\ndef getin_one(url,page):\n '''\n 在每一页中得到当前页的全部电影的url\n '''\n txt = getHTMLText(url)\n soup = BeautifulSoup(txt, \"html.parser\")\n #print(soup)\n temp = soup.find_all('div',class_=\"ss-3 clear\")\n rel = ''\n pattern = re.compile(rel)\n All_url = pattern.findall( str(temp[0]) )\n for i in range(len(All_url)):\n temp_url = 'http://www.imdb.cn'+All_url[i].replace('','')\n get_all_information(temp_url,page)\n #print(All_url)\n\n\ndef Analyze_some_infor():\n '''\n 将所有电影的年份统计并生成条形图\n '''\n plt.rc('font', family='SimHei', size=13)#字体及大小\n #Analyze_time\n file = open('time.txt')\n a,b,c,d,e,f = 0,0,0,0,0,0\n for line in file:\n line = eval(line)\n if line == 0:\n f += 1\n elif line < 1940 and line >= 1920:\n a += 1 \n elif line < 1960 and line >= 1940:\n b += 1\n elif line < 1980 and line >= 1960:\n c += 1\n elif line < 2000 and line >= 1980:\n d += 1\n else:\n e += 1\n times = [a,b,c,d,e,f]\n range_time = ['1920-1940','1940-1960','1960-1980','1980-2000','2000-现在','无信息']\n idx = np.arange(len(range_time))\n width = 0.5\n plt.bar(idx,times,width,color='green')\n plt.xticks(idx+width/2, range_time, rotation=40)\n plt.xlabel('电影年代')\n plt.ylabel('数目')\n plt.savefig('time_pic.png')\n plt.show()\n\ndef main():\n global All_txt\n getin_one('http://www.imdb.cn/IMDB250/',1)\n for i in range(2,3):\n getin_one( 'http://www.imdb.cn/imdb250/'+str(i) , i )\n #将已有内容清空\n with open('All_infor.txt','w',encoding='utf-8') as x:\n pass\n with open('All_infor.txt','a',encoding='utf-8') as x:\n for i in All_txt:\n x.write(i)\n Analyze_some_infor()\n\nmain()\n","sub_path":"basic/豆瓣电影爬虫/豆瓣电影爬虫/豆瓣电影爬虫.py","file_name":"豆瓣电影爬虫.py","file_ext":"py","file_size_in_byte":5870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"400057105","text":"import numpy as np\nimport pandas as pd\nimport torch\nfrom PIL import Image\nfrom torch import optim, nn\nimport torch.nn.functional as F\nfrom torchvision import transforms\nfrom torch.utils.data.dataset import Dataset\n\n\nclass DatasetFromCSV(Dataset):\n def __init__(self, csv_path, height, width, transforms=None):\n self.data = pd.read_csv(csv_path)\n self.labels = np.asarray(self.data.iloc[:, 0])\n self.height = height\n self.width = width\n self.transforms = transforms\n\n def __getitem__(self, index):\n single_image_label = self.labels[index]\n # 读取所有像素值,并将 1D array ([784]) reshape 成为 2D array ([28,28])\n img_as_np = np.asarray(self.data.iloc[index][1:]).reshape(8, 8).astype(float)\n # 把 numpy array 格式的图像转换成灰度 PIL image\n img_as_img = Image.fromarray(img_as_np)\n img_as_img = img_as_img.convert('L')\n # 将图像转换成 tensor\n if self.transforms is not None:\n img_as_tensor = self.transforms(img_as_img)\n # 返回图像及其 label\n return (img_as_tensor, single_image_label)\n\n def __len__(self):\n return len(self.data.index)\n\n\nbatch_size = 64\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))])\n\ntrain_data = DatasetFromCSV('./dataset/bit.csv', 8, 8, transform)\ntest_data = DatasetFromCSV(\"./dataset/bit.csv\", 8, 8, transform)\n\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size)\n\nimg, lab = next(iter(train_loader))\nprint(img.shape)\n","sub_path":"testloader.py","file_name":"testloader.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"369923510","text":"from django.db import models\n\nfrom api.validators import year_validator\n\nfrom .category_model import Category\nfrom .genre_model import Genre\n\n\nclass Title(models.Model):\n \"\"\"Модель произведения (фильма, книги, песни).\"\"\"\n name = models.CharField('название произведения', max_length=100)\n year = models.SmallIntegerField('год', blank=True, null=True,\n validators=[year_validator], )\n description = models.TextField(\n 'описание',\n max_length=1000,\n blank=True,\n null=True)\n genre = models.ManyToManyField(\n Genre,\n related_name='titles',\n verbose_name='жанр',\n )\n category = models.ForeignKey(\n Category,\n on_delete=models.SET_NULL,\n related_name='titles',\n verbose_name='категория',\n blank=True,\n null=True,\n )\n\n class Meta:\n verbose_name = 'произведение'\n verbose_name_plural = 'произведения'\n indexes = [\n models.Index(fields=['name']),\n models.Index(fields=['year']),\n ]\n\n def __str__(self):\n return self.name\n","sub_path":"api/models/title_model.py","file_name":"title_model.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"631237255","text":"import os\nimport cv2\nimport numpy as np\nfrom keras.applications import inception_v3\nfrom keras.applications.imagenet_utils import decode_predictions\nfrom keras.preprocessing.image import img_to_array\nfrom keras.preprocessing.image import load_img\nimport urllib.request\nimport urllib.parse\nimport re\nimport youtube_dl\nimport collections\nfrom PIL import Image\nimport time as t\n\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\nfrom keras.backend.tensorflow_backend import set_session\nimport tensorflow as tf\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.log_device_placement = True\nsess = tf.Session(config=config)\nset_session(sess)\ninception_model = inception_v3.InceptionV3(weights='imagenet')\nACTIVATION_THRESHOLD = 0.2\nPERCENTAGE = 4\nvideoPath = \"videos/\"\nscreensPath = \"screens/\"\nframeDelay = 200 # 5 fps\n\n\ndef setVideoPath(path):\n \"\"\"\n @param path: The video folder path\n @type path: String\n\n \"\"\"\n global videoPath\n videoPath = path\n\n\ndef setScreensPath(path):\n \"\"\"\n @param path: The screens folder path\n @type path: String\n \"\"\"\n global screensPath\n screensPath = path\n\n\ndef setActivationThreshold(ar):\n \"\"\"\n @param ar: The new activation threshold\n @type ar: Float between 0.1 and 1\n @return: 1 if value is not correct\n \"\"\"\n if 0.01 <= ar <= 1:\n global ACTIVATION_THRESHOLD\n ACTIVATION_THRESHOLD = ar\n else:\n return 1\n\n\ndef setPercentage(pt):\n \"\"\"\n @param pt: The new percentage threshold\n @type pt: Float between 1 and 100\n @return: 1 value is not correct\n \"\"\"\n if 1 <= pt <= 100:\n global PERCENTAGE\n PERCENTAGE = pt\n else:\n return 1\n\n\ndef setDelay(fps):\n \"\"\"\n @param fps: Indicates how many frames per second to extract from the video\n @type fps: Integer between 1 and 1000\n @return: 1 if value is not correct\n \"\"\"\n if 1 <= fps <= 1000:\n global frameDelay\n frameDelay = round(1000 / fps)\n else:\n return 1\n\n\ndef getVideoPath():\n \"\"\"\n @return: String containing the path to the current video folder\n \"\"\"\n return videoPath\n\n\ndef getScreensPath():\n \"\"\"\n @return: String containing the path to the current screens folder\n \"\"\"\n return screensPath\n\n\ndef youtubeQuery(input_query):\n \"\"\"\n Inputs a query on Youtube and returns a list of video URLs\n\n @param input_query: The query to search on YouTube\n @type input_query: String\n @return: List containing the URLs\n \"\"\"\n query_string = urllib.parse.urlencode({\"search_query\": input_query})\n html_content = urllib.request.urlopen(\"http://www.youtube.com/results?\" + query_string)\n search_results = re.findall(r'href=\\\"\\/watch\\?v=(.{11})', html_content.read().decode())\n urls = [\"http://www.youtube.com/watch?v=\" + url for url in search_results]\n aux = {}\n url_list = []\n for u in urls:\n if u not in aux:\n aux[u] = 1\n url_list.append(u)\n # print (url_list)\n return url_list\n\n\ndef downloadVideo(url):\n \"\"\"\n Downloads a video to the videos folder from a Youtube URL.\n\n @param url: The URL of the video to download inside the current video folder\n @type url: String\n\n @note: Tries to download the best resolution lesser or equal than 480p, for optimization purposes\n \"\"\"\n os.makedirs(getVideoPath(), exist_ok=True)\n ydl_opts = {\n 'outtmpl': '%(id)s.%(ext)s',\n 'ignoreerrors': True,\n 'format': 'bestvideo[height<=480]', # max resolution: 480p for faster execution\n }\n ydl = youtube_dl.YoutubeDL(ydl_opts)\n with ydl:\n result = ydl.extract_info(\n url,\n download=False\n )\n # video = result\n current_dir = os.getcwd()\n os.chdir(videoPath)\n ydl.download([url])\n os.chdir(current_dir)\n\n\ndef loadImageFromFile(filepath):\n \"\"\"\n Loads an image and prepares it for the InceptionV3 prediction\n\n @param filepath: String containing the path of the image to load\n @type filepath: String\n @return: Array containing the inceptionV3-ready image\n \"\"\"\n image = load_img(filepath, target_size=(299, 299))\n image_batch = np.expand_dims(img_to_array(image), axis=0)\n image.close()\n processed_image = inception_v3.preprocess_input(image_batch.copy())\n return processed_image\n\n\ndef prepareImage(image, target):\n \"\"\"\n Preprocesses an image to be analysed with InceptionV3\n\n @param image: Image to convert\n @type image: PIL image\n @param target: target=(299, 299) for InceptionV3\n @type target: (Integer, Integer)\n @return: Array containing the inceptionV3-ready image\n @note: This should be used with an image extracted by cv2.read(), otherwise loadImageFromFile()\n should be used instead\n \"\"\"\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = Image.fromarray(image)\n image = image.resize(target)\n image = img_to_array(image)\n image = np.expand_dims(image, axis=0)\n image = inception_v3.preprocess_input(image)\n return image\n\n\ndef extractImages(video_name):\n \"\"\"\n Takes a video and extracts a frame every frameDelay milliseconds, saves them in the screens folder\n\n @param video_name: Name of the video contained in the video path\n @type video_name: String\n @return: Number of frames extracted from the video\n \"\"\"\n os.makedirs(getScreensPath(), exist_ok=True)\n count = 0\n video = cv2.VideoCapture(videoPath + video_name)\n video.set(cv2.CAP_PROP_POS_AVI_RATIO, 1)\n total_len = video.get(cv2.CAP_PROP_POS_MSEC)\n # success, image = video.read()\n success = True\n while success:\n if (count * frameDelay) >= total_len: # end of video, break\n break\n video.set(cv2.CAP_PROP_POS_MSEC, (count * frameDelay))\n success, image = video.read()\n if success:\n cv2.imwrite(getScreensPath() + video_name + f\"{count:06d}.jpg\", image)\n count = count + 1\n return count\n\n\ndef clearScreens():\n \"\"\"\n Deletes every frame extracted in the screens folder\n\n @return: 1 if exception is raised\n \"\"\"\n for file in os.listdir(screensPath):\n file_path = os.path.join(screensPath, file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n # elif os.path.isdir(file_path): shutil.rmtree(file_path)\n except Exception as e:\n print(e)\n return 1\n\n\ndef clearVideos(): # deletes every video in the videos folder\n \"\"\"\n @return: 1 if exception is raised\n \"\"\"\n for file in os.listdir(videoPath):\n file_path = os.path.join(videoPath, file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except Exception as e:\n print(e)\n return 1\n\n\n# counts how many times I've found every item\ndef CountFrequency(my_list):\n \"\"\"\n Counts the frequency of every prediction, creates an ordered dictionary (from most to least frequent)\n of the predictions.\n\n @param my_list: Array of predictions\n @type my_list: String[]\n @return: OrderedDict containing the predictions and their frequencies\n @note: this should follow the predict() method and should take the predictions array as input\n \"\"\"\n freq = {}\n for item in my_list:\n if item in freq:\n freq[item] += 1\n else:\n freq[item] = 1\n sorted_x = sorted(freq.items(), key=lambda kv: kv[1], reverse=True)\n sorted_dict = collections.OrderedDict(sorted_x)\n return sorted_dict\n\n\ndef applyPercentageFilter(dict, nframes):\n \"\"\"\n Returns only the items contained in at least PERCENTAGE % of frames\n\n @param dict: Dictionary containing the predictions to be filtered\n @type dict: OrderedDict\n @param nframes: number of frames collected from the whole video\n @type nframes: Integer\n @return: OrderedDict containing the filtered predictions\n \"\"\"\n newdict = {}\n threshold = nframes * PERCENTAGE / 100\n for name in dict:\n n = dict[name]\n if n >= threshold:\n newdict[name] = n\n sorted_x = sorted(newdict.items(), key=lambda kv: kv[1], reverse=True)\n return collections.OrderedDict(sorted_x)\n\n\ndef applyThresholdFilter(predictions_list):\n \"\"\"\n Filters out the predictions in the input list which have lower confidence than ACTIVATION_THRESHOLD\n\n @param predictions_list: List of predictions\n @type image: List\n @return: Array containing the predictions above ACTIVATION_THRESHOLD\n \"\"\"\n keys = []\n for row in predictions_list:\n for frame in row:\n for prediction in frame:\n # print(prediction)\n if prediction[2] >= ACTIVATION_THRESHOLD:\n keys.append(prediction[1])\n return keys\n\n\ndef predict():\n \"\"\"\n Analyzes every frame in the screens folder, and puts every predictions in the same list (duplicates are expected)\n\n @return: A list of predictions and the number of frames processed\n \"\"\"\n predictions_list = []\n nframes = 0\n\n for file in os.listdir(screensPath):\n filepath = screensPath + file\n\n if filepath.endswith(\".jpg\"):\n processed_image = loadImageFromFile(filepath)\n predictions = inception_model.predict(processed_image)\n label = decode_predictions(predictions)\n predictions_list.append(label)\n\n nframes += 1\n return predictions_list, nframes\n\n\ndef predictSingle(filepath):\n \"\"\"\n Like predict(), but works for a single image\n\n @param filepath: Path of the image to predict\n @type filepath: String\n @return: A list of predictions\n \"\"\"\n processed_image = loadImageFromFile(filepath)\n predictions = inception_model.predict(processed_image)\n label = decode_predictions(predictions)\n return label\n\n\ndef predictFromFolder(path):\n \"\"\"\n Like predict(), but works for a different folder than the standard one\n\n @param path: Path to the folder\n @type path: String\n @return: A list of predictions and the number of frames processed\n \"\"\"\n predictions_list = []\n nframes = 0\n\n for file in os.listdir(path):\n filepath = path + file\n\n if filepath.endswith(\".jpg\"):\n processed_image = loadImageFromFile(filepath)\n predictions = inception_model.predict(processed_image)\n label = decode_predictions(predictions)\n predictions_list.append(label)\n\n nframes += 1\n return predictions_list, nframes\n\n\ndef extractAndPredict(video_name):\n \"\"\"\n Combines extractImages() and predict() to extract frames and predict them immediately,\n instead of saving them in the screens folder in extractImages() and loading them again in predict()\n\n @param video_name: Name of the video to analyze in the video folder\n @type video_name: String\n @return: A list of predictions and the number of frames processed\n @note: this may be slower than using the two functions separately.\n \"\"\"\n count = 0\n predictions_list = []\n video = cv2.VideoCapture(videoPath + video_name)\n video.set(cv2.CAP_PROP_POS_AVI_RATIO, 1)\n total_len = video.get(cv2.CAP_PROP_POS_MSEC)\n success = True\n while success:\n if (count * frameDelay) >= total_len: # end of video, break\n break\n video.set(cv2.CAP_PROP_POS_MSEC, (count * frameDelay))\n success, img = video.read()\n if success:\n image = prepareImage(img, target=(299, 299))\n predictions = inception_model.predict(image)\n label = decode_predictions(predictions)\n predictions_list.append(label)\n count = count + 1\n return predictions_list, count\n\n\ndef downloadAndClassify(yt_query, category, max_vid):\n \"\"\"\n Calls the requested query on youtube, downloads videos until it finds n of them containing the requested category\n\n @param yt_query: The query to submit\n @type yt_query: String\n @param category: The category to search for\n @type category: String\n @param max_vid: The number of videos containing the requested category to look for\n @type max_vid: Integer\n @return: A list of the first n videos containing the requested category\n \"\"\"\n start = t.time()\n\n videosList = youtubeQuery(yt_query)\n finalList = []\n predictionTime = 0\n totalFrames = 0\n os.makedirs(getVideoPath(), exist_ok=True)\n os.makedirs(getScreensPath(), exist_ok=True)\n\n for video in videosList:\n print(video)\n downloadVideo(video)\n print(\"Exploring video folder\")\n for filename in os.listdir(getVideoPath()):\n extractImages(filename)\n\n print(\"Video parsed!\")\n print(\"processing frames...\")\n\n startPredictions = t.time()\n (predictions_list, nframes) = predict()\n endPredictions = t.time()\n predictionTime += endPredictions - startPredictions\n totalFrames += nframes\n\n print(\"Predictions completed!\\n\")\n\n keys = applyThresholdFilter(predictions_list)\n countFreq = CountFrequency(keys)\n filtered = applyPercentageFilter(countFreq, nframes)\n print(filtered)\n if category in filtered:\n print(\"Video accepted!\")\n finalList.append(video)\n clearScreens()\n clearVideos()\n\n # break if we have accepted max_vid videos\n if len(finalList) >= max_vid:\n break\n\n end = t.time()\n print(\"Final list:\")\n for el in finalList:\n print(el)\n print(\"Execution completed in\", (end - start), \" seconds\")\n print(\"Predictions completed in\", predictionTime, \" seconds\")\n print(\"Predictions per second: \", nframes / predictionTime)\n return finalList\n","sub_path":"inceptiontube/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"350137895","text":"#Charlie Quinn\n\ndef get_float(prompt):\n '''Recieves user input, converts input to a float, multiplies it by two, then rounds it to two decimal places'''\n newnum = float(prompt)\n newnum = newnum*2\n newnum = round(newnum,2)\n return newnum\n \n\nnumber = input(\"Enter the price.\")\n\nwhattoprint = get_float(number)\n\nprint(whattoprint)\n\n","sub_path":"CIS_210_CS_I/Lab 3/Lab3-5.py","file_name":"Lab3-5.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"380953890","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\nimport sys\n\nfrom Client import Client\nfrom File_Packager import File_Packager\n\n\ndef extract_arguments():\n\tif len(sys.argv) != 3: # sys.argv=[python_file(UDPclient.py), file_name, server_ip]\n\t\tprint(\"invalid arguments\")\n\t\tsys.exit(0)\n\n\tfile_name = sys.argv[1]\n\tserver_ip = sys.argv[2]\n\treturn file_name, server_ip\n\n\ndef main():\n\tfile_name, server_ip = extract_arguments()\n\tpackager = File_Packager(file_name)\n\tclient = Client(server_ip)\n\n\tmeta_packet, chunks = packager.file_to_chunks()\n\n\tclient.send_all_chunks(meta_packet, chunks)\n\tclient.close_socket()\n\n\nmain()\n","sub_path":"client_main.py","file_name":"client_main.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"482103159","text":"import numpy as np\n\n\ndef tangent_vector(in_coord, ordering=None):\n \"\"\" Tangent vector calculation for 2+ noded elements.\n\n Calculates the tangent vector interpolating every dimension\n separately. It uses a (n_nodes - 1) degree polynomial, and the\n differentiation is analytical.\n\n Args:\n in_coord (np.ndarray): array of coordinates of the nodes. Dimensions = ``[n_nodes, ndim]``\n\n Notes:\n Dimensions are treated independent from each other, interpolating polynomials are computed\n individually.\n\n \"\"\"\n n_nodes, ndim = in_coord.shape\n\n if ordering is None:\n if n_nodes == 2:\n ordering = [0, n_nodes - 1]\n elif n_nodes == 3:\n ordering = [0, 2, 1]\n else:\n raise NotImplementedError('Elements with more than 3 nodes are not supported')\n\n polyfit_vec, polyfit_der_vec, coord = get_polyfit(in_coord, ordering)\n\n # tangent vector calculation\n # \\vec{t} = \\frac{fx'i + fy'j + fz'k}/mod(...)\n tangent = np.zeros_like(coord)\n for inode in range(n_nodes):\n vector = []\n for idim in range(ndim):\n vector.append((polyfit_der_vec[idim])(inode))\n # vector = np.array([polyfit_der_vec[0](inode),\n vector = np.array(vector)\n vector /= np.linalg.norm(vector)\n tangent[inode, :] = vector\n\n # check orientation of tangent vector\n fake_tangent = np.zeros_like(tangent)\n for inode in range(n_nodes):\n if inode == n_nodes - 1:\n # use previous vector\n fake_tangent[inode, :] = fake_tangent[inode - 1, :]\n continue\n fake_tangent[inode, :] = coord[inode+1, :] - coord[inode, :]\n\n inverted_tangent = False\n for inode in range(n_nodes):\n if np.dot(tangent[inode, :], fake_tangent[inode, :]) < 0:\n inverted_tangent = True\n break\n\n if inverted_tangent:\n tangent *= -1\n\n return tangent, polyfit_vec\n\n\ndef get_polyfit(in_coord, ordering):\n coord = in_coord.copy()\n n_nodes, ndim = coord.shape\n for index in range(n_nodes):\n order = ordering[index]\n coord[index, :] = in_coord[order, :]\n\n polynomial_degree = n_nodes - 1\n # first, the polynomial fit.\n # we are going to differentiate wrt the indices ([0, 1, 2] for a 3-node)\n polyfit_vec = [] # we are going to store here the coefficients of the polyfit\n for idim in range(ndim):\n polyfit_vec.append(np.polyfit(range(n_nodes), coord[:, idim],\n polynomial_degree))\n\n # differentiation\n polyfit_der_vec = []\n for idim in range(ndim):\n polyfit_der_vec.append(np.poly1d(np.polyder(polyfit_vec[idim])))\n\n return polyfit_vec, polyfit_der_vec, coord\n\n\ndef unit_vector(vector):\n if np.linalg.norm(vector) < 1e-6:\n return np.array([0.0, 0.0, 0.0])\n return vector/np.linalg.norm(vector)\n\n\ndef rotation_matrix_around_axis(axis, angle):\n axis = unit_vector(axis)\n rot = np.cos(angle)*np.eye(3)\n rot += np.sin(angle)*skew(axis)\n rot += (1 - np.cos(angle))*np.outer(axis, axis)\n return rot\n\n\ndef skew(vector):\n if not vector.size == 3:\n raise Exception('The input vector is not 3D')\n\n matrix = np.zeros((3, 3))\n matrix[1, 2] = -vector[0]\n matrix[2, 0] = -vector[1]\n matrix[0, 1] = -vector[2]\n matrix[2, 1] = vector[0]\n matrix[0, 2] = vector[1]\n matrix[1, 0] = vector[2]\n return matrix\n\n\ndef triad2rot(xb, yb, zb):\n \"\"\"\n If the input triad is the \"b\" coord system given in \"a\" frame,\n (the vectors of the triad are xb, yb, zb)\n this function returns Rab\n :param xb:\n :param yb:\n :param zb:\n :return: rotation matrix Rab\n \"\"\"\n rot = np.row_stack((xb, yb, zb))\n return rot\n\n\ndef rot_matrix_2d(angle):\n return np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n\n\ndef angle_between_vectors(vec_a, vec_b):\n return np.arctan2(np.linalg.norm(np.cross(vec_a, vec_b)), np.dot(vec_a, vec_b))\n\n\ndef angle_between_vector_and_plane(vector, plane_normal):\n angle = np.arcsin((np.linalg.norm(np.dot(vector, plane_normal)))/\n (np.linalg.norm(vector)*np.linalg.norm(plane_normal)))\n return angle\n\n\ndef rot2crv(rot):\n if np.linalg.norm(rot) < 1e-6:\n raise AttributeError('Element Vector V is not orthogonal to reference line (51105)')\n\n quat = mat2quat(rot)\n crv = quat2crv(quat)\n\n if np.linalg.norm(crv) < 1.0e-15:\n crv[0] = rot[1, 2]\n crv[1] = rot[2, 0]\n crv[2] = rot[0, 1]\n\n crv = crv_bounds(crv)\n return crv\n\n\ndef mat2quat(mat):\n matT = mat.T\n\n s = np.zeros((4, 4))\n\n s[0, 0] = 1.0 + np.trace(matT)\n s[0, 1:] = matrix2skewvec(matT)\n\n s[1, 0] = matT[2, 1] - matT[1, 2]\n s[1, 1] = 1.0 + matT[0, 0] - matT[1, 1] - matT[2, 2]\n s[1, 2] = matT[0, 1] + matT[1, 0]\n s[1, 3] = matT[0, 2] + matT[2, 0]\n\n s[2, 0] = matT[0, 2] - matT[2, 0]\n s[2, 1] = matT[1, 0] + matT[0, 1]\n s[2, 2] = 1.0 - matT[0, 0] + matT[1, 1] - matT[2, 2]\n s[2, 3] = matT[1, 2] + matT[2, 1]\n\n s[3, 0] = matT[1, 0] - matT[0, 1]\n s[3, 1] = matT[0, 2] + matT[2, 0]\n s[3, 2] = matT[1, 2] + matT[2, 1]\n s[3, 3] = 1.0 - matT[0, 0] - matT[1, 1] + matT[2, 2]\n\n smax = np.max(np.diag(s))\n ismax = np.argmax(np.diag(s))\n\n # compute quaternion angles\n quat = np.zeros((4,))\n quat[ismax] = 0.5*np.sqrt(smax)\n for i in range(4):\n if i == ismax:\n continue\n quat[i] = 0.25*s[ismax, i]/quat[ismax]\n\n return quat\n\n\ndef matrix2skewvec(matrix):\n vector = np.array([matrix[2, 1] - matrix[1, 2],\n matrix[0, 2] - matrix[2, 0],\n matrix[1, 0] - matrix[0, 1]])\n return vector\n\n\ndef quat2crv(quat):\n crv_norm = 2.0*np.arccos(max(-1.0, min(quat[0], 1.0)))\n\n # normal vector\n if abs(crv_norm) < 1e-15:\n psi = np.zeros((3,))\n else:\n psi = crv_norm*quat[1:4]/np.sin(crv_norm*0.5)\n\n return psi\n\n\ndef crv_bounds(crv_ini):\n crv = crv_ini.copy()\n # original norm\n norm_ini = np.linalg.norm(crv_ini)\n\n # force the norm to be in [-pi, pi]\n norm = norm_ini - 2.0*np.pi*int(norm_ini/(2*np.pi))\n\n if norm == 0.0:\n crv *= 0.0\n else:\n if norm > np.pi:\n norm -= 2.0*np.pi\n elif norm < -np.pi:\n norm += 2.0*np.pi\n crv *= (norm/norm_ini)\n\n return crv\n\n\ndef triad2crv(xb, yb, zb):\n return rot2crv(triad2rot(xb, yb, zb))\n\n\ndef crv2triad(psi):\n rot_matrix = crv2rot(psi)\n return rot_matrix[:, 0], rot_matrix[:, 1], rot_matrix[:, 2]\n\n\ndef crv2rot(psi):\n norm_psi = np.linalg.norm(psi)\n\n if norm_psi < 1e-15:\n skew_psi = rot_skew(psi)\n rot_matrix = np.eye(3) + skew_psi + 0.5*np.dot(skew_psi, skew_psi)\n else:\n normal = psi/norm_psi\n skew_normal = rot_skew(normal)\n\n rot_matrix = np.eye(3)\n rot_matrix += np.sin(norm_psi)*skew_normal\n rot_matrix += (1.0 - np.cos(norm_psi))*np.dot(skew_normal, skew_normal)\n\n return rot_matrix\n\n\ndef triad2crv_vec(v1, v2, v3):\n n_nodes, _ = v1.shape\n crv_vec = np.zeros((n_nodes, 3))\n for inode in range(n_nodes):\n crv_vec[inode, :] = triad2crv(v1[inode, :], v2[inode, :], v3[inode, :])\n\n return crv_vec\n\n\ndef crv2triad_vec(crv_vec):\n n_nodes, _ = crv_vec.shape\n v1 = np.zeros((n_nodes, 3))\n v2 = np.zeros((n_nodes, 3))\n v3 = np.zeros((n_nodes, 3))\n for inode in range(n_nodes):\n v1[inode, :], v2[inode, :], v3[inode, :] = crv2triad(crv_vec[inode, :])\n\n return v1, v2, v3\n\n\ndef quat2rot(q1):\n \"\"\"@brief Calculate rotation matrix based on quaternions.\n See Aircraft Control and Simulation, pag. 31, by Stevens, Lewis.\n Copied from S. Maraniello's SHARPy\n\n Remark: if A is a FoR obtained rotating a FoR G of angle fi about an axis n (remind n will be\n invariant during the rotation), and q is the related quaternion q(fi,n), the function will\n return the matrix Cag such that:\n - Cag rotates A to G\n - Cag transforms the coordinates of a vector defined in G component to A components.\n \"\"\"\n\n q = q1.copy(order='F')\n q /= np.linalg.norm(q)\n\n rot_mat = np.zeros((3, 3), order='F')\n\n rot_mat[0,0] = q[0]**2 + q[1]**2 - q[2]**2 - q[3]**2\n rot_mat[1,1] = q[0]**2 - q[1]**2 + q[2]**2 - q[3]**2\n rot_mat[2,2] = q[0]**2 - q[1]**2 - q[2]**2 + q[3]**2\n\n rot_mat[0,1] = 2.*(q[1]*q[2] + q[0]*q[3])\n rot_mat[1,0] = 2.*(q[1]*q[2] - q[0]*q[3])\n\n rot_mat[0,2] = 2.*(q[1]*q[3] - q[0]*q[2])\n rot_mat[2,0] = 2.*(q[1]*q[3] + q[0]*q[2])\n\n rot_mat[1,2] = 2.*(q[2]*q[3] + q[0]*q[1])\n rot_mat[2,1] = 2.*(q[2]*q[3] - q[0]*q[1])\n\n return rot_mat\n\n\ndef rot_skew(vec):\n matrix = np.zeros((3, 3))\n matrix[0, 1] = -vec[2]\n matrix[0, 2] = vec[1]\n matrix[1, 0] = vec[2]\n matrix[1, 2] = -vec[0]\n matrix[2, 0] = -vec[1]\n matrix[2, 1] = vec[0]\n return matrix\n\n\ndef rotation3d_x(angle):\n c = np.cos(angle)\n s = np.sin(angle)\n mat = np.zeros((3, 3))\n mat[0, :] = [1.0, 0.0, 0.0]\n mat[1, :] = [0.0, c, -s]\n mat[2, :] = [0.0, s, c]\n return mat\n\n\ndef rotation3d_z(angle):\n c = np.cos(angle)\n s = np.sin(angle)\n mat = np.zeros((3, 3))\n mat[0, :] = [ c, -s, 0.0]\n mat[1, :] = [ s, c, 0.0]\n mat[2, :] = [0.0, 0.0, 1.0]\n return mat\n\nif __name__ == '__main__':\n t = np.array([0, 1, 0])\n n = np.array([1, 0, 0])\n b = np.array([0, 0, -1])\n\n psi = triad2crv(t, n, b)\n\n tt, nn, bb = crv2triad(psi)\n\n print(t)\n print(tt)\n print(n)\n print(nn)\n print(b)\n print(bb)\n","sub_path":"sharpy/utils/algebra.py","file_name":"algebra.py","file_ext":"py","file_size_in_byte":9565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"421921947","text":"from __future__ import absolute_import\nfrom __future__ import division\n\nimport numpy as np\nfrom pyrevolve.SDF.math import Vector3, Quaternion\nimport math\n\nfrom pyrevolve.angle import RobotManager as RvRobotManager\nfrom pyrevolve.util import Time\n\nfrom pyrevolve.tol.manage import measures as ms\nfrom pyrevolve.evolution import fitness\n\n\nclass RobotManager(RvRobotManager):\n \"\"\"\n Class to manage a single robot\n \"\"\"\n\n def __init__(\n self,\n conf,\n robot,\n position,\n time,\n battery_level=0.0,\n position_log_size=None,\n warmup_time=0.0,\n ):\n \"\"\"\n :param conf:\n :param robot: RevolveBot\n :param position:\n :type position: Vector3\n :param time:\n :type time: Time\n :param battery_level: Battery charge for this robot\n :type battery_level: float\n :return:\n \"\"\"\n time = conf.evaluation_time if time is None else time\n speed_window = int(float(time) * conf.pose_update_frequency) + 1 if position_log_size is None \\\n else position_log_size\n super(RobotManager, self).__init__(\n robot=robot,\n position=position,\n time=time,\n battery_level=battery_level,\n speed_window=speed_window,\n warmup_time=warmup_time,\n )\n\n # Set of robots this bot has mated with\n self.mated_with = {}\n self.last_mate = None\n self.conf = conf\n self.size = robot.size()\n self.battery_level = battery_level\n self.initial_charge = battery_level\n\n def update_from_celery(self, msg, world):\n \"\"\"Celery messages are json and not robot manager. This function is called by\n the celery converter function msg_to_robotmanager() inside the converter.py.\n :param msg: a celery result message\"\"\"\n\n self.dead = True # if we are here robot is already done.\n\n if self.starting_time is None:\n self.starting_time = msg[\"times\"][0]\n self.last_update = msg[\"times\"][0]\n self.last_position = Vector3(msg[\"x\"][0],msg[\"y\"][0],msg[\"z\"][0])\n\n # update states\n for i in range(len(msg[\"x\"])):\n position = Vector3(msg[\"x\"][i],msg[\"y\"][i],msg[\"z\"][i])\n euler = np.array([msg[\"roll\"][i],msg[\"pitch\"][i], msg[\"yaw\"][i]])\n\n # Please note that age is currently corrupted. Because the robot might not have been\n # simulated in the world created by this thread! TO DO: Change age, get it somehow or delete it.\n age = world.age()\n\n last = self.last_position\n ds = ds = np.sqrt((position.x - last.x)**2 + (position.y - last.y)**2)\n dt = float(msg[\"times\"][i] - self.last_update)\n\n self._dist += ds\n self._time += dt\n\n if len(self._dt) >= self.speed_window:\n # Subtract oldest values if we're about to override it\n self._dist -= self._ds[-1]\n self._time -= self._dt[-1]\n\n self.last_position = position\n self.last_update = msg[\"times\"][i]\n\n self._positions.append(position)\n self._times.append(msg[\"times\"][i])\n self._ds.append(ds)\n self._dt.append(dt)\n self._orientations.append(euler)\n self._seconds.append(age.sec)\n\n # update contacts\n self._contacts = msg[\"contacts\"]\n\n def will_mate_with(self, other):\n \"\"\"\n Decides whether or not to mate with the other given robot based on\n its position and speed.\n :param other:\n :type other: RobotManager\n :return:\n \"\"\"\n if self.age() < self.warmup_time:\n # Don't mate within the warmup time\n return False\n\n mate_count = self.mated_with.get(other.name, 0)\n if mate_count > self.conf.max_pair_children:\n # Maximum number of children with this other parent\n # has been reached\n return False\n\n if self.last_mate is not None and \\\n float(self.last_update - self.last_mate) < \\\n self.conf.gestation_period:\n # Don't mate within the cooldown window\n return False\n\n if self.distance_to(other.last_position) > \\\n self.conf.mating_distance_threshold:\n return False\n\n my_fitness = self.old_revolve_fitness()\n other_fitness = other.old_revolve_fitness()\n\n # Only mate with robots with nonzero fitness, check for self\n # zero-fitness to prevent division by zero.\n return other_fitness > 0 and (\n my_fitness == 0 or\n (other_fitness / my_fitness) >= self.conf.mating_fitness_threshold\n )\n\n @staticmethod\n def header():\n \"\"\"\n :return:\n \"\"\"\n return [\n 'run', 'id', 't_birth',\n 'parent1', 'parent2', 'nparts',\n 'x', 'y', 'z',\n 'extremity_count', 'joint_count', 'motor_count',\n 'inputs', 'outputs', 'hidden', 'conn'\n ]\n\n # def write_robot(self, world, details_file, csv_writer):\n # \"\"\"\n # :param world:\n # :param details_file:\n # :param csv_writer:\n # :return:\n # \"\"\"\n # with open(details_file, 'w') as f:\n # f.write(self.robot.SerializeToString())\n #\n # row = [getattr(world, 'current_run', 0), self.robot.id,\n # world.age()]\n # row += list(self.parent_ids) if self.parent_ids else ['', '']\n # row += [self.size, self.last_position.x,\n # self.last_position.y, self.last_position.z]\n #\n # root = self.tree.root\n # inputs, outputs, hidden = root.io_count(recursive=True)\n # row += [\n # count_extremities(root),\n # count_joints(root),\n # count_motors(root),\n # inputs,\n # outputs,\n # hidden,\n # count_connections(root)\n # ]\n #\n # csv_writer.writerow(row)\n\n def old_revolve_fitness(self):\n return fitness.online_old_revolve(self)\n\n def is_evaluated(self):\n \"\"\"\n Returns true if this robot is at least one full evaluation time old.\n :return:\n \"\"\"\n return self.age() >= (self.warmup_time + self.conf.evaluation_time)\n\n def charge(self):\n \"\"\"\n Returns the remaining battery charge of this robot.\n :return:\n \"\"\"\n return self.initial_charge - (float(self.age()) * self.size)\n\n def inverse_charge(self):\n \"\"\"\n Returns the remaining battery charge of this robot.\n :return:\n \"\"\"\n return self.initial_charge - (float(self.age()) / self.size)\n\n def did_mate_with(self, other):\n \"\"\"\n Called when this robot mated with another robot successfully.\n :param other:\n :type other: RobotManager\n :return:\n \"\"\"\n self.last_mate = self.last_update\n\n if other.name in self.mated_with:\n self.mated_with[other.name] += 1\n else:\n self.mated_with[other.name] = 1\n","sub_path":"pyrevolve/tol/manage/robotmanager.py","file_name":"robotmanager.py","file_ext":"py","file_size_in_byte":7218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"546096384","text":"import logging\nimport os\nimport fileprocess\nfrom baseaction import BaseAction\nfrom sqlalchemy import and_, engine_from_config\nfrom pylons import config as pconfig\nfrom mock import Mock\nfrom fileprocess.configuration import config\nfrom fileprocess.processingthread import na\nfrom sqlalchemy.exceptions import OperationalError\n\nlog = logging.getLogger(__name__)\n\nclass DBChecker(BaseAction):\n \"\"\"\n This class checks to see if the user is established, whether or not this\n file has been uploaded by this user, and whether or not this file\n has been uploaded by any user. Pretty much just tries to see whether\n we need to continue with the less pleasant pieces of processing this file\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(DBChecker, self).__init__(*args, **kwargs)\n pconfig['pylons.g'] = Mock()\n pconfig['pylons.g'].sa_engine = engine_from_config(config,\n prefix = 'sqlalchemy.default.'\n )\n from masterapp import model\n self.model = model\n\n def process(self, file):\n assert file and len(file)>0 and \\\n file.has_key('fbid')\n self.model.Session()\n\n try:\n # Get this user, create him if he doesn't exist\n qry = self.model.Session.query(self.model.User).filter(\n self.model.User.fbid == file['fbid']\n )\n user = qry.first()\n if user == None:\n user = self.model.User(file['fbid'])\n self.model.Session.save(user)\n self.model.Session.commit()\n\n file['dbuserid'] = user.id\n\n return self._check(file, user)\n except OperationalError:\n self.model.Session.rollback()\n log.warn(\"Database error occurred, bailing on %s\", file)\n raise\n finally:\n self.model.Session.clear()\n self.model.Session.close()\n\n def _success(self, file):\n self.model.Session.commit()\n self.cleanup(file)\n return False\n\n def _check(self, file, user):\n song = None\n if file.has_key('title') and file.has_key('album') and \\\n file.has_key('artist'):\n qry = self.model.Session.query(self.model.Song).join(\n self.model.Song.artist, self.model.Song.album).filter(\n self.model.Artist.name == file['artist']).filter(\n self.model.Album.title == file['album']).filter(\n self.model.Song.title == file['title'])\n song = qry.first()\n\n if not song:\n return file\n\n # Check to see if this user owns this songs\n owner = self.model.Session.query(self.model.SongOwner).filter(\n and_(self.model.SongOwner.songid==song.id, \n self.model.SongOwner.uid == user.id)\n ).first()\n if owner:\n # This file has already been uploaded by this fella\n log.debug('%s has already been uploaded by %s', \n file.get('fname'), file['fbid'])\n file['msg'] = \"File has already been uploaded by user\"\n file['na'] = na.NOTHING\n self.cleanup(file)\n return False\n\n # Make a new PUID if this puid !exist\n if file.get('puid'):\n puid = self.model.Session.query(self.model.Puid).\\\n filter(self.model.Puid.puid == file['puid']).first()\n if not puid:\n puid = self.model.Puid()\n puid.song = song\n puid.puid = file['puid']\n self.model.Session.add(puid)\n\n # Make a new owner\n owner = user.add_song(song)\n\n # Check the quality of this song if an actual file was uploaded\n if file.has_key('sha'):\n dbfile = self.model.Session.query(self.model.File).filter_by(\n sha = file['sha']).first()\n if dbfile:\n # This file has been uploaded, we've created a user, we\n # happy\n return self._success(file)\n else:\n # Create a new file associated with the song we found or created\n dbfile = self.model.File(\n sha = file['sha'],\n bitrate = file.get('bitrate'),\n size = file.get('size'),\n song = song\n )\n log.debug(\"New file %s added to files\", file['sha'])\n\n if dbfile.bitrate > song.bitrate and \\\n dbfile.bitrate < config['maxkbps']:\n # Found a higher quality song\n song.sha = file.get('sha')\n song.bitrate = file.get('bitrate')\n song.size = file.get('size')\n \n # Mark the owner of this fine file\n fowner = self.model.Owner(file=dbfile, user=user)\n self.model.Session.add_all([dbfile, fowner])\n\n return self._success(file)\n \n","sub_path":"fileprocess/fileprocess/actions/dbchecker.py","file_name":"dbchecker.py","file_ext":"py","file_size_in_byte":4993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"70127812","text":"import collections\nimport functools\nfrom random import randint\n\nclass lru_cache_obj(object):\n\n _instance = None\n cache_dict = collections.OrderedDict()\n\n def __new__(cls, size):\n if cls._instance is None:\n # print('Creating new cache')\n cls._instance = super(lru_cache_obj, cls).__new__(cls)\n cls._instance.set_size(size)\n return cls._instance\n\n def __init__(self, size):\n self.set_size(size)\n\n def set_size(self, cache_entries):\n if cache_entries > 0:\n self.cache_size = cache_entries\n\n def set(self, k, v):\n try:\n self.cache_dict.pop(k)\n except KeyError:\n if len(self.cache_dict) >= self.cache_size:\n self.cache_dict.popitem(last=False)\n self.cache_dict[k] = v\n # print(self.cache_dict[k])\n\n def get(self, k):\n try:\n value = self.cache_dict[k]\n self.cache_dict.pop(k)\n self.cache_dict[k] = value\n # print(\"dict values... of size {}\".format(self.cache_size))\n # for key in self.cache_dict:\n # print(\"dict {}\".format(key)) \n return value\n except KeyError:\n return -1\n\n def delete(self, k):\n try:\n self.cache_dict.pop(k)\n return k\n except KeyError:\n return -1\n\ndef lru_cache(cache_size):\n def lru_cache_decorator(func):\n @functools.wraps(func)\n def wrapper_lru_cache(*args, **kwargs):\n cache_obj = lru_cache_obj(cache_size)\n # cache_obj.set_size(cache_size)\n # print(\"********\"+func.__name__+\"********\")\n if func.__name__ == \"serialize_PUT\":\n key, value = func(*args, **kwargs)\n cache_obj.set(key, value)\n return key, value\n elif func.__name__ == \"serialize_DELETE\":\n key = args\n value = cache_obj.delete(*args)\n if (value == -1):\n key, value = func(*args, **kwargs)\n return key, value\n elif func.__name__ == \"serialize_GET\":\n key = args\n value = cache_obj.get(*args)\n if (value == -1):\n key, value = func(*args, **kwargs)\n cache_obj.set(key, value)\n return key, value\n else:\n value = cache_obj.get(*args)\n if (value == -1):\n value = func(*args, **kwargs)\n cache_obj.set(*args, value)\n return value\n return wrapper_lru_cache\n return lru_cache_decorator\n\ndef lru_cache_test():\n c = lru_cache(5)\n\n for i in range(9,0,-1):\n c.set(i,\"str\")\n\n for i in range(50):\n r = randint(0,49)\n print(\"{} {}\".format(r,c.get(r)))\n\n# lru_cache_test()\n\n\n\n\n\n\n","sub_path":"lru_cache.py","file_name":"lru_cache.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"98020812","text":"from mininet.net import Mininet\nfrom mininet.node import OVSController\nfrom mininet.cli import CLI\nfrom mininet.log import setLogLevel, info\nfrom mininet.link import TCLink\nimport sys\n\nN=int(sys.argv[1])\nM=int(sys.argv[2])\n\ndef emptyNet():\n\n net = Mininet( controller=OVSController , link=TCLink)\n\n net.addController( 'c0' )\n\n\n even=1\n odd=1\n hosts=[]\n switches=[]\n evenip='11.0.0.'\n oddip='11.0.1.'\n\n for x in range(0,M*N):\n if x%2==0:\n hosts.append(net.addHost('h'+str(x+1), ip=evenip+str(even)+'/24'))\n even+=1\n else:\n hosts.append(net.addHost('h'+str(x+1), ip=oddip+str(odd)+'/24'))\n odd+=1\n\n\n for x in range(0,N):\n switches.append(net.addSwitch('s'+str(x+1)))\n\n\n bwidth=0\n for x in range(0,N):\n for y in range(0,M):\n net.addLink( hosts[M*x+y], switches[x] , bw=bwidth+1)\n bwidth=(bwidth+1)%2\n\n for x in range(0,N-1):\n net.addLink(switches[x],switches[x+1],bw=2)\n\n net.start()\n\n CLI( net )\n\n net.stop()\n\nif __name__ == '__main__':\n setLogLevel( 'info' )\n emptyNet()\n\n","sub_path":"Assignment2/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"527337356","text":"import tqdm\nimport numpy as np\nimport tensorflow as tf\n\nimport utils\nimport data_loader\nfrom model import NLR_model\nfrom hyper_params import HyperParams\n\n\ndef test():\n hparams = HyperParams()\n\n parser = hparams.parser\n hp = parser.parse_args()\n\n test_users, test_hist_items, test_scores, test_labels = data_loader.load_test_datas(\n hp.test_datas, hp.is_with_feedback)\n\n user_2_id, item_2_id, train_hypers = utils.load_training_info(hp.checkpoint_dir)\n id_2_item = {id: item for item, id in item_2_id.items()}\n\n model = NLR_model(user_embedding_dim=train_hypers.get('user_embedding_dim'),\n item_embedding_dim=train_hypers.get('item_embedding_dim'),\n hidden1_dim=train_hypers.get('hidden1_dim'),\n hidden2_dim=train_hypers.get('hidden2_dim'),\n num_users=train_hypers.get('num_users'),\n num_items=train_hypers.get('num_items'),\n interact_type=train_hypers.get('interact_type'))\n\n saver = tf.train.Saver()\n with tf.Session() as sess:\n # restore\n saver.restore(sess, hp.ckpt)\n\n items_embedding_matrix = sess.run(model.item_embedding_layer)\n items_embedding_matrix = items_embedding_matrix[:, np.newaxis, :]\n\n topk = 3\n num_right_samples = 0\n for user, hist, feedback, label in tqdm.tqdm(zip(test_users, test_hist_items, test_scores,\n test_labels)):\n user_data, items_data, feedback_data = data_loader.test_batch(user, hist, feedback,\n user_2_id, item_2_id)\n\n prob_pos = sess.run(model.probability_pos,\n feed_dict={model.input_user: user_data,\n model.input_items: items_data,\n model.input_feedback_score: feedback_data,\n model.target_emb_vec: items_embedding_matrix})\n\n prob_pos = np.squeeze(prob_pos, axis=1)\n pred_item_ids = np.argsort(prob_pos, axis=0)[:topk:-1]\n sorted_prob = np.sort(prob_pos, axis=0)[:topk:-1]\n pred_items = [id_2_item.get(int(id), '') for id in pred_item_ids]\n if label in pred_items:\n num_right_samples += 1\n\n print('top{} accuracy: {}'.format(topk, num_right_samples / len(test_labels)))\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"41047267","text":"################################################################################\n# CSE 253: Programming Assignment 1\n# Code snippet by Michael\n# Winter 2020\n################################################################################\n# We've provided you with the dataset in PA1.zip\n################################################################################\n# To install PIL, refer to the instructions for your system:\n# https://pillow.readthedocs.io/en/5.2.x/installation.html\n################################################################################\n# If you don't have NumPy installed, please use the instructions here:\n# https://scipy.org/install.html\n################################################################################\n\nfrom os import listdir\nimport os, random, copy\nfrom PIL import Image\nimport numpy as np\nfrom collections import defaultdict\n\n\n''' \nlist of face expressions (contempt, neutral are excluded) are:\n1. anger\n2. disgust\n3. fear\n4. happiness\n5. sadness\n6. surprise\n'''\n\ndef load_data(data_dir=\"./aligned/\"):\n\t\"\"\" Load all PNG images stored in your data directory into a list of NumPy\n\tarrays.\n\n\tArgs:\n\t\tdata_dir: The relative directory path to the CK+ image directory.\n\tReturns:\n\t\timages: A dictionary with keys as emotions and a list containing images associated with each key.\n\t\tcnt: A dictionary that stores the # of images in each emotion\n\t\"\"\"\n\timages = defaultdict(list)\n\n\t# Get the list of emotional directory:\n\tfor e in listdir(data_dir):\n\t\t# excluding any non-directory files\n\t\tif not os.path.isdir(os.path.join(data_dir, e)):\n\t\t\tcontinue\n\t\t# Get the list of image file names\n\t\tall_files = listdir(os.path.join(data_dir, e))\n\n\t\tfor file in all_files:\n\t\t\t# Load only image files as PIL images and convert to NumPy arrays\n\t\t\tif '.png' in file:\n\t\t\t\timg = Image.open(os.path.join(data_dir, e, file))\n\t\t\t\timages[e].append(np.array(img))\n\n\tprint(\"Emotions: {} \\n\".format(list(images.keys())))\n\n\tcnt = defaultdict(int)\n\tfor e in images.keys():\n\t\tprint(\"{}: {} # of images\".format(e, len(images[e])))\n\t\tcnt[e] = len(images[e])\n\treturn images, cnt\n\ndef balanced_sampler(dataset, cnt, emotions):\n\t# this ensures everyone has the same balanced subset for model training, don't change this seed value\n\trandom.seed(20)\n\tprint(\"\\nBalanced Set:\")\n\tmin_cnt = min([cnt[e] for e in emotions])\n\tbalanced_subset = defaultdict(list)\n\tfor e in emotions:\n\t\tbalanced_subset[e] = copy.deepcopy(dataset[e])\n\t\trandom.shuffle(balanced_subset[e])\n\t\tbalanced_subset[e] = balanced_subset[e][:min_cnt]\n\t\tprint('{}: {} # of images'.format(e, len(balanced_subset[e])))\n\treturn balanced_subset\n\ndef display_face(img):\n\t\"\"\" Display the input image and optionally save as a PNG.\n\n\tArgs:\n\t\timg: The NumPy array or image to display\n\n\tReturns: None\n\t\"\"\"\n\tprint(img)\n\t# Convert img to PIL Image object (if it's an ndarray)\n\tif type(img) == np.ndarray:\n\t\tprint(\"Converting from array to PIL Image\")\n\t\timg = Image.fromarray(img)\n\t\n\t# Display the image\n\timg.show(vmin=0, vmax=1)\n\n\n# example on how to use it\nif __name__ == '__main__':\n\t# The relative path to your image directory\n\tdata_dir = \"./aligned/\"\n\tdataset, cnt = load_data(data_dir)\n\t# test with happiness and anger\n\timages = balanced_sampler(dataset, cnt, emotions=['happiness', 'anger'])\n\tdisplay_index = 0\n\tdisplay_face(images['anger'][display_index])","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":3324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"147768443","text":"\n\nfrom xai.brain.wordbase.nouns._scabbard import _SCABBARD\n\n#calss header\nclass _SCABBARDS(_SCABBARD, ):\n\tdef __init__(self,): \n\t\t_SCABBARD.__init__(self)\n\t\tself.name = \"SCABBARDS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"scabbard\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_scabbards.py","file_name":"_scabbards.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"350404545","text":"def vec_scale_vec(vec: list):\n import numpy\n _vec = []\n for i in vec:\n _vec.append(_scale2zero_one(i))\n return numpy.array(_vec)\n\n\ndef matrix_scale_matrix(matrix):\n import numpy\n _matrix = numpy.array([vec_scale_vec(matrix[0])])\n\n for vec in matrix[1:]:\n _matrix = numpy.append(_matrix, [vec_scale_vec(vec)], axis=0)\n return _matrix\n\n\ndef _sin_scale(x: float) -> float:\n from math import sin\n return (sin(x) + 1) / 2\n\n\ndef _scale2zero_one(x):\n res = 0\n if x < -1:\n res = -2 + 1 / abs(x)\n if -1 <= x <= 1:\n res = x\n if 1 < x:\n res = 2 - 1 / x\n return (res + 2) / 4\n","sub_path":"nvd/normalizer.py","file_name":"normalizer.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"299048833","text":"# Copyright Swiss Data Science Center (SDSC). A partnership between\n# École Polytechnique Fédérale de Lausanne (EPFL) and\n# Eidgenössische Technische Hochschule Zürich (ETHZ).\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\"\"\"Curses utilities.\"\"\"\nimport curses\nimport curses.panel\nfrom typing import Dict, List, Optional, Tuple\n\nfrom renku.command.view_model.text_canvas import Point\nfrom renku.core import errors\nfrom renku.core.util import communication\nfrom renku.domain_model.provenance.activity import Activity\n\n\nclass CursesActivityGraphViewer:\n \"\"\"An interactive viewer for activity graphs.\"\"\"\n\n COLOR_MAPPING = {\n \"[31\": curses.COLOR_RED,\n \"[32\": curses.COLOR_GREEN,\n \"[33\": curses.COLOR_YELLOW,\n \"[34\": curses.COLOR_BLUE,\n \"[35\": curses.COLOR_MAGENTA,\n \"[36\": curses.COLOR_CYAN,\n \"[37\": curses.COLOR_WHITE,\n \"[0\": -1,\n }\n\n ACTIVITY_OVERLAY_WIDTH = 60\n ACTIVITY_OVERLAY_HEIGHT = 35\n HELP_OVERLAY_WIDTH = 60\n HELP_OVERLAY_HEIGHT = 6\n DATE_FORMAT = \"%Y-%m-%d %H:%M:S\"\n\n def __init__(\n self,\n text_data: str,\n navigation_data: List[List[Tuple[Point, Point, Activity]]],\n vertical_space: int,\n use_color: bool,\n ):\n self.text_data = text_data\n self.navigation_data = navigation_data\n self.vertical_space = vertical_space\n\n self.current_layer = 0\n self.layer_position = 0\n self.max_layer = len(navigation_data) - 1\n self.y_pos: int = 0\n self.x_pos: int = 0\n self.color_cache: Dict[str, int] = {}\n self.activity_overlay: Optional[curses._CursesWindow] = None\n self.help_overlay: Optional[curses._CursesWindow] = None\n self._select_activity()\n self.use_color = use_color\n self.free_move: bool = False\n\n def _init_curses(self, screen):\n \"\"\"Initialize curses screen for interactive mode.\"\"\"\n screen.keypad(True)\n curses.use_default_colors()\n curses.start_color()\n curses.curs_set(0)\n curses.noecho()\n screen.refresh()\n self._init_console_colors()\n self.rows, self.cols = screen.getmaxyx()\n\n min_width = max(self.ACTIVITY_OVERLAY_WIDTH, self.HELP_OVERLAY_WIDTH) + 1\n min_height = max(self.ACTIVITY_OVERLAY_HEIGHT, self.HELP_OVERLAY_HEIGHT) + 1\n if self.cols < min_width or self.rows < min_height:\n raise errors.TerminalSizeError(\n f\"Terminal is too small for interactive mode, size should be at least {min_width}x{min_height}.\"\n )\n\n text_data_lines = self.text_data.splitlines()\n\n self.content_max_x = max(len(line) for line in text_data_lines)\n self.content_max_y = len(text_data_lines)\n\n int16_max = 32767\n if self.content_max_y > int16_max or self.content_max_x > int16_max:\n communication.warn(\n f\"Graph is too large for interactive visualization, cropping to {int16_max} lines/columns.\"\n )\n self.content_max_x = min(self.content_max_x, int16_max)\n self.content_max_y = min(self.content_max_y, int16_max)\n text_data_lines = [line[: self.content_max_x] for line in text_data_lines[self.content_max_y]]\n\n self.content_pad = curses.newpad(self.content_max_y, self.content_max_x)\n for i, l in enumerate(text_data_lines):\n self._addstr_with_color_codes(self.content_pad, i, 0, l)\n\n self._blink_text(self.content_pad, self.activity_start, self.activity_end, bold=True)\n\n self._update_help_overlay(screen)\n\n self._refresh(screen)\n\n def _init_console_colors(self):\n \"\"\"Setup curses color mapping.\"\"\"\n if not self.use_color:\n curses.init_pair(100, -1, -1)\n for color_symbol, _ in self.COLOR_MAPPING.items():\n self.color_cache[color_symbol] = 100\n else:\n for i, (color_symbol, color) in enumerate(self.COLOR_MAPPING.items(), start=100):\n curses.init_pair(i, color, -1)\n self.color_cache[color_symbol] = i\n\n def _select_activity(self):\n \"\"\"Set the currently selected activity.\"\"\"\n start, end, self.selected_activity = self.navigation_data[self.current_layer][self.layer_position]\n\n # Ignore borders, we only care about text\n self.activity_start = Point(start.x + 1, start.y + 1)\n self.activity_end = Point(end.x - 1, end.y - 1)\n\n def _addstr_with_color_codes(self, window, y: int, x: int, text: str):\n \"\"\"Replace ANSI color codes with curses colors.\"\"\"\n if not curses.has_colors():\n window.addstr(y, x, text)\n return\n\n split_text = text.split(\"\\033\")\n\n # add first part without color\n window.addstr(y, x, split_text[0], curses.color_pair(self.color_cache[\"[0\"]))\n\n x += len(split_text[0])\n\n for substring in split_text[1:]:\n color, snippet = substring.split(\"m\", 1)\n\n if len(snippet) == 0:\n continue\n\n if color == \"[1\":\n curses_color = curses.A_BOLD\n else:\n curses_color = curses.color_pair(self.color_cache[color])\n\n window.addstr(y, x, snippet, curses_color)\n\n x += len(snippet)\n\n def _blink_text(self, window, start: Point, end: Point, bold: bool = True):\n \"\"\"Change text between start and end to blinking.\"\"\"\n style = curses.A_BLINK\n\n if bold:\n style |= curses.A_BOLD\n\n for y in range(start.y, end.y + 1):\n text = window.instr(y, start.x, end.x - start.x + 1)\n window.addstr(y, start.x, text, style)\n\n def _unblink_text(self, window, start: Point, end: Point, bold: bool = True):\n \"\"\"Change text between start and end to not-blinking.\"\"\"\n\n for y in range(start.y, end.y + 1):\n text = window.instr(y, start.x, end.x - start.x + 1)\n if bold:\n window.addstr(y, start.x, text, curses.A_BOLD)\n else:\n window.addstr(y, start.x, text)\n\n def _add_multiline_text_with_wrapping(self, window, text: str):\n \"\"\"Add a multiline text to a window, wrapping text to fit.\"\"\"\n height, width = window.getmaxyx()\n\n # don't write to window borders\n width -= 2\n i = 1\n\n for line in text.splitlines():\n chunks = [line[p : p + width] for p in range(0, len(line), width)]\n if not chunks:\n # Lines containing only \\n\n i += 1\n continue\n\n for chunk in chunks:\n if i >= height:\n # TODO: Add scrolling using a pad?\n return\n window.addstr(i, 1, chunk)\n i += 1\n\n def _refresh(self, screen):\n \"\"\"Refresh curses screens/pads/windows/panels.\"\"\"\n self.content_pad.refresh(self.y_pos, self.x_pos, 0, 0, self.rows - 1, self.cols - 1)\n\n if self.activity_overlay:\n self.activity_overlay.overlay(screen)\n self.activity_overlay.refresh()\n\n if self.help_overlay:\n self.help_overlay.overlay(screen)\n self.help_overlay.refresh()\n\n if self.activity_overlay or self.help_overlay:\n curses.panel.update_panels()\n\n def _change_layer(self, step: int):\n \"\"\"Change the currently active layer.\"\"\"\n self.current_layer = max(min(self.current_layer + step, self.max_layer), 0)\n self.layer_position = max(min(self.layer_position, len(self.navigation_data[self.current_layer]) - 1), 0)\n del self.activity_overlay\n self.activity_overlay = None\n\n def _change_layer_position(self, step: int):\n \"\"\"Change position inside current layer.\"\"\"\n self.layer_position = max(min(self.layer_position + step, len(self.navigation_data[self.current_layer]) - 1), 0)\n del self.activity_overlay\n self.activity_overlay = None\n\n def _update_activity_overlay(self, screen):\n \"\"\"Show/Hide the activity overlay.\"\"\"\n if not self.activity_overlay:\n del self.help_overlay\n self.help_overlay = None\n\n self.activity_overlay = curses.newwin(\n self.ACTIVITY_OVERLAY_HEIGHT,\n self.ACTIVITY_OVERLAY_WIDTH,\n self.rows - self.ACTIVITY_OVERLAY_HEIGHT,\n self.cols - self.ACTIVITY_OVERLAY_WIDTH,\n )\n curses.panel.new_panel(self.activity_overlay)\n self.activity_overlay.border()\n\n started_date = self.selected_activity.started_at_time.strftime(self.DATE_FORMAT)\n ended_date = self.selected_activity.ended_at_time.strftime(self.DATE_FORMAT)\n usages = \"\\n\".join(u.entity.path for u in self.selected_activity.usages)\n generations = \"\\n\".join(g.entity.path for g in self.selected_activity.generations)\n agents = \", \".join(getattr(a, \"full_name\", a.name) for a in self.selected_activity.agents)\n full_command = \" \".join(self.selected_activity.plan_with_values.to_argv(with_streams=True))\n\n content = (\n \"Id:\\n\"\n f\"{self.selected_activity.id}\\n\\n\"\n \"Started:\\n\"\n f\"{started_date}\\n\\n\"\n \"Ended:\\n\"\n f\"{ended_date}\\n\\n\"\n \"Agents:\\n\"\n f\"{agents}\\n\\n\"\n \"Plan Id:\\n\"\n f\"{self.selected_activity.association.plan.id}\\n\\n\"\n \"Plan Name:\\n\"\n f\"{self.selected_activity.association.plan.name}\\n\\n\"\n \"Inputs:\\n\"\n f\"{usages}\\n\\n\"\n \"Outputs:\\n\"\n f\"{generations}\\n\\n\"\n \"Full Command:\\n\"\n f\"{full_command}\\n\\n\"\n )\n\n self._add_multiline_text_with_wrapping(self.activity_overlay, content)\n self.activity_overlay.overlay(screen)\n else:\n del self.activity_overlay\n self.activity_overlay = None\n\n def _update_help_overlay(self, screen):\n \"\"\"Show/hide the help overlay.\"\"\"\n if not self.help_overlay:\n del self.activity_overlay\n self.activity_overlay = None\n\n self.help_overlay = curses.newwin(\n self.HELP_OVERLAY_HEIGHT, self.HELP_OVERLAY_WIDTH, 0, self.cols - self.HELP_OVERLAY_WIDTH\n )\n curses.panel.new_panel(self.help_overlay)\n self.help_overlay.border()\n\n content = (\n \"Navigate using arrow keys\\n\"\n \"Press to show activity details\\n\"\n \"Press to toggle free arrow movement\\n\"\n \"Press to show/hide this help\\n\"\n \"Press to exit\\n\"\n )\n self._add_multiline_text_with_wrapping(self.help_overlay, content)\n self.help_overlay.overlay(screen)\n else:\n del self.help_overlay\n self.help_overlay = None\n\n def _move_viewscreen_to_activity(self):\n \"\"\"Move viewscreen to include selected activity.\"\"\"\n if self.activity_start.x - 1 < self.x_pos:\n self.x_pos = max(self.activity_start.x - 1, 0)\n elif self.activity_end.x + 1 > self.x_pos + self.cols:\n self.x_pos = min(self.activity_end.x + 1, self.content_max_x) - self.cols - 1\n\n if self.activity_start.y - 1 < self.y_pos:\n self.y_pos = max(self.activity_start.y - self.vertical_space - 3, 0)\n elif self.activity_end.y + 1 > self.y_pos + self.rows:\n self.y_pos = min(self.activity_end.y + self.vertical_space + 3, self.content_max_y) - self.rows - 1\n\n def _loop(self, screen):\n \"\"\"The interaction loop.\"\"\"\n running = True\n\n while running:\n input_char = screen.getch()\n\n # update screen size to deal with resizes\n self.rows, self.cols = screen.getmaxyx()\n\n # handle keypress\n if input_char == curses.KEY_DOWN or chr(input_char) == \"k\":\n if self.free_move:\n self.y_pos = min(self.y_pos + 1, self.content_max_y - self.rows - 1)\n else:\n self._change_layer(1)\n elif input_char == curses.KEY_UP or chr(input_char) == \"i\":\n if self.free_move:\n self.y_pos = max(self.y_pos - 1, 0)\n else:\n self._change_layer(-1)\n elif input_char == curses.KEY_RIGHT or chr(input_char) == \"l\":\n if self.free_move:\n self.x_pos = min(self.x_pos + 1, self.content_max_x - self.cols - 1)\n else:\n self._change_layer_position(1)\n elif input_char == curses.KEY_LEFT or chr(input_char) == \"j\":\n if self.free_move:\n self.x_pos = max(self.x_pos - 1, 0)\n else:\n self._change_layer_position(-1)\n elif input_char == curses.KEY_ENTER or input_char == 10 or input_char == 13:\n self._update_activity_overlay(screen)\n elif chr(input_char) == \"h\":\n self._update_help_overlay(screen)\n elif chr(input_char) == \"f\":\n self.free_move = not self.free_move\n elif input_char < 256 and chr(input_char) == \"q\":\n running = False\n\n self._unblink_text(self.content_pad, self.activity_start, self.activity_end, bold=True)\n self._select_activity()\n self._blink_text(self.content_pad, self.activity_start, self.activity_end, bold=True)\n\n if not self.free_move:\n self._move_viewscreen_to_activity()\n\n self._refresh(screen)\n\n def _main(self, screen):\n \"\"\"The main execution method for wrapped curses execution.\"\"\"\n self._init_curses(screen)\n self._loop(screen)\n\n def run(self):\n \"\"\"Run interactive curses mode.\"\"\"\n curses.wrapper(self._main)\n","sub_path":"renku/ui/cli/utils/curses.py","file_name":"curses.py","file_ext":"py","file_size_in_byte":14521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"111454195","text":"import matplotlib.pyplot as plt\n\n# Create data set for visualistion\ninput_values = []\nsquares = []\n\nfor i in range(1, 10):\n\tinput_values.append(i)\n\tsquares.append(i**2)\nprint(input_values)\nprint(squares)\n\n# Plot Graph\nplt.plot(input_values, squares, linewidth=5)\n\n# Set chart title and label axes.\nplt.title(\"Square numbers\", fontsize=24)\nplt.xlabel(\"Value\", fontsize=14)\nplt.ylabel(\"Square of Value\", fontsize=14)\n\n# Set size of tick labels.\nplt.tick_params(axis='both', labelsize=14)\n\nplt.show()","sub_path":"mpl_squares.py","file_name":"mpl_squares.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"405548784","text":"# Copyright (c) 2016 Mellanox Technologies, Ltd\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom nacsa import exception\nfrom nacsa.objects import base\nfrom nacsa.objects import fields\nfrom nacsa.objects import resource_provider as rp\n\n\n@base.NacsaObjectRegistry.register\nclass Allocation(rp._HasAResourceProvider):\n # Version 1.0: Initial version\n VERSION = '1.0'\n\n fields = {\n 'id': fields.IntegerField(read_only=True),\n 'resource_provider': fields.ObjectField('ResourceProvider'),\n 'consumer_id': fields.UUIDField(nullable=False),\n 'resource_class': fields.ResourceClassField(nullable=False),\n 'used': fields.IntegerField(nullable=False),\n }\n\n def create(self):\n self._validate_create()\n updates = self._make_db(self.obj_get_changes())\n db_allocation = self.dbapi.create_allocation(updates)\n self._from_db_object(self, db_allocation)\n\n def _validate_create(self):\n if 'id' in self:\n raise exception.ObjectActionError(action='create',\n reason='specifying id '\n 'is not permitted')\n required_fields = set(self.fields) - set(['id'])\n for field in required_fields:\n if field not in self:\n raise exception.ObjectActionError(\n action='create', reason=field + ' is required')\n\n def destroy(self):\n \"\"\"Delete the allocation from the DB.\n \"\"\"\n self.dbapi.destroy_allocation(self.id)\n self.obj_reset_changes()\n\n @classmethod\n def get_by_fields(cls, **filter_fields):\n db_allocation = cls.dbapi.get_allocation_by_fields(**filter_fields)\n return cls._from_db_object(cls(), db_allocation)\n\n @classmethod\n def get_by_fields_all(cls, **filter_fields):\n allocations = cls.dbapi.get_allocation_by_fields_all(**filter_fields)\n return [cls._from_db_object(cls(), allocation)\n for allocation in allocations]\n","sub_path":"nacsa/objects/allocation.py","file_name":"allocation.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"466824907","text":"import argparse\nimport datetime as dt\nimport os\n\nfrom flask import Flask, request, abort, json\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\nimport requests\n\napp = Flask(__name__)\napp.config.from_pyfile('settings.py')\n# Since I deployed this to Heroku, it sets the DATABASE_URL environment variable\n# Set this to where your database is\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n\tname = db.Column(db.String(50), primary_key=True)\n\tlocation = db.Column(db.String(500))\n\tdefault = db.Column(db.String(500))\n\tdate = db.Column(db.Date)\n\n\tdef __init__(self, name):\n\t\tself.name = name\n\n\tdef __repr__(self):\n\t\treturn \"\".format(self.name, self.location)\n\n\n@app.route(\"/\", methods=['POST'])\ndef workingfrom():\n\t\n\tdata = check_request(request)\n\tuser_name, text = data.get('user_name'), data.get('text')\n\n\tif \"-help\" in text:\n\t\treturn app.config[\"HELP_TEXT\"]\n\n\ttext_data, action = parse_text(text)\n\t\n\tif action == 'set':\n\t\t\n\t\tuser = User.query.filter_by(name=user_name).first()\n\t\tif user is None:\n\t\t\tuser = User(user_name)\n\t\t\n\t\tlocation = text_data['location']\n\t\tuser.location = location\n\t\tuser.date = dt.datetime.now()\n\t\tdb.session.add(user)\n\n\t\tif text_data.get('default'):\n\t\t\tuser.default = location\n\t\t\tdb.session.commit()\n\t\t\treturn \"Setting your default location to {}.\\n\".format(location)\n\t\telse:\n\t\t\tdb.session.commit()\n\n\t\tannouncement = \"@{} is working from {}.\\n\".format(user.name, location)\n\n\t\tchannels = ['#working-from']\n\t\tif data.get('channel_name') != 'working-from':\n\t\t\tchannels.append(data.get('channel_name'))\n\n\t\tif text_data.get('channels'):\n\t\t\tfor each in text_data['channels']:\n\t\t\t\tchannels.append(each.strip())\n\n\t\tfor channel in channels:\n\t\t\tif channel[0] != '#':\n\t\t\t\tchannel = '#' + channel\n\t\t\tpayload = {\"text\": announcement,\n\t\t\t\t \"channel\": channel,\n\t\t\t\t \"username\": \"workingfrom\"}\n\t\t\tjson_data = json.dumps(payload)\n\t\t\trequests.post(app.config[\"WEBHOOK_URL\"], data=json_data)\n\n\t\treturn \"Got it, you're working from {}\".format(location)\n\t\n\telif action == 'get':\n\t\tuser = User.query.filter_by(name=text_data['text']).first()\n\t\tif user is None:\n\t\t\treturn \"Sorry, we don't have a record for {}.\\n\".\\\n\t\t\t\t\tformat(text_data['text'])\n\n\t\tif user.date == dt.datetime.now().date():\n\t\t\tformat_date = \"today\"\n\t\telse:\n\t\t\tformat_date = user.date.strftime(\"%D\")\n\t\t\n\t\treply = \"@{} is working from {}, as of {}.\".\\\n\t\t\t\tformat(user.name, user.location, format_date)\n\t\tif user.default is not None and format_date != \"today\":\n\t\t\treply = reply + \" Typically working from {}.\".format(user.default)\n\t\treturn reply + \"\\n\"\n\ndef check_request(request):\n\tdata = request.form\n\tif data.get('token') != app.config['TOKEN']:\n\t\treturn abort(403)\n\telse:\n\t\treturn data\n\ndef haschannels(words):\n\tfor word in words:\n\t\tif word.startswith('#'):\n\t\t\treturn True\n\telse:\n\t\treturn False\n\ndef parse_text(text):\n\tdata = {}\n\tif text[0] == '@':\n\t\taction = 'get'\n\t\tdata['text'] = text[1:]\n\telse:\n\t\taction = 'set'\n\t\twords = text.split()\n\n\t\tif ' -' in text:\n\t\t\tdata['location'] = text[:text.index(' -')]\n\t\telif '#' in text:\n\t\t\tdata['location'] = text[:text.index(' #')]\n\t\telse:\n\t\t\tdata['location'] = text\n\n\t\tif '-default' in words:\n\t\t\tdata['default'] = True\n\t\t\n\t\tif '-channels' in words:\n\t\t\tchannels = ' '.join(words[words.index('-channels') + 1:])\n\t\t\tdata['channels'] = channels.replace(',', '').split()\n\t\telif haschannels(words):\n\t\t\tdata['channels'] = [word for word in words if word.startswith('#')]\n\t\t\n\n\n\treturn data, action\n\n\nif __name__ == '__main__':\n\t# Bind to PORT if defined, otherwise default to 5000.\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"163919294","text":"# -*- coding:utf-8 -*-\n# @Author:zxy\n\n\n\nimport unittest\nimport json\nfrom scripts.Read_excel_obj import ReadExcel\nfrom libs.ddt import ddt, data\nfrom scripts.MyYuml import do_yuml\nfrom scripts.MyLogger import do_log\nfrom scripts.handle_Parameterization import Parameterization\nfrom scripts.MyRequest import HandleRequest\n\n\n@ddt\nclass TestRegister(unittest.TestCase):\n # 读取excel数据\n excel = ReadExcel('register')\n case = excel.read_excel()\n do_log.debug('读取excel用例数据成功')\n\n # 第一步:准备所有要用的数据\n # 调用封装的请求,才可以发送请求,可以在用例发生时候调用,调用结束之后一定要关闭\n @classmethod\n def setUpClass(cls): # 所有用例执行前, 会被调用一次\n cls.do_request = HandleRequest() # 创建MyRequest对象\n cls.do_request.add_hesders(do_yuml.read_yuml('request', 'version'))\n\n @classmethod\n def tearDownClass(cls): # 所有用例执行结束之后, 会被调用一次\n cls.do_request.close() # 用例测试结束,关闭会话释放内存\n\n @data(*case)\n def test_register(self,cases):\n\n #获取用例的行号\n row=cases.caseid+1\n #获取用例的参数\n par=Parameterization.parmse_all(cases.datas)\n #获取用例的url\n register_url=do_yuml.read_yuml('request','url')+cases.url\n #获取用例的期望结果\n expected=cases.expected\n #获取用例标题\n msg=cases.title\n\n #第二步:调用请求接口,发送请求,执行注册\n res=self.do_request.send(url=register_url,method=cases.method,data=par,is_json=True)#这里的method=cases.method跟is_json=True因为是默认参数,可以省略不写\n data_json=res.json()#将响应报文转化为json的字典数据\n\n #第三步:预期与实际结果进行比较\n try:\n # assertEqual第三个参数为用例执行失败之后的提示信息\n # assertEqual第一个参数为期望值, 第二个参数为实际值\n self.assertEqual(expected,data_json['code'],msg=msg)#预期与实际的2个code进行对比\n except AssertionError as e:\n #将用例的实际结果写到excel的result这一列中\n self.excel.write_excel(han=row,\n column=do_yuml.read_yuml('excel','result'),\n value=do_yuml.read_yuml('msg','fail_result'))\n do_log.error(\"{},执行测试的具体的异常为:{}\\n\".format(msg,e))\n raise e\n else:\n # 将用例的实际结果写到excel的result这一列中\n self.excel.write_excel(han=row,\n column=do_yuml.read_yuml('excel', 'result'),\n value=do_yuml.read_yuml('msg', 'success_result'))\n do_log.info('{},执行用例通过'.format(msg))\n finally:\n # 将响应的结果反写到excel的actall这一列中\n self.excel.write_excel(han=row, column=do_yuml.read_yuml('excel', 'case_result'), value=res.text)\n\n\n\n\n\nif __name__ == '__main__':\n \"\"\"\n 运行这个文件要么这main函数下右击调试运行,要么鼠标放到类上右击运行否则会报错\n \"\"\"\n unittest.main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"APITest/cases/testqcd_01_register.py","file_name":"testqcd_01_register.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"341080656","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QDialog, QLabel, QLineEdit, QPushButton, QGridLayout\n\nclass MyApp(QDialog):\n def __init__(self):\n QDialog.__init__(self)\n\n layout = QGridLayout()\n self.label = QLabel(\"Type below...\")\n line_edit = QLineEdit()\n button = QPushButton(\"Close\")\n\n layout.addWidget(self.label)\n layout.addWidget(line_edit)\n layout.addWidget(button)\n\n self.setLayout(layout)\n\n button.clicked.connect(self.close) #connect to handler\n line_edit.textChanged.connect(self.changeTextLabel)\n\n def changeTextLabel(self, text):\n self.label.setText(text)\n\n\napp = QApplication(sys.argv)\ndialog = MyApp()\ndialog.show()\napp.exec_()","sub_path":"testing/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"82379055","text":"# Module to save the data received into the excel sheet.\n\nimport xlrd\nimport xlwt\nimport os\nfrom xlutils.copy import copy\t#Tools for copying xlrd.Book objects to xlwt.Workbook objects.\n\ndef save(name,fname,mname,address,contact):\n\terrors = []\n\tpath = os.curdir + os.sep + \"system\" + os.sep + 'data' + os.sep + \"Student Information.xls\"\n\tif(os.path.exists(path)):\n\t\twb = xlrd.open_workbook(path , formatting_info = True)\n\t\tsheet = wb.sheet_by_index(0)\n\n\t\tfor i in range(sheet.ncols):\n\t\t\tcol_name = sheet.cell_value(0,i)\n\t\t\tif(col_name == 'Application #'):\n\t\t\t\tAPP_COL_NO = i\n\t\t\telif(col_name == 'Name'):\n\t\t\t\tNAME_COL_NO = i\n\t\t\telif(col_name == \"Father's Name\"):\n\t\t\t\tFNAME_COL_NO = i\n\t\t\telif(col_name == \"Mother's Name\"):\n\t\t\t\tMNAME_COL_NO = i\n\t\t\telif(col_name == \"Address\"):\n\t\t\t\tADD_COL_NO = i\n\t\t\telif(col_name == \"Contact No.\"):\n\t\t\t\tCON_COL_NO = i\n\t\t\n\t\trow = sheet.nrows\n\t\tapp_no = sheet.cell_value(row-1 , APP_COL_NO) + 1\n\t\twb = copy(wb) \n\t\tsheet = wb.get_sheet(0)\n\t\t\n\t\tsheet.write(row , APP_COL_NO , app_no)\n\t\tsheet.write(row , NAME_COL_NO , name)\n\t\tsheet.write(row , FNAME_COL_NO , fname)\n\t\tsheet.write(row , MNAME_COL_NO , mname)\n\t\tsheet.write(row , ADD_COL_NO , address)\n\t\tsheet.write(row , CON_COL_NO , contact)\n\t\t\n\t\twb.save(path)\n\telse:\n\t\terrors.append(\"File Not Found\")\n\t\n\treturn True,errors\n","sub_path":"system/student_application.py","file_name":"student_application.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"7160178","text":"import socket\nfrom struct import pack,unpack\nimport numpy as np\nfrom time import time,sleep\n\nclass udp_handler(object):\n\tdef __init__(self):\n\t\tself.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\t\tself.PKTSZ = 65500-12\n\t\tself.packets = {}\n\t\tself.pklist = []\n\t\tself.PKLEN = 2000000\n\t\tself.subtime = time()\n\n\tdef make_listener(self,ip,port):\n\t\tself.sock.bind((ip,port))\n\n\tdef send_data(self,img,ip,port):\n\t\trembytes=1\n\t\tstt=0\n\t\tdata=img.tobytes()\n\t\tpkid=img[np.random.randint(0,30)].sum()+np.random.random()*1000+(time()-self.subtime)*1000\n\t\twhile rembytes>0:\n\t\t\tbuffer=data[stt:stt+self.PKTSZ]\n\t\t\tstt+=self.PKTSZ\n\t\t\trembytes=len(data)-stt\n\t\t\tif rembytes<=0:\n\t\t\t\trembytes=0\n\t\t\tself.sock.sendto(pack('d',pkid)+pack('f',np.float32(rembytes))+buffer,(ip,port))\n\n\tdef get_data(self):\n\t\trembuf, address = self.sock.recvfrom(self.PKTSZ+12)\n\t\tpkid=unpack('d', rembuf[:8])[0]\n\t\trembytes=unpack('f', rembuf[8:12])[0]\n\t\tbuffer=rembuf[12:]\n\t\ttry:\n\t\t\tself.packets[pkid]+=buffer\n\t\texcept KeyError:\n\t\t\tself.packets[pkid]=buffer\n\t\t\tself.pklist.append(pkid)\n\t\t\tif len(self.pklist)>self.PKLEN:\n\t\t\t\tself.packets.pop(self.pklist.pop(0))\n\t\tif rembytes<=0:\n\t\t\tdata=self.packets[pkid]\n\t\t\tself.packets.pop(pkid)\n\t\t\tself.pklist.remove(pkid)\n\t\telse:\n\t\t\ttry:\n\t\t\t\tdata=self.get_data()\n\t\t\texcept RecursionError:\n\t\t\t\tdata=None\n\t\treturn data\n\n\tdef send_data_small(self,img,ip,port):\n\t\tdata=img.tobytes()\n\t\tself.sock.sendto(data,(ip,port))\n\n\tdef get_data_small(self):\n\t\tdata, address = self.sock.recvfrom(self.PKTSZ)\n\t\treturn data\n\n\tdef close(self):\n\t\tself.sock.close()","sub_path":"udp_streamer.py","file_name":"udp_streamer.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"58531540","text":"import cv2\nimport math\nimport numpy as np\nimport random\nimport vizdoom as vzd\n\nfrom keras.models import load_model\nfrom setup import setup_game_test\n\n\ndef compute_map(state, height=240, width=320,\n map_size=256, map_scale=3, fov=90.0,\n beacon_scale=50, pick_new_goal=False,\n only_visible_beacons=True, curr_goal=None,\n explored_goals={}):\n # Extract agent state from game\n depth_buffer = state.depth_buffer\n\n player_x = state.game_variables[5]\n player_y = state.game_variables[6]\n player_angle = state.game_variables[8]\n\n # Initialize maps\n canvas_size = 2*map_size + 1\n vis_map = np.zeros((canvas_size, canvas_size, 3), dtype=np.uint8)\n simple_map = np.zeros((canvas_size, canvas_size), dtype=np.uint8)\n\n # Compute upper left and upper right extreme coordinates\n r = canvas_size\n offset = 225\n\n y1 = int(r * math.cos(math.radians(offset + player_angle)))\n x1 = int(r * math.sin(math.radians(offset + player_angle)))\n\n y2 = int(r * math.cos(math.radians(offset + player_angle - fov)))\n x2 = int(r * math.sin(math.radians(offset + player_angle - fov)))\n\n # Draw FOV boundaries\n _, p1, p2 = cv2.clipLine((0, 0, canvas_size, canvas_size),\n (map_size, map_size),\n (map_size + x1, map_size + y1))\n _, p3, p4 = cv2.clipLine((0, 0, canvas_size, canvas_size),\n (map_size, map_size),\n (map_size + x2, map_size + y2))\n\n # Ray cast from eye line to project depth map into 2D ray points\n game_unit = 100.0/14\n ray_cast = (depth_buffer[height/2] * game_unit)/float(map_scale)\n\n ray_points = [(map_size, map_size)]\n for i in range(10, canvas_size-10):\n d = ray_cast[int(float(width)/canvas_size * i - 1)]\n theta = (float(i)/canvas_size * fov)\n\n ray_y = int(d * math.sin(math.radians(offset - theta))) + map_size\n ray_x = int(d * math.cos(math.radians(offset - theta))) + map_size\n\n _, _, p = cv2.clipLine((0, 0, canvas_size, canvas_size),\n (map_size, map_size),\n (ray_y, ray_x))\n ray_points.append(p)\n\n # Fill free space on 2D map with colour\n cv2.fillPoly(vis_map, np.array([ray_points], dtype=np.int32), (255, 255, 255)) # NOQA\n cv2.fillPoly(simple_map, np.array([ray_points], dtype=np.int32), (1, 1, 1))\n\n quantized_x = int(player_x/beacon_scale) * beacon_scale\n quantized_y = int(player_y/beacon_scale) * beacon_scale\n beacon_radius = 10\n\n # Get beacons within range of current agent position\n beacons = []\n for bnx in range(-beacon_radius, beacon_radius+1):\n for bny in range(-beacon_radius, beacon_radius+1):\n beacon_x = quantized_x + bnx * beacon_scale\n beacon_y = quantized_y + bny * beacon_scale\n beacons.append((beacon_x, beacon_y))\n\n # Compute set of visible beacons and draw onto the map\n visble_beacons_world = []\n for b in beacons:\n object_relative_x = -b[0] + player_x\n object_relative_y = -b[1] + player_y\n\n rotated_x = math.cos(math.radians(-player_angle)) * object_relative_x - math.sin(math.radians(-player_angle)) * object_relative_y # NOQA\n rotated_y = math.sin(math.radians(-player_angle)) * object_relative_x + math.cos(math.radians(-player_angle)) * object_relative_y # NOQA\n\n rotated_x = int(rotated_x/map_scale + map_size)\n rotated_y = int(rotated_y/map_scale + map_size)\n\n if (rotated_x >= 0 and rotated_x < canvas_size and\n rotated_y >= 0 and rotated_y < canvas_size):\n color = (255, 0, 0)\n object_id = 3\n show = True\n if simple_map[rotated_x, rotated_y] == 0:\n show = (only_visible_beacons is not True)\n else:\n visble_beacons_world.append((b[0], b[1]))\n\n if show:\n simple_map[rotated_x, rotated_y] = object_id\n cv2.circle(vis_map, (rotated_y, rotated_x), 2, color,\n thickness=-1)\n\n # Pick new goal from unexplored visible beacons if required\n if pick_new_goal:\n unexplored_beacons = []\n for b in visble_beacons_world:\n if b not in explored_goals:\n unexplored_beacons.append(b)\n\n if len(unexplored_beacons) > 0:\n beacon_idx = random.randint(0, len(unexplored_beacons)-1)\n curr_goal = unexplored_beacons[beacon_idx]\n explored_goals[curr_goal] = True\n else:\n curr_goal = None\n\n return curr_goal\n\n\ndef compute_goal(state, step, curr_goal, explored_goals):\n # Determine if new goal should be picked\n if step % 50 == 0:\n pick_new_goal = True\n else:\n pick_new_goal = False\n\n # Compute absolute position of goal\n curr_goal = compute_map(state,\n pick_new_goal=pick_new_goal,\n curr_goal=curr_goal,\n explored_goals=explored_goals)\n\n # Compute relative distance to goal\n player_x = state.game_variables[5]\n player_y = state.game_variables[6]\n player_angle = state.game_variables[8]\n\n if curr_goal is not None:\n diff_x = curr_goal[0] - player_x\n diff_y = curr_goal[1] - player_y\n rel_goal = np.array([diff_x, diff_y])\n else:\n # Project to location behind the agent\n line_length = 250\n proj_x = player_x + math.cos(math.radians(player_angle)) * line_length * -1\n proj_y = player_y + math.sin(math.radians(player_angle)) * line_length * -1\n rel_goal = np.array([proj_x, proj_y])\n\n return curr_goal, rel_goal\n\n\ndef test_scenario(model, wad_path, vid_out_name=None):\n num_steps = 4200\n history_size = 2\n\n # Setup game using WAD and LMP\n game = setup_game_test(wad_path)\n\n # Set up video if specified\n vid_out = None\n if vid_out_name is not None:\n vid_out = cv2.VideoWriter(vid_out_name,\n cv2.VideoWriter_fourcc(*'XVID'),\n vzd.DEFAULT_TICRATE, (320, 240))\n\n # Declare state history matrices\n frames = np.zeros((history_size + num_steps, 240, 320, 3))\n depths = np.zeros((history_size + num_steps, 240, 320))\n angles = np.zeros((history_size + num_steps, 1))\n goals = np.zeros((history_size + num_steps, 2))\n explored_goals = {}\n curr_goal = np.zeros(2)\n\n for step in range(num_steps - 1):\n # Get state from game\n state = game.get_state()\n frame = state.screen_buffer\n depth = state.depth_buffer\n angle = game.get_game_variable(vzd.GameVariable.ANGLE)\n\n # Write to video if specified\n if vid_out:\n vid_out.write(frame)\n\n # Record state\n data_idx = step + history_size\n frames[data_idx] = frame\n depths[data_idx] = depth\n angles[data_idx] = angle\n\n # Compute beeline goal\n curr_goal, rel_goal = compute_goal(state, step, curr_goal, explored_goals)\n goals[data_idx] = rel_goal\n print(np.linalg.norm(rel_goal))\n\n # Build input for network\n batch_rgbd_all = []\n batch_ga_all = []\n\n for j in reversed(range(history_size + 1)):\n batch_frames = frames[step + j, :, :, :]\n batch_depths = depths[step + j, :, :][:, :, np.newaxis]\n batch_rgbd_all.append(batch_frames)\n batch_rgbd_all.append(batch_depths)\n\n batch_goals = goals[step + j, :]\n batch_angles = angles[step + j, :]\n batch_ga_all.append(batch_goals)\n batch_ga_all.append(batch_angles)\n\n batch_rgbd = np.concatenate(batch_rgbd_all, axis=2)[np.newaxis, :, :, :]\n batch_ga = np.concatenate(batch_ga_all, axis=0)[np.newaxis, :]\n\n # Compute and perform action\n pred_action = np.rint(model.predict_on_batch([batch_rgbd, batch_ga])[0])\n action = [0.0] * 21\n action[7] = pred_action[0]\n action[8] = pred_action[1]\n action[9] = pred_action[2]\n game.make_action(action)\n\n # Finish writing video if specified\n if vid_out:\n vid_out.release()\n\n\nmodel_path = '../../experiments/trained_models/model_angle_history_2500.h5'\ntest_wad_ids = [192, 194, 195, 196, 197, 199, 201, 202, 203, 204]\nwad_id = test_wad_ids[1]\nwad_path = '../../data/maps/out/gen_{}_size_regular_mons_none_steepness_none.wad'.format(wad_id) # NOQA\n\nmodel = load_model(model_path)\n\ntest_scenario(model, wad_path, 'test.avi')\n","sub_path":"examples/python/train_sptm/src/imitate/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":8585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"249969565","text":"\"\"\" Activation Functions\n\nTo be used by :py:class:`~tensorx.layers.Activation` or with any other :py:class:`~tensorflow.Tensor`.\n\"\"\"\n\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops.nn import top_k\nfrom tensorflow.python.ops import nn\nfrom tensorflow.python.ops import clip_ops\n\nfrom tensorx.utils import to_tensor_cast\n\n\ndef identity(x):\n \"\"\" Returns a tensor with the same content as the input tensor.\n\n Args:\n x: The input tensor.\n\n Returns:\n A tensor of the same shape, type and content of the input tensor.\n \"\"\"\n return array_ops.identity(x)\n\n\ndef sigmoid(x):\n \"\"\"Element-wise sigmoid.\n\n Args\n x: A tensor or variable.\n\n Returns:\n A tensor.\n \"\"\"\n return nn.sigmoid(x)\n\n\ndef hard_sigmoid(x):\n \"\"\"Segment-wise linear approximation of sigmoid.\n Faster than sigmoid.\n\n Note: Approximates in 3 parts: 0, scaled linear, 1.\n\n returns `0.` if `x < -2.5`, `1.` if `x > 2.5`.\n In `-2.5 <= x <= 2.5`, returns `0.2 * x + 0.5`.\n\n Args:\n x: A tensor or variable.\n\n Returns:\n a float32 tensor resulting in an approximated element-wise sigmoid applied to x\n\n \"\"\"\n x = ops.convert_to_tensor(x)\n\n slope = to_tensor_cast(0.2, x.dtype)\n shift = to_tensor_cast(0.5, x.dtype)\n x = (slope * x) + shift\n zero = to_tensor_cast(0., x.dtype)\n one = to_tensor_cast(1., x.dtype)\n x = clip_ops.clip_by_value(x, zero, one)\n\n return x\n\n\ndef tanh(x):\n \"\"\"Element-wise hyperbolic tangent (tanh).\n\n Args:\n x: A tensor or variable.\n\n\n Returns: A tensor.\n\n \"\"\"\n return nn.tanh(x)\n\n\ndef relu(x, alpha=0., max_value=None):\n \"\"\" Rectified linear unit [1].\n\n References:\n [1] (Vinod & Hinton, 2010) \"Rectified linear units improve restricted boltzmann machines.\"\n\n Args:\n x (Tensor): Tensor or variable to compute the activation function for.\n alpha: Slope for negative input, usually between 0 and 1. The default value of 0 will lead to the standard\n rectifier, 1 will lead to a linear activation function, and any value in between will give a leaky rectifier\n max_value: Saturation threshold.\n\n Returns:\n ´´Tensor´´: A tensor that results in element-wise rectifier applied to x.\n \"\"\"\n x = ops.convert_to_tensor(x)\n if alpha != 0.:\n negative_part = nn.relu(-x)\n x = nn.relu(x)\n if max_value is not None:\n max_value = to_tensor_cast(max_value, x.dtype)\n zero = to_tensor_cast(0., x.dtype)\n x = clip_ops.clip_by_value(x, zero, max_value)\n if alpha != 0.:\n alpha = to_tensor_cast(alpha, x.dtype)\n x -= alpha * negative_part\n\n return x\n\n\ndef elu(x, alpha=1.):\n \"\"\"Exponential Linear Unit\n\n Reference:\n\n (Clevert et al. 2015) Fast and accurate deep network learning by exponential linear units (ELUs).\n\n Args:\n x: A tenor or variable to compute the activation function for.\n alpha: A scalar, slope of positive section.\n\n Returns:\n A tensor\n \"\"\"\n y = nn.elu(x)\n if alpha == 1:\n return y\n else:\n return array_ops.where(x > 0, y, x * y)\n\n\ndef softmax(x):\n \"\"\"Softmax activation function\n\n applies the softmax function to the input tensor last dimension\n\n Args:\n x: a 2D Tensor of variable\n\n Returns:\n a 2D tensor whose ijth element is computed from the softmax function\n\n \"\"\"\n return nn.softmax(x)\n\n\ndef sparsemax(logits, name=None):\n \"\"\"Computes the sparsemax activation function [1]\n\n For each batch `i` and class `j` we have\n sparsemax[i, j] = max(logits[i, j] - tau(logits[i, :]), 0)\n\n References:\n [1]: https://arxiv.org/abs/1602.02068\n\n Args:\n logits: A `Tensor`. Must be one of the following types: `half`, `float32`,\n `float64`.\n name: A name for the operation (optional).\n\n Returns:\n A `Tensor`. Has the same type as `logits`.\n \"\"\"\n\n with ops.name_scope(name, \"sparsemax\", [logits]) as name:\n logits = ops.convert_to_tensor(logits, name=\"logits\")\n obs = array_ops.shape(logits)[0]\n dims = array_ops.shape(logits)[1]\n\n z = logits - math_ops.reduce_mean(logits, axis=1)[:, array_ops.newaxis]\n\n # sort z\n z_sorted, _ = top_k(z, k=dims)\n\n # calculate k(z)\n z_cumsum = math_ops.cumsum(z_sorted, axis=1)\n k = math_ops.range(\n 1, math_ops.cast(dims, logits.dtype) + 1, dtype=logits.dtype)\n z_check = 1 + k * z_sorted > z_cumsum\n # because the z_check vector is always [1,1,...1,0,0,...0] finding the\n # (index + 1) of the last `1` is the same as just summing the number of 1.\n k_z = math_ops.reduce_sum(math_ops.cast(z_check, dtypes.int32), axis=1)\n\n # calculate tau(z)\n indices = array_ops.stack([math_ops.range(0, obs), k_z - 1], axis=1)\n tau_sum = array_ops.gather_nd(z_cumsum, indices)\n tau_z = (tau_sum - 1) / math_ops.cast(k_z, logits.dtype)\n\n # calculate p\n return math_ops.maximum(\n math_ops.cast(0, logits.dtype), z - tau_z[:, array_ops.newaxis])\n\n\n__all__ = [\"relu\", \"sigmoid\", \"hard_sigmoid\", \"tanh\", \"elu\", \"identity\", \"softmax\", \"sparsemax\"]\n","sub_path":"tensorx/activation.py","file_name":"activation.py","file_ext":"py","file_size_in_byte":5359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"549780122","text":"\"\"\"\nThis script takes two ontologies, parses them into graphs, and then merges these graphs. The ontologies used in this script are\nthe bft (Kitchen Concepts) and affordance ontologies.\n\"\"\"\nfrom rdflib import Graph, Namespace, RDF, URIRef, RDFS\nfrom rdflib.namespace import OWL\n\n\ndef create_namespace(graph, namespace, prefix):\n \"\"\"\n Binds a namespace to a given graph.\n Args:\n - graph: graph object\n - namespace: uri of the namespace to be bound to the graph\n - prefix: the prefix of the given namespace\n Output: namespace instance bound to a specified graph\n \"\"\"\n ns = Namespace(namespace)\n graph.namespace_manager.bind(prefix, namespace)\n\n return ns\n\n\ndef get_graph(ontology_file, onto_namespace, onto_prefix):\n \"\"\"\n Creates a graph from a given ontology.\n Args:\n - ontology_file: file with triples to be parsed into graph object\n - onto_namespace: the ontology's namespace\n - onto_prefix: the ontology's given prefix\n Output: a graph object with ontology axioms\n \"\"\"\n g = Graph()\n g_ns = create_namespace(g, onto_namespace, onto_prefix)\n file_format = ontology_file[3:].split('.')[1]\n g.parse(ontology_file, format=file_format)\n print(f'{ontology_file} graph has {len(g)} triples')\n\n return g\n\n\ndef merge_graphs(graph1, graph2, output_filename='merged_graph.ttl'):\n \"\"\"\n Merges two graphs.\n Args:\n - graph1: a graph object to be merged with another graph\n - graph2: a graph object to be merged with another graph\n - output_filename: (default 'merged_graph.ttl') filename of merged graph file output\n Input: two graph objects.\n Ouput: one merged graph.\n \"\"\"\n merged_g = graph1 + graph2\n classes = ['Drink', 'Food', 'Furniture', 'Kitchenware', 'Storage']\n for c in classes:\n uri_string = f'http://test.org/bft.owl#{c}'\n merged_g.add( (URIRef(uri_string), RDFS.subClassOf, URIRef('http://test.org/affordance.owl#KitchenEntity')) )\n\n # remove the ontology declarations\n merged_g.remove( (None, RDF.type, OWL.Ontology) )\n kchn_ns = create_namespace(merged_g, 'http://test.org/kitchen.owl#', 'kchn')\n merged_g.add( (URIRef('http://test.org/kitchen.owl'), RDF.type, OWL.Ontology) )\n print(\"Merged graphs have {} triples\".format(len(merged_g)))\n file_format = output_filename[3:].split('.')[1]\n\n if file_format == 'owl':\n file_format = 'xml'\n\n merged_g.serialize(destination= f'{output_filename}', format=file_format)\n\n return\n\n\ndef main():\n\n open_aff_onto_file = \"../ontologies/affordance/aff_onto_not_closed.ttl\"\n open_bft_onto_file = \"../ontologies/bft/bft_onto_not_closed.ttl\"\n\n aff_open_g = get_graph(open_aff_onto_file, \"http://test.org/affordance.owl#\", 'aff')\n bft_open_g = get_graph(open_bft_onto_file, \"http://test.org/bft.owl#\", 'bft')\n merge_graphs(aff_open_g, bft_open_g, output_filename='./graphs/aff_bft_open_graph.ttl')\n\n\n return\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"knowledge-graph/.ipynb_checkpoints/merge_aff_bft-checkpoint.py","file_name":"merge_aff_bft-checkpoint.py","file_ext":"py","file_size_in_byte":2993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"568457384","text":"import threading\nimport time\n\nfrom speech_recognition import Microphone, RequestError, WaitTimeoutError, UnknownValueError\n\nimport logger\nfrom utils import getResource\n\n\nclass Recorder:\n\n def __init__(self, recognizer, queue):\n self.recognizer = recognizer\n self.microphone = Microphone()\n self.indicator = 0\n self.queue = queue\n self.is_actually_run = None\n self.err_no_net = False\n self.service_json = None\n self.load_service_json()\n self.service_key = 'AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw'\n self.for_free = False\n\n def load_service_json(self):\n with open(getResource('service-account-file.json')) as f:\n self.service_json = f.read()\n\n def get_indicator(self):\n \"\"\"\n Returns new id number for separate request.\n \"\"\"\n self.indicator += 1\n return self.indicator\n\n def listen_in_background(self):\n \"\"\"\n Adds a new thread responsible for sound input.\n \"\"\"\n\n def stop_lister(wait_for_listener=True):\n \"\"\"\n Waits until the recorder finishes work.\n \"\"\"\n self.is_actually_run[0] = False\n if wait_for_listener:\n sound_input_thread.join()\n\n sound_input_thread = threading.Thread(target=self.threaded_listen)\n sound_input_thread.daemon = True\n sound_input_thread.start()\n return stop_lister\n\n def threaded_listen(self, timeout=1):\n \"\"\"\n Starts to listen to user. When the beginning silence is longer\n than 'timeout' then that recording will be skipped and new\n recording will start again.\n \"\"\"\n self.is_actually_run = [True]\n with self.microphone as _:\n while self.is_actually_run[0]:\n try:\n audio = self.recognizer.listen(self.microphone, timeout=timeout)\n except WaitTimeoutError:\n pass\n else:\n if self.is_actually_run[0]:\n logger.info(\"Recorder: New recording [{}]\".format(\n time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.gmtime())))\n self.callback(audio)\n\n def callback(self, audio):\n \"\"\"\n Works in background. Sends a request containing sound data and pushes\n transcripted text into the queue.\n\n Requested audio can consist of noises only. In that case 'recognize_google'\n raises an exception. It is not an error so it should be logged as info.\n \"\"\"\n try:\n if self.for_free:\n text_output = self.recognizer.recognize_google(audio, language='pl-PL', key=self.service_key)\n else:\n text_output = self.recognizer.recognize_google_cloud(audio, language='pl-PL',\n credentials_json=self.service_json)\n self.queue.push(self.get_indicator(), text_output)\n except RequestError:\n self.err_no_net = True\n logger.exception('ERR_NO_NET: Network connection lost.')\n except UnknownValueError:\n logger.info('Unable to transcript the sound data.')\n except:\n logger.exception('Unknown error')\n else:\n logger.info(msg=\"The recording has been converted successfully.\")\n","sub_path":"src/speech/recorder.py","file_name":"recorder.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"416835146","text":"\n\n#calss header\nclass _RESEND():\n\tdef __init__(self,): \n\t\tself.name = \"RESEND\"\n\t\tself.definitions = [u'to send a text message, an email, etc. again']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_resend.py","file_name":"_resend.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"97272418","text":"#!/usr/bin/python\n\"\"\"\n Copyright 2017-2019 IBM Corp 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\nfrom flask import Flask, request, jsonify\nfrom modules import trade\nfrom dbconfig import dbconfig\n\n\napplication = Flask(__name__)\n\n\n@application.route('/trade/', methods=['POST'])\ndef add_trade_wrapper(portfolio):\n #print(portfolio)\n content = request.get_json()\n print(content)\n trade_id = trade.add_trade_post(int(portfolio), content, config.get_config())\n if (trade_id is None):\n return 'Error adding trade to database', 500\n else:\n return jsonify({\"tradeId\": trade_id})\n\n@application.route('/trades/', methods=['GET'])\ndef get_trades_wrapper(portfolio):\n #print(portfolio)\n #content = request.get_json()\n #print(content)\n trades = trade.trades_get(int(portfolio), config.get_config())\n if (trades is None):\n return 'Error retrieving trades from database', 500\n else:\n return jsonify(trades)\n\n@application.route('/totals/', methods=['GET'])\ndef get_ytd_totals_wrapper(portfolio):\n year = request.args.get('year')\n if year is None:\n totals = trade.ytd_totals_get(int(portfolio), config.get_config())\n else:\n totals = trade.ytd_totals_get(int(portfolio), config.get_config(), int(year))\n\n if (totals is None):\n return 'Error retrieving totals from database', 500\n else:\n return jsonify(totals)\n\n@application.route('/readiness', methods=['GET'])\ndef readiness_wrapper():\n return jsonify({\"status\": \"ok\"})\n\nif __name__ == '__main__':\n application.run(host= '0.0.0.0',debug=False)\n","sub_path":"wsgi.py","file_name":"wsgi.py","file_ext":"py","file_size_in_byte":2152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"97799070","text":"# -*- encoding: utf-8 -*-\n\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nfrom pyuca import Collator\n\nstrings = [\n 'noel',\n 'nœl',\n 'no\\u202del\\u202c',\n '\"noel\"',\n 'Noel',\n 'no\\u0308el',\n 'noels',\n 'nuel',\n]\n\nc = Collator()\n\nimport struct\nimport base64\n\ndef p(strs):\n output = []\n for s in strs:\n output.append(\n '.'.join([\n base64.b85encode(struct.pack('>H', k)).decode('ascii')\n for k in c.sort_key(s)\n ])\n )\n print('\\n'.join(output))\n print()\n\np(strings)\np(sorted(strings))\np(sorted(strings, key=c.sort_key))\n","sub_path":"collation/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"460245994","text":"\"\"\"Wrapper for Notion API data types.\n\nWe handle databases and pages somewhat differently than other blocks since they\nrepresent top-level containers for other blocks.\n\nThese objects provide both access to the primitive data structure returned by the API\nas well as higher-level access methods. In general, attributes in lower case represent\nthe primitive data structure, where capitalized attributes provide higher-level access.\n\"\"\"\n\nimport logging\nfrom datetime import datetime\nfrom typing import Dict, List, Optional, Union\nfrom uuid import UUID\n\nfrom .core import NamedObject, TypedObject\nfrom .schema import PropertyObject\nfrom .text import plain_text\nfrom .types import EmojiObject, FileObject, PropertyValue, RichTextObject\n\nlog = logging.getLogger(__name__)\n\n\nclass ParentRef(TypedObject):\n \"\"\"Reference another block.\"\"\"\n\n # TODO method / property to resolve the reference?\n\n\nclass DatabaseParent(ParentRef, type=\"database_id\"):\n \"\"\"Reference a database.\"\"\"\n\n database_id: UUID\n\n\nclass PageParent(ParentRef, type=\"page_id\"):\n \"\"\"Reference a page.\"\"\"\n\n page_id: UUID\n\n\nclass WorkspaceParent(ParentRef, type=\"workspace\"):\n \"\"\"Reference the workspace.\"\"\"\n\n workspace: bool = True\n\n\nclass Record(NamedObject):\n \"\"\"The base type for Notion API records.\"\"\"\n\n id: UUID = None\n created_time: datetime = None\n last_edited_time: datetime = None\n has_children: bool = False\n archived: bool = False\n\n\nclass Database(Record, object=\"database\"):\n \"\"\"A database record type.\"\"\"\n\n title: List[RichTextObject] = None\n url: str = None\n parent: ParentRef = None\n icon: Optional[Union[FileObject, EmojiObject]] = None\n cover: Optional[FileObject] = None\n properties: Dict[str, PropertyObject] = {}\n\n @property\n def Title(self):\n if self.title is None:\n return None\n\n return plain_text(*self.title)\n\n\nclass Page(Record, object=\"page\"):\n \"\"\"A standard Notion page object.\"\"\"\n\n url: str = None\n parent: ParentRef = None\n icon: Optional[Union[FileObject, EmojiObject]] = None\n cover: Optional[FileObject] = None\n properties: Dict[str, PropertyValue] = {}\n\n def __getitem__(self, name):\n \"\"\"Indexer for the given property name.\n\n :param name: the name of the property to get\n \"\"\"\n\n log.debug(\"get property :: {%s} [%s]\", self.id, name)\n\n if self.properties is None:\n raise AttributeError(\"No properties in Page\")\n\n prop = self.properties.get(name)\n\n if prop is None:\n raise AttributeError(f\"No such property: {name}\")\n\n return prop\n\n def __setitem__(self, name, value):\n \"\"\"Set the object data for the given property.\n\n :param name: the name of the property to set\n :param prop: the PropertyValue for the named property\n \"\"\"\n\n log.debug(\"set property :: {%s} [%s] => %s\", self.id, name, value)\n\n if not isinstance(value, PropertyValue):\n raise ValueError(f\"Unable to set {name} :: unsupported value type\")\n\n self.properties[name] = value\n\n @property\n def Title(self):\n if self.properties is None:\n return None\n\n for prop in self.properties.values():\n if prop.id == \"title\":\n return prop.Value\n\n return None\n","sub_path":"notional/records.py","file_name":"records.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"63707717","text":"import datetime\n\nimport discord\nimport pytz\nfrom discord.ext import commands\nfrom textblob import TextBlob\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\nimport asyncio\n\nimport TOKEN\nfrom Modules.Default import Default\nfrom Modules.Mods import Mods\nfrom Modules.Roles import Roles\nfrom Modules.MyHelp import MyHelp\nfrom Modules.Authentication import Authentication\nfrom Modules.Checks import check_if_bot_spam\nfrom Modules import CONSTANT\n\nBOT_DESCRIPTION = '''\nR.E.I.N.A. 2.07\n\nRoles and Entertainment Information and Notification Agent\n\nLicensed under WTFPL\n\nUse >help [command] to see the help text of a specific command. \n\nUse bot only in #bot spam\n'''\n\nbot = commands.Bot(command_prefix='>', description=BOT_DESCRIPTION, case_insensitive=True, help_command=MyHelp())\nscheduler = AsyncIOScheduler()\nREACTIONABLES = {}\nCOUNTER_EMOJIS = [\"1️⃣\", \"2️⃣\", \"3️⃣\", \"4️⃣\", \"5️⃣\", \"6️⃣\", \"7️⃣\", \"8️⃣\", \"9️⃣\", \"🔟\"]\n\n\n@bot.listen()\nasync def on_ready():\n print('Ready!')\n print(bot.user.name)\n print(bot.user.id)\n print('------')\n await bot.change_presence(status=discord.Status.online, activity=discord.Game(\">help\"))\n\n if scheduler.state == 0:\n scheduler.add_job(prompt_keisanchuu, \"cron\", day_of_week='sat', hour=22, minute=30, args=[bot, 30])\n scheduler.add_job(prompt_keisanchuu, \"cron\", day_of_week='sat', hour=22, minute=55, args=[bot, 5])\n scheduler.add_job(prompt_radio, \"cron\", day_of_week='sat', hour=15, minute=30, args=[bot, 30])\n scheduler.add_job(prompt_radio, \"cron\", day_of_week='sat', hour=15, minute=55, args=[bot, 5])\n print(\"Background Task Setup finished. \")\n\n scheduler.start()\n print(\"Scheduler started. \")\n\n\n@bot.listen()\nasync def on_message(message):\n # don't respond to ourselves\n if message.author == bot.user:\n return\n if \"reina\" in message.content.lower().split():\n text = TextBlob(message.content.lower())\n if text.polarity >= 0.3:\n await message.add_reaction('♥️')\n if text.polarity <= -0.3:\n await message.add_reaction('💔')\n\n\n@bot.listen()\nasync def on_member_join(member):\n new_member_role = bot.get_channel(465158208978157588).guild.get_role(663581221967757313)\n await member.add_roles(new_member_role)\n\n\n@bot.listen()\nasync def on_reaction_add(reaction, user):\n if reaction.message.id in REACTIONABLES and user.id != bot.user.id:\n bot_msg = await reaction.message.channel.fetch_message(reaction.message.id)\n\n if REACTIONABLES[reaction.message.id][\"user\"] == user.id: # is the user reacted the user sent the message\n if REACTIONABLES[reaction.message.id][\"category\"] == \"subscription\" and reaction.emoji in COUNTER_EMOJIS:\n reaction_index = COUNTER_EMOJIS.index(reaction.emoji)\n\n if reaction_index < len(REACTIONABLES[reaction.message.id][\"operable\"]): # verify reaction\n role = reaction.message.guild.get_role(REACTIONABLES[reaction.message.id][\"operable\"][reaction_index])\n\n if REACTIONABLES[reaction.message.id][\"type\"] == \"add\":\n await user.add_roles(role)\n elif REACTIONABLES[reaction.message.id][\"type\"] == \"remove\":\n await user.remove_roles(role)\n await bot_msg.edit(content=\"Subscription configured. \", embed=None)\n\n await bot_msg.clear_reactions()\n await asyncio.sleep(5)\n await bot_msg.delete()\n del REACTIONABLES[reaction.message.id]\n\n\nasync def prompt_keisanchuu(bot_b, t_minus):\n now = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))\n\n tv_radio_channel = bot.get_channel(465158208978157588)\n keisanchuu_role = tv_radio_channel.guild.get_role(641112458291052584)\n\n await tv_radio_channel.trigger_typing()\n\n alert_embed = discord.Embed(title=\"Keisanchu Reminder\",\n type='rich',\n description=\"Hey guys! Time now is `{}`, The next episode of 22/7 {} is airing in **{} minutes**.\\n\"\n \"You can watch it at:\".format(now.strftime('%Y-%m-%d %H:%M %Z'),\n keisanchuu_role.mention, t_minus))\n\n alert_embed.add_field(name=\"Link 1\", value=\"https://www.zhanqi.tv/873082427\")\n alert_embed.add_field(name=\"Link 2\", value=\"https://ok.ru/videoembed/2261404032759\")\n alert_embed.add_field(name=\"Link 3\", value=\"https://vk.com/videos-177082369\")\n alert_embed.set_image(url=\"https://www.nanabunnonijyuuni.com/assets/img/tv/img_tv_visual.jpg\")\n\n alert_embed.set_footer(text='R.E.I.N.A. scheduled message.', icon_url=bot_b.user.avatar_url)\n\n await tv_radio_channel.send(content=keisanchuu_role.mention, embed=alert_embed)\n\n\nasync def prompt_radio(bot_b, t_minus):\n now = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))\n\n tv_radio_channel = bot_b.get_channel(465158208978157588)\n radio_role = tv_radio_channel.guild.get_role(694627966495490078)\n\n await tv_radio_channel.trigger_typing()\n alert_embed = discord.Embed(title='Warikirenai Plus Radio Reminder',\n type='rich',\n description=\"Hey guys! Time now is `{}`, This week's {} Plus will start in **{} minutes**. \\n\\n\"\n \"If it's your first time viewing, you will be directed to a page requesting some simple demographics info. \\n\"\n \"Fill out the form as best you can and click the bottom button to proceed to the stream.\".format(now.strftime('%Y-%m-%d %H:%M %Z'), radio_role.mention, t_minus))\n\n alert_embed.add_field(name='You can watch it at',\n value='http://www.uniqueradio.jp/agplayerf/player3.php')\n alert_embed.set_footer(text='R.E.I.N.A. scheduled message.', icon_url=bot_b.user.avatar_url)\n alert_embed.set_image(url='https://pbs.twimg.com/media/EUcZFgcUUAA43Rp?format=jpg&name=small')\n\n await tv_radio_channel.send(content=radio_role.mention, embed=alert_embed)\n\n\nclass Subscribe(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self._last_member = None\n\n @commands.command()\n @check_if_bot_spam()\n async def subscribe(self, ctx):\n \"\"\"\n Subscribe to a regular program's notification.\n \"\"\"\n user_roles = ctx.author.roles\n subscribable_roles = [ctx.guild.get_role(x) for x in CONSTANT.SUBSCRIBABLE]\n\n user_subscribed = list(set(user_roles) & set(subscribable_roles))\n\n # get subscribe-able roles\n user_subscribable = list(set(subscribable_roles) - set(user_subscribed))\n\n if len(user_subscribable) == 0:\n bot_msg = await ctx.send(\"Since you subscribed to all programs, you have no programs you can subscribe to. \")\n await asyncio.sleep(3)\n await ctx.message.delete()\n await bot_msg.delete()\n return\n\n description_str = \"\"\n for emoji, role in zip(COUNTER_EMOJIS, user_subscribable):\n description_str += \"{} {}\\n\".format(emoji, role.name)\n\n # make embed\n sub_embed = discord.Embed(title=\"Choose a reaction to subscribe\",\n colour=discord.Color.red(),\n description=description_str)\n sub_embed.set_author(name=\"You can subscribe to the following program(s)\")\n sub_embed.set_footer(text=\"Note: you must react to the message within 60 seconds. \")\n\n sub_msg = await ctx.send(embed=sub_embed)\n\n # add reactions\n for _, emoji in zip(user_subscribable, COUNTER_EMOJIS):\n await sub_msg.add_reaction(emoji)\n\n REACTIONABLES[sub_msg.id] = {\n \"category\": \"subscription\",\n \"type\": \"add\",\n \"user\": ctx.author.id,\n \"operable\": [role.id for role in user_subscribable]\n }\n\n await asyncio.sleep(3)\n await ctx.message.delete()\n await asyncio.sleep(60)\n if sub_msg.id in REACTIONABLES:\n await sub_msg.delete()\n del REACTIONABLES[sub_msg.id]\n\n @commands.command()\n @check_if_bot_spam()\n async def unsubscribe(self, ctx):\n \"\"\"\n Unsubscribe to a regular program's notification.\n \"\"\"\n user_roles = ctx.author.roles\n subscribable_roles = [ctx.guild.get_role(x) for x in CONSTANT.SUBSCRIBABLE]\n\n user_subscribed = list(set(user_roles) & set(subscribable_roles))\n\n if len(user_subscribed) == 0:\n bot_msg = await ctx.send(\"Since you subscribed to no program, you have no programs to unsubscribe to. \")\n await asyncio.sleep(3)\n await ctx.message.delete()\n await bot_msg.delete()\n return\n\n description_str = \"\"\n for index, role in enumerate(user_subscribed):\n description_str += \"{}. {}\\n\".format(index + 1, role.name)\n\n # make embed\n sub_embed = discord.Embed(title=\"Choose a reaction to unsubscribe\",\n colour=discord.Color.red(),\n description=description_str)\n sub_embed.set_author(name=\"You can unsubscribe to the following program(s)\")\n sub_embed.set_footer(text=\"Note: you must react to this message within 60 seconds. \")\n\n sub_msg = await ctx.send(embed=sub_embed)\n\n # add reactions\n for _, emoji in zip(user_subscribed, COUNTER_EMOJIS):\n await sub_msg.add_reaction(emoji)\n\n REACTIONABLES[sub_msg.id] = {\n \"category\": \"subscription\",\n \"type\": \"remove\",\n \"user\": ctx.author.id,\n \"operable\": [role.id for role in user_subscribed]\n }\n\n await asyncio.sleep(3)\n await ctx.message.delete()\n await asyncio.sleep(60)\n if sub_msg.id in REACTIONABLES:\n await sub_msg.delete()\n del REACTIONABLES[sub_msg.id]\n\n @subscribe.error\n @unsubscribe.error\n async def command_error(self, ctx, error):\n bot_channel = ctx.guild.get_channel(336287198510841856)\n if isinstance(error, commands.CheckFailure):\n message = await ctx.send('Please proceed your action at {} (deletion in 5s)'.format(bot_channel.mention))\n await asyncio.sleep(1)\n for i in range(4, 0, -1):\n await message.edit(\n content=\"Please proceed your action at {} (deletion in {}s)\".format(bot_channel.mention, i))\n await asyncio.sleep(1)\n await message.delete()\n await ctx.message.delete()\n\n\nbot.add_cog(Default(bot))\nbot.add_cog(Roles(bot))\nbot.add_cog(Mods(bot))\nbot.add_cog(Subscribe(bot))\nbot.add_cog(Authentication(bot))\nbot.run(TOKEN.TOKEN)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":10879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"341621863","text":"import json\r\nimport requests\r\nfrom config import keys\r\nclass ConvertionException(Exception):\r\n pass\r\n\r\nclass CryptoConverter():\r\n @staticmethod\r\n def get_price(quote: str, base: str, amount: str):\r\n if quote == base:\r\n raise ConvertionException(f'Невозможно конвертировать одну и ту же валюту {base}')\r\n if quote not in keys.keys():\r\n raise ConvertionException(f'Неверный ввод {quote}')\r\n elif base not in keys.keys():\r\n raise ConvertionException(f'Неверный ввод {base}')\r\n try:\r\n quote_ticker = keys[quote]\r\n except KeyError:\r\n raise ConvertionException(f'Не удалось обработать валюту {quote}')\r\n try:\r\n base_ticker = keys[base]\r\n except KeyError:\r\n raise ConvertionException(f'Не удалось обработать валюту {base}')\r\n try:\r\n amount = float(amount)\r\n if amount < 3:\r\n raise ConvertionException('Неправильно указаны параметры запроса.')\r\n except ValueError:\r\n raise ConvertionException(f'Не удалось обработать кол-во {amount}')\r\n\r\n\r\n\r\n r = requests.get(f'https://min-api.cryptocompare.com/data/price?fsym={quote_ticker}&tsyms={base_ticker}')\r\n total_base = json.loads(r.content)[keys[base]]\r\n total_base = total_base * amount\r\n return total_base\r\n\r\n","sub_path":"extensions.py","file_name":"extensions.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"376701199","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom time import time\nimport tensorflow as tfa\nimport os\nimport tensorflow.examples.tutorials.mnist.input_data as input_data\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\ntf = tfa.compat.v1\n\nckpt_dir = './ckpt_dir/'\nif not os.path.exists(ckpt_dir):\n os.mkdir(ckpt_dir)\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nx = tf.placeholder(tf.float32, [None, 784], 'X') # 输入参数\ny = tf.placeholder(tf.float32, [None, 10], 'Y') # 输出参数\n\n\n# 隐藏神经元的数量\nH1_NN = 256\nH2_NN = 64\n\ndef fcn_layer(inputs, input_dim, output_dim, activation=None):\n \"\"\"\n 全连接层函数\n :param inputs: 输入数据\n :param input_dim: 输入神经元数量\n :param output_dim: 输出神经元数量\n :param activation: 激活函数\n :return: 该层的输出结果\n \"\"\"\n # 以截断正态分布的随机函数初始化\n W = tf.Variable(tf.truncated_normal([input_dim, output_dim], stddev=0.1))\n # 以0初始化b\n b = tf.Variable(tf.zeros([output_dim]))\n\n XWb = tf.matmul(inputs, W) + b # 建立表达式:inputs * W + b\n\n if activation is None: # 默认不使用激活函数\n outputs = XWb\n else: # 若传入激活函数,则对其输出结果进行变换\n outputs = activation(XWb)\n\n return outputs\n\nh1 = fcn_layer(inputs=x, input_dim=784, output_dim=H1_NN, activation=tf.nn.relu)\nh2 = fcn_layer(inputs=h1, input_dim=H1_NN, output_dim=H2_NN, activation=tf.nn.relu)\nforward = fcn_layer(inputs=h2, input_dim=H2_NN, output_dim=10)\npred = tf.nn.softmax(forward)\n\n# 使用交叉熵作为损失函数,这个方式会造成log(0)值为NaN,最后数据不稳定的问题\n# loss_function = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))\n\n# TensorFlow提供了结合Softmax的交叉熵损失函数定义方法,其中参数为没有经过Softmax处理的数据\nloss_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=forward, labels=y))\n\n# 定义准确率\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(pred, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n# 输入的样本图像加入summary\nimage_shaped_input = tf.reshape(x, [-1, 28, 28, 1])\ntf.summary.image('input', image_shaped_input, 10) # 10为最大输出显示图像\n\n# 前向输出值以直方图显示\ntf.summary.histogram('forward', forward)\n\n# loss损失值和accuracy准确率以标量显示\ntf.summary.scalar('loss', loss_function)\ntf.summary.scalar('accuracy', accuracy)\n\n# 设置训练参数\ntrain_epochs = 40\nbatch_size = 50\ntotal_size = int(mnist.train.num_examples/batch_size)\ndisplay_step = 1\nlearning_rate = 0.01\nsave_step = 5 # 保存粒度\n\n# 选择优化器\noptimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss_function)\n\n# 记录训练开始时间\nstartTime = time()\n\n# 声明完所有变量后,调用该保存函数\nsaver = tf.train.Saver()\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n# 合并所有summary\nmerged_summary_op = tf.summary.merge_all()\nwriter = tf.summary.FileWriter('./logs/', sess.graph) # 创建写入符\n\nfor epoch in range(train_epochs):\n for batch in range(total_size):\n xs, ys = mnist.train.next_batch(batch_size) # 读取批次数据\n sess.run(optimizer, feed_dict={x:xs, y:ys}) # 执行批次训练\n\n # 生成summary\n summary_str = sess.run(merged_summary_op, feed_dict={x:xs, y:ys})\n writer.add_summary(summary_str, epoch) # 将summary写入文件\n\n # total_batch个批次训练完成后,使用验证数据计算误差与准确率\n loss, acc = sess.run([loss_function, accuracy],\n feed_dict={x:mnist.validation.images,\n y:mnist.validation.labels})\n\n if (epoch+1) % display_step == 0:\n print(\"Train Epoch:\", \"%02d\" % (epoch+1),\n \"Loss=\",\"{:.9f}\".format(loss), \"Accuracy=\", \"{:.4f}\".format(acc))\n\n if (epoch+1) % save_step == 0:\n # 存储模型\n saver.save(sess, os.path.join(ckpt_dir, 'mnist_h256_64_model_{:06d}.ckpt'.format(epoch+1)))\n print('mnist_h256_64_model_{:06d}.ckpt saved'.format(epoch+1))\n\n\nsaver.save(sess, os.path.join(ckpt_dir, 'mnist_h256_64_model.ckpt'))\nprint(\"Model saved\")\n# 显示运行总时间\nduration = time() - startTime\nprint(\"Train Finished takes:\", \"{:.2}\".format(duration))\n\n\ndef print_predict_errs(labels, prediction):\n \"\"\"\n 打印出出错的预测结果\n :param labels: 标签列表\n :param prediction: 预测值列表\n :return:\n \"\"\"\n count = 0\n compare_lists = (prediction==np.argmax(labels, 1))\n err_lists = [i for i in range(len(compare_lists)) if compare_lists[i]==False]\n for x in err_lists:\n print(\"index=\"+str(x)+\" 标签值=\", np.argmax(labels[x]), \" 预测值=\", prediction[x])\n count += 1\n\n print(\"总计:\"+str(count))\n\n\nprediction_result = sess.run(tf.argmax(pred, 1), feed_dict={x:mnist.test.images})\nprint_predict_errs(labels=mnist.test.labels, prediction=prediction_result)","sub_path":"LearningTensorFlow/手写数字识别示例/Example_02_01.py","file_name":"Example_02_01.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"32673556","text":"# -*-coding:utf-8-*- \n\"\"\"\n@Author : llame\n@Software: PyCharm\n@Time : 2020/9/23 4:10 下午\n\"\"\"\n\n\ndef min_distance(arr, num1, num2):\n if (num1 not in arr) or (num2 not in arr):\n return -1\n\n mindis = 2 ** 32\n i = 0\n pos1 = -1\n pos2 = -1\n while i < len(arr):\n if arr[i] == num1:\n pos1 = i\n if pos2 > 0:\n dist = abs(pos1 - pos2)\n mindis = min(dist, mindis)\n if arr[i] == num2:\n pos2 = i\n if pos1 > 0:\n dist = abs(pos1 - pos2)\n mindis = min(dist, mindis)\n i += 1\n return mindis\n\n\nif __name__ == '__main__':\n list_array = [4, 5, 6, 4, 7, 4, 6, 4, 7, 8, 5, 6, 4, 3, 10, 8]\n num1 = 4\n num2 = 7\n result=min_distance(list_array,num1,num2)\n print('min distance:',result)\n","sub_path":"algorithm/18-求两个元素的最短距离.py","file_name":"18-求两个元素的最短距离.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"482075214","text":"from pybbix.trigger import EXPRESSION, FUNCTIONS\n\n\ndef test_trigger_expression_fstring_correct_format():\n params = {'server': 1,\n 'key': 2,\n 'function' : 3,\n 'parameter': 4,\n 'operator': 5,\n 'constant': 6,\n }\n assert EXPRESSION.format(**params) == '{1:2.3(4)}56'\n\n\ndef test_functions_list():\n assert {'avg', 'diff', 'nodata', 'change', 'last', 'min', 'str', 'max'} == FUNCTIONS\n","sub_path":"tests/test_trigger.py","file_name":"test_trigger.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"37949142","text":"from threading import *\n\n#\n# # thread error\n# class Singleton():\n# _instance = None\n#\n# def __new__(cls, *args, **kw):\n# if not cls._instance:\n# cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)\n# return cls._instance\n\n#\n# class SingletonMixin():\n# __singleton_lock = Lock()\n# __singleton_instance = None\n#\n# @classmethod\n# def instance(cls):\n# if not cls.__singleton_instance:\n# with cls.__singleton_lock:\n# if not cls.__singleton_instance:\n# cls.__singleton_instance = cls()\n# return cls.__singleton_instance\n#\n# import threading\n#\n# class Singleton():\n# INSTANCE = None\n# lock = threading.RLock()\n# def __new__(cls):\n# cls.lock.acquire()\n# if cls.INSTANCE is None:\n# cls.INSTANCE = super(Singleton, cls).__new__(cls)\n# cls.lock.release()\n# return cls.INSTANCE\n\n\n# A thread-safe implementation of Singleton pattern\n# To be used as mixin or base class\nclass Singleton():\n __lock = RLock()\n __instance = None\n @classmethod\n def getInstance(cls):\n if not cls.__instance:\n with cls.__lock:\n if not cls.__instance:\n cls.__instance = cls()\n return cls.__instance\n\n\nclass testclase(Singleton):\n def __init__(self):\n self.a=\"test\"\n\nif __name__ == '__main__':\n a = testclase.getInstance()\n b = testclase.getInstance()\n print (id(a),a.a)\n print(id(a.a) , id(b.a))\n assert id(a.a) == id(b.a)","sub_path":"sample/pattern/singleton.py","file_name":"singleton.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"483014944","text":"import cv2\r\n\r\nperson = cv2.imread('ostad.jpg', 0)\r\n\r\nfor i in range(300):\r\n if i <= 150:\r\n for j in range(150-i, 300-i):\r\n if (j >= 0):\r\n person[i, j] = 0\r\n else:\r\n for j in range(0, 300-i):\r\n if (j >= 0):\r\n person[i, j] = 0\r\n \r\ncv2.imwrite('ostad.jpg', person)\r\ncv2.imshow('m', person)\r\ncv2.waitKey()","sub_path":"5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"172999520","text":"from pyspark import SparkConf, SparkContext\nfrom operator import add\nimport sys\n\nAPP_NAME = \"file_length\"\n\ndef main(sc, filename):\n\t#by default, each block creates a partition\n\t#you can also specify the number of partition as the second argument in textFile\n\ttextRDD = sc.textFile(filename)\n\tlength = textRDD.map(lambda s: len(s)).reduce(lambda a, b: a + b) \n\tprint(\"length: %i\" % length)\n\t\nif __name__ == \"__main__\":\n\tconf = SparkConf().setAppName(APP_NAME).setMaster(\"yarn\")\n\tsc = SparkContext(conf=conf)\n\tfilename = \"/user/jimmy/submit.sh\"\n\tmain(sc, filename)\n","sub_path":"spark/sandbox/file_length.py","file_name":"file_length.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"337256128","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.cluster import KMeans\nfrom kneed import KneeLocator\nfrom imblearn.over_sampling import SMOTE, RandomOverSampler\nfrom IPython.display import Markdown, display\n\nclass EasyPreProcessing:\n \"\"\"\n Create an object of type EasyPreProcessing\n \n Attributes:\n path (str):\n dataset (DataFrame): \n output (str): \n categorical (CategoryFeatures): \n numerical (NumericFeatures):\n clustering (Clustering): \n dates (DateTimeFeatures): \n \"\"\"\n def __init__(self, path):\n self.path = path\n self.dataset = self.load_dataframe(path)\n self.output = None\n self.categorical = CategoryFeatures(self)\n self.numerical = NumericFeatures(self)\n self.clustering = Clustering(self)\n self.dates = DateTimeFeatures(self)\n printmd(\"\"\"\n**Initialization Parameters**\n\n1. output - Set output variable/dependent variable\n2. dates.features - Set datetime field names (optional)\n\nFor example:\n1. output = 'column_name'\n2. dates.features = ['date_field_1','date_field_2']\n \"\"\")\n \n @property\n def data(self):\n return self.dataset\n \n @property\n def df(self):\n return self.dataset\n \n @property\n def missing_values(self):\n return self.dataset.isnull().sum()\n \n @property\n def columns(self):\n return self.dataset.columns\n\n @property\n def info(self):\n printmd(\"\"\"\n\n**General Template**\n\nfrom easypreprocessing import EasyPreProcessing\nprep = EasyPreProcessing('filename_here.csv')\nprep.df\nprep.output = 'output_variable_here'\nprep.remove_blank()\nprep.missing_values\nprep.categorical.impute()\nprep.numerical.impute()\nprep.categorical.encode()\nprep.correction()\nprep.standardize()\nX_train, X_test, y_train, y_test = prep.split()\n\n\n\n**Categorical Preprocessing**\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    categorical.fieldsDisplay all categorical field names
    categorical.uniqueDisplay unique/distinct categorical values
    categorical.impute()Handle categorical missing values. Parameters {'mean', 'medium', 'mode'}
    categorical.encode()Encode categorical features. Parameters {'le': LabelEncoding, 'ohe': OneHotEncoding}
    \n\n**Numerical Preprocessing**\n\n\n\n\n\n\n\n
    numerical.fieldsDisplay all numerical field names
    numerical.impute()Handle numerical missing values. Parameters {'mean', 'medium', 'mode'}
    \n\n**Date Preprocessing**\n\n\n\n\n\n\n\n
    dates.featuresDefine list of all datetime feature names
    dates.split_datetime()Split all datetime features into discrete fields (Year, Month, Day, Hour, Minute)
    \n\n**General Preprocessing**\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
    missing_valuesDisplay missing value report
    remove_blank()Remove empty/blank columns
    correction()Display correction heatmap
    standardize()Standardize entire dataset except dependent variable
    encode_output()Encode dependent feature/output variable
    over_sample()Oversample dataset. Parameters {'smote': SMOTE, 'ros': RandomOverSample}
    clustering.apply()Cluster dataset using elbow plot
    \n \"\"\")\n\n def load_dataframe(self, path):\n return pd.read_csv(path)\n \n @property\n def fields(self):\n return self.dataset.columns\n\n def reinit(self):\n self.dataset = self.load_dataframe(self.path)\n \n def get_X(self):\n return self.dataset[self.dataset.columns.difference([self.output])]\n\n def get_Y(self):\n return self.dataset[self.output]\n\n def split(self, test_size = 0.2, random_state = 0):\n self.X = self.get_X().values\n self.y = self.get_Y().values\n return train_test_split(self.X, self.y, test_size = test_size, random_state = random_state)\n\n def standardize(self):\n self.dataset[self.__get_unique_numerical()] = pd.DataFrame(StandardScaler().fit_transform(self.dataset[self.__get_unique_numerical()]))\n print('Dataset has been standardized.')\n \n def correction(self):\n sns.heatmap(self.dataset.corr())\n \n def remove_blank(self):\n emply_columns = [col for col in self.dataset.columns if self.dataset[col].isnull().all()]\n self.dataset = self.dataset.drop(emply_columns, axis=1)\n\n def __get_unique_numerical(self):\n return [col for col in list(self.dataset.columns) if (self.dataset[col].dtype in ['float64', 'int64', 'int32']) and self.output != col]\n \n def encode_output(self):\n self.dataset[self.output] = pd.DataFrame(preprocessing.LabelEncoder().fit_transform(self.dataset[self.output]))\n print('Label encoded the output variable.')\n\n def over_sample(self, strategy='random'):\n \"\"\"\n This method will over sample your dataset to balance your output variable/dependent feature.\n \n Parameters: \n strategy (str): {'random': RandomOverSampling, 'smote':SMOTE }. Default random\n \n Returns: \n None\n \"\"\"\n if strategy == 'smote':\n print('Sampling method selected: SMOTE')\n smt = SMOTE()\n X_train, y_train = smt.fit_resample(self.get_X(), self.get_Y())\n self.dataset = pd.concat([X_train, pd.DataFrame(y_train)], axis=1)\n if strategy == 'random':\n print('Sampling method selected: RandomOverSampling')\n ros = RandomOverSampler()\n X_train, y_train = ros.fit_resample(self.get_X(), self.get_Y())\n self.dataset = pd.concat([X_train, pd.DataFrame(y_train)], axis=1)\n print('Oversampling completing.')\n\nclass DateTimeFeatures:\n def __init__(self, parent):\n self.parent = parent\n self.features = []\n \n def split_datetime(self, drop=True):\n \"\"\"\n This method will split all datetime features into discrete fields (Year, Month, Day, Hour, Minute).\n \n Parameters: \n drop (bool): Drop original datetime field. Default True\n \n Returns: \n None\n \"\"\"\n for col in self.features:\n print('Splitting ', col, '...')\n self.parent.dataset[col + '_Year'] = pd.to_datetime(self.parent.dataset[col]).dt.year\n self.parent.dataset[col + '_Month'] = pd.to_datetime(self.parent.dataset[col]).dt.month\n self.parent.dataset[col + '_Day'] = pd.to_datetime(self.parent.dataset[col]).dt.day\n self.parent.dataset[col + '_Hour'] = pd.to_datetime(self.parent.dataset[col]).dt.hour\n self.parent.dataset[col + '_Minute'] = pd.to_datetime(self.parent.dataset[col]).dt.minute\n if drop == True:\n self.parent.dataset = self.parent.dataset.drop([col], axis = 1)\n print('Dropped column: ', col)\n print('Newly added columns: Year, Month, Day, Hour, Minute')\n\nclass Clustering():\n def __init__(self, parent):\n self.parent = parent\n\n def elbow_plot(self, elbow_limit, init, random_state):\n wcss=[]\n for i in range (1, elbow_limit):\n kmeans=KMeans(n_clusters=i, init=init, random_state=random_state)\n kmeans.fit(self.parent.dataset)\n wcss.append(kmeans.inertia_)\n return KneeLocator(range(1, elbow_limit), wcss, curve='convex', direction='decreasing')\n \n def apply(self, elbow_limit=11, init='k-means++', random_state=42):\n \"\"\"\n Apply KMeans clustering to entire dataset. \"Cluster\" column will be appended to the existing dataset that will mark which cluster does the record belong.\n \n Parameters: \n elbow_limit (int): Elbow limit is required for finding the best K value for clustering. Default 11 or greater.\n init (int): Default 'k-means++'\n random_state (int): Default 42\n \n Returns: \n None\n \"\"\"\n print('Calculate best Knee value for clustering...')\n self.no_clusters = self.elbow_plot(elbow_limit, init, random_state)\n print('Started clustering process...')\n self.kmeans = KMeans(n_clusters=self.no_clusters.knee, init=init, random_state=random_state)\n self.kmeans_clusters_list = self.kmeans.fit_predict(self.parent.dataset)\n self.parent.dataset['Cluster'] = self.kmeans_clusters_list\n print('Number of clusters created:', len(np.unique(self.kmeans_clusters_list)))\n\nclass NumericFeatures():\n def __init__(self, parent):\n self.parent = parent\n\n @property\n def fields(self):\n \"\"\"\n Get list of all names of numerical columns/features.\n \n Parameters: \n None\n \n Returns: \n list\n \"\"\"\n return self.__get_unique_numerical()\n \n def __get_unique_numerical(self):\n return [col for col in list(self.parent.dataset.columns) if self.parent.dataset[col].dtype == 'float64' or self.parent.dataset[col].dtype == 'int64']\n \n def impute(self, strategy='mean'):\n \"\"\"\n Method to impute numerical features.\n \n Parameters:\n strategy (str): {'mean', 'median', 'mode'}. Default 'mean'\n \n Returns:\n None\n \"\"\"\n imputer = SimpleImputer(missing_values = np.nan, strategy = strategy)\n self.parent.dataset[self.__get_unique_numerical()] = imputer.fit_transform(self.parent.dataset[self.__get_unique_numerical()])\n print('Numerical features imputated successfully.')\n\nclass CategoryFeatures():\n def __init__(self, parent):\n self.parent = parent\n \n @property\n def fields(self):\n \"\"\"\n Get list of all names of categorical columns/features.\n \n Parameters: \n None\n \n Returns: \n list\n \"\"\"\n return self.__get_unique_categorical()\n\n @property\n def unique(self):\n \"\"\"\n Print unique or distinct values of all categorical features.\n \n Parameters: \n None\n \n Returns: \n None\n \"\"\"\n for category in self.__get_unique_categorical():\n unique_values = self.parent.dataset[category].unique()\n print(str(category) + ' ' + str(unique_values))\n \n def __get_unique_categorical(self):\n return [col for col in list(self.parent.dataset.columns) if self.parent.dataset[col].dtype == 'object' and self.parent.output != col]\n \n def get_feature_mode(self, column):\n return self.parent.dataset[column].mode().values[0]\n\n def impute(self):\n \"\"\"\n Method to impute numerical features. Strategy 'mode' by default.\n \n Returns: \n None\n \"\"\"\n for col in list(self.__get_unique_categorical()):\n mode = self.get_feature_mode(col)\n self.parent.dataset[col].fillna(mode, inplace=True)\n print('Categorical features imputated successfully.')\n \n def label_encoder(self):\n self.parent.dataset[self.__get_unique_categorical()] = self.parent.dataset[self.__get_unique_categorical()].apply(preprocessing.LabelEncoder().fit_transform)\n\n def onehotencoder(self):\n encoded_data = pd.get_dummies( self.parent.dataset.drop([self.parent.output], axis=1) )\n self.parent.dataset = pd.concat( [encoded_data , self.parent.dataset[self.parent.output] ] , axis=1)\n\n def encode(self, strategy='ohe'):\n \"\"\"\n Encoding categorical features using LabelEncoding or OneHotEncoding.\n \n Parameters:\n strategy (str): {'ohe','le'}. Default 'ohe'.\n 'ohe': OneHotENcoding\n 'le': LabelEnoding\n \n Returns:\n None\n \"\"\"\n if strategy == 'ohe':\n self.onehotencoder()\n print('Dataset has been succesfully encoded using OneHotEncoder')\n if strategy == 'le':\n self.label_encoder()\n print('Dataset has been succesfully encoded using LabelEncoder')\n\ndef printmd(string):\n display(Markdown(string))\n\n","sub_path":"build/scripts-3.6/easypreprocessing.py","file_name":"easypreprocessing.py","file_ext":"py","file_size_in_byte":12524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"179697570","text":"import csv\nimport pickle\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential, Model\nfrom keras.layers import Flatten, Dense, Lambda, Activation, Dropout, Cropping2D\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\n\ndef generator(samples, batch_size=100):\n\tnum_samples = len(samples)\n\t# batch_size = int(batch_size / 4)\n\twhile 1:\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\timages = []\n\t\t\tangles = []\n\t\t\tfor batch_sample in batch_samples:\n\t\t\t\tangle = float(batch_sample[3])\n\t\t\t\tcorrection = 0.2\n\n\t\t\t\t# CENTER\n\t\t\t\timage = get_image(line[0])\n\t\t\t\timages.append(image)\n\t\t\t\tangles.append(angle)\n\n\t\t\t\t# Augmenting images by flipping across y-axis\n\t\t\t\timages.append(cv2.flip(image, 1))\n\t\t\t\tangles.append(-angle)\n\n\t\t\t\t# LEFT\n\t\t\t\timages.append(get_image(line[1]))\n\t\t\t\tangles.append(angle + correction)\n\n\t\t\t\t# RIGHT\n\t\t\t\timages.append(get_image(line[2]))\n\t\t\t\tangles.append(angle - correction)\n\n\t\t\tX_train = np.array(images)\n\t\t\ty_train = np.array(angles)\n\t\t\tyield shuffle(X_train, y_train)\n\ndef read_data_from_file(data_path='data/'):\n\tlines = []\n\twith open(data_path + 'driving_log.csv') as csvfile:\n\t\treader = csv.reader(csvfile)\n\t\tfor line in reader:\n\t\t\tlines.append(line)\n\n\timages = []\n\tangles = []\n\tfor line in lines:\n\t\tangle = float(line[3])\n\t\tcorrection = 0.2\n\n\t\t# CENTER\n\t\timage = get_image(line[0], data_path)\n\t\timages.append(image)\n\t\tangles.append(angle)\n\n\t\t# Augmenting images by flipping across y-axis\n\t\timages.append(cv2.flip(image, 1))\n\t\tangles.append(-angle)\n\n\t\t# LEFT\n\t\timages.append(get_image(line[1], data_path))\n\t\tangles.append(angle + correction)\n\n\t\t# RIGHT\n\t\timages.append(get_image(line[2], data_path))\n\t\tangles.append(angle - correction)\n\n\tX_train = np.array(images)\n\ty_train = np.array(angles)\n\n\treturn (X_train, y_train)\n\ndef store_in_pickle(data, filename='data.p'):\n\tpickle.dump(data, open(filename, 'wb'))\n\tprint(\"Stored data in {}\".format(filename))\n\ndef get_image(path, base_path='../data/'):\n\t# load image and conver to RGB\n\tfilename = path.split('/')[-1]\n\tpath = base_path + 'IMG/' + filename\n\timage = cv2.imread(path)\n\timage = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\treturn image\n\n\nif __name__ == '__main__':\n\t# lines = []\n\t# with open('../data/driving_log.csv') as csvfile:\n\t# \treader = csv.reader(csvfile)\n\t# \tfor line in reader:\n\t# \t\tlines.append(line)\n\n\t# train_samples, validation_samples = train_test_split(lines, test_size=0.2, random_state=51)\n\n\t# batch_size = 25\n\t# train_generator = generator(train_samples, batch_size)\n\t# validation_generator = generator(validation_samples, batch_size)\n\n\t# load data \n\tX_train, y_train = read_data_from_file('../data/')\n\t\n\t# Defining the model\n\tmodel = Sequential()\n\tmodel.add(Lambda(lambda x: x / 255.0 - 0.5 , input_shape=(160, 320, 3)))\n\tmodel.add(Cropping2D(cropping=((70, 25), (0, 0))))\n\tmodel.add(Conv2D(24, (5, 5), strides=2, activation='relu'))\n\tmodel.add(Conv2D(36, (5, 5), strides=2, activation='relu'))\n\tmodel.add(Conv2D(48, (5, 5), strides=2, activation='relu'))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu'))\n\tmodel.add(Conv2D(64, (3, 3), activation='relu'))\n\tmodel.add(Flatten())\n\tmodel.add(Dense(1164))\n\tmodel.add(Dropout(0.3))\n\tmodel.add(Dense(100))\n\tmodel.add(Dropout(0.3))\n\tmodel.add(Dense(50))\n\tmodel.add(Dense(10))\n\tmodel.add(Dense(1))\n\n\tmodel.compile(loss='mse', optimizer='adam')\n\thistory_object = model.fit(X_train, y_train, validation_split=0.2, shuffle=True, epochs=5, batch_size=100)\n\t# history_object = model.fit_generator(train_generator,\n\t# \t\t\t\t\t\t\t\t\t steps_per_epoch=len(train_samples)/batch_size,\n\t# \t\t\t\t\t\t\t\t\t validation_data=validation_generator,\n\t# \t\t\t\t\t\t\t\t\t validation_steps=len(validation_samples)/batch_size,\n\t# \t\t\t\t\t\t\t\t\t epochs=5)\n\n\tprint(history_object.history.keys())\n\n\t# Plot the training and validation loss for each epoch\n\tplt.plot(history_object.history['loss'])\n\tplt.plot(history_object.history['val_loss'])\n\tplt.title('model mean squared error loss')\n\tplt.ylabel('mean squared error loss')\n\tplt.xlabel('epoch')\n\tplt.legend(['training set', 'validation set'], loc='upper right')\n\tplt.show()\n\n\t# Save model for use by drive\n\tmodel.save('model.h5')","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"621022256","text":"# Copyright 2020 Nokia\n# Licensed under the Apache License 2.0.\n# SPDX-License-Identifier: Apache-2.0\n\nimport json\nindex_keys = ['name','id','index','sequence-id','buffer-name','address']\n\nclass jsondiff(object):\n \"\"\"\n Class to find json diff\n \"\"\"\n def __init__(self):\n pass\n def compare(self, newjsonfile, oldjsonfile):\n with open(newjsonfile, \"r\") as f:\n newjson = json.load(f)\n with open(oldjsonfile, \"r\") as f:\n oldjson = json.load(f)\n return self.cmp_dict(newjson, oldjson)\n\n def cmp_dict(self, new, old, parent=\"\"):\n result=[]\n keydiff = self._get_dict_key_diff(new, old)\n\n #step1 removed\n for k in keydiff[\"---\"]:\n result.append({\n \"---\":\"{}[{}]\".format(parent, k),\n \"value\":old[k]\n })\n #step2 added\n for k in keydiff[\"+++\"]:\n result.append({\n \"+++\":\"{}[{}]\".format(parent, k),\n \"value\": new[k]\n })\n\n #step3 modified\n for k in keydiff[\"common\"]:\n if isinstance(old[k] ,dict) and isinstance(new[k] ,dict):\n res = self.cmp_dict(new[k], old[k], parent =\"{}[{}]\".format(parent, k))\n result.extend(res)\n elif isinstance(old[k], list) and isinstance(new[k] ,list):\n res = self._cmp_list(new[k],old[k],parent =\"{}[{}]\".format(parent,k))\n result.extend(res)\n else:\n if not old[k] == new[k]:\n result.append({\n \"chg\": \"{}[{}]\".format(parent, k),\n \"old_value\": old[k],\n \"new_value\":new[k]\n })\n\n return result\n\n def _find_index_key(self, old_dicts):\n max_ct = 0\n key = None\n for i in index_keys:\n ct = 0\n for o in old_dicts:\n for k,v in o.items():\n if k==i:\n ct = ct +1\n continue\n if ct >max_ct:\n max_ct = ct\n key = i\n if not max_ct==0:\n return key\n #find key either string or int and present in all/many dict and is unique\n\n print(\"{}\\nType index key for above list:\".format(old_dicts))\n return str(input())\n\n def _cmp_list(self, new, old_in, parent=\"\"):\n result = []\n old = old_in[:] # to capture ---\n old_dicts = [o for o in old if isinstance(o, dict)]\n old_has_list = any([o for o in old if isinstance(o, list)])\n ind_key = None\n if len(old_dicts) >1 :\n ind_key = self._find_index_key(old_dicts)\n for index,n in enumerate(new):\n\n # either n shd be in old\n # or n not in old , n is a dict and n not have indexkey\n # or n not in old , n is a dict and n have indexkey but no matching o\n # or n not in old , n is a dict and n have indexkey but has matching o to compare\n\n if n in old_in:\n if n in old: #if duplicat n is already removed.\n old.remove(n)\n continue\n elif isinstance(n, dict):\n if len(old_dicts) == 0:\n result.append({\n \"+++\": \"{}[{}]\".format(parent, index),\n \"value\": n\n })\n continue\n elif len(old_dicts) == 1:\n res = self.cmp_dict(n,old_dicts[0],\"{}[{}]\".format(parent,index) )\n result.extend(res)\n old.remove(old_dicts[0])\n continue\n elif not ind_key in n.keys():\n result.append({\n \"+++\":\"{}[{}]\".format(parent,index),\n \"value\": n\n })\n continue\n else:\n ind_key_value = n[ind_key]\n o_to_compare = [o for o in old if ind_key in o and o[ind_key]==ind_key_value]\n if len(o_to_compare)==0:\n result.append({\n \"+++\": \"{}[{}]\".format(parent, index),\n \"value\": n\n })\n continue\n else:\n o_to_compare = o_to_compare[0]\n old.remove(o_to_compare)\n res = self.cmp_dict(n, o_to_compare, \"{}[{}]\".format(parent, index))\n result.extend(res)\n elif isinstance(n, list):\n if not old_has_list:\n result.append({\n \"+++\": \"{}[{}]\".format(parent, index),\n \"value\": n\n })\n continue\n else:\n for o in old:\n if isinstance(o, list):\n old.remove(o)\n res = self._cmp_list(n,o,\"{}[{}]\".format(parent, index))\n result.extend(res)\n continue\n #if no more list available in o\n result.append({\n \"+++\": \"{}[{}]\".format(parent, index),\n \"value\": n\n })\n continue\n else:\n result.append({\n \"+++\": \"{}[{}]\".format(parent, index),\n \"value\": n\n })\n if old:\n for index,o in enumerate(old_in):\n if o in old:\n result.append({\n \"---\": \"{}[{}]\".format(parent, index),\n \"value\": o\n })\n return result\n\n def _get_dict_key_diff(self, new, old):\n d1_keys = new.keys()\n d2_keys = old.keys()\n plus_ks = [k for k in d1_keys if k not in d2_keys]\n minus_ks = [k for k in d2_keys if k not in d1_keys]\n return {\n \"+++\":plus_ks,\n \"---\": minus_ks,\n \"common\": [k for k in d1_keys if k not in plus_ks],\n }","sub_path":"napalm_srl/jsondiff.py","file_name":"jsondiff.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"625375299","text":"#!/usr/bin/env python\n\n\"\"\"\n@Kevin Cortacero \n\"\"\"\n\nimport rospy\nfrom std_msgs.msg import Header, ColorRGBA\nfrom geometry_msgs.msg import Pose, Vector3, Point\nfrom visualization_msgs.msg import Marker\nfrom sensor_msgs import point_cloud2\nfrom human_visual_attention.msg import HumanAttentionArray\nimport colorsys\n\nclass AttentionViz(object):\n\n def __init__(self, attention_topic_sub, body_topic_pub):\n self.debug_pub = rospy.Publisher(body_topic_pub, Marker, queue_size=1)\n self.attention_sub = rospy.Subscriber(attention_topic_sub, HumanAttentionArray, callback=self.callback)\n\n def callback(self, attentions):\n if not attentions.humans:\n return \n markers = Marker(header=attentions.header, type=Marker.POINTS, action=Marker.ADD)\n markers.scale.x = 0.04\n markers.scale.y = 0.04\n\n for h in attentions.humans:\n if h.element_of_attention != 'nothing':\n #center = Marker(header=attentions.header, type=Marker.SPHERE, action=Marker.ADD)\n markers.points.append(h.point_of_attention)\n markers.colors.append(ColorRGBA(r=0, g=1, b=0, a=1))\n\n for element in h.elements:\n max_i = max([p[3] for p in point_cloud2.read_points(element, field_names = (\"x\", \"y\", \"z\", \"intensity\"), skip_nans=True)])\n for p in point_cloud2.read_points(element, field_names = (\"x\", \"y\", \"z\", \"intensity\"), skip_nans=True):\n (r, g, b) = colorsys.hsv_to_rgb(min(1-(p[3]/max_i), 0.8333), 1.0, 1.0)\n markers.points.append(Point(x=p[0], y=p[1], z=p[2]))\n markers.colors.append(ColorRGBA(r=r, g=g, b=b, a=1))\n\n self.debug_pub.publish(markers)\n\n\nif __name__ == '__main__':\n rospy.init_node(\"attention_viz_node\") \n attention_topic_sub = \"/humans/visual/current\"\n body_topic_pub = '/humans/visual/current/viz'\n AttentionViz(attention_topic_sub, body_topic_pub)\n rospy.spin()","sub_path":"human_viz/scripts/attention_viz.py","file_name":"attention_viz.py","file_ext":"py","file_size_in_byte":2000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"275487987","text":"str1 = \"Good\"; \nstr2 = \"morning\"; \n \nprint(\"Strings before swapping: \" + str1 + \" \" + str2); \n \n#Concatenate both the string str1 and str2 and store it in str1 \nstr1 = str1 + str2; \n#Extract str2 from updated str1 \nstr2 = str1[0 : (len(str1) - len(str2))]; \n#Extract str1 from updated str1 \nstr1 = str1[len(str2):]; \n \nprint(\"Strings after swapping: \" + str1 + \" \" + str2); \n","sub_path":"10. String/Create swap 2 strings without temp.py","file_name":"Create swap 2 strings without temp.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"105590552","text":"def fact(n):\n facto = 1\n while(n>1):\n facto*=n\n n-=1\n return facto\n\ndef fact_rec(n):\n if n==1:\n return 1\n else:\n return n*fact(n-1)\n\ndef perfect_num(num):\n sum_fact = 0\n temp_num = num\n while(num>0):\n dig = num%10\n sum_fact+=fact(dig)\n num//=10\n return \"Perfect Number\" if sum_fact==temp_num else \"Not Perfect\"\n\nprint(perfect_num(145))\n","sub_path":"perfect_num.py","file_name":"perfect_num.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"362620517","text":"powitanie = input(\"Podaj swoje imię\")\npowitanie2 =input(\"Cześć \" + powitanie + \" miło mi Ciebie poznać, jest to program przeliczający waluty.Czy jesteś zainteresowany/zainteresowana\")\nif powitanie2 == \"Tak\" or powitanie2 == \"tak\":\n print(\"Dobrze w takim razie podaj walutę, którą chcesz przeliczyć (Do wyboru masz dolar, funt, złotówka)\")\nelse:\n print(\"Dobrze w takim razie dziękuje i życzę miłego dnia\")\n import sys\n sys.exit(0)\nwhile True:\n waluta = input(\"Waluta którą chcesz przeliczyć: \")\n if waluta == \"dolar\" or waluta == \"Dolar\":\n print(\"Wybrałeś/aś pierwszą walutę dolar, na jaką walutę chcesz ją przeliczyć? (funt, złotówka)\")\n elif waluta == \"funt\" or waluta == \"Funt\":\n print(\"Wybrałeś/aś pierwszą walutę funt, na jaką walutę chcesz ją przeliczyć? (dolar, złotówka)\")\n elif waluta == \"złotówka\" or waluta == \"Złotówka\":\n print(\"Wybrałeś/aś pierwszą walutę złotówka, na jaką walutę chcesz ją przeliczyć? (dolar, funt)\")\n else:\n print(\"Wybrałeś/aś walutę której nie obsługujemy\")\n waluta2 = input(\"Waluta na którą chcesz przeliczyć: \")\n if waluta == waluta2:\n print(\"Kwota będzie taka sama :)\")\n elif waluta2 == \"dolar\" or waluta2 == \"Dolar\":\n print(\"Wybrałeś/aś drugą walutę dolar, jaką kwotę chciałabyś/chciałbyś przeliczyć?\")\n elif waluta2 == \"funt\" or waluta2 == \"Funt\":\n print(\"Wybrałeś/aś drugą walutę funt, jaką kwotę chciałabyś/chciałbyś przeliczyć?\")\n elif waluta2 == \"złotówka\" or waluta2 == \"Złotówka\":\n print(\"Wybrałeś/aś drugą walutę złotówka, jaką kwotę chciałabyś/chciałbyś przeliczyć?\")\n else:\n print(\"Wybrałeś/aś walutę której nie obsługujemy\")\n print(\"Kwota:\")\n suma = float(input())\n if suma <= 0:\n print(\"Kwota nie może być mniejsza ani równa 0\")\n elif suma > 0:\n print(\"Kwota którą podałeś to \" + str(suma))\n else:\n print(\"Musisz podać kwotę\")\n print(\"Wpisz po jakim kursie chcesz przeliczyć pieniądze: \")\n kurs = float(input())\n podsumowanie = input(\n \"Podsumujmy wybrałeś/aś walutę \" + waluta + \" żeby przeliczyć ją na walutę \" + waluta2 + \" a wartość którą chcesz przeliczyć to \"\n + str(suma) + \". Całość rozliczamy po kursie: \" + str(kurs) + \" Czy to się zgadza?\")\n if podsumowanie == \"tak\" or podsumowanie == \"Tak\":\n print()\n elif podsumowanie == \"nie\" or podsumowanie == \"Nie\":\n print()\n else:\n print(\"Musisz odpowiedzieć tak lub nie\")\n rozliczenie = suma * kurs\n całość = print(\"Przeliczenie : \" + str(suma) + \" \" + waluta + \" = \" + str(kurs) + \" \" + waluta2)\n reply = input(\"Czy chcesz powtórzyć przeliczenie? \")\n if reply.strip().lower() not in ('tak', 'Tak'):\n break\n","sub_path":"Przelicznik.py","file_name":"Przelicznik.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"371697676","text":"import sys\nimport time\nimport numpy as np\n\n#游戏板\nclass Gameboard():\n\n #初始化棋盘\n def __init__(self):\n self.size = 8\n self.space = '.' #棋盘为空的标记\n self.board = []\n for i in range(self.size):\n tmp = [self.space] * self.size\n self.board.append(tmp)\n self.board[3][3] = 'O'\n self.board[4][4] = 'O'\n self.board[3][4] = 'X'\n self.board[4][3] = 'X'\n\n #判断是否已经结束\n def is_over(self):\n n1 = self.find_right_flipping_position('X')\n n2 = self.find_right_flipping_position('O')\n #如果双方都没有可以走下一步的位置,则说明游戏结束\n if len(n1) == 0 and len(n2) == 0:\n return True\n return False\n\n #得出胜利者\n def winner(self):\n x_count = 0\n o_count = 0\n #计算白琪和黑棋的个数\n for i in range(self.size):\n for j in range(self.size):\n #黑棋个数+1\n if self.board[i][j] == 'X':\n x_count += 1\n #白琪个数+1\n elif self.board[i][j] == 'O':\n o_count += 1\n #黑棋胜利\n if x_count > o_count:\n return 0\n #平局\n elif x_count == o_count:\n return 1\n #白琪胜利\n else:\n return 2\n\n #打印棋盘\n def print_state(self):\n print(' ',' '.join(list('12345678')))\n for i in range(self.size):\n print(i + 1, ' '.join(self.board[i]))\n\n #打印棋盘状态\n def print_state_ts(self,mark):\n board = []\n #得出当前可以下子的合法位置\n valid_position = self.find_right_flipping_position(mark)\n #复制棋盘,防止后面操作改变原来的棋盘\n for i in range(self.size):\n tmp = []\n for j in range(self.size):\n tmp.append(self.board[i][j])\n board.append(tmp)\n #将合法位置改为'+'\n for i in range(len(valid_position)):\n x = valid_position[i][0]\n y = valid_position[i][1]\n board[x][y] = '+'\n #打印棋盘\n print(' ', ' '.join(list('12345678')))\n for i in range(self.size):\n print(i + 1, ' '.join(board[i]))\n\n #放棋子\n def move(self,mark,next_step):\n self.board[next_step[0]][next_step[1]] = mark #下子\n flipping_pieces_list = self.flipping_pieces(mark,next_step) #将所有可以翻的位置都进行翻子\n return flipping_pieces_list #返回翻子的二维坐标的列表,方便后面回溯恢复\n\n #翻子\n def flipping_pieces(self,mark,next_step):\n\n flipping_list = []\n #检查当前位置的各方向\n for direction_line in self.direction_lines(next_step):\n for i,j in enumerate(direction_line):\n #找到相同颜色的,将前面探索的位置放进队列\n if self.board[j[0]][j[1]] == mark:\n flipping_list.extend(direction_line[:i])\n break\n #遇到空位,结束探索\n elif self.board[j[0]][j[1]] == self.space:\n break\n #对所有可以翻子的位置进行翻子\n for i in range(len(flipping_list)):\n self.board[flipping_list[i][0]][flipping_list[i][1]] = mark\n\n return flipping_list\n\n\n #回溯,撤销放棋子\n def un_move(self,mark,next_step,flipping_list):\n if mark == 'X':\n anti_mark = 'O'\n else:\n anti_mark = 'X'\n #将下子的位置恢复原状\n self.board[next_step[0]][next_step[1]] = self.space\n #将所有翻子的位置恢复原状\n for i in range(len(flipping_list)):\n self.board[flipping_list[i][0]][flipping_list[i][1]] = anti_mark\n\n #检查是否有棋子可以翻\n def is_fipping(self,mark,next_step):\n flipping_list = []\n #检查当前位置的各个方向\n for direction_line in self.direction_lines(next_step):\n for i, j in enumerate(direction_line):\n #遇到相同子,结束,将之前探索的点放进队列\n if self.board[j[0]][j[1]] == mark:\n flipping_list.extend(direction_line[:i])\n break\n #遇到空格,结束探索\n elif self.board[j[0]][j[1]] == self.space:\n break\n #如果有合适位置,则返回True\n if len(flipping_list) > 0:\n return True\n else:\n return False\n\n #找到所有合法的放棋子位置\n def find_right_flipping_position(self,mark):\n if mark == 'X':\n anti_mark = 'O'\n else:\n anti_mark = 'X'\n #8个方向\n move_direct = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)]\n valid_flipping_position = []\n for i in range(self.size):\n for j in range(self.size):\n #找到相同颜色的子,进行下一步探索\n if self.board[i][j] == anti_mark:\n for move in move_direct:\n x = i + move[0]\n y = j + move[1]\n #检查合法性\n if x < self.size and x >= 0 and y < self.size and y >= 0 and self.board[x][y] == self.space and (x,y) not in valid_flipping_position:\n next_step = (x,y)\n #检查是否能够翻子,可以说明合法\n if self.is_fipping(mark,next_step) == True:\n valid_flipping_position.append((x,y))\n\n return valid_flipping_position\n\n\n #八个方向的数组\n def direction_lines(self,next_step):\n x = next_step[0]\n y = next_step[1]\n board_array = []\n for i in range(self.size):\n tmp = []\n for j in range(self.size):\n tmp.append((i,j))\n board_array.append(tmp)\n #左右方向\n left = board_array[x][0:y]\n right = board_array[x][y+1:]\n top = []\n for i in range(x):\n top.append(board_array[i][y])\n\n bottom = []\n for i in range(x+1,self.size,1):\n bottom.append(board_array[i][y])\n #4个斜方向\n x1 = x-1\n y1 = y+1\n right_top = []\n while x1 >= 0 and y1 < self.size:\n right_top.append(board_array[x1][y1])\n x1 = x1-1\n y1 = y1+1\n\n x1 = x + 1\n y1 = y + 1\n right_bottom = []\n while x1 < self.size and y1 < self.size:\n right_bottom.append(board_array[x1][y1])\n x1 = x1+1\n y1 = y1+1\n\n x1 = x-1\n y1 = y-1\n left_top = []\n while x1 >= 0 and y1 >= 0:\n left_top.append(board_array[x1][y1])\n x1 = x1-1\n y1 = y1-1\n\n x1 = x + 1\n y1 = y - 1\n left_bottom = []\n while x1 < self.size and y1 >= 0:\n left_bottom.append(board_array[x1][y1])\n x1 = x1+1\n y1 = y1-1\n\n left = list(reversed(left))\n top = list(reversed(top))\n\n # print(left,right,top,bottom,right_top,right_bottom,left_top,left_bottom)\n #存储8个方向的列表\n direction_lines = [left,right,top,bottom,right_top,right_bottom,left_top,left_bottom]\n # print(direction_lines)\n return direction_lines\n\n def count_num(self):\n x_count = 0\n o_count = 0\n empty_count = 0\n for i in range(self.size):\n for j in range(self.size):\n if self.board[i][j] == 'X':\n x_count += 1\n elif self.board[i][j] == 'O':\n o_count += 1\n else:\n empty_count += 1\n\n return x_count,o_count,empty_count\n\nif __name__ == \"__main__\":\n gameboard = Gameboard()\n gameboard.print_state()\n gameboard.direction_lines((2,3))\n","sub_path":"gameboard.py","file_name":"gameboard.py","file_ext":"py","file_size_in_byte":8082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"26181586","text":"\nimport streamlit as st\nimport streamlit.components.v1 as components\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport os\n\ndef formatfunc(*args, **kwargs):\n value = args[0]\n if value >= 0:\n return '${:,.2f}'.format(value)\n else:\n return '-${:,.2f}'.format(abs(value))\n\ndf = pd.read_csv('anon_trades_26_10_21.csv', error_bad_lines=False)\nmy_df = df[df.trade_time.str.startswith('2')]\nclosed = my_df.dropna(subset=['buy_timestamp'])\nclosed.twitter_screen_name = '@'+closed.twitter_screen_name\nmean_group = closed.groupby('twitter_screen_name')['twitter_screen_name', 'percent_pnl'].agg('mean')\nsum_group = closed.groupby('twitter_screen_name')['twitter_screen_name', 'dollar_pnl'].agg('sum')\n\ndisp_df = mean_group.join(sum_group)\ndisp_df.columns = ['Avg PnL', 'Total PnL']\ndisp_df.index.name = 'Twitter Handle'\n\nst.title(\"LazyTrade Leaderboard\")\nst.subheader('Leaderboard')\n\nst.dataframe(disp_df.style.format(formatter={'Avg PnL': \"{:.2f}%\", 'Total PnL': formatfunc}), width=500, height=1000)\n# st.table(disp_df.style.format(formatter={'Avg PnL': \"{:.2f}%\", 'Total PnL': formatfunc}))\n\nst.subheader('Historical Signals')\n\nusers = st.multiselect('Choose users to track ', tuple(\n['@binance',\n '@Bitstamp',\n '@bloomberg_crypto',\n '@coinbase',\n '@CoinDesk',\n '@coinmetrics',\n '@crypto_rand',\n '@cryptocom',\n '@CryptoGodJohn',\n '@CryptoKaleo',\n '@CryptoMichNL',\n '@cryptonews',\n '@CryptoPanicCom',\n '@cz_binance',\n '@elonmusk',\n '@KoroushAK',\n '@kucoincom',\n '@mcuban',\n '@Poloniex',\n '@Raticoin1',\n '@RookieXBT',\n '@TheCryptoDog',\n '@thescalpingpro',\n '@Tradermayne',\n '@whale_alert',\n '@Whale_Sniper',\n '@WhaleTrades']\n))\n\n# if len(users) > 0:\n# st.write('Selected')\n \nimages = os.listdir('images')\n\nimport matplotlib.pyplot as plt\n\nfor user in users:\n st.write(user)\n\n coin_list = ['1INCH',\n 'ADA',\n 'ATOM',\n 'AXS',\n 'BNB',\n 'BTC',\n 'DOGE',\n 'DOT',\n 'ETH',\n 'LINK',\n 'LTC',\n 'LUNA',\n 'RUNE',\n 'SOL',\n 'SUSHI'\n 'UNI',\n 'XRP']\n \n all_coins = [i[len(user):].split('_')[0] for i in list(filter(lambda x : x.startswith(user[1:]), images))]\n coin_subset = [i for i in coin_list if i in all_coins]\n \n coins = st.multiselect('Choose coins to plot', coin_subset)\n\n for coin in coins:\n st.write('User: %s\\n\\nCoin: %s' % (user, coin))\n# st.image('images/%s_%s_BTC.png' % (user[1:], coin))\n \n HtmlFile = open('images/%s_%s_BTC.html' % (user[1:], coin), 'r', encoding='utf-8')\n source_code_2 = HtmlFile.read()\n components.html(source_code_2, height=700)\n","sub_path":"old_streamlit_app.py","file_name":"old_streamlit_app.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"421628657","text":"import numpy as np\nimport os\nimport ntpath\nimport time\nfrom . import util\nfrom . import html\n\n\nclass Visualizer():\n def __init__(self, opt):\n # self.opt = opt\n self.display_id = opt.display_id\n self.use_html = opt.isTrain and not opt.no_html\n self.win_size = opt.display_winsize\n self.name = opt.name\n\n if self.use_html:\n self.web_dir = os.path.join(opt.checkpoints_dir, opt.name, 'web')\n self.img_dir = os.path.join(self.web_dir, 'images')\n print('create web directory %s...' % self.web_dir)\n util.mkdirs([self.web_dir, self.img_dir])\n self.log_name = os.path.join(opt.checkpoints_dir, opt.name, 'loss_log.txt')\n with open(self.log_name, \"a\") as log_file:\n now = time.strftime(\"%c\")\n log_file.write('================ Training Loss (%s) ================\\n' % now)\n\n # |visuals|: dictionary of images to display or save\n def display_current_results(self, visuals, epoch):\n if self.use_html: # save images to a html file\n for label, image_numpy in visuals.items():\n img_path = os.path.join(self.img_dir, 'epoch%.3d_%s.png' % (epoch, label))\n util.save_image(image_numpy, img_path)\n\n # errors: same format as |errors| of plotCurrentErrors\n def print_current_errors(self, epoch, i, errors, t):\n message = '(epoch: %d, iters: %d, time: %.3f) ' % (epoch, i, t)\n for k, v in errors.items():\n message += '%s: %.3f ' % (k, v)\n\n print(message)\n with open(self.log_name, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n\n # save image to the disk\n def save_images(self, webpage, visuals, image_path):\n image_dir = webpage.get_image_dir()\n short_path = ntpath.basename(image_path[0])\n name = os.path.splitext(short_path)[0]\n\n webpage.add_header(name)\n ims = []\n txts = []\n links = []\n\n for label, image_numpy in visuals.items():\n image_name = '%s_%s.png' % (name, label)\n save_path = os.path.join(image_dir, image_name)\n util.save_image(image_numpy, save_path)\n\n ims.append(image_name)\n txts.append(label)\n links.append(image_name)\n webpage.add_images(ims, txts, links, width=self.win_size)\n\n\n def save_images_demo(self, webpage, visuals, image_path):\n image_dir = webpage.get_image_dir()\n short_path = ntpath.basename(image_path[0])\n name = os.path.splitext(short_path)[0]\n\n webpage.add_header(name)\n ims = []\n txts = []\n links = []\n\n for label, image_numpy in visuals.items():\n image_name = '%s.jpg' % (name)\n save_path = os.path.join(image_dir, image_name)\n util.save_image(image_numpy, save_path)\n\n ims.append(image_name)\n txts.append(label)\n links.append(image_name)\n webpage.add_images(ims, txts, links, width=self.win_size)\n","sub_path":"EnlightenGAN-master/EnlightenGAN-master/util/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":3024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"363286239","text":"'''\nA teacher is conducting a camp for a group of five children. Based on their performance and behavior during the camp, the teacher rewards them with chocolates.\n\nWrite a Python function to\n\nFind the total number of chocolates received by all the children put together.\nAssume that each child is identified by an id and it is stored in a tuple and the number of chocolates given to each child is stored in a list.\nThe teacher also rewards a child with few extra chocolates for his/her best conduct during the camp.\nIf the number of extra chocolates is less than 1, an error message \"Extra chocolates is less than 1\", should be displayed.\nIf the given child Id is invalid, an error message \"Child id is invalid\" should be displayed. Otherwise, the extra chocolates provided for the child must be added to his/her existing number of chocolates and display the list containing the total number of chocolates received by each child.\n'''\n\n# Solution\n\n#PF-Assgn-37\n\n#Global variables\nchild_id=(10,20,30,40,50)\nchocolates_received=[12,5,3,4,6]\n\ndef calculate_total_chocolates():\n total_chocolates = 0 \n for i in chocolates_received :\n total_chocolates += i\n return total_chocolates\n\ndef reward_child(child_id_rewarded,extra_chocolates):\n if extra_chocolates < 1 :\n print(\"Extra chocolates is less than 1\")\n return\n if child_id_rewarded not in child_id :\n print(\"Child id is invalid\")\n return\n \n counter = 0 \n for i in child_id :\n if i == child_id_rewarded :\n break\n else :\n counter += 1 \n chocolates_received[counter] += extra_chocolates \n print(chocolates_received)\n\n\nprint(calculate_total_chocolates())\n#Test your code by passing different values for child_id_rewarded,extra_chocolates\nreward_child(20,2)\n","sub_path":"Programming Fundamentals using Python/Day 5/Assignments/Assignment 37: Mandatory Assignment - Level 2.py","file_name":"Assignment 37: Mandatory Assignment - Level 2.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"81639447","text":"# space_view_3d_display_tools.py Copyright (C) 2014, Jordi Vall-llovera\n#\n# Multiple display tools for fast navigate/interact with the viewport\n#\n# ***** BEGIN GPL LICENSE BLOCK *****\n#\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ***** END GPL LICENCE BLOCK *****\n\nbl_info = {\n \"name\": \"Display Tools\",\n \"author\": \"Jordi Vall-llovera Medina, Jhon Wallace\",\n \"version\": (1, 6, 0),\n \"blender\": (2, 7, 0),\n \"location\": \"Toolshelf\",\n \"description\": \"Display tools for fast navigate/interact with the viewport\",\n \"warning\": \"\",\n \"wiki_url\": \"http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts/\"\n \"3D_interaction/Display_Tools\",\n \"tracker_url\": \"\",\n \"category\": \"Addon Factory\"}\n\n\"\"\"\nAdditional links:\n Author Site: http://www.jordiart.com\n\"\"\"\n\nimport bpy\nfrom bpy.types import (\n Operator,\n Panel,\n PropertyGroup,\n AddonPreferences,\n )\nfrom bpy.props import (\n IntProperty,\n BoolProperty,\n EnumProperty,\n StringProperty,\n )\n\n\n# define base dummy class for inheritance\nclass BasePollCheck:\n @classmethod\n def poll(cls, context):\n return True\n\n\n# Set Render Settings\ndef set_render_settings(context):\n scene = context.scene\n render = scene.render\n render.simplify_subdivision = 0\n render.simplify_shadow_samples = 0\n render.simplify_child_particles = 0\n render.simplify_ao_sss = 0\n\n\nclass DisplaySimplify(Operator, BasePollCheck):\n bl_idname = \"view3d.display_simplify\"\n bl_label = \"Reset\"\n bl_description = \"Display scene simplified\"\n\n Mode = EnumProperty(\n items=[('WIREFRAME', 'Wireframe', ''),\n ('BOUNDBOX', 'Bounding Box', '')],\n name=\"Mode\"\n )\n ShowParticles = BoolProperty(\n name=\"ShowParticles\",\n description=\"Show or hide particles on fast navigate mode\",\n default=True\n )\n ParticlesPercentageDisplay = IntProperty(\n name=\"Display\",\n description=\"Display a percentage value of particles\",\n default=25,\n min=0,\n max=100,\n soft_min=0,\n soft_max=100,\n subtype='FACTOR'\n )\n\n def execute(self, context):\n set_render_settings(context)\n return {'FINISHED'}\n\n\n# Display Modifiers Render Switch\nclass DisplayModifiersRenderSwitch(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_render_switch\"\n bl_label = \"On/Off\"\n bl_description = \"Display/Hide modifiers on render\"\n\n mod_render = BoolProperty(default=True)\n\n def execute(self, context):\n try:\n if self.mod_render:\n scene = context.scene.display_tools\n scene.Simplify = 1\n\n selection = context.selected_objects\n\n if not selection:\n for obj in bpy.data.objects:\n for mod in obj.modifiers:\n mod.show_render = self.mod_render\n else:\n for obj in selection:\n for mod in obj.modifiers:\n mod.show_render = self.mod_render\n except:\n self.report({'ERROR'}, \"Display/Hide all modifiers for render failed\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\n# Display Modifiers Viewport switch\nclass DisplayModifiersViewportSwitch(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_viewport_switch\"\n bl_label = \"On/Off\"\n bl_description = \"Display/Hide modifiers in the viewport\"\n\n mod_switch = BoolProperty(default=True)\n\n def execute(self, context):\n try:\n selection = context.selected_objects\n\n if not(selection):\n for obj in bpy.data.objects:\n for mod in obj.modifiers:\n mod.show_viewport = self.mod_switch\n else:\n for obj in selection:\n for mod in obj.modifiers:\n mod.show_viewport = self.mod_switch\n except:\n self.report({'ERROR'}, \"Display/Hide modifiers in the viewport failed\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\n# Display Modifiers Edit Switch\nclass DisplayModifiersEditSwitch(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_edit_switch\"\n bl_label = \"On/Off\"\n bl_description = \"Display/Hide modifiers during edit mode\"\n\n mod_edit = BoolProperty(default=True)\n\n def execute(self, context):\n try:\n selection = context.selected_objects\n\n if not(selection):\n for obj in bpy.data.objects:\n for mod in obj.modifiers:\n mod.show_in_editmode = self.mod_edit\n else:\n for obj in selection:\n for mod in obj.modifiers:\n mod.show_in_editmode = self.mod_edit\n except:\n self.report({'ERROR'}, \"Display/Hide all modifiers failed\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\nclass DisplayModifiersCageSet(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_cage_set\"\n bl_label = \"On/Off\"\n bl_description = \"Display modifiers editing cage during edit mode\"\n\n set_cage = BoolProperty(default=True)\n\n def execute(self, context):\n selection = context.selected_objects\n try:\n if not selection:\n for obj in bpy.data.objects:\n for mod in obj.modifiers:\n mod.show_on_cage = self.set_cage\n else:\n for obj in selection:\n for mod in obj.modifiers:\n mod.show_on_cage = self.set_cage\n except:\n self.report({'ERROR'}, \"Setting Editing Cage all modifiers failed\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\n# Display Modifiers Expand\nclass DisplayModifiersExpandCollapse(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_expand_collapse\"\n bl_label = \"Expand/Collapse\"\n bl_description = \"Expand/Collapse all modifiers on modifier stack\"\n\n expands = BoolProperty(default=True)\n\n def execute(self, context):\n selection = context.selected_objects\n try:\n if not selection:\n for obj in bpy.data.objects:\n for mod in obj.modifiers:\n mod.show_expanded = self.expands\n else:\n for obj in selection:\n for mod in obj.modifiers:\n mod.show_expanded = self.expands\n\n # update Properties\n for area in context.screen.areas:\n if area.type in ('PROPERTIES'):\n area.tag_redraw()\n except:\n self.report({'ERROR'}, \"Expand/Collapse all modifiers failed\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\n# Apply modifiers\nclass DisplayModifiersApply(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_apply\"\n bl_label = \"Apply All\"\n bl_description = \"Apply modifiers\"\n\n def execute(self, context):\n selection = context.selected_objects\n try:\n if not selection:\n bpy.ops.object.select_all(action='TOGGLE')\n bpy.ops.object.convert(target='MESH', keep_original=False)\n bpy.ops.object.select_all(action='TOGGLE')\n else:\n for mesh in selection:\n if mesh.type == \"MESH\":\n bpy.ops.object.convert(target='MESH', keep_original=False)\n except:\n self.report({'ERROR'}, \"Apply modifiers could not be executed\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\n# Delete modifiers\nclass DisplayModifiersDelete(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_delete\"\n bl_label = \"Delete All\"\n bl_description = \"Delete modifiers\"\n\n def execute(self, context):\n selection = context.selected_objects\n try:\n if not(selection):\n for obj in bpy.data.objects:\n for mod in obj.modifiers:\n bpy.context.scene.objects.active = obj\n bpy.ops.object.modifier_remove(modifier=mod.name)\n else:\n for obj in selection:\n for mod in obj.modifiers:\n bpy.context.scene.objects.active = obj\n bpy.ops.object.modifier_remove(modifier=mod.name)\n except:\n self.report({'ERROR'}, \"Delete modifiers could not be executed\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\n# Put dummy modifier for boost subsurf\ndef modifiers_set_dummy(context):\n selection = context.selected_objects\n\n if not(selection):\n for obj in bpy.data.objects:\n bpy.context.scene.objects.active = obj\n bpy.ops.object.modifier_add(type='SIMPLE_DEFORM')\n value = 0\n for mod in obj.modifiers:\n if mod != 0:\n if mod.type == 'SIMPLE_DEFORM':\n value = value + 1\n mod.factor = 0\n if value > 1:\n bpy.ops.object.modifier_remove(modifier=\"SimpleDeform\")\n else:\n for obj in selection:\n bpy.context.scene.objects.active = obj\n bpy.ops.object.modifier_add(type='SIMPLE_DEFORM')\n value = 0\n for mod in obj.modifiers:\n if mod.type == 'SIMPLE_DEFORM':\n value = value + 1\n mod.factor = 0\n if value > 1:\n bpy.ops.object.modifier_remove(modifier=\"SimpleDeform\")\n\n\n# Delete dummy modifier\ndef modifiers_delete_dummy(context):\n selection = context.selected_objects\n\n if not(selection):\n for obj in bpy.data.objects:\n bpy.context.scene.objects.active = obj\n for mod in obj.modifiers:\n if mod.type == 'SIMPLE_DEFORM':\n bpy.ops.object.modifier_remove(modifier=\"SimpleDeform\")\n bpy.ops.object.modifier_remove(modifier=\"SimpleDeform.001\")\n else:\n for obj in selection:\n bpy.context.scene.objects.active = obj\n for mod in obj.modifiers:\n if mod.type == 'SIMPLE_DEFORM':\n bpy.ops.object.modifier_remove(modifier=\"SimpleDeform\")\n bpy.ops.object.modifier_remove(modifier=\"SimpleDeform.001\")\n\n\nclass DisplayAddDummy(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_set_dummy\"\n bl_label = \"Put Dummy\"\n bl_description = (\"Add a dummy simple deform modifier to boost \"\n \"subsurf modifier viewport performance\")\n\n def execute(self, context):\n modifiers_set_dummy(context)\n return {'FINISHED'}\n\n\nclass DisplayDeleteDummy(Operator, BasePollCheck):\n bl_idname = \"view3d.display_modifiers_delete_dummy\"\n bl_label = \"Delete Dummy\"\n bl_description = (\"Delete a dummy simple deform modifier to boost \"\n \"subsurf modifier viewport performance\")\n\n def execute(self, context):\n modifiers_delete_dummy(context)\n return {'FINISHED'}\n\n\nclass ModifiersSubsurfLevel_Set(Operator, BasePollCheck):\n bl_idname = \"view3d.modifiers_subsurf_level_set\"\n bl_label = \"Set Subsurf level\"\n bl_description = \"Change subsurf modifier level\"\n\n level = IntProperty(\n name=\"Subsurf Level\",\n description=\"Change subsurf modifier level\",\n default=1,\n min=0,\n max=10,\n soft_min=0,\n soft_max=6\n )\n\n def execute(self, context):\n selection = context.selected_objects\n try:\n if not selection:\n for obj in bpy.data.objects:\n context.scene.objects.active = obj\n bpy.ops.object.modifier_add(type='SUBSURF')\n value = 0\n for mod in obj.modifiers:\n if mod.type == 'SUBSURF':\n value = value + 1\n mod.levels = self.level\n if value > 1:\n bpy.ops.object.modifier_remove(modifier=\"Subsurf\")\n else:\n for obj in selection:\n bpy.ops.object.subdivision_set(level=self.level, relative=False)\n for mod in obj.modifiers:\n if mod.type == 'SUBSURF':\n mod.levels = self.level\n except:\n self.report({'ERROR'}, \"Setting the Subsurf level could not be applied\")\n return {'CANCELLED'}\n\n return {'FINISHED'}\n\n\n\n\n# register the classes and props\ndef register():\n bpy.utils.register_module(__name__)\n # Register Scene Properties\n\n\n\ndef unregister():\n bpy.utils.unregister_module(__name__)\n\n\nif __name__ == \"__main__\":\n register()\n","sub_path":"scripts/addons_extern/AF_display_tools/modifier_tools.py","file_name":"modifier_tools.py","file_ext":"py","file_size_in_byte":13664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"103211975","text":"def quick_sort(l):\n\n quick_sort_helper(l, 0, len(l) - 1)\n\n\ndef quick_sort_helper(l, first, last):\n\n if first < last:\n split_point = partition(l, first, last)\n\n quick_sort_helper(l, first, split_point - 1)\n quick_sort_helper(l, split_point + 1, last)\n\n\ndef partition(l, first, last):\n\n pivot_value = l[first]\n\n left_mark = first + 1\n right_mark = last\n\n while True:\n\n while left_mark <= right_mark and l[left_mark] <= pivot_value:\n left_mark += 1\n\n while l[right_mark] >= pivot_value and right_mark >= left_mark:\n right_mark -= 1\n\n if right_mark < left_mark:\n break\n else:\n l[left_mark], l[right_mark] = l[right_mark], l[left_mark]\n\n l[first], l[right_mark] = l[right_mark], l[first]\n\n return right_mark\n\nunsorted_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]\nquick_sort(unsorted_list)\nprint(unsorted_list)\n","sub_path":"Array/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"31362836","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom random import choice, randint\nfrom django.conf import settings\nfrom django.db import models\nfrom privateoffice.fields import AutoOneToOneField\nfrom django.contrib.auth.models import User\n\n\nif 'south' in settings.INSTALLED_APPS:\n from south.modelsinspector import add_introspection_rules\n add_introspection_rules([], ['^privateoffice\\.fields\\.AutoOneToOneField',])\n\n\n\nclass Country(models.Model):\n name = models.CharField('Страна', max_length=60)\n class Meta:\n verbose_name = 'Страна'\n verbose_name_plural = 'Страны'\n def __unicode__(self):\n return self.name\n\nclass Resort(models.Model):\n name = models.CharField('Курорт', max_length=120)\n country = models.ForeignKey(Country, related_name='resorts')\n class Meta:\n verbose_name = 'Курорт'\n verbose_name_plural = 'Курорты'\n def __unicode__(self):\n return self.name\n\nclass Hotel(models.Model):\n name = models.CharField('Отель', max_length=120)\n resort = models.ForeignKey(Resort, related_name='hotels')\n stars = models.IntegerField('Звезды', default=randint(1,5))\n country = models.ForeignKey(Country, related_name='hotels', default=1)\n price = models.IntegerField('Стоимость суток', default=randint(10, 600))\n class Meta:\n verbose_name = 'Отель'\n verbose_name_plural = 'Отели'\n def __unicode__(self):\n return self.name\n\nclass Client(models.Model):\n user = AutoOneToOneField(User, related_name='client', primary_key=True)\n tel = models.CharField('Номер телефона', max_length=15)\n class Meta:\n verbose_name = 'Клиент'\n verbose_name_plural = 'Клиенты'\n def __unicode__(self):\n return self.tel\n #self.user.get_username()\n\nclass Order(models.Model):\n status_choise = (\n ('N', 'Новая'),\n ('W', 'В работе'),\n ('A', 'Принята'),\n ('P', 'Оплачена'),\n ('C', 'Отменена'),\n ('D', 'Выполнена'),\n )\n client = models.ForeignKey(User, related_name='orders')\n hotel = models.ForeignKey(Hotel, related_name='orders')\n manager = models.ForeignKey(User, related_name='manager_orders', blank=True, null=True, default='', on_delete=models.SET_NULL)\n depart = models.DateField('Дата вылета')\n night = models.IntegerField('Количество ночей')\n status = models.CharField('Статус', max_length=1, choices=status_choise, default='N')\n added = models.DateTimeField('Добавлена', auto_now_add=True)\n price = models.IntegerField('Стоимость', default=0)\n class Meta:\n verbose_name = 'Заявка'\n verbose_name_plural = 'Заявки'\n def __unicode__(self):\n return unicode(self.depart)\n\nclass People(models.Model):\n order = models.ForeignKey(Order, verbose_name='people')\n firstName = models.CharField('Имя', max_length=100, blank=True, null=True, default='')\n lastName = models.CharField('Фамилия', max_length=100, blank=True, null=True, default='')\n patronymic = models.CharField('Отчество', max_length=100, blank=True, null=True, default='')\n passport = models.CharField('Серия и номер паспорта через пробел', max_length=30, blank=True, null=True, default='')\n class Meta:\n verbose_name = 'Человек'\n verbose_name_plural = 'Люди'\n def __unicode__(self):\n return u'%s %s' %(self.firstName, self.lastName)\n","sub_path":"privateoffice/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"640650222","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n# pip install seaborn\n__author__ = \"柯博文老師 Powen Ko, www.powenko.com\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets, linear_model\nimport pandas as pd\nfrom sklearn import linear_model\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn import metrics\n\n#read data\ndf = pd.read_excel ('Stars.xls',0)\nprint(df.head())\n############\n# 文字分類 轉 數字分類\ndf[\"ColorNo\"]=df.Color.astype(\"category\").cat.codes # 文字分類轉成數字\ndf[\"Spectral_ClassNo\"]=df.Spectral_Class.astype(\"category\").cat.codes # 文字分類轉成數字\n\n\n\n\n\n\n#############\nprint(\"資料拆切---\")\n# 決定X 分類 和Y分類 要用的欄位\ndfX=df[[\"Temperature\",\"L\",\"R\",\"A_M\",\"ColorNo\",\"Spectral_ClassNo\",\"Spectral_Numer\"]]\ndfY=df[\"Type\"]\nX=dfX.to_numpy()\nY=dfY.to_numpy()\nX_train ,X_test ,Y_train ,Y_test = train_test_split(X,Y,test_size=0.1)\n\n#############\nprint(\"迴歸計算----------------------------------------\")\nfrom sklearn import linear_model\nreg = linear_model.LinearRegression() # 初使化\nreg.fit(X_train,Y_train)\nY_test_predict= reg.predict(X_test)\nprint(\"regr.coef_ 係數:\",reg.coef_)\nprint(\"reg.singular_ 單數:\",reg.singular_)\nprint(\"---\")\nprint(\". 實際答案:\",Y_test)\nprint(\"LinearRegression預測答案:\",Y_test_predict)\n\nprint(\"KNN計算----------------------------------------\")\nfrom sklearn.neighbors import KNeighborsClassifier\nknn = KNeighborsClassifier()\nknn.fit(X_train,Y_train)\nY_test_predict=knn.predict(X_test)\nprint(\". 實際答案:\",Y_test)\nprint(\"KNN 預測答案:\",Y_test_predict)\nprint(' 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\nprint(\"K-means計算------------------------------------\")\nfrom sklearn.cluster import KMeans\nkmeans = KMeans(n_clusters=6)\nkmeans.fit(X_train)\nY_test_predict=kmeans.predict(X_test)\nprint(\". 實際答案:\",Y_test)\nprint(\"K-means 預測答案:\",Y_test_predict)\nprint('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n#print(\"第0個分類的位置\",kmeans.cluster_centers_[:,0])\n#print(\"第1個分類的位置\",kmeans.cluster_centers_[:,1])\n\nprint(\"決策數計算--------------------------------------\")\nfrom sklearn import tree\nDecisionTree = tree.DecisionTreeClassifier()\nDecisionTree.fit(X_train,Y_train)\nY_test_predict=DecisionTree.predict(X_test)\ntree.export_graphviz(DecisionTree,out_file='tree.dot')\n\nprint(\". 實際答案:\",Y_test)\nprint(\"決策數 預測答案:\",Y_test_predict)\nprint('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\nprint(\"隨機forest計算--------------------------------------\")\nfrom sklearn.ensemble import RandomForestClassifier\nmodel = RandomForestClassifier()\nmodel.fit(X_train,Y_train)\nY_test_predict=model.predict(X_test)\n\nfrom sklearn.tree import export_graphviz\nestimator = model.estimators_[5]\nexport_graphviz(estimator,out_file='forest.dot')\n\nprint(\". 實際答案:\",Y_test)\nprint(\"隨機forest 預測答案:\",Y_test_predict)\nprint('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\n\n\nprint(\"NB 計算--------------------------------------\")\nfrom sklearn.naive_bayes import GaussianNB\nmodel =GaussianNB()\nmodel.fit(X_train,Y_train)\nY_test_predict=model.predict(X_test)\n\nprint(model.class_prior_ )\nprint(model.get_params() )\nprint(\". 實際答案:\",Y_test)\nprint(\"NB 預測答案:\",Y_test_predict)\nprint('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\n\n\nprint(\"Lass 計算--------------------------------------\")\nfrom sklearn import linear_model\n\n\nmodel =linear_model.Lasso(alpha=0.1)\nmodel.fit(X_train,Y_train)\nY_test_predict=model.predict(X_test)\n\n\nprint(\". 實際答案:\",Y_test)\nprint(\"Lass 預測答案:\",Y_test_predict)\n# print('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict)) #算準確率\n\nprint(\"SGDClassifier 計算--------------------------------------\")\nfrom sklearn.linear_model import SGDClassifier\nmodel =SGDClassifier(loss=\"hinge\", penalty=\"l2\", max_iter=5)\nmodel.fit(X_train,Y_train)\nY_test_predict=model.predict(X_test)\n\nprint(\". 實際答案:\",Y_test)\nprint(\"SGDClassifier 預測答案:\",Y_test_predict)\nprint('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\nprint(\"GaussianProcessRegressor 計算--------------------------------------\")\nfrom sklearn.gaussian_process import GaussianProcessRegressor\nfrom sklearn.gaussian_process.kernels import DotProduct, WhiteKernel\n\n\nkernel = DotProduct() + WhiteKernel()\nmodel= GaussianProcessRegressor(kernel=kernel, random_state=0)\n\nmodel.fit(X_train,Y_train)\nY_test_predict=model.predict(X_test)\n\nprint(\". 實際答案:\",Y_test)\nprint(\"GaussianProcessRegressor 預測答案:\",Y_test_predict)\n# print('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\n\nprint(\"svm.SVR 計算--------------------------------------\")\nfrom sklearn import svm\n\nmodel= svm.SVR()\nmodel.fit(X_train,Y_train)\nY_test_predict=model.predict(X_test)\n\nprint(\". 實際答案:\",Y_test)\nprint(\"svm.SVR 預測答案:\",Y_test_predict)\n# print('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\n\nprint(\"svm.SVC 計算--------------------------------------\")\nfrom sklearn.model_selection import cross_val_score\nmodel= svm.SVC(kernel='linear', C=1, random_state=42)\nmodel.fit(X_train,Y_train)\nY_test_predict=model.predict(X_test)\n\nprint(\". 實際答案:\",Y_test)\nprint(\"svm.SVC 預測答案:\",Y_test_predict)\n# print('. 準確率:',metrics.accuracy_score(Y_test,Y_test_predict) ) #算準確率\n\n\n\n#############\nprint(\"畫seaborn 圖---\")\ndf2=df[[\"Temperature\",\"L\",\"R\",\"A_M\",\"ColorNo\",\"Spectral_ClassNo\",\"Spectral_Numer\",\"Type\"]]\nsns.set_theme(style=\"ticks\")\n#sns.set_theme(style=\"whitegrid\")\nsns.pairplot(df2, hue=\"Type\")\nplt.show()\n","sub_path":"0513 FinTech+機器學習練習+OpenCV/1-複習練習-機器學習-股票篇_看老師檔案/老師參考資料/X03-Starts-DataConvert-超級大集合.py","file_name":"X03-Starts-DataConvert-超級大集合.py","file_ext":"py","file_size_in_byte":6355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"78502107","text":"\"\"\"\r\nCreated on 24/10/2018\r\n@author: Thomas Bernard\r\nDescription: Construction of cooling rate from thermal histories\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\ndef cooling_rate_plot(path_data,interpolation,vmin,vmax,cmap):\r\n\r\n # path_data = \"Z:\\\\Post-orogenic sediment flux to continental margins\\\\FIGURES\\\\Figure_Realize_Adobe_Illustrator\\\\Review_time-exhumation_NS transect pyrenees\\\\V4.0\\\\Maladeta_Profile_ZFT+AFT+AHe_RD1_-EA_CO_A1.csv\"\r\n data = np.loadtxt(path_data, delimiter=',')\r\n Time = data[:, 0]; Temps = data[:, 1]; S = np.shape(data); Cooling = np.zeros(S[0])\r\n\r\n for i in range(1,S[0]-1):\r\n Cooling[i] = (Temps[i-1]-Temps[i+1])/(Time[i-1]-Time[i+1])\r\n\r\n Cooling[0] = (Temps[0]-Temps[1])/(Time[0]-Time[1])\r\n Cooling[S[0]-1] = (Temps[S[0]-2]-Temps[S[0]-1])/(Time[S[0]-2]-Time[S[0]-1])\r\n\r\n Cooling_Rate = np.zeros((S[0], 2)); Cooling_Rate[:, 0] = Time[:]; Cooling_Rate[:, 1] = Cooling[:]\r\n\r\n print(Cooling_Rate[:, 1])\r\n\r\n plt.figure(1)\r\n plt.imshow((Cooling_Rate[:, 1], Cooling_Rate[:, 1]), interpolation=interpolation, extent=(Time[0], 0, 0, 1), vmin=vmin, vmax=vmax, cmap=cmap)\r\n plt.grid(True, color='k', markeredgecolor='k', markerfacecolor='k')\r\n plt.colorbar()\r\n plt.show()\r\n\r\npath_data = \"Z:\\\\Post-orogenic sediment flux to continental margins\\\\FIGURES\\\\Figure_Realize_Adobe_Illustrator\\\\Review_time-exhumation_NS transect pyrenees\\\\V4.0\\\\Maladeta_Profile_ZFT+AFT+AHe_RD1_-EA_CO_A1.csv\"\r\ncooling_rate_plot(path_data, interpolation='bilinear', vmin=0, vmax=20, cmap='jet')\r\n\r\n\r\n\r\n\r\n","sub_path":"Thermochronological_Scripts/Test_Cooling_History.py","file_name":"Test_Cooling_History.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"213053724","text":"#!/usr/bin/env python3\n\nimport sys\nimport json\nimport subprocess\nimport os\nimport shutil\nimport pathlib\n\ndef fetch_git_repo(url, ref):\n \"\"\"Clone the repository specified by url and checkout ref\n\n The repository is cloned recursively, so submodules will also be retrieved. Note that the\n repository is cloned into the current working directory and that the name of the directory will\n be derived from the URL.\n \"\"\"\n repo = url.split(\"/\")[-1]\n if repo.endswith('.git'):\n repo = repo[:-4]\n subprocess.run(\"git clone {}\".format(url), check=True, shell=True)\n subprocess.run(\"git checkout {}\".format(ref), cwd=repo, check=True, shell=True)\n subprocess.run(\"git submodule update --recursive --init\", cwd=repo, check=True, shell=True)\n\n\ndef force_clean_git_repo(repo_path):\n \"\"\"Recursively find all git repositories under repo_path and remove untracked files\"\"\"\n for dir, subdirs, files in os.walk(repo_path):\n if '.git' in subdirs or '.git' in files:\n print(\"cleaning: {}\".format(dir))\n subprocess.run(\"git clean -xfd\", check=True, shell=True, cwd=dir)\n\n\ndef build_octave_packages(json_bs):\n \"\"\"Build Octave and create Leaf packages\"\"\"\n fetch_git_repo(\"git@github.com:flowthings/brkedgepkg.git\", json_bs[\"octave_git_ref\"])\n fetch_git_repo(\"git@github.com:mangOH/mangOH.git\", json_bs[\"mangoh_git_ref\"])\n\n for module in json_bs[\"modules\"]:\n # It seems that it is necessary to clean the brkedgepkg between each\n # build for a different module. I suspect that the build system for\n # jerryscript isn't smart enough to know that it needs to re-build\n # certain artifacts when the toolchain is swapped out.\n force_clean_git_repo(\"brkedgepkg\")\n subprocess.run(\n \"leaf setup -p swi-{}_{} _tmp_red_release\".format(\n module[\"casual_target\"], module[\"master_package_version\"]),\n check=True, shell=True)\n subprocess.run(\n \"leaf shell -c \\\"make MANGOH_ROOT=\\`pwd\\`/../mangOH DHUB_ROOT=\\`pwd\\`/../mangOH/apps/DataHub MANGOH_BOARD=red VERSION={}\\\"\".format(\n json_bs[\"octave_version\"]),\n check=True, shell=True, cwd=\"brkedgepkg\")\n subprocess.run(\"leaf profile delete _tmp_red_release\", check=True, shell=True)\n\n pathlib.Path(\"leaf\").mkdir(exist_ok=True)\n shutil.copy(\n \"brkedgepkg/build/Octave-mangOH-red-{}.leaf\".format(module[\"legato_target\"]),\n \"leaf/Octave-mangOH-red-{}_{}.leaf\".format(\n module[\"legato_target\"], json_bs[\"octave_version\"]))\n shutil.copy(\n \"brkedgepkg/build/Octave-mangOH-red-{}.leaf.info\".format(module[\"legato_target\"]),\n \"leaf/Octave-mangOH-red-{}_{}.leaf.info\".format(\n module[\"legato_target\"], json_bs[\"octave_version\"]))\n\n\ndef build_master_packages(json_bs):\n \"\"\"Build the master packages for all of the modules listed in the build specification file\"\"\"\n for module in json_bs[\"modules\"]:\n pathlib.Path(\"manifests/{}\".format(module[\"casual_target\"])).mkdir(parents=True, exist_ok=True)\n subprocess.run(\n \"leaf build manifest \\\n -o manifests/{} \\\n --name mangoh-red-{} \\\n --version {} \\\n --description \\\"mangOH Red {} - FW={}, Legato={}, Octave={}\\\" \\\n --master true \\\n --date \\\"`date --utc`\\\" \\\n --tag mangOH \\\n --tag red \\\n --tag Octave \\\n --tag {} \\\n --depends swi-{}_{} \\\n --depends Octave-mangOH-red-{}_{}\".format(\n module[\"casual_target\"],\n module[\"legato_target\"],\n json_bs[\"mangoh_version\"],\n module[\"casual_target\"],\n module[\"firmware\"],\n json_bs[\"legato_version\"],\n json_bs[\"octave_version\"],\n module[\"legato_target\"],\n module[\"casual_target\"],\n module[\"master_package_version\"],\n module[\"legato_target\"],\n json_bs[\"octave_version\"]),\n check=True,\n shell=True)\n subprocess.run(\n \"leaf build pack -i manifests/{} -o leaf/mangoh-red-{}_{}.leaf -- -J .\".format(\n module[\"casual_target\"], module[\"legato_target\"], json_bs[\"mangoh_version\"]),\n check=True,\n shell=True)\n\n\ndef build_index():\n \"\"\"Build the Leaf index for all of the packages in the leaf directory\"\"\"\n subprocess.run(\"leaf build index -o mangOH-red.json *.leaf\", check=True, shell=True, cwd=\"leaf\")\n\n\ndef red_build(build_spec):\n \"\"\"Clone, build and package for all the modules in the given build specification\"\"\"\n json_bs = None\n with open(build_spec) as bs:\n json_bs = json.load(bs)\n build_octave_packages(json_bs)\n build_master_packages(json_bs)\n build_index()\n\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n sys.stderr.write(\"Expected one argument, a JSON build spec\\n\")\n sys.exit(1)\n red_build(sys.argv[1])\n","sub_path":"red/red_release.py","file_name":"red_release.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"23287919","text":"\"\"\"Item type definitions of Bodega Cdmitems.\"\"\"\nfrom bodega_core import ItemType\nfrom .filters import CdmClusterFilter, CdmNodeFilter\nfrom .item_managers import CdmClusterManager, CdmNodeManager\nfrom .models import CdmCluster, CdmNode\nfrom .serializers import CdmClusterSerializer, CdmNodeSerializer\n\ndefinitions = [\n ItemType(\n name='cdm_node',\n plural_name='cdm_nodes',\n model=CdmNode,\n queryset=CdmNode.objects.all(),\n filter_class=CdmNodeFilter,\n serializer_class=CdmNodeSerializer,\n manager_class=CdmNodeManager),\n ItemType(\n name='cdm_cluster',\n plural_name='cdm_clusters',\n model=CdmCluster,\n queryset=CdmCluster.objects.all(),\n filter_class=CdmClusterFilter,\n serializer_class=CdmClusterSerializer,\n manager_class=CdmClusterManager),\n]\n","sub_path":"lab/bodega/bodega_cdm_items/item_types.py","file_name":"item_types.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"498516185","text":"konni = True\r\nwhile konni == True:\r\n tala1 = int(input(\"Sláðu inn tölu \"))\r\n if tala1 != 20:\r\n print(\"Þú valdir vitlaust\")\r\n if tala1 < 20:\r\n print(\"Farðu hærra!\")\r\n else:\r\n print(\"Farðu lærra!\")\r\n konni = True\r\n \r\n elif tala1 == 20:\r\n print(\"Þú valdir rétt\")\r\n svar = input(\"Viltu endurtaka þetta aftur? j/n \").lower()\r\n if svar ==\"n\":\r\n konni = False\r\nprint(\"Bless Bless\")\r\n \r\n","sub_path":"Forr1AU/æfingar/aefingaverk/while1.py","file_name":"while1.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"406267728","text":"# Embedded file name: /Users/michael/PycharmProjects/spamfilter/distance.py\nimport math as _math\nimport random\n\ndef chi2Q(x2, v, exp = _math.exp, min = min):\n \"\"\"Return prob(chisq >= x2, with v degrees of freedom).\n \n v must be even.\n \"\"\"\n # raise v & 1 == 0 or AssertionError\n m = x2 / 2.0\n sum = term = exp(-m)\n for i in range(1, v // 2):\n term *= m / i\n sum += term\n\n return min(sum, 1.0)\n","sub_path":"distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"36737662","text":"\"\"\"\nsignatures.py\n\nmodule implementing the rsa_signature_2018 signature suite and others\n\"\"\"\nimport binascii\nimport base64\nimport copy\nfrom cryptography.exceptions import InvalidSignature\nimport datetime\nfrom skillcreds import credential as cred\nfrom skillcreds.vocabs import sec\nimport sys\n\n\nclass SignatureProtocol(object):\n def create_verify_hash(self, document, creator, created=None, nonce=None, domain=None):\n raise NotImplementedError()\n\n def sign(self, document, private_key, key_id):\n raise NotImplementedError()\n\n def verify(self, document, public_key):\n raise NotImplementedError()\n\n\nclass LinkedDataSignature(SignatureProtocol):\n\n def __init__(self, suite, trace=False):\n self.suite = suite\n self.trace = trace\n\n def create_verify_hash(self, canonical, creator, created=None, nonce=None, domain=None):\n \"\"\"Given a canonicalised JSON-LD document, returns the verification\n hash of the document and the options passed in accoding to the\n LinkedDataSignatures specification.\n\n Returns:\n bytes containing the hash of the document and the options\n \"\"\"\n # Following the algorithm at\n # https://w3c-dvcg.github.io/ld-signatures/#create-verify-hash-algorithm\n # 1 Feb 2019\n # Add a datetime if one is not provided\n trace = self.trace\n if created is None: created = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S%Z')\n # Creating a copy of input options\n options = {\n sec.CREATOR: creator,\n sec.CREATED: created\n }\n if nonce is not None: options[sec.NONCE] = nonce\n if domain is not None: options[sec.DOMAIN]: domain\n\n suite = self.suite\n # Step 4.1 Canonicalise the options\n canonicalised_options = suite.normalize(options)\n if trace:\n print(\"Norm opts:\\n\"+canonicalised_options, file=sys.stderr)\n # Step 4.2 compute the hash of the options\n output = suite.hash(canonicalised_options.encode('utf-8'))\n # Step 4.3 compute the hash of the document and append\n output += suite.hash(canonical.encode('utf-8'))\n return output\n\n def sign(self, credential, private_key, key_id):\n \"\"\"Given a JSON-LD credential and a RSAPrivateKey, will return the\n signed credential according to the LinkedDataSignature 1.0\n specification. This implementation using the RsaSignature2018\n signature suite.\n\n Parameters:\n credential: JSON-LD document in compact representation\n private_key: rsa.PrivateKey object\n key_id: The JSON-LD @id (identifier) of the private/public keypair\n used\n\n Returns:\n signed credential\n \"\"\"\n suite = self.suite\n trace = self.trace\n # Following the algorithm at:\n # https://w3c-dvcg.github.io/ld-signatures/#signature-algorithm\n # 1 Feb 2019\n # Step 1: copy the credential\n output = copy.deepcopy(credential)\n # Step 2: canonicalise\n canonicalised = suite.normalize(credential)\n if trace:\n print(\"Normalized:\\n\"+canonicalised, file=sys.stderr)\n # Step 3: create verify hash, setting the creator and created options\n created = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S%Z')\n tbs = self.create_verify_hash(canonicalised, creator=key_id, created=created)\n if trace:\n print(\"TBS:\\n\"+base64.b64encode(tbs).decode('utf-8'), file=sys.stderr)\n # Step 4: sign tbs using private key and signature algorithm\n signature_value = suite.sign(tbs, private_key)\n # Step 5: add a signature node to output\n output[sec.SIGNATURE] = cred.create_ld_signature(signature_value,\n creator=key_id,\n created=created)\n return output\n\n def verify(self, signed_credential, rsa_public_key):\n \"\"\"Given a signed JSON-LD credential, will verify the signature\n according to the LinkedDataSignature 1.0 specification.\n This implementation using the RsaSignature2018\n signature suite.\n\n Parameters:\n signed_credential: signed JSON-LD document in compact representation\n\n Returns:\n True if the signature is valid, False otherwise\n \"\"\"\n suite = self.suite\n trace = self.trace\n # Following the algorithm at:\n # https://w3c-dvcg.github.io/ld-signatures/#signature-verification-algorithm\n # 1 Feb 2019\n # Step 1b: verifying owner from sec_key is left as an exercise\n # Step 2: copy signed document into document\n credential = copy.deepcopy(signed_credential)\n # Step 3: removing the signature node from the credential for comparison\n signature = credential.pop(sec.SIGNATURE);\n if sec.CREATOR not in signature: raise ValueError('Signed credential signature is missing '+sec.CREATOR+' field')\n if sec.CREATED not in signature: raise ValueError('Signed credential signature is missing '+sec.CREATED+' field')\n # Step 4: canonicalise\n canonicalised = suite.normalize(credential)\n if trace:\n print(\"Normalized:\\n\"+canonicalised, file=sys.stderr)\n # Step 5: create verify hash, setting the creator and created options\n tbv = self.create_verify_hash(canonicalised,\n creator=signature[sec.CREATOR],\n created=signature[sec.CREATED])\n if trace:\n print(\"TBV:\\n\"+base64.b64encode(tbv).decode('utf-8'), file=sys.stderr)\n # Step 6: verify tbv using the public key\n try:\n signature_value = cred.signature_bytes_from_ld_signature(signature)\n suite.verify(signature_value, tbv, rsa_public_key)\n return True\n except InvalidSignature as e:\n print(\"ERROR: Signature invalid!\", file=sys.stderr)\n return False\n except binascii.Error as e:\n print(\"ERROR: Signature invalid: \"+str(e), file=sys.stderr)\n return False\n","sub_path":"skillcreds/signatures.py","file_name":"signatures.py","file_ext":"py","file_size_in_byte":5723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"224085291","text":"# coding=utf-8\nimport PIL.Image\nimport matplotlib.image as mpimg\nimport scipy.ndimage\nimport cv2 # For Sobel etc\nimport glob\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom random import shuffle\nimport os\nnp.set_printoptions(suppress=True, linewidth=200) # Better printing of arrays\n\n\ndef getRingIndices(radius):\n # Bottom\n row1 = np.ones(radius*2+1, dtype=int)*radius\n col1 = np.arange(radius*2+1)-radius\n\n # Right\n row2 = -np.arange(1,radius*2+1)+radius\n col2 = np.ones(radius*2, dtype=int)*radius\n\n # Top\n row3 = -np.ones(radius*2, dtype=int)*radius\n col3 = -np.arange(1,radius*2+1)+radius\n\n # Left\n row4 = np.arange(1,radius*2+1-1)-radius\n col4 = -np.ones(radius*2-1, dtype=int)*radius\n\n rows = np.hstack([row1, row2, row3, row4])\n cols = np.hstack([col1, col2, col3, col4])\n return (rows,cols)\n\ndef countSteps(ring):\n # Build a big ring so we can handle circular edges\n bigring = np.hstack([ring,ring,ring])\n n = len(ring)\n # Go through middle portion of ring\n count = 0\n for i in (np.arange(n) + n):\n if (bigring[i] != bigring[i-1] and (bigring[i-1] == bigring[i-2]) and (bigring[i] == bigring[i+1])):\n count += 1\n return count\n\n\n\n# Load a tile image and check the central symmetry around a ring\ndef main():\n bad_tile_filepaths = sorted(glob.glob('dataset_binary_5/bad/img_*.png'))\n good_tile_filepaths = sorted(glob.glob('dataset_binary_5/good/img_*.png'))\n\n # shuffle(bad_tile_filepaths)\n # shuffle(good_tile_filepaths)\n \n # Setup\n tile_radius = (PIL.Image.open(good_tile_filepaths[0]).size[0]-1)/2 #(img.shape[0]-1)/2\n radius = 5\n\n # filepath = 'dataset_binary_5/bad/img_01_008.png'\n # plt.figure(figsize=(20,20))\n # plt.subplot(121)\n # plt.title('False Positives')\n rows, cols = getRingIndices(radius)\n # Center in tile\n rows += tile_radius\n cols += tile_radius\n\n # for i in range(20):\n # filepath = bad_tile_filepaths[i]\n # img = PIL.Image.open(filepath).convert('L')\n # img = np.array(img)\n # # img = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)\n # ring = img[rows,cols]\n # plt.plot(ring + i*255*2, '.-')\n # plt.plot([0,len(ring)-1], np.ones(2) + 127 + i*255*2, 'k:', alpha=0.2)\n # plt.text(0, i*255*2, countSteps(ring))\n\n # # Good tiles\n # plt.subplot(122)\n # plt.title('True Positives')\n # for i in range(20):\n # filepath = good_tile_filepaths[i]\n # img = PIL.Image.open(filepath).convert('L')\n # img = np.array(img)\n # # img = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)\n # ring = img[rows,cols]\n # plt.plot(ring + i*255*2, '.-')\n # plt.plot([0,len(ring)-1], np.ones(2) + 127 + i*255*2, 'k:', alpha=0.2)\n # plt.text(0, i*255*2, countSteps(ring))\n\n # plt.show()\n\n good_steps = []\n bad_steps = []\n for i in range(len(bad_tile_filepaths)):\n filepath = bad_tile_filepaths[i]\n img = PIL.Image.open(filepath).convert('L')\n img = np.array(img)\n ring = img[rows,cols]\n steps = countSteps(ring)\n bad_steps.append(steps)\n for i in range(len(good_tile_filepaths)):\n filepath = good_tile_filepaths[i]\n img = PIL.Image.open(filepath).convert('L')\n img = np.array(img)\n ring = img[rows,cols]\n steps = countSteps(ring)\n good_steps.append(steps)\n\n # print(good_steps)\n # print(bad_steps)\n\n plt.subplot(121)\n plt.hist(bad_steps)\n plt.title('False Positives')\n plt.subplot(122)\n plt.hist(good_steps)\n plt.title('True Positives')\n plt.show()\n\n\n\n\n\nif __name__ == '__main__':\n main()\n\n\n\n","sub_path":"centralSymmetryTile.py","file_name":"centralSymmetryTile.py","file_ext":"py","file_size_in_byte":3522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"563512400","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport socket\n\ns = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n\n\nwhile True:\n data1=input(\"输入通信字\")\n if(data1=='1'):\n s.close()\n data1=bytes(data1,encoding='utf8')\n s.sendto(data1, ('127.0.0.1', 3333))\n print(s.recv(1024).decode('utf-8'))\n \n\n\n\n# for data in [b'Michael', b'Tracy', b'Sarah']:\n# # 发送数据:\n# print(data)\n# print(type(data))\n# s.sendto(data, ('127.0.0.1', 3333))\n# # 接收数据:\n# print(s.recv(1024).decode('utf-8'))\n\n","sub_path":"廖Py教程/py/18.网络编程/udp_client.py","file_name":"udp_client.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"244881130","text":"class Person:\n name = \"\"\n age = \"\"\n hobbies = []\n def __init__(self, name, age):\n self.name = name\n self.age = age\n self.hobbies = []\n def addHobby(self, newHobby):\n self.hobbies.append(newHobby)\n def deleteHobby(self, oldHobby):\n delIndex = self.hobbies.index(oldHobby)\n self.hobbies.pop(delIndex)\n def incrementAge(self):\n self.age = str(int(self.age) + 1)\n def __repr__(self):\n output = \"\"\n output += (\"Name: \" + self.name)\n output +=(\"\\nAge: \" + self.age)\n output +=(\"\\nHobbies: \")\n for i in range(len(self.hobbies)):\n output += \"\\n\" + (self.hobbies[i])\n return output\n\ndef main():\n people = {} #keys: value where key = name value = person object\n exit = False\n while(exit == False):\n print(\"1. Create a new Person\")\n print(\"2. Add to an existing person's hobbies\")\n print(\"3. Delete an existing person's hobby\")\n print(\"4. Someone has a birthday\")\n print(\"5. See a list of people\")\n print(\"6. Exit\")\n response = input()\n name = \"\"\n if(response == '1'):\n name = input(\"Please enter the name: \")\n age = input(\"Please enter the age: \")\n people[name] = Person(name, age)\n elif(response == '2'):\n name = input(\"Who is receiving a new hobby?\")\n newHobby = input(\"What is this person's new hobby?\")\n people[name].addHobby(newHobby)\n elif(response == '3'):\n name = input(\"Who is losing a hobby?\")\n oldHobby = input(\"What hoby are you deleting?\")\n people[name].deleteHobby(oldHobby)\n elif(response == '4'):\n name = input(\"Who is having a birthday?\")\n print(\"Happy birthday, \" + name + \"!\")\n people[name].incrementAge()\n elif(response == '5'):\n for key in people:\n print(\"\\n\\n\" + repr(people[key]))\n elif(response == '6'):\n exit = True\n else:\n print(\"Invalid response\")\n\nmain()","sub_path":"1114 labs/lab12/lab12_personClass.py","file_name":"lab12_personClass.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"514031296","text":"# -*- coding: utf-8 -*-\n\"\"\"Player model views.\"\"\"\n\n# Standard library\nimport logging\n\n# Django\nfrom django.contrib import messages\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.views.generic import CreateView, DeleteView, DetailView, ListView, UpdateView\n\n# Current django project\nfrom sports_manager.forms.player import EmergencyContactForm, MedicalCertificateForm, PlayerCreationForm\nfrom sports_manager.models import Player\n\nlogger = logging.getLogger(__name__)\n\n\ndef test_user_staff(request):\n \"\"\"Test if the connected user is part of staff.\"\"\"\n return request.user.is_staff\n\n\ndef test_user_superuser(request):\n \"\"\"Test if the connected user is a superuser.\"\"\"\n return request.user.is_superuser\n\n\ndef test_user_own_page(request, kwargs, field_to_test):\n \"\"\"Test if the user logged in owned the page asked to be accessed.\"\"\"\n return request.user.username == kwargs.get(field_to_test) \n\n\ndef test_access_private_page(request, kwargs, field_to_test):\n \"\"\"Fusion of all the tests defined above.\"\"\"\n return test_user_staff(request) or \\\n test_user_superuser(request) or \\\n test_user_own_page(request, kwargs, field_to_test)\n\n\nclass PlayerListView(LoginRequiredMixin, UserPassesTestMixin, ListView):\n \"\"\"View that returns the list of categories.\"\"\"\n\n model = Player\n permission_denied_message = \"You do not have the right to view this page.\" # from AccessMixin\n raise_exception = True\n\n def test_func(self):\n return test_access_private_page(self.request, self.kwargs, 'username')\n\n def get_queryset(self):\n \"\"\"Override the getter of the queryset.\n \n This view will ony show the player owned by the user.\n \"\"\"\n return self.model.objects.filter(owner__username=self.kwargs.get('username'))\n\n\nclass PlayerDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView):\n \"\"\"View that returns the details of a category.\"\"\"\n\n model = Player\n permission_denied_message = \"You do not have the right to view this page.\" # from AccessMixin\n raise_exception = True\n\n def test_func(self):\n return test_access_private_page(self.request, self.kwargs, 'username')\n\n\nclass PlayerCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView):\n \"\"\"View that creates a new category.\"\"\"\n\n model = Player\n form_class = PlayerCreationForm\n permission_denied_message = \"You do not have the right to view this page.\" # from AccessMixin\n raise_exception = True\n\n def test_func(self):\n return test_access_private_page(self.request, self.kwargs, 'username')\n\n def get_success_url(self):\n \"\"\"Get the URL after the success.\"\"\"\n messages.success(self.request, \"Player '{}' added successfully\".format(self.object.name))\n return reverse('sports-manager:player-detail', kwargs={'slug': self.object.slug})\n\n\nclass PlayerUpdateView(UpdateView):\n \"\"\"View that updates a new category.\"\"\"\n\n model = Player\n fields = '__all__'\n\n def get(self, request, *args, **kwargs):\n \"\"\".\"\"\"\n if not request.user.is_authenticated:\n raise PermissionDenied\n\n return super().get(request, args, kwargs)\n\n def post(self, request, *args, **kwargs):\n \"\"\".\"\"\"\n if not request.user.is_authenticated:\n raise PermissionDenied\n\n return super().post(request, args, kwargs)\n\n def get_success_url(self):\n \"\"\"Get the URL after the success.\"\"\"\n messages.success(self.request, \"Player '{}' updated successfully\".format(self.object.name))\n return reverse('sports-manager:player-detail', kwargs={'slug': self.object.slug})\n\n\nclass PlayerDeleteView(DeleteView):\n \"\"\"View that deletes a new category.\"\"\"\n\n model = Player\n\n def get(self, request, *args, **kwargs):\n \"\"\".\"\"\"\n if not request.user.is_authenticated:\n raise PermissionDenied\n\n return super().get(request, args, kwargs)\n\n def post(self, request, *args, **kwargs):\n \"\"\".\"\"\"\n if not request.user.is_authenticated:\n raise PermissionDenied\n\n return super().post(request, args, kwargs)\n\n def get_success_url(self, **kwargs):\n \"\"\"Get the URL after the success.\"\"\"\n messages.success(self.request, \"Player '{}' deleted successfully\".format(self.object.name))\n return reverse('sports-manager:player-list')\n\n\ndef create_new_player(request, username):\n \"\"\"Check http://www.joshuakehn.com/2013/7/18/multiple-django-forms-in-one-form.html.\"\"\"\n if request.POST:\n logger.debug(\"Receive post\")\n player_form = PlayerCreationForm(request.POST, prefix=\"player\")\n emergency_form = EmergencyContactForm(request.POST, prefix=\"emergency\")\n certificate_form = MedicalCertificateForm(request.POST, request.FILES, prefix=\"certif\")\n \n if player_form.is_valid() and emergency_form.is_valid() and certificate_form.is_valid():\n player = player_form.save(commit=False)\n player.owner = request.user\n player.save()\n emergency_contact = emergency_form.save(commit=False)\n emergency_contact.player = player\n emergency_contact.save()\n medical_certificate = certificate_form.save(commit=False)\n medical_certificate.player = player\n medical_certificate.save()\n\n return HttpResponseRedirect(reverse('sports-manager:player-list', kwargs={'username': request.user.username}))\n else:\n player_form = PlayerCreationForm(prefix=\"player\")\n emergency_form = EmergencyContactForm(prefix=\"emergency\")\n certificate_form = MedicalCertificateForm(prefix=\"certif\")\n\n return render(request,\n 'sports_manager/player_creation_form.html',\n {'player_form': player_form, 'emergency_form': emergency_form, 'certificate_form': certificate_form}\n )","sub_path":"sports_manager/views/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":6125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"435553936","text":"class Solution(object):\n def find(self, nums):\n n = len(nums)\n res = [None] * n\n stk = []\n\n for i in range(n - 1, -1, -1):\n while stk and stk[-1] <= nums[i]:\n stk.pop()\n res[i] = stk[-1] if stk else None\n stk.append(nums[i])\n\n return res\n\n\ns = Solution()\nprint(s.find([2, 3, 4, 1, 5]))\n","sub_path":"algorithms/FirstNumberGreaterThanSelfOnRight/FirstNumberGreaterThanSelfOnRight.py","file_name":"FirstNumberGreaterThanSelfOnRight.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"290894628","text":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nprint(\"hello world\")\nlabel = 1 \ntheta = 0\nfeature_vector = np.array([1,2,3]) \ntheta_0 = 0\ndef perceptron_single_step_update(feature_vector, label, current_theta, current_theta_0):\n \"\"\"\n Section 1.3\n Properly updates the classification parameter, theta and theta_0, on a\n single step of the perceptron algorithm.\n\n Args:\n feature_vector - A numpy array describing a single data point.\n label - The correct classification of the feature vector.\n current_theta - The current theta being used by the perceptron\n algorithm before this update.\n current_theta_0 - The current theta_0 being used by the perceptron\n algorithm before this update.\n\n Returns: A tuple where the first element is a numpy array with the value of\n theta after the current update has completed and the second element is a\n real valued number with the value of theta_0 after the current updated has\n completed.\n \"\"\"\n print('single update')\n next_theta = np.add(current_theta, np.dot(label, feature_vector))\n next_theta_0 = current_theta_0 + label\n tup1 = (next_theta, next_theta_0)\n return tup1\nperceptron_single_step_update(feature_vector, label, theta, theta_0)","sub_path":"Project 1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"219483351","text":"#\n# @lc app=leetcode id=2 lang=python3\n#\n# [2] Add Two Numbers\n#\n# Definition for singly-linked list.\n\nimport unittest\n\n\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution():\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n\n p = ListNode(0)\n r = p\n\n while True:\n if l1 == None:\n l1 = ListNode(0)\n\n if l2 == None:\n l2 = ListNode(0)\n \n sum = l1.val + l2.val + r.val\n if sum >= 10:\n sum = sum % 10\n nq = 1\n else:\n nq = 0\n\n r.val = sum\n \n l1 = l1.next\n l2 = l2.next\n # 当下一级别都为空时终止\n if l1 == None and l2 == None and nq == 0:\n break\n else:\n r.next = ListNode(nq)\n r = r.next\n\n\n return p\n\n\nif __name__ == \"__main__\":\n\n l1 = ListNode(1)\n # l1.next = ListNode(8)\n # l1.next.next = ListNode(6)\n\n l2 = ListNode(9)\n l2.next = ListNode(9)\n # l2.next.next = ListNode(6)\n\n\n so = Solution()\n ret = so.addTwoNumbers(l1, l2)\n\n while True:\n print(ret.val)\n ret = ret.next\n if ret == None:\n break\n","sub_path":"2.add-two-numbers.py","file_name":"2.add-two-numbers.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"46740608","text":"import os\nimport time\nimport shutil\n\n\ndef mkdir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n return path\n else:\n return path\n\n\ndef get_data_file_path(relative_path):\n \"\"\"\n 取得最新的数据路径\n :return: format:{./oid_name_type/20180117.txt}\n \"\"\"\n path = mkdir(relative_path)\n files = os.listdir(path)\n files.sort()\n file = files[-1]\n return path+'\\\\'+file\n\n\ndef res_name_path(relative_path):\n \"\"\"\n 取得抓取明星数据的文件地址\n :param relative_path:\n :return: format{./res_container/res_20180202_120807}\n \"\"\"\n path = mkdir(relative_path)\n file_name = 'res'+'_'+time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))\n return path+'\\\\'+file_name\n\n\ndef recommed_file_path(relative_path):\n \"\"\"\n 取得recommend信息\n :param relative_path:\n :return: format:{./recommend_container/recommend_20180202_121758/}\n \"\"\"\n path = mkdir(relative_path)\n dir_name = 'recommend'+'_'+time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))\n return mkdir(path+'\\\\'+dir_name+'\\\\')\n\n\ndef format_file():\n \"\"\"\n 清除往期数据,保存最近20个记录\n :return:\n \"\"\"\n files1 = os.listdir('.\\\\oid_name_type')\n files2 = os.listdir('.\\\\recommend_container')\n files3 = os.listdir('.\\\\res_container')\n\n while len(files1)>19:\n files1.sort()\n file_name = files1[0]\n file_path = '.\\\\oid_name_type\\\\'+file_name\n # print(file_path)\n if os.path.exists(file_path):\n os.remove(file_path)\n files1 = os.listdir('.\\\\oid_name_type')\n\n while len(files2)>19:\n files2.sort()\n file_name = files2[0]\n file_path = '.\\\\recommend_container\\\\'+file_name\n # print(file_path)\n if os.path.exists(file_path):\n shutil.rmtree(file_path)\n files2 = os.listdir('.\\\\recommend_container')\n\n while len(files3)>19:\n files3.sort()\n file_name = files3[0]\n file_path = '.\\\\res_container\\\\'+file_name\n # print(file_path)\n if os.path.exists(file_path):\n os.remove(file_path)\n files3 = os.listdir('.\\\\res_container')\n","sub_path":"recommend_baike_system/mkdir.py","file_name":"mkdir.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"488647448","text":"# -*- coding: utf-8 -*-\r\n# Copyright (c) 2019, libracore and contributors\r\n# For license information, please see license.txt\r\n\r\nfrom __future__ import unicode_literals\r\nimport frappe\r\n\r\ndef cleanup_anfragen():\r\n anfragen = frappe.db.sql(\"\"\"SELECT `name` FROM `tabAnfrage` WHERE `docstatus` = 0 AND `name` NOT IN (SELECT `spo_referenz` FROM `tabTimesheet Detail` WHERE `spo_dokument` = 'Anfrage')\"\"\", as_dict=True)\r\n for _anfrage in anfragen:\r\n anfrage = frappe.get_doc(\"Anfrage\", _anfrage.name)\r\n anfrage.delete()\r\n\r\ndef cleanup_anonyme_ansichten():\r\n med_bers = frappe.db.sql(\"\"\"SELECT `name` FROM `tabMed Ber Anonym`\"\"\", as_dict=True)\r\n for med_ber in med_bers:\r\n med_ber = frappe.get_doc(\"Med Ber Anonym\", med_ber.name)\r\n med_ber.delete()\r\n\r\n tragen_anonym = frappe.db.sql(\"\"\"SELECT `name` FROM `tabTriage Anonym`\"\"\", as_dict=True)\r\n for trage_anonym in tragen_anonym:\r\n trage_anonym = frappe.get_doc(\"Triage Anonym\", trage_anonym.name)\r\n trage_anonym.delete()","sub_path":"spo/utils/cleanup.py","file_name":"cleanup.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"349486983","text":"import connexion,json\nfrom swagger_server.models.inline_response200 import InlineResponse200\nfrom swagger_server.models.inline_response2001 import InlineResponse2001\nfrom swagger_server.models.inline_response2002 import InlineResponse2002\nfrom swagger_server.models.inline_response2003 import InlineResponse2003\nfrom datetime import date, datetime\nfrom typing import List, Dict\nfrom six import iteritems\nfrom ..util import deserialize_date, deserialize_datetime\nfrom swagger_server.db import *\nfrom swagger_server.tool import *\n\ndef index_by_get():\n \"\"\"\n Index Pie Chart\n Index Pie Chart\n\n :rtype: InlineResponse2002\n \"\"\"\n try:\n result_list=[]\n result = FEmployeeLog.select().order_by(FEmployeeLog.posttime.desc()).paginate(1,3)\n for item in result:\n msg_list={\n \"name\": getname(item.uid)[0],\n \"team\": getTment(getname(item.uid)[1]),\n \"desc\": '内部员工',\n \"posttime\": transpositionTime(item.posttime)}\n result_list.append(msg_list)\n\n result1 = FVisitorsLog.select().order_by(FVisitorsLog.starttime.desc()).paginate(1,3)\n for item in result1:\n msg_lis={\n \"name\": item.username,\n \"team\": \"其他\",\n \"desc\": \"陌生人来访\",\n \"posttime\": transpositionTime(item.starttime)\n }\n result_list.append(msg_lis)\n msg = {\"code\": 0, \"status\": \"success\", \"result\":result_list}\n\n except:\n msg={\"code\":-1,\"status\":\"Error\"} \n return msg\n\ndef index_log_get():\n \"\"\"\n Index Chart Log\n Index Chart Log\n\n :rtype: InlineResponse2003\n \"\"\"\n viptotal=FVisitorsLog.select().where(FVisitorsLog.team==6).count\n msrtotal=FVisitorsLog.select().where(FVisitorsLog.team==5).count\n ygtotal=FVisitorsLog.select().where(FVisitorsLog.team!=5 & FVisitorsLog.team!=6).count\n\ndef index_pie_get():\n \"\"\"\n Index Pie Chart\n Index Pie Chart\n\n :rtype: InlineResponse2001\n \"\"\"\n\n try:\n print('--------')\n #上午积极统计(写成时间戳格式,下面判断)\n data1=FSysAttendance.select().where(FSysAttendance.type==1)\n m_start_time=int(timeTransposition((transpositionTime(int(time.time())-24*3600))[0:10]+' '+str(json.loads(data1[0].content)[\"startwork\"]))/1000)\n # 上午结束统计(写成时间戳格式,下面判断)\n data1 = FSysAttendance.select().where(FSysAttendance.type == 1)\n m_end_time = int(timeTransposition(\n (transpositionTime(int(time.time())-24*3600))[0:10] + ' ' + str(json.loads(data1[0].content)[\"endwork\"])) / 1000)\n\n\n\n\n #下午积极统计(写成时间戳格式,下面判断)\n data2 = FSysAttendance.select().where(FSysAttendance.type == 2)\n a_start_time=int(timeTransposition((transpositionTime(int(time.time())-24*3600))[0:10]+' '+str(json.loads(data2[0].content)[\"startwork\"]))/1000)\n # 下午积极统计(写成时间戳格式,下面判断)\n data2 = FSysAttendance.select().where(FSysAttendance.type == 2)\n a_end_time = int(timeTransposition(\n (transpositionTime(int(time.time())-24*3600))[0:10] + ' ' + str(json.loads(data2[0].content)[\"endwork\"])) / 1000)\n print(m_start_time,a_start_time,m_end_time,a_end_time)\n\n data=FDay.select()\n #全天\n normal = data.where(FDay.type == 0).count()\n late=data.where(FDay.type == 1).count()\n m_jj = data.where(FDay.times < m_start_time).count()\n a_jj =data.where((FDay.times < a_start_time) & (FDay.times > m_end_time)).count()\n early = data.where(FDay.type == 3).count()\n #上午\n m_normal = data.where((FDay.type == 0 )& (FDay.times < m_end_time)).count()\n m_late=data.where((FDay.type == 1 )& (FDay.times < m_end_time) & ((FDay.times > m_start_time))).count()\n m_early=data.where((FDay.type ==3 )&( FDay.times > m_start_time) & (FDay.times < m_end_time)).count()\n\n #下午\n a_normal = data.where((FDay.type == 0) & (FDay.times > m_end_time) & (FDay.times < a_start_time)).count()\n a_late = data.where((FDay.type == 1) & (FDay.times > a_start_time) & (FDay.times < a_end_time)).count()\n a_early = data.where((FDay.type ==3) &( FDay.times > a_start_time) & (FDay.times < a_end_time)).count()\n print(a_late)\n msg = {\"code\": 0, \"msg\": \"success\",\"day\":[{\"name\":\"迟到\",\"value\":late},{\"name\":\"正常\",\"value\":normal},{\"name\":\"积极\",\"value\":m_jj+a_jj},{\"name\":\"早退\",\"value\":early}],\n \"morning\":[{\"name\":\"迟到\",\"value\":m_late},{\"name\":\"正常\",\"value\":m_normal},{\"name\":\"积极\",\"value\":m_jj},{\"name\":\"早退\",\"value\":m_early}],\n \"afternoon\":[{\"name\":\"迟到\",\"value\":a_late},{\"name\":\"正常\",\"value\":a_normal},{\"name\":\"积极\",\"value\":a_jj},{\"name\":\"早退\",\"value\":a_early}]\n }\n\n except:\n msg={\"code\":-1,\"msg\":\"Error\"}\n\n\n\n return msg\n","sub_path":"python-flask-server/swagger_server/controllers/home_controller.py","file_name":"home_controller.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"58350654","text":"from datetime import date, timedelta, datetime\nimport sqlalchemy\nfrom .models import assignment, Employee, Project, Base, Task\n\n\ndef __reset_db(session, engine):\n \"\"\"DEV: drops tables and rebuild\"\"\"\n session.close()\n\n try:\n meta = sqlalchemy.MetaData(engine)\n meta.reflect()\n meta.drop_all()\n\n except:\n print('----------------------------')\n print('Table have not been deleted.')\n print('----------------------------')\n return False\n\n try:\n Base.metadata.create_all(engine)\n\n except:\n print('---------------------------')\n print('Tables have not been built.')\n print('---------------------------')\n\n return False\n\n print('----------------------------------------')\n print('Tables removed, and re-built successful.')\n print('----------------------------------------')\n\n # TODO: is return True 'pythonic', something better?\n return True\n\n\ndef __prepop_db(session):\n today = date.today()\n\n pro01 = Project(\n project='333 Dexter, Seattle, WA',\n clientstartdate=today,\n clientenddate=today + timedelta(days=20),\n inhousestartdate=today + timedelta(days=3),\n inhouseenddate=today + timedelta(days=20) - timedelta(days=3)\n )\n pro02 = Project(\n project='Michael Kors Flagship, London',\n clientstartdate=today + timedelta(days=7),\n clientenddate=today + timedelta(days=7) + timedelta(days=20),\n inhousestartdate=today + timedelta(days=7) + timedelta(days=3),\n inhouseenddate=today + timedelta(days=7) + timedelta(days=20) - timedelta(days=3)\n )\n pro03 = Project(\n project='1350 Boylston St, Boston, MA',\n clientstartdate=today + timedelta(days=15),\n clientenddate=today + timedelta(days=15) + timedelta(days=20),\n inhousestartdate=today + timedelta(days=15) + timedelta(days=3),\n inhouseenddate=today + timedelta(days=15) + timedelta(days=20) - timedelta(days=3)\n )\n session.add(pro01)\n session.add(pro02)\n session.add(pro03)\n\n emp01 = Employee(name='Ross Carter', img='ross.jpg', role='Art Director')\n emp02 = Employee(name='Ben Keen', img='ben.jpg', role='Art Director')\n emp03 = Employee(name='Craig Callison', img='craig.jpg', role='Junior')\n emp04 = Employee(name='Daniel Palma', img='dan.jpg', role='Mid')\n emp05 = Employee(name='Mike Olson', img='mike.jpg', role='Senior')\n emp06 = Employee(name='Hilary Arndt', img='hilary.jpg', role='Mid')\n emp07 = Employee(name='Alex Buckthal', img='alex.jpg', role='Junior')\n emp08 = Employee(name='Rory Jarrel', img='rory.jpg', role='Technical Director')\n\n emp01.projects.append(pro01)\n emp06.projects.append(pro01)\n emp07.projects.append(pro01)\n\n emp03.projects.append(pro02)\n emp04.projects.append(pro02)\n emp05.projects.append(pro02)\n emp06.projects.append(pro02)\n\n emp05.projects.append(pro03)\n emp07.projects.append(pro03)\n emp08.projects.append(pro03)\n\n pro01.lead.append(emp01)\n pro02.lead.append(emp02)\n pro03.lead.append(emp05)\n\n session.add(emp01)\n session.add(emp02)\n session.add(emp03)\n session.add(emp04)\n session.add(emp05)\n session.add(emp06)\n session.add(emp07)\n session.add(emp08)\n\n task01 = Task(name='Receiving photography', group=2, startdate=today + timedelta(days=2))\n task02 = Task(name='wireframe', group=3, startdate=today + timedelta(days=4))\n task03 = Task(name='draft', group=3, startdate=today + timedelta(days=10))\n task04 = Task(name='final', group=3, startdate=today + timedelta(days=15))\n task05 = Task(name='wireframe', group=4, startdate=today + timedelta(days=4))\n task06 = Task(name='draft', group=4, startdate=today + timedelta(days=10))\n task07 = Task(name='final', group=4, startdate=today + timedelta(days=15))\n task08 = Task(name='wireframe', group=5, startdate=today + timedelta(days=4))\n task09 = Task(name='draft', group=5, startdate=today + timedelta(days=10))\n task10 = Task(name='final', group=5, startdate=today + timedelta(days=15))\n\n session.add(task01)\n session.add(task02)\n session.add(task03)\n session.add(task04)\n session.add(task05)\n session.add(task06)\n session.add(task07)\n session.add(task08)\n session.add(task09)\n session.add(task10)\n\n pro01.tasks.append(task01)\n pro01.tasks.append(task02)\n pro01.tasks.append(task03)\n pro01.tasks.append(task04)\n pro01.tasks.append(task05)\n pro01.tasks.append(task06)\n pro01.tasks.append(task07)\n pro01.tasks.append(task08)\n pro01.tasks.append(task09)\n pro01.tasks.append(task10)\n\n # build group count\n tasks = [\n task01, task02, task03, task04, task05, task06, task07, task08, task10\n ]\n group_list = []\n for x in tasks:\n group_list.append(x.group)\n final_group_count = len(list(set(group_list)))\n\n pro01.taskgroup = final_group_count\n\n emp01.tasks.append(task01)\n emp02.tasks.append(task02)\n emp03.tasks.append(task03)\n emp02.tasks.append(task01)\n emp05.tasks.append(task05)\n emp03.tasks.append(task05)\n emp01.tasks.append(task06)\n emp01.tasks.append(task07)\n\n pro01.role = int(1)\n pro02.role = int(2)\n pro03.role = int(5)\n\n session.commit()\n session.close()\n\n\ndef make_dict(raw_rows):\n \"\"\" takes list of database objects, returns dict repr of objects. \"\"\"\n result = []\n # for each database object, build dict, 'row_data', from data.\n for row in raw_rows:\n row_data = {}\n for column in row.__table__.columns:\n row_data[column.name] = str(getattr(row, column.name))\n\n if row.__tablename__ == 'employee':\n row_data['projects'] = []\n\n for project in row.projects:\n row_data['projects'].append(\n {\n 'id': int(project.id),\n 'project': project.project,\n 'clientstartdate': str(project.clientstartdate).split()[0],\n 'clientenddate': str(project.clientenddate).split()[0],\n 'inhousestartdate': str(project.inhousestartdate).split()[0],\n 'inhouseenddate': str(project.inhouseenddate).split()[0],\n 'taskgroup': int(project.taskgroup),\n }\n )\n row_data['tasks'] = []\n for task in row.tasks:\n row_data['tasks'].append(\n {\n 'id': task.id,\n 'content': task.name,\n 'start': str(task.startdate).split()[0],\n 'end': str(task.enddate).split()[0],\n 'group': 5\n }\n )\n\n elif row.__tablename__ == 'project':\n row_data['employee'] = []\n if row.employee:\n for employee in row.employee:\n emp = make_dict((employee,))[0]\n del emp['projects']\n row_data['employee'].append(emp)\n\n row_data['tasks'] = []\n if row.tasks:\n for task in row.tasks:\n\n row_data['tasks'].append(\n {\n 'id': int(task.id),\n 'name': str(task.name),\n 'startdate': str(task.startdate).split()[0],\n 'enddate': str(task.enddate).split()[0],\n 'group': int(task.group)\n }\n )\n\n row_data['lead'] = []\n if row.lead:\n for lead in row.lead:\n row_data['lead'].append(\n {\n 'id': int(lead.id),\n 'name': str(lead.name)\n }\n )\n\n elif row.__tablename__ == 'task':\n row_data['project'] = []\n\n if row.project:\n for project in row.project:\n row_data['project'].append(\n {\n 'id': project.id,\n 'name': project.project\n }\n )\n\n result.append(row_data)\n\n # return database objects as dicts.\n return result\n\n\ndef post_project(args):\n # process dates\n for value in args:\n if value == 'clientstartdate':\n date_split = args['clientstartdate'].split()\n args['clientstartdate'] = date(\n int(date_split[0]), int(date_split[1]), int(date_split[2])\n )\n elif value == 'clientenddate':\n date_split = args['clientenddate'].split()\n args['clientenddate'] = date(\n int(date_split[0]), int(date_split[1]), int(date_split[2])\n )\n\n # init in house deadlines based on clientstartdate and clientenddate\n args['inhousestartdate'] = args['clientstartdate'] + timedelta(days=7)\n args['inhouseenddate'] = args['clientenddate'] - timedelta(days=7)\n\n return args\n\n\ndef post_task(args):\n # process dates\n today = date.today()\n\n for value in args:\n if value == 'project':\n args[value] = args[value].split(':')[0]\n\n if value == 'startdate':\n if args[value] == 'None':\n args[value] = today\n else:\n datetime_format = datetime.strptime(args[value], '%Y %m %d')\n args['startdate'] = datetime_format\n\n if value == 'enddate':\n if args[value] == 'None':\n args[value] = today\n else:\n datetime_format = datetime.strptime(args[value], '%Y %m %d')\n args['enddate'] = datetime_format\n\n return args\n","sub_path":"slots_api/packages/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"14504088","text":"import json\nimport requests\nimport csv\nimport pandas as pd\nimport numpy as np\n\n#/Users/liyang/desktop/comp9900/project/readbook/data.csv\n\n####################### 数据处理 #############################\n\n# 把书名合并,如果没有子标题就直接返回主标题\ndef CombineTitle(title,subtitle):\n res = title+\": \"+subtitle\n return res\n\n# isbn处理\ndef getISBN(obj):\n for i in obj:\n if i['type']=='ISBN_13':\n return i['identifier']\n\n# 处理图片地址\ndef getImageLink(obj):\n if obj['smallThumbnail']!='':\n return obj['smallThumbnail']\n else:\n return obj['thumbnail']\n\n# 处理作者\ndef getAuthors(obj):\n str = ','\n return str.join(obj)\n\n# 处理分类\n\ndef getCategories(obj):\n str=','\n return str.join(obj)\n\n# 总处理\ndef process(book):\n res = dict()\n detail = book[\"volumeInfo\"]\n res['id']=book[\"id\"]\n if 'subtitle' in detail: \n res['title']=CombineTitle(detail['title'],detail['subtitle'])\n else:\n res['title']=detail['title']\n if 'authors' in detail:\n res['authors']=getAuthors(detail['authors'])\n else:\n res['authors']=''\n if 'publisher' in detail: \n res['publisher'] = detail['publisher']\n else:\n res['publisher']=''\n if 'publishedDate' in detail:\n res['publish_date'] = detail['publishedDate']\n else:\n res['publish_date'] =''\n if 'pageCount' in detail:\n res['page_count']=detail['pageCount']\n else:\n res['page_count']=''\n if 'categories' in detail:\n res['categories']= getCategories(detail['categories'])\n else:\n res['categories']=''\n if 'description' in detail:\n res['description']=detail['description']\n else:\n res['description']=''\n if 'industryIdentifiers' in detail:\n res['ISBN']=getISBN(detail['industryIdentifiers'])\n else:\n res['ISBN']=''\n if 'imageLinks' in detail:\n res['imageLink'] = getImageLink(detail['imageLinks'])\n else:\n res['imageLink']=''\n return res\n\n#################### 写入csv ##################\n\n \n#################### ajax ###################\n\ndef ajax(obj):\n url=\"https://www.googleapis.com/books/v1/volumes?q=/\"+obj\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',}\n response = requests.get(url=url,headers=headers)\n data = response.text\n data = json.loads(data)\n return data\n\n\nif __name__ == \"__main__\":\n\n label = ['id','title','authors','publisher','publish_date','page_count','categories','ISBN','imageLink']\n # already_input_keyword_01=['python','java','linux','harryporter','Holmes','Django','Twilight','cook',\n # 'Shakespeare','hugo','Algorithm','Vampire','Verne','Ocean','Food','Fruit','Maya','Egypt','Roma',\n # 'Carthage','United Kingdom','Blues','Rock','sex','education','love','friend','countryside','airplane','magic','speaking',\n # 'alcohol','Alexandre Dumas','Goethe','Dante','Tagore','Leo Tolstoy','Maxim Gorky','Hemingway','Balzac','Pushkin',\n # 'cat','dog','chocolate','pie','database','IBM','piano','violin','elves','tank','cake','tea','coffee','pizza','milk','rose','spring','shark','lion','cache','cpu','gpu','intel','newspaper','law','sun','moon','basketball','football']\n\n # item_list=[]\n # key_word=[]\n # for i in key_word:\n # data=ajax(i)\n # for j in data['items']:\n # item_list.append(j)\n\n # df=pd.DataFrame(columns=label)\n df = pd.read_csv(\"data02.csv\")\n # for i in item_list:\n # temp=process(i)\n # df = df.append(temp,ignore_index=True)\n\n \n###### 筛选 #########\n # \"~\"->取反\n # df=df[~df['ISBN'].isnull()]\n # df=df[~df['authors'].isnull()]\n # df=df[~df['publisher'].isnull()]\n # df=df[~df['page_count'].isnull()]\n # df=df[~df['categories'].isnull()]\n df['page_count']=df['page_count'].astype(int)\n df['ISBN']=df['ISBN'].astype(int)\n df.to_csv(\"data02.csv\",index=False)\n\n\n# 通过 django shell插入数据,注意数据类型和model的类型是否一致\n# >>> import csv\n# >>> from backed.models import *\n# >>>\n# >>> f=open('data.csv')\n# >>> reader = csv.reader(f)\n# >>> for row in reader:\n# ... Book.objects.update_or_create(id=row[0],title=row[1],authors=row[2],publisher=row[3],publish_date=row[4],page_count=row[5],categories=row[6],ISBN=row[7],imageLink=row[8],description=row[9])\n\n# \n\n\n##处理csv heder 手动删除就行了…………s","sub_path":"Django_and_vue/web_cache/readbook/data/ajax_test.py","file_name":"ajax_test.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"535889634","text":"import pandas as pd\nimport numpy as np\n\ndef scorepostnr(searchpostnr,postnr):\n for i in range(0,len(searchpostnr)):\n n = len(searchpostnr)-i\n if postnr.startswith(searchpostnr[0:n]):\n return(n/len(searchpostnr))\n return(0)\n\ndef scorerooms(searchrooms,rooms):\n diff = abs(searchrooms - rooms)\n if diff > 10:\n return(0)\n else:\n return(1-diff/10)\n\ndef scoresqm(searchsqm,sqm):\n diff = abs(searchsqm - sqm)\n if diff > 30:\n return(0)\n else:\n return(1-diff/30)\n\ndef scorerent(searchrent,rent):\n absdiff = abs(rent - searchrent)\n diff = searchrent - rent\n if absdiff > 5000:\n return(0)\n else:\n return(1-absdiff/5000)\n\ndef scorebalcony(searchbalcony,balcony):\n if searchbalcony == 0:\n return(0)\n else:\n if balcony == 1:\n return(1)\n else:\n return(0)\n\ndef scoretv(searchtv,tv):\n if searchtv == 0:\n return(0)\n else:\n if tv == 1:\n return(1)\n else:\n return(0)\n\ndef scoretub(searchtub,tub):\n if searchtub == 0:\n return(0)\n else:\n if tv== 1:\n return(1)\n else:\n return(0)\n\ndef scorefireplace(searchfireplace,fireplace):\n if searchfireplace == 0:\n return(0)\n else:\n if fireplace== 1:\n return(1)\n else:\n return(0)\n\ndef scoreelevator(searchelevator,elevator):\n if searchelevator == 0:\n return(0)\n else:\n if elevator== 1:\n return(1)\n else:\n return(0)\n\ndef scoresearch(df,searches,wheights):\n scores = []\n\n for i in range(0,len(df)):\n\n score = [\n scorepostnr(searches[0],df[\"Postnr\"].iloc[i]),\n scorerooms(searches[1],df[\"Rooms\"].iloc[i]),\n scoresqm(searches[2],df[\"Sqm\"].iloc[i]),\n scorerent(searches[3],df[\"Rent\"].iloc[i]),\n scorebalcony(searches[4],df[\"Balcony\"].iloc[i]),\n scoretv(searches[5],df[\"TV\"].iloc[i]),\n scoretub(searches[6],df[\"Tub\"].iloc[i]),\n scorefireplace(searches[7],df[\"Fireplace\"].iloc[i]),\n scoreelevator(searches[8],df[\"Elevator\"].iloc[i]),\n ]\n score = np.array(score)\n weightscore = np.dot(score,wheights)\n scores.append(weightscore)\n df[\"Scores\"] = scores\n df = df.sort_values(\"Scores\",ascending=False)\n return(df)\n\ndef main():\n pass\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"matchscore.py","file_name":"matchscore.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"396172783","text":"from string import punctuation\n\n\ndef get_fileObject():\n \"\"\" Asks the user to input a file name to and then returns the object of that file. \"\"\"\n try:\n file_name = input(\"Enter filename: \\n\")\n file_object = open(file_name, \"r\")\n return file_object\n except FileNotFoundError:\n print(f\"Filename {file_name} not found!\")\n\n\ndef file_object_to_list(data):\n \"\"\" Takes a file object as a parameter and retruns it as a list of lists where \n each sublist is one paragraph.\n \"\"\"\n all_paragraphs: list = []\n paragraph: list = []\n for line in data:\n if line != \"\\n\": # Checks if the line is \n line = line.strip().split()\n for word in line:\n paragraph.append(word.strip(punctuation).lower())\n elif line == \"\\n\":\n all_paragraphs.append(paragraph)\n paragraph = [] #Reseting for the next paragraph\n all_paragraphs.append(paragraph)\n return all_paragraphs\n\n\ndef print_paragraph_location(data):\n \"\"\" Takes the list from file_object_to_list as parameter and prints out all the words\n in alphabetic order and in what paragraph the word apears in.\n \"\"\"\n words_and_locations: dict = {}\n for index, paragraph in enumerate(data):\n index = str(index + 1)\n for word in paragraph:\n if word not in words_and_locations:\n words_and_locations[word] = index\n elif index not in words_and_locations[word]:\n words_and_locations[word] = words_and_locations[word] + f\", {index}\"\n print(\"The paragraph index: \")\n for key in sorted(words_and_locations):\n print(f\"{key} {words_and_locations[key]}\")\n\n\ndef print_highest_count(data, x):\n \"\"\" Takes the list from file_object_to_list and an intiger and then prints out the top x\n most frequent words in all of the paragraghs.\n \"\"\"\n words_count: dict = {}\n for paragraph in data:\n for word in paragraph:\n if word not in words_count:\n words_count[word] = 1\n elif word in words_count:\n words_count[word] += 1\n sorted_word_counts = sorted(words_count.items(), key=lambda x: (-x[1],x[0])) # Got from Stack overflow\n print(f\"\\nThe highest {x} counts: \") \n for word in sorted_word_counts:\n print(f\"{word}\")\n if sorted_word_counts.index(word) == x-1:\n break\n\n\nfile_object = get_fileObject()\nif file_object:\n paragraphs: list = file_object_to_list(file_object)\n print_paragraph_location(paragraphs)\n print_highest_count(paragraphs, 10)\n print_highest_count(paragraphs, 20)\n","sub_path":"Heimaverkefni/Project 9 - Paragraph Analysis/paragraph_analysis.py","file_name":"paragraph_analysis.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"573464467","text":"# Все задачи текущего блока решите с помощью генераторов списков!\n\n# Дан список, заполненный произвольными числами.\n# Получить список из элементов исходного, удовлетворяющих следующим условиям:\n# + Элемент кратен 3\n# + Элемент положительный\n# + Элемент не кратен 4\n\nimport random\n\nMIN = -100\nMAX = 100\nCOUNT_NUMBER = 20\n\nlst = [random.randint(MIN, MAX) for _ in range(0, COUNT_NUMBER)]\nprint(lst)\n\nlst_result = [item for item in lst if item >= 0 and item % 3 == 0 and item % 4 != 0]\nprint(lst_result)\n","sub_path":"lesson04/easy/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"546244954","text":"\n\n#calss header\nclass _MUTTER():\n\tdef __init__(self,): \n\t\tself.name = \"MUTTER\"\n\t\tself.definitions = [u'to speak quietly and in a low voice that is not easy to hear, often when you are worried or complaining about something: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_mutter.py","file_name":"_mutter.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"437998918","text":"import sys\nimport numpy as np\nfrom numpy import ma\nimport matplotlib.pyplot as plt\n\nstart_data = []\nend_app_data = []\nend_stack_data = []\n\nwith open(sys.argv[1]) as start:\n start_data = start.readlines()\n \nwith open(sys.argv[2]) as end:\n end_app_data = end.readlines()\n\nfilename = sys.argv[1].split(\"/\")\n\nfirst_ts = 0\n\napp_seqnums = []\nstack_seqnums = []\nstart_app_times = {}\nstart_stack_times = {}\nend_app_times = {}\nend_stack_times = {}\napp_latencies = []\nstack_latencies = []\ntime_axis_data_app = {}\ntime_axis_data_stack = {}\nprocessed_seqnums = []\nreceived_count = 0\nquestionable_entries = []\n\ngraph_start_idx = 0\ngraph_end_idx = 0\n\n#timestamps seem to be in ns\nfor i in range(len(end_app_data)):\n if (\"stream frame received\" in end_app_data[i]):\n received_count += 1\n \nprint(\"received stream frames: %d\" % received_count)\n\n\n#timestamps seem to be in ns\nfor i in range(len(end_app_data)):\n if ((\"Final\" not in end_app_data[i]) and (\"Received\" in end_app_data[i]) and (\"length\" not in end_app_data[i])):\n item = end_app_data[i].split(',')\n #ie. a latency will only exist if data was passed to the application\n if (int(item[0][15:]) not in app_seqnums):\n app_seqnums.append(int(item[0][15:]))\n \nfor i in range(len(end_app_data)):\n if ((\"Final\" not in end_app_data[i]) and (\"Stack\" in end_app_data[i]) and (\"length\" not in end_app_data[i])):\n item = end_app_data[i].split(',')\n #ie. a latency will only exist if data was passed to the application\n if (int(item[0][13:]) not in stack_seqnums):\n stack_seqnums.append(int(item[0][13:]))\n \n\nfor i in range(len(start_data)):\n #if ((\"Final\" not in start_data[i]) and (\"pktlen\" not in start_data[i])):\n if (\"sent item\" in start_data[i]):\n item = start_data[i].split(',')\n ssn = int(item[0][11:])\n sts = float(item[1][:-1])\n #ie. a latency will only exist if data was passed to the application\n #if (int(item[0][11:]) in app_seqnums):\n #if ((int(item[0][11:]) in app_seqnums) and (int(item[0][11:]) not in processed_seqnums)):\n if (not start_app_times):\n first_ts = (float(item[1][:-1]))\n #if (ssn not in start_app_times):\n if (start_app_times.get(ssn) == None):\n start_app_times[ssn] = sts\n else:\n pass\n #print(\"%d already in dictionary\" % int(item[0][11:]))\n #time_axis_data_app[ssn] = ((float(item[1][:-1]) - first_ts)/1000000000.0)\n \n\nfor i in range(len(start_data)):\n #if ((\"Final\" not in start_data[i]) and (\"pktlen\" not in start_data[i])):\n if (\"sent item\" in start_data[i]):\n item = start_data[i].split(',')\n ssn = int(item[0][11:])\n sts = float(item[1][:-1])\n #ie. a latency will only exist if data was passed to the application\n #if (int(item[0][11:]) in app_seqnums):\n #if ((int(item[0][11:]) in app_seqnums) and (int(item[0][11:]) not in processed_seqnums)):\n #if (not start_stack_times):\n #first_ts = (float(item[1][:-1]))\n #if (ssn not in start_stack_times):\n if (start_stack_times.get(ssn) == None):\n start_stack_times[ssn] = sts\n #time_axis_data_stack[ssn] = ((float(item[1][:-1]) - first_ts)/1000000000.0)\n \n\n\n#print(sorted(stack_seqnums))\napp_seqnums = sorted(app_seqnums)\nstack_seqnums = sorted(stack_seqnums)\n#print(start_stack_times)\nprint(len(start_stack_times))\n#print(end_stack_times)\nprint(len(end_stack_times))\n\n#print(start_app_times)\nprint(len(start_app_times))\n#print(end_app_times)\nprint(len(end_app_times))\n\nprint(\"App: %d entries\" % len(app_seqnums))\n#print(app_seqnums)\nprint(\"Stack: %d entries\" % len(stack_seqnums))\n#print(stack_seqnums)\n\nplayback_times_actual = []\nplayback_times_rtp_ts = []\n\n#there will be more data in start_data than end_data due to retransmissions\nfor i in range(len(end_app_data)):\n if ((\"Final\" not in end_app_data[i]) and (\"Received\" in end_app_data[i]) and (\"length\" not in end_app_data[i])):\n item = end_app_data[i].split(',')\n #print(\"end time: %d\" % int(item[0][15:]))\n end_app_times[int(item[0][15:])] = float(item[1][:-1])\n if (start_app_times.get(int(item[0][15:]))):\n #print(\"accepted: %d\" % int(item[0][15:]))\n time_axis_data_app[int(item[0][15:])] = ((start_app_times.get(int(item[0][15:])) - first_ts)/1000000000.0)\n #time_axis_data_app[int(item[0][15:])] = ((float(item[1][:-1]) - first_ts)/1000000000.0)\n #end_times.append(float(item[1][:-1])/1000000000)\n #end_app_times.append(float(item[1][:-1])/1000000000)\n #end_app_times.append(float(item[1][:-1]))\n #else:\n #end_times.append(0)\n playback_item = end_app_data[i+1].split(',')\n #playback_times_actual.append(int(playback_item[0][21:]))\n playback_times_actual.append(int(playback_item[0][21:]) + 12000)\n playback_times_rtp_ts.append(int(playback_item[1][14:-1]))\n \n#print(start_app_times)\nprint(\"\")\nprint(\"\")\n#print(time_axis_data_app)\n\n\n#there will be more data in start_data than end_data due to retransmissions\nfor i in range(len(end_app_data)):\n if ((\"Final\" not in end_app_data[i]) and (\"Stack\" in end_app_data[i]) and (\"length\" not in end_app_data[i])):\n item = end_app_data[i].split(',')\n end_stack_times[int(item[0][13:])] = float(item[1][:-1])\n if (start_stack_times.get(int(item[0][13:]))):\n time_axis_data_stack[int(item[0][13:])] = ((start_stack_times.get(int(item[0][13:])) - first_ts)/1000000000.0)\n #time_axis_data_stack[int(item[0][13:])] = ((float(item[1][:-1]) - first_ts)/1000000000.0)\n #end_times.append(float(item[1][:-1])/1000000000)\n #end_app_times.append(float(item[1][:-1])/1000000000)\n #end_app_times.append(float(item[1][:-1]))\n #else:\n #end_times.append(0)\n\n#print(len(start_stack_times))\n#print(end_stack_times)\n#print(len(end_stack_times))\n\n#print(start_app_times)\n#print(len(start_app_times))\n#print(end_app_times)\n#print(len(end_app_times))\n \n#time_axis_data_app_array = sorted(time_axis_data_app.values())\n#start_app_times_array = sorted(start_app_times.values())\n#end_app_times_array = sorted(end_app_times.values())\n\n##!!ERRORS CAUSED BY MISALIGNED VALUES!!\n\ntime_axis_data_app_array = []\nstart_app_times_array = []\nend_app_times_array = []\n\ntime_axis_data_stack_array = []\nstart_stack_times_array = []\nend_stack_times_array = []\n\nplayback_offsets_array = []\npb_delay_counter_array = []\npb_delay_counter = 0\npb_offsets_array = []\n\nsent_times = []\nplayed_times = []\nplayed_times_ns = []\n\n#print(\"start_app_times_keys:\")\n#print(start_app_times.keys())\n#print(\"end_app_times_keys:\")\n#print(end_app_times.keys())\n#print(\"app_seqnums:\")\n#print(app_seqnums)\nplayback_diff_prev = 0\n\ndiff_per_frame = 1/60.0\nprint(\"diff_per_frame: %f\" % diff_per_frame)\n\ndiff_per_frame_ns = 1000000000.0/60.0\nprint(\"diff_per_frame_ns: %f\" % diff_per_frame_ns)\nfragment = 0\n\n\nfor i in range(len(app_seqnums)):\n if ((start_app_times.get(app_seqnums[i]) != None) and (end_app_times.get(app_seqnums[i]) != None)):\n #plot send -> receive at app latencies\n start_app_times_array.append(start_app_times.get(app_seqnums[i]))\n end_app_times_array.append(end_app_times.get(app_seqnums[i]))\n time_axis_data_app_array.append((start_app_times.get(app_seqnums[i]) - first_ts)/1000000000.0)\n if ((end_stack_times.get(stack_seqnums[i]) != None) and (end_app_times.get(app_seqnums[i]) != None)):\n #plot receive at app -> playback latencies\n #calculate playback offsets as if application resumes playback on lost packet\n #(ie. playback deadline doesn't increment while stalled)\n #playback_offsets_array.append((playback_times_actual[i] - playback_times_rtp_ts[i]))\n \n playback_diff = playback_times_actual[i] - playback_times_rtp_ts[i]\n if (i != 0):\n playback_diff_prev = playback_times_actual[i-1] - playback_times_rtp_ts[i-1]\n #if ((playback_offsets_array[i] != 0) and (playback_offsets_array[i-1] < 0) and (playback_offsets_array[i] > 0)):\n if ((playback_diff_prev <= 0) and (playback_diff > 0)):\n #pb_delay_counter += playback_diff\n pb_delay_counter += playback_diff\n if (graph_start_idx == 0): \n graph_start_idx = i - 20\n graph_end_idx = i + 20\n \n \n delay_encountered = (playback_diff > playback_diff_prev)\n \n #print(\"i: %d\" % i)\n sent_time = (start_app_times.get(app_seqnums[i]))\n #played_time = (end_app_times.get(app_seqnums[i]))\n #add playback delay and diff per frame\n #played_time = (end_app_times.get(app_seqnums[i]) + (((pb_delay_counter)/3000) * diff_per_frame_ns) + diff_per_frame_ns)\n if(i == 0):\n played_time = (end_app_times.get(app_seqnums[i]) + (((pb_delay_counter)/3000) * diff_per_frame_ns) + diff_per_frame_ns)\n fragment = 1\n else:\n #played_time = (played_times[i-1] + (((pb_delay_counter)/3000) * diff_per_frame_ns) + diff_per_frame_ns)\n #ie. if it's a subsequent section of an I-frame\n if ((fragment != 0) and (((playback_times_rtp_ts[i] - 3000) % 30000 == 0))):\n played_time = (played_times_ns[i-1])\n #if it's the first section of an I-frame\n elif (((playback_times_rtp_ts[i] - 3000) % 30000 == 0)):\n frame_gap = (playback_times_rtp_ts[i] - playback_times_rtp_ts[i-1]) / 3000\n #print(\"frame gap at item %d: %d\" % (i, frame_gap))\n if (playback_diff > playback_diff_prev):\n #played_time = (played_times_ns[i-1] + (((pb_delay_counter)/3000) * diff_per_frame_ns) + diff_per_frame_ns)\n played_time = (played_times_ns[i-1] + ((((pb_delay_counter)/3000) * diff_per_frame_ns) + (diff_per_frame_ns * frame_gap)))\n else:\n #played_time = (played_times_ns[i-1] + diff_per_frame_ns)\n played_time = (played_times_ns[i-1] + (diff_per_frame_ns * frame_gap))\n fragment += 1\n #otherwise, it's a P-frame\n #constantly adds pb_delay counter, should only be added once\n else:\n frame_gap = (playback_times_rtp_ts[i] - playback_times_rtp_ts[i-1]) / 3000\n if (playback_diff > playback_diff_prev):\n #played_time = (played_times_ns[i-1] + (((pb_delay_counter)/3000) * diff_per_frame_ns) + diff_per_frame_ns)\n played_time = (played_times_ns[i-1] + (((pb_delay_counter)/3000) * diff_per_frame_ns) + (diff_per_frame_ns * frame_gap))\n else:\n #played_time = (played_times_ns[i-1] + diff_per_frame_ns)\n played_time = (played_times_ns[i-1] + (diff_per_frame_ns * frame_gap))\n fragment = 0\n #print(\"pb_delay_counter: %d \" % pb_delay_counter)\n #print(\"pb_delay_counter ns: %d \" % (((pb_delay_counter)/3000) * diff_per_frame_ns))\n #print(\"played_time: %d (%f)\" % (played_time, (played_time - first_ts)/1000000000.0))\n #playback time calculated in s\n #playback_offsets_array.append((played_time - sent_time)/1000000000.0)\n #playback_offsets_array.append(((played_time - sent_time) + (((pb_delay_counter)/3000) * diff_per_frame_ns))/1000000000.0)\n #print(\"played_time - sent_time = playback_offset_time\")\n #print(\"%f - %f = %f\" % ((played_time - first_ts)/1000000000.0, (sent_time - first_ts)/1000000000.0, (played_time - sent_time)/1000000000.0))\n #sent_times.append(sent_time/1000000000.0)\n sent_times.append((sent_time - first_ts)/1000000000.0)\n #print(\"sent_times appended val: %f\" % ((sent_time - first_ts)/1000000000.0))\n \n #act as if client freezes when there's no content, buffers, then resumes from missing frame\n #if (playback_times_actual[i] > playback_times_rtp_ts[i]):\n #playback_times_actual[i] = playback_times_rtp_ts[i]\n \n pb_offset_seconds = ((pb_delay_counter)/3000) * diff_per_frame;\n #print(\"pb_offset_seconds: %f \" % pb_offset_seconds)\n \n \n \n \n played_times.append((played_time - first_ts)/1000000000.0)\n played_times_ns.append((played_time))\n playback_offsets_array.append(played_times[i] - sent_times[i])\n #print(played_times[i])\n #print(played_times_ns[i])\n #print(\"#####\")\n #print(\"played_times appended val: %f\" % ((played_time - first_ts)/1000000000.0))\n #playback_offsets_array.append((played_times[i] - (sent_time/1000000000.0)))\n pb_offsets_array.append(pb_offset_seconds)\n \nfor i in range(len(stack_seqnums)):\n if ((start_stack_times.get(stack_seqnums[i]) != None) and (end_stack_times.get(stack_seqnums[i]) != None)):\n start_stack_times_array.append(start_stack_times.get(stack_seqnums[i]))\n end_stack_times_array.append(end_stack_times.get(stack_seqnums[i]))\n time_axis_data_stack_array.append((start_stack_times.get(stack_seqnums[i]) - first_ts)/1000000000.0)\n \nprint(\"App start: %d len\" % len(start_app_times_array))\n#print(app_seqnums)\nprint(\"Stack start: %d len\" % len(start_stack_times_array))\n#print(app_seqnums)\nprint(\"App end: %d len\" % len(end_app_times_array))\n#print(stack_seqnums)\nprint(\"Stack end: %d len\" % len(end_stack_times_array))\n#print(stack_seqnums)\n\n#time_axis_data_app_array = list(time_axis_data_app.values())\n#start_app_times_array = list(start_app_times.values())\n#end_app_times_array = list(end_app_times.values())\n\n#time_axis_data_stack_array = list(time_axis_data_stack.values())\n#start_stack_times_array = list(start_stack_times.values())\n#end_stack_times_array = list(end_stack_times.values())\n\n\n#time_axis_data_stack_array = sorted(time_axis_data_app.values())\n#start_stack_times_array = sorted(start_app_times.values())\n#end_stack_times_array = sorted(end_app_times.values())\n \n#for i in range(len(start_app_times)):\n #app_latencies.append((float(end_app_times[i]) - float(start_app_times[i]))/1000000.0)\n #print(\"%d - %d = %f\" % (end_app_times[i], start_app_times[i], app_latencies[i]))\n #print(\"time axis data: %f\" % time_axis_data_app[i])\n \nlast_num = 0\n\nfor i in range(min(len(start_app_times_array), (len(end_app_times_array)))):\n #app latencies seem too high by a factor of 10 in some cases\n app_latencies.append((float(end_app_times_array[i]) - float(start_app_times_array[i]))/1000000.0)\n #if(app_latencies[i] > 100):\n #print(\"app, sn %d: %d - %d = %f\" % (app_seqnums[i], end_app_times_array[i], start_app_times_array[i], app_latencies[i]))\n '''\n if app_seqnums[i] != (last_num + 1):\n #print(\"Missing seqnum: %d\" % (last_num + 1))\n last_num = app_seqnums[i]\n else:\n last_num = app_seqnums[i]\n #print(\"time axis data: %f\" % time_axis_data_app_array[i])\n '''\n\nlast_num = 0 \n#for i in range(len(start_stack_times)):\n #stack_latencies.append((float(end_stack_times[i]) - float(start_stack_times[i]))/1000000.0)\n \nfor i in range(min(len(start_stack_times_array), (len(end_stack_times_array)))):\n stack_latencies.append((float(end_stack_times_array[i]) - float(start_stack_times_array[i]))/1000000.0)\n #if(stack_latencies[i] > 100):\n #print(\"stack, sn %d: %d - %d = %f\" % (stack_seqnums[i], end_stack_times_array[i], start_stack_times_array[i], stack_latencies[i]))\n '''\n if stack_seqnums[i] != (last_num + 1):\n #print(\"Missing seqnum: %d\" % (last_num + 1))\n last_num = last_num = stack_seqnums[i] \n else:\n last_num = stack_seqnums[i]\n #print(\"app: %d - %d = %f\" % (end_app_times_array[i], start_app_times_array[i], app_latencies[i]))\n #print(\"time axis data: %f\" % time_axis_data_stack_array[i])\n '''\n\n#print start_times\n#print end_times\n#print(app_latencies)\n#print(stack_latencies)\n#print(time_axis_data_app[0:60])\n#print(time_axis_data_stack)\n\n\n#################\n\ny = played_times\nplt.ylabel(\"Actual playback time (s)\")\n#y0 = latencies\n#y = y0.copy() + 2.5\n#y = pb_delay_counter_array\nx = sent_times\nplt.xlabel(\"Time sent (s)\")\n\nlines = plt.step(x, y, label='Actual time each packet is played when reaching application')\n\n#y -= 0.5\n#plt.step(x, y, where='post', label='post')\n\n#plt.legend()\n\nplt.xlim(0, 300)\nplt.ylim(0, 300)\n\n#y = ma.masked_where((y0 > -0.15) & (y0 < 0.15), y - 0.5)\n#plt.step(x, y, label='masked (pre)')\n\n\n#plt.show()\n#plt.savefig('app_latency/%s.pdf' % sys.argv[1][:-4])\nplt.savefig('offsets-relative-single.png')\n\nl = lines.pop(0)\nl.remove()\ndel l\n\n#################\n\nx = time_axis_data_app_array[graph_start_idx:graph_end_idx]\nplt.xlabel(\"Time elapsed (s)\")\n#y0 = latencies\n#y = y0.copy() + 2.5\n#y = pb_delay_counter_array\n#y = playback_offsets_array\ny = pb_offsets_array[graph_start_idx:graph_end_idx]\nplt.ylabel(\"Cumulative delay in playback time (s)\")\n\nlines = plt.step(x, y, label='Difference between actual and originally intended playback times')\n\n#y -= 0.5\n#plt.step(x, y, where='post', label='post')\n\n#plt.legend()\n\nprint(\"x graph_start_idx: %f (%d)\" % (time_axis_data_app_array[graph_start_idx], graph_start_idx))\nprint(\"x graph_end_idx: %f (%d)\" % (time_axis_data_app_array[graph_end_idx], graph_end_idx))\n\nprint(\"y graph_start_idx: %f (%d)\" % (pb_offsets_array[graph_start_idx], graph_start_idx))\nprint(\"y graph_end_idx: %f (%d)\" % (pb_offsets_array[graph_end_idx], graph_end_idx))\n\n#plt.xlim(0, 300)\n#plt.ylim(0, 2)\nplt.xlim(time_axis_data_app_array[graph_start_idx], time_axis_data_app_array[graph_end_idx])\nplt.ylim(pb_offsets_array[graph_start_idx], pb_offsets_array[graph_end_idx] + 0.05)\n\n#y = ma.masked_where((y0 > -0.15) & (y0 < 0.15), y - 0.5)\n#plt.step(x, y, label='masked (pre)')\n\n\n#plt.show()\n#plt.savefig('app_latency/%s.pdf' % sys.argv[1][:-4])\nplt.savefig('offsets-single.png')\n#plt.savefig('%s/offsets-single.png' % (\"/\".join(str(s) for s in filename[:-1])))\n\n\n\n\n","sub_path":"revised_data/50ms/latency_parser_offsets_single.py","file_name":"latency_parser_offsets_single.py","file_ext":"py","file_size_in_byte":17140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"653166418","text":"#!/usr/bin/env python2.7\n\"\"\"\n Copyright (C) 2018-2019 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\"\"\"\nfrom __future__ import print_function, division\n\nimport logging\nimport os\nimport sys\nfrom argparse import ArgumentParser, SUPPRESS\nfrom math import exp as exp\n# from time \nimport time\n\nimport cv2\nfrom openvino.inference_engine import IENetwork, IECore\n\nimport numpy as np\n\nimport rospy\nfrom std_msgs.msg import String,UInt8\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n\nfrom yolo_ros_real_pose.msg import RealPose\nfrom yolo_ros_real_pose.msg import ObjectsRealPose\n\n''' Parameters for camera '''\nfx = 611.855712890625\nfy = 611.8430786132812\ncx = 317.46136474609375\ncy = 247.88717651367188\n\n''' Global variables '''\nrgb_image=[]\ndepth_img=[]\nrgb_img_update=0\ndepth_img_update=0\nsig_info_update=0\nargs = []\nmodel_xml=[]\nmodel_bin=[]\nie=[]\nnet=[]\ninput_blob=[]\nexec_net=[]\nlabels_map=[]\ntime_stamp=[]\n\nbridge = CvBridge()\n\nlogging.basicConfig(format=\"[ %(levelname)s ] %(message)s\", level=logging.INFO, stream=sys.stdout)\nlog = logging.getLogger()\n\nxml_path = sys.path[0].rsplit(\"/\",1)[0] + \"/model/frozen_darknet_yolov3_model.xml\"\nlabels_path = sys.path[0].rsplit(\"/\",1)[0] + \"/model/coco.names\"\n\ndef build_argparser():\n parser = ArgumentParser(add_help=False)\n args = parser.add_argument_group('Options')\n args.add_argument('-h', '--help', action='help', default=SUPPRESS, help='Show this help message and exit.')\n args.add_argument(\"-m\", \"--model\", help=\"Required. Path to an .xml file with a trained model.\",\n default=xml_path, type=str)\n args.add_argument(\"-i\", \"--input\", help=\"Required. Path to a image/video file. (Specify 'cam' to work with \"\n \"camera)\", required=False, type=str)\n args.add_argument(\"-l\", \"--cpu_extension\",\n help=\"Optional. Required for CPU custom layers. Absolute path to a shared library with \"\n \"the kernels implementations.\", type=str, default=None)\n args.add_argument(\"-d\", \"--device\",\n help=\"Optional. Specify the target device to infer on; CPU, GPU, FPGA, HDDL or MYRIAD is\"\n \" acceptable. The sample will look for a suitable plugin for device specified. \"\n \"Default value is MYRIAD\", default=\"MYRIAD\", type=str)\n args.add_argument(\"--labels\", help=\"Optional. Labels mapping file\", default=labels_path, type=str)\n args.add_argument(\"-t\", \"--prob_threshold\", help=\"Optional. Probability threshold for detections filtering\",\n default=0.3, type=float)\n args.add_argument(\"-iout\", \"--iou_threshold\", help=\"Optional. Intersection over union threshold for overlapping \"\n \"detections filtering\", default=0.2, type=float)\n args.add_argument(\"-ni\", \"--number_iter\", help=\"Optional. Number of inference iterations\", default=1, type=int)\n args.add_argument(\"-pc\", \"--perf_counts\", help=\"Optional. Report performance counters\", default=False,\n action=\"store_true\")\n args.add_argument(\"-r\", \"--raw_output_message\", help=\"Optional. Output inference results raw values showing\",\n default=False, action=\"store_true\")\n return parser\n\n\nclass YoloV3Params:\n # ------------------------------------------- Extracting layer parameters ------------------------------------------\n # Magic numbers are copied from yolo samples\n def __init__(self, param, side):\n self.num = 3 if 'num' not in param else int(param['num'])\n self.coords = 4 if 'coords' not in param else int(param['coords'])\n self.classes = 80 if 'classes' not in param else int(param['classes']) \n self.anchors = [10.0, 13.0, 16.0, 30.0, 33.0, 23.0, 30.0, 61.0, 62.0, 45.0, 59.0, 119.0, 116.0, 90.0, 156.0,\n 198.0,\n 373.0, 326.0] if 'anchors' not in param else [float(a) for a in param['anchors'].split(',')]\n\n if 'mask' in param:\n mask = [int(idx) for idx in param['mask'].split(',')]\n #print(mask)\n #mask=[[3, 4, 5], [0, 1, 2]]\n self.num = len(mask)\n\n maskedAnchors = []\n for idx in mask:\n maskedAnchors += [self.anchors[idx * 2], self.anchors[idx * 2 + 1]]\n self.anchors = maskedAnchors\n\n self.side = side\n\n\n def log_params(self):\n params_to_print = {'classes': self.classes, 'num': self.num, 'coords': self.coords, 'anchors': self.anchors}\n [log.info(\" {:8}: {}\".format(param_name, param)) for param_name, param in params_to_print.items()]\n\n\ndef entry_index(side, coord, classes, location, entry):\n side_power_2 = side ** 2\n n = location // side_power_2\n loc = location % side_power_2\n return int(side_power_2 * (n * (coord + classes + 1) + entry) + loc)\n\n\ndef scale_bbox(x, y, h, w, class_id, confidence, h_scale, w_scale):\n xmin = int((x - w / 2) * w_scale)\n ymin = int((y - h / 2) * h_scale)\n xmax = int(xmin + w * w_scale)\n ymax = int(ymin + h * h_scale)\n return dict(xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax, class_id=class_id, confidence=confidence)\n\n\ndef parse_yolo_region(blob, resized_image_shape, original_im_shape, params, threshold):\n # ------------------------------------------ Validating output parameters ------------------------------------------\n _, _, out_blob_h, out_blob_w = blob.shape\n assert out_blob_w == out_blob_h, \"Invalid size of output blob. It sould be in NCHW layout and height should \" \\\n \"be equal to width. Current height = {}, current width = {}\" \\\n \"\".format(out_blob_h, out_blob_w)\n\n # ------------------------------------------ Extracting layer parameters -------------------------------------------\n orig_im_h, orig_im_w = original_im_shape\n resized_image_h, resized_image_w = resized_image_shape\n objects = list()\n predictions = blob.flatten()\n side_square = params.side * params.side\n\n # ------------------------------------------- Parsing YOLO Region output -------------------------------------------\n for i in range(side_square):\n row = i // params.side\n col = i % params.side\n for n in range(params.num):\n obj_index = entry_index(params.side, params.coords, params.classes, n * side_square + i, params.coords)\n scale = predictions[obj_index]\n if scale < threshold:\n continue\n box_index = entry_index(params.side, params.coords, params.classes, n * side_square + i, 0)\n x = (col + predictions[box_index + 0 * side_square]) / params.side * resized_image_w\n y = (row + predictions[box_index + 1 * side_square]) / params.side * resized_image_h\n # Value for exp is very big number in some cases so following construction is using here\n try:\n w_exp = exp(predictions[box_index + 2 * side_square])\n h_exp = exp(predictions[box_index + 3 * side_square])\n except OverflowError:\n continue\n w = w_exp * params.anchors[2 * n]\n h = h_exp * params.anchors[2 * n + 1]\n for j in range(params.classes):\n class_index = entry_index(params.side, params.coords, params.classes, n * side_square + i,\n params.coords + 1 + j)\n confidence = scale * predictions[class_index]\n if confidence < threshold:\n continue\n objects.append(scale_bbox(x=x, y=y, h=h, w=w, class_id=j, confidence=confidence,\n h_scale=orig_im_h / resized_image_h, w_scale=orig_im_w / resized_image_w))\n return objects\n\n\ndef intersection_over_union(box_1, box_2):\n width_of_overlap_area = min(box_1['xmax'], box_2['xmax']) - max(box_1['xmin'], box_2['xmin'])\n height_of_overlap_area = min(box_1['ymax'], box_2['ymax']) - max(box_1['ymin'], box_2['ymin'])\n if width_of_overlap_area < 0 or height_of_overlap_area < 0:\n area_of_overlap = 0\n else:\n area_of_overlap = width_of_overlap_area * height_of_overlap_area\n box_1_area = (box_1['ymax'] - box_1['ymin']) * (box_1['xmax'] - box_1['xmin'])\n box_2_area = (box_2['ymax'] - box_2['ymin']) * (box_2['xmax'] - box_2['xmin'])\n area_of_union = box_1_area + box_2_area - area_of_overlap\n if area_of_union == 0:\n return 0\n return area_of_overlap / area_of_union\n\n\n\ndef detect_and_give_real_pose(current_total_dect, current_image,current_depth_img):\n global fx,fy,cx,cy,stage,time_stamp, bridge\n \n # cv2.imshow(\"Image window\", current_image)\n # cv2.waitKey(3)\n \n '''Copy current image''' \n rgb_img_get = current_image.copy()\n depth_img_get = current_depth_img.copy()\n\n img_to_pub = current_image.copy()\n current_img_to_pub = bridge.cv2_to_imgmsg(img_to_pub, encoding=\"passthrough\")\n\n ''' Hand made time synchronizer'''\n current_img_to_pub.header = time_stamp \n current_total_dect.header=time_stamp\n\n ''' Prepare to input '''\n (rows,cols,channels) = current_image.shape\n n, c, h, w = net.inputs[input_blob].shape\n\n is_async_mode = False\n wait_key_code = 0\n \n cur_request_id = 0\n next_request_id = 1\n render_time = 0\n parsing_time = 0\n\n request_id = cur_request_id\n in_frame = cv2.resize(rgb_img_get, (w, h))\n\n # resize input_frame to network size\n in_frame = in_frame.transpose((2, 0, 1)) # Change data layout from HWC to CHW\n in_frame = in_frame.reshape((n, c, h, w))\n\n try:\n exec_net.start_async(request_id=request_id, inputs={input_blob: in_frame}) ###### Most time is consumed here\n except:\n rospy.loginfo(\"Start async failed!\")\n cv2.imshow(\"DetectionResults\", rgb_img_get)\n cv2.waitKey(1)\n return current_img_to_pub, False\n\n # Collecting object detection results\n objects = list()\n if exec_net.requests[cur_request_id].wait(-1) == 0:\n try:\n output = exec_net.requests[cur_request_id].outputs\n except:\n rospy.loginfo(\"Process failed!\")\n cv2.imshow(\"DetectionResults\", rgb_img_get)\n cv2.waitKey(1)\n return current_img_to_pub, False\n\n for layer_name, out_blob in output.items():\n layer_params = YoloV3Params(net.layers[layer_name].params, out_blob.shape[2])\n log.info(\"Layer {} parameters: \".format(layer_name))\n layer_params.log_params()\n objects += parse_yolo_region(out_blob, in_frame.shape[2:],\n rgb_img_get.shape[:-1], layer_params,\n args.prob_threshold) \n\n # Filtering overlapping boxes with respect to the --iou_threshold CLI parameter\n objects = sorted(objects, key=lambda obj : obj['confidence'], reverse=True)\n for i in range(len(objects)):\n if objects[i]['confidence'] == 0:\n continue\n for j in range(i + 1, len(objects)):\n if intersection_over_union(objects[i], objects[j]) > args.iou_threshold:\n objects[j]['confidence'] = 0\n\n # Drawing objects with respect to the --prob_threshold CLI parameter\n objects = [obj for obj in objects if obj['confidence'] >= args.prob_threshold]\n\n if len(objects): # Check number of objects\n if args.raw_output_message:\n log.info(\"\\nDetected boxes for batch {}:\".format(1))\n log.info(\" Class ID | Confidence | XMIN | YMIN | XMAX | YMAX | COLOR \")\n else:\n # rospy.loginfo(\"Found nothing!\")\n cv2.imshow(\"DetectionResults\", rgb_img_get)\n cv2.waitKey(1)\n return current_img_to_pub, False\n\n origin_im_size = rgb_img_get.shape[:-1]\n #print(objects)\n\n\n for obj in objects:\n # Validation bbox of detected object\n if obj['xmax'] > origin_im_size[1] or obj['ymax'] > origin_im_size[0] or obj['xmin'] < 0 or obj['ymin'] < 0:\n continue\n color = (int(min(obj['class_id'] * 15, 255)),\n min(obj['class_id'] * 20, 255), min(obj['class_id'] * 25+100, 255))\n det_label = labels_map[obj['class_id']] if labels_map and len(labels_map) >= obj['class_id'] else \\\n str(obj['class_id'])\n\n if args.raw_output_message:\n log.info(\n \"{:^9} | {:10f} | {:4} | {:4} | {:4} | {:4} | {} \".format(det_label, obj['confidence'], obj['xmin'],\n obj['ymin'], obj['xmax'], obj['ymax'],\n color))\n\n cv2.rectangle(rgb_img_get, (obj['xmin'], obj['ymin']), (obj['xmax'], obj['ymax']), color, 2)\n #rospy.loginfo(\"detect \"+det_label)\n cv2.putText(rgb_img_get,\n \"#\" + det_label + ' ' + str(round(obj['confidence'] * 100, 1)) + ' %',\n (obj['xmin'], obj['ymin'] - 7), cv2.FONT_HERSHEY_COMPLEX, 0.6, color, 1)\n\n x_pos=0\n y_pos=0\n z_pos=0\n\n info=RealPose()\n info.label = det_label\n info.confidence = obj['confidence']\n info.pix_lt_x = obj['xmin']\n info.pix_lt_y = obj['ymin']\n info.pix_rb_x = obj['xmax']\n info.pix_rb_y = obj['ymax']\n\n ### Now calculate the real position\n if len(depth_img_get)!=0 and (obj['xmax']-obj['xmin'])*(obj['ymax']-obj['ymin'])>=0:\n ### Calculate position here by depth image and camera parameters\n depth_box_width=obj['xmax']-obj['xmin']\n depth_box_height=obj['ymax']-obj['ymin']\n delta_rate=0.3\n x_box_min=int(obj['xmin'] + depth_box_width*delta_rate)\n y_box_min=int(obj['ymin'] + depth_box_height*delta_rate)\n x_box_max=int(obj['xmax'] - depth_box_width*delta_rate)\n y_box_max=int(obj['ymax'] - depth_box_height*delta_rate)\n after_width=(depth_box_width*(1-2*delta_rate))\n after_height=(depth_box_height*(1-2*delta_rate))\n ''' '''\n rect = depth_img_get[y_box_min:y_box_max,x_box_min:x_box_max] * 0.001\n rect[np.where(rect == 0)] = 99\n print(rect.min())\n # z_pos=bb.sum()/(after_width*after_height)*0.001\n\n # rect = depth_img_get[obj['xmin']:obj['xmax'], obj['ymin']:obj['ymax']]\n # rect = rect\n\n ''' Using EM, too slow '''\n # print(\"In Em\")\n # em_start_time = time.time()\n # EM_model = cv2.ml.EM_create()\n # EM_model.setClustersNumber(2)\n # EM_model.setCovarianceMatrixType(0)\n # EM_model.setTermCriteria((cv2.TermCriteria_MAX_ITER, 1, 0.2)) # int type, int maxCount, double epsilon\n # EM_model.trainEM(rect)\n # print(time.time() - em_start_time)\n # print(\"EM_model works fine\")\n\n x_pos = (0.5 * (obj['xmax'] + obj['xmin']) - cx) * z_pos / fx\n y_pos = (0.5 * (obj['ymax'] + obj['ymin']) - cy) * z_pos / fy\n\n info.x=x_pos\n info.y=y_pos\n info.z=z_pos\n\n current_total_dect.result.append(info)\n\n cv2.imshow(\"DetectionResults\", rgb_img_get)\n cv2.waitKey(1)\n\n return current_img_to_pub, True\n\n\n\ndef load_model():\n global args,model_xml,model_bin,ie,net,input_blob,exec_net,labels_map\n args = build_argparser().parse_args()\n\n model_xml = args.model\n model_bin = os.path.splitext(model_xml)[0] + \".bin\"\n\n # ------------- 1. Plugin initialization for specified device and load extensions library if specified -------------\n rospy.loginfo(\"Creating Inference Engine...\")\n ie = IECore()\n\n # -------------------- 2. Reading the IR generated by the Model Optimizer (.xml and .bin files) --------------------\n rospy.loginfo(\"Loading network files:\\n\\t{}\\n\\t{}\".format(model_xml, model_bin))\n net = IENetwork(model=model_xml, weights=model_bin)\n\n assert len(net.inputs.keys()) == 1, \"Sample supports only YOLO V3 based single input topologies\"\n\n # ---------------------------------------------- 4. Preparing inputs -----------------------------------------------\n rospy.loginfo(\"Preparing inputs\")\n input_blob = next(iter(net.inputs))\n\n # Defaulf batch_size is 1\n net.batch_size = 1\n\n # Read and pre-process input images\n n, c, h, w = net.inputs[input_blob].shape\n\n if args.labels:\n with open(args.labels, 'r') as f:\n labels_map = [x.strip() for x in f]\n else:\n labels_map = None\n\n # ----------------------------------------- 5. Loading model to the plugin -----------------------------------------\n rospy.loginfo(\"Loading model to the plugin\")\n exec_net = ie.load_network(network=net, num_requests=2, device_name=args.device)\n rospy.loginfo(\"Loaded model\")\n\n\ndef detection_loop():\n rate = rospy.Rate(100)\n global rgb_image, rgb_img_update,depth_img,depth_img_update, bridge\n\n pub_total=rospy.Publisher(\"/yolo_ros_real_pose/detected_objects\",ObjectsRealPose,queue_size = 1)\n corresponding_img_pub=rospy.Publisher(\"/yolo_ros_real_pose/img_for_detected_objects\",Image,queue_size = 1)\n\n while not rospy.is_shutdown():\n \n if rgb_img_update == 1 and depth_img_update==1:\n if len(rgb_image)!=0 and len(depth_img)!=0:\n total_dect = ObjectsRealPose()\n\n try:\n detection_start_time = time.time()\n img_to_pub, if_detected = detect_and_give_real_pose(total_dect, rgb_image, depth_img) #detection function\n rospy.loginfo(\"detection time =\" + str(time.time()-detection_start_time))\n\n if if_detected:\n pub_total.publish(total_dect)\n corresponding_img_pub.publish(img_to_pub)\n except:\n rospy.loginfo(\"detection error!\")\n continue\n\n rgb_img_update = 0\n depth_img_update =0\n \n rate.sleep()\n\n\nclass SubscriberClass:\n def __init__(self):\n self.depth_img=None\n self.color_img=None\n\n def color_callback(self,msg):\n global rgb_image,rgb_img_update, bridge\n self.color_img = bridge.imgmsg_to_cv2(msg, \"bgr8\")\n rgb_image=self.color_img.copy()\n rgb_img_update=1\n\n def depth_callback(self,msg):\n global depth_img,depth_img_update,time_stamp, bridge\n self.depth_img=bridge.imgmsg_to_cv2(msg, \"32FC1\")\n depth_img=self.depth_img.copy()\n time_stamp=msg.header\n depth_img_update=1\n # rospy.loginfo(\"depth received!!\")\n\n\ndef main():\n rospy.init_node('detection', anonymous=False,log_level=rospy.INFO)\n sub_callbacks=SubscriberClass()\n\n image_sub = rospy.Subscriber(\"/camera/color/image_raw\",Image,sub_callbacks.color_callback)\n image_depth_sub = rospy.Subscriber(\"/camera/depth/image_rect_raw\",Image,sub_callbacks.depth_callback)\n\n try:\n load_model()\n except :\n # rospy.loginfo(\"load model failed,please restart !!!\")\n rate = rospy.Rate(1)\n\n while not rospy.is_shutdown():\n rospy.loginfo(\"load failed!!!\")\n rate.sleep()\n return\n detection_loop()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"script/yolo_ros_node.py","file_name":"yolo_ros_node.py","file_ext":"py","file_size_in_byte":20008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"316702461","text":"#!/usr/bin/python2.5\n# -*- coding: utf-8 -*\n# Copyright © 2010 Andrew D. Yates\n# All Rights Reserved.\n\"\"\"Integrate PDF miner terminal application into App Engine.\n\nThis could be extended to use all of pdfminer's functionality\nincluding XML conversion, table of contents extraction, and embedded\njpeg image extraction.\n\nPDFMiner by Yusuke Shinyama\nhttp://www.unixuser.org/~euske/python/pdfminer\n\"\"\"\n\nimport StringIO\n\nfrom pdfminer import converter\nfrom pdfminer import layout\nfrom pdfminer import pdfinterp\nfrom pdfminer import pdfparser\n\n\ndef pdf_to_text(pdf):\n \"\"\"Return extracted text from PDF.\n\n Warning: This function can be slow... up to 300ms per page\n This function does not perform optical character recognition.\n\n Args:\n pdf: bytestring of PDF file\n Returns:\n str of text extracted from `pdf` contents.\n \"\"\"\n # make input and output buffers\n in_buffer = StringIO.StringIO(pdf)\n out_buffer = StringIO.StringIO()\n\n # configure pdf parser\n parser = pdfparser.PDFParser(in_buffer)\n doc = pdfparser.PDFDocument()\n parser.set_document(doc)\n doc.set_parser(parser)\n doc.initialize(password='')\n rsrcmgr = pdfinterp.PDFResourceManager()\n laparams = layout.LAParams()\n \n # convert pdf to text\n device = converter.TextConverter(\n rsrcmgr, outfp=out_buffer, codec='utf-8', laparams=laparams)\n interpreter = pdfinterp.PDFPageInterpreter(rsrcmgr, device)\n\n for page in doc.get_pages():\n interpreter.process_page(page)\n\n return out_buffer.getvalue()\n","sub_path":"Upload_mod/pdf_miner_app_engine/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"594119521","text":"#!/usr/bin/env python\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport os.path\nimport tornado.options\n\nfrom tornado.options import define, options\ndefine(\"port\", default=8000, help=\"run on the given port\", type=int)\n\nclass BseHandler(tornado.web.RequestHandler):\n def get_current_user(self):\n return self.get_secure_cookie(\"username\")\n\nclass LoginHandler(BseHandler):\n def get(self):\n self.render(\"login.xhtml\")\n\n def post(self):\n self.set_secure_cookie(\"username\", self.get_argument(\"username\"))\n self.redirect(\"/\")\n\nclass WelcomeHandler(BseHandler):\n @tornado.web.authenticated\n def get(self):\n self.render(\"Cookie_index.xhtml\", user=self.current_user)\n\nclass LogoutHandler(BseHandler):\n def get(self):\n if (self.get_argument(\"logout\",None)):\n self.clear_cookie(\"username\")\n self.redirect(\"/\")\n\nif __name__ == \"__main__\":\n tornado.options.parse_command_line()\n settings = {\n \"template_path\":os.path.join(os.path.dirname(__file__), \"templates\"),\n \"cookie_secret\": \"bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=\",\n \"xsrf_cookies\":True,\n \"login_url\":\"/login\"\n }\n application = tornado.web.Application(\n handlers=[\n (r'/', WelcomeHandler),\n (r'/login', LoginHandler),\n (r'/logout',LogoutHandler)\n ],\n **settings\n )\n http_server = tornado.httpserver.HTTPServer(application)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()","sub_path":"Python/Tornado/cookies.py","file_name":"cookies.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"649336998","text":"import tkinter\nfrom tkinter import filedialog\nfrom rdflib import Graph\nfrom tkinter import *\nfrom tkinter import simpledialog\nimport io\nimport pydotplus\nfrom IPython.display import display\nfrom rdflib.tools.rdf2dot import rdf2dot\nimport os\nimport webbrowser\nimport pathlib\nos.environ[\"PATH\"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'\n\n#Generate GUI window\nmaster = Tk()\nmaster.geometry(\"300x300\")\n\ng = Graph()\nj = Graph()\n\n#Opens file explorer so user can select turtle file to parse from any path. Parses the entire file into a holder graph g\ndef selectFile():\n try:\n master.fileName = filedialog.askopenfilename(filetypes=((\"turtle files\", \".ttl\"), (\"All files\", \"*\")))\n print(\"Parsing file please wait\")\n g.parse(master.fileName, format=\"turtle\")\n print(\"done parsing\")\n except:\n print(\"Invalid file selection, parsing incomplete\")\n\n#exit the application\ndef closeWindows():\n os.system(\"TASKKILL /F /IM ManualSearch.exe\")\n exit()\n\n\ndef visualize():\n try:\n j=Graph()\n l=0\n #iterate through g until the subject number specified by user is found\n for s in g.subjects():\n if l == c:\n selectedR = s\n break\n l+=1\n #add all triples in g that have the selected resource as their subject and add to j\n for s, p, o in g.triples((selectedR, None, None)):\n j.add((s, p, o))\n #add all triples in g that have the selected resource as their object and add to j\n for s, p, o in g.triples((None, None,selectedR)):\n #check if this relationship is already detailed in j\n if not j.__contains__((None, None, s)):\n j.add((s, p, o))\n\n #creates the graph visually and saves it as an svg file\n stream = io.StringIO()\n rdf2dot(j, stream, opts={display})\n dg = pydotplus.graph_from_dot_data(stream.getvalue())\n dg.write_svg(\"graph\"+str(c)+\".svg\")\n print(\"Graph saved\")\n #once complete the graph is automatically opened in chrome\n url = str(pathlib.Path().absolute())+\"/graph\" +str(c) +\".svg\"\n webbrowser.register('chrome',\n None,\n webbrowser.BackgroundBrowser(\"C://Program Files (x86)//Google//Chrome//Application//chrome.exe\"))\n webbrowser.get('chrome').open(url)\n except:\n print(\"unable to create graph\")\n\n\ndef subjectNumber():\n global c\n c = tkinter.simpledialog.askinteger(\"Data\",\"Which subject do you want select\")\n\n\noutput = Label(master, text=\"Simulation Visualizer\")\noutput.pack()\n\nbutton3 = Button(master, text=\"Select File\", command=selectFile)\nbutton3.pack()\n\nbutton4 = Button(master, text=\"Subject Number\", command=subjectNumber)\nbutton4.pack()\n\nbutton = Button(master, text=\"Graph Data\", command=visualize)\nbutton.pack()\n\nbutton2 = Button(master, text=\"Quit\", command=closeWindows)\nbutton2.pack()\n\nmainloop()\n","sub_path":"ManualSearch.py","file_name":"ManualSearch.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"640156344","text":"#! python3\n# multiplicationTable.py - Creates a multiplication table for a user-defined value.\n# Garbage code, still present, mixed with copied code - I took a complete shit on this one.\n# Copied from - https://github.com/priyankjain/automate-the-boring-stuff-with-python/blob/master/chapter-12/multiplicationTable.py\n\nimport openpyxl\n# from openpyxl.utils import get_column_letter\n\n\n# This is from copied code used to run from command line.\n# import openpyxl, sys\n# if len(sys.argv)!=2:\n# \tprint('Usage: python3 multiplicationTable.py ')\n# \tsys.exit(-1)\n# number = None #Nunber used in place of getNumber\n# try:\n# \tnumber = abs(int(sys.argv[1]))\n# except ValueError as e:\n# \tprint('First argument should be an integer')\n# sys.exit(-1)\n\n\ngetNumber = input('Please enter the number that you would like to have multiplied: ')\n\n# columnLetter = ''\n# rowNumber = ''\n# pairVal = ''\n\n\nwb = openpyxl.Workbook()\nsheet = wb.active\nsheet.title = 'Multiplication Table'\n\nboldFont = openpyxl.styles.Font(bold=True)\nfor rowNum in range(1, int(getNumber) + 2):\n for colNum in range(1, int(getNumber) + 2):\n if rowNum == 1 and colNum == 1:\n sheet.cell(row=rowNum, column=colNum).value = ''\n elif rowNum == 1:\n sheet.cell(row=rowNum, column=colNum).value = colNum - 1\n sheet.cell(row=rowNum, column=colNum).font = boldFont\n elif colNum == 1:\n sheet.cell(row=rowNum, column=colNum).value = rowNum - 1\n sheet.cell(row=rowNum, column=colNum).font = boldFont\n else:\n sheet.cell(row=rowNum, column=colNum).value = (rowNum - 1) * (colNum - 1)\n\n# # sheet['A1'] = int(getNumber) All garbage - was no need to convert\n# for i in range(int(getNumber)):\n# # Column Headers\n# rowNumber = i + 1\n# columnLetter = get_column_letter(int(rowNumber + 1))\n# pairVal = str(columnLetter) + str(rowNumber)\n# sheet[pairVal] = i + 1\n# # sheet[('A' + str(rowNumber))] = i + 1\n\n\nwb.save('multiplicationTable.xlsx')\nprint('Done.')\n","sub_path":"AutomateTheBoringStuff/ATBS12 - Working with Excel Spreadsheets/multiplicationTable.py","file_name":"multiplicationTable.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"233685222","text":"from ...import core\nfrom ...typecheck import*\n\nfrom .adapter import Adapter\nimport json\nimport os\n\ndef save_schema(adapters: List[Adapter]):\n\n\tallOf = []\n\tfor adapter in adapters:\n\t\tif not adapter.configuration_schema:\n\t\t\tcontinue\n\n\t\tfor key, value in adapter.configuration_schema.items():\n\t\t\tallOf.append({\n\t\t\t\t'if': {\n\t\t\t\t\t'properties': {'type': { 'const': adapter.type }, 'request': { 'const': key }},\n\t\t\t\t},\n\t\t\t\t'then': value,\n\t\t\t})\n\n\tdebuggers_schema = {\n\t\t'type': 'object',\n\t\t'properties': {\n\t\t\t'name': {\n\t\t\t\t'description': 'Name of configuration; appears in the launch configuration drop down menu.',\n\t\t\t\t'type':'string'\n\t\t\t},\n\t\t\t'type': {\n\t\t\t\t'type':'string',\n\t\t\t\t'description': 'Type of configuration.'\n\t\t\t},\n\t\t\t'request': {\n\t\t\t\t'type': 'string',\n\t\t\t\t'description': 'Request type of configuration. Can be \"launch\" or \"attach\".',\n\t\t\t\t'enum': [ 'attach', 'launch' ]\n\t\t\t}\n\t\t},\n\t\t'required': ['type', 'name', 'request'],\n\t\t'allOf': allOf,\n\t}\n\n\tschema = {\n\t\t'description': 'Debugger Configuration File',\n\t\t'type': 'object',\n\t\t'properties': {\n\t\t\t'configurations': {\n\t\t\t\t'type': 'array',\n\t\t\t\t'items': debuggers_schema,\n\t\t\t}\n\t\t},\n\t\t'required': ['configurations']\n\t}\n\t\n\n\tpath = os.path.join(core.current_package(), 'data', 'schema.json')\n\twith open(path, 'w') as file:\n\t\tfile.write(json.dumps(schema, indent=\"\\t\"))","sub_path":"modules/debugger/adapter/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"343537847","text":"import openturns as ot\nfrom math import exp\nfrom matplotlib import pyplot as plt\nfrom openturns.viewer import View\n\n\ndef C(s, t):\n return exp(-4.0 * abs(s - t) / (1 + (s * s + t * t)))\n\n\nN = 64\na = 4.0\n# myMesh = ot.IntervalMesher([N]).build(ot.Interval(-a, a))\nmyMesh = ot.RegularGrid(-a, 2 * a / N, N + 1)\n\nvertices = myMesh.getVertices()\nmyCovariance = ot.CovarianceMatrix(len(vertices))\nfor k in range(len(vertices)):\n t = vertices[k]\n for l in range(k + 1):\n s = vertices[l]\n myCovariance[k, l] = C(s[0], t[0])\n\ncovarianceModel = ot.UserDefinedCovarianceModel(myMesh, myCovariance)\ncov_graph = covarianceModel.draw(0, 0, -a, a, 512)\nfig = plt.figure(figsize=(10, 4))\nplt.suptitle('User defined covariance model')\ncov_axis = fig.add_subplot(111)\nView(cov_graph, figure=fig, axes=[cov_axis],\n add_legend=False, square_axes=True)\n","sub_path":"openturns/1.12/pyplots/UserDefinedCovarianceModel.py","file_name":"UserDefinedCovarianceModel.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"449348899","text":"# you can write to stdout for debugging purposes, e.g.\n# print \"this is a debug message\"\n\ndef solution(X, A):\n # write your code in Python 2.7\n covered = [False]*X\n uncovered = X\n for i in xrange(len(A)):\n if covered[A[i]-1] == False:\n covered[A[i]-1] = True;\n uncovered -= 1\n if uncovered == 0:\n return i\n \n return -1","sub_path":"04_FrogRiverOne.py","file_name":"04_FrogRiverOne.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"112063220","text":"from myhdl import block, instances, SignalType, always, Signal, always_comb, always_seq\n\nfrom framework import data_desc\nfrom framework.packed_struct import StructDescription, StructDescriptionMetaclass, BitVector\nfrom framework.fifo import FifoConsumer, FifoProducer, fifo\nfrom framework.pipeline import PipeInput, PipeOutput, Pipe, PipeConstant, PipeSignal\nfrom framework.vector_utils import vec_mul\nfrom generator.utils import assign, assign_3, assign_2\nfrom utils import num\nfrom generator.config import Config\nfrom generator.rk_stage import stage\n\n\n@block\ndef solver(\n config: Config,\n clk: SignalType,\n rst: SignalType,\n data_in: FifoConsumer,\n data_out: FifoProducer\n):\n solver_input_desc = data_desc.get_input_desc(config.system_size)\n solver_input = solver_input_desc.create_read_instance(data_in.data)\n solver_input_inst = solver_input.instances()\n solver_input_reg_filled = Signal(bool(0))\n solver_input_reg = solver_input_desc.create_write_instance()\n\n solver_output_desc = data_desc.get_output_desc(config.system_size)\n solver_output = solver_output_desc.create_write_instance()\n solver_output_packed = solver_output.packed()\n solver_output_reg = solver_output_desc.create_write_instance()\n solver_output_reg_filled = Signal(bool(0))\n\n if '_bit_padding' in solver_output_desc.get_fields():\n @always_seq(clk.posedge, reset=None)\n def drive_output_bit_padding():\n solver_output._bit_padding.next = 0\n\n integer_type = num.UnsignedIntegerNumberType(32)\n numeric_type = num.get_default_type()\n\n class PipeData(StructDescription, metaclass=StructDescriptionMetaclass):\n id = BitVector(integer_type)\n h = BitVector(numeric_type)\n n = BitVector(numeric_type)\n cn = BitVector(numeric_type)\n x = BitVector(numeric_type)\n y = [BitVector(numeric_type) for _ in range(config.system_size)]\n\n pipe_input_valid = Signal(bool(0))\n pipe_output_busy = Signal(bool(0))\n\n pipe_input_id = Signal(integer_type.create())\n pipe_input_h = Signal(numeric_type.create())\n pipe_input_n = Signal(integer_type.create())\n pipe_input_cn = Signal(integer_type.create())\n pipe_input_x = Signal(numeric_type.create())\n pipe_input_y = [Signal(numeric_type.create()) for _ in range(config.system_size)]\n\n cycle_p = FifoProducer(BitVector(len(PipeData)).create_instance())\n cycle_c = FifoConsumer(BitVector(len(PipeData)).create_instance())\n cycle_fifo = fifo(clk, rst, cycle_p, cycle_c, buffer_size_bits=2)\n cycle_input = PipeData.create_write_instance()\n cycle_input_packed = cycle_input.packed()\n cycle_input_reg = PipeData.create_write_instance()\n cycle_input_reg_filled = Signal(bool(0))\n cycle_output = PipeData.create_read_instance(cycle_c.data)\n cycle_output_inst = cycle_output.instances()\n\n pipe_data_in = PipeInput(pipe_input_valid,\n id=PipeSignal(integer_type, pipe_input_id),\n h=PipeSignal(numeric_type, pipe_input_h),\n n=PipeSignal(integer_type, pipe_input_n),\n cn=PipeSignal(integer_type, pipe_input_cn),\n x=PipeSignal(numeric_type, pipe_input_x),\n y=list(map(lambda x: PipeSignal(numeric_type, x), pipe_input_y)))\n v = []\n for si in range(config.stages):\n v.append(\n stage(config.get_stage_config(si), pipe_data_in.h, pipe_data_in.x, pipe_data_in.y, v)\n )\n\n y_n = [\n pipe_data_in.y[i] + pipe_data_in.h * vec_mul(\n [PipeConstant.from_float(el) for el in config.b],\n [el[i] for el in v]\n ) for i in range(config.system_size)\n ]\n\n pipe_data_out = PipeOutput(pipe_output_busy,\n id=pipe_data_in.id,\n h=pipe_data_in.h,\n n=pipe_data_in.n,\n cn=pipe_data_in.cn + PipeConstant.from_float(1, integer_type),\n x=pipe_data_in.x + pipe_data_in.h,\n y=y_n)\n pipe = Pipe(pipe_data_in, pipe_data_out)\n print(pipe.get_stats())\n pipe_inst = pipe.create(clk, rst)\n\n @always(clk.posedge)\n def state_machine():\n if rst:\n pipe_input_valid.next = False\n data_in.rd.next = True\n data_out.wr.next = False\n cycle_p.wr.next = False\n solver_input_reg_filled.next = False\n solver_output_reg_filled.next = False\n cycle_input_reg_filled.next = False\n else:\n if not pipe_data_in.pipe_busy:\n if cycle_c.rd and not cycle_c.empty:\n pipe_input_id.next = cycle_output.id\n pipe_input_h.next = cycle_output.h\n pipe_input_n.next = cycle_output.n\n pipe_input_cn.next = cycle_output.cn\n pipe_input_x.next = cycle_output.x\n pipe_input_valid.next = True\n if data_in.rd and not data_in.empty:\n # Save into register\n solver_input_reg.id.next = solver_input.id\n solver_input_reg.h.next = solver_input.h\n solver_input_reg.n.next = solver_input.n\n solver_input_reg.x_start.next = solver_input.x_start\n\n solver_input_reg_filled.next = True\n data_in.rd.next = False\n elif data_in.rd and not data_in.empty:\n pipe_input_id.next = solver_input.id\n pipe_input_h.next = solver_input.h\n pipe_input_n.next = solver_input.n\n pipe_input_cn.next = 0\n pipe_input_x.next = solver_input.x_start\n pipe_input_valid.next = True\n data_in.rd.next = True\n elif solver_input_reg_filled:\n pipe_input_id.next = solver_input_reg.id\n pipe_input_h.next = solver_input_reg.h\n pipe_input_n.next = solver_input_reg.n\n pipe_input_cn.next = 0\n pipe_input_x.next = solver_input_reg.x_start\n pipe_input_valid.next = True\n\n solver_input_reg_filled.next = False\n data_in.rd.next = True\n else:\n pipe_input_valid.next = False\n else:\n if data_in.rd and not data_in.empty:\n # Save into register\n solver_input_reg.id.next = solver_input.id\n solver_input_reg.h.next = solver_input.h\n solver_input_reg.n.next = solver_input.n\n solver_input_reg.x_start.next = solver_input.x_start\n\n solver_input_reg_filled.next = True\n data_in.rd.next = False\n\n # Output\n if not data_out.full:\n if solver_output_reg_filled:\n # From register\n solver_output.id.next = solver_output_reg.id\n solver_output.x.next = solver_output_reg.x\n\n solver_output_reg_filled.next = False\n data_out.wr.next = True\n elif not pipe_output_busy and pipe_data_out.pipe_valid and pipe_data_out.cn >= pipe_data_out.n:\n # Directly pass\n solver_output.id.next = pipe_data_out.id\n solver_output.x.next = pipe_data_out.x\n\n data_out.wr.next = True\n else:\n data_out.wr.next = False\n else:\n if not pipe_output_busy and pipe_data_out.pipe_valid and pipe_data_out.cn >= pipe_data_out.n:\n # Save to reg\n solver_output_reg.id.next = pipe_data_out.id\n solver_output_reg.x.next = pipe_data_out.x\n\n solver_output_reg_filled.next = True\n\n if not cycle_p.full:\n if cycle_input_reg_filled:\n # From register\n cycle_input.id.next = cycle_input_reg.id\n cycle_input.h.next = cycle_input_reg.h\n cycle_input.n.next = cycle_input_reg.n\n cycle_input.cn.next = cycle_input_reg.cn\n cycle_input.x.next = cycle_input_reg.x\n\n cycle_input_reg_filled.next = False\n cycle_p.wr.next = True\n elif not pipe_output_busy and pipe_data_out.pipe_valid\\\n and pipe_data_out.cn < pipe_data_out.n:\n # Directly pass\n cycle_input.id.next = pipe_data_out.id\n cycle_input.h.next = pipe_data_out.h\n cycle_input.n.next = pipe_data_out.n\n cycle_input.cn.next = pipe_data_out.cn\n cycle_input.x.next = pipe_data_out.x\n\n cycle_p.wr.next = True\n else:\n cycle_p.wr.next = False\n else:\n if not pipe_output_busy and pipe_data_out.pipe_valid and pipe_data_out.cn < pipe_data_out.n:\n # Save to reg\n cycle_input_reg.id.next = pipe_data_out.id\n cycle_input_reg.h.next = pipe_data_out.h\n cycle_input_reg.n.next = pipe_data_out.n\n cycle_input_reg.cn.next = pipe_data_out.cn\n cycle_input_reg.x.next = pipe_data_out.x\n\n cycle_input_reg_filled.next = True\n\n do_cycle_output_to_pipe_input = Signal(bool(0))\n do_solver_input_to_solver_reg = Signal(bool(0))\n do_solver_input_to_pipe_input = Signal(bool(0))\n do_solver_reg_to_pipe_input = Signal(bool(0))\n\n @always_comb\n def input_state_driver():\n do_cycle_output_to_pipe_input.next = False\n do_solver_input_to_solver_reg.next = False\n do_solver_input_to_pipe_input.next = False\n do_solver_reg_to_pipe_input.next = False\n if not pipe_data_in.pipe_busy:\n if cycle_c.rd and not cycle_c.empty:\n do_cycle_output_to_pipe_input.next = True\n if data_in.rd and not data_in.empty:\n # Save into register\n do_solver_input_to_solver_reg.next = True\n elif data_in.rd and not data_in.empty:\n do_solver_input_to_pipe_input.next = True\n elif solver_input_reg_filled:\n do_solver_reg_to_pipe_input.next = True\n else:\n if data_in.rd and not data_in.empty:\n # Save into register\n do_solver_input_to_solver_reg.next = True\n\n do_solver_output_reg_to_solver_output = Signal(bool(0))\n do_pipe_output_reg_to_solver_output = Signal(bool(0))\n do_pipe_output_to_solver_output_reg = Signal(bool(0))\n do_cycle_input_reg_to_cycle_input = Signal(bool(0))\n do_pipe_output_to_cycle_input = Signal(bool(0))\n do_pipe_output_to_cycle_input_reg = Signal(bool(0))\n\n @always_comb\n def output_state_driver():\n do_solver_output_reg_to_solver_output.next = False\n do_pipe_output_reg_to_solver_output.next = False\n do_pipe_output_to_solver_output_reg.next = False\n if not data_out.full:\n if solver_output_reg_filled:\n # From register\n do_solver_output_reg_to_solver_output.next = True\n elif not pipe_output_busy and pipe_data_out.pipe_valid and pipe_data_out.cn >= pipe_data_out.n:\n # Directly pass\n do_pipe_output_reg_to_solver_output.next = True\n else:\n if not pipe_output_busy and pipe_data_out.pipe_valid and pipe_data_out.cn >= pipe_data_out.n:\n # Save to reg\n do_pipe_output_to_solver_output_reg.next = True\n\n do_cycle_input_reg_to_cycle_input.next = False\n do_pipe_output_to_cycle_input.next = False\n do_pipe_output_to_cycle_input_reg.next = False\n\n if not cycle_p.full:\n if cycle_input_reg_filled:\n # From register\n do_cycle_input_reg_to_cycle_input.next = True\n elif not pipe_output_busy and pipe_data_out.pipe_valid \\\n and pipe_data_out.cn < pipe_data_out.n:\n # Directly pass\n do_pipe_output_to_cycle_input.next = True\n else:\n if not pipe_output_busy and pipe_data_out.pipe_valid and pipe_data_out.cn < pipe_data_out.n:\n # Save to reg\n do_pipe_output_to_cycle_input_reg.next = True\n\n @always_comb\n def pipe_output_busy_driver():\n pipe_output_busy.next = solver_output_reg_filled or cycle_input_reg_filled\n\n @always_comb\n def cycle_rd_driver():\n cycle_c.rd.next = not pipe_data_in.pipe_busy\n\n @always_comb\n def cycle_input_driver():\n cycle_p.data.next = cycle_input_packed\n\n @always_comb\n def assign_solver_output():\n data_out.data.next = solver_output_packed\n\n y_data_in_store = [\n assign(clk, do_solver_input_to_solver_reg, solver_input.y_start[i], solver_input_reg.y_start[i])\n for i in range(config.system_size)\n ]\n\n y_data_in = [\n assign_3(clk,\n do_solver_input_to_pipe_input, solver_input.y_start[i],\n do_cycle_output_to_pipe_input, cycle_output.y[i],\n do_solver_reg_to_pipe_input, solver_input_reg.y_start[i],\n pipe_input_y[i])\n for i in range(config.system_size)\n ]\n\n y_data_out = [\n assign_2(clk,\n do_solver_output_reg_to_solver_output, solver_output_reg.y[i],\n do_pipe_output_reg_to_solver_output, pipe_data_out.y[i],\n solver_output.y[i])\n for i in range(config.system_size)\n ]\n\n y_data_out_store = [\n assign(clk, do_pipe_output_to_solver_output_reg, pipe_data_out.y[i], solver_output_reg.y[i])\n for i in range(config.system_size)\n ]\n\n y_cycle_in = [\n assign_2(clk,\n do_cycle_input_reg_to_cycle_input, cycle_input_reg.y[i],\n do_pipe_output_to_cycle_input, pipe_data_out.y[i],\n cycle_input.y[i])\n for i in range(config.system_size)\n ]\n\n y_cycle_store = [\n assign(clk, do_pipe_output_to_cycle_input_reg, pipe_data_out.y[i], cycle_input_reg.y[i])\n for i in range(config.system_size)\n ]\n\n return instances()\n","sub_path":"generator/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":14594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"623557016","text":"# built-in\nimport json\nfrom functools import partial\n\n# third-party\nimport tkinter as tk\n\nclass add_quiz:\n def __init__(self):\n self.quiz_theme: str\n self.quiz: dict = {}\n self.make_window()\n\n def make_window(self):\n self.add_qz_window = tk.Tk() # !!! window\n self.add_qz_window.geometry(\"900x600\") # !!!\n\n self.question = tk.Entry(\n self.add_qz_window,\n width=256\n )\n self.entry_options_list = [\n tk.Entry(\n self.add_qz_window,\n width=\"256\"\n )\n for i in\n range(1, 4+1)\n ]\n self.right_option_entry = tk.Entry(\n self.add_qz_window,\n width=\"256\"\n )\n self.add_question_btn = tk.Button(\n self.add_qz_window,\n text=\"ДОБАВИТЬ ВОПРОС\",\n background=\"#36d88a\", # nice light green\n foreground=\"#000000\", # black\n width=\"256\",\n command=partial(\n self.add_question,\n self.add_qz_window,\n self.question,\n self.entry_options_list,\n self.right_option_entry\n )\n )\n self.done_quiz_btn = tk.Button(\n self.add_qz_window,\n text=\"ЗАКОНЧИТЬ ВИКТОРИНУ\",\n background=\"#3aaacf\", # nice light blue\n foreground=\"#000000\", # black\n width=\"256\",\n command=partial(\n self.done_quiz,\n self.add_qz_window\n )\n )\n # packing stuff\n self.question.pack()\n self.question.insert(0, \"вопрос\")\n for i, entry_option in enumerate(self.entry_options_list):\n entry_option.pack()\n entry_option.insert(0, \"{} вариант ответа\".format(i+1))\n\n self.right_option_entry.pack()\n self.right_option_entry.insert(0, \"номер правильного ответа\")\n self.add_question_btn.pack()\n self.done_quiz_btn.pack()\n self.add_qz_window.mainloop()\n\n def add_question(self,\n window: tk.Tk,\n question: tk.Entry,\n entry_options_list: list,\n right_option_entry: tk.Entry\n ) -> None:\n question_txt = question.get()\n txt_options_list = [\n option.get()\n for option in entry_options_list\n ]\n right_option_index = int(right_option_entry.get()) - 1\n window.destroy()\n self.quiz[question_txt] = {\n option: txt_options_list.index(option) == right_option_index\n for option in txt_options_list\n }\n self.make_window()\n \n def done_quiz(self,\n window: tk.Tk\n ) -> None:\n window.destroy()\n\n self.final_window = tk.Tk()\n self.final_window.geometry(\"300x300\")\n self.quiz_theme_entry = tk.Entry(\n self.final_window,\n width=\"256\"\n )\n self.done_btn = tk.Button(\n self.final_window,\n text=\"ГОТОВО\",\n background=\"#00b945\", # nice green\n foreground=\"#ffffff\", # white\n width=\"256\",\n command=partial(\n self.done_adding,\n self.final_window,\n self.quiz_theme_entry\n )\n )\n # packing\n self.quiz_theme_entry.pack()\n self.done_btn.pack()\n self.quiz_theme_entry.insert(0, \"название викторины\")\n self.final_window.mainloop()\n\n def done_adding(self,\n window: tk.Tk,\n quiz_theme_entry: tk.Entry\n ) -> None:\n self.quiz_theme = quiz_theme_entry.get()\n window.destroy()\n self.update_json(\n self.quiz_theme,\n self.quiz\n )\n\n def update_json(self,\n quiz_theme: str,\n quiz: dict\n ) -> None:\n with open(\"quizes.json\", \"r\") as file:\n json_object = json.load(file)\n json_object[quiz_theme] = quiz\n\n with open(\"quizes.json\", \"w\") as file:\n json.dump(json_object, file)\n\nif __name__ == \"__main__\":\n add_quiz()\n","sub_path":"add_quiz.py","file_name":"add_quiz.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"558124177","text":"'''\nChecks corpus of sentences for duplicates.\n'''\nimport sys\n\ndataFileFieldNames = [] # The field names from the top of the data spreadsheet.\ncorpus = [] # List of sentences in human-readable form (i.e. not in a bag of words representation)\nfileName = \"new_formality_data.csv\"\n\n\n# Checks if the 'fileName' is the correct file name\ndef checkFileNameCorrect():\n global fileName\n print(\"The default file name is \", fileName, \"\\n\")\n print(\"If this is the name of the data file, press enter\")\n newFileName = input(\"Otherwise, please provide the correct name, then press enter: \")\n if newFileName != \"\":\n fileName = newFileName\n print(\"\\nThank you. The file name has been changed to\", fileName)\n else:\n print(\"\\nThank you. You have confirmed that the file name is correct:\", fileName)\n\n\n# Checks if file present. Code for this module adapted from:\n# https://stackoverflow.com/questions/5627425/what-is-a-good-way-to-handle-exceptions-when-trying-to-read-a-file-in-python\ndef checkFilePresent():\n try:\n f = open(fileName, 'rb')\n except OSError:\n print(\"\\nFile not found:\", fileName)\n print(\"Please ensure that the data file is in the same folder as the program file.\")\n print(\"Exiting program.\")\n sys.exit()\n\n\n# This function loads the data from the file and stores it in the data structures shown above.\n# It is always the first function to be run.\n\n# This function loads the data from the file and stores it in the data structures\ndef loadData():\n checkFileNameCorrect()\n checkFilePresent()\n with open(fileName, encoding='utf-8') as inputFile:\n firstLine = inputFile.readline()\n firstLineAsList = firstLine.split(\",\")\n\n # Copy the data file field names into a global list:\n for items in firstLineAsList:\n dataFileFieldNames.append(items)\n\n # The sentence field is always the final field on the right. Therefore, the sentence index is the number of\n # fields up to and including the one immediately preceding the 'sentence' field.\n sentenceIndex = len(firstLineAsList)-1\n for line in inputFile:\n # Searches through the line for commas, character by character. Stops when 'sentenceIndex' number of commas\n # have been encountered.\n # The document is located to the right of the comma corresponding to index 'sentenceIndex'.\n # Everything to the left of that comma is data relating to the document.\n numCommas = 0\n for character in range(len(line)):\n\n # Increments numCommas whenever a comma is encountered in the line.\n if line[character] == \",\":\n numCommas = numCommas + 1\n\n # The code below is run when when the number of commas encountered equals the value of 'sentenceIndex'.\n # When the code below is run, it means that everything on the line to the right of the last comma\n # encountered is part of the sentence, and not attribute data.\n if numCommas == sentenceIndex:\n documentToAdd = line[character + 1:] # The rest of the current line is comprised of the document\n\n # Puts document into a list of Strings:\n corpus.append(documentToAdd)\n break # returns to the outer 'for' loop, so the next line can be processed.\n inputFile.close()\n print(\"\\nNo of records uploaded: \", len(corpus))\n\n\ndef testForUniqueSentences():\n tempSentencesList = []\n duplicate = False\n for sentence in corpus:\n if sentence in tempSentencesList:\n print(\"Duplicate sentence: \" + sentence)\n duplicate = True\n tempSentencesList.append(sentence)\n if not duplicate:\n print(\"\\nGood news! No duplicates were found.\")\n\n\n# METHOD CALLS THAT EXECUTE WHENEVER THE PROGRAM IS RUN\n\nloadData()\ntestForUniqueSentences()","sub_path":"Program integrity test material/checkForDuplicateSentences.py","file_name":"checkForDuplicateSentences.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"95423566","text":"from __future__ import print_function\nimport os\nimport sys\nimport threading\nfrom src import device, miner, reporter, wording\n\nif sys.version_info < (3, 4):\n\texit(wording.get('version_no').format(sys.version_info.major, sys.version_info.minor) + wording.get('exclamation_mark'))\n\ntry:\n\tfrom openrazer.client import DeviceManager, DaemonNotFound\nexcept ImportError:\n\texit(wording.get('driver_no') + wording.get('exclamation_mark'))\n\ntry:\n\tdevice_manager = DeviceManager()\n\tdevice_manager.sync_effects = True\nexcept DaemonNotFound:\n\texit(wording.get('daemon_no') + wording.get('exclamation_mark'))\n\n\ndef run(args):\n\tif threading.active_count() == 1:\n\t\treporter.header()\n\t\tprint()\n\n\t# process miner\n\n\tdata = miner.process(args)\n\n\t# handle data\n\n\tif len(data) == 0:\n\t\texit(wording.get('data_no') + wording.get('exclamation_mark'))\n\n\t# process data\n\n\tresult = reporter.process(data)\n\tif result:\n\t\treporter.log(result)\n\t\tprint()\n\n\t# handle dry run\n\n\tif args.dry_run is False:\n\n\t\t# handle device\n\n\t\tif len(device_manager.devices) == 0:\n\t\t\texit(wording.get('device_no') + wording.get('exclamation_mark'))\n\n\t\t# process device\n\n\t\tresult = device.process(device_manager.devices, result['status'])\n\t\tif result:\n\t\t\treporter.log(result)\n\t\t\tprint()\n\n\t# handle thread\n\n\tif args.background_run is True:\n\t\tthreading.Timer(args.background_interval, run, args =\n\t\t[\n\t\t\targs\n\t\t]).start()\n\n\ndef destroy(number, frame):\n\tprint('\\r' + wording.get('goodbye') + wording.get('exclamation_mark'))\n\tos._exit(0)\n","sub_path":"src/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"111505139","text":"\"\"\"\n===========================\nPandas CSV Reader Reference\n===========================\n\nA reference of needed keyword arguments to ensure that different types of\n`.csv` files are appropriately loaded as pandas dataframes.\n\"\"\"\n\nimport pandas as pd\n\n\ndef maxime_rdf_csv(path):\n \"\"\"\n Creates pandas dataframes from Maxime's RDF files.\n Maxime-RDF\n \"\"\"\n df = pd.read_csv(\n filepath_or_buffer=path,\n index_col=False,\n sep='\\s+' # Split by whitespace\n )\n # Move the columns to deal with the leading hash-tag\n df_mod = df[df.columns[:-1]]\n df_mod.columns = df.columns[1:]\n\n return df_mod\n","sub_path":"pdcsvref.py","file_name":"pdcsvref.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"465958652","text":"# -*- coding: UTF-8 -*-\n\n# Copyright (c) 2007 Daniele Favara .\n#\n# This is free software you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; either version 2, or (at your option) any\n# later version.\n#\n# This software is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this software; see the file COPYING. If not, write to the Free\n# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA\n\nimport optparse\n\nOptionValueError = optparse.OptionValueError\n\nclass HelpFormatter(optparse.HelpFormatter):\n\n def __init__(self):\n optparse.HelpFormatter.__init__(self, 2, 24, 79, 1)\n\n def format_usage(self, usage):\n return \"Usage: %s\\n\" % usage\n\n def format_heading(self, heading):\n return \"\\n%*s%s:\\n\" % (self.current_indent, \"\", heading.capitalize())\n \"options\"\n\n def format_description(self, description):\n return description.strip()\n\n def format_option(self, option):\n help = option.help\n if help:\n option.help = help.capitalize()\n result = optparse.HelpFormatter.format_option(self, option)\n option.help = help\n return result\n\nclass OptionParser(optparse.OptionParser):\n\n def __init__(self, usage=None, help=None, examples=None,\n **kwargs):\n if not \"formatter\" in kwargs:\n kwargs[\"formatter\"] = HelpFormatter()\n optparse.OptionParser.__init__(self, usage, **kwargs)\n self._override_help = help\n self._examples = examples\n\n def format_help(self, formatter=None):\n if formatter is None:\n formatter = self.formatter\n if self._override_help:\n result = self._override_help.strip()\n result += \"\\n\"\n else:\n result = optparse.OptionParser.format_help(self, formatter)\n result = result.strip()\n result += \"\\n\"\n if self._examples:\n result += formatter.format_heading(\"examples\")\n formatter.indent()\n for line in self._examples.strip().splitlines():\n result += \" \"*formatter.current_indent\n result += line+\"\\n\"\n formatter.dedent()\n result += \"\\n\"\n return result\n\n# vim:et:ts=4:sw=4\n\n","sub_path":"tginvoice/utils/option.py","file_name":"option.py","file_ext":"py","file_size_in_byte":2615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"548729277","text":"\"\"\"The visualize main file to launch the server\"\"\"\nimport json\nimport os\nimport sys\nfrom io import BytesIO\n\nimport numpy as np\nimport pandas as pd\nfrom flask import Flask, render_template, request, make_response\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\ntry:\n from train.reward import discounted_rewards_function\n from public.models.bot.trainedBot import TrainedBot\nexcept:\n raise\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef home():\n return render_template('visualizer.html')\n\n\nprint(\"Look at http://127.0.0.1:5000/performance.png for performance insights\")\n\n\n@app.route(\"/performance.png\")\ndef performance_plot():\n \"\"\"\n Plot the performance at this address\n :return:\n \"\"\"\n fig = Figure()\n sub1 = fig.add_subplot(111)\n path_to_variables = os.path.abspath(os.path.dirname(__file__)) + '/../public/models/variables/'\n list_variables = [name for name in os.listdir(path_to_variables) if name != \"README.md\"]\n path_to_npy = [path_to_variables + name + '/' + name + '.npy' for name in list_variables]\n\n rewards = [np.load(path) for path in path_to_npy]\n\n max_len = max([len(reward) for reward in rewards])\n for i, reward in enumerate(rewards):\n rewards[i] = np.append(reward, np.repeat(np.nan, max_len - len(reward)))\n\n pd.DataFrame(np.array(rewards).T, columns=list_variables).rolling(100).mean().plot(\n title=\"Weighted reward at each game. (Rolling average)\", ax=sub1)\n\n plt.show()\n canvas = FigureCanvas(fig)\n png_output = BytesIO()\n canvas.print_png(png_output)\n response = make_response(png_output.getvalue())\n response.headers['Content-Type'] = 'image/png'\n return response\n\n\ndef convert(r):\n \"\"\"\n Convert the r to the game_states/moves tuple.\n :param r:\n :return:\n \"\"\"\n def get_owner(square):\n return square['owner']\n\n def get_strength(square):\n return square['strength']\n\n get_owner = np.vectorize(get_owner)\n get_strength = np.vectorize(get_strength)\n owner_frames = get_owner(r.json[\"frames\"])[:, np.newaxis, :, :]\n strength_frames = get_strength(r.json[\"frames\"])[:, np.newaxis, :, :]\n production_frames = np.repeat(np.array(r.json[\"productions\"])[np.newaxis, np.newaxis, :, :],\n len(owner_frames),\n axis=0)\n\n moves = np.array(r.json['moves'])\n\n game_states = np.concatenate(([owner_frames, strength_frames, production_frames]), axis=1)\n\n moves = ((-5 + 5 * game_states[:-1, 0, :]) + ((moves - 1) % 5))\n return game_states, moves\n\n\n@app.route('/post_discounted_rewards', methods=['POST'])\ndef post_discounted_rewards():\n game_states, moves = convert(request)\n discounted_rewards = discounted_rewards_function(game_states, moves)\n return json.dumps({'discounted_rewards_function': discounted_rewards.tolist()})\n\n\n@app.route('/post_policies', methods=['POST'])\ndef post_policies():\n game_states, _ = convert(request)\n bot = TrainedBot()\n policies = np.array([bot.get_policies(game_state) for game_state in game_states])\n return json.dumps({'policies': policies.tolist()})\n","sub_path":"visualize/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"632182251","text":"# coding:utf-8\nimport json\nimport requests\n\"\"\"\n创建回话,加入管理员,有了会话id,才能发送\nref: https://github.com/bluetom520/dingding/blob/master/dingding.py\n\"\"\"\n\n\nclass Ding(object):\n\n def __init__(self, corp_id, corp_secret, agent_id):\n self.corp_id = corp_id\n self.corp_secret = corp_secret\n self.agent_id = agent_id\n self.token_url = 'https://oapi.dingtalk.com/gettoken'\n self.get_dept_list_url = 'https://oapi.dingtalk.com/department/list'\n self.url_send = 'https://oapi.dingtalk.com/message/send'\n self.__params = {\n \"corpid\": self.corp_id,\n \"corpsecret\": self.corp_secret\n }\n\n self.access_token = self.get_access_token()\n self.token_params = {\n 'access_token': self.access_token\n }\n\n def get_access_token(self):\n headers = {'content-type': 'application/json'}\n res = requests.get(self.token_url, headers=headers, params=self.__params)\n return res.json()['access_token']\n\n def get_dept_list(self):\n res = requests.get(self.get_dept_list_url, params=self.token_params)\n return res.json()['department']\n\n def send_text_message(self, content, userid='', toparty=''):\n payload = {\n 'touser': userid,\n 'toparty': toparty,\n 'agentid': self.agent_id,\n\n \"msgtype\": \"text\",\n \"text\": {\n 'content': content\n }\n }\n headers = {'content-type': 'application/json'}\n params = self.token_params\n res = requests.post(self.url_send, headers=headers, params=params, data=json.dumps(payload))\n return res.json()\n\n\nclass DingHK(object):\n \"\"\"webbook 调用发送到群组\"\"\"\n\n def __init__(self, access_token):\n self.send_url = \"https://oapi.dingtalk.com/robot/send\"\n self.access_token = access_token\n self.__params = {\n 'access_token': access_token\n }\n\n def send_text(self, content):\n headers = {'content-type': 'application/json'}\n payload = {\n \"msgtype\": \"text\",\n \"text\": {\n \"content\": content\n }\n }\n res = requests.post(self.send_url, headers=headers,\n params=self.__params,\n data=json.dumps(payload))\n return res.json()\n","sub_path":"ding.py","file_name":"ding.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"526709239","text":"#-*- encoding: UTF-8 -*-\nfrom lxml import html\nimport requests\nimport pandas as pd\n\ndef smm():\n '''获取smm的每日有色金属报价数据,e.g.\n name price aver change date\n 0 1#铜 36980-37150 37065 -105 08-16\n 1 升贴水 (贴) 40-(升) 50 5 -95 11:30\n 2 洋山铜溢价($) $ 40-50 $ 45 0 08-16\n 3 跨境人民币价 265.88-332.36 299.12 -0.16 08-16\n 4 A00铝 12590-12630 12610 10 08-16\n 5 升贴水 (升) 80-(升) 120 100 240 10:15\n 6 1#铅 13650-13750 13700 -75 08-16'''\n url='http://www.smm.cn/'\n xpath_name='//td[@class=\"name\"]/a/text()'#提取品种\n xpath_price = '//td[@class=\"price\"]/text()' # 提取价格\n xpath_aver = '//td[@class=\"aver\"]/text()' # 提取均价\n xpath_change = '//td[@class=\"change\"]/text()' # 提取价格变动\n xpath_today = '//td[@class=\"today\"]/text()' # 提取价格变动\n\n page = requests.get(url)\n tree = html.fromstring(page.content.decode('gbk'))\n name= tree.xpath(xpath_name)\n price = tree.xpath(xpath_price)\n aver = tree.xpath(xpath_aver)\n change=tree.xpath(xpath_change)\n today=tree.xpath(xpath_today)\n change.insert(1,-95)\n aver.insert(5,100)\n\n print()\n data={\"name\":name,'price':price,'aver':aver,'change':change,'time':today}\n df=pd.DataFrame(data).iloc[:,[2,3,0,1,4]]\n print(df)\n df.to_excel('smm.xlsx')\n\nif __name__=='__main__':\n smm()\n","sub_path":"database/smm_metal_price.py","file_name":"smm_metal_price.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"327034691","text":"import os\nimport numpy as np\nimport visdom\nimport matplotlib.image as mpimg\nfrom matplotlib.pyplot import imshow\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n\n# parse declarative query to ialgebra_name\nname2operator = {\n 'projection': 'operator.projection',\n 'selection': 'operator.selection',\n 'join': 'operator.join',\n 'antijoin': 'operator.antijoin'\n}\n\nname2compositer = {\n 'slct_proj': 'compositer.slct_proj',\n 'slct_join': 'compositer.slct_join',\n 'slct_anjo': 'compositer.slct_anjo',\n 'proj_join': 'compositer.proj_join',\n 'proj_anjo': 'compositer.proj_anjo',\n 'slct_proj_join': 'compositer.slct_proj_join',\n 'slct_proj_anjo': 'compositer.slct_proj_anjo',\n}\n\n\ndef ialgebra_interpreter(inputs_tup, models_tup, identity_name, operators_tup, operators_kwargs_tup, compositer, identity_kwargs=None):\n \"\"\"\n *Function*: \n operate saliency_maps to meet user demands\n None: if there are multiple inputs, but only one is needed to interpret for the operation, we choose the 1st input as default.\n\n\n *Inputs*:\n :input_tup: ((bx1, by1), (bx2,by2),...,(bxn,byn))\n :models_tup: (model1_kwargs, model2_kwargs, ..., modeln_kwargs)\n : model_kwargs: {'model_name': model_name, 'layer': layer, 'dataset': dataset, 'model_dir': model_dir}\n :identity_name: str()\n :identity_kwargs: dict{}\n :operators: (operator1, operator2 ,..., operatorn)\n :operators_kwargs: (operator1_kwargs, operator2_kwargs ,..., operatorn_kwargs)\n : operator_kwargs: dict{}\n\n\n *Returns*:\n :ialgebra_map: shape = [B*C*H*W], type = numpy.ndarray\n :ialgebra_mapimg: ialgebra_map+img (might not use): shape = [B*C*H*W], type = numpy.ndarray \n \"\"\"\n # parse ialgebra_name:\n ialgebra_name = operators_tup #todo\n\n if compositer:\n _ialgebra_class = getattr(getattr(__import__(\"ialgebra\"), \"operations\"), name2compositer[ialgebra_name]) \n else:\n _ialgebra_class = getattr(getattr(__import__(\"ialgebra\"), \"operations\"), name2operator[ialgebra_name]) \n \n ialgebra_map, ialgebra_mapimg = _ialgebra_class(inputs_tup, models_tup, identity_name, operators_tup, operators_kwargs_tup, identity_kwargs)\n # to revise\n\n return ialgebra_map, ialgebra_mapimg\n\n\n\ndef vis_saliancy_map(ialgebra_map, ialgebra_mapimg, vis_method = 'imshow', vis_sport = 80):\n \"\"\"\n Visualize attribution map\n\n Input: \n :ialgebra_map: shape = [B*C*H*W]\n :ialgebra_mapimg: ialgebra_map+img (shape = [B*C*H*W])\n :vis_method = 'imshow', 'vis'\n \"\"\"\n\n if vis_method == 'imshow':\n if len(ialgebra_mapimg.shape) == 3:\n imshow(ialgebra_mapimg.transpose(1,2,0)) # imshow (H, W, C)\n elif len(ialgebra_mapimg.shape) == 4:\n for k in range(len(ialgebra_mapimg)):\n imshow(ialgebra_mapimg[k][:,:,::-1])\n\n elif vis_method == 'visdom':\n vis = visdom.Visdom(env='ialgebra_visualization', port=vis_sport)\n # vis.images([ialgebra_map, ialgebra_mapimg], win='iAlgebra_maps', opts=dict(title='iAlgebra_mapimg'))\n\n\ndef save_attribution_map(ialgebra_map, ialgebra_mapimg, save_dir, save_ialgebra_map = False):\n \"\"\"\n Save attribution map:\n : 1) .npz dicts\n : 2) .png figures\n\n Input: \n :ialgebra_map: shape = [B*C*H*W]\n :ialgebra_mapimg: ialgebra_map+img (shape = [B*C*H*W])\n :save_dir\n \"\"\"\n\n # save .npy file\n save_dobj = {'ialgebra_map': ialgebra_map, 'ialgebra_mapimg': ialgebra_mapimg}\n os.makedirs(save_dir) if not os.path.exists(save_dir) else None\n np.savez(os.path.join(save_dir, 'ialgebra_maps.npz'), **save_dobj)\n\n # save figures\n if len(ialgebra_mapimg.shape) == 3:\n mpimg.imsave(os.path.join(save_dir, 'ialgebra_mapimg_None.png'), np.transpose(ialgebra_mapimg, (1, 2, 0)))\n elif len(ialgebra_mapimg.shape) == 4:\n for k in range(len(ialgebra_mapimg)):\n mpimg.imsave(os.path.join(save_dir, 'ialgebra_mapimg_{}.png'.format(k)), np.transpose(ialgebra_mapimg[k], (1, 2, 0)))\n \n if save_ialgebra_map:\n if len(ialgebra_mapimg.shape) == 3:\n mpimg.imsave(os.path.join(save_dir, 'ialgebra_map_None.png'), np.transpose(ialgebra_map, (1, 2, 0)))\n elif len(ialgebra_mapimg.shape) == 4:\n for k in range(len(ialgebra_map)):\n mpimg.imsave(os.path.join(save_dir, 'ialgebra_map_{}.png'.format(k)), np.transpose(ialgebra_map[k], (1, 2, 0)))\n ","sub_path":"build/lib/ialgebra/utils/utils_operation.py","file_name":"utils_operation.py","file_ext":"py","file_size_in_byte":4408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"337654133","text":"# -*- coding:utf-8 -*-\nimport os\nimport re\nimport random\nimport sys\nimport traceback\nfrom _socket import timeout\nfrom urllib.parse import urlparse\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nimport requests\nfrom requests.exceptions import Timeout, ProxyError, ConnectionError\nfrom requests import HTTPError\nfrom scrapy.cmdline import execute\n\nFREE_PROXY_SOURCE = \"https://raw.githubusercontent.com/clarketm/proxy-list/master/proxy-list.txt\"\n\n\ndef _parse_text(text):\n if not text:\n return\n content, describe, *_ = text.split(\" \")\n if describe[3] == \"N\":\n return\n scheme = \"https\" if describe.endswith(\"S\") else \"http\"\n return f\"{scheme}://{content}\"\n\n\ndef _verify(proxy):\n url = urlparse(proxy)\n try:\n requests.get(f\"{url.scheme}://www.baidu.com\", proxies={url.scheme: proxy}, timeout=3)\n return proxy\n except (Timeout, ProxyError, ConnectionError, timeout):\n pass\n\n\ndef _fetch_free_proxies():\n response = requests.get(FREE_PROXY_SOURCE)\n response.raise_for_status()\n content = re.split(r\"\\n{2,}\", response.text)[1]\n proxy_text_list = content.split(\"\\n\")\n proxies = list(filter(lambda x: x, [_parse_text(text) for text in proxy_text_list]))\n random.shuffle(proxies)\n available_proxies = []\n with ThreadPoolExecutor(min(len(proxies), 30)) as executor:\n tasks = [executor.submit(_verify, proxy) for proxy in proxies]\n for task in as_completed(tasks):\n proxy = task.result()\n if proxy is not None:\n available_proxies.append(proxy)\n with open(os.path.join(\"proxies.txt\"), \"w\") as w:\n w.write(\"\\n\".join(available_proxies))\n\n\ndef main():\n current_path = os.path.dirname(os.path.abspath(__file__))\n sys.path.append(current_path)\n try:\n _fetch_free_proxies()\n except HTTPError:\n traceback.print_exc()\n execute([\"scrapy\", \"crawl\", \"maoyan\"])\n\n\nif __name__ == '__main__':\n main()","sub_path":"week02/work01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"238308440","text":"class Node:\n def __init__(self, value):\n self.left = None\n self.right = None\n self.value = value\n\n\ndef findCeilingFloor(root_node, k, floor=None, ceil=None):\n if not root_node:\n return floor, ceil\n\n if root_node.value == k:\n return k, k\n elif root_node.value < k:\n return findCeilingFloor(root_node.right, k, root_node.value, ceil)\n else:\n return findCeilingFloor(root_node.left, k, floor, root_node.value)\n\n\nroot = Node(8)\nroot.left = Node(4)\nroot.right = Node(12)\n\nroot.left.left = Node(2)\nroot.left.right = Node(6)\n\nroot.right.left = Node(10)\nroot.right.right = Node(14)\n\nprint(findCeilingFloor(root, 5))\n# (4, 6)","sub_path":"2019/11/DailyInterview-20191107/TheirSolution.py","file_name":"TheirSolution.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"626919826","text":"import math\nimport constants.const\n\nclass Wall:\n \"\"\"Defining the wall of the geometry\"\"\"\n k_vec = []\n m_vec = []\n theta_vec = []\n x_vec = []\n y_vec = []\n number_of_walls = 0\n def __init__(self,x_vec,y_vec):\n\n\n self.x_vec = x_vec\n self.y_vec = y_vec\n self.number_of_walls = len(x_vec)\n\n for i in range(self.number_of_walls - 1):\n x0 = x_vec[i]\n x1 = x_vec[i+1]\n y0 = y_vec[i]\n y1 = y_vec[i+1]\n\n # y = kx + m\n k = (y1 - y0) / (x1 - x0)\n m = y1 - k * x1\n theta = math.atan(k)\n self.k_vec.append(k)\n self.m_vec.append(m)\n self.theta_vec.append(theta)\n\n def get_y(self,x):\n for i in range(1,self.number_of_walls):\n if(self.x_vec[i] >= x):\n return self.k_vec[i-1] * x + self.m_vec[i-1]\n\n def get_wall_number(self,x):\n if(x < const.x0):\n return number_of_walls - 1\n if(x > const.xmax):\n return number_of_walls\n for i in range(self.number_of_walls - 1):\n x0 = self.x_vec[i]\n x1 = self.x_vec[i+1]\n if(x0 <= x and x <= x1):\n return i\n\n return None","sub_path":"PYPIC/classes/Wall.py","file_name":"Wall.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"278356395","text":"import imagematrix\n\nclass ResizeableImage(imagematrix.ImageMatrix):\n def best_seam(self):\n dp=dict()\n for j in range(self.height):\n for i in range(self.width):\n if j==0: dp[i,j]=self.energy(i,j),None\n elif self.width==1:\n dp[i,j]=dp[i,j-1][0]+self.energy(i,j),(i,j-1)\n elif i==0:\n x=min([(dp[i,j-1][0],(i,j-1)),(dp[i+1,j-1][0],(i+1,j-1))])\n dp[i,j]=x[0]+self.energy(i,j),x[1]\n elif i==self.width-1:\n x=min([(dp[i,j-1][0],(i,j-1)),(dp[i-1,j-1][0],(i-1,j-1))])\n dp[i,j]=x[0]+self.energy(i,j),x[1]\n else:\n x=min([(dp[i,j-1][0],(i,j-1)),(dp[i+1,j-1][0],(i+1,j-1)),(dp[i-1,j-1][0],(i-1,j-1))])\n dp[i,j]=x[0]+self.energy(i,j),x[1]\n path=[]\n u=min([(dp[i,self.height-1][0],i) for i in range(self.width)])\n x=u[1],self.height-1\n while x is not None:\n path.append(x)\n x=dp[x][1]\n path.reverse()\n return path\n \n\n def remove_best_seam(self):\n self.remove_seam(self.best_seam())\n","sub_path":"resizeable_image.py","file_name":"resizeable_image.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"602970657","text":"\n# -*- coding: utf-8 -*-\n\n# Python implementation of n-vector-based geodesy tools for an\n# ellipsoidal earth model. Transcribed from JavaScript originals by\n# (C) Chris Veness 2005-2016 and published under the same MIT Licence**,\n# see \n\nfrom bases import _LatLonHeightBase\nfrom utils import fsum, len2\nfrom vector3d import Vector3d, sumOf as _sumOf\n# from math import cos, sin\n\n# all public constants, classes and functions\n__all__ = ('NorthPole', 'SouthPole', # constants\n 'Nvector', # classes\n 'sumOf') # functions\n__version__ = '17.02.01'\n\n\nclass Nvector(Vector3d): # XXX kept private\n '''Base class for ellipsoidal and spherical Nvector.\n '''\n _h = 0\n\n H = '' # or '↑' XXX\n\n def __init__(self, x, y, z, h=0):\n '''Create an n-vector normal to the earth's surface.\n\n @param {number} x - X component.\n @param {number} y - Y component.\n @param {number} z - Z component.\n @param {number} [h=0] - Height above surface in meter.\n\n @example\n from ellipsoidalNvector import Nvector\n v = Nvector(0.5, 0.5, 0.7071, 1)\n v.toLatLon() # 45.0°N, 045.0°E, +1.00m\n '''\n Vector3d.__init__(self, x, y, z)\n if h:\n self._h = float(h)\n\n def copy(self):\n '''Copy this vector.\n\n @returns {Nvector} Copy of this vector.\n '''\n n = Vector3d.copy(self)\n if n.h != self.h:\n n.h = self.h\n return n\n\n @property\n def h(self):\n '''Height above surface in meter.\n '''\n return self._h\n\n @h.setter # PYCHOK setter!\n def h(self, h):\n '''Set height above surface in meter.\n '''\n self._update(h != self._h)\n self._h = h\n\n def to3llh(self):\n '''Convert this n-vector to (geodetic) lat-, longitude\n and height.\n\n @returns {(degrees90, degrees180, meter)} 3-Tuple of\n (lat, lon, height) equivalent to this n-vector.\n '''\n return Vector3d.to2ll(self) + (self.h,)\n\n def to4xyzh(self):\n '''Return this n-vector as a 4-tuple.\n\n @returns {(x, y, z, h)} 4-Tuple with the components of\n this n-vector.\n '''\n return self.x, self.y, self.z, self.h\n\n def toStr(self, prec=5, fmt='(%s)', sep=', '): # PYCHOK expected\n '''Return a string representation of this n-vector.\n\n Height component is only included if non-zero.\n\n @param {number} [prec=5] - Number of decimals, unstripped.\n @param {string} [fmt='[%s]'] - Enclosing backets format.\n @param {string} [sep=', '] - Separator between components.\n\n @returns {string} Comma-separated x, y, z [, h] values.\n\n @example\n Nvector(0.5, 0.5, 0.7071).toStr() # (0.5, 0.5, 0.7071)\n Nvector(0.5, 0.5, 0.7071, 1).toStr(-3) # (0.500, 0.500, 0.707, +1.00)\n '''\n t = Vector3d.toStr(self, prec=prec, fmt='%s', sep=sep)\n if self.h:\n t = '%s%s%s%+.2f' % (t, sep, self.H, self.h)\n return fmt % (t,)\n\n def unit(self):\n '''Normalize this vector to unit length.\n\n @returns {Nvector} Normalised vector.\n '''\n if self._united is None:\n u = Vector3d.unit(self).copy()\n if u.h != self.h:\n u.h = self.h\n self._united = u._united = u\n return self._united\n\n\nNorthPole = Nvector(0, 0, +1)\nSouthPole = Nvector(0, 0, -1)\n\n\nclass _LatLonNvectorBase(_LatLonHeightBase):\n '''Base class for n-vector-based ellipsoidal and spherical LatLon.\n '''\n\n def others(self, other, name='other'):\n '''Refine class comparison.\n '''\n try:\n _LatLonHeightBase.others(self, other, name=name)\n except TypeError:\n if not isinstance(other, Nvector):\n raise\n\n def to4xyzh(self):\n '''Convert this (geodetic) LatLon point to n-vector (normal\n to the earth's surface) x/y/z components and height.\n\n @returns {(meter, meter, meter, meter)} 4-Tuple (x, y, z, h).\n '''\n # Kenneth Gade eqn (3), but using right-handed\n # vector x -> 0°E,0°N, y -> 90°E,0°N, z -> 90°N\n# a, b = self.toradians()\n# ca = cos(a)\n# x, y, z = ca * cos(b), ca * sin(b), sin(a)\n return _LatLonHeightBase.to3xyz(self) + (self.height,)\n\n\ndef sumOf(nvectors, Vector=Nvector, **kwds):\n '''Return the vectorial sum of any number of n-vectors.\n\n @param {Nvector[]} nvectors - The n-vectors to be added.\n @param {Nvector} Vector - Vector class to instantiate.\n @param kwds - Optional, additional Vector keyword arguments.\n\n @returns {Vector} Vectorial sum.\n\n @throws {ValueError} No nvectors.\n '''\n n, nvectors = len2(nvectors)\n if n < 1:\n raise ValueError('no nvectors: %r' & (n,))\n if 'h' not in kwds:\n kwds['h'] = fsum(v.h for v in nvectors) / n\n return _sumOf(nvectors, Vector=Vector, **kwds)\n\n# **) MIT License\n#\n# Copyright (C) 2016-2017 -- mrJean1@Gmail.com\n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n","sub_path":"geodesy/nvector.py","file_name":"nvector.py","file_ext":"py","file_size_in_byte":6243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"554853412","text":"#!/usr/bin/env python\n\n\"\"\"\nCode to load a expert policy and learn in a dagger style.\nExample usage:\n python run_expert.py experts/Humanoid-v2.pkl Humanoid-v2 --render \\\n --num_rollouts 20\n\nAuthor: Naijia Fan\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport numpy as np\nimport gym\nimport load_policy\nimport load_expert\n\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('expert_policy_file', type=str)\n parser.add_argument('expert_data_file', type=str)\n parser.add_argument('cloning_policy_file', type=str)\n parser.add_argument('envname', type=str)\n parser.add_argument('--render', action='store_true')\n parser.add_argument(\"--max_timesteps\", type=int)\n parser.add_argument('--num_rollouts', type=int, default=20,\n help='Number of expert roll outs')\n parser.add_argument(\"--dagger_iterations\", type=int)\n args = parser.parse_args()\n\n policy_fn = load_policy.load_policy(args.expert_policy_file)\n x, y = load_expert.load_expert_data(args.expert_data_file)\n\n mean_rewards = []\n std_rewards = []\n\n for idx in range(args.dagger_iterations):\n print('dagger round %i/%i' % (idx, args.dagger_iterations))\n x_train, x_test, y_train, y_test = load_expert.split_expert_data(x, y)\n\n init = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run(init)\n env = gym.make(args.envname)\n max_steps = args.max_timesteps or env.spec.timestep_limit\n\n returns = []\n add_observations = []\n add_actions = []\n\n model = keras.Sequential([\n keras.layers.Dense(128, activation=tf.nn.relu,\n input_shape=(x.shape[1],)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(y.shape[1])\n ])\n model.compile(optimizer='adam', loss=\"mse\", metrics=['mse'])\n model.fit(x_train, y_train, epochs=10, verbose=0)\n\n for i in range(args.num_rollouts):\n # print('iter', i)\n obs = env.reset()\n done = False\n totalr = 0.\n steps = 0\n while not done:\n expert_action = policy_fn(obs[None, :])\n action = model.predict(obs.reshape(1, -1))\n add_observations.append(obs)\n add_actions.append(expert_action)\n obs, r, done, _ = env.step(action)\n totalr += r\n steps += 1\n if args.render:\n env.render()\n # if steps % 100 == 0: print(\"%i/%i\"%(steps, max_steps))\n if steps >= max_steps:\n break\n returns.append(totalr)\n\n # print('returns', returns)\n # print('mean return', np.mean(returns))\n # print('std of return', np.std(returns))\n mean_rewards.append(np.mean(returns))\n std_rewards.append(np.std(returns))\n\n add_observations = np.array(add_observations)\n add_actions = np.array(add_actions)\n\n # every time dagger, get more expert data\n add_observations = add_observations.reshape(add_observations.shape[0], -1)\n add_actions = add_actions.reshape(add_actions.shape[0], -1)\n x = np.concatenate([x, add_observations])\n y = np.concatenate([y, add_actions])\n\n print('mean returns', mean_rewards)\n print('std returns', std_rewards)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hw1/run_dagger.py","file_name":"run_dagger.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"392280427","text":"from qgis.core import *\r\nfrom qgis.core import QgsProject\r\nfrom qgis.gui import *\r\n\r\nfrom PyQt5.QtCore import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtGui import QFont\r\nfrom PyQt5.QtWidgets import QDockWidget\r\n\r\n\r\nfrom module.MapLegend.UI_MapLegend import Ui_UI_MapLegend\r\n\r\nimport string\r\n\r\n\r\n# *******************************************************************************************************\r\n# ***************************** MAP LEGEND CLASS *****************************************************\r\n# *******************************************************************************************************\r\nclass Iterator_MapLegend(QDockWidget,Ui_UI_MapLegend):\r\n def __init__(self,parent):\r\n #print \"init Iterator_MapLegend\"\r\n super(Iterator_MapLegend, self).__init__(parent)\r\n self.setupUi(self)\r\n\r\n font = QFont()\r\n font.setBold(True)\r\n font.setWeight(75)\r\n self.setFont(font)\r\n self.setObjectName(\"Legend\")\r\n self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)\r\n self.setContentsMargins(5,5,5,5)\r\n parent.addDockWidget(Qt.LeftDockWidgetArea, self)\r\n\r\n\r\n\r\n\r\n\r\n\r\n def f_make_overview(self,_canvas,_overview_canvas):\r\n\r\n self.m_overview_canvas = _overview_canvas\r\n self.m_overview_canvas.resize(self.m_overview_frame.size())\r\n self.m_overview_canvas.setBackgroundColor(QColor(255, 255, 255))\r\n\r\n self.root = QgsProject.instance().layerTreeRoot()\r\n self.bridge = QgsLayerTreeMapCanvasBridge(self.root, _canvas)\r\n self.model = QgsLayerTreeModel(self.root)\r\n self.model.setFlag(QgsLayerTreeModel.AllowNodeReorder)\r\n self.model.setFlag(QgsLayerTreeModel.AllowNodeRename)\r\n self.model.setFlag(QgsLayerTreeModel.AllowNodeChangeVisibility)\r\n self.model.setFlag(QgsLayerTreeModel.ShowLegend)\r\n self.m_view_tree = QgsLayerTreeView(self.view_tree)\r\n self.m_view_tree.setModel(self.model)\r\n #self.m_view_tree.setWordWrap(True)\r\n self.m_view_tree.resize(self.view_tree.size())\r\n\r\n\r\n\r\n\r\n\r\n # --------------------------------------------------------------- f_map_view_legend\r\n def f_map_view_legend(self, show_legend):\r\n print (\"f_map_view_legend\")\r\n # show_legend = True - show legend\r\n # show_legend = False - hide legend\r\n if show_legend == True:\r\n self.show()\r\n else:\r\n self.hide()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"module/MapLegend/mapLegend.py","file_name":"mapLegend.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"31409852","text":"\n\n\nclass EdgeList:\n \"\"\"\n List of edges for graph class\n \"\"\"\n def __init__(self, vertex=None):\n self.vertex = vertex\n self.edge_list = []\n def __str__(self):\n return str(self.vertex)+': '+str(self.edge_list)\n def add_edge(self, vtx):\n if vtx not in self.edge_list:\n self.edge_list.append(vtx)\n \nclass Graph:\n \"\"\"\n generic graph class\n \n supports directed and undirected\n \"\"\"\n def __init__(self, is_directed=False, is_reversed=False):\n self.edge_lists = []\n self.directed = is_directed\n self.reverse = is_reversed\n def _get_edge_list(self,vert):\n tmp_edge_list = list(filter((lambda v: v.vertex == vert),\n self.edge_lists))\n if tmp_edge_list != []:\n #print(tmp_edge_list[0])\n #print(\"edge list ^\\n\")\n return tmp_edge_list[0]\n def make_directed(self):\n self.directed = True\n def make_undirected(self):\n self.directed = False\n def get_verts(self):\n vt_ls = []\n for el in self.edge_lists:\n vt_ls.append(el.vertex)\n return vt_ls\n def has_vertex(self,vtx):\n tmp_verts = list(filter((lambda el: el.vertex == vtx),\n self.edge_lists))\n return len(tmp_verts)!=0\n def has_edge(self,v1,v2):\n #return (self.get_edges(v1).edge_list.count(v2)!=0)\n v1_edges = self.get_edges(v1)\n return v2 in v1_edges\n # def get_neighbors(self, vtx):\n # if self.has_vertex(vtx):\n # return self._get_edge_list(vtx).edge_list\n def get_jump(self,v1,v2):\n if not self.has_edge(v1,v2):\n return None\n elif v1[0]==v2[0]: # same row\n if v1[1]>v2[1]:\n if self.has_vertex(v1[0]+prev_char(v2[1])):\n return v1[0]+prev_char(v2[1])\n else: return None\n else:\n if self.has_vertex(v1[0]+next_char(v2[1])):\n return v1[0]+next_char(v2[1])\n else: return None\n elif v1[0]v2[0] (switch prev case (basically))\n if v1[0]>'i':\n if v2[1]==v1[1]:\n return prev_char(v2[0])+v2[1]\n else:\n return prev_char(v2[0])+next_char(v2[1])\n elif v1[0]=='i':\n if v2[1]=='1' or v2[1]=='6':\n return None\n elif v2[1]==v1[1]:\n return 'g'+prev_char(v2[1])\n else:\n return 'g'+v2[1]\n elif v1[0]=='h':\n if v1[1]==v2[1]:\n return 'f'+next_char(v2[1])\n else:\n return 'f'+v2[1]\n elif v1[0]=='g':\n if v2[0]=='1' or v2[0]=='6':\n return None\n elif v1[1]==v2[1]:\n return 'f'+prev_char(v2[1])\n else:\n return 'f'+v2[1]\n else: # v1 is in b-f\n if v1[1]==v2[1]:\n if self.has_vertex(v2[0]+next_char(v2[1])):\n return prev_char(v2[0])+v2[1]\n else:\n return None\n else:\n if self.has_vertex(v2[0]+prev_char(v2[1])):\n return prev_char(v2[0])+prev_char(v2[1])\n else:\n return None\n def get_edges(self,vert): # vert is now loc? yeah?\n #return self._get_edge_list(vert).edge_list\n elarr = list(filter(lambda x:\n x.vertex == vert,\n self.edge_lists))\n if len(elarr)==0:\n return []\n el = elarr[0]\n #print(el.edge_list)\n return el.edge_list\n def add_vertex(self, vtx_name):\n self.edge_lists.append(EdgeList(vtx_name))\n def add_edge(self, vtx1, vtx2):\n if not self.directed:\n for el in self.edge_lists:\n if el.vertex == vtx1:\n el.add_edge(vtx2)\n if el.vertex == vtx2:\n el.add_edge(vtx1)\n elif not self.reverse:\n for el in self.edge_lists:\n if el.vertex == vtx1:\n el.add_edge(vtx2)\n else:\n for el in self.edge_lists:\n if el.vertex == vtx2:\n el.add_edge(vtx1)\n\ngame_board = Graph()\np1_board = Graph(True)\np2_board = Graph(True,True)\n\nverts = [\"a1\",\"b1\",\"b2\",\"c1\",\"c2\",\"c3\",\"d1\",\"d2\",\"d3\",\"d4\",\n \"e1\",\"e2\",\"e3\",\"e4\",\"e5\",\"f1\",\"f2\",\"f3\",\"f4\",\"f5\",\n \"f6\",\"g1\",\"g2\",\"g3\",\"g4\",\"g5\",\"h1\",\"h2\",\"h3\",\"h4\",\n \"h5\",\"h6\",\"i1\",\"i2\",\"i3\",\"i4\",\"i5\",\"j1\",\"j2\",\"j3\",\n \"j4\",\"k1\",\"k2\",\"k3\",\"l1\",\"l2\",\"m1\"]\n\nfor vt in verts:\n game_board.add_vertex(vt)\n p1_board.add_vertex(vt)\n p2_board.add_vertex(vt)\n\n\nedges = None\n\ndef next_char(c):\n return chr(1+ord(c))\ndef prev_char(c):\n return chr(ord(c)-1)\n\ndef set_edges(board):\n \"\"\"\n sets up the edges for a board\n \n uses board's edges, but makes it (un)directed dependent on player/general\n \"\"\"\n # this is broken (I think)\n for vt in verts:\n board.add_vertex(vt)\n for vt in verts:\n #board.add_vertex(vt)\n if vt[0]<'f':\n board.add_edge(vt,next_char(vt[0])+next_char(vt[1]))\n board.add_edge(vt,next_char(vt[0])+vt[1])\n if vt[1]!='1':\n board.add_edge(vt,vt[0]+prev_char(vt[1]))\n if vt[1]!=chr(ord(vt[0])-ord('a')+ord('1')):\n board.add_edge(vt,vt[0]+next_char(vt[1]))\n elif vt[0]=='f':\n if vt[1]!='1':\n board.add_edge(vt,next_char(vt[0])+prev_char(vt[1]))\n board.add_edge(vt,vt[0]+prev_char(vt[1]))\n if vt[1]!='5':\n board.add_edge(vt,next_char(vt[0])+vt[1])\n board.add_edge(vt,vt[0]+next_char(vt[1]))\n elif vt[0]=='g':\n board.add_edge(vt,next_char(vt[0])+next_char(vt[1]))\n board.add_edge(vt,next_char(vt[0])+vt[1])\n if vt[1]!='1':\n board.add_edge(vt,vt[0]+prev_char(vt[1])) \n if vt[1]!=chr(ord(vt[0])-ord('a')+ord('1')):\n board.add_edge(vt,vt[0]+next_char(vt[1]))\n elif vt[0]<'m':\n if vt[1]!='1':\n board.add_edge(vt,next_char(vt[0])+prev_char(vt[1]))\n board.add_edge(vt,vt[0]+prev_char(vt[1]))\n if vt[1]!=chr(ord('m')-ord(vt[0])+ord('1')):\n board.add_edge(vt,next_char(vt[0])+vt[1])\n board.add_edge(vt,vt[0]+next_char(vt[1]))\n\nset_edges(game_board)\nset_edges(p1_board)\nset_edges(p2_board)\n\n\n\nclass Board(Graph):\n def __init__(self, player=None):\n if player == \"p1\":\n super(Board, self).__init__(True)\n elif player == \"p2\":\n super(Board, self).__init__(True, True)\n else:\n super(Board, self).__init__()\n set_edges(self)\n\n\ndef get_row_len(rowletter):\n \"\"\"you know... a->1,b->2,f->6,g->5,j->4...\"\"\"\n if rowletter == 'g':\n return 5\n elif rowletter<'g':\n return ord(rowletter)-ord('a')+1\n else: # rl > g\n return ord('m')-ord(rowletter)+1\n \ndef get_mirror(location):\n \"\"\"flips the given loc\"\"\"\n row = chr(ord('m')-ord(location[0])+ord('a'))\n rank = chr(get_row_len(row) - (ord(location[1])-ord('0')) + 1 + ord('0'))\n # this works... don't worry about it...\n # would be way more readable with atoi or something though\n return row+rank\n","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":8948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"270346703","text":"import sys\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\n# 영상 불러오기\r\nsrc1 = cv2.imread('/Users/hyunsul/Desktop/ai-room/OpenCV2_python/ch09/graf1.png', cv2.IMREAD_GRAYSCALE)\r\nsrc2 = cv2.imread('/Users/hyunsul/Desktop/ai-room/OpenCV2_python/ch09/graf3.png', cv2.IMREAD_GRAYSCALE)\r\n\r\nif src1 is None or src2 is None:\r\n print('Image load failed!')\r\n sys.exit()\r\n\r\n# 특징점 알고리즘 객체 생성 (KAZE, AKAZE, ORB 등)\r\nfeature = cv2.KAZE_create()\r\nfeature1 = cv2.AKAZE_create()#hamming distance를 사용가능\r\nfeature2 = cv2.ORB_create()\r\n\r\nfor f in (feature,feature1,feature2):\r\n # 특징점 검출 및 기술자 계산\r\n kp1, desc1 = f.detectAndCompute(src1, None)\r\n kp2, desc2 = f.detectAndCompute(src2, None)\r\n\r\n # 특징점 매칭\r\n matcher = cv2.BFMatcher_create()\r\n\r\n matches = matcher.match(desc1, desc2)\r\n\r\n # 특징점 매칭 결과 영상 생성\r\n dst = cv2.drawMatches(src1, kp1, src2, kp2, matches, None)\r\n\r\n print(f'{f} of kp1:', len(kp1))\r\n print(f'{f} of kp2:', len(kp2))\r\n print(f'{f} of matches:', len(matches),'\\n')\r\n\r\n cv2.imshow('dst', dst)\r\n cv2.moveWindow('dst', 100, 300)\r\n cv2.waitKey()\r\n\r\ncv2.destroyAllWindows()\r\n","sub_path":"OpenCV2_python/ch09/custom_matching.py","file_name":"custom_matching.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"101830055","text":"# -*- coding: utf-8 -*-\n'''\nCreated on Oct 9, 2014\n@author: lin\n'''\nimport db.db_conf\nimport db.mfexchange_sql\nimport spi.ugc\nimport spi.env_conf\nimport spi.sendredpage\n\ndef init_mfexchange_user(db_name):\n try:\n db_conn = db.db_conf.get_db(db_name)\n db.mfexchange_sql.init_mfexchange_user(db_conn)\n return '初始化成功'\n except Exception as e:\n return '初始化失败:' + str(e)\n \ndef update_useraddredPage(db_name, userid):\n try:\n http_url = spi.env_conf.get_httpenv(db_name)\n print ('exchange Http'+http_url)\n db_names = db.db_conf.get_db(db_name)\n db_userId = db.mfexchange_sql.select_useridByphone_number(db_names, userid)\n print ('db_name values is:'+db_name)\n print ('http_url values is:'+http_url)\n spi.sendredpage.h_sendredpage(http_url,db_userId)\n return '增加完了!'\n except Exception as e:\n return '增加失败或用户名不存在:' + str(e)\n\ndef update_order_info(db_name, loanId, currentMomey, order_status):\n try:\n db_conn = db.db_conf.get_db(db_name)\n db.mfexchange_sql.update_order_info(db_conn, loanId, currentMomey, order_status)\n return '修改成功!'\n except Exception as e:\n return '修改失败:' + str(e)\n \ndef update_user_account(db_name, phone_number, account):\n try:\n db_conn = db.db_conf.get_db(db_name)\n db.mfexchange_sql.update_user_account(db_conn, phone_number, account)\n return '修改成功!'\n except Exception as e:\n return '修改失败:' + str(e)\n\ndef find_phone_numberCode(db_name, phone_number):\n try:\n db_conn = db.db_conf.get_db(db_name)\n message = db.mfexchange_sql.find_phone_numberCode(db_conn, phone_number)\n return message\n except Exception as e:\n return '没有数据:' + str(e)\n\n# if __name__ == '__main__':\n# update_order_info('11','1','2','3')\n# db_name = db_conf.get_db('beta_1')\n# find_phone_numberCode(db_name,\"15811297594\")\n \n","sub_path":"controlls/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"497156832","text":"import pygame\nfrom pygame.locals import *\nimport random\nimport os\nimport os.path\n\n\ndef init():\n pygame.init()\n\n global SCREENHEIGHT\n global SCREENWIDTH\n\n SCREENWIDTH = pygame.display.Info().current_w\n SCREENHEIGHT = pygame.display.Info().current_h\n\n displaysurf = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT), FULLSCREEN)\n\n brick_width = round(SCREENWIDTH * 0.01)\n bricks = []\n\n fps = 60\n fpsclock = pygame.time.Clock()\n\n client_loc = os.path.join(\"client_data\", \"PotatoPig\")\n\n state = 0\n\n buttons = [Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * 3, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1),\n Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * 2, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1),\n Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * 1, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1),\n Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * 4, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1),\n Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * 5, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1),\n Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * 7, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1)]\n\n block_buttons = [Clicky((SCREENWIDTH / 20) * 18, (SCREENHEIGHT / 8) * 1, SCREENWIDTH * 0.15, SCREENHEIGHT * 0.1),\n Clicky((SCREENWIDTH / 20) * 18, (SCREENHEIGHT / 8) * 2, SCREENWIDTH * 0.15, SCREENHEIGHT * 0.1),\n Clicky((SCREENWIDTH / 20) * 18, (SCREENHEIGHT / 8) * 3, SCREENWIDTH * 0.15, SCREENHEIGHT * 0.1),\n Clicky((SCREENWIDTH / 20) * 18, (SCREENHEIGHT / 8) * 4, SCREENWIDTH * 0.15, SCREENHEIGHT * 0.1)]\n\n save_buttons = []\n load_buttons = []\n\n file_name = []\n placement = 0\n\n user_input = \"\"\n\n for root, dirs, files in os.walk(client_loc):\n for file in files:\n placement += 1\n if file.endswith('.txt'):\n save_buttons.append(Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * placement, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1))\n load_buttons.append(Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * placement, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1))\n file_name.append(file)\n\n soundfx_off = False\n hud_on = False\n highlighted_buttons = [0] * len(buttons)\n save_highlighted = [0] * len(save_buttons)\n load_highlighted = [0] * len(load_buttons)\n pause_button = pygame.Rect(0, 0, brick_width * 3, brick_width * 3)\n\n myfont = pygame.font.SysFont(\"comicsansms\", int(SCREENWIDTH * 0.039))\n myfont2 = pygame.font.SysFont(\"comicsansms\", int(SCREENWIDTH * 0.01))\n myfont3 = pygame.font.SysFont(\"comicsansms\", int(SCREENWIDTH * 0.02))\n\n scroll = 0\n\n selection = [0] * len(block_buttons)\n\n gravity = SCREENHEIGHT * 0.0001\n\n new_bricks = True\n\n while True:\n while state == 0:\n displaysurf.fill((255, 255, 255))\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.display.quit()\n return\n if event.type == KEYDOWN:\n if event.key == K_ESCAPE:\n state = 1\n for i in range(len(buttons)):\n buttons[i].centerx = random.randrange(SCREENWIDTH)\n buttons[i].centery = random.randrange(SCREENHEIGHT)\n\n if pygame.mouse.get_pressed()[0] and MOUSEBUTTONDOWN and pause_button.collidepoint(\n pygame.mouse.get_pos()):\n state = 1\n for button in buttons:\n button.centerx = random.randrange(SCREENWIDTH)\n button.centery = random.randrange(SCREENHEIGHT)\n for i in range(len(block_buttons)):\n if event.type == MOUSEBUTTONDOWN:\n if block_buttons[i].collidepoint(pygame.mouse.get_pos()) and pygame.mouse.get_pressed()[0]:\n selection[i] = (True, False)[selection[i]]\n\n if pygame.key.get_pressed()[pygame.K_LEFT] != 0:\n scroll += SCREENWIDTH * 0.01\n if pygame.key.get_pressed()[pygame.K_RIGHT] != 0:\n scroll -= SCREENWIDTH * 0.01\n\n for brick in bricks:\n brick.draw(displaysurf, scroll)\n\n right_ui_rect = ((SCREENWIDTH * 0.8, 0), (SCREENWIDTH, SCREENHEIGHT))\n pygame.draw.rect(displaysurf, (25, 25, 25), right_ui_rect)\n\n block_text = [myfont3.render(\"gravity\", 1, (255, 255, 255)).convert_alpha(),\n myfont3.render(\"grabable\", 1, (255, 255, 255)).convert_alpha(),\n myfont3.render(\"colour\", 1, (255, 255, 255)).convert_alpha(),\n myfont3.render(\"bounce\", 1, (255, 255, 255)).convert_alpha()]\n for i in range(len(block_buttons)):\n if selection[i]:\n pygame.draw.rect(displaysurf, (50, 50, 50), block_buttons[i])\n displaysurf.blit(block_text[i], (int(block_buttons[i].x), int(block_buttons[i].y)))\n if not selection[i]:\n pygame.draw.rect(displaysurf, (100, 100, 100), block_buttons[i])\n displaysurf.blit(block_text[i], (int(block_buttons[i].x), int(block_buttons[i].y)))\n\n invisible = Rect((0, 0), (brick_width, brick_width))\n invisible.center = pygame.mouse.get_pos()\n\n for brick in bricks:\n if brick.rect.colliderect(invisible):\n new_bricks = False\n else:\n new_bricks = True\n\n if pygame.mouse.get_pressed()[0] and new_bricks:\n bricks.append(\n Brick(\n pygame.Rect(\n (pygame.mouse.get_pos()[0] - brick_width / 2) - scroll,\n (pygame.mouse.get_pos()[1] - brick_width / 2),\n brick_width,\n brick_width\n ),\n selection[0],\n selection[1],\n selection[2],\n selection[3]\n )\n )\n\n draw_ui(displaysurf, brick_width)\n\n #gravity on bricks\n for brick1 in bricks:\n if brick1.gravity and brick1.rect.bottom < SCREENHEIGHT and brick1.gravity_tog:\n brick1.vy += gravity\n if brick1.rect.bottom >= SCREENHEIGHT:\n brick1.vy = 0\n brick1.rect.bottom = SCREENHEIGHT\n\n for brick2 in bricks:\n if brick1.rect.colliderect(brick2.rect) and not brick1.rect.x == brick2.rect.x and not brick1.rect.y == brick2.rect.y:\n brick1.vy = 0\n brick1.gravity_tog = False\n\n brick1.move()\n\n for button in block_buttons:\n button.buttons_move()\n\n fpsclock.tick(fps)\n if hud_on:\n fps_text = myfont2.render(\"FPS:\" + str(fpsclock.get_fps()), 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(fps_text, (SCREENWIDTH * 0.95, 0))\n\n pygame.display.update()\n\n while state == 1:\n displaysurf.fill((120, 120, 120))\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.display.quit()\n return\n # paused screen button collisions\n if event.type == MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:\n if buttons[0].collidepoint(pygame.mouse.get_pos()):\n pygame.display.quit()\n return\n if buttons[1].collidepoint(pygame.mouse.get_pos()):\n soundfx_off = (True, False)[soundfx_off]\n\n if buttons[2].collidepoint(pygame.mouse.get_pos()):\n hud_on = (True, False)[hud_on]\n\n if buttons[3].collidepoint(pygame.mouse.get_pos()):\n state = 2\n\n if buttons[4].collidepoint(pygame.mouse.get_pos()):\n state = 3\n\n if pause_button.collidepoint(pygame.mouse.get_pos()):\n state = 1\n\n #unpause\n if event.type == KEYDOWN and event.key == K_ESCAPE:\n state = 0\n if pygame.mouse.get_pressed()[0] and MOUSEBUTTONDOWN and pause_button.collidepoint(\n pygame.mouse.get_pos()):\n state = 0\n\n for i in range(len(buttons)):\n if buttons[i].collidepoint(pygame.mouse.get_pos()):\n highlighted_buttons[i] = False\n else:\n highlighted_buttons[i] = True\n\n if highlighted_buttons[0]:\n pygame.draw.rect(displaysurf, (50, 50, 50), buttons[0])\n quit_text = myfont.render(\"Quit??\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(quit_text, (int(buttons[0].x + SCREENWIDTH * 0.19), int(buttons[0].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), buttons[0])\n quit_text = myfont.render(\"Quit??\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(quit_text, (int(buttons[0].x + SCREENWIDTH * 0.19), int(buttons[0].y)))\n\n # soundFX_button draw\n if highlighted_buttons[1]:\n pygame.draw.rect(displaysurf, (50, 50, 50), buttons[1])\n soundfx_text = myfont.render(\"SoundFX:\" + str((\"On\", \"Off\")[soundfx_off]), 1,\n (255, 255, 255)).convert_alpha()\n displaysurf.blit(soundfx_text, (int(buttons[1].x + SCREENWIDTH * 0.14), int(buttons[1].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), buttons[1])\n soundfx_text = myfont.render(\"SoundFX:\" + str((\"On\", \"Off\")[soundfx_off]), 1,\n (255, 255, 255)).convert_alpha()\n displaysurf.blit(soundfx_text, (int(buttons[1].x + SCREENWIDTH * 0.14), int(buttons[1].y)))\n\n #hud_button draw\n if highlighted_buttons[2]:\n pygame.draw.rect(displaysurf, (50, 50, 50), buttons[2])\n hud_text = myfont.render(\"HUD:\" + str((\"Off\", \"On\")[hud_on]), 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(hud_text, (int(buttons[2].x + SCREENWIDTH * 0.16), int(buttons[2].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), buttons[2])\n hud_text = myfont.render(\"HUD:\" + str((\"Off\", \"On\")[hud_on]), 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(hud_text, (int(buttons[2].x + SCREENWIDTH * 0.16), int(buttons[2].y)))\n\n #save_button draw\n if highlighted_buttons[3]:\n pygame.draw.rect(displaysurf, (50, 50, 50), buttons[3])\n hud_text = myfont.render(\"Save\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(hud_text, (int(buttons[3].x + SCREENWIDTH * 0.16), int(buttons[3].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), buttons[3])\n hud_text = myfont.render(\"Save\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(hud_text, (int(buttons[3].x + SCREENWIDTH * 0.16), int(buttons[3].y)))\n\n #load_button draw\n if highlighted_buttons[4]:\n pygame.draw.rect(displaysurf, (50, 50, 50), buttons[4])\n load_text = myfont.render(\"Load\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(load_text, (int(buttons[4].x + SCREENWIDTH * 0.16), int(buttons[4].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), buttons[4])\n load_text = myfont.render(\"Load\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(load_text, (int(buttons[4].x + SCREENWIDTH * 0.16), int(buttons[4].y)))\n\n #button updates\n for button in buttons:\n button.buttons_move()\n\n draw_ui(displaysurf, brick_width)\n\n fpsclock.tick(fps)\n pygame.display.update()\n\n while state == 2:\n displaysurf.fill((120, 120, 120))\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.display.quit()\n return\n\n for button in save_buttons:\n if event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP):\n if event.button == 4:\n button.target_y += SCREENHEIGHT * 0.02\n if event.button == 5:\n button.target_y -= SCREENHEIGHT * 0.02\n\n # unpause\n if event.type == KEYDOWN and event.key == K_ESCAPE:\n state = 1\n if pygame.mouse.get_pressed()[0] and MOUSEBUTTONDOWN and pause_button.collidepoint(pygame.mouse.get_pos()):\n state = 0\n #paused screen button collisions\n if event.type == MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:\n for i in range(len(save_buttons)):\n if save_buttons[i].collidepoint(pygame.mouse.get_pos()):\n if not os.path.exists(client_loc):\n os.makedirs(client_loc)\n open(\"client_data/PotatoPig/\"+str(file_name[i]), 'a').close()\n with open(\"client_data/PotatoPig/\"+str(file_name[i]), \"r+\") as blocks:\n blocks.truncate()\n for brick in bricks:\n x = brick.rect.x\n y = brick.rect.y\n blocks.write(str(x) + \" \" + str(y) + \"\\n\")\n if buttons[5].collidepoint(pygame.mouse.get_pos()):\n state = 4\n while state == 4:\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n if event.unicode.isalpha():\n user_input += event.unicode\n elif event.key == K_BACKSPACE:\n user_input = user_input[:-1]\n elif event.key == K_RETURN:\n state = 2\n elif event.key == K_ESCAPE:\n state = 2\n user_input = \"\"\n displaysurf.fill((255, 255, 255))\n typing = myfont.render(user_input, True, (50, 50, 50))\n typing_rect = typing.get_rect()\n typing_rect.center = displaysurf.get_rect().center\n displaysurf.blit(typing, typing_rect)\n\n pygame.display.flip()\n\n if len(user_input) > 1:\n if not os.path.exists(client_loc):\n os.makedirs(client_loc)\n open(os.path.join(client_loc, str(user_input) + \".txt\"), 'a').close()\n with open(os.path.join(client_loc, str(user_input) + \".txt\"), \"r+\") as block_pos:\n block_pos.truncate()\n for brick in bricks:\n x = brick.rect.x\n y = brick.rect.y\n s1 = bool(brick.gravity)\n s2 = brick.grabable\n s3 = brick.colour\n s4 = brick.bounce\n block_pos.write(str(x) + \" \" + str(y) + \" \" + str(s1) + \" \" + str(s2) + \" \" + str(s3) + \" \" + str(s4) + \"\\n\")\n save_buttons.append(Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * placement, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1))\n load_buttons.append(Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * placement, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1))\n file_name.append(user_input)\n save_buttons = []\n load_buttons = []\n file_name = []\n placement = 0\n for root, dirs, files in os.walk(client_loc):\n for file in files:\n placement += 1\n if file.endswith('.txt'):\n save_buttons.append(Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * placement, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1))\n load_buttons.append(Clicky(SCREENWIDTH / 2, (SCREENHEIGHT / 8) * placement, SCREENWIDTH * 0.5, SCREENHEIGHT * 0.1))\n file_name.append(file)\n save_highlighted = [0] * len(save_buttons)\n load_highlighted = [0] * len(load_buttons)\n\n for i in range(len(buttons)):\n if buttons[i].collidepoint(pygame.mouse.get_pos()):\n highlighted_buttons[i] = False\n else:\n highlighted_buttons[i] = True\n\n for i in range(len(save_buttons)):\n if save_buttons[i].collidepoint(pygame.mouse.get_pos()):\n save_highlighted[i] = False\n else:\n save_highlighted[i] = True\n\n # saves button draw\n for i in range(len(save_buttons)):\n if save_highlighted[i]:\n pygame.draw.rect(displaysurf, (50, 50, 50), save_buttons[i])\n load_text = myfont.render(str(file_name[i]), 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(load_text, (int(save_buttons[i].x + SCREENWIDTH * 0.16), int(save_buttons[i].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), save_buttons[i])\n load_text = myfont.render(str(file_name[i]), 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(load_text, (int(save_buttons[i].x + SCREENWIDTH * 0.16), int(save_buttons[i].y)))\n\n #new_button draw\n if highlighted_buttons[5]:\n pygame.draw.rect(displaysurf, (50, 50, 50), buttons[5])\n load_text = myfont.render(\"New\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(load_text, (int(buttons[5].x + SCREENWIDTH * 0.16), int(buttons[5].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), buttons[5])\n load_text = myfont.render(\"New\", 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(load_text, (int(buttons[5].x + SCREENWIDTH * 0.16), int(buttons[5].y)))\n\n #button updates\n for button in save_buttons:\n button.buttons_move()\n\n draw_ui(displaysurf, brick_width)\n\n fpsclock.tick(fps)\n pygame.display.update()\n\n while state == 3:\n displaysurf.fill((120, 120, 120))\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.display.quit()\n return\n\n for button in load_buttons:\n if event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP):\n if event.button == 4:\n button.target_y += SCREENHEIGHT * 0.02\n if event.button == 5:\n button.target_y -= SCREENHEIGHT * 0.02\n # unpause\n if event.type == KEYDOWN and event.key == K_ESCAPE:\n state = 1\n #paused screen button collisions\n if event.type == MOUSEBUTTONDOWN and pygame.mouse.get_pressed()[0]:\n for i in range(len(load_buttons)):\n if load_buttons[i].collidepoint(pygame.mouse.get_pos()):\n if not os.path.exists(client_loc):\n os.makedirs(client_loc)\n if not os.path.exists(os.path.join(client_loc, str(file_name[i]))):\n open(os.path.join(client_loc, str(file_name[i])), 'a').close()\n\n bricks = []\n\n with open(os.path.join(client_loc, str(file_name[i])), \"r+\") as blocks:\n newbricks = list(blocks)\n\n for newbrick in newbricks:\n newbrick = newbrick.split()\n x = int(newbrick[0])\n y = int(newbrick[1])\n s1 = bool(newbrick[2])\n s2 = bool(newbrick[3])\n s3 = bool(newbrick[4])\n s4 = bool(newbrick[5])\n bricks.append(\n Brick(\n pygame.Rect(\n x,\n y,\n brick_width,\n brick_width\n ),\n s1,\n s2,\n s3,\n s4\n )\n )\n if MOUSEBUTTONDOWN and pause_button.collidepoint(pygame.mouse.get_pos()):\n state = 0\n\n for i in range(len(buttons)):\n if buttons[i].collidepoint(pygame.mouse.get_pos()):\n highlighted_buttons[i] = False\n else:\n highlighted_buttons[i] = True\n\n for i in range(len(load_buttons)):\n if load_buttons[i].collidepoint(pygame.mouse.get_pos()):\n load_highlighted[i] = False\n else:\n load_highlighted[i] = True\n\n # load_button draw\n for i in range(len(load_buttons)):\n if load_highlighted[i]:\n pygame.draw.rect(displaysurf, (50, 50, 50), load_buttons[i])\n hud_text = myfont.render(str(file_name[i]), 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(hud_text, (int(load_buttons[i].x + SCREENWIDTH * 0.16), int(load_buttons[i].y)))\n else:\n pygame.draw.rect(displaysurf, (100, 100, 100), load_buttons[i])\n hud_text = myfont.render(str(file_name[i]), 1, (255, 255, 255)).convert_alpha()\n displaysurf.blit(hud_text, (int(load_buttons[i].x + SCREENWIDTH * 0.16), int(load_buttons[i].y)))\n\n #button updates\n for button in load_buttons:\n button.buttons_move()\n\n draw_ui(displaysurf, brick_width)\n\n fpsclock.tick(fps)\n pygame.display.update()\n\n\ndef draw_ui(displaysurf, brick_width):\n # draw the UI bar\n pygame.draw.rect(displaysurf,\n (200, 200, 200),\n (0, 0, SCREENWIDTH, brick_width * 3))\n\n #draw the pause button\n pygame.draw.rect(displaysurf,\n (120, 120, 120),\n (0, 0, brick_width * 3, brick_width * 3))\n pygame.draw.line(displaysurf,\n (0, 0, 0),\n (int(brick_width * 2), int(brick_width * 2.5)),\n (int(brick_width * 2), int(brick_width * 0.5)),\n int(brick_width * 0.5))\n pygame.draw.line(displaysurf,\n (0, 0, 0),\n (int(brick_width * 1), int(brick_width * 2.5)),\n (int(brick_width * 1), int(brick_width * 0.5)),\n int(brick_width * 0.5))\n\n\nclass Clicky(pygame.Rect):\n def __init__(self, targetx, targety, block_width, block_height):\n self.target_x = targetx\n self.target_y = targety\n self.x = random.randrange(SCREENWIDTH)\n self.y = random.randrange(SCREENHEIGHT)\n self.width = block_width\n self.height = block_height\n\n def buttons_move(self):\n if self.centery < self.target_y:\n self.centery -= (self.centery - self.target_y) * 0.2\n\n if self.centery > self.target_y:\n self.centery -= (self.centery - self.target_y) * 0.2\n\n if self.centerx < self.target_x:\n self.centerx -= (self.centerx - self.target_x) * 0.2\n\n if self.centerx > self.target_x:\n self.centerx -= (self.centerx - self.target_x) * 0.2\n\n\nclass Brick(object):\n def __init__(self, rect, gravity, grabable, colour, bounce):\n self.rect = rect\n self.gravity = gravity\n self.grabable = grabable\n self.colour = colour\n self.bounce = bounce\n self.vx = 0\n self.vy = 0\n self.gravity_tog = True\n\n def draw(self, surf, scroll):\n x = int(self.rect.x + scroll)\n y = self.rect.y\n w = self.rect.width\n h = self.rect.height\n if self.rect.colliderect(((0 - scroll, 0), (SCREENWIDTH - scroll, SCREENHEIGHT))):\n pygame.draw.rect(surf, (0, 0, 0), ((x, y), (w, h)))\n\n def move(self):\n self.rect.x += self.vx\n self.rect.y += self.vy","sub_path":"src/bobnomercy/PotatoPig.py","file_name":"PotatoPig.py","file_ext":"py","file_size_in_byte":26306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"308365987","text":"# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.\n# See LICENSE in the project root for license information.\n\nimport ujson as json\nimport time\nimport hmac\nimport hashlib\nimport base64\nimport urllib\nfrom flask.ext.login import current_user\nfrom urllib3.connectionpool import HTTPConnectionPool\n\n\nclass ApiServerError(Exception):\n def __init__(self, resp):\n self.resp = resp\n\n\nclass IrisClient(HTTPConnectionPool):\n def __init__(self, host, port, user, api_key, version=0, **kwargs):\n super(IrisClient, self).__init__(host, port, **kwargs)\n self.version = version\n self.user = user\n self.HMAC = hmac.new(api_key, '', hashlib.sha512)\n\n def post(self, endpoint, qs=None, **data):\n path_parts = ['/v%s/' % self.version, endpoint]\n if qs:\n path_parts.extend(('?', qs))\n path = ''.join(path_parts)\n method = 'POST'\n body = json.dumps(data)\n window = int(time.time()) // 5\n headers = self.get_headers(window, method, path, body)\n path_parts[1] = urllib.quote(path_parts[1])\n path = ''.join(path_parts)\n re = self.urlopen(method, path, headers=headers, body=body)\n if re.status / 100 != 2:\n raise(ApiServerError(re))\n return re\n\n def put(self, endpoint, qs=None, **data):\n path_parts = ['/v%s/' % self.version, endpoint]\n if qs:\n path_parts.extend(('?', qs))\n path = ''.join(path_parts)\n method = 'PUT'\n body = json.dumps(data)\n window = int(time.time()) // 5\n headers = self.get_headers(window, method, path, body)\n path_parts[1] = urllib.quote(path_parts[1])\n path = ''.join(path_parts)\n re = self.urlopen(method, path, headers=headers, body=body)\n if re.status / 100 != 2:\n raise(ApiServerError(re))\n return re\n\n def get(self, endpoint, qs=None):\n path_parts = ['/v%s/' % self.version, endpoint]\n if qs:\n path_parts.extend(('?', qs))\n path = ''.join(path_parts)\n method = 'GET'\n window = int(time.time()) // 5\n body = ''\n headers = self.get_headers(window, method, path, body)\n path_parts[1] = urllib.quote(path_parts[1])\n path = ''.join(path_parts)\n re = self.urlopen(method, path, headers=headers)\n if re.status != 200:\n raise(ApiServerError(re))\n return re\n\n def delete(self, endpoint, qs=None, **data):\n path_parts = ['/v%s/' % self.version, endpoint]\n if qs:\n path_parts.extend(('?', qs))\n path = ''.join(path_parts)\n method = 'DELETE'\n body = json.dumps(data)\n window = int(time.time()) // 5\n headers = self.get_headers(window, method, path, body)\n path_parts[1] = urllib.quote(path_parts[1])\n path = ''.join(path_parts)\n re = self.urlopen(method, path, headers=headers, body=body)\n if re.status != 200:\n raise(ApiServerError(re))\n return re\n\n def get_headers(self, window, method, path, body):\n HMAC = self.HMAC.copy()\n headers = {'Content-Type': 'application/json'}\n if current_user:\n headers['X-IRIS-USERNAME'] = current_user.id\n HMAC.update('%s %s %s %s %s' % (window, method, path, body, current_user.id))\n else:\n HMAC.update('%s %s %s %s' % (window, method, path, body))\n digest = base64.urlsafe_b64encode(HMAC.digest())\n headers['Authorization'] = 'hmac %s:' % self.user + digest\n return headers\n","sub_path":"src/iris_frontend/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"244401215","text":"import os\n\nDEBUG = True\nSTAGE = 'dev'\nALLOWED_HOSTS = ['127.0.0.1', '.execute-api.eu-west-1.amazonaws.com']\n\nPROJECT_DIR = \"{}/../\".format(os.path.dirname(__file__))\n\nADMINS = (\n ('Fabrice Triboix', 'ftriboix@incise.co'),\n)\n\nMANAGERS = ADMINS\n\nif 'RDS_DB_NAME' in os.environ:\n DATABASES = {\n 'default': {\n 'ENGINE':'django.db.backends.postgresql_psycopg2',\n 'NAME': os.environ['RDS_DB_NAME'],\n 'USER': os.environ['RDS_USERNAME'],\n 'PASSWORD': os.environ['RDS_PASSWORD'],\n 'HOST': os.environ['RDS_HOSTNAME'],\n 'PORT': os.environ['RDS_PORT'],\n }\n }\nelse:\n\tDATABASES = {\n \t\t'default': {\n \t'ENGINE': 'django.db.backends.sqlite3',\n \t'NAME': 'notejam.db',\n \t'USER': '',\n \t'PASSWORD': '',\n \t'HOST': '',\n \t'PORT': '',\n }\n}\n\n\n# Local time zone for this installation. Choices can be found here:\n# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n# although not all choices may be available on all operating systems.\n# In a Windows environment this must be set to your system time zone.\nTIME_ZONE = 'Europe/London'\n\n# Language code for this installation. All choices can be found here:\n# http://www.i18nguy.com/unicode/language-identifiers.html\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\n# If you set this to False, Django will make some optimizations so as not\n# to load the internationalization machinery.\nUSE_I18N = True\n\n# If you set this to False, Django will not format dates, numbers and\n# calendars according to the current locale.\nUSE_L10N = True\n\n# If you set this to False, Django will not use timezone-aware datetimes.\nUSE_TZ = True\n\n# Absolute filesystem path to the directory that will hold user-uploaded files.\n# Example: \"/home/media/media.lawrence.com/media/\"\nMEDIA_ROOT = os.path.join(PROJECT_DIR, 'media/')\n\n# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n# trailing slash.\n# Examples: \"http://media.lawrence.com/media/\", \"http://example.com/media/\"\nMEDIA_URL = ''\n\n# Absolute path to the directory static files should be collected to.\n# Don't put anything in this directory yourself; store your static files\n# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n# Example: \"/home/media/media.lawrence.com/static/\"\nSTATIC_ROOT = os.path.join(PROJECT_DIR, 'static/')\n\n# URL prefix for static files.\n# Example: \"http://media.lawrence.com/static/\"\nSTATIC_URL = '/' + STAGE + '/static/'\nWHITENOISE_STATIC_PREFIX = '/static/'\n\n# Additional locations of static files\nSTATICFILES_DIRS = (\n os.path.join(PROJECT_DIR, 'static_files/'),\n)\n\n# List of finder classes that know how to find static files in\n# various locations.\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder'\n)\n\n# Make this unique, and don't share it with anybody.\nSECRET_KEY = 'g+cy2q816xje*f#k=9z!e*t%h-7tt(tbo$q^1n)l0gd1=x8$65'\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\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.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'notejam.urls'\n\nAPPEND_SLASH = True\n\n# Python dotted path to the WSGI application used by Django's runserver.\nWSGI_APPLICATION = 'notejam.wsgi.application'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'APP_DIRS': True,\n 'DIRS': ['templates/', 'users/templates/', 'notes/templates/', 'pads/templates/'],\n 'OPTIONS': {\n 'debug': DEBUG,\n 'context_processors': [\n \"django.contrib.auth.context_processors.auth\",\n \"django.template.context_processors.debug\",\n \"django.template.context_processors.i18n\",\n \"django.template.context_processors.media\",\n \"django.template.context_processors.static\",\n \"django.template.context_processors.tz\",\n \"django.template.context_processors.request\",\n \"django.contrib.messages.context_processors.messages\"\n ]\n }\n }\n]\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n 'rest_framework',\n 'pads',\n 'notes',\n 'users'\n)\n\nAUTHENTICATION_BACKENDS = (\n 'users.auth_backends.EmailModelBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\nLOGIN_URL = '/' + STAGE + '/signin/'\nLOGOUT_URL = '/' + STAGE + '/signout/'\n\n# development email file-based backend\nEMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend'\nEMAIL_FILE_PATH = '/tmp'\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\n# custom test runner\nTEST_RUNNER = 'notejam.tests.AdvancedTestSuiteRunner'\n\n# exclude non app tests\nTEST_EXCLUDE = (\n 'django',\n)\n\nSQLITE_BUCKET = os.environ.get('SQLITE_BUCKET', \"serverless-djangotomas\")\n\n# Are we running in Lambda environment ?\n# See https://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html#lambda-environment-variables\nIS_OFFLINE = os.environ.get('LAMBDA_TASK_ROOT') is None\n\n\n# I hate different configuration for local and cloud, but this is what we have now.\n# if IS_OFFLINE:\n# DATABASES = {\n# 'default': {\n# 'ENGINE': 'django.db.backends.sqlite3',\n# 'NAME': os.path.join(PROJECT_DIR, 'notejam.db'),\n# }\n# }\n# else:\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'notejam', # dbname\n 'USER': 'root', # master username\n 'PASSWORD': 'sdfh834rn3443FSDFfff', # master password\n 'HOST': 'notejam-17ov4sx22c5q3.cluster-ciyk7lf4cmwo.eu-west-1.rds.amazonaws.com', # Endpoint\n 'PORT': '3306',\n }\n}\nREST_FRAMEWORK = {\n # Use Django's standard `django.contrib.auth` permissions,\n # or allow read-only access for unauthenticated users.\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'\n ]\n}\n","sub_path":"django/notejam/notejam/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":7277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"475991262","text":"# %%\nimport pandas as pd\nfrom pandas import pivot_table, DataFrame, crosstab\nimport numpy as np\nimport os\nimport csv\nimport string\n\n# import us_state_abbrev\n\n# would not import using import\nus_state_abbrev = {\n 'Alabama': 'AL',\n 'Alaska': 'AK',\n 'Arizona': 'AZ',\n 'Arkansas': 'AR',\n 'California': 'CA',\n 'Colorado': 'CO',\n 'Connecticut': 'CT',\n 'Delaware': 'DE',\n 'Florida': 'FL',\n 'Georgia': 'GA',\n 'Hawaii': 'HI',\n 'Idaho': 'ID',\n 'Illinois': 'IL',\n 'Indiana': 'IN',\n 'Iowa': 'IA',\n 'Kansas': 'KS',\n 'Kentucky': 'KY',\n 'Louisiana': 'LA',\n 'Maine': 'ME',\n 'Maryland': 'MD',\n 'Massachusetts': 'MA',\n 'Michigan': 'MI',\n 'Minnesota': 'MN',\n 'Mississippi': 'MS',\n 'Missouri': 'MO',\n 'Montana': 'MT',\n 'Nebraska': 'NE',\n 'Nevada': 'NV',\n 'New Hampshire': 'NH',\n 'New Jersey': 'NJ',\n 'New Mexico': 'NM',\n 'New York': 'NY',\n 'North Carolina': 'NC',\n 'North Dakota': 'ND',\n 'Ohio': 'OH',\n 'Oklahoma': 'OK',\n 'Oregon': 'OR',\n 'Pennsylvania': 'PA',\n 'Rhode Island': 'RI',\n 'South Carolina': 'SC',\n 'South Dakota': 'SD',\n 'Tennessee': 'TN',\n 'Texas': 'TX',\n 'Utah': 'UT',\n 'Vermont': 'VT',\n 'Virginia': 'VA',\n 'Washington': 'WA',\n 'West Virginia': 'WV',\n 'Wisconsin': 'WI',\n 'Wyoming': 'WY',\n}\nAL = {\"Emp ID\": \"Emp ID\",\n \"First Name\": \"FN\",\n \"Last Name\": \"Name\",\n \"DOB\": \"DOB\",\n \"SSN\": \"SSN\",\n \"State\": \"State\"}\nOR = [\"Emp ID\",\n \"First Name\",\n \"Last Name\",\n \"DOB\",\n \"SSN\",\n \"State\"]\n\ndef left(s, amount):\n return s[:amount]\n\n\ndef right(s, amount):\n return s[-amount:]\n\n\ndef mid(s, offset, amount):\n return s[offset:offset+amount]\n\n\n# File moved to local directory instead of using os.path.join(...),which is problematic\nflocation = 'employee_data.csv'\n\n\nEmployeeList = [] # Dictionary of Individual\nNewEmployeeList = []\n# Opens file for 'r'eading - safest technique for open and closing files as will always close even if there is an exception\n# thereby not hanging the os and losing the file\nwith open(flocation, 'r') as infile:\n csv_input = csv.reader(infile, delimiter=',')\n EmployeeList = list(csv_input)\n #NewEmployeelist = EmployeeList[:] # creates a duplicate of Employeelist not used in this case since I need to insert a column\n #and there does not seem to be an elegant way of doing it - tried comprehension but it kept crashing.\n rowcnt = 0\n for i in EmployeeList: \n #Append will append a single item to the list, in this case I am\n #appending a modified row list as indicated by the brackets.\n #if I used parenthesis I would be creating a tuple, except in that\n #case I can't modify any of the elements, which is a problem in this case\n NewEmployeeList.append([i[0],'First Name', i[1], i[2], i[3],i[4]])\n for row in NewEmployeeList:\n if rowcnt==0:\n row[2]=\"Last Name\"\n print(row)\n rowcnt+=1\n continue #continue on with the loop\n words = row[2].split( ) #make a list of the whitespace separated items\n if len(words) > 1: # I did't complete for the idea that a name would have less than two names\n row[1] = words[1] #first name\n row[2] = words[0] #redefine the name, renamed to Last name, that the parsed last name\n ds=row[3].split(\"-\")#split on the hyphen\n row[3]=ds[1]+\"/\"+ds[2]+\"/\"+ds[0] # glue the split back in a different order\n row[4] = \"***-**-\" + right(row[4],4) # used a def for slice the right 4 characters\n #I tried doing all of this strState in one line by Python kept barfing on me, so I \n #broke it up into more manageable pieces\n strState=row[5]\n strState=strState.lower()\n strState=strState.title() \n strState=us_state_abbrev[strState]\n row[5] = strState\n print(row)\n rowcnt+=1\nprint('-')\nprint('-')\nprint(\"There are \" + str(rowcnt-1) + \" employees registered in this file at the moment\") ","sub_path":"python-challenge/pyboss/pyboss.py","file_name":"pyboss.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"120985227","text":"import pika\r\n\r\nconnection=pika.BlockingConnection(pika.ConnectionParameters('localhost'))\r\nchannel=connection.channel()\r\n\r\nchannel.queue_declare(queue='hello')\r\n\r\ndef function(ch, method, properties, body):\r\n print('Received!:%r'%body)\r\n\r\nchannel.basic_consume(queue='hello', auto_ack=1, on_message_callback=function)\r\n\r\nprint('Waiting for messages. You know how to exit')\r\nchannel.start_consuming()\r\n\r\n ","sub_path":"TSIS10/First Tutorial/receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"608171204","text":"class Solution(object):\n def maxArea(self, height):\n \"\"\"\n :type height: List[int]\n :rtype: int\n \"\"\"\n left,right = 0,len(height)-1\n maxArea = 0\n while(left \n\nUse scatter() to plot the FPKM values of SRR072893 vs SRR072915.\n~/data/results/stringtie/SRR072893/t_data.ctab\n~/data/results/stringtie/SRR072915/t_data.ctab\n\n\n- Provide plot title and label axes\n- Compensate for extreme values by log transforming your values. Be sure not to lose any transcripts.\n- Compensate for overlapping points by adjusting transparency\n- Fit a curve\n\n\"\"\"\n\ndf1 = pd.read_csv( sys.argv[1], sep=\"\\t\")\ndf2 = pd.read_csv( sys.argv[2], sep=\"\\t\")\n\nx = np.log(df1[\"FPKM\"] + 1)\ny = np.log(df2[\"FPKM\"] + 1)\n\n## NOT WORKING YET\n# poly = np.polyfit(x,y,1)\n# fit = np.poly1d(poly)\n\nplt.figure()\nplt.scatter(x, y, alpha = 0.1)\nplt.plot(np.unique(x), np.poly1d(np.polyfit(x,y, deg = 2))(np.unique(x)))\nplt.axis([0,10,0,10])\nplt.xlabel(\"SRR072893\")\nplt.ylabel(\"SRR072915\")\nplt.title(\"RPKM Values\")\nplt.savefig( sys.argv[3] + \".png\" )\nplt.close()\n\n","sub_path":"day4-morning/day4-lunch.py","file_name":"day4-lunch.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"140820638","text":"def dict_invert_simple(dictionary):\n return_dict = dict((value ,[key]) for key, value in dictionary.items())\n return return_dict\n\nd1 = {1:10, 2:20, 3:30} #then dict_invert(d) returns {10: [1], 20: [2], 30: [3]}\nd2 = {1:10, 2:20, 3:30, 4:30} #then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]}\nd3 = {4:True, 2:True, 0:True} #then dict_invert(d) returns {True: [0, 2, 4]}\nd4 = {30000: 30, 600: 30, 2: 10}\n\ndef dict_invert(dictionary):\n from collections import defaultdict\n return_dict = defaultdict(list)\n for key, value in dictionary.items():\n return_dict[value].append(key)\n return_dict[value].sort()\n return dict(return_dict)\n\nprint(dict_invert(d1))\nprint(dict_invert(d2))\nprint(dict_invert(d3))\nprint(dict_invert(d4))\n","sub_path":"final/dict_invert.py","file_name":"dict_invert.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"71450661","text":"#!/usr/bin/env python\n\nimport gzip\nimport argparse\nfrom nltk.tokenize import word_tokenize\nfrom nltk import FreqDist\nimport nltk\nfrom nltk.corpus import stopwords\n\t\ndef all_u_prob(u_freqdist, u_len):\n\tu_prob_dict = {}\n\tfor word in u_freqdist.keys():\n\t\tu_prob_dict[word] = u_freqdist[word] / u_len\n\treturn u_prob_dict\n\t\ndef all_b_prob(b_freqdist, b_len):\n\tb_prob_dict = {}\n\tfor b in b_freqdist.keys():\n\t\tb_prob_dict[b] = b_freqdist[b] / b_len\n\treturn b_prob_dict\n\t\ndef all_pmi(b_freqdist, bi_length, u_freqdist, uni_length):\n\tpmi_dict = {}\n\tall_b_list = all_b_prob(b_freqdist, bi_length)\n\tall_u_list = all_u_prob(u_freqdist, uni_length)\n\tfor b in all_b_list.keys():\n\t\tword1_word2_p = all_b_list[b]\n\t\tword1_p = all_u_list[b[0]]\n\t\tword2_p = all_u_list[b[1]]\n\t\tpmi_dict[b] = word1_word2_p / (word1_p * word2_p)\n\treturn pmi_dict\n\t\n\t\nif __name__ == \"__main__\":\n\tstop_words = [word.upper() for word in stopwords.words('english')]\n\tparser = argparse.ArgumentParser(description = 'Structuring the data -- split sentences & word tokenize')\n\tparser.add_argument('-i', '--input')\n\targs = parser.parse_args()\n\twith open(args.input, 'r') as f_in:\n\t\ttext = f_in.read()\n\ttokens = word_tokenize(text)\n\t\n\tu_tokens = [word for word in tokens if word not in stop_words]\n\tu_freq = dict(FreqDist(u_tokens))\n\n\tb_tokens = nltk.bigrams(u_tokens)\n\tb_freq = dict(FreqDist(b_tokens))\n\t\n\tprint('The 30 highest-PMI word pairs, along with their unigram and bigram frequencies. ')\n\t\n\tresult_pmi = all_pmi(b_freq, len(list(nltk.bigrams(u_tokens))), u_freq, len(u_tokens))\n\tsort_pmi = sorted(result_pmi.items(), key = lambda item: item[1], reverse = True)\n\tpmi_30 = sort_pmi[:30]\n\t\n\tfor pmi in pmi_30:\n\t\tprint(\"Word pairs: \", pmi[0], ', PMI: ', pmi[1], ', Unigram frequency: ', str(u_freq[pmi[0][0]]), str(u_freq[pmi[0][1]]), ', Bigram frequencies: ', str(b_freq[pmi[0]]))\n\t\t\n\tthresholds = [30, 70, 100, 130, 170, 200, 230, 270, 300, 400]\n\tfor t in thresholds:\n\t\tprint('The 10 hightest-PMI word pairs if bigram frequency is higher than ', str(t))\n\t\tcount = 0\n\t\tfor p in sort_pmi:\n\t\t\tif count >= 10:\n\t\t\t\tbreak\n\t\t\tif b_freq[p[0]] > t:\n\t\t\t\tprint(\"Word pairs: \", p[0], ', PMI: ', p[1], ', Unigram frequency: ', str(u_freq[p[0][0]]), str(u_freq[p[0][1]]), ', Bigram frequencies: ', str(b_freq[p[0]]))\n\t\t\t\tcount += 1\n\tprint(\"Take 'NEW YORK' as an example: \")\n\ttest_tuple = ('NEW', 'YORK')\n\tdict_pmi = dict(sort_pmi)\n\tprint('PMI: ', str(dict_pmi[test_tuple]), ', Unigram frequency: ', str(u_freq['NEW']), str(u_freq['YORK']), ', Bigram frequencies: ', str(b_freq[test_tuple]))\n\t\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\n\t\n\n\n\n","sub_path":"hw1/word_association.py","file_name":"word_association.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"619430375","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExample to illustrate the use of frequency domain decomposition methods\nas implemented in fdd.py\n\"\"\"\n\nimport numpy\n\nfrom sigproc import FDD\n\n# Read some data from file\ndata = numpy.genfromtxt(\"testData.csv\",delimiter=\",\",skip_header=1)\n\n# Seperate into data and time values\nt = data[:,0]\nx = data[:,1:]\ndel data\n \n# Determine sample frequency\ndt = t[1]-t[0]\nfs= 1/dt\ndel dt\n\n# Perform frequency domain decomposition\nres = FDD(x,fs,MACtol=0.85,Np=3,makePlots=True,curveFit=True)","sub_path":"examples/fdd/fdd_example.py","file_name":"fdd_example.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"139209677","text":"from flask import Flask, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\n\nuser = 'ywmswqox'\npassword = 'i5oXVwybHjfgsk03Docu8Ul6krB0pZSX'\nhost = 'tuffi.db.elephantsql.com'\ndatabase = 'ywmswqox'\n\napp.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{user}:{password}@{host}/{database}'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.secret_key = 'secreta'\n\ndb = SQLAlchemy(app)\n\n\nclass Usuario(db.Model):\n __tablename__ = 'usuario'\n id = db.Column(db.Integer, primary_key=True)\n nome = db.Column(db.String(255), nullable=False)\n email = db.Column(db.String(255), nullable=False)\n endereco = db.Column(db.String(255), nullable=False)\n\n def __init__(self, nome, email, endereco):\n self.nome = nome\n self.email = email\n self.endereco = endereco\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n\n @staticmethod\n def read_single(registro_id):\n # select * from anuncios where id=1\n return anuncios.query.get(registro_id)\n\nclass anuncios(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n nome_vendedor = db.Column(db.String(255), nullable=False)\n nome_produto = db.Column(db.String(255), nullable=False)\n valor_produto = db.Column(db.Integer, nullable=False)\n descricao_produto = db.Column(db.String, nullable=False)\n imagem_url = db.Column(db.String(255), nullable=False)\n\n def __init__(self, nome_vendedor, nome_produto, valor_produto, descricao_produto, imagem_url):\n self.nome_vendedor = nome_vendedor\n self.nome_produto = nome_produto\n self.valor_produto = valor_produto\n self.descricao_produto = descricao_produto\n self.imagem_url = imagem_url\n\n @staticmethod\n def read_all():\n # select * from anuncios order by id desc\n return anuncios.query.order_by(anuncios.id.asc()).all()\n\n @staticmethod\n def read_single(registro_id):\n # select * from anuncios where id=1\n return anuncios.query.get(registro_id)\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n\n def update(self, new_data):\n self.nome_vendedor = new_data.nome_vendedor\n self.nome_produto = new_data.nome_produto\n self.valor_produto = new_data.valor_produto\n self.descricao_produto = new_data.descricao_produto\n self.imagem_url = new_data.imagem_url\n self.save()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n@app.route(\"/\")\ndef index():\n return render_template('index.html')\n\n@app.route('/read')\ndef read_all():\n registros = anuncios.read_all()\n return render_template('read_all.html', registros=registros)\n\n\n@app.route('/read/') # Posso colocar qualquer nome entre <>\ndef read_single(registro_id):\n registro = anuncios.read_single(registro_id)\n print(registro)\n\n return render_template('read_single.html', registro=registro)\n\n@app.route('/create', methods=('GET', 'POST'))\ndef create():\n id_atribuido = None\n if request.method == 'POST':\n form = request.form\n registro = anuncios(form['nome_vendedor'], form['nome_produto'], form['valor_produto'], form['descricao_produto'], form['imagem_url'])\n registro.save()\n id_atribuido = registro.id\n\n return render_template('create.html', id_atribuido=id_atribuido)\n\n@app.route('/update/', methods=('GET', 'POST'))\ndef update(registro_id):\n sucesso = None\n registro = anuncios.read_single(registro_id)\n\n if request.method == 'POST':\n form = request.form\n new_data = anuncios(form['nome_vendedor'], form['nome_produto'],form['valor_produto'], form['descricao_produto'], form['imagem_url'])\n registro.update(new_data)\n sucesso = True\n return render_template('update.html', registro=registro, sucesso=sucesso)\n\n@app.route('/dados/', methods=('GET', 'POST'))\ndef dados(registro_id):\n usuario = Usuario.read_single(registro_id)\n comprado_s = None\n id = None\n nome= None\n email = None\n endereco = None\n registro = anuncios.read_single(registro_id)\n novo = None\n \n if request.method == 'POST':\n form = request.form\n novo = Usuario(form['nome'],form['email'], form['endereco'])\n novo.save()\n comprado_s = True\n nome = novo.nome\n email= novo.email\n endereco = novo.endereco\n id = novo.id\n \n return render_template('dados.html', usuario = usuario, registro=registro, id = id, comprado_s = comprado_s, nome = nome, email = email, endereco = endereco)\n\n\n@app.route('/dados//confirmar')\ndef confirmar(registro_id):\n comprado = None\n registro = anuncios.read_single(registro_id)\n\n if registro:\n registro.delete()\n comprado = True\n \n \n return render_template('dados.html', registro_id=registro_id, registro=registro, comprado=comprado)\n\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"modulo2/blue/banco de dados/teste/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"168196996","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nimport time\nimport datetime\nimport collections\n\nst = datetime.datetime.strptime('2018-05-01 08:00:00', '%Y-%m-%d %H:%M:%S')\n\nprint(st)\nprint(st.timetuple())\n\nprint(time.strptime('2018-05-01 08:00:00', '%Y-%m-%d %H:%M:%S'))\n\nprint(int(time.mktime(st.timetuple())))\n\nstart = time.mktime(time.strptime('2018-05-01 08:00:00', '%Y-%m-%d %H:%M:%S'))\nend = time.mktime(time.strptime('2018-05-01 09:00:00', '%Y-%m-%d %H:%M:%S'))\n\nstep = 5 * 60\n\nprint(range(1, 100, 5))\n\n\ndef _range(start, end, step):\n return [x for x in xrange(start, end + 1) if x % step == 0]\n\n\ndef _range2(start, end, step):\n return range(start if start % step == 0 else start + (step - start % step), end + 1, step)\n\n\nprint(_range(10, 100, 5))\nprint(_range2(10, 100, 5))\n\nprint(_range(1, 100, 5))\nprint(_range2(1, 100, 5))\n\n\ndef make_container(keys):\n d = collections.OrderedDict()\n for k in keys:\n d.update(k={\n 'ts': k,\n 'max': '-',\n 'min': '-',\n 'avg': '-',\n })\n return d\n\n\ndef replenish(data, start, end, gran):\n step = gran * 60\n keys = _range(start, end, step)\n result = make_container(keys)\n\n for item in data:\n if item['ts'] in result:\n result[item['ts']] = item\n\n return result.values()\n","sub_path":"snippets/replenish.py","file_name":"replenish.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"567656485","text":"import sys\n\nfrom setuptools import setup\n\n_version_file = 'hooked/version.py'\n\nwith open(_version_file) as vf:\n exec(vf.read())\n\n\n# Include pytest-runner as a setup-requirement only if it looks like we're\n# doing something test-related.\n#\n# This way we can avoid having to install it when, for example, somebody just\n# wants to build/install django-gapi-hooked as a dependency.\n#\n# See: https://pypi.org/project/pytest-runner/#conditional-requirement\nneeds_pytest = {'pytest', 'test', 'ptr'}.intersection(sys.argv)\nmaybe_pytest_runner = ['pytest-runner'] if needs_pytest else []\n\n\nsetup(\n name='django-gapi-hooked',\n version=__version__,\n author='G Adventures',\n author_email='software@gadventures.com',\n description='A tiny library to add a G Adventures API Web Hook receiver view to your code base.',\n download_url='https://github.com/gadventures/django-gapi-hooked/tarball/%s' % __version__,\n url='https://github.com/gadventures/django-gapi-hooked',\n packages=[\n 'hooked',\n ],\n install_requires=[\n 'django',\n ],\n keywords=[\n 'gapi',\n 'g adventures',\n 'g api',\n 'gapipy'\n ],\n setup_requires=maybe_pytest_runner,\n tests_require=[\n 'pytest',\n 'pytest-django',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"30944912","text":"import numpy as np\nimport train_helper\nimport math\n\ndef calc_one_hist(t, u, v,all_tags,five_words,features_id,w,curr_opt_hist):\n num_tags = len(all_tags)\n ppword = five_words[0]\n pword = five_words[1]\n cword = five_words[2]\n nword = five_words[3]\n nnword = five_words[4]\n\n pptag = all_tags[t]\n ptag = all_tags[u]\n ctag = all_tags[v]\n\n curr_hist = [cword, pptag, ptag, ctag, nword, pword, nnword, ppword]\n curr_feature = train_helper.represent_input_with_features(curr_hist, features_id)\n sum_one_feature = 0\n for idx in curr_feature:\n sum_one_feature += w[idx]\n curr_exp = math.exp(sum_one_feature)\n #curr_exp = np.exp(sum_one_feature)\n curr_opt_hist[t, u, v] = curr_exp\n","sub_path":"Wet1/Code Directory/Code/calc_one_hist.py","file_name":"calc_one_hist.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"486874555","text":"import os\nimport glob\nimport readline\nfrom zipfile import ZipFile\nfrom tempfile import NamedTemporaryFile\n\nfrom pyxnat import Interface\n\ndef complete(text, state):\n return (glob.glob(text + '*') + [None])[state]\n\ndef create(entity, ID=None):\n if not entity.exists():\n if ID is not None:\n entity.create(ID=ID)\n else:\n entity.create()\n\nreadline.set_completer_delims(' \\t\\n;')\nreadline.parse_and_bind('tab: complete')\nreadline.set_completer(complete)\n\n\nuser = raw_input(\"Username: \")\ninterface = Interface(server='https://fmrif-xnat.nimh.nih.gov/xnat', user=user, cachedir='./tmp')\n\nproj_name = raw_input(\"Project: \")\nproj = interface.select.project(proj_name)\ncreate(proj)\n\nsubj_name = raw_input(\"Subject: \")\nsubj = proj.subject(subj_name)\ncreate(subj)\n\nexp_name = raw_input(\"Experiment: \")\nexp = subj.experiment(exp_name)\ncreate(exp)\n\nstudydir = raw_input(\"Study Directory: \")\n#studydir = '/Users/naegelejd/data/tmp/MEFacesScenes/subject01/'\n\nfor dirname in os.listdir(studydir):\n scandir = os.path.join(studydir, dirname)\n niftis = glob.glob(os.path.join(scandir, '*.nii'))\n scan = exp.scan(dirname)\n scan.create()\n nii = scan.resource('NIFTI')\n temp = NamedTemporaryFile()\n zf = ZipFile(temp, 'w')\n for vol in niftis:\n zf.write(vol, os.path.basename(vol))\n zf.close()\n temp.seek(0)\n nii.put_zip(temp.name)\n","sub_path":"nihfmrif/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"26137595","text":"#!/bin/env python3\n#coding=utf-8\n# @Time : 2020/1/1 13:45\n# @Author : Victor\n# @Site :\n# @File : l_offlineData2mysql.py 即离线数据导入MySQL的开发脚本\n# @Software: PyCharm\nimport uuid\nimport pymysql\nimport csv\nimport datetime\nfrom basic_config.bc_offlinedata2mysql import Config\n\n\ndef gene_uuid():\n uuid_ = str(uuid.uuid4()).replace(\"-\", \"\") + '000'\n return uuid_\n\ndef connect_mysql(mysql_conf):\n db = pymysql.connect(mysql_conf['addr'], mysql_conf['user'], mysql_conf['pswd'], charset=\"utf8\",port=mysql_conf['port'])\n cur = db.cursor()\n cur.execute(\"use {}\".format(mysql_conf['usedb']))\n return db, cur\n\nuuid_train_type = gene_uuid()\nuuid_trian_no = gene_uuid()\nuuid_real_time = gene_uuid()\nm = 'TEST001###TEST_TYPE_01###1001'\nlist_split = m.split(\"###\")\nsql_cd_train_type = Config.sql_cd_train_type.format(uuid_train_type, list_split[0], list_split[1],\n Config.list_basic_attr['create_by'],\n Config.list_basic_attr['create_date'],\n Config.list_basic_attr['update_by'],\n Config.list_basic_attr['update_date'],\n Config.list_basic_attr['remarks'],\n Config.list_basic_attr['del_flag'])\n# print(sql_cd_train_type)\n\ndb,cur = connect_mysql(Config.mysql_config)\ncur.execute(Config.exec_judge_aff_app.format('E28','250公里统型','2216'))\n# data = cur.fetchall()\nprint(cur.fetchall())\ndb.commit()\ndb.close()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"test/test_offdata2mysql.py","file_name":"test_offdata2mysql.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"487092239","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport logging\nimport numpy as np\nfrom typing import Dict\nimport torch\nfrom torch import nn\n\nfrom utils.util_class import ShapeSpec\nfrom config import Config as cfg\nfrom model.matcher import Matcher\nfrom model.model_util import Conv2d\nfrom model.poolers import ROIPooler\nfrom model.box_regression import Box2BoxTransform\nfrom utils.batch_norm import get_norm\nfrom train.loss_pool import FastRCNNOutputLayers\n\n\nclass ROIHeads(torch.nn.Module):\n \"\"\"\n ROIHeads perform all per-region computation in an R-CNN.\n\n It contains logic of cropping the regions, extract per-region features,\n and make per-region predictions.\n\n It can have many variants, implemented as subclasses of this class.\n \"\"\"\n\n def __init__(self, input_shape: Dict[str, ShapeSpec]):\n super(ROIHeads, self).__init__()\n\n # fmt: off\n self.batch_size_per_image = cfg.Model.ROI_HEADS.BATCH_SIZE_PER_IMAGE\n self.positive_sample_fraction = cfg.Model.ROI_HEADS.POSITIVE_FRACTION\n self.test_score_thresh = cfg.Model.ROI_HEADS.SCORE_THRESH_TEST\n self.test_nms_thresh = cfg.Model.ROI_HEADS.NMS_THRESH_TEST\n self.test_detections_per_img = 100\n self.in_features = cfg.Model.ROI_HEADS.INPUT_FEATURES\n self.num_classes = cfg.Model.ROI_HEADS.NUM_CLASSES\n self.proposal_append_gt = cfg.Model.ROI_HEADS.PROPOSAL_APPEND_GT\n self.feature_strides = {k: v.stride for k, v in input_shape.items()}\n self.feature_channels = {k: v.channels for k, v in input_shape.items()}\n self.cls_agnostic_bbox_reg = cfg.Model.ROI_BOX_HEAD.CLS_AGNOSTIC_BBOX_REG\n self.smooth_l1_beta = cfg.Model.ROI_BOX_HEAD.SMOOTH_L1_BETA\n self.rotated_box_training = \"true\"\n self.vp_bins = cfg.Model.Structure.VP_BINS\n self.vp_weight_loss = cfg.Model.Structure.VP_WEIGHT_LOSS\n self.weights_height = cfg.Model.Structure.WEIGHTS_HEIGHT\n # fmt: on\n\n # Matcher to assign box proposals to gt boxes\n self.proposal_matcher = Matcher(\n cfg.Model.ROI_HEADS.IOU_THRESHOLDS,\n cfg.Model.ROI_HEADS.IOU_LABELS,\n allow_low_quality_matches=False,\n )\n\n # Box2BoxTransform for bounding box regression\n self.box2box_transform = Box2BoxTransform(weights=cfg.Model.ROI_BOX_HEAD.BBOX_REG_WEIGHTS)\n\n def _sample_proposals(self, matched_idxs, matched_labels, gt_classes):\n \"\"\"\n Based on the matching between N proposals and M groundtruth,\n sample the proposals and set their classification labels.\n\n Args:\n matched_idxs (Tensor): a vector of length N, each is the best-matched\n gt index in [0, M) for each proposal.\n matched_labels (Tensor): a vector of length N, the matcher's label\n (one of cfg.MODEL.ROI_HEADS.IOU_LABELS) for each proposal.\n gt_classes (Tensor): a vector of length M.\n\n Returns:\n Tensor: a vector of indices of sampled proposals. Each is in [0, N).\n Tensor: a vector of the same length, the classification label for\n each sampled proposal. Each sample is labeled as either a category in\n [0, num_classes) or the background (num_classes).\n \"\"\"\n has_gt = gt_classes.numel() > 0\n # Get the corresponding GT for each proposal\n if has_gt:\n gt_classes = gt_classes[matched_idxs]\n # Label unmatched proposals (0 label from matcher) as background (label=num_classes)\n gt_classes[matched_labels == 0] = self.num_classes\n # Label ignore proposals (-1 label)\n gt_classes[matched_labels == -1] = -1\n else:\n gt_classes = torch.zeros_like(matched_idxs) + self.num_classes\n\n sampled_fg_idxs, sampled_bg_idxs = subsample_labels(\n gt_classes, self.batch_size_per_image, self.positive_sample_fraction, self.num_classes\n )\n\n sampled_idxs = torch.cat([sampled_fg_idxs, sampled_bg_idxs], dim=0)\n return sampled_idxs, gt_classes[sampled_idxs]\n\n @torch.no_grad()\n def label_and_sample_proposals(self, proposals, targets):\n \"\"\"\n Prepare some proposals to be used to train the ROI heads.\n It performs box matching between `proposals` and `targets`, and assigns\n training labels to the proposals.\n It returns `self.batch_size_per_image` random samples from proposals and groundtruth boxes,\n with a fraction of positives that is no larger than `self.positive_sample_fraction.\n\n Args:\n See :meth:`ROIHeads.forward`\n\n Returns:\n list[Instances]:\n length `N` list of `Instances`s containing the proposals\n sampled for training. Each `Instances` has the following fields:\n - proposal_boxes: the proposal boxes\n - gt_boxes: the ground-truth box that the proposal is assigned to\n (this is only meaningful if the proposal has a label > 0; if label = 0\n then the ground-truth box is random)\n Other fields such as \"gt_classes\", \"gt_masks\", that's included in `targets`.\n \"\"\"\n gt_boxes = [x.gt_boxes for x in targets]\n # Augment proposals with ground-truth boxes.\n # In the case of learned proposals (e.g., RPN), when training starts\n # the proposals will be low quality due to random initialization.\n # It's possible that none of these initial\n # proposals have high enough overlap with the gt objects to be used\n # as positive examples for the second stage components (box head,\n # cls head, mask head). Adding the gt boxes to the set of proposals\n # ensures that the second stage components will have some positive\n # examples from the start of training. For RPN, this augmentation improves\n # convergence and empirically improves box AP on COCO by about 0.5\n # points (under one tested configuration).\n if self.proposal_append_gt:\n proposals = add_ground_truth_to_proposals(gt_boxes, proposals)\n\n proposals_with_gt = []\n\n num_fg_samples = []\n num_bg_samples = []\n for proposals_per_image, targets_per_image in zip(proposals, targets):\n has_gt = len(targets_per_image) > 0\n match_quality_matrix = pairwise_iou(\n targets_per_image.gt_boxes, proposals_per_image.proposal_boxes\n )\n matched_idxs, matched_labels = self.proposal_matcher(match_quality_matrix)\n sampled_idxs, gt_classes = self._sample_proposals(\n matched_idxs, matched_labels, targets_per_image.gt_classes\n )\n\n # Set target attributes of the sampled proposals:\n proposals_per_image = proposals_per_image[sampled_idxs]\n proposals_per_image.gt_classes = gt_classes\n\n # We index all the attributes of targets that start with \"gt_\"\n # and have not been added to proposals yet (=\"gt_classes\").\n if has_gt:\n sampled_targets = matched_idxs[sampled_idxs]\n # NOTE: here the indexing waste some compute, because heads\n # like masks, keypoints, etc, will filter the proposals again,\n # (by foreground/background, or number of keypoints in the image, etc)\n # so we essentially index the data twice.\n for (trg_name, trg_value) in targets_per_image.get_fields().items():\n if trg_name.startswith(\"gt_\") and not proposals_per_image.has(trg_name):\n proposals_per_image.set(trg_name, trg_value[sampled_targets])\n else:\n gt_boxes = Boxes(\n targets_per_image.gt_boxes.tensor.new_zeros((len(sampled_idxs), 4))\n )\n proposals_per_image.gt_boxes = gt_boxes\n\n num_bg_samples.append((gt_classes == self.num_classes).sum().item())\n num_fg_samples.append(gt_classes.numel() - num_bg_samples[-1])\n proposals_with_gt.append(proposals_per_image)\n\n # Log the number of fg/bg samples that are selected for training ROI heads\n storage = get_event_storage()\n storage.put_scalar(\"roi_head/num_fg_samples\", np.mean(num_fg_samples))\n storage.put_scalar(\"roi_head/num_bg_samples\", np.mean(num_bg_samples))\n\n return proposals_with_gt\n\n def forward(self, images, features, proposals, targets=None):\n \"\"\"\n Args:\n images (ImageList):\n features (dict[str: Tensor]): input data as a mapping from feature\n map name to tensor. Axis 0 represents the number of images `N` in\n the input data; axes 1-3 are channels, height, and width, which may\n vary between feature maps (e.g., if a feature pyramid is used).\n proposals (list[Instances]): length `N` list of `Instances`s. The i-th\n `Instances` contains object proposals for the i-th input image,\n with fields \"proposal_boxes\" and \"objectness_logits\".\n targets (list[Instances], optional): length `N` list of `Instances`s. The i-th\n `Instances` contains the ground-truth per-instance annotations\n for the i-th input image. Specify `targets` during training only.\n It may have the following fields:\n - gt_boxes: the bounding box of each instance.\n - gt_classes: the label for each instance with a category ranging in [0, #class].\n - gt_masks: PolygonMasks or BitMasks, the ground-truth masks of each instance.\n - gt_keypoints: NxKx3, the groud-truth keypoints for each instance.\n\n Returns:\n results (list[Instances]): length `N` list of `Instances`s containing the\n detected instances. Returned during inference only; may be []\n during training.\n losses (dict[str: Tensor]): mapping from a named loss to a tensor\n storing the loss. Used during training only.\n \"\"\"\n raise NotImplementedError()\n\n\nclass StandardROIHeads(ROIHeads):\n \"\"\"\n It's \"standard\" in a sense that there is no ROI transform sharing\n or feature sharing between tasks.\n The cropped rois go to separate branches (boxes and masks) directly.\n This way, it is easier to make separate abstractions for different branches.\n\n This class is used by most models, such as FPN and C5.\n To implement more models, you can subclass it and implement a different\n :meth:`forward()` or a head.\n \"\"\"\n\n def __init__(self, input_shape):\n super(StandardROIHeads, self).__init__(input_shape)\n self._init_box_head()\n\n def _init_box_head(self):\n # fmt: off\n pooler_resolution = cfg.Model.ROI_BOX_HEAD.POOLER_RESOLUTION\n pooler_scales = tuple(1.0 / self.feature_strides[k] for k in self.in_features)\n sampling_ratio = cfg.Model.ROI_BOX_HEAD.POOLER_SAMPLING_RATIO\n pooler_type = \"ROIAlignV2\"\n # fmt: on\n\n # If StandardROIHeads is applied on multiple feature maps (as in FPN),\n # then we share the same predictors and therefore the channel counts must be the same\n in_channels = [self.feature_channels[f] for f in self.in_features]\n # Check all channel counts are equal\n assert len(set(in_channels)) == 1, in_channels\n in_channels = in_channels[0]\n\n self.box_pooler = ROIPooler(\n output_size=pooler_resolution,\n scales=pooler_scales,\n sampling_ratio=sampling_ratio,\n pooler_type=pooler_type,\n canonical_level=int((cfg.Model.RESNET.OUT_FEATURES[-1].split('res'))[1])\n )\n # Here we split \"box head\" and \"box predictor\", which is mainly due to historical reasons.\n # They are used together so the \"box predictor\" layers should be part of the \"box head\".\n # New subclasses of ROIHeads do not need \"box predictor\"s.\n self.box_head = FastRCNNConvFCHead(\n ShapeSpec(channels=in_channels, height=pooler_resolution, width=pooler_resolution)\n )\n self.box_predictor = FastRCNNOutputLayers(\n self.box_head.output_size, self.num_classes, self.cls_agnostic_bbox_reg\n )\n\n def forward(self, images, features, proposals, targets=None):\n \"\"\"\n See :class:`ROIHeads.forward`.\n \"\"\"\n del images\n if self.training:\n proposals = self.label_and_sample_proposals(proposals, targets)\n del targets\n\n features_list = [features[f] for f in self.in_features]\n\n if self.training:\n losses = self._forward_box(features_list, proposals)\n # During training the proposals used by the box head are\n # used by the mask, keypoint (and densepose) heads.\n losses.update(self._forward_mask(features_list, proposals))\n losses.update(self._forward_keypoint(features_list, proposals))\n return proposals, losses\n else:\n pred_instances = self._forward_box(features_list, proposals)\n # During inference cascaded prediction is used: the mask and keypoints heads are only\n # applied to the top scoring box detections.\n pred_instances = self.forward_with_given_boxes(features, pred_instances)\n return pred_instances, {}\n\n def forward_with_given_boxes(self, features, instances):\n \"\"\"\n Use the given boxes in `instances` to produce other (non-box) per-ROI outputs.\n\n This is useful for downstream tasks where a box is known, but need to obtain\n other attributes (outputs of other heads).\n Test-time augmentation also uses this.\n\n Args:\n features: same as in `forward()`\n instances (list[Instances]): instances to predict other outputs. Expect the keys\n \"pred_boxes\" and \"pred_classes\" to exist.\n\n Returns:\n instances (Instances):\n the same `Instances` object, with extra\n fields such as `pred_masks` or `pred_keypoints`.\n \"\"\"\n assert not self.training\n assert instances[0].has(\"pred_boxes\") and instances[0].has(\"pred_classes\")\n features = [features[f] for f in self.in_features]\n\n instances = self._forward_mask(features, instances)\n instances = self._forward_keypoint(features, instances)\n return instances\n\n def _forward_box(self, features, proposals):\n \"\"\"\n Forward logic of the box prediction branch.\n\n Args:\n features (list[Tensor]): #level input features for box prediction\n proposals (list[Instances]): the per-image object proposals with\n their matching ground truth.\n Each has fields \"proposal_boxes\", and \"objectness_logits\",\n \"gt_classes\", \"gt_boxes\".\n\n Returns:\n In training, a dict of losses.\n In inference, a list of `Instances`, the predicted instances.\n \"\"\"\n box_features = self.box_pooler(features, [x.proposal_boxes for x in proposals])\n box_features = self.box_head(box_features)\n pred_class_logits, pred_proposal_deltas, viewpoint_logits, \\\n viewpoint_residuals, height_logits = self.box_predictor(box_features)\n del box_features\n\n outputs = FastRCNNOutputs(\n self.box2box_transform,\n pred_class_logits,\n pred_proposal_deltas,\n proposals,\n self.smooth_l1_beta,\n self.vp_bins,\n viewpoint_logits,\n viewpoint_residuals,\n self.rotated_box_training,\n height_logits,\n self.weights_height\n )\n if self.training:\n losses = outputs.losses()\n for loss in losses.keys():\n if \"viewpoint\" in loss:\n losses[loss] *= self.vp_weight_loss\n return losses\n else:\n pred_instances, _ = outputs.inference(\n self.test_score_thresh, self.test_nms_thresh, self.test_detections_per_img\n )\n return pred_instances\n\n\nclass FastRCNNConvFCHead(nn.Module):\n \"\"\"\n A head with several 3x3 conv layers (each followed by norm & relu) and\n several fc layers (each followed by relu).\n \"\"\"\n\n def __init__(self, input_shape: ShapeSpec):\n \"\"\"\n The following attributes are parsed from config:\n num_conv, num_fc: the number of conv/fc layers\n conv_dim/fc_dim: the dimension of the conv/fc layers\n norm: normalization for the conv layers\n \"\"\"\n super().__init__()\n\n # fmt: off\n num_conv = cfg.Model.ROI_BOX_HEAD.NUM_CONV\n conv_dim = cfg.Model.ROI_BOX_HEAD.CONV_DIM\n num_fc = cfg.Model.ROI_BOX_HEAD.NUM_FC\n fc_dim = cfg.Model.ROI_BOX_HEAD.FC_DIM\n norm = cfg.Model.ROI_BOX_HEAD.NORM\n # fmt: on\n assert num_conv + num_fc > 0\n\n self._output_size = (input_shape.channels, input_shape.height, input_shape.width)\n\n self.conv_norm_relus = []\n for k in range(num_conv):\n conv = Conv2d(\n self._output_size[0],\n conv_dim,\n kernel_size=3,\n padding=1,\n bias=not norm,\n norm=get_norm(norm, conv_dim),\n activation=F.relu,\n )\n self.add_module(\"conv{}\".format(k + 1), conv)\n self.conv_norm_relus.append(conv)\n self._output_size = (conv_dim, self._output_size[1], self._output_size[2])\n\n self.fcs = []\n for k in range(num_fc):\n fc = nn.Linear(np.prod(self._output_size), fc_dim)\n self.add_module(\"fc{}\".format(k + 1), fc)\n self.fcs.append(fc)\n self._output_size = fc_dim\n\n # for layer in self.conv_norm_relus:\n # weight_init.c2_msra_fill(layer)\n # for layer in self.fcs:\n # weight_init.c2_xavier_fill(layer)\n\n def forward(self, x):\n for layer in self.conv_norm_relus:\n x = layer(x)\n if len(self.fcs):\n if x.dim() > 2:\n x = torch.flatten(x, start_dim=1)\n for layer in self.fcs:\n x = F.relu(layer(x))\n return x\n\n @property\n def output_size(self):\n return self._output_size\n","sub_path":"model/head.py","file_name":"head.py","file_ext":"py","file_size_in_byte":18509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"266567679","text":"import pytest\nimport math\nimport numpy as np\nimport autodiff32 as ad\n\ndef test_submulti():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=3, Graph=Graph)\n y = ad.Node(value=2, Graph=Graph)\n func = 1 + x*5 - 2*y\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert(func.value, x.deri, y.deri) == (12, 5, -2)\n\n\ndef test_addnegexp():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=5, Graph=Graph)\n func = -x + 2*x**2 + 2\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert(func.value, x.deri) == (47, 19)\n\n\ndef test_div():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=5, Graph=Graph)\n func = 1 / x + x/2\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert (func.value, x.deri) == (2.7, .46)\n\ndef test_revpower():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=2, Graph=Graph)\n func = 2 - 2**x\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert(func.value, x.deri) == (-2, -4*np.log(2))\n\n\ndef test_series():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=5, Graph=Graph)\n f = x ** 2\n C = np.array([[4, 2, 3]])\n D = 1\n Vals, Ders = Graph.SeriesValues(C, D, Graph)\n assert np.array_equal(Vals, [16, 4, 9]) and np.array_equal(Ders, [[8], [4], [6]])\n\n\ndef test_jacobian():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=3, Graph=Graph)\n y = ad.Node(value=5, Graph=Graph)\n z = ad.Node(value=1, Graph=Graph)\n f = np.array([-2*x, 2*y+z, 3*x+3*y+2*z])\n func = ad.ReverseVecFunc(f, x=x, y=y, z=z)\n val, jacobian = func.value(Graph)\n assert np.array_equal(val, [-6, 11, 26]) and np.array_equal(jacobian, [[-2, 0, 0], [0, 2, 1], [3, 3, 2]])\n\n\ndef test_jacobian_series():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=3, Graph=Graph)\n y = ad.Node(value=4, Graph=Graph)\n X = [1, 3]\n Y = [2, 4]\n C = np.array([X, Y])\n D = 2 # Dimension\n f = np.array([x * 3, 5 * y ** 2])\n func = ad.ReverseVecFunc(f, x=x, y=y)\n vals, derivs = func.Seriesvalue(C, D, Graph)\n assert np.array_equal(vals, [[3, 20], [9, 80]]) and np.array_equal(derivs, [[[3, 0], [0,20]], [[3, 0], [0, 40]]])\n\n\ndef test_exp():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=3, Graph=Graph)\n func = ad.expr(x)\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert (func.value, x.deri) == (np.exp(3), np.exp(3))\n\n\ndef test_logsqrt():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=2, Graph=Graph)\n func = ad.sqrtr(ad.logr(x))\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert (func.value, x.deri) == (np.sqrt(np.log(2)), .25 * (1 / (np.sqrt(np.log(2)))))\n\n\ndef test_trig1():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=math.pi, Graph=Graph)\n func = ad.cosr(x) - ad.sinr(2*x) + ad.tanr(x)\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert abs(func.value - (-1)) < .000001 and abs(x.deri - (-1)) < .000001\n\n\ndef test_trig2():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=0, Graph=Graph)\n func = ad.asinr(x) * ad.acosr(x**2) + 2*ad.atanr(x)\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert (func.value, x.deri) == (0, 2+np.arccos(0))\n\n\ndef test_trig3():\n Graph = ad.ComputationalGraph()\n x = ad.Node(value=0, Graph=Graph)\n func = ad.sinhr(x) + ad.coshr(x) + ad.tanhr(x)\n Graph.ComputeValue()\n Graph.ComputeGradient()\n assert (func.value, x.deri) == (1, 2)\n\n\n\n","sub_path":"tests/Reverse_test.py","file_name":"Reverse_test.py","file_ext":"py","file_size_in_byte":3434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"389148211","text":"import tkinter as tk\nfrom tkinter.font import Font\nfrom tkinter import messagebox\nimport os\nimport pickle\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.figure import Figure\n\n\nclass PbVisualisation(tk.Frame):\n \"\"\"Take the 1D arrays from stored files of (ΔPB) and (ΔNeq) and plot\n them in graphical interface\"\"\"\n\n def __init__(self, parent):\n tk.Frame.__init__(self, parent)\n # Setup increment number to determinate how many subplots in one\n # figure.\n self.increment_num = tk.IntVar()\n self.increment_num.set(0)\n # variables to determine amino acids\n self.aa_start_var = tk.IntVar()\n self.aa_end_var = tk.IntVar()\n\n self.parent = parent\n self.local_parent = tk.Toplevel()\n # Create Panels\n self.left_panel = tk.Frame(self.local_parent, width=350, height=200)\n self.left_panel.grid(row=0, column=0, columnspan=25, padx=5, pady=5)\n self.left_panel.grid_columnconfigure(0, weight=1)\n self.left_panel.rowconfigure(0, weight=1)\n self.right_panel = tk.Frame(self.local_parent, width=350, height=200)\n self.right_panel.grid(row=0, column=26, padx=5, pady=5)\n self.right_panel.grid_columnconfigure(0, weight=1)\n self.right_panel.rowconfigure(0, weight=1)\n # Create listbox to show list of available files\n bold_font = Font(weight='bold')\n self.box_title = tk.Label(self.left_panel, font=bold_font,\n text=\"List of (ΔPB), (ΔNeq) and (Neq)\"\n \" files:\"\n )\n self.box_title.grid(row=0, column=0, padx=5, sticky='w')\n\n self.files_lstbx = tk.Listbox(self.left_panel, width=55)\n self.files_lstbx.grid(row=2, column=0, rowspan=20,\n columnspan=40, padx=5, pady=5)\n self.files_lstbx.bind(\"<>\", self.plot_it)\n\n # Create widgets to determine which part of sequence to be shown\n start_aa_lbl = tk.Label(self.left_panel,\n text=\"AA start at position:\")\n start_aa_lbl.grid(row=22, column=0, columnspan=5, padx=5, pady=5,\n sticky=tk.W\n )\n end_aa_lbl = tk.Label(self.left_panel,\n text=\"AA end at position:\")\n end_aa_lbl.grid(row=23, column=0, columnspan=5, padx=5, pady=5,\n sticky=tk.W\n )\n\n self.aa_start_entry = tk.Entry(self.left_panel, width=10,\n textvariable=self.aa_start_var\n )\n self.aa_start_entry.grid(row=22, column=8, columnspan=15,\n sticky=tk.W+tk.E\n )\n self.aa_end_entry = tk.Entry(self.left_panel, width=10,\n textvariable=self.aa_end_var)\n self.aa_end_entry.grid(row=23, column=8, columnspan=15,\n sticky=tk.W+tk.E\n )\n apply_but = tk.Button(self.left_panel, text=\"Apply\",\n command=self.plot_it\n )\n apply_but.grid(row=24, column=20, padx=5, pady=5)\n\n # Create canvas to show generated graphs\n self.canvas_support = tk.Canvas(self.right_panel, bg='gray65',\n width=350, height=300)\n self.canvas_support.grid(row=0, column=0, padx=5, pady=5)\n # Make the Canvas to contain the inner object, and keep the\n # size(not to propagate)\n self.canvas_support.grid_columnconfigure(0, weight=1)\n self.canvas_support.grid_rowconfigure(0, weight=1)\n self.canvas_support.propagate(0)\n\n # Initialisation\n self.load_files()\n\n def load_files(self):\n \"\"\"load,into the listbox, all files exist in the directory\n (database/results/)\"\"\"\n path_to_files = os.getcwd() + '/database/results/'\n self.files_lstbx.delete(0, 'end')\n if os.path.exists(path_to_files):\n files_list = [_file for _file in os.listdir(path_to_files)]\n for x in files_list:\n # Exclude files with .pbq (not ready to plot)\n extension = x.split(\".\")[-1]\n if extension != \"pbq\":\n self.files_lstbx.insert('end', x)\n\n def plot_it(self, *event):\n \"\"\"Show plots of the gaven data\n\n :param\n :return: graph by matplotlib\n \"\"\"\n\n # Extract data from the file\n # TODO: other way: file = self.files_lstbx.get(tk.ACTIVE)\n # Be sure that user has selected an element from listbox\n file = self.files_lstbx.selection_get()\n path_to_file = os.getcwd() + '/database/results/' + str(file)\n data_file = open(path_to_file, mode='rb')\n data = pickle.load(data_file)\n\n # Assign the length of wanted amino acids to variables\n if self.aa_end_var.get() == 0:\n self.aa_end_var.set(len(data))\n # show only certain portion of sequence\n zoomed_data = data[self.aa_start_var.get():\n self.aa_end_var.get()]\n\n # In order to get on graph in the canvas we run the function\n # .get_tk_widget().grid_remove() to remove the actual plot\n # graph.\n # TODO: separate this if block in an independent function\n if self.increment_num.get() == 0:\n # Plot the data\n self.plot_figure = Figure(figsize=(5, 5), dpi=100)\n self.subplot = self.plot_figure.add_subplot(111)\n # plotting from data\n x_axis = [element for element in range(len(zoomed_data))]\n self.subplot.plot(x_axis, zoomed_data)\n self.plot_canvas = FigureCanvasTkAgg(self.plot_figure,\n self.canvas_support)\n # Set labels for the graph\n self.subplot.set_title(str(file))\n extension = list(str(file).split(\".\"))\n if extension[-1] == \"neq_delta\":\n self.subplot.set_ylabel(\"ΔNeq\")\n elif extension[-1] == \"pbq_delta\":\n self.subplot.set_ylabel(\"ΔPB\")\n self.subplot.set_xlabel(\"Amino Acids\")\n # Show plot\n self.plot_canvas.draw()\n self.plot_canvas.get_tk_widget().grid()\n self.increment_num.set(self.increment_num.get() + 1)\n # If we need two graphs in the canvas we have to make the\n # increment number > than 1, if three we set 2, etc...\n elif self.increment_num.get() > 0:\n # Empty the plot support\n self.plot_canvas.get_tk_widget().grid_remove()\n # Plot the data\n self.plot_figure = Figure(figsize=(5, 5), dpi=100)\n self.subplot = self.plot_figure.add_subplot(111)\n # Plotting from data\n x_axis = [element for element in range(len(zoomed_data))]\n self.subplot.plot(x_axis, zoomed_data)\n self.plot_canvas = FigureCanvasTkAgg(self.plot_figure,\n self.canvas_support)\n self.subplot.set_title(str(file))\n extension = str(file).split(\".\")\n if extension[-1] == \"neq_delta\":\n self.subplot.set_ylabel(\"ΔNeq\")\n elif extension[-1] == \"pbq_delta\":\n self.subplot.set_ylabel(\"ΔPB\")\n self.subplot.set_xlabel(\"Amino Acids\")\n # Show plot\n self.plot_canvas.draw()\n self.plot_canvas.get_tk_widget().grid()\n\n","sub_path":"visualise_it.py","file_name":"visualise_it.py","file_ext":"py","file_size_in_byte":7696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"414916916","text":"#!/usr/local/bin/python3.7\nimport requests\nimport json\nimport time\n\nnifi_url='http://172.25.40.138:9090/'\npg_name='Ray'\nsearch_api='nifi-api/flow/search-results?q='\npg_api='nifi-api/flow/process-groups/'\npg_api_suffix='/controller-services'\n\ndef pg_search(pg_name):\n\n url = nifi_url+search_api+pg_name\n req_out = requests.get(url)\n json_out = req_out.json()\n print(json_out)\n\n for i in json_out['searchResultsDTO']['processGroupResults']:\n if i['name'] == pg_name:\n return i['id']\n break\n\ndef cs_search(pg_id):\n\n url = nifi_url+pg_api+pg_id+pg_api_suffix\n req_out = requests.get(url)\n json_out = req_out.json()\n print(json_out)\n cs_dic={}\n for i in json_out['controllerServices']:\n if i['component']['name'] == 'DRHiveConnectionPool':\n cs_dic[i['id']]=i['component']['properties']['hive-db-user']\n return cs_dic\n\n\ndef main():\n\n#1. Get the first PG name from input.csv\n\n#2. Search results for the PG\n\n pg_id = pg_search(pg_name)\n\n#3. Find controller services ID for that PG ID where name of Controller service is DRHiveConnectionPool\n\n cs_id = cs_search(pg_id)\n\n#4\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"CS.py","file_name":"CS.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"151818163","text":"'''\r\nCreated on May 26, 2020\r\n\r\n@author: xuwang\r\n'''\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom scipy.signal import butter\r\nfrom scipy.signal import filtfilt\r\nfrom scipy.signal import freqz\r\nfrom scipy.signal import find_peaks\r\nimport matplotlib.pyplot as plt\r\nimport argparse\r\nimport csv\r\n# import statistics as stat\r\n#------------------------------------------------------------------------\r\ndef butter_lowpass(cutoff, fs, order=5):\r\n nyq = 0.5 * fs\r\n normal_cutoff = cutoff / nyq\r\n b, a = butter(order, normal_cutoff, btype='low', analog=False)\r\n return b, a\r\n\r\ndef butter_lowpass_filter(data, cutoff, fs, order=5):\r\n b, a = butter_lowpass(cutoff, fs, order=order)\r\n y = filtfilt(b, a, data, method = \"gust\")\r\n return y\r\n#------------------------------------------------------------------------\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-s\", \"--srcPath\", required=True,\r\n help=\"source folder with canopy rate file\")\r\n#==============\r\n# ap.add_argument(\"-p\", \"--pltFile\", required=True,\r\n# help=\"plot layout file\")\r\n#==============\r\n# ap.add_argument(\"-t\", \"--targetPath\", required=True,\r\n# help=\"output path\")\r\n#==============\r\nargs = ap.parse_args()\r\nsourceFile = args.srcPath+\"\\\\CanopyCoverRate.csv\"\r\n# outputPath = args.targetPath\r\n# Number of ranges 2018AM3 28, 2018IPSR 51, 2017AYN 56\r\nrn = 28\r\n#------------------------------------------------------------------------\r\ndf = pd.read_csv(sourceFile, usecols=[1,2], dtype=float)\r\n# ampCanopy = df['Canopy_Rate_Index'].values.tolist() # -1 to 1\r\ndf['Can_reverse1'] = 1 - df['Canopy_Rate1']\r\nallCanopy = df['Can_reverse1'].values.tolist() # percentage\r\nimgFileNames = df\r\nnormAmp = [float(i)/max(allCanopy) for i in allCanopy]\r\n\r\ndf['Can_reverse2'] = 1 - df['Canopy_Rate2']\r\nallCanopy2 = df['Can_reverse2'].values.tolist() # percentage\r\nimgFileNames = df\r\nnormAmp2 = [float(i)/max(allCanopy2) for i in allCanopy2]\r\n\r\n\r\n#------------------------------------------------------------------------\r\nFs = 30 # Fs, sampling rate, frame rate, Frequency\r\nTs = 1.0/Fs # sampling interval\r\nn = len(allCanopy) # length of the signal(canopy cover)\r\nT = n/Fs # total sampling period\r\nt = np.arange(0, T, Ts) # time vector\r\nif len(t) != n:\r\n t = t[0:len(t)-1]\r\n \r\nn2 = len(allCanopy2) # length of the signal(canopy cover)\r\nT2 = n2/Fs # total sampling period\r\nt2 = np.arange(0, T2, Ts) # time vector\r\nif len(t2) != n2:\r\n t2 = t[0:len(t2)-1]\r\n#------------------------------------------------------------------------\r\n# FFT\r\nk = np.arange(n)\r\nfrq = k/T\r\nfrq = frq[range(int(n/2))]\r\nY = np.fft.fft(allCanopy)/n\r\nY = Y[range(int(n/2))]\r\n\r\n\r\nk2 = np.arange(n2)\r\nfrq2 = k2/T2\r\nfrq2 = frq2[range(int(n2/2))]\r\nY2 = np.fft.fft(allCanopy2)/n2\r\nY2 = Y[range(int(n2/2))]\r\n\r\n\r\n#------------------------------------------------------------------------\r\n# Design Low-pass filter\r\norder = 8\r\nfs = Fs # sample rate, Hz\r\ncutoff = 1.3 # desired cutoff frequency of the filter, Hz, 1.6 1-AM3 2.4-IPSR\r\nb, a = butter_lowpass(cutoff, fs, order)\r\n#------------------------------------------------------------------------\r\n# Filter the signal by applying the low-pass filter\r\ny2 = butter_lowpass_filter(normAmp, cutoff, fs, order)\r\n\r\ny4 = butter_lowpass_filter(normAmp2, cutoff, fs, order)\r\n\r\n# Find local peaks, y2\r\npeaks_y2, _ = find_peaks(y2)\r\n# peaks_y_sd = peaks_y.sort(reverse=True)\r\ny2_peaks_sd = sorted(y2[peaks_y2], reverse=True)\r\nif len(y2_peaks_sd)>=rn:\r\n height_peaks_th = y2_peaks_sd[rn-1]\r\n peaks_y2_rn, _ = find_peaks(y2, height=height_peaks_th)\r\nelse:\r\n peaks_y2_rn, _ = find_peaks(y2)\r\nt2_peaks = peaks_y2_rn/Fs\r\n\r\n\r\npeaks_y4, _ = find_peaks(y4)\r\n# peaks_y_sd = peaks_y.sort(reverse=True)\r\ny4_peaks_sd = sorted(y4[peaks_y4], reverse=True)\r\nif len(y4_peaks_sd)>=rn:\r\n height_peaks_th2 = y4_peaks_sd[rn-1]\r\n peaks_y4_rn, _ = find_peaks(y4, height=height_peaks_th2)\r\nelse:\r\n peaks_y4_rn, _ = find_peaks(y4)\r\nt4_peaks = peaks_y4_rn/Fs\r\n#------------------------------------------------------------------------\r\n#------------------------------------------------------------------------\r\nfig, ax = plt.subplots(4,1)\r\n# Plot original signal\r\nprint(\"Down Bound \", len(peaks_y2_rn))\r\nprint(\"Up Bound \", len(peaks_y4_rn))\r\nprint(len(t))\r\nprint(len(allCanopy))\r\n# ax[0].plot(t,ampCanopy,'r-',linewidth=2)\r\nax[0].plot(t,normAmp,'b',linewidth=1)\r\nax[0].set_xlabel('Time')\r\nax[0].set_ylabel('CCover Indicator')\r\nax[0].set_ylim(-2,2)\r\n#------------------------------------------------------------------------\r\n# Plot frequency domain\r\nax[1].plot(frq,abs(Y),'r')\r\nax[1].set_xlabel('Freq (Hz)')\r\nax[1].set_ylabel('|Y(freq)|')\r\n#------------------------------------------------------------------------\r\n# Plot frequency response of the low-pass filter\r\nw, h = freqz(b, a, worN=2000)\r\nplt.subplot(4, 1, 3)\r\nplt.plot(0.5*fs*w/np.pi, np.abs(h), 'b')\r\nplt.plot(cutoff, 0.5*np.sqrt(2), 'ko')\r\nplt.axvline(cutoff, color='k')\r\nplt.xlim(0, 0.5*fs)\r\nplt.title(\"Lowpass Filter Frequency Response\")\r\nplt.xlabel('Frequency [Hz]')\r\nplt.ylabel('Attenuation')\r\nplt.grid()\r\n#------------------------------------------------------------------------\r\n# Plot filtered signal\r\nplt.subplot(4, 1, 4)\r\n# plt.plot(t, y1, 'r-', linewidth=2, label='Filtered Index')\r\nplt.plot(t, y2, 'b', linewidth=1, label='Filtered Rate')\r\n# plt.plot(t1_peaks, y1[peaks_y1_rn], 'gx')\r\nplt.plot(t2_peaks, y2[peaks_y2_rn], 'kx')\r\nplt.xlabel('Time [sec]')\r\nplt.ylabel('CCover Indicator')\r\nplt.grid()\r\nplt.legend()\r\n#------------------------------------------------------------------------\r\nplt.subplots_adjust(hspace=1)\r\nplt.show()\r\n#========================================================================\r\n# sourceFile = args.srcFile\r\n# outputPath = args.targetPath\r\nst_range=sourceFile.find(\"_C0\")+3\r\nrangeNum = int(sourceFile[st_range:st_range+2])\r\nprint(\"Range Number: %d\" % rangeNum)\r\n# print(\"Peaks: \", peaks_y1_rn)\r\ndf2 = pd.read_csv(sourceFile, usecols=[0], dtype=str)\r\n# print(\"Green dots: \", peaks_y1_rn)\r\nprint(\"Black dots: \", peaks_y2_rn)\r\n# # y1_list = peaks_y1_rn.tolist()\r\n# y2_list = peaks_y2_rn.tolist()\r\n# delta_y2 = []\r\n# for j in range(len(y2_list)-1):\r\n# delta_y2.append(y2_list[j+1]-y2_list[j])\r\n# sd_y2 = sorted(delta_y2, reverse=False)\r\n# print(stat.median(sd_y2))\r\n\r\nimgFileNames = df2['Image_file'].values.tolist() # image file nams\r\nfinalFile = open(args.srcPath+\"\\\\peaks.csv\",'wt')\r\n\r\ntry:\r\n # Create final output file\r\n writer = csv.writer(finalFile, delimiter=',', lineterminator='\\n')\r\n # Header row if needed\r\n # writer.writerow(('Column','Image_file'))\r\n if (rangeNum % 2) == 1:\r\n for i in range(len(peaks_y4_rn)):\r\n col = i+1\r\n imf = imgFileNames[peaks_y4_rn[len(peaks_y4_rn)-1-i]]\r\n imgNum = imf.split(\"_\")[4]\r\n imgNum = int(imgNum.split(\".\")[0])\r\n #---------------------------------------------------\r\n writer.writerow((col, imgNum)) \r\n for i in range(len(peaks_y2_rn)):\r\n col = i+1\r\n imf = imgFileNames[peaks_y2_rn[len(peaks_y2_rn)-1-i]]\r\n imgNum = imf.split(\"_\")[4]\r\n imgNum = int(imgNum.split(\".\")[0])\r\n #---------------------------------------------------\r\n writer.writerow((col, imgNum))\r\n else:\r\n for i in range(len(peaks_y4_rn)):\r\n col = i+1\r\n imf = imgFileNames[peaks_y4_rn[i]]\r\n imgNum = imf.split(\"_\")[4]\r\n imgNum = int(imgNum.split(\".\")[0])\r\n #---------------------------------------------------\r\n writer.writerow((col, imgNum)) \r\n for i in range(len(peaks_y2_rn)):\r\n col = i+1\r\n imf = imgFileNames[peaks_y2_rn[i]]\r\n imgNum = imf.split(\"_\")[4]\r\n imgNum = int(imgNum.split(\".\")[0])\r\n #---------------------------------------------------\r\n writer.writerow((col, imgNum))\r\nfinally:\r\n finalFile.close() \r\n# ","sub_path":"canopyBPFilter4.py","file_name":"canopyBPFilter4.py","file_ext":"py","file_size_in_byte":7927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"502364332","text":"import unittest\nfrom SeleniumBase import init\nfrom LoginPage import LoginPage\nfrom MenuPage import MenuPage\n\nclass SignUpWithExistingUser(unittest.TestCase):\n\n def setUp(self):\n self.driver = init( )\n self.driver = self.driver.start(\"Firefox\")\n self.driver.get( \"https://wearegofl-web-sandbox.herokuapp.com/\" )\n\n def runTest(self):\n MenuPage( self.driver ).accessLoginPage()\n login_page = LoginPage( self.driver )\n login_page.signUp( \"hbarros@gmail.com\" , \"123456\" , \"test\" , \"test\" , \"11/08/1990\" , True)\n assert login_page.existingUserMessageDisplayed( )\n\n def tearDown(self):\n self.driver.close()\n","sub_path":"tests/login/Test_SignUpWithExistingUser.py","file_name":"Test_SignUpWithExistingUser.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"244676178","text":"# Copyright (c) 2016 b<>com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom unittest import mock\n\nimport jsonschema\n\nfrom watcher.applier.actions import base as baction\nfrom watcher.applier.actions import change_nova_service_state\nfrom watcher.common import clients\nfrom watcher.common import nova_helper\nfrom watcher.decision_engine.model import element\nfrom watcher.tests import base\n\n\nclass TestChangeNovaServiceState(base.TestCase):\n\n def setUp(self):\n super(TestChangeNovaServiceState, self).setUp()\n\n self.m_osc_cls = mock.Mock()\n self.m_helper_cls = mock.Mock()\n self.m_helper = mock.Mock(spec=nova_helper.NovaHelper)\n self.m_helper_cls.return_value = self.m_helper\n self.m_osc = mock.Mock(spec=clients.OpenStackClients)\n self.m_osc_cls.return_value = self.m_osc\n\n m_openstack_clients = mock.patch.object(\n clients, \"OpenStackClients\", self.m_osc_cls)\n m_nova_helper = mock.patch.object(\n nova_helper, \"NovaHelper\", self.m_helper_cls)\n\n m_openstack_clients.start()\n m_nova_helper.start()\n\n self.addCleanup(m_openstack_clients.stop)\n self.addCleanup(m_nova_helper.stop)\n\n self.input_parameters = {\n \"resource_name\": \"compute-1\",\n \"state\": element.ServiceState.ENABLED.value,\n }\n self.action = change_nova_service_state.ChangeNovaServiceState(\n mock.Mock())\n self.action.input_parameters = self.input_parameters\n\n def test_parameters_down(self):\n self.action.input_parameters = {\n baction.BaseAction.RESOURCE_ID: \"compute-1\",\n self.action.STATE: element.ServiceState.DISABLED.value}\n self.assertTrue(self.action.validate_parameters())\n\n def test_parameters_up(self):\n self.action.input_parameters = {\n baction.BaseAction.RESOURCE_ID: \"compute-1\",\n self.action.STATE: element.ServiceState.ENABLED.value}\n self.assertTrue(self.action.validate_parameters())\n\n def test_parameters_exception_wrong_state(self):\n self.action.input_parameters = {\n baction.BaseAction.RESOURCE_ID: \"compute-1\",\n self.action.STATE: 'error'}\n self.assertRaises(jsonschema.ValidationError,\n self.action.validate_parameters)\n\n def test_parameters_resource_id_empty(self):\n self.action.input_parameters = {\n self.action.STATE: element.ServiceState.ENABLED.value,\n }\n self.assertRaises(jsonschema.ValidationError,\n self.action.validate_parameters)\n\n def test_parameters_applies_add_extra(self):\n self.action.input_parameters = {\"extra\": \"failed\"}\n self.assertRaises(jsonschema.ValidationError,\n self.action.validate_parameters)\n\n def test_change_service_state_pre_condition(self):\n try:\n self.action.pre_condition()\n except Exception as exc:\n self.fail(exc)\n\n def test_change_service_state_post_condition(self):\n try:\n self.action.post_condition()\n except Exception as exc:\n self.fail(exc)\n\n def test_execute_change_service_state_with_enable_target(self):\n self.action.execute()\n\n self.m_helper_cls.assert_called_once_with(osc=self.m_osc)\n self.m_helper.enable_service_nova_compute.assert_called_once_with(\n \"compute-1\")\n\n def test_execute_change_service_state_with_disable_target(self):\n self.action.input_parameters[\"state\"] = (\n element.ServiceState.DISABLED.value)\n self.action.input_parameters[\"disabled_reason\"] = (\n \"watcher_disabled\")\n self.action.execute()\n\n self.m_helper_cls.assert_called_once_with(osc=self.m_osc)\n self.m_helper.disable_service_nova_compute.assert_called_once_with(\n \"compute-1\", \"watcher_disabled\")\n\n def test_revert_change_service_state_with_enable_target(self):\n self.action.input_parameters[\"disabled_reason\"] = (\n \"watcher_disabled\")\n self.action.revert()\n\n self.m_helper_cls.assert_called_once_with(osc=self.m_osc)\n self.m_helper.disable_service_nova_compute.assert_called_once_with(\n \"compute-1\", \"watcher_disabled\")\n\n def test_revert_change_service_state_with_disable_target(self):\n self.action.input_parameters[\"state\"] = (\n element.ServiceState.DISABLED.value)\n self.action.revert()\n\n self.m_helper_cls.assert_called_once_with(osc=self.m_osc)\n self.m_helper.enable_service_nova_compute.assert_called_once_with(\n \"compute-1\")\n","sub_path":"watcher/tests/applier/actions/test_change_nova_service_state.py","file_name":"test_change_nova_service_state.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"215365084","text":"import os\nimport argparse\nimport logging\nimport numpy as np\nfrom osim.env import ProstheticsEnv\nimport ray\nimport ray.rllib.agents.ddpg as ddpg\nfrom ray.tune.registry import register_env\nfrom evaluator import Evaluator\n\nMAX_STEPS_PER_ITERATION = 300\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(message)s')\nlogger = logging.getLogger(__name__)\n\n\ndef env_creator(env_config):\n from custom_env import CustomEnv\n env = CustomEnv(action_repeat=args.action_repeat)\n return env\n\n\ndef configure(args):\n config = ddpg.DEFAULT_CONFIG.copy()\n\n # DDPG specific - according to arguments\n actor_hiddens = []\n actor_layers = args.actor_hiddens.split('-')\n for actor_layer in actor_layers:\n actor_hiddens.append(int(actor_layer))\n critic_hiddens = []\n critic_layers = args.critic_hiddens.split('-')\n for critic_layer in critic_layers:\n critic_hiddens.append(int(critic_layer))\n \n config[\"actor_hiddens\"] = actor_hiddens\n config[\"actor_hidden_activation\"] = args.actor_activation\n config[\"critic_hiddens\"] = critic_hiddens\n config[\"critic_hidden_activation\"] = args.critic_activation\n \n return config\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"RLlib version AI for Prosthetics Challenge\")\n # model\n parser.add_argument(\"--actor-hiddens\", default=\"400-300\", type=str, help=\"Actor architecture\")\n parser.add_argument(\"--critic-hiddens\", default=\"400-300\", type=str, help=\"Critic architecture\")\n parser.add_argument(\"--actor-activation\", default=\"relu\", type=str, help=\"Actor activation function\")\n parser.add_argument(\"--critic-activation\", default=\"relu\", type=str, help=\"Critic activation function\")\n # hyperparameters\n parser.add_argument(\"--action-repeat\", default=4, type=int, help=\"repeat time for each action\")\n # checkpoint\n parser.add_argument(\"--checkpoint-dir\", default=\"output\", type=str, help=\"checkpoint output directory\")\n parser.add_argument(\"--checkpoint-id\", default=None, type=str, help=\"id of checkpoint file\")\n parser.add_argument(\"--no-render\", default=False, action=\"store_true\", help=\"no visualization for evaluation\")\n \n args = parser.parse_args()\n\n ray.init(num_cpus=1)\n\n register_env(\"ProstheticsEnv\", env_creator)\n config = configure(args)\n\n evaluator = Evaluator(args.action_repeat, render=True if args.no_render is False else False)\n\n agent = ddpg.DDPGAgent(env=\"ProstheticsEnv\", config=config)\n checkpoint_path = os.path.join(args.checkpoint_dir, \"checkpoint-\" + str(args.checkpoint_id))\n agent.restore(checkpoint_path=checkpoint_path)\n\n evaluation_reward, evaluation_steps = evaluator(agent)\n logger.info('score: {}'.format(evaluation_reward))\n logger.info('steps: {}'.format(evaluation_steps))\n\n evaluator.close()\n","sub_path":"validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":2825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"250084142","text":"__author__ = 'user'\n\nimport datetime\nimport json\n\n\n# can be merged\nclass repaymentListView(object):\n def __init__(self,Repaymentid,single_money,request_pay_time,actual_pay_time,repay_times,is_finished,project_name):\n self.Paymentid = Repaymentid\n self.single_money = single_money\n self.request_pay_time = request_pay_time\n self.actual_pay_time = actual_pay_time\n self.pay_times = repay_times\n self.project_name = project_name\n\n def object2dict(self):\n d = {}\n #d['__class__'] = obj.__class__.__name__\n #d['__module__'] = obj.__module__\n d.update(self.__dict__)\n return d\n\n\n\n","sub_path":"zkloan/ListViewModels/RepaymentListView.py","file_name":"RepaymentListView.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"340063367","text":"import logging\nfrom typing import Any, Dict, List\n\nimport numpy as np\nimport pyhf\nimport tabulate\n\n\nlog = logging.getLogger(__name__)\n\n\ndef _header_name(channel_name: str, i_bin: int, unique: bool = True) -> str:\n \"\"\"Constructs the header name for a column in a yield table.\n\n There are two modes: by default the names are unique (to be used as keys). With\n ``unique=False``, the region names are skipped for bins beyond the first bin (for\n less redundant output).\n\n Args:\n channel_name (str): name of the channel (phase space region)\n i_bin (int): index of bin in channel\n unique (bool, optional): whether to return a unique key, defaults to True\n\n Returns:\n str: the header name to be used for the column\n \"\"\"\n if i_bin == 0 or unique:\n header_name = f\"{channel_name}\\nbin {i_bin+1}\"\n else:\n header_name = f\"\\nbin {i_bin+1}\"\n return header_name\n\n\ndef _yields_per_bin(\n model: pyhf.pdf.Model,\n model_yields: List[List[List[float]]],\n total_stdev_model: List[List[float]],\n data: List[List[float]],\n) -> List[Dict[str, Any]]:\n \"\"\"Outputs and returns a yield table with predicted and observed yields per bin.\n\n Args:\n model (pyhf.pdf.Model): the model which the table corresponds to\n model_yields (List[List[List[float]]]): yields per channel, sample, and bin\n total_stdev_model (List[List[float]]): total model standard deviation per\n channel and bin\n data (List[List[float]]): data yield per channel and bin\n\n Returns:\n List[Dict[str, Any]]: yield table for use with the ``tabulate`` package\n \"\"\"\n table = [] # table containing all yields\n headers = {} # headers with nicer formatting for output\n\n # rows for each individual sample\n for i_sam, sample_name in enumerate(model.config.samples):\n sample_dict = {\"sample\": sample_name} # one dict per sample\n for i_chan, channel_name in enumerate(model.config.channels):\n for i_bin in range(model.config.channel_nbins[channel_name]):\n sample_dict.update(\n {\n _header_name(\n channel_name, i_bin\n ): f\"{model_yields[i_chan][i_sam][i_bin]:.2f}\"\n }\n )\n table.append(sample_dict)\n\n # dicts for total model prediction and data\n total_dict = {\"sample\": \"total\"}\n data_dict = {\"sample\": \"data\"}\n for i_chan, channel_name in enumerate(model.config.channels):\n total_model = np.sum(model_yields[i_chan], axis=0) # sum over samples\n for i_bin in range(model.config.channel_nbins[channel_name]):\n header_name = _header_name(channel_name, i_bin)\n headers.update(\n {header_name: _header_name(channel_name, i_bin, unique=False)}\n )\n total_dict.update(\n {\n header_name: f\"{total_model[i_bin]:.2f} \"\n f\"\\u00B1 {total_stdev_model[i_chan][i_bin]:.2f}\"\n }\n )\n data_dict.update({header_name: f\"{data[i_chan][i_bin]:.2f}\"})\n table += [total_dict, data_dict]\n\n log.info(\n \"yields per bin:\\n\"\n + tabulate.tabulate(\n table,\n headers=headers,\n tablefmt=\"fancy_grid\",\n )\n )\n return table\n\n\ndef _yields_per_channel(\n model: pyhf.pdf.Model,\n model_yields: List[List[float]],\n total_stdev_model: List[float],\n data: List[float],\n) -> List[Dict[str, Any]]:\n \"\"\"Outputs and returns a yield table with predicted and observed yields per channel.\n\n Args:\n model (pyhf.pdf.Model): the model which the table corresponds to\n model_yields (List[List[float]]): yields per channel and sample\n total_stdev_model (List[float]): total model standard deviation per channel\n data (List[float]): data yield per channel\n\n Returns:\n List[Dict[str, Any]]: yield table for use with the ``tabulate`` package\n \"\"\"\n table = [] # table containing all yields\n\n # rows for each individual sample\n for i_sam, sample_name in enumerate(model.config.samples):\n sample_dict = {\"sample\": sample_name} # one dict per sample\n for i_chan, channel_name in enumerate(model.config.channels):\n sample_dict.update({channel_name: f\"{model_yields[i_chan][i_sam]:.2f}\"})\n table.append(sample_dict)\n\n # dicts for total model prediction and data\n total_dict = {\"sample\": \"total\"}\n data_dict = {\"sample\": \"data\"}\n for i_chan, channel_name in enumerate(model.config.channels):\n total_model = np.sum(model_yields[i_chan], axis=0) # sum over samples\n total_dict.update(\n {\n channel_name: f\"{total_model:.2f} \"\n f\"\\u00B1 {total_stdev_model[i_chan]:.2f}\"\n }\n )\n data_dict.update({channel_name: f\"{data[i_chan]:.2f}\"})\n table += [total_dict, data_dict]\n\n log.info(\n \"yields per channel:\\n\"\n + tabulate.tabulate(\n table,\n headers=\"keys\",\n tablefmt=\"fancy_grid\",\n )\n )\n return table\n","sub_path":"src/cabinetry/tabulate.py","file_name":"tabulate.py","file_ext":"py","file_size_in_byte":5177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"450848478","text":"'''\nAutor: Marcos Felipe da Silva\nversão: 1.0\n\nDescrição: Faz testes a autenticação de um usuário\n\n'''\n\nimport unittest, json\nfrom requests import Session\nfrom cred import obj\n\nclass TestAlterarAvatar(unittest.TestCase):\n\n def __init__(self, *args, **kargs):\n super(TestAlterarAvatar, self).__init__(*args, **kargs)\n self._host = 'http://localhost:8585'\n self._c = Session()\n self._url = '/'\n \n \n def test_a_usuario_sem_envio_campo_nome(self):\n dados = {'senha': obj['senha']}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_b_usuario_sem_envio_campo_senha(self):\n dados = {'nome': obj['nome']}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_c_usuario_ou_senha_incorretos(self):\n dados = {'nome': 'fulano', 'senha': 'ciclano'}\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('erro', resp.keys())\n \n def test_d_autenticacao_bem_sucedida(self):\n dados = obj\n resp = self._c.post(self._host+self._url, data = dados).json()\n print(resp)\n self.assertIn('sucesso', resp.keys())\n\n\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"__testes__/index/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"483046803","text":"# coding: utf-8\n\n\"\"\"\n App Center Client\n\n Microsoft Visual Studio App Center API # noqa: E501\n\n OpenAPI spec version: preview\n Contact: benedetto.abbenanti@gmail.com\n Project Repository: https://github.com/b3nab/appcenter-sdks\n\"\"\"\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass BuildConcurrencyResponse(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\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 'quantity': 'number',\n 'committed_quantity': 'number'\n }\n\n attribute_map = {\n 'quantity': 'quantity',\n 'committed_quantity': 'committed_quantity'\n }\n\n def __init__(self, quantity=None, committed_quantity=None): # noqa: E501\n \"\"\"BuildConcurrencyResponse - a model defined in Swagger\"\"\" # noqa: E501\n self._quantity = None\n self._committed_quantity = None\n self.discriminator = None\n if quantity is not None:\n self.quantity = quantity\n if committed_quantity is not None:\n self.committed_quantity = committed_quantity\n\n @property\n def quantity(self):\n \"\"\"Gets the quantity of this BuildConcurrencyResponse. # noqa: E501\n\n The number of pipelines set by the billing plan # noqa: E501\n\n :return: The quantity of this BuildConcurrencyResponse. # noqa: E501\n :rtype: number\n \"\"\"\n return self._quantity\n\n @quantity.setter\n def quantity(self, quantity):\n \"\"\"Sets the quantity of this BuildConcurrencyResponse.\n\n The number of pipelines set by the billing plan # noqa: E501\n\n :param quantity: The quantity of this BuildConcurrencyResponse. # noqa: E501\n :type: number\n \"\"\"\n\n self._quantity = quantity\n\n @property\n def committed_quantity(self):\n \"\"\"Gets the committed_quantity of this BuildConcurrencyResponse. # noqa: E501\n\n The number of pipelines committed, which can be equal or greater than the number from the billing plan # noqa: E501\n\n :return: The committed_quantity of this BuildConcurrencyResponse. # noqa: E501\n :rtype: number\n \"\"\"\n return self._committed_quantity\n\n @committed_quantity.setter\n def committed_quantity(self, committed_quantity):\n \"\"\"Sets the committed_quantity of this BuildConcurrencyResponse.\n\n The number of pipelines committed, which can be equal or greater than the number from the billing plan # noqa: E501\n\n :param committed_quantity: The committed_quantity of this BuildConcurrencyResponse. # noqa: E501\n :type: number\n \"\"\"\n\n self._committed_quantity = committed_quantity\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.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 \"\"\"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, BuildConcurrencyResponse):\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":"sdks/python/appcenter_sdk/models/BuildConcurrencyResponse.py","file_name":"BuildConcurrencyResponse.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"120004519","text":"from tkinter import *\r\nfrom Monte_Carlo_Fresnel import *\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom matplotlib.figure import Figure\r\nfrom matplotlib import cm\r\nfrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, \r\nNavigationToolbar2Tk) \r\n\r\npat = []\r\n\r\ndef pl():\r\n fig = Figure(figsize=(5, 5), dpi=100)\r\n #fig, ax = plt.subplots(1,1)\r\n #ax.contourf(pattern(sxsize.get()*10**-6, sysize.get()*10**-6, sz.get(), sl.get()*10**-6))\r\n global pat\r\n pat = pattern(sxsize.get()*10**-6, sysize.get()*10**-6, sz.get(), sl.get()*10**-6)\r\n kstep = (sxsize.get()*10**-6 + sysize.get()*10**-6)/2\r\n k = 35 #Same k as used in random sampling part of Monte_Carlo_Frensel.pattern()\r\n fig.add_subplot(111).contourf(np.linspace(-k*0.5*kstep, k*0.5*kstep, k), np.linspace(-k*0.5*kstep, k*0.5*kstep, k), pat, cmap = cm.plasma)\r\n canvas = FigureCanvasTkAgg(fig, master = master) \r\n canvas.draw() \r\n canvas.get_tk_widget().place(x=800, y=100)\r\n\r\ndef open():\r\n top=Tk()\r\n top.title(\"About the app\")\r\n label=Label(top, text=\"Hello and welcome to diffraction guru!!\\n\\n\\nThis app helps one understand the concept of diffraction through a real time graph \\nwhich plots the pattern of diffraction depending upon the values that the user enters.\\n\\n\\nWe will take various inputs from the user such as the wavelength and the slit distance and suchand then plot the diffraction pattern that would have been obtained on the screen\\n\\nWe hope this app is found to be helpful to students in understanding diffraction better.\\n\\n\\n\\n\\n\\n\\nEnjoy using it!!\", font=('arial', 10, 'italic'))\r\n label.grid(row=0, column=0)\r\n\r\ndef open2():\r\n top = Tk()\r\n top.geometry(\"900x500\")\r\n top.title(\"Intensity on the Axes\")\r\n fig2 = Figure(figsize = (3,3), dpi=100)\r\n fig3 = Figure(figsize = (3,3), dpi=100)\r\n xint = pat[18][0:len(pat[18])]\r\n yint = []\r\n k = 35\r\n kstep = (sxsize.get()*10**-6 + sysize.get()*10**-6)/2\r\n for i in range(k):\r\n yint += [pat[i][18]]\r\n maxy = 0\r\n for j in yint:\r\n if j > maxy:\r\n maxy = j\r\n fig2.add_subplot(111).plot(np.linspace(-k*0.5*kstep, k*0.5*kstep, k), yint)\r\n fig3.add_subplot(111).plot(np.linspace(-k*0.5*kstep, k*0.5*kstep, k), xint)\r\n canvas2 = FigureCanvasTkAgg(fig2, master = top)\r\n canvas2.draw()\r\n canvas2.get_tk_widget().place(x=100, y=100)\r\n canvas3 = FigureCanvasTkAgg(fig3, master = top)\r\n canvas3.draw()\r\n canvas3.get_tk_widget().place(x=500, y=100)\r\n \r\n \r\n \r\n \r\nmaster = Tk()\r\nmaster.title('Diffraction Guru')\r\nmaster.geometry(\"2000x2000\")\r\n\r\nframe=LabelFrame(master, text=\"For Diffraction Pattern\\nClick here\", padx=10, pady=10)\r\nframe.place(x=60, y=400)\r\n\r\nlabel1=Label(master, text=\"Diffraction Guru\", font=('arial',30,'bold','italic'))\r\nlabel1.place(x=500, y=0)\r\n\r\nsxsize = Scale(master, label=\"x length(micro m)\", from_=0, to=3000, orient='horizontal', length = 600)\r\nsxsize.set(3)\r\nsxsize.place(x = 10, y = 100)\r\n\r\nsysize = Scale(master, label=\"y length(micro m)\", from_=0, to=3000, orient='horizontal', length = 600)\r\nsysize.set(3000)\r\nsysize.place(x = 10, y = 160)\r\n\r\nsz = Scale(master, label=\"Screen distance(m)\", from_=0, to=10, orient='horizontal', length = 600)\r\nsz.set(1)\r\nsz.place(x = 10, y = 220)\r\n\r\nsl = Scale(master, label=\"Wavelength\", from_=0, to=3000, orient='horizontal', length = 600)\r\nsl.set(6)\r\nsl.place(x = 10, y = 280)\r\n\r\nb = Button(frame, text = \"PLOT\", command=pl, fg=\"red\", bg=\"yellow\")\r\nb.grid(row=300, column = 100)\r\n\r\nbtn = Button(master, text = \"To know more about this app\\nClick here\", bg=\"lightblue\",command=open)\r\nbtn.place(x=30, y=600)\r\n\r\ninteframe = LabelFrame(master, text = \"For Intensity Graphs along axes\\nClick here\", padx=10, pady=10)\r\ninteframe.place(x = 200, y= 400)\r\n\r\nintebtn = Button(inteframe, text = \"PLOTS\", command = open2 , fg = \"red\", bg = \"yellow\")\r\nintebtn.grid(row = 300, column = 100)\r\n\r\nmaster.mainloop()\r\n","sub_path":"Diffraction Guru/GUI3.py","file_name":"GUI3.py","file_ext":"py","file_size_in_byte":3937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"444140037","text":"import math as m \nfil=open(\"tester.txt\",\"w+\")\nfil2=open(\"A-small-attempt2.in\",\"r\")\ntestCases=int(fil2.readline())\nfor i in range(1,testCases+1):\n gene=0\n flag=0\n fraction=fil2.readline()\n frac=fraction.split(\"/\")\n first=int(frac[0])\n second=int(frac[1])\n for j in range(1,(first+1)/2):\n if((second%j==0)&(first%j==0)):\n second=second/j\n first=first/j\n for j in range(0,41):\n if(second==(2**j)):\n flag=1\n if(first==1):\n gene=int(m.log(second,2))\n else:\n gene=gene+1\n while(first<(second/2)):\n second=second/2\n gene=gene+1\n\n \n \n if(flag==0):\n fil.write('Case #%d: impossible\\n'%(i))\n else:\n fil.write('Case #%d: %d\\n'%(i,gene))\n \n\n","sub_path":"Googlecodejam/GCJ 2014/elves.py","file_name":"elves.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"57438216","text":"\n\nfrom django.db import models, migrations\n\ndef make_mlu(apps, schema_editor):\n # We can't import the Person model directly as it may be a newer\n # version than this migration expects. We use the historical version.\n Visit = apps.get_model(\"study\", \"Visit\")\n VisitClinical = apps.get_model(\"study\", \"VisitClinical\")\n ClinicalImpression = apps.get_model(\"study\", \"ClinicalImpressions\")\n new_mlu,c = ClinicalImpression.objects.get_or_create(clinical_name = 'Clin Estimate of MLU')\n new_mlu.save()\n for v in Visit.objects.all():\n new_vc, c = VisitClinical.objects.get_or_create(visit = v, clinical = new_mlu)\n new_vc.concern = None\n new_vc.save()\n\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('study', '0019_auto_20150224_1806'),\n ]\n operations = [\n migrations.RunPython(make_mlu),\n ]\n","sub_path":"study/migrations/0020_auto_20150224_1815.py","file_name":"0020_auto_20150224_1815.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"396628879","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\nimport csv\nfrom collections import namedtuple, defaultdict\nfrom datetime import datetime\n\nfrom django.core.management.base import BaseCommand\nfrom corehq.apps.locations.models import SQLLocation\n\ndomain = \"enikshay\"\n\nLocationDetail = namedtuple('LocationDetail', 'name nikshay_code nikshay_code_2 mobile loc_type nikshay_tu_id')\nnikshay_locations = {}\nenikshay_locations = {}\nnikshay_codes_in_multiple_locations = defaultdict(set)\n\n\nclass Command(BaseCommand):\n \"\"\"\n Takes a list of nikshay locations with its nikshay code and then finds corresponding\n locations in eNikshay using that Nikshay Code.\n Headers for input file:\n Name, Nikshay Code, Mobile, Type, Nikshay Code 2, Nikshay TU ID\n where Nikshay Code and Nikshay Code 2 are usually similar with padding like\n 123 and 0123 so safe to check for both when searching in eNikshay\n Then generates a report to show\n 1. Duplicates in eNikshay where more than one location has the same nikshay code\n 2. matches along with Nikshay TU ID for locations for comparison\n 3. nikshay codes that were not found in eNikshay\n Generates two reports\n 1. The comparison report for all nikshay codes received\n 2. Location ids in case of duplicates for a nikshay codes\n \"\"\"\n def add_arguments(self, parser):\n parser.add_argument('file_path')\n\n def handle(self, file_path, *args, **options):\n # Iterate the input file and create a dict with each nikshay code as key and the\n # corresponding details as value\n # While iterating in case of duplicates Take the latest value\n with open(file_path, 'rU') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n if row['Nikshay Code'] in nikshay_locations:\n print(\"Found two rows for nikshay code {code}. Taking latest.\"\n .format(code=row['Nikshay Code']))\n nikshay_locations[row['Nikshay Code'].strip()] = LocationDetail(\n name=row['Name'],\n nikshay_code=row['Nikshay Code'].strip(),\n nikshay_code_2=row['Nikshay Code 2'].strip(),\n mobile=row['Mobile'],\n loc_type=row['Type'],\n nikshay_tu_id=row['Nikshay TU ID']\n )\n # also track Nikshay Code 2 if its separate from Nikshay Code\n if row['Nikshay Code'].strip() != row['Nikshay Code 2'].strip():\n nikshay_locations[row['Nikshay Code 2'].strip()] = LocationDetail(\n name=row['Name'],\n nikshay_code=row['Nikshay Code'].strip(),\n nikshay_code_2=row['Nikshay Code 2'].strip(),\n mobile=row['Mobile'],\n loc_type=row['Type'],\n nikshay_tu_id=row['Nikshay TU ID']\n )\n # Iterate over locations ignoring test locations and create a dict with nikshay code\n # as key and location object as value.\n # While iterating keep track of duplicates and store them separately for report later\n for location in SQLLocation.active_objects.filter(domain=domain):\n loc_metadata = location.metadata\n is_test = (loc_metadata.get('is_test', 'yes') == 'yes')\n if not is_test:\n location_nikshay_code = loc_metadata.get('nikshay_code', '').strip()\n if location_nikshay_code:\n if location_nikshay_code in enikshay_locations:\n nikshay_codes_in_multiple_locations[location_nikshay_code].add(\n enikshay_locations[location_nikshay_code].location_id\n )\n nikshay_codes_in_multiple_locations[location_nikshay_code].add(\n location.location_id\n )\n enikshay_locations[location_nikshay_code] = location\n\n result_file = \"locations_codes_match_result_{timestamp}.csv\".format(\n timestamp=datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n )\n headers = ['name', 'nikshay_code', 'nikshay_code_2',\n 'mobile', 'type', 'nikshay_tu_id',\n 'enikshay_name', 'enikshay_nikshay_code', 'enikshay_nikshay_tu_id',\n 'is_test', 'location_id', 'duplicates'\n ]\n\n with open(result_file, 'w') as output_buffer:\n writer = csv.DictWriter(output_buffer, fieldnames=headers)\n writer.writeheader()\n # Iterate over all nikshay codes and find corresponding enikshay location\n # and then add report for the match accordingly\n for nikshay_code, nikshay_location_detail in nikshay_locations.items():\n enikshay_location = enikshay_locations.get(nikshay_location_detail.nikshay_code)\n row = {\n 'name': nikshay_location_detail.name,\n 'nikshay_code': nikshay_location_detail.nikshay_code,\n 'nikshay_code_2': nikshay_location_detail.nikshay_code_2,\n 'mobile': nikshay_location_detail.mobile,\n 'type': nikshay_location_detail.loc_type,\n 'nikshay_tu_id': nikshay_location_detail.nikshay_tu_id,\n 'duplicates': ','.join(\n nikshay_codes_in_multiple_locations.get(\n nikshay_location_detail.nikshay_code, []\n ))\n }\n if enikshay_location:\n loc_metadata = enikshay_location.metadata\n row['enikshay_name'] = enikshay_location.name\n row['enikshay_nikshay_code'] = loc_metadata.get('nikshay_code')\n row['enikshay_nikshay_tu_id'] = loc_metadata.get('nikshay_tu_id')\n row['is_test'] = loc_metadata.get('is_test')\n row['location_id'] = enikshay_location.location_id\n writer.writerow(row)\n\n duplicate_locs_file = \"locations_codes_duplicate_{timestamp}.csv\".format(\n timestamp=datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n )\n\n # add reports for all duplicates found in enikshay for nikshay codes\n # present in the input file\n with open(duplicate_locs_file, 'w') as output_buffer:\n headers = ['nikshay_code', 'location_ids']\n writer = csv.DictWriter(output_buffer, fieldnames=headers)\n writer.writeheader()\n for nikshay_code in nikshay_codes_in_multiple_locations:\n writer.writerow({\n 'nikshay_code': nikshay_code,\n 'location_ids': ','.join(nikshay_codes_in_multiple_locations[nikshay_code])\n })\n","sub_path":"custom/enikshay/management/commands/nikshay_locations_codes_check.py","file_name":"nikshay_locations_codes_check.py","file_ext":"py","file_size_in_byte":6957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"603971079","text":"def part1(input):\n two = 0\n three = 0\n\n for checksum in input:\n has_two = False\n has_three = False\n\n for letter in set(checksum):\n count = checksum.count(letter)\n has_two = has_two or count == 2\n has_three = has_three or count == 3\n\n if has_two:\n two += 1\n if has_three:\n three += 1\n\n return two * three\n\n\ndef part2(input):\n ids = []\n\n while input:\n current = input.pop(0)\n position = 0\n\n for checksum in input:\n differences = 0\n\n for index, letter in list(enumerate(checksum)):\n if letter != current[index]:\n differences += 1\n position = index\n if differences == 2:\n break\n\n if differences == 1:\n return checksum[:position] + checksum[position+1:]\n","sub_path":"2018/day2/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"118294292","text":"#!/usr/bin/env python3\n\nimport time\nimport sys\nimport re\nimport os\nimport os.path as path\n\nimport ian_utils as iu\nimport argument_parser as ap\n\ndef mk_file_hash(function):\n h = hash(function)\n h *= hash(time.time())\n h *= os.getpid()\n return hex(h % (1 << 48))[2:] # Trim 0x\n\n\ndef make_X_0(box_list):\n \"\"\" Makes a box from the given python structure\"\"\"\n box = list()\n for i in range(len(box_list)):\n box.append(box_list[i][0], box_list[i][1])\n return box\n\n\ndef append_to_environ(pathname, addition):\n try:\n os.environ[pathname] = \"{}:{}\".format(addition,\n os.environ[pathname])\n except KeyError:\n os.environ[pathname] = addition\n\n\ndef setup_requirements(base_dir):\n # Add to paths used during runtime for requirements\n path_addition = path.join(base_dir, \"requirements/bin\")\n append_to_environ(\"PATH\", path_addition)\n\n ld_lib_addition = path.join(base_dir, \"requirements/lib\")\n append_to_environ(\"LD_LIBRARY_PATH\", ld_lib_addition)\n\n lib_addition = path.join(base_dir, \"requirements/lib\")\n append_to_environ(\"LIBRARY_PATH\", lib_addition)\n\n c_inc_addition = path.join(base_dir, \"requirements/include\")\n append_to_environ(\"C_INCLUDE_PATH\", c_inc_addition)\n\n cplus_inc_addition = path.join(base_dir, \"requirements/include\")\n append_to_environ(\"CPLUS_INCLUDE_PATH\", cplus_inc_addition)\n\n\n# Directory names used in this script\nfull_dir = path.abspath(path.dirname(sys.argv[0])) # Directory for this file\nbase_dir = path.split(full_dir)[0] # One directory up\nsrc_dir = path.join(base_dir, \"src\")\nbin_dir = path.join(base_dir, \"bin\")\nassert(full_dir == bin_dir)\n\n\ndef main():\n setup_requirements(base_dir)\n\n parsing_start = time.time()\n arg_dict = ap.parse_args()\n\n # Add to paths used during runtime for our rust libs\n append_to_environ(\"PATH\", bin_dir)\n rust_ld_lib_addition = path.join(base_dir, \".compiled\")\n if arg_dict[\"debug\"]:\n rust_ld_lib_addition += \":\" + path.join(base_dir, \"src/func/target/debug/\")\n rust_ld_lib_addition += \":\" + path.join(base_dir, \"target/debug/deps\")\n # Set debug mode in case of a crash\n append_to_environ(\"RUST_BACKTRACE\", \"1\")\n else:\n rust_ld_lib_addition += \":\" + path.join(base_dir, \"src/func/target/release/\")\n rust_ld_lib_addition += \":\" + path.join(base_dir, \"target/release/deps\")\n append_to_environ(\"LD_LIBRARY_PATH\", rust_ld_lib_addition)\n\n\n # Grab input interval variables, use them for the function translation,\n # and write them out to a rust file\n # start_box, dimensions, variables = parse_box2(arg_dict[\"input\"])\n # import function_to_rust\n # tup = function_to_rust.translate(arg_dict[\"function\"], variables)\n # (function, constants, part) = tup\n\n inputs = [tup[1] for tup in arg_dict['inputs']]\n inputs = \"|\".join(inputs)\n\n file_id = mk_file_hash(arg_dict[\"rust_function\"])\n function_filename = path.join(src_dir, \n \"func/src/lib_generated_{}.rs\".format(file_id))\n\n if arg_dict[\"debug\"]:\n executable = path.join(base_dir, 'target/debug/cooperative')\n else:\n executable = path.join(base_dir, 'target/release/cooperative')\n\n # Log output\n executable_args = ['-c', arg_dict[\"constants\"],\n '-f', arg_dict[\"interp_function\"],\n '-i', inputs,\n \"-x\", str(arg_dict[\"input_epsilon\"]),\n \"-y\", str(arg_dict[\"output_epsilon\"]),\n \"-S\", \"generated_\"+file_id, # Function file suffix\n \"-n\", \",\".join(b[0] for b in arg_dict[\"inputs\"]),\n \"-t\", str(arg_dict[\"timeout\"]),\n \"-u\", str(arg_dict[\"update\"]),\n \"-d\" if arg_dict[\"debug\"] else \"\", # If a debug run\n \"-L\" if arg_dict[\"logfile\"] else \"\"] \n \n iu.log(1, iu.cyan(\"Interpreted: \") + arg_dict[\"interp_function\"])\n iu.log(1, iu.cyan(\"Rust: \") + arg_dict[\"rust_function\"])\n iu.log(1, iu.cyan(\"Domain: \") + inputs)\n iu.log(1, iu.cyan(\"Variables: \") + \", \".join(b[0] for b in arg_dict[\"inputs\"]))\n iu.log(1, iu.cyan(\"Command: \") + ' '.join([executable] + executable_args))\n\n parsing_end = time.time()\n\n# Use try so that we can catch control-c easily\n output = None\n logging = bool(arg_dict[\"logfile\"])\n log_file = arg_dict[\"logfile\"] if type(arg_dict[\"logfile\"]) is str else None\n \n try:\n with open(function_filename, 'w') as f:\n f.write(arg_dict[\"rust_function\"])\n\n if log_file:\n with open(log_file, 'w') as f2:\n f2.write(\"\")\n f2.flush()\n \n start = time.time()\n term_time = None\n if arg_dict[\"timeout\"] != 0:\n if arg_dict[\"grace\"] == 0:\n term_time = start + arg_dict[\"timeout\"]*2\n else:\n term_time = start + arg_dict[\"grace\"]\n \n iu.log(1, iu.cyan(\"Running\"))\n for line in iu.run_async(executable, executable_args, term_time):\n if logging and line.startswith(\"lb:\"): # Hacky\n print(line.strip(), file=sys.stderr)\n if log_file:\n with open(log_file, 'a') as f2:\n f2.write(line.strip())\n f2.write('\\n')\n f2.flush()\n else:\n if arg_dict['dreal']:\n match = re.search(\"\\[([^,]+),(.*)\", line)\n if match:\n line = \"[{},{}\".format(-float(match.group(1)), match.group(2))\n print(line.strip())\n except KeyboardInterrupt:\n iu.warning(\"Caught ctrl-C, exiting now\")\n finally:\n if not arg_dict[\"debug\"]:\n os.remove(function_filename)\n try:\n os.remove(path.join(base_dir, \".compiled/libfunc_generated_\"+file_id+\".so\"))\n except:\n pass\n\n try:\n p = path.join(src_dir, \"func/target/release/libfunc_generated_\"+file_id+\".so\")\n os.remove(p)\n except:\n pass\n\n try:\n p = path.join(src_dir, \"func/target/release/func_generated_\"+file_id+\".d\")\n os.remove(p)\n except:\n pass\n end = time.time()\n \n if output:\n print(output)\n\n iu.log(0, iu.green(\"Parsing time: \")+str(parsing_end-parsing_start))\n iu.log(0, iu.green(\"Solver time: \")+str(end-start))\n\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"src/frontend/gelpia.py","file_name":"gelpia.py","file_ext":"py","file_size_in_byte":6620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"538702649","text":"import os\r\nimport psutil\r\nimport threading\r\nimport sys\r\nimport json\r\n\r\nglobal with_usage\r\n\r\n\r\ndef error_print(*args, **kwargs):\r\n print(*args, file=sys.stderr, **kwargs)\r\n\r\n\r\ndef get_usage(process_list, range1, range2):\r\n for proc in process_list[range1:range2]:\r\n try:\r\n with_usage.append({'pid': proc.pid, 'name': proc.name(), 'usage_cpu': proc.cpu_percent(\r\n interval=0.1), 'usage_memory': proc.memory_percent()})\r\n except:\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n with_usage = []\r\n username = os.getlogin()\r\n processlist = []\r\n for pid in psutil.pids():\r\n process = psutil.Process(pid)\r\n current_username = ''\r\n current_status = ''\r\n try:\r\n current_status = process.status()\r\n except:\r\n continue\r\n if current_status != 'running':\r\n continue\r\n processlist.append(process)\r\n proc_num = len(processlist)\r\n threads = []\r\n multi = 10\r\n chunks = int(proc_num / multi) # 한 청크당 긁어모을 개수\r\n rest = proc_num % multi # 마지막 청크\r\n for i in range(0, multi + 1):\r\n start = i * chunks\r\n end = start + chunks\r\n if i == multi:\r\n end = start + rest\r\n error_print(\"프로세스 분석 중...\", start + 1, \"~\", end, \"of\", proc_num)\r\n t = threading.Thread(target=get_usage, args=(\r\n processlist[start: end], 0, 10))\r\n threads.append(t)\r\n t.start()\r\n for thread in threads:\r\n thread.join()\r\n res = {\r\n 'result': sorted(with_usage, key=lambda proc: proc['usage_memory'], reverse=True)\r\n }\r\n print(json.dumps(res))\r\n","sub_path":"src/main/exec/processAnalysisWin/processAnalysisWin.py","file_name":"processAnalysisWin.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"103089310","text":"# Copyright (c) 2016, Vladimir Feinberg\n# Licensed under the BSD 3-clause license (see LICENSE)\n\n# The interp_cubic code below was modified from MSGP demo code provided by\n# Wilson. The demo code itself is based off of extending components\n# in GPML, which is BSD 2-clause licenced. I've replicated the\n# copyrights and/or licences to both code source in this repository's\n# LICENSE file.\n\nimport logging\n\nimport numpy as np\nimport scipy\nimport scipy.sparse\n\nfrom ..util.numpy_convenience import begin_end_indices\n\n_LOG = logging.getLogger(__name__)\n\ndef cubic_kernel(x):\n \"\"\"\n The cubic convolution kernel can be used to compute interpolation\n coefficients. Its definition is taken from:\n\n Cubic Convolution Interpolation for Digital Image Processing by\n Robert G. Keys.\n\n It is supported on values of absolute magnitude less than\n 2 and is defined as:\n\n .. math::\n \\\\newcommand{abs}[1]{\\\\left\\\\vert{#1}\\\\right\\\\vert}\n u(x) = \\\\begin{cases}\n \\\\frac{3}{2}\\\\abs{x}^3-\\\\frac{5}{2}\\\\abs{x}^2+1 & 0\\\\le \\\\abs{x}\\\\le 1\n \\\\\\\\\n \\\\frac{3}{2}\\\\abs{x}^3+\\\\frac{5}{2}-4\\\\abs{x}+2 & 1 < \\\\abs{x} \\\\le 2\n \\\\end{cases}\n\n :param x: input array\n :type x: :class:`numpy.ndarray`\n :returns: :math:`u` vectorized over `x`\n \"\"\"\n y = np.zeros_like(x)\n x = np.fabs(x)\n if np.any(x > 2):\n raise ValueError('only absolute values <= 2 allowed')\n q = x <= 1\n y[q] = ((1.5 * x[q] - 2.5) * x[q]) * x[q] + 1\n q = ~q\n y[q] = ((-0.5 * x[q] + 2.5) * x[q] - 4) * x[q] + 2\n return y\n\ndef interp_cubic(grid, samples):\n \"\"\"\n Given a one dimensional grid `grid` of size `m` (that's sorted) and\n `n` sample points `samples` contained in `grid[1:-1]`, compute the\n interpolation coefficients for a cubic interpolation on the grid.\n\n An interpolation coefficient matrix `M` is then an `n` by `m` matrix\n that has 4 entries per row.\n\n For a (vectorized) twice-differentiable function `f`, `M.dot(f(grid))`\n approaches `f(sample)` at a rate of :math:`O(m^{-3})`.\n\n `samples` should be contained with the range of `grid`, but this method\n will make do will work with what it has (it will clip things back into\n range).\n\n :returns: the interpolation coefficient matrix\n :raises ValueError: if any of the following hold true:\n\n #. `grid` or `samples` are not 1-dimensional\n #. `grid` size less than 4\n #. `grid` is not equispaced\n \"\"\"\n\n grid_size = len(grid)\n n_samples = samples.size\n\n if n_samples == 0:\n return scipy.sparse.csr_matrix((0, grid_size), dtype=float)\n\n if grid.ndim != 1:\n raise ValueError('grid dim {} should be 1'.format(grid.ndim))\n\n if samples.ndim != 1:\n raise ValueError('samples dim {} should be 1'.format(samples.ndim))\n\n if grid_size < 4:\n raise ValueError('grid size {} must be >=4'.format(grid_size))\n\n if samples.min() <= grid[0] or samples.max() >= grid[-1]:\n _LOG.warning('range of samples [%f, %f] outside grid range [%f, %f]',\n samples.min(), samples.max(), grid[0], grid[-1])\n\n delta = grid[1] - grid[0]\n factors = (samples - grid[0]) / delta\n # closest refers to the closest grid point that is smaller\n idx_of_closest = np.floor(factors)\n dist_to_closest = factors - idx_of_closest # in units of delta\n\n csr = scipy.sparse.csr_matrix((n_samples, grid_size), dtype=float)\n for conv_idx in range(-2, 2): # cubic conv window\n coeff_idx = idx_of_closest - conv_idx\n coeff_idx[coeff_idx < 0] = 0 # threshold (no wraparound below)\n coeff_idx[coeff_idx >= grid_size] = grid_size - 1 # none above\n\n relative_dist = dist_to_closest + conv_idx\n data = cubic_kernel(relative_dist)\n col_idx = coeff_idx\n ind_ptr = np.arange(0, n_samples + 1)\n csr += scipy.sparse.csr_matrix((data, col_idx, ind_ptr),\n shape=(n_samples, grid_size))\n return csr\n\n# TODO(test)\n# TODO(cleanup) - refactor to get rid of pylint warning\ndef multi_interpolant(Xs, inducing_grid): # pylint: disable=too-many-locals\n \"\"\"\n Creates a sparse CSR matrix across multiple inputs `Xs`.\n\n Each input is mapped onto the inducing grid with a cubic interpolation,\n with :func:`runlmc.approx.interpolation.interp_cubic`.\n\n This induces :math:`n_i\\\\times m` interpolation matrices :math:`W_i` for\n the :math:`i`-th element of `Xs` onto the shared inducing grid.\n\n :param Xs: list of 1-dimensional numpy vectors, the inputs.\n :param inducing_gird: 1-dimensional vector of grid points\n :return: the rectangular block diagonal matrix of :math:`W_i`.\n \"\"\"\n multiout_grid_sizes = np.arange(len(Xs)) * len(inducing_grid)\n Ws = [interp_cubic(inducing_grid, X) for X in Xs]\n\n row_lens = [len(X) for X in Xs]\n row_begins, row_ends = begin_end_indices(row_lens)\n order = row_ends[-1]\n\n col_lens = [W.nnz for W in Ws]\n col_begins, col_ends = begin_end_indices(col_lens)\n width = col_ends[-1]\n\n ind_starts = np.roll(np.add.accumulate([W.indptr[-1] for W in Ws]), 1)\n ind_starts[0] = 0\n ind_ptr = np.append(np.repeat(ind_starts, row_lens), width)\n data = np.empty(width)\n col_indices = np.repeat(multiout_grid_sizes, col_lens)\n for rbegin, rend, cbegin, cend, W in zip(\n row_begins, row_ends, col_begins, col_ends, Ws):\n ind_ptr[rbegin:rend] += W.indptr[:-1]\n data[cbegin:cend] = W.data\n col_indices[cbegin:cend] += W.indices\n\n ncols = len(Xs) * len(inducing_grid)\n return scipy.sparse.csr_matrix(\n (data, col_indices, ind_ptr), shape=(order, ncols))\n","sub_path":"runlmc/approx/interpolation.py","file_name":"interpolation.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"489824696","text":"# SIVANAGA SURYA VAMSI POPURI\r\n# ASU ID: 1217319207\r\nimport numpy as np # needed for arrays and math\r\nimport pandas as pd # needed to read the data\r\nimport matplotlib.pyplot as plt # used for plotting\r\nfrom matplotlib import cm as cm # for the color map\r\nimport seaborn as sns # data visualization\r\n\r\n################################################################################\r\n# function to create covariance for dataframes #\r\n# Inputs: #\r\n# mydataframe - the data frame to analyze #\r\n# numtoreport - the number of highly correlated pairs to report #\r\n# Outputs: #\r\n# correlations are printed to the screen #\r\n################################################################################\r\n\r\ndef mosthighlycorrelated(mydataframe, numtoreport): \r\n cormatrix = mydataframe.corr() # find the correlations \r\n\r\n cormatrix *= np.tri(*cormatrix.values.shape, k=-1).T \r\n\r\n # find the top n correlations \r\n #print(cormatrix)\r\n cormatrix = cormatrix.stack() # rearrange so the reindex will work...\r\n #print(cormatrix)\r\n\r\n # Reorder the entries so they go from largest at top to smallest at bottom\r\n # based on absolute value\r\n cormatrix = cormatrix.reindex(cormatrix.abs().sort_values(ascending=False).index).reset_index() \r\n #print(cormatrix)\r\n\r\n # assign human-friendly names \r\n cormatrix.columns = [\"FirstVariable\", \"SecondVariable\", \"Correlation\"] \r\n print(\"\\nMost Highly Correlated\")\r\n print(cormatrix.head(numtoreport)) # print the top values\r\n\r\n################################################################################\r\n# Function to create the Correlation matrix #\r\n# Input: #\r\n# X - a dataframe #\r\n# Output: #\r\n# The correlation matrix plot #\r\n################################################################################\r\n\r\ndef correl_matrix(X):\r\n # create a figure that's 7x7 (inches?) with 100 dots per inch\r\n fig = plt.figure(figsize=(7,7), dpi=100)\r\n\r\n # add a subplot that has 1 row, 1 column, and is the first subplot\r\n ax1 = fig.add_subplot(111)\r\n\r\n # get the 'jet' color map\r\n cmap = cm.get_cmap('jet',30)\r\n\r\n # Perform the correlation and take the absolute value of it. Then map\r\n # the values to the color map using the \"nearest\" value\r\n cax = ax1.imshow(np.abs(X.corr()),interpolation='nearest',cmap=cmap)\r\n\r\n # now set up the axes\r\n major_ticks = np.arange(0,len(X.columns),1)\r\n ax1.set_xticks(major_ticks)\r\n ax1.set_yticks(major_ticks)\r\n ax1.grid(True,which='both',axis='both')\r\n plt.title('Correlation Matrix')\r\n ax1.set_xticklabels(X.columns,fontsize=9)\r\n ax1.set_yticklabels(X.columns,fontsize=12)\r\n\r\n # add the legend and show the plot\r\n fig.colorbar(cax, ticks=[-0.4,-0.25,-.1,0,0.1,.25,.5,.75,1])\r\n plt.show()\r\n\r\n################################################################################\r\n# Function to create the pair plots #\r\n# Input: #\r\n# df - a dataframe #\r\n# Output: #\r\n# The pair plots #\r\n################################################################################\r\n\r\ndef pairplotting(df):\r\n sns.set(style='whitegrid', context='notebook') # set the apearance\r\n a = sns.pairplot(df,height=2.5) # create the pair plots\r\n a.savefig(\"pair_plot.jpg\")\r\n plt.show() # and show them\r\n\r\n# this creates a dataframe similar to a dictionary\r\n# a data frame can be constructed from a dictionary\r\n# https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html\r\n#iris = pd.read_csv('data_banknote_authentication.txt')\r\ndata_set = [line.rstrip('\\n').split(',') for line in open('data_banknote_authentication.txt')] # Read text file. \r\ndf = pd.DataFrame(data = data_set)\r\ndf = df.astype(float)\r\ndf = df.rename(columns={0: \"variance\", 1: \"skewness\",2:\"kurtosis\",3:\"entropy\",4:'class'}) # rename, for better understanding\r\ndf['class'] = df['class'].astype(int)\r\nprint('first 5 observations\\n',iris.head(5))\r\ncols = df.columns\r\n\r\n# descriptive statistics\r\nprint('\\nDescriptive Statistics')\r\nprint(df.describe())\r\n\r\nmosthighlycorrelated(df,5) # generate most highly correlated list\r\ncorrel_matrix(df) # generate the covariance heat plot\r\npairplotting(df) # generate the pair plot\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Python_Project_ML_Currency/ML_datanalysis2.py","file_name":"ML_datanalysis2.py","file_ext":"py","file_size_in_byte":5235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"605759776","text":"from flask import Flask, render_template, request, redirect, url_for, flash, \\\r\n Response, session, Blueprint\r\nfrom flask_bootstrap import Bootstrap\r\nfrom filters import datetimeformat, file_type\r\nfrom resources import get_bucket, get_buckets_list\r\nfrom flask_login import login_required, current_user\r\n# from . import db\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom flask_login import LoginManager\r\n\r\napp = Flask(__name__)\r\nBootstrap(app)\r\napp.secret_key = 'MDlp+ObL6Bg0SArdX3vWIQGB163k4vKOKP/8OOnk'\r\napp.jinja_env.filters['datetimeformat'] = datetimeformat\r\napp.jinja_env.filters['file_type'] = file_type\r\n\r\ndb = SQLAlchemy()\r\n\r\n@app.route('/')\r\ndef index():\r\n return render_template('index.html')\r\n\r\n\r\n@app.route('/profile')\r\n@login_required\r\ndef profile():\r\n \r\n return render_template(\"profile.html\", name=current_user.name)\r\n\r\n@app.route('/bucket', methods=['GET', 'POST'])\r\n@login_required\r\ndef bucket():\r\n if request.method == 'POST':\r\n bucket = request.form['bucket']\r\n session['bucket'] = bucket\r\n return redirect(url_for('files'))\r\n else:\r\n buckets = get_buckets_list()\r\n return render_template(\"bucket.html\", buckets=buckets)\r\n\r\n\r\n@app.route('/files')\r\n@login_required\r\ndef files():\r\n my_bucket = get_bucket()\r\n summaries = my_bucket.objects.all()\r\n\r\n return render_template('files.html', my_bucket=my_bucket, files=summaries)\r\n\r\n\r\n@app.route('/upload', methods=['POST'])\r\n@login_required\r\ndef upload():\r\n file = request.files['file']\r\n\r\n my_bucket = get_bucket()\r\n my_bucket.Object(file.filename).put(Body=file)\r\n\r\n flash('File uploaded successfully')\r\n return redirect(url_for('files'))\r\n\r\n\r\n@app.route('/delete', methods=['POST'])\r\n@login_required\r\ndef delete():\r\n key = request.form['key']\r\n\r\n my_bucket = get_bucket()\r\n my_bucket.Object(key).delete()\r\n\r\n flash('File deleted successfully')\r\n return redirect(url_for('files'))\r\n\r\n\r\n@app.route('/download', methods=['POST'])\r\n@login_required\r\ndef download():\r\n key = request.form['key']\r\n\r\n my_bucket = get_bucket()\r\n file_obj = my_bucket.Object(key).get()\r\n\r\n return Response(\r\n file_obj['Body'].read(),\r\n mimetype='text/plain',\r\n headers={\"Content-Disposition\": \"attachment;filename={}\".format(key)}\r\n )\r\n\r\ndef create_app():\r\n\r\n app.config['SECRET_KEY'] = 'secret-key-goes-here'\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'\r\n\r\n db.init_app(app)\r\n\r\n from auth import auth as auth_blueprint\r\n app.register_blueprint(auth_blueprint)\r\n\r\n app_blueprint = Blueprint('app', __name__)\r\n app.register_blueprint(app_blueprint)\r\n return app\r\n\r\ndef run_app():\r\n app.config['SECRET_KEY'] = 'secret-key-goes-here'\r\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'\r\n\r\n db.init_app(app)\r\n\r\n from auth import auth as auth_blueprint\r\n app.register_blueprint(auth_blueprint)\r\n\r\n login_manager = LoginManager()\r\n login_manager.login_view = 'auth.login'\r\n login_manager.init_app(app)\r\n\r\n @login_manager.user_loader\r\n def load_user(user_id):\r\n from models import User\r\n return User.query.get(int(user_id))\r\n app.run(debug=True)\r\n\r\nif __name__ == \"__main__\":\r\n run_app()\r\n","sub_path":"Version 1/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"138259741","text":"\"\"\"\nGiven a string S that only contains \"I\" (increase) or \"D\" (decrease), let N = S.length.\n\nReturn any permutation A of [0, 1, ..., N] such that for all i = 0, ..., N-1:\n\nIf S[i] == \"I\", then A[i] < A[i+1]\nIf S[i] == \"D\", then A[i] > A[i+1]\n\nExample 1:\nInput: \"IDID\"\nOutput: [0,4,1,3,2]\n\nExample 2:\nInput: \"III\"\nOutput: [0,1,2,3]\n\nExample 3:\nInput: \"DDI\"\nOutput: [3,2,0,1]\n \n\nNote:\n1 <= S.length <= 10000\nS only contains characters \"I\" or \"D\".\n\"\"\"\nfrom typing import List\n\nclass Solution:\n def diStringMatch(self, S: str) -> List[int]:\n left = 0\n right = len(S)\n result = [None] * (right + 1)\n for idx, el in enumerate(S):\n if el == \"I\":\n result[idx] = left\n left += 1\n else:\n result[idx] = right\n right -= 1\n result[-1] = left\n return result\n\n\nif __name__ == \"__main__\":\n assert Solution().diStringMatch(\"IDID\") == [0,4,1,3,2]\n assert Solution().diStringMatch(\"III\") == [0,1,2,3]\n assert Solution().diStringMatch(\"DDI\") == [3,2,0,1]\n","sub_path":"Python/easy/0942_di_string_match.py","file_name":"0942_di_string_match.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"82639511","text":"#!/usr/bin/env python\n\nimport numpy as np\n\ntrainDataFile = ['./../feature/attribute/badges.attribute.SGD100train1.arff',\n './../feature/attribute/badges.attribute.SGD100train2.arff',\n './../feature/attribute/badges.attribute.SGD100train3.arff', \n './../feature/attribute/badges.attribute.SGD100train4.arff', \n './../feature/attribute/badges.attribute.SGD100train5.arff']\n \ntestDataFile = ['./../feature/attribute/badges.attribute.SGD100test1.arff', \n './../feature/attribute/badges.attribute.SGD100test2.arff',\n './../feature/attribute/badges.attribute.SGD100test3.arff',\n './../feature/attribute/badges.attribute.SGD100test4.arff',\n './../feature/attribute/badges.attribute.SGD100test5.arff']\n\ndef readArff(filePath, N):\n # read the data from the arff file\n # store the feature in feature \n # and store result in result in 1 or 0\n \n with open(filePath, 'r') as f:\n a = f.readlines()\n \n trainData = a[N:]\n\n instanceNumber = len(trainData)\n length = len(trainData[0].split(',')) - 1\n\n feature = np.zeros((instanceNumber, length))\n result = str()\n for i in range(instanceNumber):\n temp = trainData[i].split(',')\n feature[i, :] = np.array(temp[:-1])\n result = result + temp[-1][0] + ',' \n\n result = result.split(',')[:-1]\n for i in range(len(result)):\n if result[i] == '+':\n result[i] = 1.0\n else:\n result[i] = -1.0\n \n return feature, result\n\ndef simpleSGD(trainPath, testPath, N):\n # SGD algorithm\n\n alpha = 0.005\n threshold = 0.001\n \n featureTrain, resultTrain = readArff(trainPath, N)\n \n trainLength = len(featureTrain[1, :])\n instanceNumber = len(resultTrain)\n \n # give w a initial number\n #w = np.random.rand(trainLength)\n w = np.ones(trainLength)/2\n \n count = 0\n while True:\n j = np.random.randint(0, instanceNumber)\n deltaW = alpha*(resultTrain[j] - np.dot(w, featureTrain[j, :]))*featureTrain[j, :];\n w = w + deltaW \n tempResult = np.dot(w, featureTrain[j, :])\n error = abs(tempResult - resultTrain[j])\n if error < threshold:\n count = count + 1\n if count > 70:\n break \n \n ## read the test data \n featureTest, resultTest = readArff(testPath, N)\n testTempResult = np.dot(w, featureTest.T)\n a = testTempResult\n testLength = len(testTempResult)\n for i in range(testLength):\n if testTempResult[i] > 0.0:\n testTempResult[i] = 1.0\n else:\n testTempResult[i] = -1.0\n \n rightNumber = 0\n for i in range(testLength):\n if testTempResult[i] == resultTest[i]:\n rightNumber = rightNumber + 1\n \n # calculate the result \n accurateRate = rightNumber/testLength\n \n return rightNumber, accurateRate, testLength\n\nresultPath = './../result/stump100SGD_result.txt'\nwith open(resultPath, 'w') as f:\n for i in range(5):\n trainPath = trainDataFile[i]\n testPath = testDataFile[i]\n rightNumber, accurateRate, totalNumber = simpleSGD(trainPath, testPath, 105)\n \n f.write('Cross Validation')\n f.write('Correctly classified Instances' + '\\t' + str(rightNumber) + '\\t' + str(accurateRate) + '\\n')\n f.write('Total Number of Instances' + '\\t' + str(totalNumber) + '\\n')\n\n","sub_path":"UIUC_CS446/hw2/dt-problem/Code/src/stump100SGD.py","file_name":"stump100SGD.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"345438457","text":"from flask import Flask, flash, redirect, url_for, render_template\nfrom flask_mail import Mail, Message\nfrom forms import SubscribeForm\nimport os\napp = Flask(__name__)\n\n\napp.config.update(\n MAIL_SERVER=os.getenv('MAIL_SERVER'),\n MAIL_USE_SSL=True,\n MAIL_PORT=465,\n MAIL_USERNAME=os.getenv('MAIL_USERNAME'),\n MAIL_PASSWORD=os.getenv('MAIL_PASSWORD'),\n MAIL_DEFAULT_SENDER=('Grey Li', os.getenv('MAIL_USERNAME')),\n SECRET_KEY=os.getenv('SECRET_KEY')\n)\n\nmail = Mail(app)\n\n\ndef send_mail(subject, to, **kw):\n message = Message(subject=subject, recipients=[to])\n message.body = render_template('subscribe.txt', **kw)\n message.html = render_template('subscribe.html', **kw)\n mail.send(message)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/about')\ndef about():\n return redirect(url_for('index'))\n\n\n@app.route('/subscribe', methods=['GET', 'POST'])\ndef subscribe():\n form = SubscribeForm()\n if form.validate_on_submit():\n to = form.to.data\n subject = form.subject.data\n body = form.body.data\n send_mail(subject, to, name=body)\n flash(\"Subscribe success!\")\n return redirect(url_for('index'))\n return render_template('subscribe_form.html', form=form)\n\n\n@app.route('/unsubscribe')\ndef unsubscribe():\n return redirect(url_for('index'))","sub_path":"demos/mail/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"365999633","text":"from build_model import EncoderDecoder\nfrom torchvision import transforms\nfrom torch import optim\nimport torch\nfrom PIL import Image\nimport streamlit as st\n\n\nLOAD_MODEL_PATH = 'image_captioning_model.pth.tar'\nMAX_LEN = 50\nst.set_option('deprecation.showfileUploaderEncoding', False)\n\n\ndef load_model(path):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n checkpoint = torch.load(path, map_location=device)\n\n model = EncoderDecoder(\n embedding_size=256,\n train_all=False,\n num_lstms=2,\n hidden_size=256,\n vocab_size=9859,\n index_to_string=checkpoint['index_to_string']\n ).to(device)\n\n lr = 2e-4\n optimizer = optim.Adam(model.parameters(), lr)\n\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n model.eval()\n return model, device\n\n\ndef predict(image, device, model, max_len):\n transform = transforms.Compose(\n [\n transforms.Resize((224, 224)),\n transforms.ToTensor()\n ]\n )\n image = transform(image.convert(\"RGB\")).unsqueeze(0).to(device)\n prediction = model.predict(image, max_len)\n return prediction\n\n\ndef main():\n model, device = load_model(LOAD_MODEL_PATH)\n st.write(\"\"\"\n # Image Captioning - Describe the Image\n \"\"\"\n )\n st.write(\"This app will describe your picture after uploading it\")\n file = st.file_uploader(\"Please upload an image file\", type=[\"jpg\", \"png\"])\n if file is None:\n st.text(\"Please upload an image file\")\n else:\n image = Image.open(file)\n st.image(image, use_column_width=True)\n prediction = predict(image, device, model, MAX_LEN)\n st.write(prediction)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"API.py","file_name":"API.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"106574999","text":"\"\"\" Module that drives the program\"\"\"\nfrom pizza import ConcretePizza, ParmigianoReggianoDecorator, FreshMozzarellaDecorator, VeganCheeseDecorator, PeppersDecorator, PineappleDecorator, MushroomsDecorator, FreshBasilDecorator, SpinachDecorator, PepperoniDecorator, BeyondMeatDecorator\n\n\nclass Controller:\n \"\"\"\n Class that deals with the Pizza relevant classes\n \"\"\"\n\n def __init__(self):\n \"\"\" Initializes the Controller class\"\"\"\n self.pizza = ConcretePizza()\n\n def run(self):\n \"\"\"\n Runs the program\n \"\"\"\n option_input = Controller.display_options()\n self.prompt(option_input)\n\n def prompt(self, user_input):\n try:\n if user_input == 1:\n cheese_or_topping_input = input(\n f\"Would you like to add cheese or topping?\\n\").strip().lower()\n try:\n if cheese_or_topping_input == \"cheese\":\n cheese_input = int(input(f\"Which Cheese do you want to add?\\n\"\n \"1. Parmigiano Reggiano: $4.99\\n\"\n \"2. Fresh Mozarella: $3.99\\n\"\n \"3. Vegan Cheese: $5.99\\n\"\n ))\n self.add_cheese(cheese_input)\n elif cheese_or_topping_input == \"topping\":\n topping_input = int(input(f\"Which Topping do you want to add\\n\"\n \"1. Peppers: $1.5\\n\"\n \"2. Pineapple: $2\\n\"\n \"3. Mushrooms: $1.5\\n\"\n \"4. Fresh Basil: $2\\n\"\n \"5. Spinach: $1\\n\"\n \"6. Pepperoni: $3\\n\"\n \"7. Beyond Meat: $4\\n\"\n ))\n self.add_topping(topping_input)\n else:\n raise TypeError\n except TypeError:\n print(\"Not a valid option!\")\n option_input = Controller.display_options()\n self.prompt(option_input)\n return True\n elif user_input == 2:\n print(self.pay())\n else:\n raise ValueError\n except ValueError:\n print(\"Number must be either 1 or 2!\")\n\n @staticmethod\n def display_options():\n \"\"\"\n Displays the available options for the user to choose\n :return: an int\n \"\"\"\n return int(input(\"What would you like to do?\\n\"\n f\"1. Add Ingredients\\n\"\n f\"2. Pay\\n\"\n ))\n\n def add_cheese(self, cheese_input):\n \"\"\"\n Provided option that allows adding toppings to the pizza\n \"\"\"\n try:\n if cheese_input == 1:\n self.pizza = ParmigianoReggianoDecorator(self.pizza)\n elif cheese_input == 2:\n self.pizza = FreshMozzarellaDecorator(self.pizza)\n elif cheese_input == 3:\n self.pizza = VeganCheeseDecorator(self.pizza)\n else:\n raise TypeError\n except TypeError:\n print(\"Doesn't seem like a valid number! Try Again!\")\n\n def add_topping(self, topping_input):\n try:\n if topping_input == 1:\n self.pizza = PeppersDecorator(self.pizza)\n elif topping_input == 2:\n self.pizza = PineappleDecorator(self.pizza)\n elif topping_input == 3:\n self.pizza = MushroomsDecorator(self.pizza)\n elif topping_input == 4:\n self.pizza = FreshBasilDecorator(self.pizza)\n elif topping_input == 5:\n self.pizza = SpinachDecorator(self.pizza)\n elif topping_input == 6:\n self.pizza = PepperoniDecorator(self.pizza)\n elif topping_input == 7:\n self.pizza = BeyondMeatDecorator(self.pizza)\n else:\n raise TypeError\n except TypeError:\n print(\"Doesn't seem like a valid number! Try Again!\")\n\n def pay(self):\n \"\"\"\n Provided option to the user to finish the transaction by paying the total cost\n \"\"\"\n try:\n if self.pizza.get_cost() == 4.99:\n raise AddIngredientError(\"OOPS! Add at least one ingredient!\")\n else:\n return f\"{self.pizza.get_ingredient()} \\nTotal Cost: ${self.pizza.get_cost()} \\n\"\n except AddIngredientError as e:\n print(e)\n\n\nclass AddIngredientError(Exception):\n def __init__(self, phrase):\n super().__init__(phrase)\n\n\nif __name__ == '__main__':\n controller = Controller()\n controller.run()\n","sub_path":"Assignments/assignment3/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"431558674","text":"import os\nimport xml.etree.ElementTree as ET\nimport codecs\nimport imp\nimport platform\nimport subprocess\nimport re\n\nimport time\nimport multiprocessing\n\ndef heideltime(text, language, document_type='news', document_creation_time='', date_granularity=''):\n full_path = ''\n if platform.system() == 'Linux' or platform.system() == 'Darwin':\n path = imp.find_module('py_heideltime')[1]\n full_path = path + \"/Heideltime/TreeTaggerLinux\"\n else:\n path = imp.find_module('py_heideltime')[1]\n pp = path.replace('\\\\', '''\\\\\\\\''')\n full_path = str(pp) + '''\\\\\\Heideltime\\\\\\TreeTaggerWindows'''\n conf = '''\n################################\n## MAIN ##\n################################\n# Consideration of different timex3-types\n# Date\nconsiderDate = true\n# Duration\nconsiderDuration = true\n# Set\nconsiderSet = true\n# Time\nconsiderTime = true\n# Temponyms (make sure you know what you do if you set this to \"true\")\nconsiderTemponym = false\n###################################\n# Path to TreeTaggerLinux home directory\n###################################\n# Ensure there is no white space in path (try to escape white spaces)\ntreeTaggerHome = '''+full_path+'''\n# This one is only necessary if you want to process chinese documents.\nchineseTokenizerPath = SET ME IN CONFIG.PROPS! (e.g., /home/jannik/treetagger/chinese-tokenizer)\n##################################\n# paths to JVnTextPro model paths:\n##################################\nsent_model_path = SET ME IN CONFIG.PROPS! (e.g., /home/jannik/jvntextpro/models/jvnsensegmenter)\nword_model_path = SET ME IN CONFIG.PROPS! (e.g., /home/jannik/jvntextpro/models/jvnsegmenter)\npos_model_path = SET ME IN CONFIG.PROPS! (e.g., /home/jannik/jvntextpro/models/jvnpostag/maxent)\n#####################################################\n# paths to Stanford POS Tagger model or config files:\n#####################################################\nmodel_path = SET ME IN CONFIG.PROPS! (e.g., /home/jannik/stanford-postagger-full-2014-01-04/models/arabic.tagger)\n# leave this unset if you do not need one (e.g., /home/jannik/stanford-postagger-full-2014-01-04/tagger.config)\nconfig_path =\n########################################\n## paths to hunpos and its tagger files:\n########################################\nhunpos_path = SET ME IN CONFIG.PROPS! (e.g., /home/jannik/hunpos)\nhunpos_model_name = SET ME IN CONFIG.PROPS! (e.g., model.hunpos.mte5.defnpout)\n# DO NOT CHANGE THE FOLLOWING\n################################\n# Relative path of type system in HeidelTime home directory\ntypeSystemHome = desc/type/HeidelTime_TypeSystem.xml\n# Relative path of dkpro type system in HeidelTime home directory\ntypeSystemHome_DKPro = desc/type/DKPro_TypeSystem.xml\n# Name of uima-context variables...\n# ...for date-consideration\nuimaVarDate = Date\n# ...for duration-consideration\nuimaVarDuration = Duration\n# ...for language\nuimaVarLanguage = Language\n# ...for set-consideration\nuimaVarSet = Set\n# ...for time-consideration\nuimaVarTime = Time\n# ...for temponym-consideration\nuimaVarTemponym = Temponym\n# ...for type to process\nuimaVarTypeToProcess = Type\n'''\n\n f = codecs.open(\"config.props\", \"w+\", \"utf-8\")\n f.truncate()\n f.write(conf)\n f.close()\n num_files = create_txt_files(text)\n list_dates = exec_java_heideltime(num_files, path, full_path, language, document_type, document_creation_time, date_granularity)\n remove_files(num_files)\n return list_dates\n\n\ndef create_txt_files(text):\n tests = text.split(\". \")\n n = max(1, 100)\n merge_sentenses = [tests[i:i + n] for i in range(0, len(tests), n)]\n num_files = 0\n for i in range(len(merge_sentenses)):\n te = \" \".join(merge_sentenses[i])\n text_file = codecs.open('text'+str(i)+'.txt', \"w+\", \"utf-8\")\n text_file.truncate()\n text_file.write(te)\n text_file.close()\n num_files = i\n return num_files\n\n\ndef exec_java_heideltime(file_number, path, full_path,language, document_type, document_creation_time, date_granularity):\n list_dates=[]\n match = re.findall('\\d{4}[-]\\d{2}[-]\\d{2}', document_creation_time)\n\n if match == [] and document_creation_time != '':\n print('Bad document_creation_time format you must specify da date in YYYY-MM-DD format.')\n else:\n n=0\n while n <= file_number:\n if document_creation_time == '':\n java_command = 'java -jar ' + path + '/Heideltime/de.unihd.dbs.heideltime.standalone.jar ' + document_type + ' -l ' + language + ' text'+str(n)+'.txt'\n else:\n java_command = 'java -jar ' + path + '/Heideltime/de.unihd.dbs.heideltime.standalone.jar -dct ' +\\\n document_creation_time + ' -t ' + document_type + ' -l ' + language + ' text'+str(n)+'.txt'\n # run java heideltime standalone version to get all dates\n if platform.system() == 'Windows':\n myCmd = subprocess.check_output(java_command)\n else:\n myCmd = os.popen(java_command).read()\n\n # parsing the xml to get only the date value and the expression that originate the date\n\n from lxml import etree\n parser = etree.XMLParser(recover=True)\n root = etree.fromstring(myCmd, parser=parser)\n for i in range(len(root)):\n # insert in list the date value and the expression that originate the date\n if date_granularity != '':\n if re.match('\\w{4}[-]\\w{2}[-]\\w{2}', root[i].attrib['value']):\n if date_granularity.lower() == 'year':\n years = re.findall('\\w{4}', root[i].attrib['value'])\n list_dates.append((years[0], root[i].text))\n elif date_granularity.lower() == 'month':\n months = re.findall('\\w{4}[-]\\w{2}', root[i].attrib['value'])\n list_dates.append((months[0], root[i].text))\n elif date_granularity.lower() == 'day':\n days = re.findall('\\w{4}[-]\\w{2}[-]\\w{2}', root[i].attrib['value'])\n list_dates.append((days[0], root[i].text))\n else:\n list_dates.append((root[i].attrib['value'], root[i].text))\n n += 1\n # write error message for linux users to advertise that should give execute java heideltime\n if list_dates == [] and platform.system() == 'Linux':\n print('Sorry, maybe something went wrong.')\n print('Please check if the format of values of variables are like the documentation or')\n print('run this command to give execution privileges to execute java heideltime')\n print('sudo chmod 111 ' + full_path + '/bin/*')\n\n return list_dates\n\n\ndef remove_files(num_files):\n import os\n os.remove('config.props')\n i_files = 0\n while i_files <= num_files:\n os.remove('text'+str(i_files)+'.txt')\n i_files += 1\n","sub_path":"py_heideltime/py_heideltime.py","file_name":"py_heideltime.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"566692111","text":"import numpy as np\n\ndef initialize(num_pts,dt,dims,R=np.ones((2,2))):\n X = np.zeros((num_pts, 2*dims, 2))\n P = np.tile(np.eye(2*dims), (num_pts, 1, 1))\n A = np.tile(np.eye(2*dims) + dt * np.eye(2*dims, k=dims), (num_pts, 1, 1))\n Q = np.eye(2*dims)\n H = np.zeros((dims, 2*dims))\n H[:, :dims] = np.eye(dims)\n return (X,P,A,Q,R,H)\n\ndef predict(X,P,A,Q,B=0,U=0):\n if B == 0:\n B = np.zeros(X.shape[0])\n if U == 0:\n U = np.zeros((X.shape[0],1))\n X = np.dot(A,X) + np.dot(B,U)\n P = np.dot(A,np.dot(P,A.T)) + Q\n return (X,P)\n\ndef update(P,H,R,X,Z):\n K = np.dot(P,np.dot(H.T,np.linalg.inv(np.dot(H,np.dot(P,H.T)) + R)))\n X = X + np.dot(K,(Z - np.dot(H,X)))\n P = np.dot((np.eye(P.shape[0]) - np.dot(K,H)),P)\n return (X,P)\n","sub_path":"Kalman.py","file_name":"Kalman.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"391188464","text":"from __future__ import with_statement\nimport sys\nimport os\nimport time\n\nimport java.io.FileReader as FileReader\nimport java.io.File as File\nimport java.lang.String as String\nimport java.lang.StringBuffer as StringBuffer\nimport java.lang.Boolean as Boolean\nimport java.util.Random as Random\n\nimport dist.DiscreteDependencyTree as DiscreteDependencyTree\nimport dist.DiscreteUniformDistribution as DiscreteUniformDistribution\nimport dist.Distribution as Distribution\nimport dist.DiscretePermutationDistribution as DiscretePermutationDistribution\nimport opt.DiscreteChangeOneNeighbor as DiscreteChangeOneNeighbor\nimport opt.EvaluationFunction as EvaluationFunction\nimport opt.GenericHillClimbingProblem as GenericHillClimbingProblem\nimport opt.HillClimbingProblem as HillClimbingProblem\nimport opt.NeighborFunction as NeighborFunction\nimport opt.RandomizedHillClimbing as RandomizedHillClimbing\nimport opt.SimulatedAnnealing as SimulatedAnnealing\nimport opt.example.FourPeaksEvaluationFunction as FourPeaksEvaluationFunction\nimport opt.ga.CrossoverFunction as CrossoverFunction\nimport opt.ga.SingleCrossOver as SingleCrossOver\nimport opt.ga.DiscreteChangeOneMutation as DiscreteChangeOneMutation\nimport opt.ga.GenericGeneticAlgorithmProblem as GenericGeneticAlgorithmProblem\nimport opt.ga.GeneticAlgorithmProblem as GeneticAlgorithmProblem\nimport opt.ga.MutationFunction as MutationFunction\nimport opt.ga.StandardGeneticAlgorithm as StandardGeneticAlgorithm\nimport opt.ga.UniformCrossOver as UniformCrossOver\nimport opt.prob.GenericProbabilisticOptimizationProblem as GenericProbabilisticOptimizationProblem\nimport opt.prob.MIMIC as MIMIC\nimport opt.prob.ProbabilisticOptimizationProblem as ProbabilisticOptimizationProblem\nimport shared.FixedIterationTrainer as FixedIterationTrainer\nimport opt.example.TravelingSalesmanEvaluationFunction as TravelingSalesmanEvaluationFunction\nimport opt.example.TravelingSalesmanRouteEvaluationFunction as TravelingSalesmanRouteEvaluationFunction\nimport opt.SwapNeighbor as SwapNeighbor\nimport opt.ga.SwapMutation as SwapMutation\nimport opt.example.TravelingSalesmanCrossOver as TravelingSalesmanCrossOver\nimport opt.example.TravelingSalesmanSortEvaluationFunction as TravelingSalesmanSortEvaluationFunction\nimport shared.Instance as Instance\nimport util.ABAGAILArrays as ABAGAILArrays\n\nfrom array import array\n\ndef list_avg(*args):\n output = []\n for i in range(len(args[0])):\n temp = 0.0\n for j in range(len(args)):\n temp += args[j][i]\n output.append(temp / len(args))\n return output\n\nOUTPUT_FILE = 'tsm_result.csv'\n\nSA_TEMPERATURE = 1e12\nSA_COOLING_FACTOR = .999\n\nGA_POPULATION = 2000\nGA_CROSSOVER = 1500\nGA_MUTATION = 250\n\nMIMIC_SAMPLES = 500\nMIMIC_TO_KEEP = 100\n\n# Random number generator */\nN=50\nrandom = Random()\n\ncycle = 5\niterations = [10,20,30,50,70,100,200,300,500,700,1000,2000,3000,4000,5000]\n\nrhc_fitness = [[] for i in range(cycle)]\nrhc_training_time = [[] for i in range(cycle)]\n\nsa_fitness = [[] for i in range(cycle)]\nsa_training_time = [[] for i in range(cycle)]\n\nga_fitness = [[] for i in range(cycle)]\nga_training_time = [[] for i in range(cycle)]\n\nmimic_fitness = [[] for i in range(cycle)]\nmimic_training_time = [[] for i in range(cycle)]\n\nfor n in range(cycle):\n print(\"the %d th cycle\" %(n+1))\n \n points = [[0 for x in xrange(2)] for x in xrange(N)]\n for i in range(0, len(points)):\n points[i][0] = random.nextDouble()\n points[i][1] = random.nextDouble()\n \n ef = TravelingSalesmanRouteEvaluationFunction(points)\n odd = DiscretePermutationDistribution(N)\n nf = SwapNeighbor()\n mf = SwapMutation()\n cf = TravelingSalesmanCrossOver(ef)\n hcp = GenericHillClimbingProblem(ef, odd, nf)\n gap = GenericGeneticAlgorithmProblem(ef, odd, mf, cf)\n \n ef2 = TravelingSalesmanRouteEvaluationFunction(points)\n fill = [N] * N\n ranges = array('i', fill)\n odd2 = DiscreteUniformDistribution(ranges);\n df = DiscreteDependencyTree(.1, ranges); \n pop = GenericProbabilisticOptimizationProblem(ef2, odd2, df);\n \n rhc = RandomizedHillClimbing(hcp)\n sa = SimulatedAnnealing(SA_TEMPERATURE, SA_COOLING_FACTOR, hcp)\n ga = StandardGeneticAlgorithm(GA_POPULATION, GA_CROSSOVER, GA_MUTATION, gap)\n mimic = MIMIC(MIMIC_SAMPLES, MIMIC_TO_KEEP, pop)\n \n for n_iteration in iterations:\n fit_rhc = FixedIterationTrainer(rhc, n_iteration*200)\n fit_sa = FixedIterationTrainer(sa, n_iteration*200)\n fit_ga = FixedIterationTrainer(ga, n_iteration)\n fit_mimic = FixedIterationTrainer(mimic, n_iteration)\n \n print(\"calculating the %d th iteration\" % n_iteration)\n\n # Training\n start_rhc = time.time()\n fit_rhc.train()\n end_rhc = time.time()\n\n start_sa = time.time()\n fit_sa.train()\n end_sa = time.time()\n \n start_ga = time.time()\n fit_ga.train()\n end_ga = time.time()\n \n start_mimic = time.time()\n fit_mimic.train()\n end_mimic = time.time()\n\n # Result extracting\n last_training_time_rhc = end_rhc - start_rhc\n rhc_training_time[n].append(last_training_time_rhc)\n rhc_fitness[n].append(ef.value(rhc.getOptimal()))\n\n last_training_time_sa = end_sa - start_sa\n sa_training_time[n].append(last_training_time_sa)\n sa_fitness[n].append(ef.value(sa.getOptimal()))\n \n last_training_time_ga = end_ga - start_ga\n ga_training_time[n].append(last_training_time_ga)\n ga_fitness[n].append(ef.value(ga.getOptimal()))\n\n last_training_time_mimic = end_mimic - start_mimic\n mimic_training_time[n].append(last_training_time_mimic)\n mimic_fitness[n].append(ef.value(mimic.getOptimal()))\n\noverall_rhc_training_time = list_avg(*rhc_training_time)\noverall_rhc_fitness = list_avg(*rhc_fitness)\n\noverall_sa_training_time = list_avg(*sa_training_time)\noverall_sa_fitness = list_avg(*sa_fitness)\n\noverall_ga_training_time = list_avg(*ga_training_time)\noverall_ga_fitness = list_avg(*ga_fitness)\n\noverall_mimic_training_time = list_avg(*mimic_training_time)\noverall_mimic_fitness = list_avg(*mimic_fitness)\n\n#print mimic_training_time\n#print overall_mimic_training_time\n\nwith open(OUTPUT_FILE, \"w\") as outFile:\n for i in range(1):\n outFile.write(','.join([\n \"sa_rhc_iterations\",\n \"rhc_fitness\",\n \"rhc_training_time\",\n \"sa_fitness\",\n \"sa_training_time\",\n \"ga_mimic_iterations\"\n \"ga_fitness\",\n \"ga_training_time\",\n \"mimic_fitness\",\n \"mimic_training_time\"]) + '\\n')\n for i in range(len(iterations)):\n outFile.write(','.join([\n str(iterations[i]*200),\n str(overall_rhc_fitness[i]),\n str(overall_rhc_training_time[i]),\n str(overall_sa_fitness[i]),\n str(overall_sa_training_time[i]),\n str(iterations[i]),\n str(overall_ga_fitness[i]),\n str(overall_ga_training_time[i]),\n str(overall_mimic_fitness[i]),\n str(overall_mimic_training_time[i])]) + '\\n')\n \nprint(\"The end of the program\") \n \n ","sub_path":"HW2/tsmITER.py","file_name":"tsmITER.py","file_ext":"py","file_size_in_byte":7205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"485393940","text":"#!/bin/env python\nimport re\nfrom collections import namedtuple \n\n_TODO_RE = re.compile(\"\\* (TODO|DONE) (.*)\")\n_DATETIME_RE = \"\\d{2}\\d{2}\\d{2} \\d{2}:\\d{2}\"\n_DATE_RE = \"\\d{2}\\d{2}\\d{2}\"\n\nclass Todo(namedtuple('Todo', 'caption done deadline contents')):\n def __repr__(self):\n return \"%s %s%s%s\" % ('DONE' if self.done else 'TODO',\n self.caption,\n ' ' + self.deadline if self.deadline else '',\n '\\n\\t' + self.contents if self.contents else '')\n\ndef _deadline_or_none(line):\n return re.findall(_DATETIME_RE, line) or re.findall(_DATE_RE, line) or None\n\ndef todo_parser(text):\n caption = None\n deadline = None\n contents = []\n done = False\n\n for line in text.split(\"\\n\"):\n match = _TODO_RE.match(line)\n if match:\n if caption:\n yield Todo(caption, done, deadline, \"\\n\".join(contents))\n contents = []\n done = match.group(1) == 'DONE'\n caption = match.group(2)\n deadline = _deadline_or_none(line)\n elif caption:\n contents.append(line.strip())\n if caption:\n yield Todo(caption, done, deadline, \"\\n\".join(contents))\n\n\ndef todo_coder(todos):\n out = []\n for todo in todos:\n out += [\"* %s %s%s\" % ('DONE' if todo.done else 'TODO',\n todo.caption,\n todo.deadline if todo.deadline else \"\")]\n for line in todo.contents.split('\\n'):\n out += [\" \" + line]\n return \"\\n\".join(out)\n\ndef load_todo(path):\n with open(path) as source:\n data = source.read()\n return list(todo_parser(data))\n\ndef save_todo(path, todos):\n with open(path, \"w\") as dest:\n dest.write(todo_coder(todos))\n\ndef cmdline_parse(raw):\n if not '---' in raw:\n deadline = _deadline_or_none(raw)\n return Todo(raw.strip(), False, deadline, '')\n\n data = raw.split('---')\n caption = data[0].strip()\n content = \"\\n\".join(data[1:]).strip()\n deadline = _deadline_or_none(caption)\n return Todo(caption, False,deadline, content)\n\ndef cmd_add(path, raw):\n todo = cmdline_parse(raw)\n todos = load_todo(path)\n todos = [todo] + todos\n save_todo(path, todos)\n\ndef cmd_view(path):\n todos = load_todo(path)\n for i, todo in zip(range(1, len(todos)+1), todos):\n print(i, str(todo))\n\ndef cmd_done(path, index):\n \"\"\"1-based index!\"\"\"\n index = int(index)\n todos = load_todo(path)\n todo = todos.pop(index-1)\n todos.append(todo._replace(done=True))\n save_todo(path, todos)\n\ndef cmd_delete(path, index):\n \"\"\"1-based index!\"\"\"\n index = int(index)\n todos = load_todo(path)\n todo = todos[index-1]\n del todos[index-1]\n save_todo(path, todos)\n\ndef cmd_init(path):\n save_todo(path, [])\n\nif __name__ == \"__main__\":\n import sys, os\n if len(sys.argv) < 2: sys.exit()\n path = os.environ['HOME'] + \"/.plan\"\n fn = globals()['cmd_%s' % sys.argv[1]]\n if sys.argv[2:]:\n fn(path, \" \".join(sys.argv[2:]))\n else:\n fn(path)\n\n\n\n\n\n\n \n","sub_path":"pytodo/todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":3118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"212998675","text":"import redis\nimport sys\nimport re\nimport json\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_auth\n\nfrom plotly import graph_objects as go\nimport dash_bootstrap_components as dbc\nfrom crow.events import LOG_MESSAGE, GENERATED_BC_VARIANT, EXPLORATION_RESULT, BC_EXPLORATION_QUEUE, GENERATION_QUEUE, \\\n WAT_QUEUE, WASM_QUEUE\nfrom crow.monitor.logger import ERROR\nfrom crow.events.event_manager import Subscriber, subscriber_function, Publisher\nimport traceback\nfrom crow.settings import config\nfrom crow.monitor import MONITOR_QUEUE_NAME\nfrom crow.storage import STORAGE_QUEUE_NAME\nfrom crow.utils import printProgressBar\nfrom zipfile import ZipFile\nimport os\nimport flask\nfrom shutil import make_archive\nfrom flask.helpers import send_file\nimport pika\nimport time\n\nNOW = time.time()\n\nclass RabbitMonitor:\n\n def __init__(self, save_query=True):\n\n self.__setup()\n self.save_query = save_query\n self.queries = {}\n\n def __setup(self):\n BROKER_PASS = os.getenv(\"BROKER_PASS\", None)\n BROKER_USER = os.getenv(\"BROKER_USER\", None)\n\n if BROKER_PASS and BROKER_USER:\n credentials = pika.PlainCredentials(BROKER_USER, BROKER_PASS)\n print(\"Connecting with credentials\", config['event']['host'])\n param = pika.ConnectionParameters(host=config[\"event\"][\"host\"],\n virtual_host=\"/\",\n port=config[\"event\"].getint(\"port\"),\n credentials=credentials)\n else:\n param = pika.ConnectionParameters(host=config[\"event\"][\"host\"],\n port=config[\"event\"].getint(\"port\"))\n while True:\n try:\n self.connection = pika.BlockingConnection(param)\n self.channel = self.connection.channel()\n break\n except Exception as e:\n print(\"Error connecting\", e, traceback.format_stack())\n time.sleep(5)\n\n def __get_message_count(self, QUEUE_NAME):\n\n try:\n queue = self.channel.queue_declare(\n queue=QUEUE_NAME,passive=True\n )\n\n if self.save_query:\n if QUEUE_NAME not in self.queries:\n self.queries[QUEUE_NAME] = []\n\n self.queries[QUEUE_NAME].append((\n time.time() - NOW,\n queue.method.message_count\n ))\n return queue.method.message_count\n except Exception:\n time.sleep(3) # waiting 3 seconds\n self.__setup()\n\n\n def __purge_queue(self, queue_name):\n\n try:\n print(f\"Purging {queue_name}\")\n self.channel.queue_purge(queue_name)\n except Exception:\n time.sleep(3)\n self.__setup()\n def purge_exploration_queue(self):\n self.__purge_queue(BC_EXPLORATION_QUEUE)\n\n def purge_generation_queue(self):\n self.__purge_queue(GENERATION_QUEUE)\n\n def purge_storage_queue(self):\n self.__purge_queue(STORAGE_QUEUE_NAME)\n\n def purge_wasm2wat_queue(self):\n self.__purge_queue(WASM_QUEUE)\n\n def purge_wat2wasm_queue(self):\n self.__purge_queue(WAT_QUEUE)\n\n def get_exploration_message_count(self):\n return self.__get_message_count(BC_EXPLORATION_QUEUE)\n\n def get_generation_message_count(self):\n return self.__get_message_count(GENERATION_QUEUE)\n\n def get_storage_message_count(self):\n return self.__get_message_count(STORAGE_QUEUE_NAME)\n\n def get_wasm2wat_message_count(self):\n return self.__get_message_count(WAT_QUEUE)\n\n def get_bc2wasm_message_count(self):\n return self.__get_message_count(WASM_QUEUE)\n\nPROGRAM_RE = re.compile(r\"^(.+?):\")\nBASE_DIR = os.path.dirname(__file__)\n\nif __name__ == \"__main__\":\n\n m = RabbitMonitor()\n m.get_exploration_message_count()\n\n redis_host = sys.argv[1]\n redis_port = int(sys.argv[2])\n redis_db = sys.argv[3]\n redis_pass = sys.argv[4]\n out_folder = sys.argv[5]\n\n VALID_USERNAME_PASSWORD_PAIRS = {\n }\n if os.getenv(\"BROKER_USER\"):\n VALID_USERNAME_PASSWORD_PAIRS[os.getenv(\"BROKER_USER\")] = os.getenv(\"BROKER_PASS\")\n else:\n exit(0)\n\n connection = redis.Redis(host=redis_host,port=redis_port, db=redis_db, password=redis_pass)\n app = dash.Dash(external_stylesheets=[dbc.themes.LUX], suppress_callback_exceptions=True)\n auth = dash_auth.BasicAuth(\n app,\n VALID_USERNAME_PASSWORD_PAIRS\n )\n\n unique_bitcodes_queries = {}\n total_bitcodes_queries = {}\n\n unique_wasms_queries = {}\n total_wasms_queries = {}\n\n def has(k):\n return connection.get(k) is not None\n\n def get_all_programs(prefix=\"\", save=False, getsnapshotfirst=True):\n\n if getsnapshotfirst and has(f\"SNAPSHOT:all_programs:{prefix}\"):\n return json.loads(connection.get(f\"SNAPSHOT:all_programs:{prefix}\").decode())\n\n print(\"getting programs\")\n allkeys = connection.keys(f\"{prefix}*\")\n\n r = { }\n\n print(\"keys retrieved\")\n for k in allkeys:\n kd = k.decode()\n\n match= PROGRAM_RE.match(kd)\n if match:\n r[match.group(1)] = { }\n\n\n if save:\n connection.set(f\"SNAPSHOT:all_programs:{prefix}\", json.dumps(r).encode())\n\n print(\"Returning all programs\")\n return r\n\n def get_unique_bitcodes(program, save=False, getsnapshotfirst=True):\n if getsnapshotfirst and has(f\"SNAPSHOT:unique_bitcodes:{program}\"):\n return json.loads(connection.get(f\"SNAPSHOT:unique_bitcodes:{program}\").decode())\n\n bc_keys = connection.keys(f\"{program}:bc:*\")\n\n if program not in unique_bitcodes_queries:\n unique_bitcodes_queries[program] = []\n\n unique_bitcodes_queries[program].append((\n time.time() - NOW,\n len(bc_keys)\n ))\n\n if save:\n connection.set(f\"SNAPSHOT:unique_bitcodes:{program}\", json.dumps([k.decode() for k in bc_keys]).encode())\n\n return bc_keys\n\n\n def get_eq_variants_for_bc(bitcode_key):\n\n try:\n variants = connection.get(f\"{bitcode_key.decode()}\")\n except:\n variants = connection.get(f\"{bitcode_key}\")\n return json.loads(variants.decode()) if variants else None\n\n\n def get_eq_variants_for_wasm(wasm_key):\n variants = connection.get(f\"{wasm_key.decode()}\")\n return json.loads(variants.decode()) if variants else None\n\n def get_eq_variants_for_wat( wat_key):\n variants = connection.get(f\"{wat_key.decode()}\")\n return json.loads(variants.decode()) if variants else None\n\n def get_unique_wasm(program):\n wasm_keys = connection.keys(f\"{program}:wasm:*\")\n\n if program not in unique_wasms_queries:\n unique_wasms_queries[program] = []\n\n unique_wasms_queries[program].append((\n time.time() - NOW,\n len(wasm_keys)\n ))\n return wasm_keys\n\n def get_unique_wat(program):\n wat_keys = connection.keys(f\"{program}:wat:*\")\n return wat_keys\n\n def get_total_llvm(program):\n C = 0\n for bc in get_unique_bitcodes(program):\n C += len(get_eq_variants_for_bc(bc))\n\n if program not in total_bitcodes_queries:\n total_bitcodes_queries[program] = []\n total_bitcodes_queries[program].append((\n time.time() - NOW,\n C\n ))\n return C\n\n def get_total_wasm(program):\n C = 0\n for bc in get_unique_wasm(program):\n C += len(get_eq_variants_for_wasm(bc))\n\n\n if program not in total_wasms_queries:\n total_wasms_queries[program] = []\n\n\n total_wasms_queries[program].append((\n time.time() - NOW,\n C\n ))\n return C\n\n def get_total_wat(program):\n C = 0\n for bc in get_unique_wat(program):\n C += len(get_eq_variants_for_wat(bc))\n return C\n\n def make_zip(path, name=\"out\"):\n print(path, os.listdir(path))\n\n make_archive(\n f'{BASE_DIR}/{name}',\n 'zip', # the archive format - or tar, bztar, gztar\n root_dir=path, # root for archive - current working dir if None\n base_dir=None) # start archiving from here - cwd if None too\n\n return f\"{name}.zip\"\n\n @app.server.route('/downloadable/')\n def serve_static_bitcodes(program_name):\n\n o = make_zip(f\"{out_folder}/{program_name}/bitcodes/variants\", \"bitcodes\")\n\n return flask.send_from_directory(\n BASE_DIR, o, as_attachment=True,cache_timeout=0\n )\n\n\n @app.server.route('/downloadablew/')\n def serve_static_wasms(program_name):\n\n o = make_zip(f\"{out_folder}/{program_name}/wasm\", \"wasms\")\n\n return flask.send_from_directory(\n BASE_DIR, o, as_attachment=True, cache_timeout=0\n )\n\n\n @app.server.route('/downloadablewt/')\n def serve_static_wat(program_name):\n\n o = make_zip(f\"{out_folder}/{program_name}/wat\", \"wats\")\n\n return flask.send_from_directory(\n BASE_DIR, o, as_attachment=True, cache_timeout=0\n )\n\n\n @app.callback(dash.dependencies.Output('logs', 'children'),\n [dash.dependencies.Input('purge-button1', 'n_clicks'),\n dash.dependencies.Input('purge-button1', 'key')],\n )\n def purge_exploration(n_clicks, key):\n\n if n_clicks and key == \"EXPLORATION\":\n return m.purge_exploration_queue()\n\n\n return None\n\n\n '''\n html.A(\n style=dict(\n marginLeft='5px'\n ),\n id=\"purge-button1\",\n className='btn btn-danger',\n children=f\"Purge\",\n key=\"EXPLORATION\"\n ),\n '''\n @app.callback(dash.dependencies.Output('page-content', 'children'),\n [dash.dependencies.Input('url', 'pathname'),\n dash.dependencies.Input('interval1', 'n_intervals'),\n dash.dependencies.Input('update-button', 'n_clicks')],\n )\n def display_page(pathname, n_clicks, n_intervals):\n\n\n def plot_general_stats():\n\n sc = m.get_storage_message_count()\n ec = m.get_exploration_message_count()\n gc = m.get_generation_message_count()\n wc = m.get_wasm2wat_message_count()\n bc = m.get_bc2wasm_message_count()\n\n print(\"Queues count retrieved\", sc, ec, gc, wc, bc)\n\n return html.Div(\n style=dict(\n padding=\"30px\"\n ),\n children=[\n html.Hr(),\n html.H2(\n children=\"Broker status, pending messages\"\n ),\n html.Div(\n className=\"row\",\n children=[\n html.Div(\n className='col col-md-4',\n children=dcc.Graph(\n figure={\n 'data': [\n go.Scatter(\n x=[x[0] for x in m.queries[BC_EXPLORATION_QUEUE]],\n y=[x[1] for x in m.queries[BC_EXPLORATION_QUEUE]],\n mode=\"markers+lines\",\n name=\"test\"\n )\n\n ],\n 'layout': {\n 'title': f'Exploration queue {ec}'\n }\n },\n\n )\n ),\n html.Div(\n className='col col-md-4',\n children=dcc.Graph(\n figure={\n 'data': [\n go.Scatter(\n x=[x[0] for x in m.queries[GENERATION_QUEUE]],\n y=[x[1] for x in m.queries[GENERATION_QUEUE]],\n mode=\"markers+lines\",\n name=\"variant generation\"\n ),\n go.Scatter(\n x=[x[0] for x in m.queries[WAT_QUEUE]],\n y=[x[1] for x in m.queries[WAT_QUEUE]],\n mode=\"markers+lines\",\n name=\"wasm2wat generation\"\n ),\n go.Scatter(\n x=[x[0] for x in m.queries[WASM_QUEUE]],\n y=[x[1] for x in m.queries[WASM_QUEUE]],\n mode=\"markers+lines\",\n name=\"bc2wasm generation\"\n )\n\n ],\n 'layout': {\n 'title': f'Generation queue {gc}, {wc}, {bc}'\n }\n }\n )\n\n ),\n html.Div(\n className='col col-md-4',\n children=dcc.Graph(\n figure={\n 'data': [\n go.Scatter(\n x=[x[0] for x in m.queries[STORAGE_QUEUE_NAME]],\n y=[x[1] for x in m.queries[STORAGE_QUEUE_NAME]],\n mode=\"markers+lines\",\n name=\"test\"\n )\n\n ],\n 'layout': {\n 'title': f'Storage queue {sc}'\n }\n }\n )\n )\n ]\n )])\n\n def generate_report_for_module(module):\n\n print(\"Getting stats for\", module)\n unique_llvm = len(get_unique_bitcodes(module))\n unique_wasm = len(get_unique_wasm(module))\n\n total_llvm = get_total_llvm(module)\n total_wasm = get_total_wasm(module)\n \n if unique_wasm > 1:\n print(module, unique_llvm, unique_wasm, total_llvm, total_wasm)\n\n if total_llvm == 0 or total_wasm == 0 or unique_llvm <= 1:\n return None\n\n return html.Div(\n children=html.Div(\n children=[\n html.H2(\n children=[\n\n html.A(\n children=module\n ), # TODO go to module page\n # TODO in module page, show size of the bitcode/wasm equality distribution\n ]\n ),\n html.Div(\n className=\"row\",\n children=[\n\n html.H4(\n className=\"col\",\n children=f\"Unique LLVM {unique_llvm}/{total_llvm} ({unique_llvm/total_llvm*100:.2f}%)\"\n ),\n html.A(\n className=\"btn btn-primary\",\n children=\"Get bitcodes\",\n href=f\"/downloadable/{module}\",\n style={\n 'marginRight': '50px'\n }\n )\n ,\n html.H4(\n className=\"col\",\n children=f\"Unique WASM {unique_wasm}/{total_wasm} ({unique_wasm/total_wasm*100:.2f}%)\"\n ),\n\n html.A(\n className=\"btn btn-primary\",\n children=\"Get wasms\",\n href=f\"/downloadablew/{module}\",\n style={\n 'marginRight': '50px'\n }\n ),\n html.A(\n className=\"btn btn-primary\",\n children=\"Get wats\",\n href=f\"/downloadablewt/{module}\",\n style={\n 'marginRight': '50px'\n }\n )\n ]\n ),\n html.Div(\n className='row',\n children=[\n html.Div(\n className='col',\n children=\n dcc.Graph(\n id='GrapGo',\n figure={\n 'data': [\n go.Scatter(\n x=[x[0] for x in total_bitcodes_queries[module]],\n y=[x[1] for x in total_bitcodes_queries[module]],\n mode=\"markers+lines\",\n name=\"Total\"\n ),\n go.Scatter(\n x=[x[0] for x in unique_bitcodes_queries[module]],\n y=[x[1] for x in unique_bitcodes_queries[module]],\n mode=\"markers+lines\",\n name=\"Unique\"\n )\n\n ]\n },\n style={\n 'minHeight': '300px'\n }\n )\n ),\n html.Div(\n className='col',\n children=\n dcc.Graph(\n id='GrapGo',\n figure={\n 'data': [\n go.Scatter(\n x=[x[0] for x in total_wasms_queries[module]],\n y=[x[1] for x in total_wasms_queries[module]],\n mode=\"markers+lines\",\n name=\"Total\"\n ),\n go.Scatter(\n x=[x[0] for x in unique_wasms_queries[module]],\n y=[x[1] for x in unique_wasms_queries[module]],\n mode=\"markers+lines\",\n name=\"Unique\"\n )\n\n ]\n },\n style={\n 'minHeight': '300px'\n }\n )\n )\n ]\n ),\n html.Hr()\n ]\n ),\n style={\n 'textAlign': 'left',\n 'color': colors['text']\n }\n )\n if pathname == '/':\n programs = get_all_programs()\n print(len(programs))\n colors = {\n 'background': '#FFFFFF',\n 'text': '#000000'\n }\n return html.Div(style={'backgroundColor': colors['background']}, children=[\n html.Div(\n children=[\n html.H1(\n children='CROW dashboard'\n ),\n html.H2(\n children=f\"DB {redis_db}\"\n ),\n plot_general_stats()\n ],\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n\n html.H2(\n children=f\"{len(programs)} Modules \",\n style={\n 'textAlign': 'center',\n 'color': colors['text']\n }\n ),\n html.Div(\n style=dict(\n padding=\"50px\"\n ),\n children=list(map(generate_report_for_module, programs))\n )\n\n ])\n\n\n\n def deploy_dash(debug=True):\n\n\n\n app.layout = html.Div(children=[\n dcc.Location(id='url', refresh=False),\n html.A(\n className=\"btn btn-default\",\n id=\"update-button\",\n children=\"Reload\",\n style={\n 'marginRight': '50px',\n 'position':'fixed',\n 'zIndex': '99999'\n }\n ),\n dcc.Interval(id='interval1', interval=600 * 1000, n_intervals=0),\n html.Div(id='logs'),\n html.Div(id='page-content'),\n ])\n\n app.run_server(host=\"0.0.0.0\", port=8050, debug=debug)\n\n def print_general_stats():\n programs = get_all_programs(prefix=\"sodium3\", save=True, getsnapshotfirst=False)\n\n for k in programs.keys():\n\n print(k)\n bc_unique = get_unique_bitcodes(k, save=True, getsnapshotfirst=False)\n print(f\"\\t bitcodes {len(bc_unique)}\")\n\n\n print(\"\\t\\teq \", end=\"\")\n for bc in bc_unique:\n variants = get_eq_variants_for_bc(bc)\n print(f\"{len(variants)}\", end=\" \")\n\n print()\n\n\n w_unique = get_unique_wasm(k)\n print(f\"\\t wasm {len(w_unique)}\")\n\n \n #subscriber = Subscriber(1, MONITOR_QUEUE_NAME, GENERATED_BC_KEY, config[\"event\"].getint(\"port\"), general_log)\n #subscriber.setup()\n\n\n deploy_dash(debug=True)\n #print_general_stats()\n","sub_path":"crow/crow/monitor/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":24121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"169919479","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThis experiment was created using PsychoPy3 Experiment Builder (v3.0.4),\r\n on June 28, 2019, at 17:24\r\nIf you publish work using this script please cite the PsychoPy publications:\r\n Peirce, JW (2007) PsychoPy - Psychophysics software in Python.\r\n Journal of Neuroscience Methods, 162(1-2), 8-13.\r\n Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy.\r\n Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008\r\n\"\"\"\r\n\r\nfrom __future__ import absolute_import, division\r\nfrom psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock\r\nfrom psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,\r\n STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)\r\nimport numpy as np # whole numpy lib is available, prepend 'np.'\r\nfrom numpy import (sin, cos, tan, log, log10, pi, average,\r\n sqrt, std, deg2rad, rad2deg, linspace, asarray)\r\nfrom numpy.random import random, randint, normal, shuffle\r\nimport os # handy system and path functions\r\nimport sys # to get file system encoding\r\n\r\n# Ensure that relative paths start from the same directory as this script\r\n_thisDir = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(_thisDir)\r\n\r\n# Store info about the experiment session\r\npsychopyVersion = '3.0.4'\r\nexpName = 'AggPrototype' # from the Builder filename that created this script\r\nexpInfo = {'participant': '', 'session': '001'}\r\ndlg = gui.DlgFromDict(dictionary=expInfo, title=expName)\r\nif dlg.OK == False:\r\n core.quit() # user pressed cancel\r\nexpInfo['date'] = data.getDateStr() # add a simple timestamp\r\nexpInfo['expName'] = expName\r\nexpInfo['psychopyVersion'] = psychopyVersion\r\n\r\n# Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc\r\nfilename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])\r\n\r\n# An ExperimentHandler isn't essential but helps with data saving\r\nthisExp = data.ExperimentHandler(name=expName, version='',\r\n extraInfo=expInfo, runtimeInfo=None,\r\n originPath='C:\\\\Users\\\\sumsh86\\\\Desktop\\\\Main AGG codes\\\\New Psychopy aggression\\\\3 Phase Experiment Script\\\\Phase 3 Original_lastrun.py',\r\n savePickle=True, saveWideText=True,\r\n dataFileName=filename)\r\n# save a log file for detail verbose info\r\nlogFile = logging.LogFile(filename + '.log', level=logging.EXP)\r\nlogging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file\r\n\r\nendExpNow = False # flag for 'escape' or other condition => quit the exp\r\n\r\n# Start Code - component code to be run before the window creation\r\n\r\n# Setup the Window\r\nwin = visual.Window(\r\n size=[1920, 1200], fullscr=True, screen=0,\r\n allowGUI=False, allowStencil=False,\r\n monitor='testMonitor', color=[0, 0, 0], colorSpace='rgb',\r\n blendMode='avg', useFBO=True)\r\n# store frame rate of monitor if we can measure it\r\nexpInfo['frameRate'] = win.getActualFrameRate()\r\nif expInfo['frameRate'] != None:\r\n frameDur = 1.0 / round(expInfo['frameRate'])\r\nelse:\r\n frameDur = 1.0 / 60.0 # could not measure, so guess\r\n\r\n# Initialize components for Routine \"WelcomeScreen\"\r\nWelcomeScreenClock = core.Clock()\r\nWelcomeText = visual.TextStim(win=win, name='WelcomeText',\r\n text=\"Please have a seat\\n\\n\\nPress 'Spacebar' to continue\",\r\n font='Arial',\r\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=0.0);\r\n\r\n# Initialize components for Routine \"Blank500\"\r\nBlank500Clock = core.Clock()\r\nBlankText = visual.TextStim(win=win, name='BlankText',\r\n text=None,\r\n font='Arial',\r\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=0.0);\r\n\r\n# Initialize components for Routine \"InstructionRetaliation\"\r\nInstructionRetaliationClock = core.Clock()\r\nIRText = visual.TextStim(win=win, name='IRText',\r\n text=\"It is now your turn to return shocks to the other players\\n\\nUse the NumPad\\nPress '0' for NO shocks\\nPress '1' for ONE shock\\nPress '2' for TWO shocks\\n\\nPress 'Spacebar' when you are ready to continue\",\r\n font='Arial',\r\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=0.0);\r\n\r\n# Initialize components for Routine \"Blank500\"\r\nBlank500Clock = core.Clock()\r\nBlankText = visual.TextStim(win=win, name='BlankText',\r\n text=None,\r\n font='Arial',\r\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=0.0);\r\n\r\n# Initialize components for Routine \"RConnect\"\r\nRConnectClock = core.Clock()\r\nWaitingText = visual.TextStim(win=win, name='WaitingText',\r\n text='Waiting for players...',\r\n font='Arial',\r\n pos=(0, 0.3), height=0.12, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=0.0);\r\nP1 = visual.TextStim(win=win, name='P1',\r\n text='P1',\r\n font='Arial',\r\n pos=(-0.6, 0.1), height=0.08, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=-1.0);\r\nP2 = visual.TextStim(win=win, name='P2',\r\n text='P2',\r\n font='Arial',\r\n pos=(-0.2, 0.1), height=0.08, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=-2.0);\r\nUser = visual.TextStim(win=win, name='User',\r\n text='P3 (you)',\r\n font='Arial',\r\n pos=(0.2, 0.1), height=0.08, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=-3.0);\r\nP4 = visual.TextStim(win=win, name='P4',\r\n text='P4',\r\n font='Arial',\r\n pos=(0.6, 0.1), height=0.08, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=-4.0);\r\nP1G = visual.Polygon(\r\n win=win, name='P1G',\r\n edges=16, size=(0.09, 0.14),\r\n ori=0, pos=(-0.6, -0.1),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='green', fillColorSpace='rgb',\r\n opacity=1, depth=-5.0, interpolate=True)\r\nP1R = visual.Polygon(\r\n win=win, name='P1R',\r\n edges=16, size=(0.09, 0.14),\r\n ori=0, pos=(-0.6, -0.1),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='red', fillColorSpace='rgb',\r\n opacity=1, depth=-6.0, interpolate=True)\r\nP2G = visual.Polygon(\r\n win=win, name='P2G',\r\n edges=16, size=(0.09, 0.14),\r\n ori=0, pos=(-0.2, -0.1),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='green', fillColorSpace='rgb',\r\n opacity=1, depth=-7.0, interpolate=True)\r\nP2R = visual.Polygon(\r\n win=win, name='P2R',\r\n edges=16, size=(0.09, 0.14),\r\n ori=0, pos=(-0.2, -0.1),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='red', fillColorSpace='rgb',\r\n opacity=1, depth=-8.0, interpolate=True)\r\nUserG = visual.Polygon(\r\n win=win, name='UserG',\r\n edges=16, size=(0.09, 0.14),\r\n ori=0, pos=(0.2, -0.1),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='green', fillColorSpace='rgb',\r\n opacity=1, depth=-9.0, interpolate=True)\r\nP4G = visual.Polygon(\r\n win=win, name='P4G',\r\n edges=16, size=(0.09, 0.14),\r\n ori=0, pos=(0.6, -0.1),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='green', fillColorSpace='rgb',\r\n opacity=1, depth=-10.0, interpolate=True)\r\nP4R = visual.Polygon(\r\n win=win, name='P4R',\r\n edges=16, size=(0.09, 0.14),\r\n ori=0, pos=(0.6, -0.1),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='red', fillColorSpace='rgb',\r\n opacity=1, depth=-11.0, interpolate=True)\r\n\r\n# Initialize components for Routine \"Blank500\"\r\nBlank500Clock = core.Clock()\r\nBlankText = visual.TextStim(win=win, name='BlankText',\r\n text=None,\r\n font='Arial',\r\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=0.0);\r\n\r\n# Initialize components for Routine \"FixCross\"\r\nFixCrossClock = core.Clock()\r\nCross = visual.ShapeStim(\r\n win=win, name='Cross', vertices='cross',\r\n size=(0.02, 0.03),\r\n ori=0, pos=(0, 0),\r\n lineWidth=1, lineColor='black', lineColorSpace='rgb',\r\n fillColor='black', fillColorSpace='rgb',\r\n opacity=1, depth=0.0, interpolate=True)\r\n\r\n# Initialize components for Routine \"Retaliation\"\r\nRetaliationClock = core.Clock()\r\nRetaliationImages = visual.ImageStim(\r\n win=win, name='RetaliationImages', units='pix',\r\n image='sin', mask=None,\r\n ori=0, pos=(0, 0), size=(360, 450),\r\n color=[1, 1, 1], colorSpace='rgb', opacity=1,\r\n flipHoriz=False, flipVert=False,\r\n texRes=128, interpolate=True, depth=0.0)\r\nRetaliationReminder = visual.TextStim(win=win, name='RetaliationReminder',\r\n text=\"Press '0' for NO shocks\\nPress '1' for ONE shock\\nPress '2' for TWO shocks\",\r\n font='Arial',\r\n pos=(0, -0.6), height=0.08, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=-1.0);\r\nShock0 = visual.ImageStim(\r\n win=win, name='Shock0',\r\n image='images/shock0.png', mask=None,\r\n ori=0, pos=(0, 0.5), size=(0.08, 0.1),\r\n color=[1, 1, 1], colorSpace='rgb', opacity=1,\r\n flipHoriz=False, flipVert=False,\r\n texRes=128, interpolate=True, depth=-3.0)\r\nShock1 = visual.ImageStim(\r\n win=win, name='Shock1',\r\n image='images/Shock1.png', mask=None,\r\n ori=0, pos=(0, 0.5), size=(0.08, 0.1),\r\n color=[1, 1, 1], colorSpace='rgb', opacity=1,\r\n flipHoriz=False, flipVert=False,\r\n texRes=128, interpolate=True, depth=-4.0)\r\nShock2 = visual.ImageStim(\r\n win=win, name='Shock2',\r\n image='images/Shock2.png', mask=None,\r\n ori=0, pos=(0, 0.5), size=(0.08, 0.1),\r\n color=[1, 1, 1], colorSpace='rgb', opacity=1,\r\n flipHoriz=False, flipVert=False,\r\n texRes=128, interpolate=True, depth=-5.0)\r\n\r\n# Initialize components for Routine \"EndScreen\"\r\nEndScreenClock = core.Clock()\r\nEndText = visual.TextStim(win=win, name='EndText',\r\n text='Thank you for participating\\n\\nPlease contact the researcher',\r\n font='Arial',\r\n pos=(0, 0), height=0.1, wrapWidth=None, ori=0,\r\n color='white', colorSpace='rgb', opacity=1,\r\n languageStyle='LTR',\r\n depth=0.0);\r\n\r\n# Create some handy timers\r\nglobalClock = core.Clock() # to track the time since experiment started\r\nroutineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine\r\n\r\n# ------Prepare to start Routine \"WelcomeScreen\"-------\r\nt = 0\r\nWelcomeScreenClock.reset() # clock\r\nframeN = -1\r\ncontinueRoutine = True\r\n# update component parameters for each repeat\r\nWelcomeContinue = event.BuilderKeyResponse()\r\n# keep track of which components have finished\r\nWelcomeScreenComponents = [WelcomeText, WelcomeContinue]\r\nfor thisComponent in WelcomeScreenComponents:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n# -------Start Routine \"WelcomeScreen\"-------\r\nwhile continueRoutine:\r\n # get current time\r\n t = WelcomeScreenClock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *WelcomeText* updates\r\n if t >= 0.0 and WelcomeText.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n WelcomeText.tStart = t\r\n WelcomeText.frameNStart = frameN # exact frame index\r\n WelcomeText.setAutoDraw(True)\r\n\r\n # *WelcomeContinue* updates\r\n if t >= 0.0 and WelcomeContinue.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n WelcomeContinue.tStart = t\r\n WelcomeContinue.frameNStart = frameN # exact frame index\r\n WelcomeContinue.status = STARTED\r\n # keyboard checking is just starting\r\n win.callOnFlip(WelcomeContinue.clock.reset) # t=0 on next screen flip\r\n event.clearEvents(eventType='keyboard')\r\n if WelcomeContinue.status == STARTED:\r\n theseKeys = event.getKeys(keyList=['space'])\r\n\r\n # check for quit:\r\n if \"escape\" in theseKeys:\r\n endExpNow = True\r\n if len(theseKeys) > 0: # at least one key was pressed\r\n WelcomeContinue.keys = theseKeys[-1] # just the last key pressed\r\n WelcomeContinue.rt = WelcomeContinue.clock.getTime()\r\n # a response ends the routine\r\n continueRoutine = False\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in WelcomeScreenComponents:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n# -------Ending Routine \"WelcomeScreen\"-------\r\nfor thisComponent in WelcomeScreenComponents:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n# check responses\r\nif WelcomeContinue.keys in ['', [], None]: # No response was made\r\n WelcomeContinue.keys = None\r\nthisExp.addData('WelcomeContinue.keys', WelcomeContinue.keys)\r\nif WelcomeContinue.keys != None: # we had a response\r\n thisExp.addData('WelcomeContinue.rt', WelcomeContinue.rt)\r\nthisExp.nextEntry()\r\n# the Routine \"WelcomeScreen\" was not non-slip safe, so reset the non-slip timer\r\nroutineTimer.reset()\r\n\r\n# ------Prepare to start Routine \"Blank500\"-------\r\nt = 0\r\nBlank500Clock.reset() # clock\r\nframeN = -1\r\ncontinueRoutine = True\r\nroutineTimer.add(0.500000)\r\n# update component parameters for each repeat\r\n# keep track of which components have finished\r\nBlank500Components = [BlankText]\r\nfor thisComponent in Blank500Components:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n# -------Start Routine \"Blank500\"-------\r\nwhile continueRoutine and routineTimer.getTime() > 0:\r\n # get current time\r\n t = Blank500Clock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *BlankText* updates\r\n if t >= 0.0 and BlankText.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n BlankText.tStart = t\r\n BlankText.frameNStart = frameN # exact frame index\r\n BlankText.setAutoDraw(True)\r\n frameRemains = 0.0 + 0.5 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if BlankText.status == STARTED and t >= frameRemains:\r\n BlankText.setAutoDraw(False)\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in Blank500Components:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n# -------Ending Routine \"Blank500\"-------\r\nfor thisComponent in Blank500Components:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n\r\n# ------Prepare to start Routine \"InstructionRetaliation\"-------\r\nt = 0\r\nInstructionRetaliationClock.reset() # clock\r\nframeN = -1\r\ncontinueRoutine = True\r\n# update component parameters for each repeat\r\nIRContinue = event.BuilderKeyResponse()\r\n# keep track of which components have finished\r\nInstructionRetaliationComponents = [IRText, IRContinue]\r\nfor thisComponent in InstructionRetaliationComponents:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n# -------Start Routine \"InstructionRetaliation\"-------\r\nwhile continueRoutine:\r\n # get current time\r\n t = InstructionRetaliationClock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *IRText* updates\r\n if t >= 0.0 and IRText.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n IRText.tStart = t\r\n IRText.frameNStart = frameN # exact frame index\r\n IRText.setAutoDraw(True)\r\n\r\n # *IRContinue* updates\r\n if t >= 0.0 and IRContinue.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n IRContinue.tStart = t\r\n IRContinue.frameNStart = frameN # exact frame index\r\n IRContinue.status = STARTED\r\n # keyboard checking is just starting\r\n win.callOnFlip(IRContinue.clock.reset) # t=0 on next screen flip\r\n event.clearEvents(eventType='keyboard')\r\n if IRContinue.status == STARTED:\r\n theseKeys = event.getKeys(keyList=['space'])\r\n\r\n # check for quit:\r\n if \"escape\" in theseKeys:\r\n endExpNow = True\r\n if len(theseKeys) > 0: # at least one key was pressed\r\n IRContinue.keys = theseKeys[-1] # just the last key pressed\r\n IRContinue.rt = IRContinue.clock.getTime()\r\n # a response ends the routine\r\n continueRoutine = False\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in InstructionRetaliationComponents:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n# -------Ending Routine \"InstructionRetaliation\"-------\r\nfor thisComponent in InstructionRetaliationComponents:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n# check responses\r\nif IRContinue.keys in ['', [], None]: # No response was made\r\n IRContinue.keys = None\r\nthisExp.addData('IRContinue.keys', IRContinue.keys)\r\nif IRContinue.keys != None: # we had a response\r\n thisExp.addData('IRContinue.rt', IRContinue.rt)\r\nthisExp.nextEntry()\r\n# the Routine \"InstructionRetaliation\" was not non-slip safe, so reset the non-slip timer\r\nroutineTimer.reset()\r\n\r\n# ------Prepare to start Routine \"Blank500\"-------\r\nt = 0\r\nBlank500Clock.reset() # clock\r\nframeN = -1\r\ncontinueRoutine = True\r\nroutineTimer.add(0.500000)\r\n# update component parameters for each repeat\r\n# keep track of which components have finished\r\nBlank500Components = [BlankText]\r\nfor thisComponent in Blank500Components:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n# -------Start Routine \"Blank500\"-------\r\nwhile continueRoutine and routineTimer.getTime() > 0:\r\n # get current time\r\n t = Blank500Clock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *BlankText* updates\r\n if t >= 0.0 and BlankText.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n BlankText.tStart = t\r\n BlankText.frameNStart = frameN # exact frame index\r\n BlankText.setAutoDraw(True)\r\n frameRemains = 0.0 + 0.5 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if BlankText.status == STARTED and t >= frameRemains:\r\n BlankText.setAutoDraw(False)\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in Blank500Components:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n# -------Ending Routine \"Blank500\"-------\r\nfor thisComponent in Blank500Components:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n\r\n# ------Prepare to start Routine \"RConnect\"-------\r\nt = 0\r\nRConnectClock.reset() # clock\r\nframeN = -1\r\ncontinueRoutine = True\r\nroutineTimer.add(8.000000)\r\n# update component parameters for each repeat\r\n# keep track of which components have finished\r\nRConnectComponents = [WaitingText, P1, P2, User, P4, P1G, P1R, P2G, P2R, UserG, P4G, P4R]\r\nfor thisComponent in RConnectComponents:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n# -------Start Routine \"RConnect\"-------\r\nwhile continueRoutine and routineTimer.getTime() > 0:\r\n # get current time\r\n t = RConnectClock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *WaitingText* updates\r\n if t >= 0.0 and WaitingText.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n WaitingText.tStart = t\r\n WaitingText.frameNStart = frameN # exact frame index\r\n WaitingText.setAutoDraw(True)\r\n frameRemains = 0.0 + 8 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if WaitingText.status == STARTED and t >= frameRemains:\r\n WaitingText.setAutoDraw(False)\r\n\r\n # *P1* updates\r\n if t >= 0.0 and P1.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P1.tStart = t\r\n P1.frameNStart = frameN # exact frame index\r\n P1.setAutoDraw(True)\r\n frameRemains = 0.0 + 8 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P1.status == STARTED and t >= frameRemains:\r\n P1.setAutoDraw(False)\r\n\r\n # *P2* updates\r\n if t >= 0.0 and P2.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P2.tStart = t\r\n P2.frameNStart = frameN # exact frame index\r\n P2.setAutoDraw(True)\r\n frameRemains = 0.0 + 8 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P2.status == STARTED and t >= frameRemains:\r\n P2.setAutoDraw(False)\r\n\r\n # *User* updates\r\n if t >= 0.0 and User.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n User.tStart = t\r\n User.frameNStart = frameN # exact frame index\r\n User.setAutoDraw(True)\r\n frameRemains = 0.0 + 8 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if User.status == STARTED and t >= frameRemains:\r\n User.setAutoDraw(False)\r\n\r\n # *P4* updates\r\n if t >= 0.0 and P4.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P4.tStart = t\r\n P4.frameNStart = frameN # exact frame index\r\n P4.setAutoDraw(True)\r\n frameRemains = 0.0 + 8 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P4.status == STARTED and t >= frameRemains:\r\n P4.setAutoDraw(False)\r\n\r\n # *P1G* updates\r\n if t >= 5.5 and P1G.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P1G.tStart = t\r\n P1G.frameNStart = frameN # exact frame index\r\n P1G.setAutoDraw(True)\r\n frameRemains = 5.5 + 2.5 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P1G.status == STARTED and t >= frameRemains:\r\n P1G.setAutoDraw(False)\r\n\r\n # *P1R* updates\r\n if t >= 0.0 and P1R.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P1R.tStart = t\r\n P1R.frameNStart = frameN # exact frame index\r\n P1R.setAutoDraw(True)\r\n frameRemains = 0.0 + 5.5 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P1R.status == STARTED and t >= frameRemains:\r\n P1R.setAutoDraw(False)\r\n\r\n # *P2G* updates\r\n if t >= 6 and P2G.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P2G.tStart = t\r\n P2G.frameNStart = frameN # exact frame index\r\n P2G.setAutoDraw(True)\r\n frameRemains = 6 + 2 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P2G.status == STARTED and t >= frameRemains:\r\n P2G.setAutoDraw(False)\r\n\r\n # *P2R* updates\r\n if t >= 0.0 and P2R.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P2R.tStart = t\r\n P2R.frameNStart = frameN # exact frame index\r\n P2R.setAutoDraw(True)\r\n frameRemains = 0.0 + 6 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P2R.status == STARTED and t >= frameRemains:\r\n P2R.setAutoDraw(False)\r\n\r\n # *UserG* updates\r\n if t >= 0.0 and UserG.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n UserG.tStart = t\r\n UserG.frameNStart = frameN # exact frame index\r\n UserG.setAutoDraw(True)\r\n frameRemains = 0.0 + 8 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if UserG.status == STARTED and t >= frameRemains:\r\n UserG.setAutoDraw(False)\r\n\r\n # *P4G* updates\r\n if t >= 2 and P4G.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P4G.tStart = t\r\n P4G.frameNStart = frameN # exact frame index\r\n P4G.setAutoDraw(True)\r\n frameRemains = 2 + 6 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P4G.status == STARTED and t >= frameRemains:\r\n P4G.setAutoDraw(False)\r\n\r\n # *P4R* updates\r\n if t >= 0.0 and P4R.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n P4R.tStart = t\r\n P4R.frameNStart = frameN # exact frame index\r\n P4R.setAutoDraw(True)\r\n frameRemains = 0.0 + 2 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if P4R.status == STARTED and t >= frameRemains:\r\n P4R.setAutoDraw(False)\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in RConnectComponents:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n# -------Ending Routine \"RConnect\"-------\r\nfor thisComponent in RConnectComponents:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n\r\n# set up handler to look after randomisation of conditions etc\r\nRetaliationLoop = data.TrialHandler(nReps=6, method='random',\r\n extraInfo=expInfo, originPath=-1,\r\n trialList=data.importConditions('ImageFiles.xlsx'),\r\n seed=None, name='RetaliationLoop')\r\nthisExp.addLoop(RetaliationLoop) # add the loop to the experiment\r\nthisRetaliationLoop = RetaliationLoop.trialList[0] # so we can initialise stimuli with some values\r\n# abbreviate parameter names if possible (e.g. rgb = thisRetaliationLoop.rgb)\r\nif thisRetaliationLoop != None:\r\n for paramName in thisRetaliationLoop:\r\n exec('{} = thisRetaliationLoop[paramName]'.format(paramName))\r\n\r\nfor thisRetaliationLoop in RetaliationLoop:\r\n currentLoop = RetaliationLoop\r\n # abbreviate parameter names if possible (e.g. rgb = thisRetaliationLoop.rgb)\r\n if thisRetaliationLoop != None:\r\n for paramName in thisRetaliationLoop:\r\n exec('{} = thisRetaliationLoop[paramName]'.format(paramName))\r\n\r\n # ------Prepare to start Routine \"Blank500\"-------\r\n t = 0\r\n Blank500Clock.reset() # clock\r\n frameN = -1\r\n continueRoutine = True\r\n routineTimer.add(0.500000)\r\n # update component parameters for each repeat\r\n # keep track of which components have finished\r\n Blank500Components = [BlankText]\r\n for thisComponent in Blank500Components:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n # -------Start Routine \"Blank500\"-------\r\n while continueRoutine and routineTimer.getTime() > 0:\r\n # get current time\r\n t = Blank500Clock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *BlankText* updates\r\n if t >= 0.0 and BlankText.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n BlankText.tStart = t\r\n BlankText.frameNStart = frameN # exact frame index\r\n BlankText.setAutoDraw(True)\r\n frameRemains = 0.0 + 0.5 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if BlankText.status == STARTED and t >= frameRemains:\r\n BlankText.setAutoDraw(False)\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in Blank500Components:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n # -------Ending Routine \"Blank500\"-------\r\n for thisComponent in Blank500Components:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n\r\n # ------Prepare to start Routine \"FixCross\"-------\r\n t = 0\r\n FixCrossClock.reset() # clock\r\n frameN = -1\r\n continueRoutine = True\r\n routineTimer.add(0.500000)\r\n # update component parameters for each repeat\r\n # keep track of which components have finished\r\n FixCrossComponents = [Cross]\r\n for thisComponent in FixCrossComponents:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n # -------Start Routine \"FixCross\"-------\r\n while continueRoutine and routineTimer.getTime() > 0:\r\n # get current time\r\n t = FixCrossClock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *Cross* updates\r\n if t >= 0.0 and Cross.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n Cross.tStart = t\r\n Cross.frameNStart = frameN # exact frame index\r\n Cross.setAutoDraw(True)\r\n frameRemains = 0.0 + 0.5 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if Cross.status == STARTED and t >= frameRemains:\r\n Cross.setAutoDraw(False)\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in FixCrossComponents:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n # -------Ending Routine \"FixCross\"-------\r\n for thisComponent in FixCrossComponents:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n\r\n # ------Prepare to start Routine \"Retaliation\"-------\r\n t = 0\r\n RetaliationClock.reset() # clock\r\n frameN = -1\r\n continueRoutine = True\r\n routineTimer.add(10.000000)\r\n # update component parameters for each repeat\r\n RetaliationImages.setImage(ImageFile)\r\n RetaliationKey = event.BuilderKeyResponse()\r\n Shock0.opacity = 0 # start shock0 invisible\r\n Shock1.opacity = 0 # start shock1 invisible\r\n Shock2.opacity = 0 # start shock2 invisible\r\n\r\n # keep track of which components have finished\r\n RetaliationComponents = [RetaliationImages, RetaliationReminder, RetaliationKey, Shock0, Shock1, Shock2]\r\n for thisComponent in RetaliationComponents:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n # -------Start Routine \"Retaliation\"-------\r\n while continueRoutine and routineTimer.getTime() > 0:\r\n # get current time\r\n t = RetaliationClock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *RetaliationImages* updates\r\n if t >= 0.75 and RetaliationImages.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n RetaliationImages.tStart = t\r\n RetaliationImages.frameNStart = frameN # exact frame index\r\n RetaliationImages.setAutoDraw(True)\r\n frameRemains = 0.75 + 9.25 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if RetaliationImages.status == STARTED and t >= frameRemains:\r\n RetaliationImages.setAutoDraw(False)\r\n\r\n # *RetaliationReminder* updates\r\n if t >= 0.6 and RetaliationReminder.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n RetaliationReminder.tStart = t\r\n RetaliationReminder.frameNStart = frameN # exact frame index\r\n RetaliationReminder.setAutoDraw(True)\r\n frameRemains = 0.6 + 9.4 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if RetaliationReminder.status == STARTED and t >= frameRemains:\r\n RetaliationReminder.setAutoDraw(False)\r\n\r\n # *RetaliationKey* updates\r\n if t >= 0.75 and RetaliationKey.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n RetaliationKey.tStart = t\r\n RetaliationKey.frameNStart = frameN # exact frame index\r\n RetaliationKey.status = STARTED\r\n # keyboard checking is just starting\r\n win.callOnFlip(RetaliationKey.clock.reset) # t=0 on next screen flip\r\n event.clearEvents(eventType='keyboard')\r\n frameRemains = 0.75 + 9.25 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if RetaliationKey.status == STARTED and t >= frameRemains:\r\n RetaliationKey.status = FINISHED\r\n if RetaliationKey.status == STARTED:\r\n theseKeys = event.getKeys(keyList=['num_0', 'num_1', 'num_2'])\r\n\r\n # check for quit:\r\n if \"escape\" in theseKeys:\r\n endExpNow = True\r\n if len(theseKeys) > 0: # at least one key was pressed\r\n RetaliationKey.keys = theseKeys[-1] # just the last key pressed\r\n RetaliationKey.rt = RetaliationKey.clock.getTime()\r\n\r\n # *Shock0* updates\r\n if t >= 0.0 and Shock0.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n Shock0.tStart = t\r\n Shock0.frameNStart = frameN # exact frame index\r\n Shock0.setAutoDraw(True)\r\n frameRemains = 0.0 + 10 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if Shock0.status == STARTED and t >= frameRemains:\r\n Shock0.setAutoDraw(False)\r\n\r\n # *Shock1* updates\r\n if t >= 0.0 and Shock1.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n Shock1.tStart = t\r\n Shock1.frameNStart = frameN # exact frame index\r\n Shock1.setAutoDraw(True)\r\n frameRemains = 0.0 + 10 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if Shock1.status == STARTED and t >= frameRemains:\r\n Shock1.setAutoDraw(False)\r\n\r\n # *Shock2* updates\r\n if t >= 0.0 and Shock2.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n Shock2.tStart = t\r\n Shock2.frameNStart = frameN # exact frame index\r\n Shock2.setAutoDraw(True)\r\n frameRemains = 0.0 + 10 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if Shock2.status == STARTED and t >= frameRemains:\r\n Shock2.setAutoDraw(False)\r\n if 'num_0' == RetaliationKey.keys: # if down key pushed,\r\n Shock0.opacity = 1.0 # make shock0 appear\r\n Shock1.opacity = 0 # make shock1 invisible\r\n Shock2.opacity = 0 # make shock2 invisible\r\n elif 'num_1' == RetaliationKey.keys: # if left key is pushed\r\n Shock1.opacity = 1.0 # make shock1 appear\r\n Shock0.opacity = 0 # make shock0 invisible\r\n Shock2.opacity = 0 # make shock2 invisible\r\n elif 'num_2' == RetaliationKey.keys: # if right key is pushed\r\n Shock2.opacity = 1.0 # make shock2 appear\r\n Shock0.opacity = 0 # make shock0 invisible\r\n Shock1.opacity = 0 # make shock1 invisible\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in RetaliationComponents:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n # -------Ending Routine \"Retaliation\"-------\r\n for thisComponent in RetaliationComponents:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n # check responses\r\n if RetaliationKey.keys in ['', [], None]: # No response was made\r\n RetaliationKey.keys = None\r\n RetaliationLoop.addData('RetaliationKey.keys', RetaliationKey.keys)\r\n if RetaliationKey.keys != None: # we had a response\r\n RetaliationLoop.addData('RetaliationKey.rt', RetaliationKey.rt)\r\n\r\n thisExp.nextEntry()\r\n\r\n# completed 6 repeats of 'RetaliationLoop'\r\n\r\n\r\n# ------Prepare to start Routine \"EndScreen\"-------\r\nt = 0\r\nEndScreenClock.reset() # clock\r\nframeN = -1\r\ncontinueRoutine = True\r\nroutineTimer.add(10.000000)\r\n# update component parameters for each repeat\r\n# keep track of which components have finished\r\nEndScreenComponents = [EndText]\r\nfor thisComponent in EndScreenComponents:\r\n if hasattr(thisComponent, 'status'):\r\n thisComponent.status = NOT_STARTED\r\n\r\n# -------Start Routine \"EndScreen\"-------\r\nwhile continueRoutine and routineTimer.getTime() > 0:\r\n # get current time\r\n t = EndScreenClock.getTime()\r\n frameN = frameN + 1 # number of completed frames (so 0 is the first frame)\r\n # update/draw components on each frame\r\n\r\n # *EndText* updates\r\n if t >= 0.0 and EndText.status == NOT_STARTED:\r\n # keep track of start time/frame for later\r\n EndText.tStart = t\r\n EndText.frameNStart = frameN # exact frame index\r\n EndText.setAutoDraw(True)\r\n frameRemains = 0.0 + 10 - win.monitorFramePeriod * 0.75 # most of one frame period left\r\n if EndText.status == STARTED and t >= frameRemains:\r\n EndText.setAutoDraw(False)\r\n\r\n # check for quit (typically the Esc key)\r\n if endExpNow or event.getKeys(keyList=[\"escape\"]):\r\n core.quit()\r\n\r\n # check if all components have finished\r\n if not continueRoutine: # a component has requested a forced-end of Routine\r\n break\r\n continueRoutine = False # will revert to True if at least one component still running\r\n for thisComponent in EndScreenComponents:\r\n if hasattr(thisComponent, \"status\") and thisComponent.status != FINISHED:\r\n continueRoutine = True\r\n break # at least one component has not yet finished\r\n\r\n # refresh the screen\r\n if continueRoutine: # don't flip if this routine is over or we'll get a blank screen\r\n win.flip()\r\n\r\n# -------Ending Routine \"EndScreen\"-------\r\nfor thisComponent in EndScreenComponents:\r\n if hasattr(thisComponent, \"setAutoDraw\"):\r\n thisComponent.setAutoDraw(False)\r\n\r\n# these shouldn't be strictly necessary (should auto-save)\r\nthisExp.saveAsWideText(filename + '.csv')\r\nthisExp.saveAsPickle(filename)\r\nlogging.flush()\r\n# make sure everything is closed down\r\nthisExp.abort() # or data files will save again on exit\r\nwin.close()\r\ncore.quit()\r\n","sub_path":"3 Phase Experiment Script/Phase 1-3.py","file_name":"Phase 1-3.py","file_ext":"py","file_size_in_byte":44413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"519728575","text":"import numpy as np\nimport matplotlib.pyplot as plt\ndef cantor(x,left_bound=0,right_bound=1,level=1,v_offset=0):\n division = (right_bound-left_bound)/3\n if level>50: return 1/2**level + v_offset\n if x < left_bound + division:\n return cantor(x,left_bound,left_bound+division,level+1,v_offset)\n elif x < left_bound + 2*division:\n return 1/2**level + v_offset\n else:\n return cantor(x,left_bound+2*division,right_bound,level+1,\n 1/2**level + v_offset)\n\nx = np.linspace(0,1,1000)\ny = x.copy()\nfor i in range(len(y)):\n y[i] = cantor(y[i])\nplt.plot(x,y)\nplt.show()\n1/2**100\n","sub_path":"Cantor.py","file_name":"Cantor.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"51893424","text":"# https://projecteuler.net/problem=14\nimport datetime\nstart_time = datetime.datetime.now()\n\n\n\ndef check_collatz(start):\n longest = 0\n for i in range(1, start+1):\n # count is 1 because integer 1 is inclusive to the chain\n count = 1\n seq = i\n # loop breaks when sequence gets to 1(end of collatz seq)\n while seq != 1:\n count += 1\n if seq % 2 == 0:\n seq /= 2\n else:\n seq = (seq*3) + 1\n # determines the max chain\n if count > longest:\n longest = count\n startnum = i\n # runtime status check\n print(i, count, (datetime.datetime.now()-start_time))\n return startnum, longest\n\n\nprint(check_collatz(1000000))\n","sub_path":"Level1/Problem14.py","file_name":"Problem14.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"527848759","text":"import os\n\n#set paths\ninPath = '{}/../../input/'.format(os.getcwd())\noutPath = '{}/../../output/'.format(os.getcwd())\nsourceDir = '{}maildir/'.format(inPath)\n\n\n#download the data\nurl = 'https://www.cs.cmu.edu/~enron/enron_mail_20150507.tar.gz'\nenronFile = os.path.basename(url)\nos.chdir(inPath)\n\nos.system('wget {}'.format(url))\n\n#unzip the data\nos.system('tar -xvzf {}'.format(enronFile))","sub_path":"code/orchestration/fetchAndUnzipData.py","file_name":"fetchAndUnzipData.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"54559303","text":"from django.shortcuts import render\nfrom .models import Searches\nfrom blog.models import Post\n\n\ndef blog_search_qs(request):\n query = request.GET.get('q', None) #q is the name in search form html\n \n user = None\n if request.user.is_authenticated:\n user = request.user\n context = {'query': query}\n if query is not None:\n searches = Searches.objects.create(user= user ,query=query)\n blog_list = Post.objects.search(query=query)\n context['blog_list'] = blog_list\n \n return render(request, 'searches/blog_search.html', context)\n","sub_path":"searches/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"194665990","text":"import json\nimport os\n\nimport requests\nimport xmltodict\n\nfrom common.settings import settings\n\nMOBILE_COMMONS_API_BASE = mobileCommonsApiBase = 'https://secure.mcommons.com/api/'\n\n\ndef post_to_mobile_commons(api_method, payload):\n url = mobileCommonsApiBase + api_method\n resp = requests.post(\n url,\n auth=(settings.mobile_commons_username(), settings.mobile_commons_password()),\n json=payload,\n )\n print(f'Response from MC {api_method}', resp.text[0:400])\n return resp\n\n\ndef send_sms(campaign_id, phone_number, message):\n try:\n payload = {\n 'campaign_id': campaign_id,\n 'phone_number': phone_number,\n 'body': message,\n }\n mobile_commons_response = post_to_mobile_commons('send_message', payload)\n except RuntimeError as e:\n print('Error posting to MC', e)\n\n\ndef profile_exists(phone_number):\n try:\n payload = {\n 'phone_number': phone_number,\n }\n mobile_commons_response = post_to_mobile_commons('profile', payload)\n d = xmltodict.parse(mobile_commons_response.text, attr_prefix='', cdata_key='value')\n return 'response' in d and 'success' in d['response'] and d['response']['success'] == 'true'\n except RuntimeError as e:\n print('Error posting to MC', e)\n\n\ndef create_or_update_mobile_commons_profile(payload):\n try:\n mobile_commons_response = post_to_mobile_commons('profile_update', payload)\n except RuntimeError as e:\n print('Error posting to MC creating profile', e)\n","sub_path":"common/mobile_commons.py","file_name":"mobile_commons.py","file_ext":"py","file_size_in_byte":1546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"433321447","text":"'''\r\nCreated on 10 Dec 2013\r\n\r\n@author: Nathan\r\n'''\r\n\r\nclass RepoDirectoryNames(object):\r\n '''\r\n Holds all the directory/folder names for the repo\r\n '''\r\n def __init__(self):\r\n self.names = {\"environments\":\"environments\", \r\n \"applications\":\"applications\",\r\n \"appgroups\":\"appgroups\",\r\n \"hosts\": \"hosts\",\r\n \"hostgroups\": \"hostgroups\",\r\n \"properties\":\"properties\",\r\n \"logs\":\"logs\",\r\n \"tmp\":\"tmp\"}\r\n \r\n def getDirName(self, name):\r\n return self.names[name]","sub_path":"src/Slave/RepoDirectoryNames.py","file_name":"RepoDirectoryNames.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"452039761","text":"from flask import Flask, request, jsonify\nfrom cloudevents.http import from_http\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s')\n\napp = Flask(__name__)\n@app.route('/', methods=['GET','POST'])\ndef echo():\n if request.method == 'GET':\n sc = 200\n msg = 'POST to this endpoint to echo cloud events'\n message = {\n 'status': sc,\n 'message': msg,\n }\n resp = jsonify(message)\n resp.status_code = sc\n return resp\n\n if request.method == 'POST':\n try:\n event = from_http(request.headers, request.get_data(),None)\n app.logger.info(event)\n return {}, 204\n except Exception as e:\n sc = 404\n msg = f'could not decode cloud event: {e}'\n app.logger.error(msg)\n message = {\n 'status': sc,\n 'error': msg,\n }\n resp = jsonify(message)\n resp.status_code = sc\n return resp\n\n# hint: run with FLASK_ENV=development FLASK_APP=handler.py flask run\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"97811107","text":"from pathlib import Path\n\ndef get_mycfg_dir() -> Path:\n import appdirs # type: ignore[import]\n import os\n # not sure if that's necessary, i.e. could rely on PYTHONPATH instead\n # on the other hand, by using MY_CONFIG we are guaranteed to load it from the desired path?\n mvar = os.environ.get('MY_CONFIG')\n if mvar is not None:\n mycfg_dir = Path(mvar)\n else:\n mycfg_dir = Path(appdirs.user_config_dir('my'))\n return mycfg_dir\n","sub_path":"my/core/preinit.py","file_name":"preinit.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"318945802","text":"# 用于读取Excel数据\n# encoding = utf - 8\nimport openpyxl\nfrom openpyxl.styles import Border, Side, Font\nimport time\n\n\nclass ParseExcel(object):\n\n def __init__(self):\n self.workbook = None\n self.excelFile = None\n self.font = Font(color=None) # 设置字体颜色\n # 颜色对应的RGB值\n self.RGBDict = {'red': 'FFFF3030',\n 'green': 'FF008B00'}\n\n def loadWorkBook(self, excelPathAndName):\n # 将Excle 文件加载到内存,并获取workbook对象\n try:\n self.workbook = openpyxl.load_workbook(excelPathAndName)\n except Exception as e:\n raise e\n self.excelFile = excelPathAndName\n return self.workbook\n\n def getSheetByName(self, sheetName):\n # 根据sheet名称获取sheet对象\n try:\n sheet = self.workbook.get_sheet_by_name(sheetName)\n return sheet\n except Exception as e:\n raise e\n\n def getSheetByIndex(self, sheetIndex):\n # 根据sheet的索引号获取sheet对象\n try:\n sheetname = self.workbook.get_sheet_names()[sheetIndex]\n except Exception as e:\n raise e\n sheet = self.workbook.get_sheet_by_name(sheetname)\n return sheet\n\n def getRowsNumber(self, sheet):\n # 获取sheet中数据的结束行号\n return sheet.max_row\n\n def getColsNumber(self, sheet):\n # 获取sheet有数据区域的结束的列号\n return sheet.max_column\n\n def getStarRowNumber(self, sheet):\n # 获取sheet中有数据区域的开始的行号\n return sheet.min_row\n\n def getStartColNumer(self, sheet):\n # 获取sheet 中有数据区域的的列号\n return sheet.min_column\n\n def getRow(self, sheet, rowNo):\n # 获取sheet中某一行,返回的事这一行所有的数据内容组成的tuple\n # 下标从1开始,sheet ,rows[1]表示第一行\n try:\n return list(sheet.rows)[rowNo - 1]\n except Exception as e:\n raise e\n\n def getColumn(self, sheet, colNo):\n # 获取sheet中某一列,返回的事这一列所有的数据内容组成tuple\n # 下标从1开始, sheet.rows[1]表示第一行\n try:\n return list(sheet.columns)[colNo - 1]\n except Exception as e:\n raise e\n\n def getCollOfValue(self, sheet, coordinate=None,\n rowNo=None, colsNo=None):\n # 根据单元格所在的位置索引获取该单元格中的值,从下标1开始,\n # sheet.cell(row = 1,column =1 ).value,表示excel中第一行第一列值\n if coordinate != None:\n try:\n return sheet.cell(coordinate=coordinate).value\n except Exception as e:\n raise e\n elif coordinate is None and rowNo is not None and colsNo is not None:\n try:\n return sheet.cell(row=rowNo, column=colsNo).value\n except Exception as e:\n raise e\n else:\n raise Exception(\"Insufficient Coordinates of cell!\")\n\n def getCellOfObject(self, sheet, coordinate=None,\n rowNo=None, colsNo=None):\n # 获取某个单元格的对象,可以根据单元格所在未知的数字索引,\n # 也可以直接根据Excel中单元格的编码及坐标\n # 如getCellObject(sheet,coordinate = 'A1' )or getCell0fbject(self,sheet,rowNo = 1,colsNo =2 )\n\n if coordinate != None:\n try:\n return sheet.cell(coordinate=coordinate)\n except Exception as e:\n raise e\n elif coordinate == None and rowNo is not None and colsNo is not None:\n try:\n return sheet.cell(row=rowNo, column=colsNo)\n except Exception as e:\n raise e\n\n else:\n raise Exception(\"Issufficient Coordinates of ecll!\")\n\n def writCell(self, sheet, content, coordinate=None,\n rowNo=None, colsNo=None, style=None):\n # 根据单元格在Eecel中的编码坐标或者数字索引坐标单元格中写入数据\n # 下标从1开始,参数style表示字体的颜色的名字,比如red,green\n if coordinate is not None:\n try:\n sheet.cell(coordinate=coordinate).value = content\n if style is not None:\n sheet.cell(coordinate=coordinate). \\\n font = Font(color=self.RGBDict[style])\n self.workbook.save(self.excelFile)\n except Exception as e:\n raise e\n elif coordinate == None and rowNo is not None and colsNo is not None:\n try:\n sheet.cell(row=rowNo, column=colsNo).value = content\n if style:\n sheet.cell(row=rowNo, column=colsNo). \\\n font = Font(color=self.RGBDict[style])\n self.workbook.save(self.excelFile)\n except Exception as e:\n raise e\n else:\n raise Exception(\"Insufficient Coordinates of cell\")\n\n def writeCellCurrentTime(self, sheet, coordinate=None, rowNo=None, colsNo=None):\n # 写入当前的时间,下标从1开始\n now = int(time.time()) # 显示为时间戳\n timeArray = time.localtime(now)\n currentTime = time.strftime(\"%Y-%m-%d %H:%M:%S\", timeArray)\n if coordinate is not None:\n try:\n sheet.cell(coordinate=coordinate).value = currentTime\n self.workbook.save(self.excelFile)\n except Exception as e:\n raise e\n elif coordinate == None and rowNo is not None and colsNo is not None:\n try:\n sheet.cell(row=rowNo, column=colsNo).value = currentTime\n self.workbook.save(self.excelFile)\n except Exception as e:\n raise e\n else:\n raise Exception(\"Insufficient Coordinates of cell。。。!\")\n\n\nif __name__ == '__main__':\n pe = ParseExcel()\n # 测试所用的Excel 文件“126邮箱 联系人。xlsx 请自行创建\n pe.loadWorkBook(r\"G:\\KeyWordFromeWork\\testData\\126邮箱发送邮件.xlsx\")\n\n print(\"通过名称获取sheet对象的名字:\", pe.getSheetByName(\"登录\").title)\n print(\"通过index序号获取sheet对象的名字:\", pe.getSheetByIndex(1).title)\n sheet = pe.getSheetByIndex(1)\n print(type(sheet))\n print(pe.getRowsNumber(sheet)) # 获取最大行号\n print(pe.getColsNumber(sheet)) # 获取最大列号\n rows = pe.getRow(sheet, 1) # 获取第一行\n for i in rows:\n print(i.value)\n # # 获取第一行第一列单元格内容\n print(pe.getCollOfValue(sheet, rowNo=1, colsNo=1))\n print(pe.getCollOfValue(sheet, rowNo=1, colsNo=5))\n # for i, in pe.getSheetByIndex(2).title:\n # print(i,end='')\n # print(pe.getRowsNumber(sheet))\n # pe.writCell(sheet, \"我爱祖国\", rowNo=10, colsNo=10)\n # pe.writeCellCurrentTime(sheet, rowNo=10, colsNo=11)\n\n# p = ParseExcel()\n# p.loadWorkBook(r\"G:\\KeyWordFromeWork\\testData\\126邮箱联系人.xlsx\")\n# s = p.getSheetByIndex(0)\n# print(p.getRowsNumber(s))\n","sub_path":"util/ParseExcel.py","file_name":"ParseExcel.py","file_ext":"py","file_size_in_byte":7224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"527265935","text":"\"\"\"\n * Copyright 2020, Departamento de sistemas y Computación\n * Universidad de Los Andes\n *\n *\n * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos\n *\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n \"\"\"\n\nimport sys\n\nimport config\nfrom App import controller\n\nassert config\n\n\"\"\"\nLa vista se encarga de la interacción con el usuario.\nPresenta el menu de opciones y por cada seleccion\nhace la solicitud al controlador para ejecutar la\noperación seleccionada.\n\"\"\"\n\n# ___________________________________________________\n# Ruta a los archivos\n# ___________________________________________________\n\n\naccfile = \"us_accidents_small.csv\"\n\n# ___________________________________________________\n# Menu principal\n# ___________________________________________________\n\n\ndef printMenu():\n print(\"\\n\")\n print(\"*******************************************\")\n print(\"Bienvenido\")\n print(\"1- Inicializar Analizador\")\n print(\"2- Cargar información de accidentes\")\n print(\"3- Requerimento 1 (Conocer los accidentes en una fecha)\")\n print(\"4- Requerimento 2 (Conocer los accidentes anteriores a una fecha)\")\n print(\"5- Requerimento 3 (Conocer los accidentes en un rango de fechas)\")\n print(\"6- Requerimento 4 (Conocer el estado con mas accidentes)\")\n print(\"7- Requerimento 5 (Conocer los accidentes por rango de horas)\")\n print(\"8- Requerimento 6 (Conocer la zona geográfica mas accidentada)\")\n print(\"0- Salir\")\n print(\"*******************************************\")\n\n\n\"\"\"\nMenu principal\n\"\"\"\nwhile True:\n printMenu()\n inputs = input(\"Seleccione una opción para continuar\\n>\")\n if inputs == \"\":\n print(\"Opción no válida...\")\n continue\n if int(inputs[0]) == 1:\n print(\"\\nInicializando....\")\n # cont es el controlador que se usará de acá en adelante\n cont = controller.init()\n\n elif int(inputs[0]) == 2:\n print(\"\\nCargando información de accidentes ....\")\n controller.loadData(cont, accfile)\n print(\"Crimenes cargados: \" + str(controller.crimesSize(cont)))\n print(\"Altura del arbol: \" + str(controller.indexHeight(cont)))\n print(\"Elementos en el arbol: \" + str(controller.indexSize(cont)))\n print(\"Menor Llave: \" + str(controller.minKey(cont)))\n print(\"Mayor Llave: \" + str(controller.maxKey(cont)))\n\n elif int(inputs[0]) == 3:\n print(\"\\nRequerimiento No 1 del reto 3: \\n\")\n impDate = input(\n \"Digite la fecha de interés; recuerde que el formato de la fecha debe ser:\\n\\tYYYY-MM-DD\\n\\t\"\n )\n print(\n f\"Ocurrieron {controller.total_accidentes(cont, impDate, next_day=True)} accidentes en la fecha {impDate}\"\n )\n\n elif int(inputs[0]) == 4:\n print(\"\\nRequerimiento No 2 del reto 3: \\n\")\n finalDate = input(\n \"Digite la fecha final; recuerde que el formato de la fecha debe ser:\\n\\tYYYY-MM-DD\\n\\t\"\n )\n print(\n f\"Ocurrieron {controller.total_accidentes(cont, finalDate, from_begining=True)} accidentes entre la fecha inicial (primera fecha con registro) y la fecha {finalDate}\"\n )\n\n elif int(inputs[0]) == 5:\n print(\"\\nRequerimiento No 3 del reto 3: \\n\")\n initialDate = input(\n \"Digite la fecha inicial; recuerde que el formato de la fecha debe ser:\\n\\tYYYY-MM-DD\\n\\t\"\n )\n finalDate = input(\n \"Digite la fecha final; recuerde que el formato de la fecha debe ser:\\n\\tYYYY-MM-DD\\n\\t\"\n )\n print(\n f\"Ocurrieron {controller.total_accidentes(cont, initialDate, finalDate)} accidentes entre la fecha {initialDate} y la fecha {finalDate}\"\n )\n\n elif int(inputs[0]) == 6:\n print(\"\\nRequerimiento No 4 del reto 3: \\n\")\n fechaIni = input(\n \"Digite la fecha inicial, recuerde que el formato de la fecha debe ser:\\n\\tYYYY-MM-DD\\n\\t\"\n )\n fechaFin = input(\n \"Digite la fecha final, recuerde que el formato de la fecha debe ser:\\n\\tYYYY-MM-DD\\n\\t\"\n )\n print(\n f\"El estado y la fecha con más accidentes fueron: {controller.R4_EstadoMasAcc(cont, fechaIni, fechaFin)} entre la fecha {fechaIni} y la fecha {fechaFin}\"\n )\n\n elif int(inputs[0]) == 7:\n print(\"\\nRequerimiento No 5 del reto 3: \\n\")\n\n initial_hour = input(\n \"Digite la hora inicial, recuerde que el formato de la fecha debe ser de 24 horas\\n\\tHH:MM:SS\\n\\t\"\n )\n final_hour = input(\n \"Digite la hora inicial, recuerde que el formato de la fecha debe ser de 24 horas\\n\\tHH:MM:SS\\n\\t\"\n )\n \n print(f\"{controller.total_horas(cont, initial_hour, final_hour)}\")\n\n elif int(inputs[0]) == 8:\n print(\"\\nRequerimiento No 6 del reto 3: \\n\")\n latitude = float(input(\"Digite la LATITUD del punto central:\\n\\t\"))\n longitude = float(input(\"Digite la LONGITUD del punto central:\\n\\t\"))\n ratio = float(\n input(\n \"Digite el RADIO (en millas) alrededor del centro establecido;\\nTenga en cuenta que aproximadamente 1° = 69.4 millas:\\n\\t\"\n )\n )\n ans = controller.R6(cont, latitude, longitude, ratio)\n print(\n f\"El día en el que más se presentaron casos dentro del rango fue un {ans[0]}.\\nEn total ocurrieron {ans[1]} casos dentro del rango.\"\n )\n\n else:\n sys.exit(0)\nsys.exit(0)\n","sub_path":"App/view.py","file_name":"view.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"434644691","text":"from mechanics.damage import DamageTypes\nfrom character.masteries import MasteriesEnum\n\nfrom mechanics.chances.CritHitGrazeMiss import ImpactChances\n\nbaseline_chances = ImpactChances(0.05, 0.35, 0.5)\n\ndef chances_price(chances: ImpactChances):\n\n crit_awesomeness = 0.2 + chances.crit / baseline_chances.crit\n hit_awesomeness = 0.2 + chances.hit / baseline_chances.hit\n graze_awesomeness = 0.2 + chances.crit / baseline_chances.graze\n\n return (crit_awesomeness * 2 + hit_awesomeness ** 5 + graze_awesomeness ** 5) / 5\n\n\n\nclass WeaponType:\n def __init__(self, damage_type, mastery, chances, damage_factor=1., atb_factor=1., cost_factor=1):\n self.damage_type = damage_type\n self.mastery = mastery\n self.chances = chances\n self.damage_factor = damage_factor\n self.atb_factor = atb_factor\n\n self.cost_factor = cost_factor * chances_price(chances) * ( 1 + damage_factor ** 2 / (atb_factor** (2/3) )) / 2\n\n\nd = DamageTypes\nm = MasteriesEnum\n\nclass WeaponTypes:\n AXE = WeaponType(d.SLASH, m.AXE, ImpactChances(0.05, 0.3, 0.7), damage_factor=1.3, atb_factor=1.6)\n SWORD = WeaponType(d.SLASH, m.SWORD, ImpactChances(0.05, 0.4, 0.5))\n DAGGER = WeaponType(d.PIERCE, m.DAGGER, ImpactChances(0.10, 0.3, 0.2), damage_factor=0.7, atb_factor=0.45)\n SPEAR = WeaponType(d.PIERCE, m.SPEAR, ImpactChances(0.05, 0.4, 0.5))\n HAMMER = WeaponType(d.CRUSH, m.HAMMER, ImpactChances(0.1, 0.35, 0.25), damage_factor=1.5, atb_factor=2.1)\n CLUB = WeaponType(d.CRUSH, m.CLUB, ImpactChances(0.07, 0.37, 0.47))\n\n BOW = WeaponType(d.PIERCE, m.BOW, ImpactChances(0.02, 0.25, 0.25), cost_factor=3)\n CROSSBOW = WeaponType(d.PIERCE, m.SHOOT, ImpactChances(0.02, 0.25, 0.25), damage_factor=1.5, atb_factor=2.1, cost_factor=3)\n\n\nif __name__ == \"__main__\":\n wts = WeaponTypes\n for wt in [wts.AXE, wts.SWORD, wts.DAGGER, wts.SPEAR, wts.HAMMER, wts.CLUB, wts.BOW, wts.CROSSBOW]:\n print(wt.cost_factor)","sub_path":"game_objects/items/blueprints/types/WeaponTypes.py","file_name":"WeaponTypes.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"309992018","text":"# multiAgents.py\n# --------------\n# Licensing Information: You are free to use or extend these projects for\n# educational purposes provided that (1) you do not distribute or publish\n# solutions, (2) you retain this notice, and (3) you provide clear\n# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.\n#\n# Attribution Information: The Pacman AI projects were developed at UC Berkeley.\n# The core projects and autograders were primarily created by John DeNero\n# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).\n# Student side autograding was added by Brad Miller, Nick Hay, and\n# Pieter Abbeel (pabbeel@cs.berkeley.edu).\n\n\nfrom util import manhattanDistance\nfrom game import Directions\nimport random, util\nimport math\n\nfrom game import Agent\n\nclass ReflexAgent(Agent):\n \"\"\"\n A reflex agent chooses an action at each choice point by examining\n its alternatives via a state evaluation function.\n\n The code below is provided as a guide. You are welcome to change\n it in any way you see fit, so long as you don't touch our method\n headers.\n \"\"\"\n\n\n def getAction(self, gameState):\n \"\"\"\n You do not need to change this method, but you're welcome to.\n\n getAction chooses among the best options according to the evaluation function.\n\n Just like in the previous project, getAction takes a GameState and returns\n some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}\n \"\"\"\n # Collect legal moves and successor states\n legalMoves = gameState.getLegalActions()\n\n # Choose one of the best actions\n scores = [self.evaluationFunction(gameState, action) for action in legalMoves]\n bestScore = max(scores)\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = random.choice(bestIndices) # Pick randomly among the best\n\n \"Add more of your code here if you want to\"\n #returns a best action, as determined by applying evaluationFunction on all legal actions\n return legalMoves[chosenIndex]\n\n def evaluationFunction(self, currentGameState, action):\n \"\"\"\n Design a better evaluation function here.\n\n The evaluation function takes in the current and proposed successor\n GameStates (pacman.py) and returns a number, where higher numbers are better.\n\n The code below extracts some useful information from the state, like the\n remaining food (newFood) and Pacman position after moving (newPos).\n newScaredTimes holds the number of moves that each ghost will remain\n scared because of Pacman having eaten a power pellet.\n\n Print out these variables to see what you're getting, then combine them\n to create a masterful evaluation function.\n \"\"\"\n # Useful information you can extract from a GameState (pacman.py)\n successorGameState = currentGameState.generatePacmanSuccessor(action)\n newPos = successorGameState.getPacmanPosition()\n newFood = successorGameState.getFood()\n newGhostStates = successorGameState.getGhostStates() #the list of ghost agentstates, each has functions such as getPosition and getDirection\n newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]\n \"*** YOUR CODE HERE ***\"\n #brainstorming: implementations taking different factors into account, in order of increasing difficulty:\n #1) collects nearest food\n #2) weight a move based on a sum of the number of foods it brings closer to pacman with exponentially heavier weights depending on\n # the proximity to pacman, minus [something equivalent for the foods that become farther away] * [some constant c<1]\n #3) take ghost positions into account: weight each ghost with exponentially heavier weights depending on proximity to pacman (ideally with\n # a higher exponent than is used for foods). negative value if action takes pacman closer to ghost, positive if takes away from ghost.\n ###########################\n #mazeDistance calc stuff\n ###########################\n def manhattanDistance(point1, point2):\n x1, x2 = point1\n y1, y2 = point2\n return (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)\n def mazeDistance(point1, point2):\n return len(bfs(point1, point2))\n def bfs(start, goal):\n from util import Queue\n q = Queue()\n explored = set()\n q.push((start, []))\n while not q.isEmpty():\n popped = q.pop()\n if popped[0] in explored:\n continue\n explored.add(popped[0])\n if popped[0] == goal:\n return popped[1]\n for successor in getSuccessors(popped[0]):\n if successor[0] not in explored:\n #push successor, where actions and cost are cumulative on its parent (popped)\n q.push((successor[0], popped[1] + [successor[1]]))\n return popped[1]\n\n def getSuccessors(position):\n from game import Actions\n successors = []\n for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:\n x,y = position\n dx, dy = Actions.directionToVector(action)\n nextx, nexty = int(x + dx), int(y + dy)\n walls = successorGameState.getWalls()\n if not walls[nextx][nexty]:\n nextState = (nextx, nexty)\n successors.append((nextState, action))\n return successors\n ###########################\n #mazeDistance calc stuff\n ###########################\n\n\n\n ###########################\n #food stuff\n ###########################\n oldPos = currentGameState.getPacmanPosition()\n oldFood = currentGameState.getFood()\n w = oldFood.width\n h = oldFood.height\n mazeSize = math.sqrt(w*w + h*h)\n closerF = [] #list of distances from newPos to food for the foods that become closer after action. each distance is in a tuple also containing the foods coords\n fartherF = [] #become farther\n for i in range(w):\n for j in range(h):\n if oldFood[i][j]: #theres a food at (i,j) in oldfood, implying theres a food in newfood, apart from in the following edge case\n if not newFood[i][j]: #this would mean we just ate the food at (i,j)\n #print(\"(should be true) we ate food! \", newPos == (i, j))\n closerF.append((.7, (i, j))) #for the sake of calculations we equate eating a food to having a food only .7 distance away from pacman\n continue\n oldDist = mazeDistance(oldPos, (i, j))\n newDist = mazeDistance(newPos, (i, j))\n if oldDist > newDist:\n closerF.append((newDist, (i, j)))\n if oldDist < newDist:\n fartherF.append((newDist, (i, j)))\n ###########################\n #food stuff\n ###########################\n\n\n\n ###########################\n #ghost stuff\n ###########################\n closerG = [] #list of distances to ghosts that become closer\n fartherG = [] #become farther\n ghostPositions = []\n for i in range(len(newGhostStates)):\n x,y = newGhostStates[i].getPosition()\n ghostPositions.append((int(x), int(y)))\n for i in range(len(newGhostStates)):\n if newPos == ghostPositions[i]: #we run into a ghost\n closerG.append((0.001, newGhostStates[i]))\n continue\n oldDist = mazeDistance(oldPos, ghostPositions[i])\n newDist = mazeDistance(newPos, ghostPositions[i])\n if oldDist > newDist:\n closerG.append((newDist, newGhostStates[i]))\n if oldDist < newDist:\n fartherG.append((newDist, newGhostStates[i]))\n ###########################\n #ghost stuff\n ###########################\n\n\n\n ###########################\n #corner stuff\n ###########################\n corners = [(w,1), (w,h), (1,h), (1,1)]\n x,y = int(newPos[0]), int(newPos[1])\n closest = math.sqrt(manhattanDistance((1,1), (x,y))) #dist from (1,1)\n index = 3 #len(corners) - 1\n for i in range(len(corners) - 1): #closest already set to dist from (1,1), so we only iterate over len - 1\n c = corners[i]\n manhattanD = math.sqrt(manhattanDistance(c, (x,y)))\n if manhattanD < closest:\n closest = manhattanD\n index = i\n pnc = corners[index] #there was a shorter way to do this based on looking at newPos coords vs w/2 and h/2....\n\n def pncManhattanDist(tuple):\n d = math.sqrt(manhattanDistance(tuple, pnc)) #manhattan distance to pnc\n if d > mazeSize/2: #if d is greater than half the grids hypotenuse\n return -1\n #else, it is in the same quadrant as pacman. we'll value the food more for smaller d\n if d == 0:\n return 0.5\n return d\n ###########################\n #corner stuff\n ###########################\n\n\n\n ###########################\n #score calc stuff\n ###########################\n wallsNum = 0\n wallGrid = successorGameState.getWalls()\n for i in range(wallGrid.width): #apparently the same value as w\n for j in range(wallGrid.height):\n if wallGrid[i][j]:\n wallsNum += 1\n initialFood = wallGrid.width*wallGrid.height - wallsNum - (wallGrid.height-2)\n foodLeft = currentGameState.getNumFood()\n foodleftMultiplier = min(1, initialFood/foodLeft/4)\n closerFoodScore = 0\n fartherFoodScore = 0\n if foodLeft == 0:\n foodLeft = 0.5\n for x in closerF:\n dist, coords = x[0], x[1]\n n = pncManhattanDist(coords)\n cornerMultiplier = 1\n if n > 0:\n cornerMultiplier = min(1, mazeSize/2/n / 4)\n val = 1/dist/dist*foodleftMultiplier*cornerMultiplier\n closerFoodScore += val\n\n \"\"\"\"\n for x in fartherF:\n dist, coords = x[0], x[1]\n n = pncManhattanDist(coords)\n cornerMultiplier = 1\n if n > 0:\n cornerMultiplier = min(1, mazeSize/2/n / 4)\n val = 1/dist/dist*foodleftMultiplier*cornerMultiplier\n fartherFoodScore += val\n \"\"\"\n ghostScore = 0\n nearestScared = None\n for ghost in closerG: #find nearest scared ghost\n if ghost[1].scaredTimer > 0:\n if not nearestScared:\n nearestScared = ghost\n if ghost[0] < nearestScared[0]:\n nearestScared = ghost\n\n for ghost in closerG: #tuple of dist to newPos and the ghost object\n val = 1/ghost[0]**(3)\n if ghost[1].scaredTimer == 0:\n if not nearestScared:\n ghostScore -= val\n continue\n if ghost[0] < nearestScared[0]:\n print(\"asdf\")\n ghostScore -= val**(1/3)*nearestScared[0]/ghost[0] #if ghost is closer than nearestScared, lets make moving towards ghost much more costly. more costly if neared scared if far, more costly if brave ghost is close\n\n if ghost[1].scaredTimer > 0:\n if ghost[0] == 1:\n ghostScore += math.sqrt(val)*(ghost[1].scaredTimer + 40)**3 #go in for the kill\n difference = ghost[1].scaredTimer - ghost[0]\n if difference >= 0:\n ghostScore += math.sqrt(val)*(ghost[1].scaredTimer + 40)*(difference+1)**2\n ghostScore += math.sqrt(val)*ghost[1].scaredTimer\n\n for ghost in fartherG:\n val = 1/ghost[0]**(3)\n ghostScore += val\n\n #stop will always return 0 since oldDist == newDist always, so closer and farther lists remain empty\n return ghostScore + closerFoodScore #we no longer subtract fartherFoodScore/2, it doesnt seem beneficial\n \"\"\"\n capsules = currentGameState.getCapsules()\n closeCapDist = mazeDistance(newPos, capsules[len(capsules) - 1]) #initialize with last capsule in list\n index = len(capsules) - 1\n oneAway = False\n for i in range(len(capsules) - 1):\n dist = mazeDistance(newPos, capsules[i])\n if dist < closeCapDist:\n closeCapDist = dist\n index = i\n if closeCapDist == 1:\n oneAway = True\n closestCap = capsules[index]\n\n\n #calculate (mazeDistance/2)**2/distance**4 for each ghost to closestcap, sum it, and mult by number of ghosts (number of ghosts is kindof to the power of 2-- its like we take the average distance for all ghosts and mult by num of ghosts squared)\n #divide by ourdistance to closestcap\n capsuleScore = 0\n for ghost in ghostPositions:\n capsuleScore += 1/mazeDistance(ghost, closestCap)**3\n numOfGhosts = len(ghostPositions)\n capsuleScore *= mazeSize/2numOfGhosts/mazeDistance(newPos, closestCap) #the mazeSize/2 at the front was chosen pretty arbitrarily, just to make capsulescore a bit bigger\n #if the action makes us eat a food and brings us to newPos thats one away from capsule, we make capsulescore super important\n #capsuleScore *= (mazeSize/2)**\n #if oneaway capsuleScore is some large negative value if we go closer, unless our current capsulescore is really good, then we pump it up super high\n oldDist = mazeDistance(oldPos, closestCap)\n newDist = mazeDistance(newPos, closestCap)\n #if oneAway\n #if oldDist == newDist:\n # capsuleScore = 0\n #if oldDist < newDist:\n # capsuleScore = -1*capsuleScore/numOfGhosts\n\n print(ghostScore, closerFoodScore, capsuleScore)\n \"\"\"\n\ndef scoreEvaluationFunction(currentGameState):\n \"\"\"\n This default evaluation function just returns the score of the state.\n The score is the same one displayed in the Pacman GUI.\n\n This evaluation function is meant for use with adversarial search agents\n (not reflex agents).\n \"\"\"\n return currentGameState.getScore()\n\nclass MultiAgentSearchAgent(Agent):\n \"\"\"\n This class provides some common elements to all of your\n multi-agent searchers. Any methods defined here will be available\n to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.\n\n You *do not* need to make any changes here, but you can if you want to\n add functionality to all your adversarial search agents. Please do not\n remove anything, however.\n\n Note: this is an abstract class: one that should not be instantiated. It's\n only partially specified, and designed to be extended. Agent (game.py)\n is another abstract class.\n \"\"\"\n\n def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'):\n self.index = 0 # Pacman is always agent index 0\n self.evaluationFunction = util.lookup(evalFn, globals())\n self.depth = int(depth)\n\nclass MinimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent (question 2)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action from the current gameState using self.depth\n and self.evaluationFunction.\n\n Here are some method calls that might be useful when implementing minimax.\n\n gameState.getLegalActions(agentIndex):\n Returns a list of legal actions for an agent\n agentIndex=0 means Pacman, ghosts are >= 1\n\n gameState.generateSuccessor(agentIndex, action):\n Returns the successor game state after an agent takes an action\n\n gameState.getNumAgents():\n Returns the total number of agents in the game\n\n gameState.isWin():\n Returns whether or not the game state is a winning state\n\n gameState.isLose():\n Returns whether or not the game state is a losing state\n \"\"\"\n \"*** YOUR CODE HERE\"\n \"\"\"\n def maxVal(state, agentCount, depth):\n if depth == 0 or state.isLose() or state.isWin():\n return self.evaluationFunction(state)\n value = -69000\n legalMoves = state.getLegalActions()\n for action in legalMoves:\n value = max(value, minVal(state.generateSuccessor(0, action), 1, agentCount, depth-1))\n return value\n\n def minVal(state, ghostIndex, agentCount, depth):\n value = 6969\n if depth == 0 or state.isLose() or state.isWin():\n return self.evaluationFunction(state)\n legalMoves = state.getLegalActions(ghostIndex)\n if ghostIndex == agentCount - 1: #we've come to the last ghost-- its time to decrease depth and go back to moving pacman\n for action in legalMoves:\n value = min(value, maxVal(state.generateSuccessor(ghostIndex, action), agentCount, depth-1))\n return value\n for action in legalMoves:\n value = min(value, minVal(state.generateSuccessor(ghostIndex, action), ghostIndex+1, agentCount, depth))\n return value\n\n legalMoves = gameState.getLegalActions()\n agentCount = gameState.getNumAgents()\n previous = -699999\n best = None\n for action in legalMoves:\n score = minVal(gameState.generateSuccessor(0, action), 1, agentCount, self.depth)\n if score > previous:\n best = action;\n previous = score\n return best\n \"\"\"\n #above method not expanding right number of nodes... another attempt:\n def minimax(state, agentIndex, action, depth):\n agentCount = state.getNumAgents()\n if state.isLose() or state.isWin() or depth == 0:\n return (action, self.evaluationFunction(state))\n if agentIndex == 0:\n bestMove = (None, -69)\n for legalAction in state.getLegalActions(agentIndex):\n if depth == self.depth*agentCount:\n next = legalAction\n else:\n next = action\n currentMove = minimax(state.generateSuccessor(agentIndex, legalAction), (agentIndex + 1) % agentCount, next, depth - 1)\n if currentMove[1] > bestMove[1]:\n bestMove = currentMove\n return bestMove\n else:\n bestAction = (None, 69000)\n for legalAction in state.getLegalActions(agentIndex):\n currentMove = minimax(state.generateSuccessor(agentIndex, legalAction), (agentIndex + 1) % agentCount, action, depth - 1)\n if currentMove[1] < bestAction[1]:\n bestAction = currentMove\n return bestAction\n return minimax(gameState, 0, Directions.STOP, gameState.getNumAgents()*self.depth)[0]\n\nclass AlphaBetaAgent(MultiAgentSearchAgent):\n \"\"\"\n Your minimax agent with alpha-beta pruning (question 3)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the minimax action using self.depth and self.evaluationFunction\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n \"\"\"\n def alphaBeta(gameState, action, depth, agentIndex, alpha, beta):\n if gameState.isLose() or gameState.isWin() or depth == 0:\n return (action, self.evaluationFunction(gameState))\n if agentIndex == 0:\n bestAction = (action, alpha)\n for legalAction in gameState.getLegalActions(agentIndex):\n currAction = alphaBeta(gameState.generateSuccessor(agentIndex, legalAction), (legalAction if depth is self.depth*gameState.getNumAgents() else action), depth - 1, 1, alpha, beta)\n if currAction[1] > bestAction[1]:\n bestAction = currAction\n if bestAction[1] > alpha:\n break\n return bestAction\n else:\n bestAction = (Directions.STOP, beta)\n for legalAction in gameState.getLegalActions(agentIndex):\n currAction = alphaBeta(gameState.generateSuccessor(agentIndex, legalAction), action, depth - 1, (agentIndex + 1) % gameState.getNumAgents(), alpha, beta)\n if currAction[1] < bestAction[1]:\n bestAction = currAction\n if bestAction[1] < beta:\n break\n return bestAction\n return alphaBeta(gameState, Directions.STOP, self.depth*gameState.getNumAgents(), 0, -999999, 999999)[0]\n \"\"\"\n evaluationFunc = self.evaluationFunction\n\n # numOfAgents = gameState.getNumAgents()\n # numOfGhosts = numOfAgents-1\n\n alfa = -99999999\n beta = 99999999\n\n def maxValue(state, depth, alfa, beta):\n v = -9999999999\n #legalMoves = state.getLegalActions(0)\n # need to modify the for loop compared the previous question, because that one expands always.\n for act in state.getLegalActions(0):\n #successor = state.generateSuccessor(0, act)\n numOfAgents = state.getNumAgents()\n numOfGhosts = numOfAgents - 1\n\n if numOfGhosts == 0:\n v = max(v, value(0, state.generateSuccessor(0, act), depth + 1, alfa, beta))\n if v > beta:\n #print '...............pruningg this max: ', v\n return v\n\n alfa = max(v, alfa)\n\n else:\n v = max(v, value(1, state.generateSuccessor(0, act), depth, alfa, beta))\n if v > beta:\n #print '...............pruningg this max: ', v\n return v\n alfa = max(alfa, v)\n return v\n\n def minValue(state, depth, agentIndex, alfa, beta):\n v = 9999999999\n numOfAgents = state.getNumAgents()\n numOfGhosts = numOfAgents - 1\n\n for act in state.getLegalActions(agentIndex):\n #successor = state.generateSuccessor(agentIndex, act)\n numOfAgents = state.getNumAgents()\n numOfGhosts = numOfAgents - 1\n if agentIndex == numOfGhosts:\n v = min(v, value(0, state.generateSuccessor(agentIndex, act), depth + 1, alfa, beta))\n if v < alfa:\n #print '...............pruningg this min: ', v\n return v\n beta = min(beta,v)\n # print 'v after min operation: ', v\n else:\n v = min(v, value(agentIndex + 1, state.generateSuccessor(agentIndex, act), depth, alfa, beta))\n if v < alfa:\n #print '...............pruningg this min: ', v\n return v\n beta = min(beta,v)\n # print 'v after min operation: ', v\n\n return v\n\n def value(agentIndex, state, depth, alfa ,beta):\n if depth == self.depth:\n scr = evaluationFunc(state)\n #print 'evaluated value: ',scr\n return scr\n if state.isWin() or state.isLose():\n scr = evaluationFunc(state)\n #print 'evaluated value: ', scr\n return scr\n numOfAgents = state.getNumAgents()\n numOfGhosts = numOfAgents - 1\n if agentIndex == 0 or numOfGhosts == 0:\n return maxValue(state, depth, alfa, beta)\n\n return minValue(state, depth, agentIndex, alfa, beta)\n\n legalMoves = gameState.getLegalActions()\n\n numOfAgents = gameState.getNumAgents()\n numOfGhosts = numOfAgents - 1\n\n scores = []\n\n for act in legalMoves:\n successor = gameState.generateSuccessor(0, act)\n if numOfGhosts == 0:\n v = value(0, gameState.generateSuccessor(0, act), 1, alfa, beta)\n else:\n v = value(1, gameState.generateSuccessor(0, act), 0, alfa, beta)\n alfa = max(v, alfa)\n scores.append(v)\n\n bestScore = max(scores)\n # print 'best scores: ',bestScore\n bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore]\n chosenIndex = bestIndices[0] # Pick first of the bests\n\n return legalMoves[chosenIndex]\n\nclass ExpectimaxAgent(MultiAgentSearchAgent):\n \"\"\"\n Your expectimax agent (question 4)\n \"\"\"\n\n def getAction(self, gameState):\n \"\"\"\n Returns the expectimax action using self.depth and self.evaluationFunction\n\n All ghosts should be modeled as choosing uniformly at random from their\n legal moves.\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n currentD = 0\n currentAI = 0\n val = self.value(gameState, currentD, currentAI)\n return val[0]\n\n def value(self, state, currentD, currentAI):\n if currentAI >= state.getNumAgents():\n currentAI = 0\n currentD += 1\n if currentD == self.depth:\n return self.evaluationFunction(state)\n if currentAI == 0:\n return self.maxValue(state, currentD, currentAI)\n else:\n return self.expValue(state, currentD, currentAI)\n\n def expValue(self, state, currentD, currentAI):\n v = [\"unknown\", 0]\n if not state.getLegalActions(currentAI):\n return self.evaluationFunction(state)\n\n prob = 1.0/len(state.getLegalActions(currentAI))\n for action in state.getLegalActions(currentAI):\n if action == \"Stop\":\n continue\n retVal = self.value(state.generateSuccessor(currentAI, action), currentD, currentAI + 1)\n if type(retVal) is tuple:\n retVal = retVal[1]\n v[1] += retVal * prob\n v[0] = action\n return tuple(v)\n\n def maxValue(self, state, currentD, currentAI):\n v = (\"unknown\", -1*float(\"inf\"))\n if not state.getLegalActions(currentAI):\n return self.evaluationFunction(state)\n for action in state.getLegalActions(currentAI):\n if action == \"Stop\":\n continue\n retVal = self.value(state.generateSuccessor(currentAI, action), currentD, currentAI + 1)\n if type(retVal) is tuple:\n retVal = retVal[1]\n vNew = max(v[1], retVal)\n if vNew is not v[1]:\n v = (action, vNew)\n return v\n\ndef betterEvaluationFunction(currentGameState):\n \"\"\"\n Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable\n evaluation function (question 5).\n\n DESCRIPTION: \n \"\"\"\n \"\"\"\n \"*** YOUR CODE HERE ***\"\n \"\"\"\n def mazeDistance(point1, point2):\n return len(bfs(point1, point2))\n def bfs(start, goal):\n from util import Queue\n q = Queue()\n explored = set()\n q.push((start, []))\n while not q.isEmpty():\n popped = q.pop()\n if popped[0] in explored:\n continue\n explored.add(popped[0])\n if popped[0] == goal:\n return popped[1]\n for successor in getSuccessors(popped[0]):\n if successor[0] not in explored:\n #push successor, where actions and cost are cumulative on its parent (popped)\n q.push((successor[0], popped[1] + [successor[1]]))\n return popped[1]\n def getSuccessors(position):\n from game import Actions\n successors = []\n for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:\n x,y = position\n dx, dy = Actions.directionToVector(action)\n nextx, nexty = int(x + dx), int(y + dy)\n walls = currentGameState.getWalls()\n if not walls[nextx][nexty]:\n nextState = (nextx, nexty)\n successors.append((nextState, action))\n return successors\n\n if currentGameState.isWin():\n return 69000\n if currentGameState.isLose():\n return -69000\n\n currentPos = currentGameState.getPacmanPosition()\n foodList = currentGameState.getFood().asList()\n nearestF = 69\n for food in foodList:\n dist = util.manhattanDistance(currentPos, food)\n if (dist < nearestF):\n nearestF = dist\n\n ghostCount = currentGameState.getNumAgents() - 1\n nearestG = 69\n for ghost in currentGameState.getGhostPositions():\n dist = util.manhattanDistance(currentPos, ghost)\n if (dist < nearestG):\n nearestG = dist\n\n score = scoreEvaluationFunction(currentGameState)\n scared = False\n for ghost in currentGameState.getGhostStates():\n if ghost.scaredTimer > 0:\n scared = True\n if scared:\n score -= nearestG**2\n score += min(nearestG,3)\n score -= math.sqrt(nearestF)\n capsules = len(currentGameState.getCapsules())\n score -= 100*capsules\n return score\n \"\"\"\n def mazeDistance(point1, point2):\n return len(bfs(point1, point2))\n def bfs(start, goal):\n from util import Queue\n q = Queue()\n explored = set()\n q.push((start, []))\n while not q.isEmpty():\n popped = q.pop()\n if popped[0] in explored:\n continue\n explored.add(popped[0])\n if popped[0] == goal:\n return popped[1]\n for successor in getSuccessors(popped[0]):\n if successor[0] not in explored:\n #push successor, where actions and cost are cumulative on its parent (popped)\n q.push((successor[0], popped[1] + [successor[1]]))\n return popped[1]\n def getSuccessors(position):\n from game import Actions\n successors = []\n for action in [Directions.NORTH, Directions.SOUTH, Directions.EAST, Directions.WEST]:\n x,y = position\n dx, dy = Actions.directionToVector(action)\n nextx, nexty = int(x + dx), int(y + dy)\n walls = currentGameState.getWalls()\n if not walls[nextx][nexty]:\n nextState = (nextx, nexty)\n successors.append((nextState, action))\n return successors\n\n currentPos = currentGameState.getPacmanPosition()\n foodGrid = currentGameState.getFood()\n w = foodGrid.width\n h = foodGrid.height\n hypotenuse = math.sqrt(w*w + h*h)\n closestFood = 69000\n for food in foodGrid.asList():\n dist = mazeDistance(currentPos, food) + manhattanDistance(currentPos, food)\n if dist < closestFood:\n closestFood = dist\n foodScore = (hypotenuse/2)**2/closestFood**2\n\n ghostScore = 0\n for ghost in currentGameState.getGhostStates():\n dist = util.manhattanDistance(ghost.getPosition(), currentPos)\n timer = ghost.scaredTimer\n if timer == 0:\n ghostScore -= (hypotenuse/2)**3/dist**3\n continue\n ghostScore += (hypotenuse/2)**3/dist**3\n\n score = 0\n if currentGameState.isWin():\n score += 69000\n elif currentGameState.isLose():\n score -= 69000\n print(foodScore, ghostScore, currentPos)\n return score + foodScore + ghostScore\n \"\"\"\n# Abbreviation\nbetter = betterEvaluationFunction\n","sub_path":"multiagent/multiAgents.py","file_name":"multiAgents.py","file_ext":"py","file_size_in_byte":32007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"460234058","text":"import functools\nfrom basic import Line, Point\nfrom random import randint\nfrom math import inf\n\ndef intersections(G, T):\n \"Número de intersecções e uma intersecção aleatória no intervalo T em O(n log n)\"\n\n def inversions(v, p = 0):\n \"Número de inversões e a p-ésima inversão de v\"\n\n def merge(l, r, p):\n \"Combina duas listas ordenadas, retorna numéro de inversões e a p-ésima inversão do merge\"\n\n ll, rl = l\n lr, rr = r\n n, nv = 0, [0] * (rr + rl - lr - ll + 2)\n i, j, ni, inv = ll, lr, 0, None\n while i <= rl and j <= rr:\n if v[i] <= v[j]:\n nv[n] = v[i]\n n += 1\n i += 1\n else:\n nv[n] = v[j]\n n += 1\n diff = (rl - ll + 1) - (i - ll)\n if ni < p and ni + diff >= p:\n pos = p - ni\n inv = (v[j], v[i + pos - 1])\n ni += diff\n j += 1\n while i <= rl:\n nv[n] = v[i]\n n += 1\n i += 1\n while j <= rr:\n nv[n] = v[j]\n n += 1\n j += 1\n for i in range(ll, rr + 1):\n v[i] = nv[i - ll]\n return ni, inv\n\n def sort(t, p):\n \"Ordena uma lista v, retorna número de inversões e a p-ésima inversão de v\"\n\n l, r = t\n if r - l + 1 <= 1:\n return 0, None\n mid = (l + r + 1) // 2\n ni_l, i_l = sort((l, mid - 1), p)\n ni_r, i_r = sort((mid, r), p - ni_l)\n ni_m, i_m = merge((l, mid - 1), (mid, r), p - ni_l - ni_r)\n return ni_m + ni_l + ni_r, i_m or i_l or i_r\n \n ni, inv = sort((0, len(v) - 1), p)\n return ni, inv\n\n bijection = {}\n L = sorted(G, key=functools.cmp_to_key(Line.cmp(T[0])))\n R = sorted(G, key=functools.cmp_to_key(Line.cmp(T[1])))\n for i, l in enumerate(L):\n bijection[l] = i\n\n v = [bijection[l] for l in R]\n count, inv = inversions(v)\n v = [bijection[l] for l in R]\n count, inv = inversions(v, randint(1, max(1, count)))\n inv = inv if not inv else (L[inv[0]], L[inv[1]])\n return count, inv\n\ndef level(G, p, x):\n \"p-ésimo elemento de G em x, se G estivesse ordenado\"\n\n return sorted(G, key=functools.cmp_to_key(Line.cmp(x)))[p]\n\ndef has_odd_intersections(G1, G2, p1, p2, T):\n \"verifica se a quantidade de intersecções entre os níveis p1 e p2 em T é ímpar\"\n\n l, r = T\n left = Line.cmp(l)(level(G1, p1, l), level(G2, p2, l))\n right = Line.cmp(r)(level(G1, p1, r), level(G2, p2, r))\n return left * right < 0\n\ndef verify_solution(P1, P2, l):\n \"verifica se a reta l resolve o problema para os conjuntos de pontos P1 e P2\"\n\n count = [[0, 0], [0, 0]]\n P = [P1, P2]\n for i in range(2):\n for p in P[i]:\n if p in l:\n continue\n if p.above(l):\n count[i][0] += 1\n if p.under(l):\n count[i][1] += 1\n if 2 * max(count[i][0], count[i][1]) > len(P[i]):\n return False\n\n return True\n\ndef max_intersections(G):\n \"conta a maior quantidade de intersecções possíveis no nível G\"\n\n return (len(G) * (len(G) - 1)) // 2\n\ndef new_interval(G1, G2, p1, p2, T):\n \"retorna um novo intervalo com a propriedade de intersecção ímpar e se a quantidade de retas é pequena o suficiente para um testa tudo\"\n\n cur_intersections, random_inversion = intersections(G1, T)\n is_base = (max_intersections(G1) <= 32)\n while 32 * cur_intersections > max_intersections(G1) and not is_base:\n x = random_inversion[0].intersect(random_inversion[1]).x\n if has_odd_intersections(G1, G2, p1, p2, (T[0], x)):\n T = (T[0], x)\n else:\n T = (x, T[1])\n cur_intersections, random_inversion = intersections(G1, T)\n return T, is_base\n\ndef new_trapezoid(G, p, T):\n \"retorna um trapezoide para eliminaçāo de retas\"\n\n off = len(G) // 8\n dL1 = Point(T[0], level(G, p - off, T[0])(T[0]))\n dL2 = Point(T[0], level(G, p + off, T[0])(T[0]))\n dR1 = Point(T[1], level(G, p - off, T[1])(T[1]))\n dR2 = Point(T[1], level(G, p + off, T[1])(T[1]))\n return (dL1, dL2, dR2, dR1)\n\ndef intersects_trapezoid(l, t):\n \"checa se a reta l intersecta o trapezoide t e se l está abaixo de t\"\n\n is_under, is_above = True, True\n\n for i in range(4):\n if t[i].under_in(l):\n is_under = False\n\n if t[i].above_in(l):\n is_above = False\n \n return is_under, is_above\n\ndef discard_lines(G, p, t):\n nG = []\n b = 0\n for l in G:\n is_under, is_above = intersects_trapezoid(l, t)\n if not (is_under or is_above):\n nG.append(l)\n elif is_under:\n b += 1\n return nG, p - b\n\ndef recursive_ham_sandwich(G1, G2, p1, p2, T):\n if len(G1) < len(G2):\n return recursive_ham_sandwich(G2, G1, p2, p1, T)\n T, is_base = new_interval(G1, G2, p1, p2, T)\n\n if is_base:\n valid_answers = []\n for g in G1:\n for h in G2:\n p = g.intersect(h)\n if p and isinstance(p.dual(), Line):\n valid_answers.append(p.dual())\n return valid_answers\n\n t = new_trapezoid(G1, p1, T)\n G1, p1 = discard_lines(G1, p1, t)\n G2, p2 = discard_lines(G2, p2, t)\n\n return recursive_ham_sandwich(G1, G2, p1, p2, T)\n\ndef ham_sandwich(P1, P2):\n G1 = P1 if len(P1) % 2 else P1[1:]\n G2 = P2 if len(P2) % 2 else P2[1:]\n G1 = [p.dual() for p in G1]\n G2 = [p.dual() for p in G2]\n valid_answers = recursive_ham_sandwich(G1, G2, len(G1)//2, len(G2)//2, (-inf, inf))\n for l in valid_answers:\n if verify_solution(P1, P2, l):\n return l\n return None\n","sub_path":"code/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"622387466","text":"# bot.py\nimport os\nfrom sys import exit\nimport random\n\nimport discord\nfrom dotenv import load_dotenv\n\nimport nltk\n\nload_dotenv()\nTOKEN = os.getenv('DISCORD_TOKEN')\nif not TOKEN:\n exit('TOKEN = None')\n\nclient = discord.Client()\n\n\ndef is_similar_to(text1, text2, percent=0.35): # Похожая на ...\n # Добрый вечер\n # Дбрый вечер\n # Добрый вече\n\n # Добрый вечер\n\n # Добрый дечер\n # Добрый денер\n # Добрый деньр\n # Добрый день\n\n # Добрый день\n\n # Расстояние = 4\n # Изменение в проценнтах = 4/26 (= 0.15) Какой хороший Добрый день\n # Изменение в проценнтах = 4/26 (= 0.33) Добрый день\n distance = nltk.edit_distance(text1, text2)\n difference = distance / len(text1)\n # print(distance, difference)\n\n if difference < percent:\n return True\n return False\n\n\n@client.event\nasync def on_ready():\n print(f'{client.user.name} подключился к Discord!')\n\n\n@client.event\nasync def on_member_join(member):\n await member.create_dm()\n await member.dm_channel.send(\n f'Hi {member.name}, Приветствуем тебя на нашем сервере!'\n )\n\n\n@client.event\nasync def on_message(message):\n if message.author == client.user:\n return\n\n if message.author.bot: # message.member.roles.has(BOT_ROLE)\n return\n\n if message.content == 'raise-exception':\n raise discord.DiscordException\n\n response = start_dialogue(message.content)\n await message.channel.send(response)\n\n\ndef clear_phrases(replica):\n replica = replica.lower()\n alphabet_russ = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'\n alphabet_eng = 'abcdefghijklmnopqrstuvwxyz'\n some_symbols = ' -'\n\n replica_copy = ''\n for symbol in replica:\n if symbol in (alphabet_russ + alphabet_eng + some_symbols):\n replica_copy += symbol # replica_copy = replica_copy + symbol\n\n replica = replica_copy\n return replica\n\n\ndef get_intent(replica):\n intent = None\n for string in intents_list:\n if string.startswith('##'):\n index_separator = string.index(':')\n intent = string[index_separator + 1:]\n # print(intent)\n if is_similar_to(replica, string.lower()):\n return intent\n\n return None\n\n\ndef failure_phrases():\n phrases = [\n 'как-то непонятно',\n 'Нет данных',\n 'Я не понял, скажи нормально',\n 'Не понимаю о чем ты',\n 'Черт его знает, спроси чего полегче',\n 'чего?',\n 'а?',\n 'Что ты сказал?',\n 'выражайтесь так, как принято в культурном обществе]'\n ]\n return random.choice(phrases)\n\n\ndef get_answer_from_intent(intent, replica):\n \"\"\"\n Сообщение боту: Чем знаменит Борис Ельцин?\n Ответ бота: Он бывший президент России\n\n Сообщение боту: где живут пингвины?\n Ответ бота: на Антарктиде\n \"\"\"\n response = []\n\n # answer = random.choice(response)\n answer = None\n if intent == 'wiki':\n if is_similar_to('Чем знаменит Борис Ельцин?', replica):\n answer = 'Он бывший президент России'\n elif is_similar_to('где живут пингвины?', replica):\n answer = 'на Антарктиде'\n else:\n answer = 'Насколько я понял, твоё намерение: ' + intent\n return answer\n\n\ndef start_dialogue(replica):\n # NLU (Natural Language Understanding):\n # + Предварительная обработка реплики (очистка, регистр букв и т.п.)\n # + Относим реплику к какому-либо классу намерений\n # - Извлекаем параметры реплики (извлечение сущностей и объектов)\n\n # NLG (Natural Language Generation):\n # + Выдать заготовленный ответ основываясь на намерении\n # - Если заготовленного ответа нет, то сгенерировать ответ автоматически и выдать его\n # + Если не удалось сгенерировать ответ, то выдать фразу: \"Я непонял\"; \"Перефразируй\" и т.п.\n\n answer = ''\n # Предварительная обработка реплики (очистка, регистр букв и т.п.)\n replica = clear_phrases(replica)\n\n # Относим реплику к какому-либо классу намерений\n intent = get_intent(replica)\n print(intent)\n\n # Выдать заготовленный ответ основываясь на намерении\n if intent:\n answer = get_answer_from_intent(intent, replica)\n\n # Если не удалось сгенерировать ответ, то выдать фразу: \"Я непонял\"; \"Перефразируй\" и т.п.\n if not answer:\n answer = failure_phrases()\n\n return answer\n\n\ndef load_intents_old(): # Загрузить намерения из файла в память\n file = open('Intents/intents_old.txt', 'r') # Отрытие файла в режиме чтения\n text = file.read() # Чтение данных из файла\n file.close() # Закрытие файла\n\n text = text.split('\\n') # Разделение текста и преобразование его в список строк\n\n intents_list = [\n # ['hello', [], []],\n # ['goodbye', [], []],\n ]\n\n mode = 'intent' # examples, responses, end_string, default_string\n end_paragraph = 'default_string' # end_string\n index = -1\n for string in text:\n if string == '[intent]':\n index += 1\n mode = 'intent'\n continue\n elif string == '[examples]':\n mode = 'examples'\n continue\n elif string == '[responses]':\n mode = 'responses'\n continue\n elif string == '':\n end_paragraph = 'end_string'\n else:\n end_paragraph = 'default_string'\n\n if mode == 'intent' and end_paragraph == 'default_string':\n intents_list.append([string, [], []])\n elif mode == 'examples' and end_paragraph == 'default_string':\n intents_list[index][1].append(string)\n elif mode == 'responses' and end_paragraph == 'default_string':\n intents_list[index][2].append(string)\n\n for intent in intents_list:\n print(intent)\n\n\ndef load_intents(): # Загрузить намерения из файла в память\n file = open('Intents/intents.txt', 'r', encoding='utf-8') # Отрытие файла в режиме чтения\n text = file.read() # Чтение данных из файла\n file.close() # Закрытие файла\n\n text = text.split('\\n') # Разделение текста и преобразование его в список строк\n\n return text\n\n\n# intents_list = [\n # ['hello', [], []],\n # ['goodbye', [], []],\n# ]\n\n# load_intents_old()\n\n# intents - list strings from raw file intents.txt\nintents_list = load_intents()\n\nclient.run(TOKEN)\n","sub_path":"interface_discord.py","file_name":"interface_discord.py","file_ext":"py","file_size_in_byte":7660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"38400080","text":"from __future__ import division, print_function, unicode_literals\r\n\r\nfrom sacred import Experiment\r\nfrom sacred.observers import FileStorageObserver\r\nfrom config import ingredient_config, create_scratch\r\nfrom config import model_name, result_name\r\nfrom config import model_path, result_path\r\nfrom config import filelist, remove_files\r\nfrom config import result_path_all, result_path_category\r\nfrom config import result_path_best\r\n\r\nimport os\r\n\r\nimport joblib\r\nimport numpy as np\r\nimport json\r\nimport pandas as pd\r\nimport random\r\nimport glob\r\nfrom functools import partial\r\nimport shutil\r\nimport sqlite3\r\nimport copy\r\nimport re\r\n\r\nimport utils.scoring\r\n#from utils.results import aggregate\r\nfrom utils.excel_writer import df_to_excel\r\nfrom utils.observers import get_observers\r\nfrom utils.plotting import plot_curves\r\nfrom utils.df_helper import filter_df, best_by_group, best_row\r\nfrom utils.vocab import Vocab\r\nfrom utils.proj_setup import setup_dir\r\nfrom utils.merge_labels import merge_labels, label_split_seq\r\nfrom utils.scoring import get_masked\r\nfrom visualization.latex import dict_df_to_latex\r\nfrom utils.path_utils import find_files\r\n#from utils.seq_prep import preprocess_tokens, preprocess_labels\r\n#from utils.seq_prep import strip_BIO, strip_BIO_seq\r\n#from utils.seq_prep import postprocess_labels\r\n#from step012_mimic_extract_basic import NOTE_START_PATTERN\r\nfrom math import ceil\r\nfrom visualization.latex import dict_df_to_latex\r\nfrom utils.tokenization_nltk import tokenize_doc\r\nfrom step011_mimic_extract import rm_linebreaks\r\nfrom utils.seq_prep import strip_BIO, OUTSIDE\r\n\r\nfrom utils.proj_setup import make_and_clear\r\nfrom annotate.standoff_create import to_standoff_corpus\r\nfrom annotate.standoff_create import unmerge_entities, unmerge_events, combine_seq, remove_labels, rename_entity\r\n\r\n# Define experiment and load ingredients\r\nex = Experiment('step520_mimic_load', ingredients=[ingredient_config])\r\n\r\n\r\n\r\n@ex.config\r\ndef cfg(config):\r\n\r\n \r\n\r\n # Paths\r\n\r\n entity = None\r\n\r\n\r\n source = config['mimic_basic_fn']\r\n #source = '/atm/turkey/vol/transitory/lybarger/clinical_extraction/analyses/20180207_full/step012_mimic_extract_basic/extracted2.txt'\r\n\r\n\r\n substance_fn = '/atm/turkey/vol/transitory/lybarger/clinical_extraction/analyses/20180503_fast/step300_Indicator_train_summary/Substance_model.pkl' #config['indicator_train_model_best']\r\n #multitask_dir = config['multitask_best_dir']\r\n \r\n multitask_fn = '/atm/turkey/vol/transitory/lybarger/clinical_extraction/analyses/20180503_fast/step206_Multitask_train/MULTISTAGE3_04_1c2b4a79851a4e418b57f2cfa449f77e/Multitask_model.pkl'#model_path(multitask_dir, 'multitask') \r\n brat_dest = '/s1/lybarger/brat/brat-v1.3_Crunchy_Frog/data/examples/MIMIC'\r\n\r\n \r\n \r\n dest = config['annotate_mimic']\r\n\r\n max_seq_len = 200\r\n min_seq_len = 1\r\n num_examples = 50\r\n \r\n #label_def = get_label_def()\r\n\r\n\r\n \r\n fast_run = False\r\n num_to_fetch = 2\r\n batch_size = 10 if fast_run else 1000\r\n\r\n # Mimic database location\r\n db = config['mimic_db'] \r\n note_category = 'Discharge summary'\r\n \r\n \r\n \r\n scratch = setup_dir(dest, config['root'], config['scratch'])\r\n\r\n num_list_pat = config['num_list_pat']\r\n\r\n\r\n quantity_events = config['quantity_events']\r\n quantity_entities = config['quantity_entities']\r\n quantity = config['quantity']\r\n substance = config['substance']\r\n type_events = config['type_events']\r\n type_ = config['type_']\r\n \r\n status_events = config['status_events']\r\n status_sent = config['status_sent']\r\n status_seq = config['status_seq']\r\n has_attribute = config['has_attribute']\r\n \r\n substance_events = config['status_events']\r\n substance_sent = config['substance_sent']\r\n substance_seq = config['substance_seq']\r\n \r\n events_remove = [substance]\r\n #entities_remove = [substance_sent, substance_seq, quantity]\r\n entities_remove = [quantity]\r\n \r\n \r\n head_entity = substance\r\n\r\n\r\n # Create observers\r\n ex.observers.extend(get_observers(ex, dest, 'none', \\\r\n config['use_file_obs'], config['use_slack_obs'], \\\r\n slack_webhook = config['slack_webhook']))\r\n\r\n\r\n\r\n\r\ndef labeled_as_string(sentences, labels):\r\n '''\r\n Convert labeled corpus to string\r\n '''\r\n\r\n labels_to_include = [(('quantity', 'Alcohol'), 'Alcohol'),\r\n (('quantity', 'Drug'), 'Drug'),\r\n (('quantity', 'Tobacco'), 'Tobacco'),\r\n (('status', 'Alcohol'), 'status_Alcohol'),\r\n (('status', 'Drug'), 'status_Drug'),\r\n (('status', 'Tobacco'), 'status_Tobacco'),\r\n ]\r\n\r\n\r\n # Check length\r\n assert len(sentences) == len(labels), 'length error'\r\n out = []\r\n \r\n\r\n for sent, labs in zip(sentences, labels):\r\n\r\n # Remove start and stop tokens \r\n \r\n d = {}\r\n d['tokens'] = sent \r\n \r\n # Substance event predicted\r\n if labs is not None:\r\n\r\n # Get type so it can be included with others\r\n type_labs = strip_BIO_seq(labs[('type', 'substance')])\r\n type_non_neg_cnt = len([0 for tp in type_labs if tp != 'O'])\r\n types_ = {}\r\n for typ in TYPES:\r\n types_[typ] = [re.sub('_{}'.format(typ),'',x) if re.search(typ, x) else 'O' for x in type_labs]\r\n type_non_neg_cnt_check = 0\r\n\r\n # Loop on labels\r\n for lab_orig, lab_new in labels_to_include:\r\n \r\n \r\n entity, typ = lab_orig\r\n \r\n lab = labs[lab_orig]\r\n \r\n seq_of_seq = isinstance(lab, list)\r\n\r\n if seq_of_seq:\r\n lab = strip_BIO_seq(lab[1:-1])\r\n typ_labs = types_[typ][1:-1]\r\n \r\n \r\n assert len(lab) == len(sent), 'len mismatch ={}/{}'.format(len(lab), len(sent))\r\n assert len(typ_labs) == len(sent), 'len mismatch ={}/{}'.format(len(typ_labs), len(sent))\r\n \r\n \r\n for j in range(len(lab)):\r\n if typ_labs[j] != 'O':\r\n type_non_neg_cnt_check += 1\r\n lab[j] = typ_labs[j]\r\n \r\n else:\r\n lab = [lab] + ['']*(len(sent)-1)\r\n \r\n d[lab_new] = lab\r\n \r\n assert type_non_neg_cnt == type_non_neg_cnt_check, 'Error distributing type '\r\n \r\n df = pd.DataFrame(d)\r\n cols = ['tokens', 'Alcohol', 'Drug', 'Tobacco', 'status_Alcohol', 'status_Drug', 'status_Tobacco']\r\n df = df[cols]\r\n\r\n \r\n else:\r\n df = pd.DataFrame(d)\r\n cols = ['tokens']\r\n df = df[cols]\r\n \r\n df = df.transpose()\r\n\r\n out.append(df.to_string(header=False))\r\n \r\n return out\r\n\r\n\r\ndef get_label_stats(y_pred):\r\n print('+'*72)\r\n print(\"Getting label stats\")\r\n print('+'*72)\r\n \r\n stats = {}\r\n \r\n for sent in y_pred:\r\n if sent is not None:\r\n for entity_type, labels in sent.items():\r\n \r\n if entity_type not in stats.keys():\r\n stats[entity_type] = {}\r\n \r\n \r\n \r\n if not isinstance(labels, list):\r\n labels = [labels]\r\n \r\n for lab in labels:\r\n if lab not in stats[entity_type].keys():\r\n stats[entity_type][lab] = 0\r\n stats[entity_type][lab] += 1\r\n\r\n stats2 = {}\r\n \r\n status_types = [('status', 'Alcohol'), ('status', 'Drug'), ('status', 'Tobacco')]\r\n for entity_type in status_types:\r\n stats2[entity_type] = sum([cnt for lab, cnt in stats[entity_type].items() if lab in ['past', 'none', 'current']])\r\n\r\n\r\n quantity_types = [('quantity', 'Alcohol'), ('quantity', 'Drug'), ('quantity', 'Tobacco')]\r\n quantity_entities = ['B-Amount', 'B-Frequency', 'B-ExposureHistory', 'B-QuitHistory']\r\n for entity_type in quantity_types:\r\n stats2[entity_type] = {lab: stats[entity_type].get(lab, 0) for lab in quantity_entities}\r\n \r\n type_entities = [('type', 'substance')]\r\n type_types = ['B-Type_Alcohol', 'B-Type_Drug', 'B-Type_Tobacco']\r\n for entity_type in type_entities: \r\n stats2[entity_type] = {lab:cnt for lab, cnt in stats[entity_type].items() if lab in type_types}\r\n \r\n\r\n\r\n\r\n for entity_type, cnts in stats.items():\r\n print()\r\n print(entity_type)\r\n print(stats[entity_type])\r\n if entity_type in stats2.keys():\r\n print(stats2[entity_type])\r\n\r\n\r\n rows = []\r\n rows.append([stats2[typ] for typ in status_types])\r\n for ent in type_entities:\r\n rows.append([stats2[ent][typ] for typ in type_types])\r\n for ent in quantity_entities:\r\n rows.append([stats2[typ][ent] for typ in quantity_types])\r\n\r\n \r\n df = pd.DataFrame(rows, columns=['Alcohol', 'Drug', 'Tobacco'], index=['status', 'type', 'amount', 'frequency', 'exposure history', 'quit history'])\r\n print(df)\r\n \r\n return df\r\n \r\n \r\n \r\n \r\ndef get_counts(tokens, max_seq_len):\r\n\r\n sent_count = len(tokens)\r\n sent_lengths = [len(sent) for sent in tokens]\r\n token_count = sum(sent_lengths)\r\n \r\n long_line_count = len([0 for ln in sent_lengths \\\r\n if ln > max_seq_len])\r\n longest_line = max(sent_lengths)\r\n \r\n return (sent_count, token_count, long_line_count, longest_line)\r\n \r\n \r\n@ex.automain\r\ndef main(source, dest, scratch, substance_fn, multitask_fn,\r\n min_seq_len, max_seq_len, num_examples, num_list_pat,\r\n quantity, substance, \r\n quantity_entities, quantity_events, type_events, type_,\r\n status_events, status_sent, status_seq, \r\n entities_remove, events_remove, has_attribute,\r\n head_entity,\r\n substance_events, substance_sent, substance_seq,\r\n brat_dest, fast_run, num_to_fetch, db, note_category, batch_size):\r\n\r\n fn_summary = os.path.join(dest, 'summary.txt')\r\n\r\n\r\n\r\n '''\r\n Prep work space\r\n '''\r\n make_and_clear(brat_dest, recursive=True, clear_=True)\r\n print(\"Workspace prepped\")\r\n\r\n '''\r\n Load corpus\r\n '''\r\n \r\n # Connect to database\r\n conn = sqlite3.connect(db)\r\n c = conn.cursor()\r\n print(\"Loaded sqlite database\")\r\n\r\n\r\n # Get note text associated with category\r\n c.execute('SELECT CATEGORY, ROW_ID, TEXT FROM NOTEEVENTS WHERE CATEGORY=\"{}\"'.format(note_category))\r\n print(\"Query executed\")\r\n \r\n # Query table\r\n corpus = c.fetchmany(size=num_to_fetch) if fast_run \\\r\n else c.fetchall()\r\n print(\"Notes fetched\")\r\n\r\n '''\r\n Load extractors\r\n '''\r\n # Load models\r\n substance_model = joblib.load(substance_fn)\r\n multitask_model = joblib.load(multitask_fn)\r\n print(\"Models loaded\")\r\n print('Substance model:\\t{}'.format(substance_fn)) \r\n print('Multitask model:\\t{}'.format(multitask_fn))\r\n\r\n '''\r\n Process and annotate\r\n '''\r\n\r\n # Initialize output summary\r\n summary = []\r\n fn_summary = os.path.join(dest, 'summary.txt')\r\n \r\n # Totals\r\n sent_count = 0\r\n long_count = 0\r\n word_count = 0\r\n note_count = len(corpus)\r\n \r\n # Loop in batches\r\n batch_indices = range(0, note_count, batch_size)\r\n batch_count = len(batch_indices)\r\n \r\n n = 0\r\n for i in batch_indices:\r\n \r\n with open(fn_summary, 'a') as f: \r\n f.write(\"\\n\\nBatch {}/{}\".format(n+1, batch_count))\r\n n += 1\r\n \r\n # Current batch\r\n category, fns, text = zip(*corpus[i:i+batch_size])\r\n \r\n # Tokenize document, list of documents\r\n text_tmp = [rm_linebreaks(t, num_list_pat) for t in text]\r\n tokenized_nested = [tokenize_doc(doc) for doc in text_tmp]\r\n\r\n with open(fn_summary, 'a') as f: \r\n f.write(\"\\n\\tTokenized\")\r\n\r\n\r\n # Sentences per doc\r\n sent_counts_by_doc = [len(doc) for doc in tokenized_nested]\r\n sent_count += sum(sent_counts_by_doc)\r\n\r\n # Flatten tokenized documents to single list of sentences\r\n tokenized = [sent for doc in tokenized_nested for sent in doc]\r\n word_count += sum([len(sent) for sent in tokenized])\r\n\r\n # Filenames by sentence\r\n fns = [fn_ for fn_, cnt in zip(fns, sent_counts_by_doc) \\\r\n for _ in range(cnt)]\r\n\r\n # Check lengths\r\n msg = 'Sentence count = {}\\nFilename count = {}'.format( \\\r\n len(tokenized), len(fns))\r\n assert len(tokenized) == len(fns), msg\r\n\r\n # Get sentence lengths, before truncation\r\n sent_count1, token_cnt1, long_cnt1, longest1 = \\\r\n get_counts(tokenized, max_seq_len)\r\n long_count += long_cnt1\r\n \r\n # Truncate long lines, by imposing linebreaks\r\n tokenized_short = []\r\n fns_short = []\r\n for sent, fn in zip(tokenized, fns):\r\n \r\n # Loop on subsets of sentence\r\n for j in range(0, len(sent), max_seq_len):\r\n tokenized_short.append(sent[j:j+max_seq_len])\r\n fns_short.append(fn)\r\n \r\n tokenized = tokenized_short\r\n fns = fns_short\r\n del tokenized_short\r\n del fns_short\r\n with open(fn_summary, 'a') as f: \r\n f.write(\"\\n\\tLong line split complete\")\r\n \r\n\r\n # Check lengths\r\n msg = 'Sentence count = {}\\nFilename count = {}'.format( \\\r\n len(tokenized), len(fns))\r\n assert len(tokenized) == len(fns), msg\r\n \r\n # Get sentence lengths, after truncation\r\n sent_count2, token_cnt2, long_cnt2, longest2 = \\\r\n get_counts(tokenized, max_seq_len)\r\n s = []\r\n s.append('\\n\\tSent count:\\t{}/{}'.format(sent_count1, sent_count2))\r\n s.append('\\tToken count:\\t{}/{}'.format(token_cnt1, token_cnt2))\r\n s.append('\\tLongest line:\\t{}/{}'.format(longest1, longest2))\r\n s.append('\\tLong line count:\\t{}/{}'.format(long_cnt1, long_cnt2))\r\n with open(fn_summary, 'a') as f: \r\n f.write(\"\\n\".join(s))\r\n \r\n '''\r\n Get mask\r\n '''\r\n mask, _ = substance_model.predict_wo_score(tokenized) \r\n with open(fn_summary, 'a') as f: \r\n f.write(\"\\n\\tSubstance model - prediction complete\")\r\n f.write(\"\\n\\tSubstance model - found:\\t{}\".format(np.sum(mask)))\r\n '''\r\n Run tensorflow\r\n '''\r\n multitask_model.verbose = False\r\n y_pred, y_prob = multitask_model.predict_wo_score(tokenized, mask) \r\n y = []\r\n for sent in tokenized:\r\n d = {}\r\n for k, v in y_pred[0].items():\r\n if isinstance(v, list):\r\n d[k] = [v[0]]*len(sent)\r\n else:\r\n d[k] = v\r\n \r\n y.append(d)\r\n y_pred, y_prob = multitask_model.restore_mask(y, y_pred, y_prob, mask)\r\n\r\n with open(fn_summary, 'a') as f: \r\n f.write(\"\\n\\tTensorFlow complete\")\r\n \r\n\r\n\r\n '''\r\n Output in BRAT format\r\n '''\r\n # Unmerge entities, e.g. Amount, Frequency, etc. merged Alcohol\r\n y_pred = unmerge_entities(y_pred, quantity_events, \\\r\n quantity_entities, quantity, OUTSIDE)\r\n \r\n # Unmerge events, e.g. Type emerged for Alcohol, Drug, and Tobacco\r\n y_pred = unmerge_events(y_pred, type_events, \\\r\n type_, substance, OUTSIDE)\r\n\r\n # Combine sentence-level in word-level status labels\r\n y_pred = combine_seq(labels = y_pred, \r\n events = status_events, \r\n sent_entity = status_sent, \r\n seq_entity = status_seq, \r\n neg_label = OUTSIDE, \r\n check_pos = False, \r\n pos_label = None,\r\n neg_labels = [OUTSIDE, 0])\r\n\r\n \r\n y_pred = combine_seq(labels = y_pred, \r\n events = substance_events, \r\n sent_entity = substance_sent, \r\n seq_entity = substance_seq, \r\n neg_label = 0, \r\n check_pos = True, \r\n pos_label = 1,\r\n neg_labels = [OUTSIDE, 0])\r\n \r\n \r\n y_pred = remove_labels(y_pred, events_remove, entities_remove)\r\n\r\n\r\n for event in status_events:\r\n y_pred = rename_entity(y_pred, event, head_entity, event)\r\n\r\n to_standoff_corpus( \\\r\n brat_dest, \r\n fns = fns, \r\n text = text, \r\n tokens = tokenized, \r\n labels = y_pred, \r\n has_attribute = has_attribute)\r\n\r\n with open(fn_summary, 'a') as f: \r\n f.write(\"\\n\\tStandoff complete\")\r\n\r\n\r\n '''\r\n Bundle results and save\r\n '''\r\n \r\n return '''\r\n sent_count = {}\r\n long_count = {}\r\n word_count = {}\r\n note_count = {}\r\n '''.format(sent_count, long_count, word_count, note_count)\r\n\r\n\r\n\r\n'''\r\n \r\n Get start and stop indices of notes\r\n \r\n # Indices of note starts\r\n note_indices = []\r\n pattern = NOTE_START_PATTERN.format(category='.+', idx='.+')\r\n for i, sent in enumerate(result['corpus']): \r\n if re.match(pattern, \" \".join(sent)):\r\n note_indices.append(i)\r\n \r\n starts = note_indices\r\n stops = note_indices[1:] + [len(result['corpus'])]\r\n starts_stops = list(zip(starts, stops))\r\n indices = list(range(len(starts_stops)))\r\n print(\"Start and stop indices found: {}\".format(len(indices))) \r\n \r\n \r\n \r\n Determine which notes are likely to have substance abuse event\r\n \r\n # Get note indices with substance abuse event\r\n assert len(result['mask']) == len(result['corpus']), 'mask length does not match corpus'\r\n contains_event = []\r\n for i in indices: \r\n start, stop = starts_stops[i]\r\n start += 1\r\n contains_event.append(max(result['mask'][start:stop]))\r\n \r\n # Filter indices\r\n indices_sub = [ind for evt, ind in zip(contains_event, indices) if evt]\r\n print(\"All notes: {}\".format(len(indices))) \r\n print(\"Notes with substance abuse determined: {}\".format(len(indices_sub))) \r\n\r\n \r\n Label stats\r\n \r\n df_stats = get_label_stats(result['y_pred'])\r\n df_stats = {'label_stats': df_stats}\r\n dict_df_to_latex(df_stats, dest, \\\r\n ['Alcohol', 'Drug', 'Tobacco'], \r\n columns_int = ['Alcohol', 'Drug', 'Tobacco'], \r\n )\r\n \r\n \r\n \r\n \r\n Sample notes and write disk\r\n \r\n labeled_by_note = []\r\n dir_ = os.path.join(dest, 'labeled_subset')\r\n\r\n if os.path.exists(dir_):\r\n shutil.rmtree(dir_)\r\n os.makedirs(dir_)\r\n \r\n # Sample indices\r\n np.random.seed(4)\r\n indices_sample = np.random.choice(indices_sub, size=num_examples, \\\r\n replace=False)\r\n # Write to disk\r\n for j, i in enumerate(indices_sample):\r\n start, stop = starts_stops[i]\r\n start += 1\r\n\r\n # Get annotations as string\r\n labeled = labeled_as_string(result['corpus'][start:stop], \r\n result['y_pred'][start:stop]) \r\n labeled_note = \"\\n\\n\".join(labeled)\r\n \r\n # Write\r\n fn = os.path.join(dir_, '{}.txt'.format(i))\r\n with open(fn,'w') as f:\r\n f.write(labeled_note)\r\n print('Labeled examples written:\\t{}/{}'.format(j+1, num_examples))\r\n\r\n''' ","sub_path":"code/step905_mimic_summarize.py","file_name":"step905_mimic_summarize.py","file_ext":"py","file_size_in_byte":20291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"578528716","text":"# piEstimatorApprox.py\r\n# This code estimates pi using a series equation.\r\n\r\n\r\nimport numpy as np\r\n\r\ndef piEstimatorApprox(tol):\r\n values = []\r\n prevApproxList = [0]\r\n for k in range(1, 10000):\r\n values.append(((-1)**(k + 1)) / (2*k - 1))\r\n piEst = 4 * (np.sum(values))\r\n prevApproxList.append(piEst)\r\n prevApprox = prevApproxList[k - 1]\r\n approxPctRelError = ((piEst - abs(prevApprox)) / piEst ) * 100\r\n if abs(approxPctRelError) < tol:\r\n return piEst, approxPctRelError\r\n\r\nprint(\"Estimate of pi:\",str(piEstimatorApprox(10)))\r\nprint(\"Estimate of pi:\",str(piEstimatorApprox(0.1)))\r\n","sub_path":"piEstimatorApprox.py","file_name":"piEstimatorApprox.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"581779475","text":"'''get urls from useful_url.txt and get details from them.\n save titles and related url in modian.txt'''\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nuseful_list = []\n\nwith open('useful_url.txt', 'rt') as fp:\n useful_list.extend(fp.readlines())\nprint(useful_list)\nfor num in range(len(useful_list)):\n useful_list[num] = useful_list[num].strip('\\n').strip(\"'\")\ncontents = []\nprint(useful_list)\n\nfor url in useful_list:\n req = requests.get(url)\n if req.status_code is not None and req.status_code == 200:\n html = req.content\n if html:\n bsobj = BeautifulSoup(html, 'lxml')\n content = bsobj.find_all('p')[1].get_text()\n content = (content, url)\n contents.append(content)\n print(str(content))\n else:\n print('nothing in this page')\n\nwith open('modian.txt', 'w+') as fp:\n for content in contents:\n fp.write(content[0].encode('utf-8') + ' ------ ' + content[1])\n fp.write('\\n')","sub_path":"modian/get_titles.py","file_name":"get_titles.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"394672125","text":"import os\nimport argparse\nimport tensorflow as tf\n\nfrom process_data import ProcessData\nfrom data_io import IO\nfrom model import grainedDKTModel, BatchGenerator, run\n\nDATA_FOLDER = '../data/'\nASSISTment_Datafile = 'skill_builder_data.csv'\nASSISTment_train = '../data/training_ASSISTment_all.csv'\nASSISTment_test = '../data/testing_ASSISTment_all.csv'\nASSISTment_evaluate_result = 'ASSISTment_results.csv'\nASSISTment_Category_MappingFile = '../data/skill-category(UTF-8).csv'\nMODEL_LOG_FOLDER = \"../logs/\"\nMODEL_FOLDER = \"../model/\"\nMODEL_FILE = 'model.ckpt'\n\nPKU_Datafile = '../data/PKU_MOOC/question_sessions.csv'\nPKU_train = '../data/PKU_MOOC/training.csv'\nPKU_test = '../data/PKU_MOOC/testing.csv'\nPKU_evaluate_result = '../data/PKU_MOOC/PKU_results.csv'\nPKU_Category_MappingFile = '../data/PKU_MOOC/question_category.csv'\n\nfname_TrainData = PKU_train\nfname_TestData = PKU_test\nfname_MapData = PKU_Category_MappingFile\nfname_Result = PKU_evaluate_result\n\nDATA_READY = True\nSILENT_WARNINGS = True # to silent the warnings (https://github.com/tensorflow/tensorflow/issues/8037)\n\nif not DATA_READY:\n PrePrcess = ProcessData(data_folder = DATA_FOLDER)\n PreProcess.ASSISTment_load_save(ASSISTment_Datafile)\nif SILENT_WARNINGS:\n os.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\ndef main(args):\n batch_size = args.batch_size\n n_epoch = args.n_epoch\n n_step = args.n_step\n keep_prob = args.keep_prob\n n_hidden_units = args.n_hidden_units\n embedding_size = args.embedding_size\n initial_learning_rate=args.initial_learning_rate\n final_learning_rate=args.final_learning_rate\n assert args.embedding in ['random', 'one_hot'], 'Unrecognized embedding method'\n random_embedding = True if args.embedding == 'random' else False\n assert args.granularity in ['single', 'multi'], 'Unrecognized granularity'\n multi_granined = True if args.granularity == 'multi' else False\n assert args.granularity_out in ['single', 'multi'], 'Unrecognized granularity'\n multi_granined_out = True if args.granularity_out == 'multi' else False\n assert args.train_mode in ['step', 'epoch'], 'Unreconized traning mode (please specify step or epoch)'\n \n PrepData = IO()\n train_response_list, question_list = PrepData.load_model_input(fname_TrainData, sep=',')\n test_response_list, question_list = PrepData.load_model_input(fname_TestData, sep=',', question_list=question_list)\n id_encoding = PrepData.question_id_1hotencoding(question_list)\n category_map_dict = PrepData.load_category_map(fname_MapData, sep=',')\n category_encoding = PrepData.category_id_1hotencoding(category_map_dict)\n\n skill2category_map =PrepData.skill_idx_2_category_idx(category_map_dict, category_encoding)\n n_id = len(id_encoding)\n n_categories = len(category_encoding)\n\n # print {skill: category_encoding[category_map_dict[skill]] for skill in category_map_dict.keys()}\n # print skill2category_map\n\n train_batches = BatchGenerator(train_response_list, batch_size, id_encoding, n_id, n_id, n_categories, random_embedding=random_embedding, skill_to_category_dict=skill2category_map, multi_granined_out=multi_granined_out)\n test_batches = BatchGenerator(test_response_list, batch_size, id_encoding, n_id, n_id, n_categories, random_embedding=random_embedding, skill_to_category_dict=skill2category_map, multi_granined_out=multi_granined_out)\n\n sess = tf.Session()\n run(sess, train_batches, test_batches, \\\n option=args.train_mode, record_performance=True, \\\n model_saved_path=os.path.join(MODEL_FOLDER, MODEL_FILE),\n n_step=n_step, random_embedding=random_embedding, multi_granined=multi_granined, \\\n n_categories=n_categories, out_folder=DATA_FOLDER, out_file=fname_Result, \\\n keep_prob=keep_prob, n_hidden_units=n_hidden_units, embedding_size=embedding_size, \\\n initial_learning_rate=0.001, final_learning_rate=0.00001,\n multi_granined_out=multi_granined_out)\n # tensorboard --logdir logs\n writer = tf.summary.FileWriter(MODEL_LOG_FOLDER, sess.graph) # http://localhost:6006/#graphs on mac\n sess.close()\n \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch-size', \n dest='batch_size',\n # required=True,\n default=16,\n type=int,\n help=\"Batch size\")\n parser.add_argument('--train-steps',\n dest='n_step',\n # required=True,\n default=5001,\n type=int,\n help='Maximum number of training steps to perform.')\n parser.add_argument('--train-epochs',\n dest='n_epoch',\n # required=True,\n default=20,\n type=int,\n help='Maximum number of training epochs to perform.')\n parser.add_argument('--train-mode', \n dest='train_mode',\n default=\"step\",\n type=str,\n help=\"By Step or By Epoch\")\n parser.add_argument('--num-hiddenunits', \n dest='n_hidden_units',\n default=200,\n type=int,\n help=\"Number of hidden units\")\n parser.add_argument('--embedding-size', \n dest='embedding_size',\n default=200,\n type=int,\n help=\"Size of embedded input vectors\")\n parser.add_argument('--droupout-keep', \n dest='keep_prob',\n default=0.5,\n type=float,\n help=\"Size of embedded input vectors\")\n parser.add_argument('--learningrate-init', \n dest='initial_learning_rate',\n default=0.001,\n type=float,\n help=\"Initialized learning rate\")\n parser.add_argument('--learningrate-final', \n dest='final_learning_rate',\n default=0.00001,\n type=float,\n help=\"Final learning rate\")\n parser.add_argument('--input-embedding', \n dest='embedding',\n default=\"random\",\n type=str,\n help=\"Use randomized embedding or 1-hot embedding as inputs?\")\n parser.add_argument('--input-grain', \n dest='granularity',\n default=\"single\",\n type=str,\n help=\"Use standard information or multi-grained information?\")\n parser.add_argument('--output-grain', \n dest='granularity_out',\n default=\"single\",\n type=str,\n help=\"Use standard information or multi-grained information for output?\")\n parse_args, unknown = parser.parse_known_args()\n # Set python level verbosity\n tf.logging.set_verbosity('INFO')\n args = parser.parse_args()\n main(args)","sub_path":"code_copy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"87024781","text":"from datetime import datetime\nfrom collections import OrderedDict\n\nfrom flask import render_template, flash, redirect, session, url_for, request, g\nfrom flask.ext.login import login_user, logout_user, current_user, login_required\nfrom sqlalchemy.sql.expression import func\n\nfrom config import POSTS_PER_PAGE, ADMINS\nfrom app import app, db, lm, oid\nfrom forms import GoogleLoginForm, EditForm, PostForm, JournalEntryForm, ProjectEulerForm\nfrom models import User, Post, Tag, Project, Journal, ProjectEuler, Virtues\n\n\n@app.route('/')\ndef index():\n return render_template(\"index.html\")\n\n#Delete later\n@app.route('/deco')\ndef deco():\n return render_template(\"map.html\")\n\n@app.route('/writing', methods = ['GET', 'POST'])\n@app.route('/writing/', methods = ['GET', 'POST'])\ndef writing(page = 1):\n categories = set([p.category for p in Post.query.filter_by(published=True)])\n posts = Post.query.filter_by(published=True).order_by(Post.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False)\n return render_template(\"blog.html\", posts = posts, categories = categories)\n\n@app.route('/writing/')\ndef post(post_slug):\n post = Post.query.filter_by(slug = post_slug).first()\n if post == None:\n return redirect(url_for('post_not_found'))\n return render_template(\"post.html\", post = post)\n\n@app.route('/admin', methods = ['GET', 'POST'])\n@login_required\ndef admin(page = 1):\n posts = Post.query.order_by(Post.timestamp.desc()).paginate(page, POSTS_PER_PAGE, False)\n return render_template(\"admin.html\", posts = posts, user = g.user)\n\n\n@app.route('/admin/edit-post', methods = ['GET', 'POST'])\n@app.route('/admin/edit-post/', methods = ['GET', 'POST'])\n@login_required\ndef edit_post(post_id = None):\n if post_id is not None:\n post = Post.query.get(post_id)\n else:\n #Create a new post\n post = Post(\n title = \"\",\n summary = \"\",\n body = \"\",\n tags = \"\",\n category = \"\",\n timestamp = datetime.utcnow(),\n published = False,\n author = g.user)\n form = PostForm(obj=post)\n form.tags.choices = [t.tag for t in Tag.query.order_by('tag')]\n form.category.choices = set([p.category for p in Post.query.all()])\n if form.validate_on_submit():\n post.title = form.title.data\n post.summary = form.summary.data\n post.body = form.body.data\n post.tags = form.tags.data\n post.category = form.category.data\n post.slugify_title()\n if post_id == None:\n db.session.add(post)\n if request.form['btn'] == 'Save':\n db.session.commit()\n flash('Your post has been saved.')\n return redirect(url_for('edit_post', post_id = post.id))\n elif request.form['btn'] == 'Publish':\n post.published = True\n db.session.commit()\n flash('Your post has been published.')\n return redirect(url_for('index'))\n return render_template(\"edit_post.html\", form = form, post = post)\n\n@app.route('/admin/new-journal-entry', methods = ['GET', 'POST'])\ndef new_journal_entry():\n j = Journal.query.order_by(Journal.timestamp.desc()).first()\n most_recent = j.timestamp\n timestamp = datetime.utcnow()\n if most_recent.month == timestamp.month and most_recent.day == timestamp.day:\n flash(\"You've already published a journal entry today\")\n return redirect(url_for('index'))\n form = JournalEntryForm()\n virtue = Virtues.query.order_by(func.random()).first()\n if form.validate_on_submit():\n entry = Journal(\n timestamp = timestamp,\n entry = form.entry.data,\n temperance = form.temperance.data,\n silence = form.silence.data,\n order = form.order.data,\n resolution = form.resolution.data,\n frugality = form.frugality.data,\n industry = form.industry.data,\n sincerity = form.sincerity.data,\n justice = form.justice.data,\n moderation = form.moderation.data,\n cleanliness = form.cleanliness.data,\n tranquility = form.tranquility.data,\n chastity = form.chastity.data,\n humility = form.humility.data,\n )\n db.session.add(entry)\n db.session.commit()\n flash('Your journal entry has been published.')\n return redirect(url_for('index'))\n return render_template(\"new_journal_entry.html\", form = form, timestamp = timestamp, virtue = virtue)\n\n\n@app.route('/admin/edit-project-euler', methods = ['GET', 'POST'])\n@app.route('/admin/edit-project-euler/', methods = ['GET', 'POST'])\n@login_required\ndef edit_project_euler_problem(problem_id = None):\n if problem_id is not None:\n problem = ProjectEuler.query.get(problem_id)\n else:\n #Create a new post\n problem = ProjectEuler(\n problem_number = \"\",\n programming_language = \"\",\n code = \"\",\n timestamp = datetime.utcnow(),\n published = False,\n )\n form = ProjectEulerForm(obj=problem)\n if form.validate_on_submit():\n problem.problem_number = int(form.problem_number.data)\n problem.programming_language = form.programming_language.data\n problem.code = form.code.data\n if problem_id == None:\n db.session.add(problem)\n if request.form['btn'] == 'Save':\n db.session.commit()\n flash('Your post has been saved.')\n return redirect(url_for('edit_project_euler_problem', problem_id = problem.id))\n elif request.form['btn'] == 'Publish':\n problem.published = True\n db.session.commit()\n flash('Your post has been published.')\n return redirect(url_for('index'))\n return render_template(\"edit_project_euler_problem.html\", form = form, problem = problem)\n\n@app.route('/coding', methods = ['GET'])\ndef coding():\n projects = Project.projects\n return render_template(\"coding.html\", projects = projects)\n\n@app.route('/coding/')\ndef project(project_slug):\n return render_template(project_slug + \".html\")\n\n@app.route('/coding/project-euler')\ndef project_euler():\n problems = ProjectEuler.query.order_by(ProjectEuler.programming_language.asc())\n p_dict = {}\n for p in problems:\n if p.problem_number in p_dict.keys():\n p_dict[p.problem_number].append(p)\n else:\n p_dict[p.problem_number] = [p]\n problems_sorted = OrderedDict(sorted(p_dict.items(), key=lambda t: t[0]))\n\n return render_template(\"project_euler.html\", problems_sorted = problems_sorted)\n\n@app.route('/coding/project-euler/')\ndef project_euler_problem(problem_id):\n problem = ProjectEuler.query.get(problem_id)\n return render_template(\"project_euler_problem.html\", problem = problem)\n\n@app.route('/reflecting', methods = ['GET'])\ndef journal():\n entries = Journal.query.order_by(Journal.timestamp.desc())\n return render_template(\"journal.html\", entries = entries)\n\n@app.route('/reflecting/')\ndef journal_entry(entry_id):\n entry = Journal.query.get(entry_id)\n prev = entry_id - 1\n next = entry_id + 1\n return render_template(\"journal_entry.html\", entry = entry, prev = prev, next = next)\n\n@app.route('/admin/delete-post/', methods = ['GET', 'POST'])\n@login_required\ndef delete_post(post_id = None):\n if post_id is not None:\n post = Post.query.get(post_id)\n db.session.delete(post)\n db.session.commit()\n return redirect(url_for('admin'))\n\n@app.route('/who')\ndef who():\n admins = User.query.filter(User.email.in_(ADMINS))\n return render_template('who.html', admins=admins)\n\n@app.route('/admin/edit-profile', methods = ['GET', 'POST'])\n@login_required\ndef edit_profile():\n form = EditForm(g.user.username)\n if form.validate_on_submit():\n g.user.username = form.username.data\n g.user.firstname = form.firstname.data\n g.user.lastname = form.lastname.data\n g.user.about_me = form.about_me.data\n db.session.add(g.user)\n db.session.commit()\n flash('Your changes have been saved.')\n return redirect(url_for('edit'))\n else:\n form.username.data = g.user.username\n form.firstname.data = g.user.firstname\n form.lastname.data = g.user.lastname\n form.about_me.data = g.user.about_me\n return render_template('edit_profile.html', form = form)\n\n@app.before_request\ndef before_request():\n g.user = current_user\n if g.user.is_authenticated():\n g.user.last_seen = datetime.utcnow()\n db.session.add(g.user)\n db.session.commit()\n\n##############\n### ERRORS ###\n##############\n\n@app.route('/post-not-found')\ndef post_not_found():\n return render_template('404.html'), 404\n\n@app.errorhandler(404)\ndef internal_error(error):\n return render_template('404.html'), 404\n\n@app.errorhandler(500)\ndef internal_error(error):\n db.session.rollback()\n return render_template('500.html'), 500\n\n#############\n### LOGIN ###\n#############\n@app.route('/login', methods = ['GET', 'POST'])\n@oid.loginhandler\ndef login():\n google_open_id = \"https://www.google.com/accounts/o8/id\"\n if g.user is not None and g.user.is_authenticated():\n return redirect(url_for('index'))\n form = GoogleLoginForm()\n if form.validate_on_submit():\n session['remember_me'] = form.remember_me.data\n return oid.try_login(google_open_id, ask_for = ['nickname', 'email'])\n return render_template('login.html', title = 'Sign In', form = form)\n\n@oid.after_login\ndef after_login(resp):\n if resp.email not in ADMINS or resp.email is None or resp.email == \"\":\n flash('Invalid login. Please try again.')\n return redirect(url_for('login'))\n user = User.query.filter_by(email = resp.email).first()\n if user is None:\n username = resp.nickname\n if username is None or username == \"\":\n username = resp.email.split('@')[0]\n user = User(username = username, email = resp.email)\n db.session.add(user)\n db.session.commit()\n remember_me = False\n if 'remember_me' in session:\n remember_me = session['remember_me']\n session.pop('remember_me', None)\n login_user(user, remember = remember_me)\n return redirect(request.args.get('next') or url_for('index'))\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n@lm.user_loader\ndef load_user(id):\n return User.query.get(int(id))","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"197102070","text":"from django.contrib.auth.models import User as DjangoUser\nfrom django.contrib.auth.models import Group\nfrom home.models.salesforce import ClassEnrollment, Contact, ClassOffering\nfrom home.models.models import UserProfile, Classroom, Attendance, Session\nfrom django.core.mail import send_mail\nfrom django.template.loader import render_to_string\nfrom django.utils.html import strip_tags\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom home.forms import AddVolunteersForm, AddStudentsForm\nfrom datetime import timedelta, datetime\n\n\ndef create_user_with_profile(form, random_password):\n new_user = DjangoUser.objects.create_user(\n username=\"%s.%s\"\n % (form.cleaned_data.get(\"first_name\"), form.cleaned_data.get(\"last_name\")),\n email=form.cleaned_data.get(\"email\"),\n first_name=form.cleaned_data.get(\"first_name\"),\n last_name=form.cleaned_data.get(\"last_name\"),\n password=random_password,\n )\n new_user = parse_new_user(new_user, form)\n new_user.save()\n return new_user\n\n\ndef parse_new_user(new_user, form):\n birthdate = form.cleaned_data.get(\"birthdate\")\n print(birthdate.month)\n print(birthdate.day)\n print(birthdate.month)\n new_user.userprofile.change_pwd = True\n new_user.userprofile.salesforce_id = \"%s%s%s%s%s\" % (\n form.cleaned_data.get(\"first_name\")[:3].lower(),\n form.cleaned_data.get(\"last_name\")[:3].lower(),\n '%04d' % birthdate.year,\n '%02d' % birthdate.month,\n '%02d' % birthdate.day,\n )\n new_user.userprofile.date_of_birth = birthdate\n return new_user\n\n\ndef enroll_in_class(form, user):\n ClassEnrollment.objects.get_or_create(\n name=form.cleaned_data.get(\"course\"),\n created_by=form.cleaned_data.get(\"created_by\"),\n contact=user,\n status=\"Enrolled\",\n class_offering=form.cleaned_data.get(\"course\"),\n )\n\n\ndef setup_classroom_teachers(request, form):\n classroom = Classroom.objects.create(\n teacher_id=UserProfile.objects.get(\n salesforce_id=form.cleaned_data.get(\"teacher\").client_id.lower()\n ).user_id,\n teacher_assistant_id=UserProfile.objects.get(\n salesforce_id=form.cleaned_data.get(\"teacher_assistant\").client_id.lower()\n ).user_id,\n course=form.cleaned_data.get(\"course\").name,\n )\n teacher_email_list = [\n DjangoUser.objects.get(id=classroom.teacher_id).email,\n DjangoUser.objects.get(id=classroom.teacher_assistant_id).email,\n ]\n enroll_in_class(form, form.cleaned_data.get(\"teacher\"))\n enroll_in_class(form, form.cleaned_data.get(\"teacher_assistant\"))\n email_classroom(request, teacher_email_list, classroom.course)\n return classroom\n\n\ndef add_volunteers_and_students_to_classroom(request, form, classroom):\n email_list = []\n for volunteer in form.cleaned_data.get(\"volunteers\"):\n enroll_in_class(form, volunteer)\n django_user = UserProfile.objects.get(\n salesforce_id=volunteer.client_id.lower()\n ).user_id\n classroom.volunteers.add(django_user)\n email_list.append(DjangoUser.objects.get(id=django_user).email)\n for student in form.cleaned_data.get(\"students\"):\n enroll_in_class(form, student)\n django_user = UserProfile.objects.get(\n salesforce_id=student.client_id.lower()\n ).user_id\n classroom.students.add(django_user)\n email_list.append(DjangoUser.objects.get(id=django_user).email)\n email_classroom(request, email_list, classroom.course)\n\n\ndef email_new_user(request, email, first_name, account_type, username, password):\n subject = \"%s - Your new %s account has been set up\" % (first_name, account_type)\n msg_html = render_to_string(\n \"email_templates/new_user_email.html\",\n {\n \"first_name\": first_name,\n \"email\": email,\n \"username\": username,\n \"password\": password,\n \"account_type\": account_type,\n },\n )\n from_user = settings.EMAIL_HOST_USER\n send_mail(\n subject=subject,\n message=strip_tags(msg_html),\n from_email=from_user,\n recipient_list=[\"tyler.iams@gmail.com\"], # Will replace with email\n html_message=msg_html,\n )\n messages.add_message(request, messages.SUCCESS, \"Email sent successfully\")\n\n\ndef email_classroom(request, email_list, classroom_name):\n subject = \"Your Mission Bit %s Classroom Has Been Created\" % classroom_name\n msg_html = render_to_string(\n \"email_templates/new_classroom_email.html\", {\"classroom_name\": classroom_name}\n )\n from_user = settings.EMAIL_HOST_USER\n recipient_list = [\n \"tyler.iams@gmail.com\",\n \"iams.sophia@gmail.com\",\n ] # Will replace with email_list\n send_mail(\n subject=subject,\n message=strip_tags(msg_html),\n from_email=from_user,\n recipient_list=recipient_list,\n html_message=msg_html,\n )\n messages.add_message(request, messages.SUCCESS, \"Email sent successfully\")\n\n\ndef get_emails_from_form(form):\n email_list = []\n groups = form.getlist(\"recipient_groups\")\n for group in groups:\n group_name = Group.objects.get(id=group)\n users = DjangoUser.objects.filter(groups__name=group_name)\n for user in users:\n email_list.append(user.email)\n classrooms = form.getlist(\"recipient_classrooms\")\n for classroom in classrooms:\n classroom_object = Classroom.objects.get(id=classroom)\n teacher = DjangoUser.objects.get(id=classroom_object.teacher_id).email\n email_list.append(teacher.email)\n teacher_assistant = DjangoUser.objects.get(\n id=classroom_object.teacher_assistant_id\n ).email\n email_list.append(teacher_assistant.email)\n students = DjangoUser.objects.filter(\n classroom_students__course=classroom_object.course\n )\n volunteers = DjangoUser.objects.filter(\n classroom_volunteers__course=classroom_object.course\n )\n for student in students:\n email_list.append(student.email)\n for volunteer in volunteers:\n email_list.append(volunteer.email)\n return email_list\n\n\ndef email_announcement(request, form, email_list):\n subject = form.instance.title\n msg_html = render_to_string(\n \"email_templates/announcement_email.html\",\n {\n \"subject\": form.instance.title,\n \"message\": form.instance.announcement,\n \"from\": form.instance.created_by,\n },\n )\n from_user = settings.EMAIL_HOST_USER\n recipient_list = [\n \"tyler.iams@gmail.com\",\n \"iams.sophia@gmail.com\",\n ] # Will replace with email_list\n send_mail(\n subject=subject,\n message=strip_tags(msg_html),\n from_email=from_user,\n recipient_list=recipient_list,\n html_message=msg_html,\n )\n messages.add_message(request, messages.SUCCESS, \"Recipients Successfully Emailed\")\n\n\ndef add_students_to_student_dict(classroom):\n student_dict = {}\n for x, student in enumerate(classroom.students.all()):\n student_user = DjangoUser.objects.get(id=student.id)\n student_dict[\"student%s\" % x] = \"%s %s\" % (\n student_user.first_name,\n student_user.last_name,\n )\n return student_dict\n\n\ndef add_volunteers_to_volunteer_dict(classroom):\n volunteer_dict = {}\n for x, volunteer in enumerate(classroom.volunteers.all()):\n volunteer_user = DjangoUser.objects.get(id=volunteer.id)\n volunteer_dict[\"volunteer%s\" % x] = \"%s %s\" % (\n volunteer_user.first_name,\n volunteer_user.last_name,\n )\n return volunteer_dict\n\n\ndef change_classroom_teacher(request):\n teacher_contact = get_contact_by_user_id(request.POST[\"former_teacher\"])\n class_offering = get_class_offering_by_id(request.POST[\"course_id\"])\n new_teacher = get_contact_by_user_id(request.POST[\"teacher\"])\n classroom = Classroom.objects.get(id=request.POST[\"course_id\"])\n classroom.teacher_id = request.POST[\"teacher\"]\n classroom.save()\n remove_enrollment(teacher_contact, class_offering)\n ClassEnrollment.objects.get_or_create(\n created_by=class_offering.created_by,\n contact=new_teacher,\n status=\"Enrolled\",\n class_offering=class_offering,\n )\n class_offering.instructor = new_teacher\n class_offering.save()\n\n\ndef change_classroom_ta(request):\n ta_contact = get_contact_by_user_id(request.POST[\"former_ta\"])\n class_offering = get_class_offering_by_id(request.POST[\"course_id\"])\n new_ta = get_contact_by_user_id(request.POST[\"teacher\"])\n classroom = Classroom.objects.get(id=request.POST[\"course_id\"])\n classroom.teacher_assistant_id = request.POST[\"teacher\"]\n classroom.save()\n remove_enrollment(ta_contact, class_offering)\n ClassEnrollment.objects.get_or_create(\n created_by=class_offering.created_by,\n contact=new_ta,\n status=\"Enrolled\",\n class_offering=class_offering,\n )\n\n\ndef remove_volunteer(request):\n vol_contact = get_contact_by_user_id(request.POST[\"former_vol\"])\n class_offering = get_class_offering_by_id(request.POST[\"course_id\"])\n classroom = Classroom.objects.get(id=request.POST[\"course_id\"])\n classroom.volunteers.remove(request.POST[\"former_vol\"])\n remove_enrollment(vol_contact, class_offering)\n\n\ndef remove_student(request):\n student_contact = get_contact_by_user_id(request.POST[\"former_student\"])\n class_offering = get_class_offering_by_id(request.POST[\"course_id\"])\n classroom = Classroom.objects.get(id=request.POST[\"course_id\"])\n classroom.students.remove(request.POST[\"former_student\"])\n remove_enrollment(student_contact, class_offering)\n\n\ndef add_volunteers(request):\n form = AddVolunteersForm(request.POST)\n class_offering = get_class_offering_by_id(request.POST[\"course_id\"])\n classroom = Classroom.objects.get(id=request.POST[\"course_id\"])\n if form.is_valid():\n for volunteer in form.cleaned_data.get(\"volunteers\"):\n vol_contact = get_contact_by_user_id(volunteer)\n ClassEnrollment.objects.create(\n created_by=class_offering.created_by,\n contact=vol_contact,\n status=\"Enrolled\",\n class_offering=class_offering,\n )\n classroom.volunteers.add(volunteer)\n\n\ndef add_students(request):\n form = AddStudentsForm(request.POST)\n class_offering = get_class_offering_by_id(request.POST[\"course_id\"])\n classroom = Classroom.objects.get(id=request.POST[\"course_id\"])\n if form.is_valid():\n for student in form.cleaned_data.get(\"students\"):\n student_contact = get_contact_by_user_id(student)\n ClassEnrollment.objects.create(\n created_by=class_offering.created_by,\n contact=student_contact,\n status=\"Enrolled\",\n class_offering=class_offering,\n )\n classroom.students.add(student)\n\n\ndef remove_enrollment(contact, class_offering):\n old_enrollment = ClassEnrollment.objects.get(\n contact=contact, status=\"Enrolled\", class_offering=class_offering\n )\n created_by = old_enrollment.created_by\n old_enrollment.delete()\n return created_by\n\n\ndef get_contact_by_user_id(id):\n return Contact.objects.get(\n client_id=UserProfile.objects.get(user_id=id).salesforce_id\n )\n\n\ndef get_class_offering_by_id(id):\n course_name = get_course_name_by_id(id)\n return ClassOffering.objects.get(name=course_name)\n\n\ndef get_course_name_by_id(id):\n return Classroom.objects.get(id=id).course\n\n\ndef sync_attendance_with_salesforce_class_offerings():\n \"\"\"\n This method is fluid; in its current state it will duplicate entries\n in your postgres templates database if you've already got templates data!\n Only use if you don't have templates data but do have Classroom\n data.\n \"\"\"\n for classoffering in ClassOffering.objects.all():\n if (classoffering.name == \"Test_Class\"):\n continue\n dates = class_offering_meeting_dates(classoffering)\n classroom = Classroom.objects.get(course=classoffering.name)\n for day in dates:\n session = Session.objects.create()\n for student in classroom.students.all():\n Attendance.objects.create(\n student_id=student.id,\n session_id=session.id,\n classroom_id=classroom.id,\n date=day,\n )\n\n\ndef class_offering_meeting_dates(class_offering):\n int_days = get_integer_days(class_offering)\n class_range = class_offering.end_date - class_offering.start_date\n dates = []\n for i in range(class_range.days + 1):\n the_date = class_offering.start_date + timedelta(days=i)\n if the_date.weekday() in int_days:\n dates.append(the_date)\n return dates\n\n\ndef get_integer_days(class_offering):\n if class_offering.meeting_days == \"M-F\":\n return [0, 1, 2, 3, 4]\n elif class_offering.meeting_days == \"M/W\":\n return [0, 2]\n elif class_offering.meeting_days == \"T/R\":\n return [1, 3]\n","sub_path":"staff/staff_views_helper.py","file_name":"staff_views_helper.py","file_ext":"py","file_size_in_byte":13213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"259968710","text":"from handlers.BaseCommandHandlerParameter import BaseCommandHandlerParameter\n\nclass FindContoursHandlerParameter(BaseCommandHandlerParameter):\n def __init__(self, objectParameter,pl_filter,path_file, name_safe_train_test, size_of_image):\n self.objectParameter = objectParameter\n self.pl_filter = pl_filter\n self.path_file = path_file\n self.name_safe_train_test = name_safe_train_test\n self.size_of_image = size_of_image\n\n\n","sub_path":"handlers/findContoursPhotoHandler/findContoursHandlerParameter.py","file_name":"findContoursHandlerParameter.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"64779327","text":"from kivy.uix.screenmanager import Screen\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.label import Label\nfrom kivy.uix.popup import Popup\nfrom kivy.properties import ObjectProperty\nfrom popups import ConfirmPopup\nfrom functools import partial\nimport time\n\n\nclass StartScreen(Screen):\n app_obj = ObjectProperty()\n root_obj = ObjectProperty()\n\n def open_class_popup(self):\n root = self.root_obj\n args = {'item': root.selected_class, 'item_list': root.class_list,\n 'attribute': 'class_', 'callback': self.select_class,\n 'title': 'Choisissez une classe', 'size_hint_y': 0.3}\n return root.open_choice_popup(**args)\n\n def select_class(self, a_class):\n self.active_class_label.text = \"{}\".format(a_class.class_)\n self.root_obj.selected_class = a_class\n\n def open_skill_set_popup(self):\n args = {'item': self.root_obj.selected_skill_set,\n 'item_list': self.root_obj.skill_set_list,\n 'attribute': 'set_name',\n 'callback': self.select_skill_set,\n 'title': 'Choisissez un jeu de compétences',\n 'size_hint_y': 0.3}\n return self.root_obj.open_choice_popup(**args)\n\n def select_skill_set(self, a_set):\n self.active_skill_set_label.text = \"{}\".format(a_set.set_name)\n self.root_obj.selected_skill_set = a_set\n\n def display_behaviour(self):\n self.display_header.clear_widgets()\n self.display_label.clear_widgets()\n output = self.app_obj.data_output\n data = {}\n header = [\"prenom\",\n \"Bavardage\", \"Insolence\", \"Inactivite\", \"Travail non fait\"]\n header_layout = GridLayout(cols=len(header))\n [header_layout.add_widget(Label(text=item,\n font_size='12sp')) for item in header]\n grid_layout = GridLayout(cols=len(header), size_hint_y=None)\n grid_layout.bind(minimum_height=grid_layout.setter('height'))\n for key in output:\n data[key] = output[key]\n try:\n data[key].pop('class')\n data[key].pop('name')\n except KeyError:\n pass\n row = [data[key][\"surname\"]]\n for behaviour in header[1:]:\n try:\n item = data[key][behaviour]\n row.append(\"\\n\".join(str(item[i]) for i in item))\n except KeyError:\n row.extend([\" \"])\n [grid_layout.add_widget(Label(text=item, size_hint_y=None,\n height='40dp',\n font_size='12sp')) for item in row]\n for label in header_layout.children:\n if label.text != \"prenom\":\n label.text = label.text[:4]\n self.display_header.add_widget(header_layout)\n self.display_label.add_widget(grid_layout)\n\n def display_skills(self):\n self.display_header.clear_widgets()\n self.display_label.clear_widgets()\n output = self.app_obj.data_output\n data = {}\n header = [\"prenom\"]\n header.extend([skill.title for skill in self.root_obj.active_skills])\n header_layout = GridLayout(cols=len(header))\n [header_layout.add_widget(Label(text=item,\n font_size='12sp')) for item in header]\n grid_layout = GridLayout(cols=len(header), size_hint_y=None)\n grid_layout.bind(minimum_height=grid_layout.setter('height'))\n for key in output:\n data[key] = output[key]\n try:\n data[key].pop('class')\n data[key].pop('name')\n except KeyError:\n pass\n row = [data[key][\"surname\"]]\n for skill in header[1:]:\n try:\n item = data[key][skill]\n row.append(\", \".join(str(item[i]) for i in item))\n except KeyError:\n row.extend([\" \"])\n [grid_layout.add_widget(Label(text=item, size_hint_y=None,\n height='40dp',\n font_size='12sp')) for item in row]\n for label in header_layout.children:\n if label.text != \"prenom\":\n label.text = label.text[:4]\n self.display_header.add_widget(header_layout)\n self.display_label.add_widget(grid_layout)\n\n\nclass SkillsScreen(Screen):\n root_obj = ObjectProperty()\n app_obj = ObjectProperty()\n selected_student = ObjectProperty()\n selected_skill = ObjectProperty()\n student_review = ObjectProperty(GridLayout())\n confirm_popup = ObjectProperty()\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.bind(selected_student=self.display_stud_skills)\n self.bind(selected_skill=self.display_stud_skills)\n\n def open_student_popup(self):\n args = {'item': self.selected_student,\n 'item_list': self.root_obj.active_students,\n 'attribute': 'surname',\n 'callback': self.select_student,\n 'title': 'Choisissez un élève',\n 'size_hint_y': 1}\n return self.root_obj.open_choice_popup(**args)\n\n def _on_answer(self, func, instance, answer):\n self.confirm_popup.dismiss()\n if answer == 'yes':\n return func()\n else:\n return\n\n def select_student(self, student):\n self.student_name.text = \"{} {}\".format(student.surname,\n student.name)\n self.selected_student = student\n\n def select_skill(self, skill):\n self.skill_name.text = skill.title\n self.skill_summary.text = skill.summary\n self.selected_skill = skill\n\n def open_skills_popup(self):\n args = {'item': self.selected_skill,\n 'item_list': self.root_obj.active_skills,\n 'attribute': 'title',\n 'callback': self.select_skill,\n 'title': 'Choisissez une compétence',\n 'size_hint_y': 0.4}\n return self.root_obj.open_choice_popup(**args)\n\n def pre_set_student_skill(self, value):\n try:\n skill = self.selected_skill.title\n student = self.selected_student\n content = ConfirmPopup(text=\"Confirmez la note:\\n\\n{} {}\\n\\n\"\n \"{} {}\".format(\n skill, value, student.surname,\n student.name))\n func = partial(self.set_student_skill, value)\n __on_answer = partial(self._on_answer, func)\n content.bind(on_answer=__on_answer)\n self.confirm_popup = Popup(title=\"Confirmation\",\n content=content,\n size_hint_y=.4,\n auto_dismiss=False)\n self.confirm_popup.open()\n except AttributeError:\n pass\n\n def set_student_skill(self, value):\n student = self.selected_student.id_\n output = self.app_obj.data_output\n skill = self.selected_skill.title\n try:\n length = len(output[student][skill])\n output[student][skill][length] = value\n except KeyError:\n try:\n output[student][skill] = {0: value}\n except KeyError:\n output[student] = self.students_data[student]\n output[student][skill] = {0: value}\n output._is_changed = True\n output.store_sync()\n\n def display_stud_skills(self, *ignore):\n try:\n assert self.selected_student and self.selected_skill\n self.student_review.add_widget(Label(text='caca',\n size_hint_y=.8))\n except AssertionError:\n pass\n\n\nclass BehaviourScreen(Screen):\n app_obj = ObjectProperty()\n root_obj = ObjectProperty()\n selected_student = ObjectProperty()\n confirm_popup = ObjectProperty()\n\n def open_student_popup(self):\n args = {'item': self.selected_student,\n 'item_list': self.root_obj.active_students,\n 'attribute': 'surname',\n 'callback': self.select_student,\n 'title': 'Choisissez un élève',\n 'size_hint_y': 1}\n return self.root_obj.open_choice_popup(**args)\n\n def select_student(self, student):\n self.student_name.text = \"{} {}\".format(student.surname,\n student.name)\n self.selected_student = student\n\n def _on_answer(self, func, instance, answer):\n self.confirm_popup.dismiss()\n if answer == 'yes':\n return func()\n else:\n return\n\n def pre_set_student_disobedience(self, value):\n try:\n student = self.selected_student\n content = ConfirmPopup(text=\"Confirmez la sanction:\\n\\n{}\\n\\n\"\n \"{} {}\".format(\n value, student.surname,\n student.name))\n func = partial(self.set_student_disobedience, value)\n __on_answer = partial(self._on_answer, func)\n content.bind(on_answer=__on_answer)\n self.confirm_popup = Popup(title=\"Confirmation\",\n content=content,\n size_hint_y=.4,\n auto_dismiss=False)\n self.confirm_popup.open()\n except AttributeError:\n pass\n\n def set_student_disobedience(self, value):\n time_ = time.strftime(\"%d %B %H:%M:%S\")\n student = self.selected_student.id_\n output = self.app_obj.data_output\n try:\n length = len(output[student][value])\n output[student][value][length] = time_\n except KeyError:\n try:\n output[student][value] = {0: time_}\n except KeyError:\n output[student] = self.students_data[student]\n output[student][value] = {0: time_}\n output._is_changed = True\n output.store_sync()\n","sub_path":"screens.py","file_name":"screens.py","file_ext":"py","file_size_in_byte":10341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"473844716","text":"import time\nfrom datetime import datetime as dt\nimport platform\n\n# Dynamically allotting host_file_path according to the Operating System\nhost_file_path=''\nif platform.system()=='Linux':\n host_file_path= '/etc/hosts'\nelif platform.system()=='Windows':\n host_file_path= 'C:\\Windows\\System32\\drivers\\etc\\hosts'\nelse:\n print('Caution: Error while detecting the platform.')\n print('\\tDetected Platform was',platform.system())\n\nredirect_path = \"127.0.0.1\"\nwebsites = [\n\"www.facebook.com\",\n\"facebook.com\", \"twitter.com\", \"www.twitter.com\",\n\"youtube.com\", \"www.youtube.com\",\n\"www.reddit.com\",\n\"reddit.com\",\n\"www.dsogaming.com\",\"dsogaming.com\",\n\"www.gamemag.ru\",\"gamemag.ru\",\n\"www.9gag.com\",\"9gag.com\",\n\"www.3dnews.ru\",\"3dnews.ru\",\n\"www.phoronix.com\",\"phoronix.com\"\n]\n\n\ndef write_to_hosts_file(host_file_path, websites,redirect_path):\n print(\"Time to block website!\")\n # Open the hosts file\n with open(host_file_path, 'r+') as file:\n # Read the content and print it out on the terminal\n content = file.read()\n print(content)\n for website in websites:\n if website in content:\n pass\n else:\n file.write (redirect_path + \" \" + website + \"\\n\")\n print(\"Updated /etc/hosts \\n\")\n\n\ndef unblock_hosts(host_file_path, websites, redirect_path):\n with open (host_file_path, 'r+') as file:\n content = file.readlines()\n file.seek(0)\n for line in content:\n if not any(website in line for website in websites):\n file.write(line)\n file.truncate()\n print(\"Websites are unblocked!\")\n\n# Need to make script very adaptable\n\n# To make the script running all the time\nwhile True:\n curr_time = dt(dt.now().year, dt.now().month, dt.now().day,dt.now().hour, dt.now().minute)\n\n time_allow_start_1 = dt(dt.now().year, dt.now().month, dt.now().day, 8)\n time_allow_end_1 = dt(dt.now().year, dt.now().month, dt.now().day, 10,00)\n print('curr_time is ', curr_time)\n print('time 1 is ', time_allow_start_1)\n print('time 2 is ', time_allow_end_1)\n #time.sleep(10)\n\n\n time_allow_start_2 = dt(dt.now().year, dt.now().month, dt.now().day, 12)\n time_allow_end_2 = dt(dt.now().year, dt.now().month, dt.now().day, 13,00)\n\n\n time_allow_start_3 = dt(dt.now().year, dt.now().month, dt.now().day, 16)\n time_allow_end_3 = dt(dt.now().year, dt.now().month, dt.now().day, 17,00)\n\n\n time_allow_start_4 = dt(dt.now().year, dt.now().month, dt.now().day, 20)\n time_allow_end_4 = dt(dt.now().year, dt.now().month, dt.now().day, 21,00)\n\n\n if time_allow_start_4 macd.macd_signal().iloc[x],\n company.prices[:-1])\n\n\ndef get_rsi(company):\n rsi_time_period = 20\n low_rsi = 40\n high_rsi = 70\n\n rsi_indicator = RSIIndicator(serie_from_datas(company.prices), rsi_time_period)\n\n return datas_from_serie(rsi_indicator.rsi()), generate_buy_sell_signals(\n lambda x: rsi_indicator.rsi().values[x] < low_rsi,\n lambda x: rsi_indicator.rsi().values[x] > high_rsi,\n company.prices)\n\n\ndef get_bollinger_bands(company):\n indicator_bb = BollingerBands(serie_from_datas(company.prices))\n\n return datas_from_serie(indicator_bb.bollinger_lband()), datas_from_serie(indicator_bb.bollinger_mavg()), datas_from_serie(indicator_bb.bollinger_hband()), generate_buy_sell_signals(\n lambda x: float(company.prices[x]['price']) < indicator_bb.bollinger_lband().values[x],\n lambda x: float(company.prices[x]['price']) > indicator_bb.bollinger_hband().values[x],\n company.prices)\n","sub_path":"finance.py","file_name":"finance.py","file_ext":"py","file_size_in_byte":10124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"413999122","text":"CONFIG = {\n 'schema': {\n 'type': 'object',\n 'title': 'Comment',\n 'description': 'Description',\n 'required': [\n 'name',\n 'image',\n 'port',\n 'openshift_cluster_id',\n 'memory_limit',\n ],\n 'properties': {\n 'name': {\n 'type': 'string'\n },\n 'description': {\n 'type': 'string'\n },\n 'image': {\n 'type': 'string',\n },\n 'port': {\n 'type': 'integer',\n },\n 'volume_mount_point': {\n 'type': 'string',\n },\n 'openshift_cluster_id': {\n 'type': 'string',\n 'title': 'Cluster name (configured in credentials file)',\n },\n 'memory_limit': {\n 'type': 'string',\n 'default': '512M',\n },\n 'maximum_instances_per_user': {\n 'type': 'integer',\n 'title': 'Maximum instances per user',\n 'default': 1,\n },\n 'maximum_lifetime': {\n 'type': 'string',\n 'title': 'Maximum life-time (days hours mins)',\n 'default': '1h 0m',\n 'pattern': '^(\\d+d\\s?)?(\\d{1,2}h\\s?)?(\\d{1,2}m\\s?)?$',\n 'validationMessage': 'Value should be in format [days]d [hours]h [minutes]m'\n },\n 'cost_multiplier': {\n 'type': 'number',\n 'title': 'Cost multiplier',\n 'default': 0.0,\n },\n 'environment_vars': {\n 'type': 'string',\n 'title': 'environment variables for docker, separated by space',\n 'default': '',\n },\n 'autodownload_url': {\n 'type': 'string',\n 'title': 'Autodownload URL',\n 'default': '',\n },\n 'autodownload_filename': {\n 'type': 'string',\n 'title': 'Autodownload file name',\n 'default': '',\n },\n 'show_password': {\n 'type': 'boolean',\n 'title': 'Show the required password/token (if any), to the user',\n 'default': True,\n },\n }\n },\n 'form': [\n {\n 'type': 'help',\n 'helpvalue': '

    Docker instance config

    '\n },\n 'name',\n 'description',\n 'image',\n 'port',\n 'volume_mount_point',\n 'openshift_cluster_id',\n 'environment_vars',\n 'autodownload_url',\n 'autodownload_filename',\n 'show_password',\n 'memory_limit',\n 'maximum_instances_per_user',\n 'maximum_lifetime',\n 'cost_multiplier'\n ],\n 'model': {\n 'name': 'openshift_testing',\n 'description': 'openshift testing template',\n 'cost_multiplier': 0.0,\n 'port': 8888,\n 'image': '',\n 'memory_limit': '512M',\n }\n}\n","sub_path":"pebbles/drivers/provisioning/openshift_driver_config.py","file_name":"openshift_driver_config.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"381664610","text":"#-*-coding:utf-8-*-\n\nimport MySQLdb\nimport sys\nimport md5\nfrom flask import Flask, render_template, url_for, redirect, request, flash, session, g\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\napp = Flask(__name__)\napp.secret_key = 'development key'\n\n#Internal functions\ndef get_already_db(param, tablename):\n\tquery = 'select ' + param + ' from ' + tablename\n\tg.c.execute(query)\n\n\tresult = []\n\tfor i in g.c.fetchall():\n\t\tresult.append(i[param])\n\n\treturn result\n\ndef get_keywords():\t\n\tquery = 'select words from keywords;'\n\tg.c.execute(query)\n\n\tkeywords = []\n\tfor i in g.c.fetchall():\n\t\tkeywords.append(i['words'])\n\n\tkeywords = list(set(keywords))\n\tkeywords.sort()\n\n\treturn keywords\n\n#before and after request\n@app.before_request\ndef before_request():\n\tg.db = MySQLdb.connect(host = 'localhost', user = 'root', passwd = 'm091211', db = 'work')\n\tg.db.set_character_set('utf8')\n\tg.c = g.db.cursor(MySQLdb.cursors.DictCursor)\n\tg.user = None\n\tif 'user_id' in session:\n\t\tg.c.execute(\"select * from user where username = '\" + session['user_id'] + \"';\")\n\t\tg.user = g.c.fetchone()\n\n@app.teardown_request\ndef teardown_request(exception):\n\tg.db.commit()\n\tg.db.close()\n\n#URI Consturction\n\n@app.route('/')\ndef timeline():\n\tquery = 'select * from message order by t desc;'\n\tg.c.execute(query)\n\tmessages = g.c.fetchall()\n\n\tquery = 'select words from keywords;'\n\tg.c.execute(query)\n\n\tkeywords = get_keywords()\n\n\treturn render_template('index.html', messages = messages, keywords = keywords)\n\n@app.route('/new')\ndef newArticle():\n\tif not g.user:\n\t\tredirect(url_for('timeline'))\n\treturn render_template('new.html')\n\n@app.route('/add_message', methods=['POST'])\ndef add_message():\n\tif request.method == 'POST':\n\t\tcontent = request.form['contents']\n\t\ttitle = request.form['title']\n\t\tauthor = g.user['username']\n\t\tkeywords = request.form['keywords'].strip()\n\n\t\tquery = 'insert into message (title, author_id, keywords, content) values ('\n\t\tquery += \"'\" + title + \"','\" + author + \"','\" + keywords.replace(' ', ', ') + \"','\" + content + \"');\"\n\n\t\tg.c.execute('set names utf8')\n\t\tg.c.execute(query)\n\n\t\tg.c.execute('select * from message order by t desc;')\n\t\tmessage_id = g.c.fetchone()['id']\n\n\t\tfor i in keywords.split(' '):\n\t\t\tquery = \"insert into keywords (words, message_id) values ('\"\n\t\t\tquery += i + \"','\" + str(message_id) + \"');\"\n\t\t\tg.c.execute('set names utf8')\n\t\t\tg.c.execute(query)\n\n\treturn redirect(url_for('timeline'))\n\n@app.route('/modify/')\ndef modifyArticle(message_id):\n\tquery = \"select * from message where id = '\" + str(message_id) + \"';\"\n\tg.c.execute(query)\n\tmessage = g.c.fetchone()\n\tmessage['keywords'] = message['keywords'].replace(',', '')\n\n\treturn render_template('modify.html', message = message)\n\n####################under construction here!!!!!!\n\n@app.route('/delete/')\ndef delete(message_id):\n\tquery = \"delete from keywords where message_id = '\" + str(message_id) + \"';\"\n\tg.c.execute(query)\n\tquery = \"delete from message where id = '\" + str(message_id) + \"';\"\n\tg.c.execute(query)\n\n\treturn redirect(url_for('timeline'))\n\n@app.route('/modify_message/', methods=['POST'])\ndef modify_message(message_id):\n\tif request.method == 'POST':\n\t\tquery = \"delete from keywords where message_id = '\" + str(message_id) + \"';\"\n\t\tg.c.execute(query)\n\n\t\tcontent = request.form['contents']\n\t\ttitle = request.form['title']\n\t\tauthor = g.user['username']\n\t\tkeywords = request.form['keywords'].strip()\n\n\t\tquery = 'update message set '\n\t\tquery += \"title = '\" + title + \"', keywords = '\" + keywords.replace(' ', ', ') + \"', content = '\" + content + \"' \"\n\t\tquery += \"where id = '\" + str(message_id) + \"';\"\n\t\t\n\t\tg.c.execute('set names utf8')\n\t\tg.c.execute(query)\n\n\t\tfor i in keywords.split(' '):\n\t\t\tquery = \"insert into keywords (words, message_id) values ('\"\n\t\t\tquery += i + \"','\" + str(message_id) + \"');\"\n\t\t\tg.c.execute('set names utf8')\n\t\t\tg.c.execute(query)\t\n\n\treturn redirect(url_for('timeline'))\n\n@app.route('/signin')\ndef signin():\n\treturn render_template('signin.html')\n\n@app.route('/add_user', methods=['POST'])\ndef add_user():\n\terror = None\n\tif request.method == 'POST':\n\t\tif not request.form['ID']:\n\t\t\terror = 'You have to enter a username'\n\t\telif request.form['ID'] in get_already_db('username', 'user'):\n\t\t\terror = 'The ID is already taken'\n\t\telif not request.form['email'] or '@' not in request.form['email']:\n\t\t\terror = 'You have to enter a valid email address'\n\t\telif not request.form['pwd1'] or not request.form['pwd2']:\n\t\t\terror = 'You have to enter a password'\n\t\telif request.form['pwd1'] != request.form['pwd2']:\n\t\t\terror = 'The two passwords do not match'\n\t\telse:\n\t\t\tuserid = request.form['ID']\n\t\t\temail = request.form['email']\n\t\t\tpwd = md5.md5(request.form['pwd1']).hexdigest()\n\n\t\t\tquery = 'insert into user (username, pwdhash, email) values ('\n\t\t\tquery += \"'\" + userid + \"','\" + pwd + \"','\" + email + \"');\"\n\n\t\t\tg.c.execute('set names utf8')\n\t\t\tg.c.execute(query)\n\n\treturn redirect(url_for('timeline'))\n\n@app.route('/log_in', methods=['POST'])\ndef log_in():\n\terror = None\n\tif request.method == 'POST':\n\t\tif not request.form['ID']:\n\t\t\terror = 'You have to enter a username'\n\t\telif request.form['ID'] not in get_already_db('username', 'user'):\n\t\t\terror = 'Invalid username'\n\t\telif not request.form['pwd']:\n\t\t\terror = 'You have to enter a password'\n\t\telse:\n\t\t\tID = request.form['ID']\n\t\t\tpwd = md5.md5(request.form['pwd']).hexdigest()\n\t\t\tg.c.execute(\"select pwdhash from user where username = '\" + ID + \"';\")\n\t\t\tif pwd == g.c.fetchone()['pwdhash']:\n\t\t\t\tflash('You were logged in')\n\t\t\t\tsession['user_id'] = ID\n\t\t\t\treturn redirect(url_for('timeline'))\n\t\t\telse:\n\t\t\t\terror = 'Invalid password'\n\n\treturn redirect(url_for('timeline'), error = error)\n\n@app.route('/log_out')\ndef log_out():\n\tflash('You were logged out')\n\tsession.pop('user_id', None)\n\treturn redirect(url_for('timeline'))\n\n@app.route('/keywords/')\ndef keywordsort(word):\n\tkeywords = get_keywords()\n\n\tquery = \"select * from keywords where words='\" + word + \"';\"\n\tg.c.execute(query)\n\tIDList = g.c.fetchall()\n\tmessages = []\n\n\tfor i in IDList:\n\t\tquery = \"select * from message where id = '\" + str(i['message_id']) + \"';\"\n\t\tg.c.execute(query)\n\t\tmessages.append(g.c.fetchone())\n\n\treturn render_template('index.html', messages = messages, keywords = keywords)\n\n\n@app.route('/profile')\ndef profile():\n\treturn render_template('profile.html')\n\napp.run(debug = True)","sub_path":"SimpleWorkflow.py","file_name":"SimpleWorkflow.py","file_ext":"py","file_size_in_byte":6349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"238237920","text":"from utilities import *\nfrom item import Item\nfrom weather import WEATHERS, NO_WEATHER, Weather\nfrom teams import EnemyTeam\nfrom output import Op\nfrom character import EnemyCharacter\nfrom fileSystem import getEnemyList\nfrom serialize import AbstractJsonSerialable\nimport random\n\n\"\"\"\nThe Battle class pits 2 teams\nagainst eachother,\ninitializing them\nand the weather.\n\"\"\"\nclass Battle(AbstractJsonSerialable):\n \"\"\"\n Required kwargs:\n - name : str\n - desc : str\n - prescript : list of str, defaults to []\n - postscript : list of str, defaults to []\n - forecast : list of Weather, defaults to WEATHERS, or if an empty list is passed, defaults to NO_WEATHER\n - enemyNames : list of str, the names of enemies to put on the enemy team\n - level : the level of enemies on the enemy team\n - rewards : list of Items, defaults to []\n \"\"\"\n def __init__(self, **kwargs):#name: str, desc: str, script: list, finalAct: list, level: int, enemyNames: list, rewards = []):\n super(Battle, self).__init__(**dict(kwargs, type=\"Battle\"))\n self.name = kwargs[\"name\"]\n self.desc = kwargs[\"desc\"]\n self.prescript = kwargs.get(\"prescript\", [])\n self.postscript = kwargs.get(\"postscript\", [])\n self.forecast = kwargs.get(\"forecast\", WEATHERS)\n if len(self.forecast) == 0:\n self.forecast = [NO_WEATHER]\n self.enemyNames = kwargs[\"enemyNames\"]\n self.level = kwargs[\"level\"]\n self.rewards = kwargs.get(\"rewards\", [])\n\n self.addSerializedAttributes(\n \"name\",\n \"desc\",\n \"prescript\",\n \"postscript\",\n \"forecast\",\n \"enemyNames\",\n \"level\",\n \"rewards\"\n )\n\n\n @classmethod\n def deserializeJson(cls, jdict: dict)->\"Battle\":\n jdict[\"forecast\"] = [Weather.deserializeJson(data) for data in jdict[\"forecast\"]]\n jdict[\"rewards\"] = [Item.deserializeJson(data) for data in jdict[\"rewards\"]]\n return Battle(**jdict)\n\n \"\"\"\n gets data for outputting\n \"\"\"\n def getDisplayData(self):\n ret = [self.name, \"\\t\" + self.desc]\n for name in self.enemyNames: # enemy team is not yet loaded\n ret.append(\"\\t* {0} Lv. {1}\".format(name, self.level))\n return ret\n\n def __str__(self):\n return \"\\n\".join(self.getDisplayData())\n\n # add random loot\n def check_winner(self):\n \"\"\"\n Runs when one\n teams loses all\n members.\n \"\"\"\n if not self.player_team.isDefeated():\n Op.add(self.player_team.name + \" won!\")\n Op.display()\n\n for line in self.postscript:\n Op.add(line)\n Op.display()\n\n for reward in self.rewards:\n if reward != None:\n reward.give(self.player_team)\n\n def end(self):\n \"\"\"\n The stuff that takes place after battle\n \"\"\"\n xp = self.enemy_team.getXpGiven()\n for member in self.player_team.members:\n member.gainXp(xp)\n\n \"\"\"\n Used to start\n the battle\n \"\"\"\n def play(self, playerTeam):\n # set teams\n self.player_team = playerTeam\n enemies = [EnemyCharacter.loadEnemy(enemyName) for enemyName in self.enemyNames]\n for enemy in enemies:\n enemy.level = self.level\n enemy.displayData()\n\n self.enemy_team = EnemyTeam(\n name=\"Enemy Team\",\n members=enemies\n )\n\n for line in self.prescript:\n Op.add(line)\n Op.display()\n\n self.enemy_team.initForBattle()\n self.enemy_team.enemy = self.player_team\n\n self.player_team.initForBattle()\n self.player_team.enemy = self.enemy_team\n\n self.enemy_team.displayData()\n self.player_team.displayData()\n\n self.weather = random.choice(self.forecast)\n Op.add(self.weather.getMsg())\n Op.display()\n\n while not self.enemy_team.isDefeated() and not self.player_team.isDefeated():\n self.weather.applyEffect(self.enemy_team.membersRem)\n # did the weather defeat them?\n if not self.enemy_team.isDefeated():\n self.enemy_team.doTurn()\n # only bother doing player turn if enemy survives\n # so this way we don't get 'ghost rounds'\n self.weather.applyEffect(self.player_team.membersRem)\n if not self.player_team.isDefeated():\n self.player_team.doTurn()\n self.check_winner()\n self.end()\n\n self.enemy_team = None # uncache enemy team to save memory\n\n \"\"\"\n Creates a random level\n \"\"\"\n @staticmethod\n def generateRandom():\n enemyNames = []\n numEnemies = random.randint(1, 4)\n\n allEnemyNames = getEnemyList()\n\n for i in range(0, numEnemies):\n enemyNames.append(random.choice(allEnemyNames))\n\n return Battle(\n name=\"Random encounter\",\n desc=\"Random battle\",\n enemyNames=enemyNames,\n level=1\n )\n","sub_path":"battle/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":5101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"63754572","text":"# Copyright (c) 2014 Universidade Federal Fluminense (UFF)\n# Copyright (c) 2014 Polytechnic Institute of New York University.\n# This file is part of noWorkflow.\n# Please, consult the license terms in the LICENSE file.\n\nfrom __future__ import (absolute_import, print_function,\n division, unicode_literals)\n\nfrom collections import defaultdict, OrderedDict\nfrom .utils import calculate_duration, FORMAT\nfrom ..persistence import row_to_dict\nfrom ..persistence import persistence as pers\n\nclass History(object):\n \"\"\" This model represents the workflow evolution history\n\n It is possible to filter the evolution history by selecting the script:\n history.script = \"script1.py\"\n\n The list of scripts can be accessed by:\n history.scripts()\n\n It is also possible to filter the evolution history by selecting the\n trial status:\n history.execution = \"finished\"\n\n The list of status are:\n finished: show only finished trials\n unfinished: show only unfinished trials\n backup: show only backup trials\n\n The default option for both filters is \"*\", which means that all trials\n appear in the history\n history.script = \"*\"\n history.execution = \"*\"\n\n You can change the graph width and height by the variables:\n history.graph_width = 600\n history.graph_height = 200\n \"\"\"\n\n def __init__(self):\n self.data = {}\n self.script = \"*\"\n self.execution = \"*\"\n\n self.execution_options = [\"*\", \"finished\", \"unfinished\", \"backup\"]\n self.graph_width = 700\n self.graph_height = 300\n\n def scripts(self):\n \"\"\" Returns the list of scripts used for trials \"\"\"\n return {s[0].rsplit('/', 1)[-1] for s in pers.distinct_scripts()}\n\n def graph_data(self, script=\"*\", execution=\"*\"):\n \"\"\" Prepares evolution history as a dict \"\"\"\n if self.script != \"*\" and script == \"*\":\n script = self.script\n if self.execution != \"*\" and execution == \"*\":\n execution = self.execution\n\n key = (script, execution)\n if key in self.data:\n return self.data[key]\n\n nodes, edges = [], []\n result = {'nodes': nodes, 'edges': edges}\n id_map, children = {}, defaultdict(list)\n scripts, order = defaultdict(list), OrderedDict()\n\n # Filter nodes and adds to dicts\n tid = 0\n for trial in map(row_to_dict, pers.load('trial', order=\"start\")):\n different_script = (trial['script'] != script)\n finished = trial['finish']\n unfinished = not finished and trial['run']\n backup = not finished and not trial['run']\n\n if script != '*' and different_script:\n continue\n if execution == 'finished' and not finished:\n continue\n if execution == 'unfinished' and not unfinished:\n continue\n if execution == 'backup' and not backup:\n continue\n\n trial_id = trial[\"id\"]\n trial[\"level\"] = 0\n trial[\"status\"] = \"Finished\" if trial[\"finish\"] else \"Unfinished\"\n if not trial['run']:\n trial[\"status\"] = \"Backup\"\n trial[\"tooltip\"] = \"\"\"\n {script}
    \n {status}
    \n Start: {start}
    \n Finish: {finish}\n \"\"\".format(**trial)\n if trial['finish']:\n trial[\"tooltip\"] += \"\"\"\n
    \n Duration: {duration}ns\n \"\"\".format(duration=calculate_duration(trial))\n id_map[trial_id] = tid\n scripts[trial['script']].append(trial)\n nodes.append(trial)\n tid += 1\n\n # Create edges\n for trial in reversed(nodes):\n trial_id, parent_id = trial[\"id\"], trial[\"parent_id\"]\n if parent_id and parent_id in id_map:\n edges.append({\n 'source': id_map[trial_id],\n 'target': id_map[parent_id],\n 'right': 1,\n 'level': 0\n })\n children[parent_id].append(trial_id)\n order[trial['script']] = 1\n\n # Set position\n level = 0\n for script in order:\n last = level\n for trial in scripts[script]:\n trial_id, parent_id = trial[\"id\"], trial[\"parent_id\"]\n if parent_id and parent_id in id_map:\n parent = nodes[id_map[parent_id]]\n if children[parent_id].index(trial_id) > 0:\n trial[\"level\"] = last\n last += 1\n else:\n trial[\"level\"] = parent[\"level\"]\n level = max(level, trial[\"level\"] + 1)\n else:\n trial[\"level\"] = level\n level += 1\n last += 1\n\n self.data[key] = result\n return result\n\n def _ipython_display_(self):\n \"\"\" Displays d3 graph on ipython notebook \"\"\"\n from IPython.display import (\n display_png, display_html, display_latex,\n display_javascript, display_svg\n )\n import json\n import time\n\n uid = str(int(time.time()*1000000))\n display_html(\"\"\"\n
    \n
    \n
    \n \n \n \n
    \n
    \n
    \n
    \"\"\".format(uid, self.graph_width, self.graph_height), raw=True)\n display_javascript(\"\"\"\n var hg = now_history_graph('#history-{0}', {0}, {1}, {2}, {3}, \"#show-history-tooltips-{0}\", {{\n custom_size: function() {{\n return [{2}, {3}];\n }},\n hint_message: \"\",\n }});\n\n $( \"[name='show-history-tooltips']\" ).change(function() {{\n hg.graph.set_use_tooltip(d3.select(\"#show-history-tooltips-{0}\").property(\"checked\"));\n }});\n\n $('#restore-history-zoom-{0}').on('click', function(e){{\n hg.graph.reset_zoom();\n }});\n \"\"\".format(\n uid,\n json.dumps(self.graph_data()),\n self.graph_width, self.graph_height), raw=True)\n","sub_path":"capture/noworkflow/now/models/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":6895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"145862280","text":"#Ian Cardoso - 11411EMT014\n\nimport select\nimport errno \nimport socket\nimport sys\n\n\nHEADER_LENGTH = 10\nIP = \"127.0.0.1\"\nPORT = 1234\n\nmy_username = input(\"Username:\") #pega a informação do usuario e aloca em my_username\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) \nclient_socket.connect((IP, PORT)) \nclient_socket.setblocking(False) #impede bloqueamento de dados\n\nusername = my_username.encode(\"utf-8\") #tratamento do username\nusername_header = f\"{len(username):<{HEADER_LENGTH}}\".encode(\"utf-8\")\nclient_socket.send(username_header + username) #Manada para o server o username e o header\n\nwhile True:\n message = input(f\"{my_username} > \") #Usuario insere o nome\n\n if message: #se a mensagem não vier vazia\n message = message.encode(\"utf-8\")\n message_header = f\"{len(message) :<{HEADER_LENGTH} }\".encode(\"utf-8\")\n client_socket.send(message_header + message) #envia mensagem ao servidor\n try:\n while True: #Recebendo os objetos\n username_header = client_socket.recv(HEADER_LENGTH)\n if not len(username_header):\n print(\"Conexão fechada pelo servidor\")\n sys.exit()\n username_length = int(username_header.decode(\"utf-8\").strip())\n username = client_socket.recv(username_length).decode(\"utf-8\")\n\n message_header = client_socket.recv(HEADER_LENGTH)#Recebe o tamanho do header pre definido\n message_length = int(message_header.decode(\"utf-8\").strip())#Transforma em inteiro o header da mensagem\n message = client_socket.recv(message_length).decode(\"utf-8\")#Recebe o tamanho em bytes e volta pra objeto\n\n print(f\"{username} > {message}\")\n\n except IOError as e: #tratamento d erros\n if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK: #Testa se o erro não é vaizou ou não pertence a biblioteca importada de erro\n sys.exit() #fecha o sistema\n continue\n\n except Exception as e:\n print('General error', srt(e)) #mostra o erro geral\n sys.exit()\n pass\n\n\n","sub_path":"Semana05/semana05_socket/5_client.py","file_name":"5_client.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"336763303","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom pathlib import Path\nimport warnings\nimport country_converter as coco\nfrom dask import dataframe as dd\nimport pandas as pd\nfrom covsirphy.util.error import deprecate, SubsetNotFoundError\nfrom covsirphy.cleaning.term import Term\n\n\nclass CleaningBase(Term):\n \"\"\"\n Basic class for data cleaning.\n\n Args:\n filename (str or None): CSV filename of the dataset\n citation (str or None): citation\n\n Returns:\n If @filename is None, empty dataframe will be set as raw data.\n If @citation is None, citation will be empty string.\n \"\"\"\n\n def __init__(self, filename, citation=None):\n warnings.simplefilter(\"ignore\", DeprecationWarning)\n if filename is None:\n self._raw = pd.DataFrame()\n self._cleaned_df = pd.DataFrame()\n else:\n Path(filename).parent.mkdir(exist_ok=True, parents=True)\n self._raw = dd.read_csv(\n filename, dtype={\"Province/State\": \"object\"}\n ).compute()\n self._cleaned_df = self._cleaning()\n self._citation = citation or \"\"\n\n @property\n def raw(self):\n \"\"\"\n pandas.DataFrame: raw data\n \"\"\"\n return self._raw\n\n @raw.setter\n def raw(self, dataframe):\n \"\"\"\n pandas.DataFrame: raw dataset\n \"\"\"\n self._raw = self._ensure_dataframe(dataframe, name=\"dataframe\")\n\n @staticmethod\n def load(urlpath, header=0, columns=None, dtype=\"object\"):\n \"\"\"\n Load a local/remote file.\n\n Args:\n urlpath (str or pathlib.Path): filename or URL\n header (int): row number of the header\n columns (list[str]): columns to use\n dtype (str or dict[str]): data type for the dataframe or specified columns\n\n Returns:\n pd.DataFrame: raw dataset\n \"\"\"\n kwargs = {\n \"low_memory\": False, \"dtype\": dtype, \"header\": header, \"usecols\": columns}\n try:\n return dd.read_csv(urlpath, blocksize=None, **kwargs).compute()\n except (FileNotFoundError, UnicodeDecodeError, pd.errors.ParserError):\n return pd.read_csv(urlpath, **kwargs)\n\n def cleaned(self):\n \"\"\"\n Return the cleaned dataset.\n\n Note:\n Cleaning method is defined by CleaningBase._cleaning() method.\n\n Returns:\n pandas.DataFrame: cleaned data\n \"\"\"\n return self._cleaned_df\n\n def _cleaning(self):\n \"\"\"\n Perform data cleaning of the raw data.\n\n Returns:\n pandas.DataFrame: cleaned data\n \"\"\"\n return self._raw.copy()\n\n @property\n def citation(self):\n \"\"\"\n str: citation/description of the dataset\n \"\"\"\n return self._citation\n\n @citation.setter\n def citation(self, description):\n self._citation = str(description)\n\n def ensure_country_name(self, country):\n \"\"\"\n Ensure that the country name is correct.\n If not, the correct country name will be found.\n\n Args:\n country (str): country name\n\n Returns:\n str: country name\n \"\"\"\n df = self._ensure_dataframe(\n self._cleaned_df, name=\"the cleaned dataset\", columns=[self.COUNTRY])\n selectable_set = set(df[self.COUNTRY].unique())\n # return country name as-is if selectable\n if country in selectable_set:\n return country\n # Convert country name\n converted = coco.convert(country, to=\"name_short\", not_found=None)\n # Additional abbr\n abbr_dict = {\n \"Congo Republic\": \"Republic of the Congo\",\n \"DR Congo\": \"Democratic Republic of the Congo\",\n \"UK\": \"United Kingdom\",\n \"Vatican\": \"Holy See\",\n }\n name = abbr_dict.get(converted, converted)\n # Return the name if registered in the dataset\n if name in selectable_set:\n return name\n raise SubsetNotFoundError(country=country, country_alias=name)\n\n @deprecate(\"CleaningBase.iso3_to_country()\", new=\"CleaningBase.ensure_country_name()\")\n def iso3_to_country(self, iso3_code):\n \"\"\"\n Convert ISO3 code to country name if records are available.\n\n Args:\n iso3_code (str): ISO3 code or country name\n\n Returns:\n str: country name\n\n Note:\n If ISO3 codes are not registered, return the string as-si @iso3_code.\n \"\"\"\n return self.ensure_country_name(iso3_code)\n\n def country_to_iso3(self, country):\n \"\"\"\n Convert country name to ISO3 code if records are available.\n\n Args:\n country (str): country name\n\n Raises:\n KeyError: ISO3 code of the country is not registered\n\n Returns:\n str: ISO3 code or \"---\" (when unknown)\n \"\"\"\n name = self.ensure_country_name(country)\n return coco.convert(name, to=\"ISO3\", not_found=\"---\")\n\n @classmethod\n def area_name(cls, country, province=None):\n \"\"\"\n Return area name of the country/province.\n\n Args:\n country (str): country name or ISO3 code\n province (str): province name\n\n Returns:\n str: area name\n\n Note:\n If province is None or '-', return country name.\n If not, return the area name, like 'Japan/Tokyo'\n \"\"\"\n if province in [None, cls.UNKNOWN]:\n return country\n return f\"{country}{cls.SEP}{province}\"\n\n def _subset_by_area(self, country, province=None):\n \"\"\"\n Return subset for the country/province.\n\n Args:\n country (str): country name\n province (str or None): province name\n\n Returns:\n pandas.DataFrame: subset for the country/province\n \"\"\"\n # Country level\n country = self.ensure_country_name(country)\n df = self._ensure_dataframe(\n self._cleaned_df, name=\"the cleaned dataset\", columns=[self.COUNTRY])\n df = df.loc[df[self.COUNTRY] == country, :]\n # Province level\n province = province or self.UNKNOWN\n if self.PROVINCE not in df.columns and province == self.UNKNOWN:\n return df\n df = self._ensure_dataframe(\n df, \"the cleaned dataset\", columns=[self.PROVINCE])\n return df.loc[df[self.PROVINCE] == province, :]\n\n def subset(self, country, province=None, start_date=None, end_date=None):\n \"\"\"\n Return subset of the country/province and start/end date.\n\n Args:\n country (str): country name or ISO3 code\n province (str or None): province name\n start_date (str or None): start date, like 22Jan2020\n end_date (str or None): end date, like 01Feb2020\n\n Returns:\n pandas.DataFrame\n Index\n reset index\n Columns\n without ISO3, Country, Province column\n \"\"\"\n country_alias = self.ensure_country_name(country)\n df = self._subset_by_area(country=country, province=province)\n df = df.drop(\n [self.COUNTRY, self.ISO3, self.PROVINCE], axis=1, errors=\"ignore\")\n if df.empty:\n raise SubsetNotFoundError(\n country=country, country_alias=country_alias, province=province)\n # Subset with Start/end date\n if start_date is None and end_date is None:\n return df.reset_index(drop=True)\n df = self._ensure_dataframe(\n df, name=\"the cleaned dataset\", columns=[self.DATE])\n series = df[self.DATE].copy()\n start_obj = self.date_obj(date_str=start_date, default=series.min())\n end_obj = self.date_obj(date_str=end_date, default=series.max())\n df = df.loc[(start_obj <= series) & (series <= end_obj), :]\n if df.empty:\n raise SubsetNotFoundError(\n country=country, country_alias=country_alias, province=province,\n start_date=start_date, end_date=end_date)\n return df.reset_index(drop=True)\n\n def subset_complement(self, country, **kwargs):\n \"\"\"\n Return the subset. If necessary, complemention will be performed.\n\n Raises:\n NotImplementedError\n \"\"\"\n raise NotImplementedError\n\n def records(self, country, province=None, start_date=None, end_date=None,\n auto_complement=True, **kwargs):\n \"\"\"\n Return the subset. If necessary, complemention will be performed.\n\n Args:\n country (str): country name or ISO3 code\n province (str or None): province name\n start_date (str or None): start date, like 22Jan2020\n end_date (str or None): end date, like 01Feb2020\n auto_complement (bool): if True and necessary, the number of cases will be complemented\n kwargs: the other arguments of complement\n\n Returns:\n pandas.DataFrame\n Index\n reset index\n Columns\n without ISO3, Country, Province column\n \"\"\"\n country_alias = self.ensure_country_name(country)\n subset_arg_dict = {\n \"country\": country, \"province\": province, \"start_date\": start_date, \"end_date\": end_date}\n if auto_complement:\n try:\n df, is_complemented = self.subset_complement(\n **subset_arg_dict, **kwargs)\n if not df.empty:\n return (df, is_complemented)\n except NotImplementedError:\n pass\n try:\n return (self.subset(**subset_arg_dict), False)\n except SubsetNotFoundError:\n raise SubsetNotFoundError(\n country=country, country_alias=country_alias, province=province,\n start_date=start_date, end_date=end_date) from None\n\n def countries(self):\n \"\"\"\n Return names of countries where records are registered.\n\n Raises:\n KeyError: Country names are not registered in this dataset\n\n Returns:\n list[str]: list of country names\n \"\"\"\n df = self._ensure_dataframe(\n self._cleaned_df, name=\"the cleaned dataset\", columns=[self.COUNTRY])\n return list(df[self.COUNTRY].unique())\n\n def total(self):\n \"\"\"\n Calculate total values of the cleaned dataset.\n \"\"\"\n raise NotImplementedError\n","sub_path":"covsirphy/cleaning/cbase.py","file_name":"cbase.py","file_ext":"py","file_size_in_byte":10528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"83032254","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.keras import layers\n# 学習済みモデル所得用\nimport tensorflow_hub as hub\nimport datetime\n\n# -------------------------------------\n# ログ出力の定義\n# -------------------------------------\nimport os.path\nimport logging\nimport logging.config\nfrom logging import getLogger\n\nif os.path.isdir(\"out\") == False:\n os.mkdir(\"out\")\n\nlogging.config.fileConfig(\"logging.conf\")\nlogger = getLogger(__name__)\n\n# -------------------------------------\n# データの準備\n# -------------------------------------\n# データをダウンロードしてinフォルダに格納\n_url = 'https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz'\n\ndata_root = tf.keras.utils.get_file(\n 'flower_photos', _url, cache_dir='./', cache_subdir='in', untar=True\n)\n\nlogger.info(f'data_root:{data_root}')\n# データ読み込み用のジェネレーターを定義\nIMAGE_SHAPE = (224, 224)\n\nimage_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1/255)\nimage_data = image_generator.flow_from_directory(str(data_root), target_size=IMAGE_SHAPE)\n\nfor image_batch, label_batch in image_data:\n logger.info(f'Image batch shape: {image_batch.shape}')\n logger.info(f'Label batch shape: {label_batch.shape}')\n break\n\n# -------------------------------------\n# モデルの構築(転移学習)\n#--------------------------------------\n# 学習済モデルの取得\n_url = \"https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/2\" #@param {type:\"string\"}\nbase_layer = hub.KerasLayer(_url, input_shape=(224,224,3))\nbase_layer.trainable = False\n\n# モデルの構築(全結合層の追加)\nmodel = tf.keras.Sequential([\n base_layer,\n layers.Dense(image_data.num_classes, activation='softmax')\n])\nmodel.summary(print_fn=logger.info)\n\nmodel.compile(\n optimizer=tf.keras.optimizers.Adam(),\n loss='categorical_crossentropy',\n metrics=['acc']\n)\n\n# 独自で損失を取得するためのコールバック\nclass CollectBatchStats(tf.keras.callbacks.Callback):\n def __init__(self):\n self.batch_losses = []\n self.batch_acc = []\n\n def on_train_batch_end(self, batch, logs=None):\n self.batch_losses.append(logs['loss'])\n self.batch_acc.append(logs['acc'])\n self.model.reset_metrics()\n\nbatch_stats_callback = CollectBatchStats()\n\n# TensorBoard用コールバック。起動はターミナルで以下を入力\n# tensorboard --logdir='./out/fit'\nlog_dir = \"./out/fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\ntensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)\n\n# 1エポックあたりのステップ数\nsteps_per_epoch = np.ceil(image_data.samples/image_data.batch_size)\n\n# -----------------------------------\n# 学習\n# -----------------------------------\nhistory = model.fit_generator(image_data, epochs=2,\n steps_per_epoch=steps_per_epoch,\n callbacks = [batch_stats_callback])\n\nlogger.info('batchlosses:')\nlogger.info(batch_stats_callback.batch_losses)\nlogger.info('batch_acc:')\nlogger.info(batch_stats_callback.batch_acc)\n\n# -----------------------------------\n# 結果確認\n# -----------------------------------\n# 損失をグラフ化\nplt.figure()\nplt.ylabel(\"Loss\")\nplt.xlabel(\"Training Steps\")\nplt.ylim([0,2])\nplt.plot(batch_stats_callback.batch_losses)\nplt.savefig('./out/fig_loss.png')\n\n# 正解率をグラフ化\nplt.figure()\nplt.ylabel(\"Accuracy\")\nplt.xlabel(\"Training Steps\")\nplt.ylim([0,1])\nplt.plot(batch_stats_callback.batch_acc)\nplt.savefig('./out/fig_acc.png')\n\n# ------------------------------------\n# 予測\n# ------------------------------------\nclass_names = sorted(image_data.class_indices.items(), key=lambda pair:pair[1])\nclass_names = np.array([key.title() for key, value in class_names])\nlogger.info(f'class_name:{class_names}')\n\npredicted_batch = model.predict(image_batch)\npredicted_id = np.argmax(predicted_batch, axis=-1)\npredicted_label_batch = class_names[predicted_id]\n\nlabel_id = np.argmax(label_batch, axis=-1)\n\n# 予測結果(イメージ)を保存\nplt.figure(figsize=(10,9))\nplt.subplots_adjust(hspace=0.5)\nfor n in range(30):\n plt.subplot(6,5,n+1)\n plt.imshow(image_batch[n])\n color = \"green\" if predicted_id[n] == label_id[n] else \"red\"\n plt.title(predicted_label_batch[n].title(), color=color)\n plt.axis('off')\n_ = plt.suptitle(\"Model predictions (green: correct, red: incorrect)\")\nplt.savefig('./out/predict.png')\n\n# ------------------------------------\n# モデルのエクスポート\n# ------------------------------------\nimport time\nt = time.time()\n\nexport_path = \"./out/{}\".format(int(t))\nmodel.save(export_path, save_format='tf')\nlogger.info(f'export_path:{export_path}')\n\n# リロードできる。エクスポート前を同じ結果が得られる\nreloaded = tf.keras.models.load_model(export_path)\n\nresult_batch = model.predict(image_batch)\nreloaded_result_batch = reloaded.predict(image_batch)\n\ndiff = abs(reloaded_result_batch - result_batch).max()\n\nlogger.info(f'diff: {diff}')\n","sub_path":"python/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"357008826","text":"from flask import Flask, Response, request\nimport requests\nimport hashlib\nimport redis\nimport socket\n\napp = Flask(__name__)\nredis_cache = redis.StrictRedis(host='redis', port=6379, socket_connect_timeout=2, socket_timeout=2, db=0)\nsalt = \"UNIQUE_SALT\"\ndefault_name = 'John Doe'\n\n@app.route('/', methods=['GET', 'POST'])\ndef mainpage():\n\n try:\n visits = redis_cache.incr(\"counter\")\n except redis.RedisError:\n visits = \"cannot connect to Redis, counter disabled\"\n\n name = default_name\n if request.method == 'POST':\n name = request.form['name']\n salted_name = salt + name\n name_hash = hashlib.sha256(salted_name.encode()).hexdigest()\n\n page = '''\n \n \n Monster Icon\n \n \n \n

    Monster Icon

    \n
    \n Hello dear \n !\n \n
    \n

    Here is your monster icon :

    \n \n
    \n\n

    container info:

    \n
      \n
    • Hostname: {hostname}
    • \n
    • Visits: {visits}
    • \n
    \n \n \n '''.format(name=name, name_hash=name_hash, hostname=socket.gethostname(), visits=visits)\n\n return page\n\n\n@app.route('/monster/')\ndef get_identicon(name):\n image = redis_cache.get(name)\n if image is None:\n print (\"Cache miss: picture icon not found in Redis\", flush=True)\n r = requests.get('http://dnmonster:8080/monster/' + name + '?size=80')\n image = r.content\n redis_cache.set(name, image)\n\n return Response(image, mimetype='image/png')\n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n\n","sub_path":"flaskapp_src/app/monster_icon.py","file_name":"monster_icon.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"621518556","text":"#!/usr/bin/python\n\n# Modules\nimport subprocess\n\ndef linuxCommand (commandList):\n proc = subprocess.Popen(commandList, stdout=subprocess.PIPE)\n return proc.stdout.read().strip('\\n')\n\n#output = linuxCommand([\"ps\", \"aux\"])\n\noutput = linuxCommand([\"top\", \"-a\", \"-n\", \"1\"]).splitlines()\nprint(output[7:9].strip(\"\\n\"))","sub_path":"a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"11630801","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)\n\ndef plot_innings_runs_histogram():\n df=ipl_df[['match_code','inning','total']]\n new_df=df.groupby(['match_code','inning']).sum()\n inning1=new_df[new_df.index.get_level_values('inning')==1]\n inning2=new_df[new_df.index.get_level_values('inning')==2]\n plt.subplot(1,2,1)\n plt.hist(inning1.values)\n plt.subplot(1,2,2)\n plt.hist(inning2.values)\n plt.show()\n# Solution\n","sub_path":"q03_plot_innings_runs_histogram/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"274279794","text":"#!/usr/bin/env python\n\n# For a new copies repo, we may do following:\n# cd .repo/manifests && git reset --hard HEAD^ && cd - && ./repo init -u ssh://android.intel.com/a/aosp/platform/manifest -b abt/private/topic/aosp_stable/master && cd .repo/manifests && git am /workspace/project/gyagp/share/python/aosp-stable/patches/0001-Replace-webview-and-chromium_org.patch && cd - && ./repo start x64 --all\n\n\nimport sys\nsys.path.append(sys.path[0] + '/..')\nfrom util import *\n\nrepo_default = ['aosp-stable', 'aosp-stable-cr']\nrepo = []\ndate = get_datetime(format='%Y%m%d')\n\n\ndef handle_option():\n global args, args_dict\n\n parser = argparse.ArgumentParser(description='Script to sync, build Android',\n formatter_class=argparse.RawTextHelpFormatter,\n epilog='''\nexamples:\n python %(prog)s -b aosp-stable\n python %(prog)s -b aosp-stable-cr\n python %(prog)s -b all\n''')\n\n parser.add_argument('--repo', dest='repo', help='repo to build', choices=repo_default + ['all'], default='aosp-stable-cr')\n parser.add_argument('-b', '--build', dest='build', help='build', action='store_true')\n parser.add_argument('--keep-out', dest='keep_out', help='keep the out dir', action='store_true')\n parser.add_argument('--skip-sync', dest='skip_sync', help='skip sync', action='store_true')\n\n args = parser.parse_args()\n args_dict = vars(args)\n\n if len(sys.argv) <= 1:\n parser.print_help()\n quit()\n\n\ndef setup():\n global repo\n\n repo = _setup_list('repo')\n backup_dir('/workspace/project')\n\n\ndef build():\n if not args.build:\n return\n\n for repo_temp in repo:\n backup_dir(repo_temp + '-daily')\n\n # Ensure last good build is kept if available\n if not args.keep_out:\n if not os.path.exists('out_bk'):\n execute('mv out out_bk')\n else:\n if os.path.exists('out/target/product/baytrail_64/live.img'):\n execute('rm -rf out_bk')\n execute('mv out out_bk')\n else:\n execute('rm -rf out')\n\n cmd = 'python aosp-stable.py --patch --target-arch all --target-device all -b --backup'\n if not args.skip_sync:\n cmd += ' --sync all'\n execute(cmd, interactive=True)\n restore_dir()\n\n\ndef _setup_list(var):\n if var in args_dict and args_dict[var]:\n if args_dict[var] == 'all':\n list_temp = eval(var + '_default')\n else:\n list_temp = eval('args.' + var).split(',')\n else:\n if (var + '_default') in globals():\n list_temp = eval(var + '_default')\n else:\n list_temp = []\n return list_temp\n\n\nif __name__ == \"__main__\":\n handle_option()\n setup()\n build()\n","sub_path":"python/archive/daily.py","file_name":"daily.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"282451509","text":"from django.shortcuts import render_to_response\nfrom django.conf import settings\nimport json\nimport os\n\n\ndef get_suite_context(request, path):\n full_path = os.path.join(settings.QUNIT_TEST_DIRECTORY, path)\n full_path, directories, files = os.walk(full_path).next()\n\n suite = {}\n\n # set suite name\n pieces = path.split(\"/\")\n if len(pieces) < 2:\n suite[\"name\"] = \"main\"\n else:\n suite[\"name\"] = \"\".join(pieces[-2])\n\n # defaults\n suite[\"extra_urls\"] = []\n suite[\"extra_media_urls\"] = []\n\n package_json = \"package.json\"\n if \"QUNIT_PACKAGE_JSON\" in dir(settings):\n package_json = settings.QUNIT_PACKAGE_JSON\n\n # load suite.json if present\n if package_json in files:\n with open(os.path.join(full_path, package_json), \"r\") as f:\n content = f.read()\n suite.update(json.loads(content))\n\n previous_directory = parent_directory(path)\n\n return {\n \"files\": [path + ff for ff in files if ff.endswith(\"js\")],\n \"previous_directory\": previous_directory,\n \"in_subdirectory\": True and (previous_directory is not None) or False,\n \"subsuites\": directories,\n \"suite\": suite,\n }\n\n\ndef run_tests(request, path):\n index_html = \"index.html\"\n if \"QUNIT_INDEX_HTML\" in dir(settings):\n index_html = settings.QUNIT_INDEX_HTML\n suite_context = get_suite_context(request, path)\n return render_to_response(index_html, suite_context)\n\n\ndef parent_directory(path):\n \"\"\"\n Get parent directory. If root, return None\n \"\" => None\n \"foo/\" => \"/\"\n \"foo/bar/\" => \"foo/\"\n \"\"\"\n if path == '':\n return None\n prefix = '/'.join(path.split('/')[:-2])\n if prefix != '':\n prefix += '/'\n return prefix\n","sub_path":"django_qunit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"219913866","text":"import os\nimport boto3\nimport logging\nimport json\nimport codecs\nimport hashlib\nimport binascii\nimport inspect\nfrom collections import defaultdict\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\ns3 = boto3.resource('s3')\n\nclass Emitter(object):\n\n def __init__(self, outputBucket, outputPrefix, jobId, emitterType):\n self.emitBuffer = defaultdict(list)\n self.outputBucket = outputBucket\n self.outputPrefix = outputPrefix\n self.jobId = jobId\n self.emitterType = emitterType\n\n def emit(self, key, value):\n self.emitBuffer[key].append(value)\n\n def flushEmits(self):\n for key in self.emitBuffer:\n self.flushEmit(key, self.emitBuffer[key])\n\n def flushEmit(self, key, values):\n logger.debug(f\"flushing {key}, {values}\")\n keyIsBuffer = type(key).__name__ is 'bytes'\n outputKey = codecs.encode(key, 'base64') if keyIsBuffer else key\n\n allValues = []\n for v in values:\n valueIsBuffer = type(v).__name__ is 'bytes'\n outputValue = codecs.encode(v, 'base64') if valueIsBuffer else v\n value = {\n 'value': outputValue,\n 'valueIsBase64': valueIsBuffer,\n }\n allValues.append(value)\n\n # for S3 keys\n h = hashlib.sha256()\n if(keyIsBuffer):\n h.update(key)\n else:\n h.update(key.encode('utf-8'))\n partitionKey = h.hexdigest()\n partKey = str(binascii.hexlify(os.urandom(16)), 'ascii')\n\n flushKey = f\"{self.outputPrefix}/{self.jobId}/{self.emitterType}/{partitionKey}/{partKey}\"\n\n logger.debug(f\"Flushing key: {key}, values: {allValues}, to s3://{self.outputBucket}/{flushKey}\")\n\n body = {\n 'key': outputKey,\n 'keyIsBase64': keyIsBuffer,\n 'values': allValues\n }\n obj = s3.Object(self.outputBucket, flushKey)\n obj.put(Body=json.dumps(body).encode('utf-8'))\n","sub_path":"cfmr/emitter.py","file_name":"emitter.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"448584248","text":"import pygame\nimport random\nrandom.seed()\ndef print_text(screen,text,point):\n text_font=pygame.font.SysFont('freesansbold.ttf',50)\n textSurface=text_font.render(text,True,(255,0,0))\n screen.blit(textSurface,(point[0],point[1]))\npictures={'mid_bird':'pictures/redbird-midflap.png',\n 'up_bird':'pictures/redbird-upflap.png',\n 'down_bird':'pictures/redbird-downflap.png',\n 'green_pipe_u':'pictures/pipe-green-u.png',\n\t\t 'green_pipe_d':'pictures/pipe-green-d.png',\n 'red_pipe_up':'pictures/red-pipe.png',\n 'red_pipe_down':'pictures/red-pipe-d.png',\n 'cloud':'pictures/cloud.png',\n 'base':'pictures/base.png',\n 'sky':'pictures/sky.png',\n 'white_cloud':'pictures/w-cloud.png'\n }\nclass Bird:\n\tdef __init__(self,screen,bird_x,bird_y,speed_x,speed_y,y_change):\n\t\tself.screen=screen\n\t\tself.bird_x=bird_x\n\t\tself.bird_y=bird_y\n\t\tself.speed_x=speed_x\n\t\tself.speed_y=speed_y\n\t\tself.y_change=y_change\n\t\tself.gameover=False\n\t\tself.images=[pygame.image.load(pictures['down_bird']),pygame.image.load(pictures['mid_bird']),pygame.image.load(pictures['up_bird'])]\n\t\tself.counter=0\n\tdef __gameover(self):\n\t\t\tself.gameover=True\n\t\t\tpygame.display.update()\n\tdef update(self):\n\t\tif self.bird_y > self.screen.get_height():\n\t\t\treturn\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type==pygame.KEYDOWN:\n\t\t\t\tif event.key==pygame.K_SPACE and not self.gameover:\n\t\t\t\t\t\tself.speed_y-=self.y_change*40\n\t\tif self.speed_y > 0:\n\t\t\tself.speed_y+=1.1*self.y_change\n\t\telse:\n\t\t\tself.speed_y+=3*self.y_change\n\t\tself.bird_y+=self.speed_y\n\t\tif self.bird_y < 0 or self.bird_y > self.screen.get_height():\n\t\t\tself.__gameover()\n\t\tself.counter+=1\n\t\tif self.counter == 3:\n\t\t\tself.counter = 0\n\tdef show(self):\n\t\tself.screen.blit(self.images[self.counter],(self.bird_x,self.bird_y))\n\tdef is_col(self,pipe):\n\t\tif self.bird_x>pipe.xpos and self.bird_xpipe.y1:\n\t\t\t\tself.__gameover()\nclass Pipe:\n\tdef __init__(self,screen,xpos,speed_x):\n\t\tself.screen=screen\n\t\tself.speed_x=speed_x\n\t\tself.width=screen.get_width()\n\t\tself.height=screen.get_height()\n\t\tself.uppipe=pygame.image.load(pictures['green_pipe_u'])\n\t\tself.downpipe=pygame.image.load(pictures['green_pipe_d'])\n\t\tself.__newpipe(xpos)\n\t\tpygame.display.update()\n\tdef __newpipe(self,xpos):\n\t\tself.xpos=xpos\n\t\tself.ypos_u=(random.random()*self.height/4)+self.height/2 +12\n\t\tself.y1=self.ypos_u\n\t\tself.y2=random.random()*self.height/4 + self.height/4 -12\n\t\tself.ypos_d=self.y2 - self.downpipe.get_height()\n\tdef update(self,scores):\n\t\tself.xpos-=self.speed_x\n\t\tif self.xpos+self.uppipe.get_width()<0:\n\t\t\tscores+=1\n\t\t\tself.__newpipe(self.width)\n\t\treturn scores\n\tdef show(self):\n\t\tself.screen.blit(self.uppipe, (self.xpos, self.ypos_u))\n\t\tself.screen.blit(self.downpipe, (self.xpos, self.ypos_d))\nclass Cloud:\n\tdef __init__(self,screen):\n\t\tself.screen=screen\n\t\tself.cloud=pygame.image.load(pictures['white_cloud'])\n\t\tself.__newcloud(self.screen.get_width())\n\tdef __newcloud(self,xpos):\n\t\tself.xpos=xpos\n\t\tself.ypos=(self.screen.get_height()-self.cloud.get_height())*random.random()\n\tdef update(self):\n\t\tself.xpos+=-1.5\n\t\tif self.xpos + self.cloud.get_width() < 0:\n\t\t\tself.__newcloud(self.screen.get_width())\n\tdef show(self):\n\t\tself.screen.blit(self.cloud, (self.xpos, self.ypos))\n","sub_path":"objects.py","file_name":"objects.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"313065456","text":"import time, os, sys\r\nfrom time import strftime\r\nimport threading\r\nimport thread\r\n\r\n\r\nfrom SerialCommunication import *\r\n\r\n\r\nclass startThread(threading.Thread):\r\n def __init__(self, target, *args):\r\n self._target = target\r\n self._args = args\r\n threading.Thread.__init__(self)\r\n \r\n def run(self):\r\n self._target(*self._args)\r\n\r\n'''\r\nTo be used only on Windows Operating Systems\r\n'''\r\nclass ConsoleLogger(SerialCommunication):\r\n\r\n def __init__(self, comPort, baudRate = 9600, prompt = None, username = None, password = None):\r\n '''\r\n comPort has to be 'com1 or com2 etc\r\n '''\r\n self.format = \"%Y-%m-%d_%H-%M-%S\"\r\n self.baudRate = baudRate\r\n SerialCommunication.__init__(self, int(str(comPort).lower().strip(\"com\")), baudRate, prompt, username, password)\r\n self.consoleLock = thread.allocate_lock()\r\n self.breakFlag = False # This is a shared variable .. guard it with consoleLock\r\n self.consoleProc = False\r\n self.logFileName = None\r\n self.log = False\r\n \r\n def setLogger(self, loggerObject):\r\n self.log = loggerObject\r\n SerialCommunication.setLogger(self, self.log)\r\n \r\n def _initLogFilePath(self, logFileName = None, logDir = None):\r\n if self.logFileName == None:\r\n if logFileName == None:\r\n self.logFileName = \"ConsoleLog-%s.txt\"%strftime(self.format)\r\n else:\r\n self.logFileName = logFileName\r\n \r\n if logDir == None:\r\n logDir = os.path.join(os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(\"ConsoleLogger.py\")), os.pardir)), \"logs\")\r\n try:\r\n if not os.path.exists(logDir):\r\n os.mkdir(logDir)\r\n\r\n self.logFilePath = os.path.join(logDir,self.logFileName)\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n raise\r\n\r\n def consoleThread(self):\r\n '''\r\n Private thread method .. not to be used externally\r\n '''\r\n self.consoleLock = thread.allocate_lock()\r\n self.connect()\r\n while True:\r\n try:\r\n output = self._rxStrict()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n \r\n if output == None:\r\n output = []\r\n newOutput = \"\"\r\n for l in output:\r\n if l == '\\r\\n':\r\n continue\r\n newOutput += l.strip('\\r\\n')\r\n try:\r\n self.fp.write(l.strip('\\r\\n'))\r\n self.fp.write(\"\\n\")\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n \r\n try:\r\n self.consoleLock.acquire()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n \r\n if self.breakFlag == True:\r\n try:\r\n self.consoleLock.release()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n break\r\n else:\r\n try:\r\n self.consoleLock.release()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n try:\r\n self.disconnect()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n try:\r\n self.fp.close()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n \r\n \r\n def __restart(self):\r\n '''\r\n Private method .. not to be used externally\r\n '''\r\n try:\r\n if self.consoleProc != False:\r\n return\r\n self.fp = open(self.logFilePath, \"a\")\r\n self.consoleProc = startThread(self.consoleThread)\r\n self.consoleProc.start()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n raise\r\n return self.logFilePath\r\n \r\n def startConsole(self, logFileName = None, logDir = None):\r\n '''\r\n Public method - to be called when the console logging should be started.\r\n If logFileName is not supplied a file with the time-stamped name is generated and is used to store the console logs\r\n If logDir is not supplied, the console log file will be stored in the \"logs\" folder.\r\n It returns the log file path.\r\n '''\r\n try:\r\n if self.consoleProc != False:\r\n self.stopConsole()\r\n self.logFileName = None\r\n self._initLogFilePath(logFileName, logDir)\r\n self.fp = open(self.logFilePath, \"w\")\r\n self.consoleProc = startThread(self.consoleThread)\r\n self.consoleProc.start()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n raise\r\n return self.logFilePath\r\n\r\n \r\n def start(self, logFileName = None, logDir = None):\r\n '''\r\n Public method - to be called when the console logging should be started.\r\n If logFileName is not supplied a file with the time-stamped name is generated and is used to store the console logs\r\n If logDir is not supplied, the console log file will be stored in the \"logs\" folder.\r\n It returns the log file path.\r\n '''\r\n try:\r\n if self.consoleProc != False:\r\n self.stopConsole()\r\n self.logFileName = None\r\n self._initLogFilePath(logFileName, logDir)\r\n self.fp = open(self.logFilePath, \"w\")\r\n self.consoleProc = startThread(self.consoleThread)\r\n self.consoleProc.start()\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n raise\r\n return self.logFilePath\r\n \r\n \r\n def stopConsole(self):\r\n '''\r\n Public method - to be called when the console logging is no longer needed. It returns the console log file path\r\n '''\r\n try:\r\n if self.consoleProc == False:\r\n return self.logFilePath\r\n self.consoleLock.acquire()\r\n self.breakFlag = True\r\n self.consoleLock.release()\r\n try:\r\n self.consoleProc.join()\r\n except:\r\n pass\r\n self.consoleProc = False\r\n self.breakFlag = False\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n raise\r\n return self.logFilePath\r\n \r\n def stop(self):\r\n '''\r\n Public method - to be called when the console logging is no longer needed. It returns the console log file path\r\n '''\r\n try:\r\n if self.consoleProc == False:\r\n return self.logFilePath\r\n self.consoleLock.acquire()\r\n self.breakFlag = True\r\n self.consoleLock.release()\r\n try:\r\n self.consoleProc.join()\r\n except:\r\n pass\r\n self.consoleProc = False\r\n self.breakFlag = False\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n raise\r\n return self.logFilePath\r\n \r\n def executeConsoleCmd(self, cmd):\r\n return self.execute(cmd)\r\n \r\n def execute(self, cmd):\r\n '''\r\n Public method - to be used to run non-blocking commands and also commands which do not generate a large output.\r\n It returns the output of the command in the form of a string (multi-line)\r\n '''\r\n try:\r\n self._initLogFilePath()\r\n self.stop()\r\n time.sleep(2)\r\n self.connect()\r\n time.sleep(2)\r\n self._tx(cmd)\r\n time.sleep(2)\r\n output = self._rxStrict()\r\n #time.sleep(2)\r\n self.disconnect()\r\n time.sleep(2)\r\n fp = open(self.logFilePath, \"a\")\r\n newOutput = \"\"\r\n for l in output:\r\n newOutput += l\r\n fp.write(l)\r\n fp.write(\"\\n\")\r\n fp.close()\r\n self.__restart()\r\n return newOutput\r\n except:\r\n if self.log:\r\n self.log.LogException()\r\n raise\r\n \r\n def getConsoleLogFilePath(self):\r\n '''\r\n Public method which returns the current logFilePath name\r\n '''\r\n return self.logFilePath\r\n \r\n\r\nif __name__ == \"__main__\":\r\n pass","sub_path":"test-automation-4partners/lib/ConsoleLogger.py","file_name":"ConsoleLogger.py","file_ext":"py","file_size_in_byte":8743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"33332774","text":"from collections import defaultdict\n\ndef hierholzer_algo(edges):\n \"\"\"\n Problem: find a circuit/path which uses each at edge exactly one time\n\n Given: DIRECTED graph\n \n Requirements: \n 1. All vertices with non-zero degree belong to a single strongly connected component\n 2. In-degree = Out-degree for all vertices\n\n\n idea: \n 1. start at random node if circuit else in one node with degree 1\n 2. build current path by taking unused edges\n 3. if you stuck somewhere backtrack (and add nodes to return list) until you still can take unuesd edges\n 4. return reuslt reversed\n\n\n ACTUALLY it is just postorder traversal with dfs\n \"\"\"\n\n\n \n graph = defaultdict(list)\n for i,j in edges:\n graph[i].append(j)\n\n degrees = {}\n for key in graph.keys():\n degrees[key] = len(graph[key])\n\n\n if len(edges) == 0:\n return\n\n\n curr_path = [edges[0][0]]\n circuit = []\n\n while curr_path:\n node = curr_path[-1]\n if degrees[node]>0:\n curr_path.append(graph[node].pop())\n degrees[node] -= 1\n else:\n circuit.append(curr_path.pop())\n\n return circuit[::-1]\n\nprint(hierholzer_algo([[0,1],[1,0],[1,2],[2,3],[3,1]]))\n \n \n\n\ndef alternative():\n \"\"\"\n hierholzer is similiar to postorder traveral for circut as well as for paths\n \"\"\"\n flightMap = defaultdict(list)\n\n for origin, dest in tickets:\n flightMap[origin].append(dest)\n\n\n for adjacent in flightMap.values():\n adjacent.sort(reverse=True)\n \n ret = []\n \n def dfs(origin):\n destList = flightMap[origin]\n while destList:\n dfs(destList.pop())\n ret.append(origin)\n\n\n\n dfs('JFK')\n\n return ret[::-1]\n","sub_path":"else/euler_circuit_hierholzer_algo_directed_graphs.py","file_name":"euler_circuit_hierholzer_algo_directed_graphs.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"28212704","text":"# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def levelOrder(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[List[int]]\n \"\"\"\n if not root:return []\n level = [root]\n res = []\n while level:\n nextlevel = []\n val = []\n for node in level:\n val.append(node.val)\n if node.left:\n nextlevel.append(node.left)\n if node.right:\n nextlevel.append(node.right)\n res.append(val)\n level = nextlevel\n return res","sub_path":"102_Binary_Tree_Level_Order_Traversal.py","file_name":"102_Binary_Tree_Level_Order_Traversal.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"463784161","text":"import torch\nimport torch.nn as nn\n\nfrom utils import *\nimport pdb\nimport argparse\nimport random\nfrom tqdm import tqdm\n\nfrom argha.models import NetCrossInteractionLayersz\n\nfrom utils import load_train_data, load_test_data, load_val_data, cal_affinity_torch\n\n\ndef do_stuff(args):\n ###### train ######\n train_set = dataset('train')\n train_loader = torch.utils.data.DataLoader(dataset=train_set, batch_size=args.batch_size, shuffle=True)\n val_set = dataset('val')\n val_loader = torch.utils.data.DataLoader(dataset=val_set, batch_size=args.batch_size, shuffle=False)\n model = NetCrossInteractionLayersz(args.l0, args.l1, args.l2, args.l3)\n model = nn.DataParallel(model)\n model = model.cuda()\n optimizer = torch.optim.Adam(model.parameters(), 1e-4)\n\n # fused_matrix = torch.tensor(np.load(args.data_processed_dir+'fused_matrix.npy')).cuda()\n loss_val_best = 1e10\n\n if args.train == 1:\n # train\n torch.cuda.empty_cache()\n for epoch in range(args.epoch):\n # for epoch in tqdm(range(args.epoch)):\n model.train()\n loss_epoch, batch = 0, 0\n for prot_data1, prot_data2, label in train_loader:\n prot_data1, prot_data2, label = prot_data1.cuda(), prot_data2.cuda(), label.cuda()\n\n optimizer.zero_grad()\n loss = model(prot_data1, prot_data2, label).mean()\n print('epoch', epoch, 'batch', batch, loss.detach().cpu().numpy())\n # print(\"loss size\",loss.size())\n loss.backward()\n torch.nn.utils.clip_grad_value_(model.parameters(), 5)\n optimizer.step()\n loss_epoch += loss.detach().cpu().numpy()\n batch += 1\n # break\n\n model.eval()\n loss_epoch_val, batch_val = 0, 0\n for prot_data1, prot_data2, label in val_loader:\n prot_data1, prot_data2, label = prot_data1.cuda(), prot_data2.cuda(), label.cuda()\n with torch.no_grad():\n loss = model(prot_data1, prot_data2, label).mean()\n loss_epoch_val += loss.detach().cpu().numpy()\n batch_val += 1\n\n print('epoch', epoch, 'train loss', loss_epoch / batch, 'val loss', loss_epoch_val / batch_val)\n if loss_epoch_val / batch_val < loss_val_best:\n loss_val_best = loss_epoch_val / batch_val\n torch.save(model.module.state_dict(),\n './weights/concatenation_' + str(args.l0) + '_' + str(args.l1) + '_' + str(\n args.l2) + '_' + str(args.l3) + '.pth')\n # torch.save(model.state_dict(), './weights/concatenation_' + str(args.l0) + '_' + str(args.l1) + '_' + str(args.l2) + '_' + str(args.l3) + '.pth')\n\n del train_loader\n del val_loader\n\n ###### evaluation ######\n # evaluation\n model = NetCrossInteractionLayersz(args.l0, args.l1, args.l2, args.l3).cuda()\n model.load_state_dict(torch.load(\n './weights/concatenation_' + str(args.l0) + '_' + str(args.l1) + '_' + str(args.l2) + '_' + str(\n args.l3) + '.pth'))\n model.eval()\n\n data_processed_dir = args.data_processed_dir\n\n print('train')\n eval_set = dataset('train')\n eval_loader = torch.utils.data.DataLoader(dataset=eval_set, batch_size=args.batch_size, shuffle=False)\n cal_affinity_torch(model, eval_loader)\n # prot_length1 = np.load(data_processed_dir+'prot_train_length1.npy')\n # prot_length2 = np.load(data_processed_dir+'prot_train_length2.npy')\n # cal_interaction_torch(model, eval_loader, prot_length1, prot_length2)\n\n print('test')\n eval_set = dataset('test')\n eval_loader = torch.utils.data.DataLoader(dataset=eval_set, batch_size=args.batch_size, shuffle=False)\n cal_affinity_torch(model, eval_loader)\n\n print('val')\n eval_set = dataset('val')\n eval_loader = torch.utils.data.DataLoader(dataset=eval_set, batch_size=args.batch_size, shuffle=False)\n cal_affinity_torch(model, eval_loader)\n # prot_length1 = np.load(data_processed_dir+'prot_dev_length1.npy')\n # prot_length2 = np.load(data_processed_dir+'prot_dev_length2.npy')\n # cal_interaction_torch(model, eval_loader, prot_length1, prot_length2)\n\n \"\"\"\n print('test')\n eval_set = dataset('test')\n eval_loader = torch.utils.data.DataLoader(dataset=eval_set, batch_size=args.batch_size, shuffle=False)\n cal_affinity_torch(model, eval_loader)\n prot_length1 = np.load(data_processed_dir+'prot_test_length1.npy')\n prot_length2 = np.load(data_processed_dir+'prot_test_length2.npy')\n cal_interaction_torch(model, eval_loader, prot_length1, prot_length2)\n\n print('exactly one unseen protein')\n eval_set = dataset('unseen_prot')\n eval_loader = torch.utils.data.DataLoader(dataset=eval_set, batch_size=args.batch_size, shuffle=False)\n cal_affinity_torch(model, eval_loader)\n prot_length1 = np.load(data_processed_dir+'uniq_one_length1.npy')\n prot_length2 = np.load(data_processed_dir+'uniq_one_length2.npy')\n cal_interaction_torch(model, eval_loader, prot_length1, prot_length2)\n\n\n print('unseen both')\n eval_set = dataset('unseen_both')\n eval_loader = torch.utils.data.DataLoader(dataset=eval_set, batch_size=args.batch_size, shuffle=False)\n cal_affinity_torch(model, eval_loader)\n rot_length1 = np.load(data_processed_dir+'uniq_both_length1.npy')\n prot_length2 = np.load(data_processed_dir+'uniq_both_length2.npy')\n cal_interaction_torch(model, eval_loader, prot_length1, prot_length2)\n\n \"\"\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--l0', type=float, default=0.01)\n parser.add_argument('--l1', type=float, default=0.01)\n parser.add_argument('--l2', type=float, default=0.0001)\n parser.add_argument('--l3', type=float, default=1000.0)\n parser.add_argument('--batch_size', type=int, default=8)\n parser.add_argument('--epoch', type=int, default=200)\n parser.add_argument('--train', type=int, default=0)\n parser.add_argument('--data_processed_dir', type=str,\n default='/home/arghamitra.talukder/ecen_404/vector_machine_data/')\n args = parser.parse_args()\n print(args)\n\n torch.manual_seed(0)\n torch.cuda.manual_seed_all(0)\n torch.backends.cudnn.deterministic = True\n np.random.seed(0)\n random.seed(0)\n\n do_stuff(args=args)\n\nif __name__==\"__main__\":\n main()\n","sub_path":"ECEN_404/PPI_Xmodality/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"433769349","text":"#!/usr/local/bin/python3\n\nimport os\nimport fnmatch\nimport datetime\n\nheader='header.template.html'\nfooter='footer.template.html'\n\ncontents=[]\n\ndef gentitle(name):\n if name=='index':\n return 'Homepage'\n else:\n return name.capitalize()\n\ndef genpage(name):\n names=''\n for filename in contents:\n if name==filename[1]:\n names += '
  • '+gentitle(filename[1])+'
  • \\n'\n else:\n names += '
  • '+gentitle(filename[1])+'
  • \\n'\n return names\n\n\ndef main():\n for file in sorted(os.listdir()):\n if fnmatch.fnmatch(file,'*.content.html'):\n contents.append((file,file.split('.')[1]))\n for filename in contents:\n target=filename[1]+'.html'\n w=open('./target/'+target,'w');\n for name in [header,filename[0],footer]:\n r=open(name,'r')\n w.write(r.read().format(subtitle=gentitle(filename[1]),pages=genpage(filename[1]),updatetime=datetime.date.today()))\n print (target + ' done.')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"makeall.py","file_name":"makeall.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"380494456","text":"from conans import ConanFile, Meson, tools\nfrom six import StringIO\nfrom conans.errors import ConanInvalidConfiguration\nfrom conans.tools import os_info\n# from conan.tools.meson import MesonToolchain\nimport os\nimport shutil\n\nclass FubbleConan(ConanFile):\n name = \"fubble\"\n license = \"All Rights Reserved\"\n author = \"Fubble OG \"\n url = \"fubble.io\"\n description = \"Conferencing that works\"\n topics = (\"conference\", \"fubble\", \"video\", \"audio\", \"webrtc\")\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [False, True],\n \"treat_warnings_as_errors\": [True, False],\n \"sanatize\": [True, False], \"qt_install\": \"ANY\",\n \"enable_ui\": [True, False], \"meson_cross_file\": \"ANY\"}\n # https://docs.conan.io/en/latest/reference/conanfile/attributes.html#default-options\n default_options = {\"shared\": False, \"qt_install\": None, \"enable_ui\": True,\n \"meson_cross_file\": None,\n \"nlohmann_json:multiple_headers\": True, \"restinio:asio\": \"boost\",\n # qt options\n # \"qt:openssl\": False, \"qt:with_mysql\": False, \"qt:with_pq\": False, \"qt:with_odbc\": False, \"qt:widgets\": False,\n # \"qt:with_libalsa\": False,\n # qt submodules https://github.com/bincrafters/conan-qt/blob/testing/5.15.1/qtmodules.conf\n # \"qt:qtsvg\": True, \"qt:qtmultimedia\": True, \"qt:qtquickcontrols2\": True, \"qt:qtcharts\": True,\n \"treat_warnings_as_errors\": False, \"sanatize\": False}\n generators = \"pkg_config\"\n exports_sources = \"*\", \"!fubble/app/mock_qml_models*\"\n no_copy_source = True\n\n # https://docs.conan.io/en/latest/versioning/introduction.html\n version = '1.0.0'\n #def set_version(self):\n # buffer = StringIO()\n # self.run(\"git describe\", output=buffer)\n # self.version = buffer.getvalue()\n\n def _get_qt_bin_paths(self):\n if self.settings.os != \"Windows\":\n return []\n return ['C:\\\\Qt\\\\5.15.1\\\\msvc2019_64\\\\bin']\n # return self.deps_cpp_info[\"qt\"].bin_paths\n\n def _is_ios(self):\n return self.settings.os == \"iOS\"\n\n def _get_build_type(self):\n return self.settings.get_safe(\"build_type\", default=\"Release\")\n\n def config_options(self):\n if self.settings.os == \"Windows\":\n del self.options.sanatize\n\n def configure(self):\n if self._get_build_type() == \"Release\" and 'sanatize' in self.options:\n if self.options.sanatize:\n raise ConanInvalidConfiguration(\"can't enable sanatize without debug information\")\n\n def imports(self):\n self.copy(\"*.dll\", dst=\"bin\", keep_path=False)\n\n #def source(self):\n # self.run(\"git clone git@gitlab.com:acof/fubble.git .\")\n\n def build_requirements(self):\n # if self.settings.os == \"Windows\":\n # # will not compile with less than visual studio 2019\n # self.build_requires(\"qt/5.15.0@bincrafters/stable\")\n if not tools.which('meson'):\n self.build_requires(\"meson/0.56.0\")\n if os_info.is_macos: # maybe even for windows, instead of the pkgconfig-lite \"hack\"\n self.build_requires(\"pkgconf/1.7.3\")\n\n def requirements(self):\n self.requires(\"nlohmann_json/3.7.0\")\n self.requires(\"boost/1.73.0\")\n self.requires(\"gtest/1.10.0\")\n self.requires(\"fmt/7.0.3\")\n self.requires(\"google-webrtc/88\")\n if not self._is_ios() and self.options.enable_ui:\n self.requires(\"RectangleBinPack/1.0.2\")\n if self.settings.os == \"Linux\":\n self.requires(\"restinio/0.6.11\")\n # self.requires(\"qt/5.15.1@bincrafters/stable\")\n\n # does not work well... it's a very new feature (2020-12), revisit and do issues!\n #def generate(self):\n # tc = MesonToolchain(self)\n # tc.generate()\n\n def build(self):\n # https://docs.conan.io/en/latest/reference/build_helpers/meson.html\n addtional_paths = []\n if self.settings.os == \"Windows\":\n qt_path_bin = self._get_qt_bin_paths()\n self.output.info(\"qt_path_bin:%s\" % (qt_path_bin))\n addtional_paths += qt_path_bin\n elif self.options.qt_install:\n qt_install = str(self.options.qt_install)\n self.output.info(\"qt_install:%s\" % (qt_install))\n addtional_paths += [os.path.join(qt_install, 'bin')]\n\n boost_path = self.deps_cpp_info[\"boost\"].rootpath\n self.output.info(\"boost_path:%s\" % (boost_path))\n boost_include_path = self.deps_cpp_info[\"boost\"].include_paths\n self.output.info(\"boost_include_path:%s\" % (boost_include_path))\n boost_library_path = self.deps_cpp_info[\"boost\"].lib_paths\n self.output.info(\"boost_library_path:%s\" % (boost_library_path))\n\n with_servers = False\n with_tests = True\n if self.settings.os == \"Windows\":\n with_tests = False\n if self.settings.os == \"Linux\":\n with_servers = True\n with_ui = self.options.enable_ui == True\n if self._is_ios():\n with_servers = False\n with_tests = False\n with_ui = False\n\n # https://mesonbuild.com/Builtin-options.html#base-options\n meson_options = {'cpp_std': 'c++17', 'b_ndebug': 'if-release',\n 'with_servers': with_servers, 'with_tests': with_tests,\n 'with_ui': with_ui}\n if self.settings.os == \"Linux\":\n meson_options['warning_level'] = '3'\n if self.options.treat_warnings_as_errors:\n meson_options['werror'] = 'true'\n build_type = self._get_build_type()\n if build_type == 'Debug' and self.settings.os == 'Linux':\n meson_options['b_lto'] = 'false'\n if 'sanatize' in self.options and self.options.sanatize:\n meson_options['b_sanitize'] = 'address,undefined'\n if self._is_ios() and self.settings.arch != \"x86_64\": # no bitcode for simulator\n meson_options['b_bitcode'] = 'true'\n meson_options['b_pch'] = 'false'\n # meson_options['b_vscrt'] = 'mtd'\n\n meson = Meson(self)\n with tools.environment_append({\n \"PATH\": addtional_paths,\n \"BOOST_ROOT\": boost_path,\n \"BOOST_INCLUDEDIR\": boost_include_path,\n \"BOOST_LIBRARYDIR\": boost_library_path}):\n pkg_config_paths = [self.install_folder]\n if self.options.qt_install:\n pkg_config_paths += [os.path.join(str(self.options.qt_install), 'lib/pkgconfig')]\n meson_args = ['--fatal-meson-warnings']\n if self.options.meson_cross_file:\n cross_file = str(self.options.meson_cross_file)\n if not os.path.isabs(cross_file):\n cross_file = os.path.abspath(os.path.join(self.source_folder, cross_file))\n cross_file_copy = os.path.join(self.install_folder, 'meson_cross.ini')\n shutil.copyfile(cross_file, cross_file_copy)\n tools.replace_in_file(cross_file_copy,\n '__SYSROOT__', os.environ.get(\"SYSROOT\", \"\"),\n strict=False)\n tools.replace_in_file(cross_file_copy,\n '__CC__', os.environ.get(\"CC\", \"\"),\n strict=False)\n tools.replace_in_file(cross_file_copy,\n '__CXX__', os.environ.get(\"CXX\", \"\"),\n strict=False)\n tools.replace_in_file(cross_file_copy,\n '__AR__', os.environ.get(\"AR\", \"\"),\n strict=False)\n tools.replace_in_file(cross_file_copy,\n '__STRIP__', os.environ.get(\"STRIP\", \"\"),\n strict=False)\n self.output.info(\"cross_file %s\" % cross_file_copy)\n meson_args += ['--cross-file', cross_file_copy]\n\n # this is a very dirty hack. for pkgconf. https://github.com/mesonbuild/meson/issues/8448\n self.run('ln -fs /home $SYSROOT || true')\n self.run('ln -fs /root $SYSROOT || true')\n\n # meson_args += ['--cross-file', os.path.join(self.install_folder, 'conan_meson_cross.ini')]\n\n self.output.info(\"pkg_config_paths: %s\" % pkg_config_paths)\n meson.configure( build_folder=\"meson\", defs=meson_options,\n args=meson_args,\n pkg_config_paths=pkg_config_paths\n )\n build_args = []\n ninja_jobs = os.getenv('FUBBLE_BUILD_NINJA_JOBS')\n if ninja_jobs:\n build_args += ['-j %s' % (ninja_jobs)]\n # build_args += ['-k0']\n # build_args += ['-v]\n meson.build(args=build_args)\n\n def package(self):\n meson = Meson(self)\n meson.install(build_dir=\"meson\")\n if self.settings.os == \"Linux\":\n pass\n if self.settings.os == \"Windows\":\n bin_dir = os.path.join(self.package_folder, 'bin')\n vars_dict = tools.vcvars_dict(self.settings)\n\n windows_sdk_dir = vars_dict['WindowsSdkDir']\n windows_sdk_version = vars_dict['WindowsSDKVersion']\n ucrt_redist_dir = os.path.join(windows_sdk_dir, 'Redist', windows_sdk_version, 'ucrt', 'DLLs', 'x64')\n if not os.path.exists(ucrt_redist_dir):\n raise ConanInvalidConfiguration(\"ucrt redist dir does not exist: %s\" % (ucrt_redist_dir))\n self.copy('*.dll', dst=bin_dir, src=ucrt_redist_dir)\n\n vctoolsredist_dir = vars_dict['VCToolsRedistDir']\n vcredist_dir = os.path.join(vctoolsredist_dir, 'x64', 'Microsoft.VC142.CRT')\n if not os.path.exists(vcredist_dir):\n raise ConanInvalidConfiguration(\"ucrt redist dir does not exist: %s\" % (ucrt_redist_dir))\n self.copy('*.dll', dst=bin_dir, src=vcredist_dir)\n\n qt_path_bin = self._get_qt_bin_paths()\n with tools.environment_append({\"PATH\": qt_path_bin}):\n with tools.chdir(bin_dir):\n qml_dir = os.path.join(self.source_folder, 'fubble', 'app')\n # dont do -no-widgets # widgets is needed for svg\n self.run('windeployqt.exe fubble.exe --no-compiler-runtime --qmldir \"%s\"'\n % (qml_dir))\n\n def package_info(self):\n self.cpp_info.libs = ['fubble']\n self.cpp_info.includedirs = ['include']\n self.cpp_info.cxxflags = [\n '-DBOOST_THREAD_VERSION=5',\n '-DBOOST_ASIO_SEPARATE_COMPILATION',\n '-DBOOST_BEAST_SEPARATE_COMPILATION',\n ]\n if self.settings.os == \"Windows\":\n self.cpp_info.system_libs = [\n 'ole32.lib', 'dbgeng.lib',\n ]\n","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":10803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"551836833","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\n\nfrom flask import Blueprint, current_app\n\nfrom eduid_common.api.decorators import require_user, can_verify_identity, MarshalWith, UnmarshalWith\nfrom eduid_common.api.helpers import add_nin_to_user, verify_nin_for_user\nfrom eduid_common.api.exceptions import MsgTaskFailed, AmTaskFailed\nfrom eduid_common.api.schemas.csrf import CSRFResponse\nfrom eduid_webapp.lookup_mobile_proofing import schemas\nfrom eduid_webapp.lookup_mobile_proofing.helpers import create_proofing_state, match_mobile_to_user\nfrom eduid_webapp.lookup_mobile_proofing.lookup_mobile_relay import LookupMobileTaskFailed\n\n__author__ = 'lundberg'\n\nmobile_proofing_views = Blueprint('lookup_mobile_proofing', __name__, url_prefix='', template_folder='templates')\n\n\n@mobile_proofing_views.route('/proofing', methods=['GET'])\n@MarshalWith(CSRFResponse)\n@require_user\ndef get_state(user):\n return {}\n\n\n@mobile_proofing_views.route('/proofing', methods=['POST'])\n@UnmarshalWith(schemas.LookupMobileProofingRequestSchema)\n@MarshalWith(schemas.LookupMobileProofingResponseSchema)\n@can_verify_identity\n@require_user\ndef proofing(user, nin):\n current_app.logger.info('Trying to verify nin via mobile number for user {}.'.format(user))\n current_app.logger.debug('NIN: {!s}.'.format(nin))\n\n # Add nin as not verified to the user\n proofing_state = create_proofing_state(user, nin)\n add_nin_to_user(user, proofing_state)\n\n # Get list of verified mobile numbers\n verified_mobiles = [item.number for item in user.phone_numbers.to_list() if item.is_verified]\n if not verified_mobiles:\n return {'_status': 'error', 'message': 'no_phone'}\n\n try:\n success, proofing_log_entry = match_mobile_to_user(user, nin, verified_mobiles)\n except LookupMobileTaskFailed:\n current_app.stats.count('validate_nin_by_mobile_error')\n return {'_status': 'error', 'message': 'error_lookup_mobile_task'}\n except MsgTaskFailed:\n current_app.stats.count('navet_error')\n return {'_status': 'error', 'message': 'error_navet_task'}\n\n if success:\n try:\n # Verify nin for user\n verify_nin_for_user(user, proofing_state, proofing_log_entry)\n return {'success': True, 'message': 'letter.verification_success'}\n except AmTaskFailed as e:\n current_app.logger.error('Verifying nin for user {} failed'.format(user))\n current_app.logger.error('{}'.format(e))\n return {'_status': 'error', 'message': 'Temporary technical problems'}\n\n return {'_status': 'error', 'message': 'nins.no-mobile-match'}\n","sub_path":"src/eduid_webapp/lookup_mobile_proofing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"78212847","text":"# Python 測試 twstock 1\n\nimport twstock\nimport matplotlib.pyplot as plt\nimport time\n\n# 以鴻海的股票代號建立 Stock 物件\nstock = twstock.Stock('2317')\nprint('最新資料')\nprint(stock.price)\nprint('日期:',stock.date[-1])\nprint('開盤價:',stock.open[-1])\nprint('最高價:',stock.high[-1])\nprint('最低價:',stock.low[-1])\nprint('收盤價:',stock.price[-1])\n\n# 以鴻海的股票代號建立 Stock 物件\nstock = twstock.Stock('2317')\n# 取得 2019 年 12 月的資料\nstocklist = stock.fetch(2019,12)\nfor s in stocklist:\n print(s.date.strftime('%Y-%m-%d'), end='\\t')\n print(s.open, end='\\t')\n print(s.high, end='\\t')\n print(s.low, end='\\t')\n print(s.close)\n\n\n# 鴻海股票即時交易資訊\nreal = twstock.realtime.get('2317') \nif real['success']: #如果讀取成功\n print('即時股票資料:',real['info']['name']) \n print('開盤價:',real['realtime']['open'], end=', ')\n print('最高價:',real['realtime']['high'], end=', ') \n print('最低價:',real['realtime']['low'], end=', ')\n print('目前股價:',real['realtime']['latest_trade_price']) \nelse:\n print('錯誤:' + real['rtmessage'])\n\n\n# 以鴻海的股票代號建立 Stock 物件\nstock = twstock.Stock('2317') \n# 取得 2019 年 12 月的資料\nstocklist = stock.fetch(2019,12) \nlistx = []\nlisty = []\nfor s in stocklist:\n listx.append(s.date.strftime('%Y-%m-%d'))\n listy.append(s.close)\n\nplt.figure(figsize=[10,5])\t#圖像大小[英吋]\nplt.title('鴻海2019年12月股價',fontsize=18)\nplt.xlabel(\"日期\",fontsize=14)\nplt.ylabel(\"股價\",fontsize=14)\nplt.plot(listx, listy, 'r:s')\n\nplt.xticks(rotation=45)\nplt.grid('k:', alpha=0.5)\nplt.ylim(88,93)\nplt.yticks([88,89,90,91,92,93])\n\n#設定中文字型及負號正確顯示\n#設定中文字型檔\nplt.rcParams[\"font.sans-serif\"] = \"Microsoft JhengHei\" # 將字體換成 Microsoft JhengHei\n#設定負號\nplt.rcParams[\"axes.unicode_minus\"] = False # 讓負號可正常顯示\n\nplt.show() \n\n\ncompanys = ['2330','2912','3293']\nplt.figure(figsize=[10,5])\t#圖像大小[英吋]\nfor company in companys:\n stock = twstock.Stock(company) \n # 取得 2019 年 12 月的資料\n stocklist = stock.fetch(2019,12) \n listx = []\n listy = []\n for s in stocklist:\n listx.append(s.date.strftime('%Y-%m-%d'))\n listy.append(s.close)\n \n plt.plot(listx, listy)\n plt.xticks(rotation=45)\nplt.show()\n\n\n\n#plt.figure(figsize=[12,30])\t#圖像大小[英吋]\nstock = twstock.Stock('2317') \nslist = []\nfor i in range(1,13):\n stocklist = stock.fetch(2019,i)\n [slist.append(s) for s in stocklist]\n# listx = [s.date.strftime('%d') for s in stocklist]\n# listy = [s.close for s in stocklist]\n# plt.subplot('62{}'.format(i))\n# plt.xticks(rotation=45)\n# plt.title(label=\"{}月\".format(i))\n\n# plt.plot(listx, listy)\n print(len(slist))\n time.sleep(5)\n if i == 6:\n time.sleep(20)\n \n#plt.show()\n\n#lista = []\n#list1 = [1,2,3,4,5]\n#list2 = [7,8,9,10,11]\n#list1.append(list2)\n#list1\n#%%\n\n\n#將資料寫出到csv檔 \nimport csv\nwith open('2019_2330.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(slist)\n\n","sub_path":"_4.python/urllib_requests_BeautifulSoup/_stock/stock2_twstock1.py","file_name":"stock2_twstock1.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"69447203","text":"import pygame\nimport pygame.camera\nimport pygame_gui\n\n\n\"\"\"\nPygame Camera module is a bit tricky.\n\nOn Windows:\n- Requires VideoCapture grabbed from here: https://www.lfd.uci.edu/~gohlke/pythonlibs/#videocapture\n installed with 'pip install name_of_file.whl'\n- Doesn't work with python 3.8 and pygame 1.9.6 \n- Works fine on python 3.6 and pygame 1.9.6\n- Works fine with 3.8 and 2.0.0.dev6\n- 'list cameras' doesn't seem to actually list multiple usb cameras, they still work you just have \n to set the index yourself\n\"\"\"\n\n\nclass CameraWindow(pygame_gui.elements.UIWindow):\n def __init__(self,\n rect: pygame.Rect,\n camera_id,\n camera_name,\n ui_manager: pygame_gui.core.interfaces.IUIManagerInterface):\n super().__init__(rect, ui_manager, window_display_title=camera_name, resizable=True)\n\n self.camera = None\n\n self.camera = pygame.camera.Camera(camera_id, (160, 120))\n self.camera.start()\n\n cam_rect = pygame.Rect((0, 0), self.get_container().rect.size)\n self.cam_image = pygame_gui.elements.UIImage(relative_rect=cam_rect,\n image_surface=self.camera.get_image(),\n manager=self.ui_manager,\n container=self,\n anchors={'left': 'left',\n 'right': 'right',\n 'top': 'top',\n 'bottom': 'bottom'})\n\n def update(self, time_delta: float):\n super().update(time_delta)\n\n if self.camera is not None:\n\n self.cam_image.set_image(pygame.transform.smoothscale(self.camera.get_image(),\n self.get_container().rect.size))\n\n\npygame.init()\npygame.camera.init()\n\npygame.display.set_caption('Quick Start')\nwindow_surface = pygame.display.set_mode((800, 600))\nmanager = pygame_gui.UIManager((800, 600), 'data/themes/quick_theme.json')\n\nbackground = pygame.Surface((800, 600))\nbackground.fill(manager.ui_theme.get_colour('dark_bg'))\n\n\ncam_window_pos = [10, 10]\nnum_connected_cameras = 1\ncam_names = [\"My Camera\", \"My Boss\"]\nfor cam_id in range(0, num_connected_cameras):\n cam_window_rect = pygame.Rect(0, 0, 400, 300)\n cam_window_rect.topleft = cam_window_pos\n CameraWindow(cam_window_rect, cam_id, cam_names[cam_id], manager)\n cam_window_pos = (cam_window_pos[0] + 420,\n cam_window_pos[1])\n\nclock = pygame.time.Clock()\nis_running = True\n\nwhile is_running:\n time_delta = clock.tick(60)/1000.0\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n is_running = False\n\n manager.process_events(event)\n\n manager.update(time_delta)\n\n window_surface.blit(background, (0, 0))\n manager.draw_ui(window_surface)\n\n pygame.display.update()\n","sub_path":"camera_window_test.py","file_name":"camera_window_test.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"79536929","text":"from .. import utils\n\n# Constants\n\nincrease_factor = 2\ninitial_diff = 1\nneg_obj_name = \"neg_obj\"\n\n# Attributes\n\nsolver = None\nnegated = False\noptdir = 'min'\n\ndef configure(solv, options, inpcode, od):\n global solver\n global optdir\n solver = solv\n optdir = od\n solver.configure(inpcode, options)\n \ndef optimize(objective, accuracy):\n global solver\n global negated\n verbprint = utils.verbprint\n utils.stats_create(\"Bisection time\", 0.0)\n utils.stats_create(\"Bisection iterations\", 0)\n obj = objective\n if (optdir == 'max'):\n if (negated == False):\n verbprint(3, \"Converting maximization problem into minimization problem...\", False)\n solver.add_opposite_eq(neg_obj_name, obj)\n negated = True\n verbprint(3, \"done.\", True)\n obj = neg_obj_name\n feas_model = solver.check_feasibility()\n if (feas_model == None):\n return None\n start_up = solver.get_float(feas_model, obj, accuracy)\n verbprint(3, \"Initial value for the objective: \" + str(start_up), True)\n verbprint(3, \"Looking for initial bounds...\", True)\n utils.increase_indentation()\n (lower, upper, gbounds_model, naive_found_it) = get_bounds(obj, start_up, accuracy, feas_model)\n utils.decrease_indentation()\n if (naive_found_it == True):\n return gbounds_model\n verbprint(3, \"Initial interval: \" + str((lower, upper)), True)\n verbprint(3, \"Applying bisection...\", True)\n utils.increase_indentation() \n bisec_model = bisection(obj, lower, upper, accuracy, gbounds_model)\n utils.decrease_indentation()\n if (bisec_model != None):\n objval = solver.get_float(bisec_model, obj, accuracy)\n verbprint(3, \"Bisection complete. Found objective: \" + str(objval), True)\n return bisec_model\n\ndef get_bounds(objective, upper, accuracy, feas_model):\n global increase_factor\n global initial_diff\n global solver\n gbounds_model = feas_model\n verbprint = utils.verbprint\n utils.time_start(\"Bounds search time\")\n diff = initial_diff\n push_count = 0\n lower = upper - diff\n iteration = 1\n finished = False\n naive_found_it = False\n while (finished == False):\n verbprint(3, \"Iteration \" + str(iteration), True)\n verbprint(3, \"NAIVE step\", True)\n new = upper - accuracy\n verbprint(3, \"Trying with value \" + str(upper) + \" - \" + str(accuracy) + \" = \" + str(new), True)\n verbprint(3, \"Adding condition \" + str(objective) + \" < \" + str(new) + \" ...\", False)\n solver.add_lt(objective, new)\n push_count = push_count + 1\n verbprint(3, \"done.\", True)\n tmpmodel = solver.check_feasibility()\n verbprint(3, \"Result is: \" + str(\"sat\" if (tmpmodel != None) else \"unsat\"), True)\n if (tmpmodel == None):\n finished = True\n naive_found_it = True\n else:\n objval = solver.get_float(tmpmodel, objective, accuracy)\n verbprint(3, \"Objective value: \" + str(objval), True)\n upper = objval\n gbounds_model = tmpmodel\n verbprint(3, \"UBS step\", True)\n verbprint(3, \"Adding condition \" + objective + \" < \" + str(lower) + \" ...\", False)\n solver.add_lt(objective, lower)\n push_count = push_count + 1\n verbprint(3, \"done.\", True)\n tmpmodel = solver.check_feasibility()\n verbprint(3, \"Result is: \" + str(\"sat\" if (tmpmodel != None) else \"unsat\"), True)\n if (tmpmodel != None):\n objval = solver.get_float(tmpmodel, objective, accuracy)\n verbprint(3, \"Objective (\" + objective + \") value: \" + str(objval), True)\n upper = objval\n diff = diff * increase_factor\n lower = upper - diff\n verbprint(3, \"lower = \" + str(lower) + \", upper = \" + str(upper), True)\n gbounds_model = tmpmodel\n else:\n verbprint(3, \"Removing the last assertion...\", False)\n solver.pop(1)\n push_count = push_count - 1\n verbprint(3, \"done.\", True)\n finished = True\n iteration = iteration + 1\n verbprint(3, \"Clearing \" + str(push_count) + \" initial bounds learned clauses...\", False)\n solver.pop(push_count)\n verbprint(3, \"done.\", True)\n utils.stats_update(\"Bounds search time\", utils.time_take(\"Bounds search time\"))\n utils.stats_update(\"Bounds search iterations\", iteration)\n return lower, upper, gbounds_model, naive_found_it\n\n \ndef bisection(objective, lower, upper, accuracy, gbounds_model):\n global solver\n push_count=0\n bisec_model = gbounds_model\n utils.time_start(\"Bisection time\")\n verbprint = utils.verbprint\n iteration=0\n finished = False\n while ((upper - lower > accuracy) and (finished == False)):\n iteration = iteration + 1\n verbprint(3, \"Iteration \" + str(iteration), True)\n verbprint(3, \"NAIVE step\", True)\n new = upper - accuracy\n verbprint(3, \"Trying with value \" + str(upper) + \" - \" + str(accuracy) + \" = \" + str(new), True)\n verbprint(3, \"Adding condition \" + str(objective) + \" < \" + str(new) + \" ...\", False)\n solver.add_lt(objective, new)\n push_count = push_count + 1\n verbprint(3, \"done.\", True)\n tmpmodel = solver.check_feasibility()\n verbprint(3, \"Result is: \" + str(\"sat\" if (tmpmodel != None) else \"unsat\"), True)\n if (tmpmodel == None):\n finished = True\n else:\n objval = solver.get_float(tmpmodel, objective, accuracy)\n verbprint(3, \"Objective value: \" + str(objval), True)\n upper = objval\n bisec_model = tmpmodel\n verbprint(3, \"UBS step\", True)\n middle = (lower + upper) / 2.0\n verbprint(3, \"Trying with lower = \" + str(lower) + \" and upper = \" + str(upper), True)\n verbprint(3, \"middle = \" + str(middle), True)\n verbprint(3, \"Adding condition \" + str(objective) + \" < \" + str(middle) + \" ...\", False)\n solver.add_lt(objective, middle)\n push_count = push_count + 1\n verbprint(3, \"done.\", True)\n tmpmodel = solver.check_feasibility()\n verbprint(3, \"Result is: \" + str(\"sat\" if (tmpmodel != None) else \"unsat\"), True)\n if (tmpmodel != None):\n objval = solver.get_float(tmpmodel, objective, accuracy)\n verbprint(3, \"Objective value: \" + str(objval), True)\n upper = min(middle, objval)\n bisec_model = tmpmodel\n else:\n solver.pop(1)\n push_count = push_count - 1\n lower = middle\n verbprint(3, \"Clearing \" + str(push_count) + \" bisection learned clauses...\", False)\n solver.pop(push_count)\n verbprint(3, \"done.\", True)\n utils.stats_update(\"Bisection time\", utils.time_take(\"Bisection time\"))\n utils.stats_update(\"Bisection iterations\", iteration)\n return bisec_model\n\n\n# Auxiliary functions required by above layers\n\ndef model_vars(model):\n return solver.model_vars(model)\n\ndef is_int(model, x_str):\n return solver.is_int(model, x_str)\n\ndef get_model_value(model, x_str):\n return solver.get_model_value(model, x_str)\n\ndef get_floor(model, x_str):\n return solver.get_floor(model, x_str)\n\ndef get_ceil(model, x_str):\n return solver.get_ceil(model, x_str)\n \ndef exclude_interval(x, a, b):\n return solver.exclude_interval(x, a, b)\n\ndef get_obj(model, objective, accuracy):\n return solver.get_float(model, objective, accuracy)\n\n\n","sub_path":"optstack/croptimizers/_hybrid.py","file_name":"_hybrid.py","file_ext":"py","file_size_in_byte":6987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"579704112","text":"#!/usr/bin/env python\n# (C) Copyright 2011 Dapper Vision, Inc.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\"\"\"Train an Eigenface feature on the lfw dataset.\n\"\"\"\n__author__ = 'Vlad I. Morariu '\n__license__ = 'GPL V3'\n\n\nimport face_feature\nimport imfeat\nimport cv\nimport numpy as np\nimport random\nimport cPickle\ntry:\n import unittest2 as unittest\nexcept ImportError:\n import unittest\n\n\ndef get_lfw_cropped_data(split='dv_train'):\n \"\"\"\n Args:\n split: Dataset split, one of:\n 'dv_train', 'dv_test',\n '01_train', '01_test',\n '02_train', '02_test',\n '03_train', '03_test',\n '04_train', '04_test',\n '05_train', '05_test',\n '06_train', '06_test',\n '07_train', '07_test',\n '08_train', '08_test',\n '09_train', '09_test',\n '10_train', '10_test'\n (default: 'dv_train')\n\n Returns:\n Dataset as specified by 'split'\n\n Data is in the form of out[[image_path1,image_path2]] = objects, where\n objects is {'class': class_name}. Here classname is either\n 'same' or 'diff' based on whether the images are of the same\n person or not.\n \"\"\"\n lfw_cropped_path = '/home/morariu/downloads/lfwcrop_color'\n lists_path = '%s/lists' % lfw_cropped_path\n faces_path = '%s/faces' % lfw_cropped_path\n splitnums = set(map(lambda x: '%02i' % x, range(1, 11)) + ['dv'])\n splittypes = set(['train', 'test'])\n classnames = set(['same', 'diff'])\n\n components = split.lower().split('_')\n if(len(components) < 2 or len(components) > 3 or\n not components[0] in splitnums or\n not components[1] in splittypes or\n len(components) == 3 and not components[2] in classnames):\n raise ValueError('Unrecognized \\'split\\' value \\'%s\\'' % split)\n\n if(len(components) == 2):\n lists = [components + ['same'], components + ['diff']]\n else:\n lists = [components]\n\n out = {}\n for l in lists:\n with open('%s/%s.txt' % (lists_path, '_'.join(l)), 'r') as f:\n for line in f.read().strip().split('\\n'):\n files = map(lambda x: '%s/%s.ppm' % (faces_path, x),\n line.strip(' ').split())\n out[tuple(files)] = {'class' : l[-1]}\n return out\n\n\ndef get_unique_lfw_training_images():\n train_data = get_lfw_cropped_data('01_train')\n test_data = get_lfw_cropped_data('01_test')\n # combine train and test folds to use all folds for training\n train_data.update(test_data)\n # get a list of unique training images\n train_fns = []\n for fnpair in train_data.keys():\n train_fns.extend(fnpair)\n train_fns = sorted(set(train_fns))\n return train_fns\n\n\ndef train(training_fns, pickle_fn, max_train_ims=3000):\n # load the unique training images, and learn PCA\n print('Training Eigenfaces feature space (%i training images)...' % (\n len(training_fns)))\n if len(training_fns) <= max_train_ims:\n train_ims = [cv.LoadImage(fn) for fn in training_fns]\n else:\n train_ims = [cv.LoadImage(fn)\n for fn in random.sample(training_fns, max_train_ims)]\n feat = face_feature.Eigenfaces(train_ims)\n with open(pickle_fn, 'w') as fp:\n cPickle.dump(feat, fp)\n\n\nif __name__ == '__main__':\n pickle_fn = 'eigenfaces_lfw_cropped.pkl'\n training_fns = get_unique_lfw_training_images()\n train(training_fns, pickle_fn)\n","sub_path":"face_feature/eigenfaces_train.py","file_name":"eigenfaces_train.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"373024174","text":"import pygame\r\nimport sys\r\nfrom pygame.locals import *\r\n\r\n\r\n# alustaa pugamen\r\npygame.init()\r\n\r\nkoko = (400,600) # eka on leveys ja toka korkeus\r\nruutu = pygame.display.set_mode(koko)\r\n\r\ntaustavari = (0, 255, 4)\r\npallovari = (255, 0, 0)\r\n#käsittelee tapahtumia\r\ndef FARD():\r\n tapahtumat = pygame.event.get()\r\n for tapahtuma in tapahtumat:\r\n if tapahtuma.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n\r\n\r\n#piirtää\r\ndef MONKE():\r\n napit = pygame.mouse.get_pressed()\r\n if napit[0]:\r\n ruutu.fill(taustavari)\r\n keskipiste = pygame.mouse.get_pos()\r\n koko2 = (15,10)\r\n pygame.draw.circle(ruutu, pallovari, keskipiste, 30)\r\n #pygame.draw.rect(ruutu, pallovari, keskipiste+koko2)\r\n\r\n#pelin silmukka\r\nwhile True:\r\n FARD()\r\n MONKE()\r\n pygame.display.flip()","sub_path":"kakka.py","file_name":"kakka.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"145096288","text":"def gematria():\n words = []\n b, count = ord('A'), 0\n while True:\n string = input()\n if string == '':\n break\n words.insert(count, string)\n count += 1\n return sorted(words, key=lambda word: sum([(ord(i) - ord('A') + 1) for i in word.upper()]))\n\n\n# print(*gematria(), sep='\\n')\n","sub_path":"24/24.2.py","file_name":"24.2.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"396194890","text":"#!/usr/bin/env python\n\nfrom fiona.crs import from_epsg\nimport geopandas as gpd\nfrom shapely.geometry import Point\nfrom glob import glob\nimport matplotlib.pyplot as plt\n\ndef map_format(ax, on = False):\n\n plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)\n plt.margins(0,0)\n ax.xaxis.set_major_locator(plt.NullLocator())\n ax.yaxis.set_major_locator(plt.NullLocator())\n\n if not on:\n ax.set_axis_off()\n ax.set_axis_on()\n for a in [\"bottom\", \"top\", \"right\", \"left\"]:\n ax.spines[a].set_linewidth(0)\n\n return ax\n\n\ndef make_pa_pittsburgh(f, e = 3364):\n\n gdf = gpd.read_file(f).to_crs(epsg = e)\n pittsburgh = gpd.GeoDataFrame(crs = from_epsg(4326), geometry = [Point(-79.9959, 40.4406)]).to_crs(epsg = 3364)\n\n ax = gdf.plot(column = \"id\", cmap = \"nipy_spectral\", alpha = 0.4, figsize = (4, 4))\n gdf.plot(color = \"none\", alpha = 1, edgecolor = \"k\", linewidth = 0.8, ax = ax)\n\n pittsburgh.plot(facecolor = \"none\", edgecolor = \"k\", markersize = 410, ax = ax)\n pittsburgh.plot(facecolor = \"none\", edgecolor = \"k\", markersize = 490, ax = ax)\n pittsburgh.plot(facecolor = \"none\", edgecolor = \"w\", markersize = 450, ax = ax)\n\n ax.set_xlim(290000, 900000)\n map_format(ax)\n\n # ax.figure.savefig(\"paper_figs/pa_ex/\" + f.split(\"/\")[-1].replace(\"geojson\", \"pdf\"))\n ax.figure.savefig(\"paper_figs/pa_ex/\" + f.split(\"/\")[-1].replace(\"geojson\", \"png\"))\n\n plt.close(\"all\")\n\n\nfor fm in glob(\"data/pa_ex/*.geojson\"):\n make_pa_pittsburgh(fm)\n\n","sub_path":"geomap.py","file_name":"geomap.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"430984089","text":"# -*- coding: utf-8 -*-\nfrom PyQt4 import QtCore, QtGui\nimport sys\n\ndef on_clicked():\n (font, ok) = QtGui.QFontDialog.getFont(QtGui.QFont(\"Tahoma\", 16),\n window, \"Заголовок окна\")\n if ok:\n print(font.family(), font.pointSize(), font.weight(),\n font.italic(), font.underline())\n\napp = QtGui.QApplication(sys.argv)\nwindow = QtGui.QWidget()\nwindow.setWindowTitle(\"Класс QFontDialog\")\nwindow.resize(300, 70)\n\nbutton = QtGui.QPushButton(\"Отобразить диалоговое окно...\")\nbutton.clicked.connect(on_clicked)\n\nbox = QtGui.QVBoxLayout()\nbox.addWidget(button)\nwindow.setLayout(box)\nwindow.show()\n\nsys.exit(app.exec_())","sub_path":"140_gui/pyqt_pyside/examples/PyQt_PySide_book/008_dialogs windows/007_The window to select a font/710_getFont.py","file_name":"710_getFont.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"57575695","text":"from tensorflow import keras \nimport numpy as np \nimport rssi_data as data\nimport tensorflow as tf \nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras import regularizers\nfrom keras.datasets import mnist\n# from keras import backend as K\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\n\nx,y = data.read_datasets()\ntrain_val_split = int(0.7 * len(x)) # mask index array\nx_train = np.array(x[:train_val_split])\ny_train = np.array(y[:train_val_split])\nx_val = np.array(x[train_val_split:])\ny_val = np.array(y[train_val_split:])\n\n\n# print(\"data shapes:\")\n# print(x.shape)\n# print(y.shape)\n# print(\"train shapes:\")\n# print(x_train.shape)\n# print(y_train.shape)\n\n# model = keras.Sequential()\n# model.add(keras.layers.Dense(256, activation='relu', input_shape=(520,)))\n# model.add(keras.layers.Dropout(0.2))\n# model.add(keras.layers.Dense(128, activation='relu'))\n# model.add(keras.layers.Dropout(0.2))\n# model.add(keras.layers.Dense(118, activation='sigmoid'))\n\n\n\n# model.compile(optimizer=tf.train.AdamOptimizer(),\n# loss='binary_crossentropy',\n# metrics=['accuracy'])\n\n# model.fit(x_train, y_train, epochs=20)\n\n# test_loss, test_acc = model.evaluate(x_val,y_val)\n\n# print('Test accuracy:', test_acc)\n\n# predictions = model.predict(x_val)\n\n# diff_building = 0\n# diff_floor = 0\n# diff_place = 0\n\n# for i in range(1,len(x_val)):\n# sub1 = np.argmax(predictions[-i][:3])\n# sub2 = np.argmax(predictions[-i][3:8])\n# sub3 = np.argmax(predictions[-i][8:118])\n\n# sub4 = np.argmax(y_val[-i][:3])\n# sub5 = np.argmax(y_val[-i][3:8])\n# sub6 = np.argmax(y_val[-i][8:118])\n\n# if (sub1 != sub4):\n# diff_building += 1\n# else:\n# if (sub2 != sub5):\n# diff_floor += 1\n# else:\n# if (sub3 != sub6):\n# diff_place += 1\n\n# s = len(x_val)\n# a1 = 100 * (s - diff_building) / s\n# a2 = 100 * (s - diff_floor) / s\n# a3 = 100 * (s - diff_place) / s\n\n# print(\"For \",s,\" test data:\")\n# print(\"building accuracy: \", a1,\"%\")\n# print(\"building + floor prediction accuracy: \", a2,\"%\")\n# print(\"building + floor + place accuracy: \", a3,\"%\")\n\n\n# Single fully-connected neural layer as encoder and decoder\n\nuse_regularizer = False\nmy_regularizer = None\nmy_epochs = 20\nfeatures_path = 'simple_autoe_features.pickle'\nlabels_path = 'simple_autoe_labels.pickle'\n\nif use_regularizer:\n # add a sparsity constraint on the encoded representations\n # note use of 10e-5 leads to blurred results\n my_regularizer = regularizers.l1(10e-8)\n # and a larger number of epochs as the added regularization the model\n # is less likely to overfit and can be trained longer\n my_epochs = 20\n features_path = 'sparse_autoe_features.pickle'\n labels_path = 'sparse_autoe_labels.pickle'\n\n# this is the size of our encoded representations\nencoding_dim = 256 # 32 floats -> compression factor 24.5, assuming the input is 784 floats\n\n# this is our input placeholder; \ninput_img = Input(shape=(520, ))\n\n# \"encoded\" is the encoded representation of the inputs\nencoded = Dense(encoding_dim, activation='relu', activity_regularizer=my_regularizer)(input_img)\n\n# \"decoded\" is the lossy reconstruction of the input\ndecoded = Dense(520, activation='sigmoid')(encoded)\n\n# this model maps an input to its reconstruction\nautoencoder = Model(input_img, decoded)\n\n# Separate Encoder model\n\n# this model maps an input to its encoded representation\nencoder = Model(input_img, encoded)\n\n# Separate Decoder model\n\n# create a placeholder for an encoded (32-dimensional) input\nencoded_input = Input(shape=(encoding_dim,))\n# retrieve the last layer of the autoencoder model\ndecoder_layer = autoencoder.layers[-1]\n# create the decoder model\ndecoder = Model(encoded_input, decoder_layer(encoded_input))\n\n# Train to reconstruct MNIST digits\n\n# configure model to use a per-pixel binary crossentropy loss, and the Adadelta optimizer\nautoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\n\n# prepare input data\nx_test = x_val\n\n# normalize all values between 0 and 1 and flatten the 28x28 images into vectors of size 784\nprint(x_train.shape)\nprint(x_test.shape)\n\n# Train autoencoder for 50 epochs\n\nautoencoder.fit(x_train, x_train, epochs=my_epochs, batch_size=256, shuffle=True, validation_data=(x_test, x_test),\n verbose=2)\n\n# after 50/100 epochs the autoencoder seems to reach a stable train/test lost value\n\n# Visualize the reconstructed encoded representations\n\n# encode and decode some digits\n# note that we take them from the *test* set\nencoded_imgs = encoder.predict(x_test)\nprint(encoded_imgs.shape)\ndecoded_imgs = decoder.predict(encoded_imgs)\n\n# # save latent space features 32-d vector\n# pickle.dump(encoded_imgs, open(features_path, 'wb'))\n# pickle.dump(y_test, open(labels_path, 'wb'))\n\n# n = 10 # how many digits we will display\n# plt.figure(figsize=(10, 2), dpi=100)\n# for i in range(n):\n# # display original\n# ax = plt.subplot(2, n, i + 1)\n# plt.imshow(x_test[i].reshape(28, 28))\n# plt.gray()\n# ax.set_axis_off()\n\n# # display reconstruction\n# ax = plt.subplot(2, n, i + n + 1)\n# plt.imshow(decoded_imgs[i].reshape(28, 28))\n# plt.gray()\n# ax.set_axis_off()\n\n# plt.show()\n\nx_train_compressed = encoder.predict(x_train)\nx_val_compressed = encoder.predict(x_val)\nprint(x_train_compressed.shape)\nprint(x_val_compressed.shape)\nprint(x_train_compressed[0])\nprint(type(x_train_compressed))\n\n\nmodel = keras.Sequential()\nmodel.add(keras.layers.Dense(256, activation='relu', input_shape=(256,)))\nmodel.add(keras.layers.Dropout(0.2))\nmodel.add(keras.layers.Dense(128, activation='relu'))\nmodel.add(keras.layers.Dropout(0.2))\nmodel.add(keras.layers.Dense(118, activation='sigmoid'))\n\n# x_train_compressed = encoder.predict(x_train)\n# x_val_compressed = encoder.predict(x_val)\n\nmodel.compile(optimizer=tf.train.AdamOptimizer(),\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\nmodel.fit(x_train_compressed, y_train, epochs=20)\n\ntest_loss, test_acc = model.evaluate(x_val_compressed,y_val)\n\nprint('Test accuracy:', test_acc)\n\npredictions = model.predict(x_val_compressed)\n\ndiff_building = 0\ndiff_floor = 0\ndiff_place = 0\n\nfor i in range(1,len(x_val)):\n sub1 = np.argmax(predictions[-i][:3])\n sub2 = np.argmax(predictions[-i][3:8])\n sub3 = np.argmax(predictions[-i][8:118])\n\n sub4 = np.argmax(y_val[-i][:3])\n sub5 = np.argmax(y_val[-i][3:8])\n sub6 = np.argmax(y_val[-i][8:118])\n\n if (sub1 != sub4):\n diff_building += 1\n else:\n if (sub2 != sub5):\n diff_floor += 1\n else:\n if (sub3 != sub6):\n diff_place += 1\n\ns = len(x_val)\na1 = 100 * (s - diff_building) / s\na2 = 100 * (s - diff_floor) / s\na3 = 100 * (s - diff_place) / s\n\nprint(\"For \",s,\" test data:\")\nprint(\"building accuracy: \", a1,\"%\")\nprint(\"building + floor prediction accuracy: \", a2,\"%\")\nprint(\"building + floor + place accuracy: \", a3,\"%\")\n# K.clear_session()","sub_path":"Stage4/rssi_ae_dnn_comp.py","file_name":"rssi_ae_dnn_comp.py","file_ext":"py","file_size_in_byte":6998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"309634144","text":"from collections import Counter\n\nclass Fabric:\n def __init__(self, line='#123 @ 3,2: 5x4\\n'):\n if line is not None:\n line = line.split(' ')\n self.claim_no = int(line[0][1:])\n self.top_left = list(map(int, line[2][:-1].split(',')))\n width, height = list(map(int, line[3].split('x')))\n self.width = width\n self.height = height\n cs = []\n for i in range(self.top_left[0], self.top_left[0] + width):\n for j in range(self.top_left[1], self.top_left[1] + height):\n cs.append((i, j))\n self.coordinates = set(cs)\n else:\n self.claim_no = None\n self.top_left = None\n self.width = None\n self.height = None\n \n def __str__(self):\n return (f'C: {self.claim_no} TL: {self.top_left} ' + \n f'W: {self.width} H: {self.height} CS: {list(sorted(self.coordinates))}')\n \n def __and__(self, other):\n f = Fabric(None)\n f.coordinates = self.coordinates & other.coordinates\n return f\n \n def __or__(self, other):\n f = Fabric(None)\n f.coordinates = self.coordinates | other.coordinates\n return f\n\nwith open(\"input.txt\", \"r\") as f:\n lines = f.readlines()\n fabrics = []\n for line in lines:\n fabrics.append(Fabric(line))\n \n for i in range(len(fabrics)):\n this = set()\n for j in range(len(fabrics)):\n if i != j:\n this |= (fabrics[i] & fabrics[j]).coordinates\n if len(this) == 0:\n print(fabrics[i])\n# 560","sub_path":"2018/day3/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"102953811","text":"from django.contrib import admin\nfrom django.urls import path,include\nfrom rest_framework import permissions\nfrom drf_yasg.views import get_schema_view\nfrom drf_yasg import openapi\n\n\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"Pizza Delivery API\",\n default_version='v1',\n description=\"A REST API for a Pizza delivery service\",\n contact=openapi.Contact(email=\"admin@app.com\"),\n ),\n public=True,\n permission_classes=(permissions.AllowAny,),\n)\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('auth/',include('authentication.urls')),\n path('orders/',include('orders.urls')),\n path('auth/', include('djoser.urls.jwt')),\n path('swagger.json|.yaml)', schema_view.without_ui(cache_timeout=0), name='schema-json'),\n path('docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),\n path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),\n]\n","sub_path":"pizza/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"228242396","text":"import Sensor\n\nWaterThreshold = 60\nLuminosityThreshold = 900\nTempertureMinRelax = 15\nTempertureMaxRelax = 30\n\n\nclass Plant:\n def __init__(\n self,\n display_name,\n name,\n sensor_buffer,\n speech_center,\n water_threshold=WaterThreshold,\n luminosity_threshold=LuminosityThreshold,\n temperture_min_relax=TempertureMinRelax,\n temperture_max_relax=TempertureMaxRelax,\n ):\n self.display_name = display_name\n self.name = name\n self.__sensor_buf = sensor_buffer\n self.__speech_center = speech_center\n self.water_threshold = water_threshold\n self.luminosity_threshold = luminosity_threshold\n self.temperture_min_relax = temperture_min_relax\n self.temperture_max_relax = temperture_max_relax\n self.push_message = None\n\n self.__sensor_buf.start(Sensor.loop)\n\n def update(self):\n return None\n\n # Lineに出力すべきテキストを生成します\n def chat(self, text):\n return self.__speech_center.make_response(self, user_text=text)\n\n # 初回生成時の挨拶を返します\n def say_nice_to_meet_you(self):\n return self.__speech_center.say_nice_to_meet_you(self)\n\n # 呼び出し時の挨拶を生成します\n def say_hello(self):\n return self.__speech_center.say_hello(self)\n\n # 別れの挨拶を生成します\n def say_see_you(self):\n return self.__speech_center.respond_see_you(self)\n\n # 天気予報のメッセージをプッシュします\n def report_weather_forecast(self, postal_code):\n self.push_message(\n self.__speech_center.report_weather_forecast(postal_code))\n\n\n def sense_condition(self):\n \"\"\"新しいセンサ値を取得します\"\"\"\n self.__sensor_buf.get_current_condition()\n\n def needWater(self):\n hum, _ = self.__sensor_buf.get_current_condition(False)\n print(\"hum %d\" % hum)\n return hum >= self.water_threshold\n\n def needLuminesity(self):\n _, lum = self.__sensor_buf.get_current_condition(False)\n print(\"lum %d\" % lum)\n return lum < self.luminosity_threshold\n\n # センサーバッファのfetchspanを書き換えます\n def set_beacon_buf_span(self, check_beacon_eco_time):\n if check_beacon_eco_time:\n self.__sensor_buf.fetch_span = self.__sensor_buf.ECO_FETCH_SPAN\n else:\n self.__sensor_buf.fetch_span = self.__sensor_buf.DEFAULT_FETCH_SPAN\n","sub_path":"whisper/Plant.py","file_name":"Plant.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"595639913","text":"#!/usr/bin/env python\n# This programs deals with a single event.\n# John Vidale 2/2019, still modifying 2/2021\n\nimport os\n\nos.environ['PATH'] += os.pathsep + '/usr/local/bin'\nos.chdir('/Users/vidale/Documents/GitHub/Array_codes')\n\n#%% Import functions\nfrom pro3b_sort_plot_singlet import pro3singlet\nfrom pro5a_stack import pro5stack\nfrom pro5b_stack2d import pro5stack2d\nfrom pro6_singlet import pro6_singlet\nfrom pro7_singlet import pro7_singlet\n\n#%% Workflow selection\n\ndo_3a = False # single event\ndo_5a = False # stack\ndo_6a = False # treats single events, no time shifts calculated or plotted\ndo_7a = True\neq_num = 91 # index on location file\n\n#%% Common parameters\nARRAY = 1\nauto_dist = True\nmin_dist = 0\nmax_dist = 180\n\n# P\n# start_buff = 600\n# end_buff = 2500\nstart_buff = 1350\nend_buff = 1450\n# start_buff = 1550\n# end_buff = 1750\n\n# HF\nfreq_min = 1\nfreq_max = 3\n\n# Pro5 stacking\nstat_corr = 1\ndecimate_fac = 5 # set for pro5stack2d for single event envelopes, set to 0 for other codes\nsimple_taper = 1\nmax_taper_length = 5. # taper is minimum of taper_frac (0.05) and this number of seconds\nskip_SNR = 1\nref_phase = 'PKiKP'\nslowR_lo = -0.1\nslowR_hi = 0.1\nslowT_lo = -0.1\nslowT_hi = 0.1\nslow_delta = 0.0025\nNS = True # 1 for N-S co=ords, 0 for R-T\n\n# Pro5 1D plot options\nslowR_lo_1D = -0.04\nslowR_hi_1D = 0.1\nslow_delta_1D = 0.001\n\n# Pro6 options: mostly time shift measurement\ncc_twin = 3 # time window for cross-correlation (s)\ncc_len = 0.2 # max time window shift to compute CC (fraction of whole time window)\ncc_delta = 0.4 # time interval for cc (s)\ncc_interp1d = 5 # interpolation factor\ncc_thres = 0.5 # threshold beam correlation to use in stack\n\n# Pro 7 range selection options\nzoom = False # to restrict time range and slowness range in pro7_pair_scan\nZslowR_lo = -0.06\nZslowR_hi = 0.06\nZslowT_lo = -0.06\nZslowT_hi = 0.06\nZstart_buff = 1000\nZend_buff = 1250\nstart_beam = 0 # Limit time window for summary slowness beam in beam sums\nend_beam = 0 # better be within Zstart and Zend, if zoom is set\nmin_amp = 0.0 # threshold amp to use in stack\n\n# Pro 7 auto_slice == True options\nauto_slice = True # slices span wide range of R and T slownesses\ntwo_slice_plots = True # makes R-T pair and snap through time span\nbeam_sums = True # sums tdiff and amp over time\nwiggly_plots = False # shows wiggly plots\n\n# Pro7 auto-plot options\nnR_plots = 1 # number of plots along the radial axis, makes (2 x nR_plots - 1) total\nnT_plots = 1 # number of plots along the transv axis\nslow_incr = 0.06 # increment at which amp and tdiff are plotted\n\n# Pro7 two_slice and snap options\nR_slow_plot = 0.010\nT_slow_plot = 0.000\nsnaptime = 1350\nsnaps = 10\nsnap_depth = 10 # time window over which snap is integrated, 0 is one time point\n\n# Pro 7 more plotting options\ndo_T = False # present T plots\ndo_R = True # present R plots\nno_tdiff_plot = True # also to speed plots of only amplitude\nlog_plot = False\ntdiff_clip = 0.15\nwig_scale_fac = 0.5\ntdiff_scale_fac = 1\nlog_plot_range = 1.5\nplot_scale_fac = 1\n\n#%% Individual event\n#%% -- Cull seismic section event\nif do_3a == True:\n pro3singlet(ARRAY = ARRAY, stat_corr = stat_corr, eq_num = eq_num,\n max_taper_length = max_taper_length, simple_taper = simple_taper,\n rel_time = 0, start_buff = start_buff, end_buff = end_buff,\n plot_scale_fac = 0.1, skip_SNR = 1,\n dphase = ref_phase, dphase2 = 'SKKP', dphase3 = 'PKPPcP', dphase4 = 'pPKIKKIKP',\n freq_min = freq_min, freq_max = freq_max,\n ref_loc = 0, fig_index = 101, min_dist = min_dist, max_dist = max_dist, auto_dist = auto_dist)\n#%% -- 1D stack\n# if do_5 == True:\n# pro5stack(ARRAY = ARRAY, eq_num = eq_num, plot_scale_fac = 0.05,\n# slowR_lo = slowR_lo_1D, slowR_hi = slowR_hi_1D, slow_delta = slow_delta_1D,\n# start_buff = start_buff, end_buff = end_buff,\n# log_plot = 0, envelope = 1, plot_dyn_range = 50,\n# norm = 1, global_norm_plot = 1, color_plot = 1, fig_index = 301)\n\n#%% -- 2D stack\nif do_5a == True:\n pro5stack2d(eq_num = eq_num, slowR_lo = slowR_lo, slowR_hi = slowR_hi, slowT_lo = slowT_lo,\n slowT_hi = slowT_hi, slow_delta = slow_delta,\n start_buff = start_buff, end_buff = end_buff, norm = 1,\n ARRAY = ARRAY, decimate_fac = decimate_fac, NS = NS)\n\n#%% just amp, no time shifts estimates\nif do_6a == True:\n pro6_singlet(eq_num = eq_num, slowR_lo = slowR_lo, slowR_hi = slowR_hi,\n slowT_lo = slowT_lo, slowT_hi = slowT_hi, slow_delta = slow_delta,\n start_buff = start_buff, end_buff = end_buff, cc_delta = cc_delta)\n\n#%% -- Make a variety of plots\nif do_7a == True:\n pro7_singlet(eq_num = eq_num, wig_scale_fac = wig_scale_fac,\n slowR_lo = slowR_lo, slowR_hi = slowR_hi, slowT_lo = slowT_lo, slowT_hi = slowT_hi, slow_delta = slow_delta,\n zoom = zoom, ZslowR_lo = ZslowR_lo, ZslowR_hi = ZslowR_hi, ZslowT_lo = ZslowT_lo,\n ZslowT_hi = ZslowT_hi, Zstart_buff = Zstart_buff, Zend_buff = Zend_buff,\n start_buff = start_buff, end_buff = end_buff, do_T = do_T, do_R = do_R,\n min_amp = min_amp, ref_phase = ref_phase,\n R_slow_plot = R_slow_plot, T_slow_plot = T_slow_plot,\n snaptime = snaptime, snaps = snaps, snap_depth =snap_depth,\n nR_plots = nR_plots, nT_plots = nT_plots, slow_incr = slow_incr, NS = NS,\n ARRAY = ARRAY, auto_slice = auto_slice, two_slice_plots = two_slice_plots, beam_sums = beam_sums,\n wiggly_plots = wiggly_plots, log_plot = log_plot, log_plot_range = log_plot_range,\n start_beam = start_beam, end_beam = end_beam)\n\nos.system('say \"All Done\"')","sub_path":"Run_Japan/Examples/run_individual_freestanding.py","file_name":"run_individual_freestanding.py","file_ext":"py","file_size_in_byte":6039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"372760404","text":"def solve_puzzle(clues):\n table = [[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]\n rc = reorder_clue(clues)\n print(rc)\n start0(table, clues)\n # insert_for_4(table, clues)\n # insert_for_1(table, clues)\n\n sets = create_sets()\n answer = recursive(table, rc, sets)\n\n # Make list to tuple\n return answer\n\n\ndef start0(table, clues):\n for idx, clue in enumerate(clues):\n if idx < 4 and clue > 0:\n table[0][idx] = 0\n table[1][idx] = 0\n table[2][idx] = 0\n table[3][idx] = 0\n elif idx < 8 and clue > 0:\n table[idx % 4][0] = 0\n table[idx % 4][1] = 0\n table[idx % 4][2] = 0\n table[idx % 4][3] = 0\n elif idx < 12 and clue > 0:\n table[0][3 - idx % 4] = 0\n table[1][3 - idx % 4] = 0\n table[2][3 - idx % 4] = 0\n table[3][3 - idx % 4] = 0\n elif clue > 0:\n table[3 - idx % 4][0] = 0\n table[3 - idx % 4][1] = 0\n table[3 - idx % 4][2] = 0\n table[3 - idx % 4][3] = 0\n\n\n# def insert_for_4(table, clues):\n# for idx, clue in enumerate(clues):\n# if idx < 4 and clue == 4:\n# table[0][idx] = 1\n# table[1][idx] = 2\n# table[2][idx] = 3\n# table[3][idx] = 4\n# elif idx < 8 and clue == 4:\n# table[idx % 4][0] = 4\n# table[idx % 4][1] = 3\n# table[idx % 4][2] = 2\n# table[idx % 4][3] = 1\n# elif idx < 12 and clue == 4:\n# table[0][3 - idx % 4] = 4\n# table[1][3 - idx % 4] = 3\n# table[2][3 - idx % 4] = 2\n# table[3][3 - idx % 4] = 1\n# elif clue == 4:\n# table[3 - idx % 4][0] = 1\n# table[3 - idx % 4][1] = 2\n# table[3 - idx % 4][2] = 3\n# table[3 - idx % 4][3] = 4\n#\n#\n# def insert_for_1(table, clues):\n# for idx, clue in enumerate(clues):\n# if idx < 4 and clue == 1:\n# table[0][idx] = 4\n# elif idx < 8 and clue == 1:\n# table[idx % 4][3] = 4\n# elif idx < 12 and clue == 1:\n# table[3][3 - idx % 4] = 4\n# elif clue == 1:\n# table[3 - idx % 4][0] = 4\n\n\ndef create_sets():\n set4 = [[1, 2, 3, 4]]\n set1 = [\n [4, 1, 2, 3],\n [4, 1, 3, 2],\n [4, 2, 3, 1],\n [4, 2, 1, 3],\n [4, 3, 1, 2],\n [4, 3, 2, 1],\n ]\n set2 = [\n [1, 4, 2, 3],\n [1, 4, 3, 2],\n [2, 1, 4, 3],\n [2, 4, 1, 3],\n [2, 4, 3, 1],\n [3, 1, 2, 4],\n [3, 1, 4, 2],\n [3, 2, 1, 4],\n [3, 2, 4, 1],\n [3, 4, 1, 2],\n [3, 4, 2, 1],\n ]\n set3 = [\n [1, 2, 4, 3],\n [1, 3, 2, 4],\n [1, 3, 4, 2],\n [2, 1, 3, 4],\n [2, 3, 1, 4],\n [2, 3, 4, 1],\n ]\n return [[], set1, set2, set3, set4]\n\ndef reorder_clue(clues):\n order = [4, 1, 3, 2]\n reorder = []\n for o in order:\n for idx, clue in enumerate(clues):\n if clue == o:\n reorder.append((idx, clue))\n return reorder\n\n\ndef recursive(table, rc, sets):\n count0 = sum(row.count(0) for row in table)\n if count0 == 0:\n return table\n\n \n\n# t = solve_puzzle(( 0, 0, 1, 2,\n# 0, 2, 0, 0,\n# 0, 3, 0, 0,\n# 0, 1, 0, 0 ))\nt = solve_puzzle(( 2, 2, 1, 3,\n 2, 2, 3, 1,\n 1, 2, 2, 3,\n 3, 2, 1, 3 ))\nprint(t)\n","sub_path":"Codewars/4kyu/[undone]skyscraper4x4.py","file_name":"[undone]skyscraper4x4.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"417053463","text":"from flask import Flask, flash, redirect, render_template, request, session, abort,jsonify\r\napp = Flask(__name__,static_url_path='/static')\r\n\r\n@app.route(\"/\")\r\ndef charMap():\r\n return render_template(\r\n 'index.html')\r\n@app.route('/charMap/',methods = ['POST'])\r\ndef checkOneToOneMapping():\r\n s1 = str(request.form.get('s1', ''))\r\n s2= str(request.form.get('s2', ''))\r\n #If the length of first string is not equal to the second string return false\r\n Answer = 'Yes'\r\n if len(s1) != len(s2):\r\n Answer = 'No'\r\n else:\r\n mapDict ={}\r\n for i in range(0,len(s1)):\r\n #checking if the \r\n if s1[i] not in mapDict:\r\n mapDict[s1[i]] = s2[i]\r\n else:\r\n if mapDict[s1[i]] != s2[i]:\r\n Answer= 'No'\r\n data = {'answer' : Answer}\r\n data=jsonify(data)\r\n return data\r\n\r\nif __name__ == \"__main__\":\r\n app.run()\r\n","sub_path":"CharMapping/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"381918538","text":"import requests\nimport re\nimport os\nimport time\nfrom bs4 import BeautifulSoup\n\nRED = \"\\033[1;31m\" \nBLUE = \"\\033[1;34m\"\nCYAN = \"\\033[1;36m\"\nGREEN = \"\\033[0;32m\"\nRESET = \"\\033[0;0m\"\nBOLD = \"\\033[;1m\"\nREVERSE = \"\\033[;7m\"\n\n\ndef pegarUrl():\n while True:\n os.system('clear')\n var = input('Escolha uma das Opções de Busca no Workana abaixo: \\n\\nTI e Programação: \\n [1] - Programação \\n [2] - Web Design \\n [3] - Data Science \\n\\nDesign e Multimedia: \\n [4] - Web Design \\n [5] - Landing Page \\n\\n')\n\n if(var == '1'):\n var = 'https://www.workana.com/jobs?category=it-programming&language=pt&subcategory=web-development'\n break\n elif(var == '2'):\n var = 'https://www.workana.com/jobs?category=it-programming&language=pt&subcategory=web-design'\n break\n elif(var == '3'):\n var = 'https://www.workana.com/jobs?category=it-programming&language=pt&subcategory=data-science-1'\n break\n elif(var == '4'):\n var = 'https://www.workana.com/jobs?category=design-multimedia&language=pt&subcategory=web-design-1'\n break\n elif(var == '5'):\n var = 'https://www.workana.com/jobs?category=design-multimedia&language=pt&subcategory=landing-page'\n break\n else:\n print('\\nOpção Inválida!')\n time.sleep(1)\n\n return var\n\ndef listaTrabalhos(var):\n response = requests.get(var)\n site = BeautifulSoup(response.text, 'html.parser')\n trabalhos = site.findAll('div', attrs={'class': 'project-item'})\n\n os.system('clear')\n\n return trabalhos\n\ndef imprimirTrabalhos(trab):\n for trabalho in trab:\n titulo = trabalho.find('h2', attrs={'class': 'project-title'})\n horario = trabalho.find('span', attrs={'class': 'date'})\n autor = trabalho.find('span', attrs={'class': 'author-info'})\n detalhes = trabalho.find('div', attrs={'class': 'expander'})\n valor = trabalho.find('span', attrs={'class': 'values'})\n\n detalhes = detalhes.text\n\n perguntas = ['Categoria', 'Subcategoria', 'Do que você precisa',\n 'Isso é um projeto ou uma posição de trabalho', 'Disponibilidade requerida',\n 'Integrações de API', 'Necesidad específica', 'Necesidade específica',\n 'Funções necessárias', 'Tenho, atualmente', 'Qual é o alcance do projeto',\n 'Tamanho do projeto']\n\n detalhes = re.sub(perguntas[0], '\\n' + perguntas[0], detalhes)\n\n for i in range(0, len(perguntas)):\n detalhes = re.sub(perguntas[i], '\\n' + BOLD + perguntas[i] + GREEN, detalhes)\n\n print(RED + '========================================================================================' + RESET)\n print(BLUE + titulo.text + BOLD)\n print(BOLD + 'Valor: ' + GREEN + valor.text + RESET)\n print(horario.text)\n print(autor.text, '\\n' + CYAN)\n print(detalhes, '\\n\\n\\n' + RESET)\n\ndef buscarTrabalhos():\n while True:\n url = pegarUrl()\n trabalhos = listaTrabalhos(url)\n imprimirTrabalhos(trabalhos)\n\n cont = input('Pressione Enter para realizar uma nova busca. Caso contrário digite qualquer coisa\\n')\n if(cont == ''):\n cont = ''\n else:\n break\n\nif __name__ == '__main__':\n buscarTrabalhos()","sub_path":"busca_job_workana.py","file_name":"busca_job_workana.py","file_ext":"py","file_size_in_byte":3390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"47707860","text":"# -*- coding:UTF-8 -*-\r\nimport os\r\nimport numpy as np\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\n\r\npath = \"../data_gen_and_train/\"\r\npath = path + input(\"输入权重文件目录(如ckpt):\")\r\nfile_list = os.listdir(path)\r\n# print(file_list)\r\ntotal_loss_dict = []\r\nval_loss_dict = []\r\nfor file_str in file_list:\r\n str_list = file_str.strip(\".pth\").split(\"-\")\r\n epoch = int(str_list[0][5:])\r\n total_loss = float(str_list[1][10:])\r\n val_loss = float(str_list[2][8:])\r\n total_loss_dict.append([epoch, total_loss])\r\n val_loss_dict.append([epoch, val_loss])\r\n\r\n# 按照epoch排序\r\ntotal_loss_dict = np.array(sorted(total_loss_dict, key=lambda x:x[0]))\r\nval_loss_dict = np.array(sorted(val_loss_dict, key=lambda x:x[0]))\r\n# print(total_loss_dict)\r\n\r\nepoch = np.array(total_loss_dict[15:, 0], dtype=int)\r\ntotal_loss = total_loss_dict[15:, 1]\r\nval_loss = val_loss_dict[15:, 1]\r\n\r\n# 绘制\r\nplt.plot(epoch, total_loss, linewidth=2)\r\nplt.title(\"train loss\", fontsize=16)\r\nplt.xlabel(\"epoch\", fontsize=10)\r\nplt.ylabel(\"loss\", fontsize=10)\r\nplt.tick_params(axis='both', labelsize=10)\r\nplt.savefig(path+\"_train_loss.png\")\r\nplt.close('all')\r\n\r\nplt.figure()\r\nplt.plot(epoch, val_loss, linewidth=2)\r\nplt.title(\"val loss\", fontsize=16)\r\nplt.xlabel(\"epoch\", fontsize=10)\r\nplt.ylabel(\"loss\", fontsize=10)\r\nplt.tick_params(axis='both', labelsize=10)\r\nplt.savefig(path+\"_val_loss.png\")\r\nplt.close('all')\r\n","sub_path":"draw_loss/draw_loss.py","file_name":"draw_loss.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"532205312","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\nfrom django.contrib import admin\nadmin.autodiscover()\nfrom HomeworkManager.settings import TEMPLATE_DIRS\nfrom Manager import views\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'HomeworkManager.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^css/(?P.*)$','django.views.static.serve',\n {'document_root':TEMPLATE_DIRS[0]+'/dist/css'}),\n url(r'^js/(?P.*)$','django.views.static.serve',\n {'document_root':TEMPLATE_DIRS[0]+'/dist/js'}),\n url(r'^media/(?P.*)$','django.views.static.serve',\n {'document_root':settings.MEDIA_ROOT}),\n\n #url(r'^font/(?P.*)$','django.views.static.serve',\n #{'document_root':TEMPLATE_DIRS[0]+'/dist/css'}),\n url(r'^$',views.index),\n url(r'^login/$',views.login),\n url(r'^logout/$',views.logout),\n url(r'^t/$',views.index_teacher),\n url(r'^t/(\\d+)/addHW_teacher.html$',views.addHW_teacher),\n url(r'^t/shiyan/(\\d+).html$',views.shiyan_details_teacher),\n url(r'^t/shiyan/(\\d+)/alter$',views.alterHW_teacher),\n url(r'^t/shiyan/(\\d+)/manageShiyan_files.html$',views.manageShiyan_Files_teacher),\n url(r'^t/manageTeach_teacher.html$',views.manage_teach_teacher),\n url(r'^t/course/(\\d+)/studentlist.html$',views.studentlist_teacher),\n url(r'^t/course/(\\d+)$',views.course_details_teacher),\n url(r'^t/course/(\\d+)/delete',views.delete_course_teacher),\n url(r'^t/correctHW.html$',views.correctHW_teacher),\n url(r'^t/manageScore.html$',views.manageScore_teacher),\n url(r'^t/correctHW/download/([a-z]+)/(\\d+)',views.downloadHW_teacher),\n\n url(r'^s/$',views.index_student),\n url(r'^s/shiyan/(\\d+).html$',views.shiyan_details_student),\n url(r'^s/shiyan/(\\d+)/uploadhomework.html$',views.upload_homework_student),\n url(r'^s/All_HW_student.html$',views.all_HW_student),\n url(r'^s/others_student.html$',views.others_student),\n url(r'^a/$',views.submit_admin),\n url(r'^a/submit/$',views.submit_admin),\n)\n","sub_path":"HomeworkManager/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"290627130","text":"import sys\nimport re\nimport math\nimport time\n#this returns a non-unique ID. s is the string and n is the \nstart_time = time.time()\ndef col_index(s,n):\n\treturn hash(s)%n\n\ndef sigmoid(score):\n\toverflow = 20.0\n\tif score>overflow:\n\t\tscore = overflow\n\telif score < -overflow:\n\t\tscore = -overflow\n\texp = math.exp(score)\n\treturn exp/(1+exp)\n\ndef tokenizeDoc(cur_doc):\n return re.findall('\\\\w+', cur_doc)\n\ndef split_line(line):\n splits = line.split('\\t')\n labels = tokenizeDoc(splits[1])\n words = tokenizeDoc(splits[2])\n return labels, words\n\ndef make_empty_list(n):\n\tnum_labels = 5\n\tl = [0]*n\n\tfor i in range(n):\n\t\tl[i] = [0]*5\n\treturn l\n\ndef build_label_list(labels,cur_label_count,label_dictl,llist):\n\ta = []\n\tfor label in labels:\n\t\tif label not in label_dict:\n\t\t\tlabel_dict[label] = cur_label_count\n\t\t\tcur_label_count += 1\n\t\t\tllist.append(label)\n\t\ta.append(label_dict[label])\n\treturn cur_label_count, label_dict, llist\n\ndef labels_to_index(labels,label_dict):\n\tonehot = [0]*5\n\tfor label in labels:\n\t\tindex = int(label_dict[label])\n\t\tonehot[index] = 1\n\treturn onehot\n\ndef dot_product (keys,B,x):\n\ta = [0]*5\n\t#print len(keys)\n\tfor key in keys:\n\t\tfor yi, j in enumerate(B[key]):\n\t\t\tvalue = x[key]*j\n\t\t\ta[yi]=a[yi]+value\n\treturn a\n\ndef init_x(n):\n\tl = [0]*n\n\treturn l\n\n\nn = int(sys.argv[1])\ninit_l = float(sys.argv[2])\nmu = float(sys.argv[3])\nmax_iter = sys.argv[4]\ntrain_size = int(sys.argv[5])\ntest_file = sys.argv[6]\nlabel_dict = dict()\ncur_label_count = 0\nllist = []\nstopwords = ['a','the','of','be','to','and','in','that','have','it','for','not','on']\n\nk = 0.0\nA = make_empty_list(n)\nB = make_empty_list(n)\nfor i,curdoc in enumerate(sys.stdin):\n\t#create epochs\n\tepoch = i/train_size\n\tlam = init_l/((1+epoch)**2)\n\tx = dict()\n\tlabels,words = split_line(curdoc)\n\n\tfor word in stopwords:\n\t\ttry:\n\t\t\twords.remove(word)\n\t\texcept ValueError:\n\t\t\tpass\n\tif cur_label_count < 5:\n\t\tcur_label_count,label_dict,llist = build_label_list(labels,cur_label_count,label_dict,llist)\n\n\tl_index = labels_to_index(labels,label_dict)\n\tk = k+1\n\tkeys = []\n\tfor word in words:\n\t\tkey = col_index(word,n)\n\t\tx[key]= x.get(key,0.0)+1.0\n\t\tif key not in keys:\n\t\t\tkeys.append(key)\n\tdot = dot_product(keys,B,x)\n\tfor yi, label_i in enumerate(l_index):\n\t\tp = sigmoid(dot[yi])\n\t\tif (label_i-p)>0.5 or i%2 == 0:\n\t\t\tval1 = lam*(label_i-p)\n\t\t\tval2 = 1.0-2.0*lam*mu\n\t\t\tfor key in keys:\n\t\t\t\tif abs(B[key][yi]) > .7:\n\t\t\t\t\tB[key][yi]=B[key][yi]*(val2)**(k-A[key][yi])\n\t\t\t\tB[key][yi] = B[key][yi] + val1\n\t\t\t\tA[key][yi] = k\n\n#Test time!\n\nwith open(test_file) as f:\n\tcorrect = 0.0\n\ttotal = 0.0\n\tfor i,curdoc in enumerate(f):\n\t\tps = []\n\t\tfinal_string = ''\n\t\tx = [0]*n\n\t\t#populate x\n\t\tlabels,words = split_line(curdoc)\n\t\tkeys = []\n\t\t\n\t\tfor word in stopwords:\n\t\t\ttry:\n\t\t\t\twords.remove(word)\n\t\t\texcept ValueError:\n\t\t\t\tpass\n\n\t\tfor word in words:\n\t\t\tkey = col_index(word,n)\n\t\t\tx[key]+=1\n\t\t\tif key not in keys:\n\t\t\t\tkeys.append(key)\n\t\tdot = dot_product(keys,B,x)\n\t\tl_index = labels_to_index(labels,label_dict)\n\t\t\t\n\t\tfor yi, label in enumerate(llist):\n\n\t\t\tp = math.exp(dot[yi])/(1+math.exp(dot[yi]))\n\t\t\tps.append(p)\n\t\t\tfinal_string = final_string+label+'\\t'+str(p)+','\n\t\tprint(final_string[:-1])\n\t\tif llist[ps.index(max(ps))] in labels:\n\t\t\tcorrect +=1\n\t\ttotal+=1\nprint (correct/total)\nprint (time.time() - start_time)\n\n\t\t\n\n\n\n\n","sub_path":"MLLD/3/devLR.py","file_name":"devLR.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"94863816","text":"import math\nimport operator\nimport os\nimport os.path as path\n\n# parameters given to compute bm25 score\nk1 = 1.2\nb = 0.75\nk2 = 100\nN = 3204\nr = 0\nR = 0\n\nindex = {} # dict for storing the index\nK = {} # dicy for storing K value for each document\ndoc_length = {} # dict for storing number of terms in a document\n\n# search if a given document is present in the inverted list of given term\ndef search(key,value,lst):\n for i in range(len(lst)):\n if lst[i][key] == value:\n return i\n return -1\n\n\n# Use file generated from HW3 to build K and doc_length dicts\ndef populate_dicts():\n paths = os.path.abspath(os.path.join(os.getcwd(), \"../../\"))\n paths = os.path.join(paths, \"Step 2-Index Generation\")\n file = open(os.path.join(paths,\"Document_lengths.txt\"),'r',encoding='utf-8')\n content= file.read()\n content = content.split(\"\\n\")\n content = [c for c in content if c!=\"\"] #remove the last line\n\n sum_of_dls = 0\n for item in content:\n item = item.split(\" \")\n docid = item[0]\n dl = int(item[1])\n doc_length[docid] = dl\n sum_of_dls += dl\n # calculate average document length\n avgdl = sum_of_dls / N\n # calculate K for a document by the formula given\n for key,value in doc_length.items():\n ratio = value/avgdl\n K[key] = k1*((1-b) + (b*ratio))\n\n\n# calculate score for a single query\ndef calculate_score(output,query):\n query = query.split(\"||\") # separate query id and query\n qid = query[0]\n full_query = query[1]\n qterms = full_query.split(\" \") # collect all query terms in array\n\n qf = {} # dict for storing frequency of term in query\n # initialize qf dict\n for q in qterms:\n qf[q] = 0\n # populate qf dict\n for q in qterms:\n qf[q] += 1\n\n bm_score = {} # dict for storing the bm scores of each document\n for key,value in K.items(): # iterate over all documents\n score = 0\n for term in qterms: # iterate over all terms in query\n if term in index:\n inverted_list = index[term] # fetch inverted list of current term\n n = len(inverted_list)\n f = 0 # initialize tf in a document to 0\n doc_index = search('docid',key,index[term])\n # if current doc contains current term, update f with tf\n # from the index\n if doc_index != -1:\n f = index[term][doc_index]['tf']\n # calculate bm25 score by formula\n a = ((r+0.5)/(R-r+0.5))/((n-r+0.5)/(N-n-R+r+0.5))\n first = math.log(a)\n second = ((k1+1)*f)/(value+f)\n third = ((k2+1)*qf[term])/(k2+qf[term])\n score += first*second*third\n # if the doc doesnt contain any of the query term , do not consider adding it\n # into results\n if score!=0:\n bm_score[key] = score\n # sort the documents by bm25 scores\n bm_score = sorted(bm_score.items(), key=operator.itemgetter(1), reverse=True)\n\n # write results to query\n i=1\n output.write(\"\\n\\n\"+full_query+\"\\n\")\n for key,value in bm_score[:100]:\n output.write(\"\\n\"+qid+\" Q0 \"+key +\" \"+str(i)+\" \"+str(value)+\" BM25NoStopStem\")\n i+=1\n\n\n# creating inverted index into a dictionary\ndef create_index_dict():\n paths = os.path.abspath(os.path.join(os.getcwd(), \"../../\"))\n paths = os.path.join(paths, \"Step 2-Index Generation\")\n index_file = open(os.path.join(paths,\"Unigram_stemmed_index.txt\"),'r',encoding='utf-8')\n content = index_file.read()\n entries = content.split(\"\\n\")\n entries = [e for e in entries if e != \"\"] # remove the last line\n # building the index again from file\n for entry in entries:\n entry =entry.split(\" -> \")\n term = entry[0]\n postings = entry[1]\n index[term] = []\n # remove the formatting\n postings = postings.replace(\"(\",\"\").replace(\")\",\"\").split(\" \")\n for posting in postings:\n posting = posting.rsplit(\",\",1)\n docid = posting[0]\n tf = int(posting[1])\n index[term].append({'docid':docid,'tf':tf})\n\n index_file.close()\n\n\n# calculate scores for all the queries from cleanQueries.txt\ndef calculate_scores():\n # get all queries from file\n paths = os.path.abspath(os.path.join(os.getcwd(), \"../../\"))\n paths = os.path.join(paths, \"Step 3- Query Cleaning\")\n path = open(os.path.join(paths,\"cleanQueries.txt\"),'r',encoding='utf-8')\n content = path.read()\n path.close()\n queries = content.split(\"\\n\")\n queries = [q for q in queries if q!=\"\"]\n output = open(\"Stem_BM25Scores_NoRelevance.txt\",'w',encoding='utf=8')\n # loop over all the queries\n for query in queries:\n calculate_score(output,query)\n output.close()\n\n\nif __name__ == \"__main__\":\n create_index_dict() # retrieve index from file\n populate_dicts() # populate K and doc_length dicts\n calculate_scores()","sub_path":"Phase 1/Task 3/Task 3-B/Step 4 - Retrieval Models/BM25/bm25_NoRelevance.py","file_name":"bm25_NoRelevance.py","file_ext":"py","file_size_in_byte":4963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"42688325","text":"from tealight.art import (color, line, spot, circle, box, image, text, background)\nimport random\nrandom1 = [400,500,600,700,800]\nrandom2 = [-2,-1,0,1,2]\n\nm = []\nxp = []\nyp = []\nvx = []\nvy = []\nax = []\nay = []\n\nxp.append(500)\nyp.append(500)\nvx.append(0)\nvy.append(0)\nax.append(0)\nay.append(0)\nm.append(1200)\n\npower = 0.3\nplanets = 1\ngravity = 0.01\nminimum_distance = 30\nplanet_size = 2\n\ndef handle_keydown(key):\n \n if key == \"left\":\n ax[0] = -power\n elif key == \"right\":\n ax[0] = power\n elif key == \"up\":\n ay[0] = -power\n elif key == \"down\":\n ay[0] = power\n\ndef handle_keyup(key):\n global ax, ay\n\n if key == \"left\" or key == \"right\":\n ax[0] = 0\n elif key == \"up\" or key == \"down\":\n ay[0] = 0\n \ndef handle_frame():\n text(32,32,str(planets))\n for i in range(1,planets):\n for j in range(0,planets):\n if (i != j):\n x_distance = (xp[i]-xp[j])\n y_distance = (yp[i]-yp[j])\n if x_distance > -minimum_distance and x_distance < minimum_distance:\n if x_distance > 0:\n x_distance = minimum_distance\n else:\n x_distance = -minimum_distance\n if y_distance > -minimum_distance and y_distance < minimum_distance:\n if y_distance > 0:\n y_distance = minimum_distance\n else:\n y_distance = -minimum_distance\n total_distance = (x_distance**2 + y_distance**2)**(0.5)\n # changes it depending on positive or negative\n if x_distance > 0:\n ax[i] = ax[i] - m[i]*m[j]*gravity/total_distance/total_distance\n else:\n ax[i] = ax[i] + m[i]*m[j]*gravity/total_distance/total_distance\n \n if y_distance > 0:\n ay[i] = ay[i] - m[i]*m[j]*gravity/total_distance/total_distance\n else:\n ay[i] = ay[i] + m[i]*m[j]*gravity/total_distance/total_distance\n \n for i in range(0,planets):\n color(\"white\")\n \n spot(xp[i],yp[i],8*m[i]/800*planet_size)\n vx[i] = vx[i] + ax[i]\n vy[i] = vy[i] + ay[i]\n \n xp[i] = xp[i] + vx[i]\n yp[i] = yp[i] + vy[i]\n \n # resets the acceleration to 0\n ax[i] = 0\n ay[i] = 0\n \n color(\"blue\")\n spot(xp[i],yp[i],8*m[i]/800*planet_size)\n \n \n \ndef handle_mousedown(x,y):\n global lastx, lasty, vx, vy, ax, ay, random1, random2, planets\n \n xp.append(x)\n yp.append(y)\n vx.append(10)#random.choice(random2))\n vy.append(0)#random.choice(random2))\n ax.append(0)\n ay.append(0)\n m.append(random.choice(random1))\n planets = planets + 1\n ","sub_path":"art/orbits.py","file_name":"orbits.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"15760636","text":"#took help from geeksforgeeks\r\nclass repre: \r\n def __init__(self, x, y): \r\n self.x = x \r\n self.y = y \r\ndef Segon(p, q, r): \r\n if ((q.x <= max(p.x, r.x)) and (q.x >= min(p.x, r.x)) and \r\n (q.y <= max(p.y, r.y)) and (q.y >= min(p.y, r.y))): \r\n return True\r\n return False\r\n \r\ndef orient(p, q, r): \r\n ans =(float(q.y - p.y)*(r.x - q.x))-(float(q.x - p.x)*(r.y - q.y)) \r\n if ans>0: \r\n return 1\r\n elif ans<0: \r\n return -1\r\n else: \r\n return 0\r\n\r\ndef doint(p1,q1,p2,q2): \r\n o1 = orient(p1, q1, p2) \r\n o2 = orient(p1, q1, q2) \r\n o3 = orient(p2, q2, p1) \r\n o4 = orient(p2, q2, q1) \r\n if ((o1 != o2) and (o3 != o4)): \r\n return True\r\n elif ((o1 == 0) and Segon(p1, p2, q1)): \r\n return True\r\n elif ((o2 == 0) and Segon(p1, q2, q1)): \r\n return True\r\n elif ((o3 == 0) and Segon(p2, p1, q2)): \r\n return True\r\n elif ((o4 == 0) and Segon(p2, q1, q2)): \r\n return True\r\n return False\r\n \r\ndef line_intersection(line1, line2):\r\n xdiff = (line1[0][0] - line1[1][0], line2[0][0] - line2[1][0])\r\n ydiff = (line1[0][1] - line1[1][1], line2[0][1] - line2[1][1])\r\n def det(a, b):\r\n return a[0] * b[1] - a[1] * b[0]\r\n div = det(xdiff, ydiff)\r\n d = (det(*line1), det(*line2))\r\n x = det(d, xdiff) / div\r\n y = det(d, ydiff) / div\r\n return x, y\r\n\r\nfrom sys import *\r\ninp=stdin.readline\r\nout=stdout.write\r\nt=int(inp())\r\nwhile t>0:\r\n n,q=map(int,inp().split())\r\n al=list(map(int,inp().split()))\r\n list_of_points=[[i+1,al[i]]for i in range(n)]\r\n while q>0:\r\n count=0\r\n x1,x2,y=map(int,inp().split())\r\n p2=repre(x1,y)\r\n q2=repre(x2,y)\r\n C=(x1,y)\r\n D=(x2,y)\r\n prev=(0,0)\r\n for i in range(n-1):\r\n p1=repre(list_of_points[i][0],list_of_points[i][1])\r\n q1=repre(list_of_points[i+1][0],list_of_points[i+1][1])\r\n A=(list_of_points[i][0],list_of_points[i][1])\r\n B=(list_of_points[i+1][0],list_of_points[i+1][1])\r\n \r\n if doint(p1,q1,p2,q2):\r\n ans=line_intersection((A,B),(C,D))\r\n if ans==prev:\r\n pass\r\n else:\r\n prev=ans\r\n \r\n count+=1\r\n out(str(count)+\"\\n\")\r\n q-=1\r\n t-=1","sub_path":"tusshar_2000/MARCH20B/LAZER 30177959.py","file_name":"LAZER 30177959.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"600022255","text":"# Copyright 2018 99cloud, 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\nimport logging\n\nfrom sushy import exceptions\nfrom sushy.resources import base\nfrom sushy.resources import common\nfrom sushy import utils\n\nfrom rsd_lib import base as rsd_lib_base\nfrom rsd_lib.resources.v2_1.ethernet_switch import ethernet_switch_acl_rule\n\nLOG = logging.getLogger(__name__)\n\n\nclass BindActionField(common.ActionField):\n\n allowed_values = base.Field(\n \"Port@Redfish.AllowableValues\", adapter=utils.get_members_identities\n )\n\n\nclass UnbindActionField(common.ActionField):\n\n allowed_values = base.Field(\n \"Port@Redfish.AllowableValues\", adapter=utils.get_members_identities\n )\n\n\nclass EthernetSwitchACLActionsField(base.CompositeField):\n\n bind = BindActionField(\"#EthernetSwitchACL.Bind\")\n unbind = UnbindActionField(\"#EthernetSwitchACL.Unbind\")\n\n\nclass LinksField(base.CompositeField):\n\n bound_ports = base.Field(\n \"BoundPorts\", adapter=utils.get_members_identities\n )\n\n\nclass EthernetSwitchACL(rsd_lib_base.ResourceBase):\n \"\"\"EthernetSwitchACL resource class\n\n A Ethernet Switch ACL represents Access Control List for switch.\n \"\"\"\n\n links = LinksField(\"Links\")\n\n _actions = EthernetSwitchACLActionsField(\"Actions\")\n\n def _get_bind_action_element(self):\n bind_action = self._actions.bind\n if not bind_action:\n raise exceptions.MissingActionError(\n action=\"#EthernetSwitchACL.Bind\", resource=self._path\n )\n return bind_action\n\n def get_allowed_bind_ports(self):\n \"\"\"Get the allowed ports for bind action.\n\n :returns: A set with the allowed bind ports.\n \"\"\"\n bind_action = self._get_bind_action_element()\n return bind_action.allowed_values\n\n def bind_port(self, port):\n \"\"\"Bind port from this switch ACL\n\n :param port: Link to port to bind.\n :raises: InvalidParameterValueError\n \"\"\"\n bind_action = self._get_bind_action_element()\n valid_ports = bind_action.allowed_values\n target_uri = bind_action.target_uri\n\n if port and port not in valid_ports:\n raise exceptions.InvalidParameterValueError(\n parameter=\"port\", value=port, valid_values=valid_ports\n )\n\n data = {\"Port\": {\"@odata.id\": port}}\n\n self._conn.post(target_uri, data=data)\n\n def _get_unbind_action_element(self):\n unbind_action = self._actions.unbind\n if not unbind_action:\n raise exceptions.MissingActionError(\n action=\"#EthernetSwitchACL.Unbind\", resource=self._path\n )\n return unbind_action\n\n def get_allowed_unbind_ports(self):\n \"\"\"Get the allowed ports for unbind action.\n\n :returns: A set with the allowed unbind ports.\n \"\"\"\n unbind_action = self._get_unbind_action_element()\n return unbind_action.allowed_values\n\n def unbind_port(self, port):\n \"\"\"Unbind port from this switch ACL\n\n :param port: Link to port to unbind.\n :raises: InvalidParameterValueError\n \"\"\"\n unbind_action = self._get_unbind_action_element()\n valid_ports = unbind_action.allowed_values\n target_uri = unbind_action.target_uri\n\n if port and port not in valid_ports:\n raise exceptions.InvalidParameterValueError(\n parameter=\"port\", value=port, valid_values=valid_ports\n )\n\n data = {\"Port\": {\"@odata.id\": port}}\n\n self._conn.post(target_uri, data=data)\n\n def delete(self):\n \"\"\"Delete this ACL\"\"\"\n self._conn.delete(self._path)\n\n @property\n @utils.cache_it\n def rules(self):\n \"\"\"Property to provide reference to `EthernetSwitchACLRuleCollection` instance\n\n It is calculated once when it is queried for the first time. On\n refresh, this property is reset.\n \"\"\"\n return ethernet_switch_acl_rule.EthernetSwitchACLRuleCollection(\n self._conn,\n utils.get_sub_resource_path_by(self, \"Rules\"),\n redfish_version=self.redfish_version,\n )\n\n\nclass EthernetSwitchACLCollection(rsd_lib_base.ResourceCollectionBase):\n\n @property\n def _resource_type(self):\n return EthernetSwitchACL\n\n def create_acl(self):\n \"\"\"Create a new ACL\n\n :returns: The location of the acl rule\n \"\"\"\n target_uri = self._path\n\n resp = self._conn.post(target_uri, data={})\n acl_url = resp.headers[\"Location\"]\n\n LOG.info(\"Create ACL at %s\", acl_url)\n return acl_url[acl_url.find(self._path):]\n","sub_path":"rsd_lib/resources/v2_1/ethernet_switch/ethernet_switch_acl.py","file_name":"ethernet_switch_acl.py","file_ext":"py","file_size_in_byte":5182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"241651447","text":"# -*- coding: utf-8 -*-\n\"\"\"\nxclim xarray.DataArray utilities module\n\"\"\"\n# import abc\nimport calendar\nimport datetime as dt\nimport functools\nimport re\nimport warnings\nfrom collections import defaultdict\nfrom collections import OrderedDict\nfrom inspect import signature\n\nimport numpy as np\nimport pint\nimport xarray as xr\nfrom boltons.funcutils import wraps\n\nimport xclim\nfrom . import checks\n\nunits = pint.UnitRegistry(autoconvert_offset_to_baseunit=True)\nunits.define(\n pint.unit.UnitDefinition(\"percent\", \"%\", (), pint.converters.ScaleConverter(0.01))\n)\n\n# Define commonly encountered units not defined by pint\nunits.define(\n \"degrees_north = degree = degrees_N = degreesN = degree_north = degree_N \"\n \"= degreeN\"\n)\nunits.define(\n \"degrees_east = degree = degrees_E = degreesE = degree_east = degree_E = degreeE\"\n)\nunits.define(\n \"degC = kelvin; offset: 273.15 = celsius = C\"\n) # add 'C' as an abbrev for celsius (default Coulomb)\nunits.define(\"d = day\")\n\n# Default context.\nnull = pint.Context(\"none\")\nunits.add_context(null)\n\n# Precipitation units. This is an artificial unit that we're using to verify that a given unit can be converted into\n# a precipitation unit. Ideally this could be checked through the `dimensionality`, but I can't get it to work.\nunits.define(\"[precipitation] = [mass] / [length] ** 2 / [time]\")\nunits.define(\"mmday = 1000 kg / meter ** 2 / day\")\n\nunits.define(\"[discharge] = [length] ** 3 / [time]\")\nunits.define(\"cms = meter ** 3 / second\")\n\nhydro = pint.Context(\"hydro\")\nhydro.add_transformation(\n \"[mass] / [length]**2\",\n \"[length]\",\n lambda ureg, x: x / (1000 * ureg.kg / ureg.m ** 3),\n)\nhydro.add_transformation(\n \"[mass] / [length]**2 / [time]\",\n \"[length] / [time]\",\n lambda ureg, x: x / (1000 * ureg.kg / ureg.m ** 3),\n)\nhydro.add_transformation(\n \"[length] / [time]\",\n \"[mass] / [length]**2 / [time]\",\n lambda ureg, x: x * (1000 * ureg.kg / ureg.m ** 3),\n)\nunits.add_context(hydro)\nunits.enable_contexts(hydro)\n\n# These are the changes that could be included in a units definition file.\n\n# degrees_north = degree = degrees_N = degreesN = degree_north = degree_N = degreeN\n# degrees_east = degree = degrees_E = degreesE = degree_east = degree_E = degreeE\n# degC = kelvin; offset: 273.15 = celsius = C\n# day = 24 * hour = d\n# @context hydro\n# [mass] / [length]**2 -> [length]: value / 1000 / kg / m ** 3\n# [mass] / [length]**2 / [time] -> [length] / [time] : value / 1000 / kg * m ** 3\n# [length] / [time] -> [mass] / [length]**2 / [time] : value * 1000 * kg / m ** 3\n# @end\nbinary_ops = {\">\": \"gt\", \"<\": \"lt\", \">=\": \"ge\", \"<=\": \"le\"}\n\n# Maximum day of year in each calendar.\ncalendars = {\n \"standard\": 366,\n \"gregorian\": 366,\n \"proleptic_gregorian\": 366,\n \"julian\": 366,\n \"no_leap\": 365,\n \"365_day\": 365,\n \"all_leap\": 366,\n \"366_day\": 366,\n \"uniform30day\": 360,\n \"360_day\": 360,\n}\n\n\ndef units2pint(value):\n \"\"\"Return the pint Unit for the DataArray units.\n\n Parameters\n ----------\n value : xr.DataArray or string\n Input data array or expression.\n\n Returns\n -------\n pint.Unit\n Units of the data array.\n\n \"\"\"\n\n def _transform(s):\n \"\"\"Convert a CF-unit string to a pint expression.\"\"\"\n return re.subn(r\"([a-zA-Z]+)\\^?(-?\\d)\", r\"\\g<1>**\\g<2>\", s)[0]\n\n if isinstance(value, str):\n unit = value\n elif isinstance(value, xr.DataArray):\n unit = value.attrs[\"units\"]\n elif isinstance(value, units.Quantity):\n return value.units\n else:\n raise NotImplementedError(\"Value of type {} not supported.\".format(type(value)))\n\n try: # Pint compatible\n return units.parse_expression(unit).units\n except (\n pint.UndefinedUnitError,\n pint.DimensionalityError,\n ): # Convert from CF-units to pint-compatible\n return units.parse_expression(_transform(unit)).units\n\n\ndef pint2cfunits(value):\n \"\"\"Return a CF-Convention unit string from a `pint` unit.\n\n Parameters\n ----------\n value : pint.Unit\n Input unit.\n\n Returns\n -------\n out : str\n Units following CF-Convention.\n \"\"\"\n # Print units using abbreviations (millimeter -> mm)\n s = \"{:~}\".format(value)\n\n # Search and replace patterns\n pat = r\"(?P/ )?(?P\\w+)(?: \\*\\* (?P\\d))?\"\n\n def repl(m):\n i, u, p = m.groups()\n p = p or (1 if i else \"\")\n neg = \"-\" if i else (\"^\" if p else \"\")\n\n return \"{}{}{}\".format(u, neg, p)\n\n out, n = re.subn(pat, repl, s)\n return out\n\n\ndef pint_multiply(da, q, out_units=None):\n \"\"\"Multiply xarray.DataArray by pint.Quantity.\n\n Parameters\n ----------\n da : xr.DataArray\n Input array.\n q : pint.Quantity\n Multiplicating factor.\n out_units : str\n Units the output array should be converted into.\n \"\"\"\n a = 1 * units2pint(da)\n f = a * q.to_base_units()\n if out_units:\n f = f.to(out_units)\n out = da * f.magnitude\n out.attrs[\"units\"] = pint2cfunits(f.units)\n return out\n\n\ndef convert_units_to(source, target, context=None):\n \"\"\"\n Convert a mathematical expression into a value with the same units as a DataArray.\n\n Parameters\n ----------\n source : str, pint.Quantity or xr.DataArray\n The value to be converted, e.g. '4C' or '1 mm/d'.\n target : str, pint.Unit or DataArray\n Target array of values to which units must conform.\n context : str\n\n Returns\n -------\n out\n The source value converted to target's units.\n \"\"\"\n # Target units\n if isinstance(target, units.Unit):\n tu = target\n elif isinstance(target, (str, xr.DataArray)):\n tu = units2pint(target)\n else:\n raise NotImplementedError\n\n if isinstance(source, str):\n q = units.parse_expression(source)\n\n # Return magnitude of converted quantity. This is going to fail if units are not compatible.\n return q.to(tu).m\n\n if isinstance(source, units.Quantity):\n return source.to(tu).m\n\n if isinstance(source, xr.DataArray):\n fu = units2pint(source)\n\n if fu == tu:\n return source\n\n tu_u = pint2cfunits(tu)\n with units.context(context or \"none\"):\n out = units.convert(source, fu, tu)\n out.attrs[\"units\"] = tu_u\n return out\n\n # TODO remove backwards compatibility of int/float thresholds after v1.0 release\n if isinstance(source, (float, int)):\n if context == \"hydro\":\n fu = units.mm / units.day\n else:\n fu = units.degC\n warnings.warn(\n \"Future versions of XCLIM will require explicit unit specifications.\",\n FutureWarning,\n )\n return (source * fu).to(tu).m\n\n raise NotImplementedError(\n \"source of type {} is not supported.\".format(type(source))\n )\n\n\ndef _check_units(val, dim):\n if dim is None or val is None:\n return\n\n if str(val).startswith(\"UNSET \"):\n from warnings import warn\n\n warnings.warn(\n \"This index calculation will soon require user-specified thresholds.\",\n FutureWarning,\n stacklevel=4,\n )\n val = str(val).replace(\"UNSET \", \"\")\n\n # TODO remove backwards compatibility of int/float thresholds after v1.0 release\n if isinstance(val, (int, float)):\n return\n\n expected = units.get_dimensionality(dim.replace(\"dimensionless\", \"\"))\n val_dim = units2pint(val).dimensionality\n if val_dim == expected:\n return\n\n # Check if there is a transformation available\n start = pint.util.to_units_container(expected)\n end = pint.util.to_units_container(val_dim)\n graph = units._active_ctx.graph\n if pint.util.find_shortest_path(graph, start, end):\n return\n\n if dim == \"[precipitation]\":\n tu = \"mmday\"\n elif dim == \"[discharge]\":\n tu = \"cms\"\n elif dim == \"[length]\":\n tu = \"m\"\n else:\n raise NotImplementedError\n\n try:\n (1 * units2pint(val)).to(tu, \"hydro\")\n except (pint.UndefinedUnitError, pint.DimensionalityError):\n raise AttributeError(\n \"Value's dimension {} does not match expected units {}.\".format(\n val_dim, expected\n )\n )\n\n\ndef declare_units(out_units, **units_by_name):\n \"\"\"Create a decorator to check units of function arguments.\"\"\"\n\n def dec(func):\n # Match the signature of the function to the arguments given to the decorator\n sig = signature(func)\n bound_units = sig.bind_partial(**units_by_name)\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n # Match all passed in value to their proper arguments so we can check units\n bound_args = sig.bind(*args, **kwargs)\n for name, val in bound_args.arguments.items():\n _check_units(val, bound_units.arguments.get(name, None))\n\n out = func(*args, **kwargs)\n\n # In the generic case, we use the default units that should have been propagated by the computation.\n if \"[\" in out_units:\n _check_units(out, out_units)\n\n # Otherwise, we specify explicitly the units.\n else:\n out.attrs[\"units\"] = out_units\n return out\n\n return wrapper\n\n return dec\n\n\ndef threshold_count(da, op, thresh, freq):\n \"\"\"Count number of days above or below threshold.\n\n Parameters\n ----------\n da : xarray.DataArray\n Input data.\n op : {>, <, >=, <=, gt, lt, ge, le }\n Logical operator, e.g. arr > thresh.\n thresh : float\n Threshold value.\n freq : str\n Resampling frequency defining the periods\n defined in http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling.\n\n Returns\n -------\n xarray.DataArray\n The number of days meeting the constraints for each period.\n \"\"\"\n from xarray.core.ops import get_op\n\n if op in binary_ops:\n op = binary_ops[op]\n elif op in binary_ops.values():\n pass\n else:\n raise ValueError(\"Operation `{}` not recognized.\".format(op))\n\n func = getattr(da, \"_binary_op\")(get_op(op))\n c = func(da, thresh) * 1\n return c.resample(time=freq).sum(dim=\"time\")\n\n\ndef percentile_doy(arr, window=5, per=0.1):\n \"\"\"Percentile value for each day of the year\n\n Return the climatological percentile over a moving window around each day of the year.\n\n Parameters\n ----------\n arr : xarray.DataArray\n Input data.\n window : int\n Number of days around each day of the year to include in the calculation.\n per : float\n Percentile between [0,1]\n\n Returns\n -------\n xarray.DataArray\n The percentiles indexed by the day of the year.\n \"\"\"\n # TODO: Support percentile array, store percentile in coordinates.\n # This is supported by DataArray.quantile, but not by groupby.reduce.\n rr = arr.rolling(min_periods=1, center=True, time=window).construct(\"window\")\n\n # Create empty percentile array\n g = rr.groupby(\"time.dayofyear\")\n\n p = g.reduce(np.nanpercentile, dim=(\"time\", \"window\"), q=per * 100)\n\n # The percentile for the 366th day has a sample size of 1/4 of the other days.\n # To have the same sample size, we interpolate the percentile from 1-365 doy range to 1-366\n if p.dayofyear.max() == 366:\n p = adjust_doy_calendar(p.loc[p.dayofyear < 366], arr)\n\n p.attrs.update(arr.attrs.copy())\n return p\n\n\ndef infer_doy_max(arr):\n \"\"\"Return the largest doy allowed by calendar.\n\n Parameters\n ----------\n arr : xarray.DataArray\n Array with `time` coordinate.\n\n Returns\n -------\n int\n The largest day of the year found in calendar.\n \"\"\"\n cal = arr.time.encoding.get(\"calendar\", None)\n if cal in calendars:\n doy_max = calendars[cal]\n else:\n # If source is an array with no calendar information and whose length is not at least of full year,\n # then this inference could be wrong (\n doy_max = arr.time.dt.dayofyear.max().data\n if len(arr.time) < 360:\n raise ValueError(\n \"Cannot infer the calendar from a series less than a year long.\"\n )\n if doy_max not in [360, 365, 366]:\n raise ValueError(\"The target array's calendar is not recognized\")\n\n return doy_max\n\n\ndef _interpolate_doy_calendar(source, doy_max):\n \"\"\"Interpolate from one set of dayofyear range to another\n\n Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1\n to 365).\n\n Parameters\n ----------\n source : xarray.DataArray\n Array with `dayofyear` coordinates.\n doy_max : int\n Largest day of the year allowed by calendar.\n\n Returns\n -------\n xarray.DataArray\n Interpolated source array over coordinates spanning the target `dayofyear` range.\n\n \"\"\"\n if \"dayofyear\" not in source.coords.keys():\n raise AttributeError(\"source should have dayofyear coordinates.\")\n\n # Interpolation of source to target dayofyear range\n doy_max_source = source.dayofyear.max()\n\n # Interpolate to fill na values\n tmp = source.interpolate_na(dim=\"dayofyear\")\n\n # Interpolate to target dayofyear range\n tmp.coords[\"dayofyear\"] = np.linspace(start=1, stop=doy_max, num=doy_max_source)\n\n return tmp.interp(dayofyear=range(1, doy_max + 1))\n\n\ndef adjust_doy_calendar(source, target):\n \"\"\"Interpolate from one set of dayofyear range to another calendar.\n\n Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1\n to 365).\n\n Parameters\n ----------\n source : xarray.DataArray\n Array with `dayofyear` coordinate.\n target : xarray.DataArray\n Array with `time` coordinate.\n\n Returns\n -------\n xarray.DataArray\n Interpolated source array over coordinates spanning the target `dayofyear` range.\n\n \"\"\"\n doy_max_source = source.dayofyear.max()\n\n doy_max = infer_doy_max(target)\n if doy_max_source == doy_max:\n return source\n\n return _interpolate_doy_calendar(source, doy_max)\n\n\ndef resample_doy(doy, arr):\n \"\"\"Create a temporal DataArray where each day takes the value defined by the day-of-year.\n\n Parameters\n ----------\n doy : xarray.DataArray\n Array with `dayofyear` coordinate.\n arr : xarray.DataArray\n Array with `time` coordinate.\n\n Returns\n -------\n xarray.DataArray\n An array with the same `time` dimension as `arr` whose values are filled according to the day-of-year value in\n `doy`.\n \"\"\"\n if \"dayofyear\" not in doy.coords:\n raise AttributeError(\"`doy` should have dayofyear coordinates.\")\n\n # Adjust calendar\n adoy = adjust_doy_calendar(doy, arr)\n\n # Create array with arr shape and coords\n out = xr.full_like(arr, np.nan)\n\n # Fill with values from `doy`\n d = out.time.dt.dayofyear.values\n out.data = adoy.sel(dayofyear=d)\n\n return out\n\n\ndef get_daily_events(da, da_value, operator):\n r\"\"\"\n function that returns a 0/1 mask when a condition is True or False\n\n the function returns 1 where operator(da, da_value) is True\n 0 where operator(da, da_value) is False\n nan where da is nan\n\n Parameters\n ----------\n da : xarray.DataArray\n da_value : float\n operator : string\n\n\n Returns\n -------\n xarray.DataArray\n\n \"\"\"\n events = operator(da, da_value) * 1\n events = events.where(~np.isnan(da))\n events = events.rename(\"events\")\n return events\n\n\ndef daily_downsampler(da, freq=\"YS\"):\n r\"\"\"Daily climate data downsampler\n\n Parameters\n ----------\n da : xarray.DataArray\n freq : string\n\n Returns\n -------\n xarray.DataArray\n\n\n Note\n ----\n\n Usage Example\n\n grouper = daily_downsampler(da_std, freq='YS')\n x2 = grouper.mean()\n\n # add time coords to x2 and change dimension tags to time\n time1 = daily_downsampler(da_std.time, freq=freq).first()\n x2.coords['time'] = ('tags', time1.values)\n x2 = x2.swap_dims({'tags': 'time'})\n x2 = x2.sortby('time')\n \"\"\"\n\n # generate tags from da.time and freq\n if isinstance(da.time.values[0], np.datetime64):\n years = [\"{:04d}\".format(y) for y in da.time.dt.year.values]\n months = [\"{:02d}\".format(m) for m in da.time.dt.month.values]\n else:\n # cannot use year, month, season attributes, not available for all calendars ...\n years = [\"{:04d}\".format(v.year) for v in da.time.values]\n months = [\"{:02d}\".format(v.month) for v in da.time.values]\n seasons = [\n \"DJF DJF MAM MAM MAM JJA JJA JJA SON SON SON DJF\".split()[int(m) - 1]\n for m in months\n ]\n\n n_t = da.time.size\n if freq == \"YS\":\n # year start frequency\n l_tags = years\n elif freq == \"MS\":\n # month start frequency\n l_tags = [years[i] + months[i] for i in range(n_t)]\n elif freq == \"QS-DEC\":\n # DJF, MAM, JJA, SON seasons\n # construct tags from list of season+year, increasing year for December\n ys = []\n for i in range(n_t):\n m = months[i]\n s = seasons[i]\n y = years[i]\n if m == \"12\":\n y = str(int(y) + 1)\n ys.append(y + s)\n l_tags = ys\n else:\n raise RuntimeError(\"freqency {:s} not implemented\".format(freq))\n\n # add tags to buffer DataArray\n buffer = da.copy()\n buffer.coords[\"tags\"] = (\"time\", l_tags)\n\n # return groupby according to tags\n return buffer.groupby(\"tags\")\n\n\ndef walk_map(d, func):\n \"\"\"Apply a function recursively to values of dictionary.\n\n Parameters\n ----------\n d : dict\n Input dictionary, possibly nested.\n func : function\n Function to apply to dictionary values.\n\n Returns\n -------\n dict\n Dictionary whose values are the output of the given function.\n \"\"\"\n out = {}\n for k, v in d.items():\n if isinstance(v, (dict, defaultdict)):\n out[k] = walk_map(v, func)\n else:\n out[k] = func(v)\n return out\n\n\n# This class needs to be subclassed by individual indicator classes defining metadata information, compute and\n# missing functions. It can handle indicators with any number of forcing fields.\nclass Indicator:\n r\"\"\"Climate indicator based on xarray\n \"\"\"\n # Unique ID for function registry.\n identifier = \"\"\n\n # Output variable name. May use tags {} that will be formatted at runtime.\n var_name = \"\"\n\n _nvar = 1\n\n # CF-Convention metadata to be attributed to the output variable. May use tags {} formatted at runtime.\n standard_name = (\n \"\"\n ) # The set of permissible standard names is contained in the standard name table.\n long_name = \"\" # Parsed.\n units = \"\" # Representative units of the physical quantity.\n cell_methods = \"\" # List of blank-separated words of the form \"name: method\"\n description = (\n \"\"\n ) # The description is meant to clarify the qualifiers of the fundamental quantities, such as which\n # surface a quantity is defined on or what the flux sign conventions are.\n\n # The `pint` unit context. Use 'hydro' to allow conversion from kg m-2 s-1 to mm/day.\n context = \"none\"\n\n # Additional information that can be used by third party libraries or to describe the file content.\n title = (\n \"\"\n ) # A succinct description of what is in the dataset. Default parsed from compute.__doc__\n abstract = \"\" # Parsed\n keywords = \"\" # Comma separated list of keywords\n references = (\n \"\"\n ) # Published or web-based references that describe the data or methods used to produce it. Parsed.\n comment = (\n \"\"\n ) # Miscellaneous information about the data or methods used to produce it.\n notes = \"\" # Mathematical formulation. Parsed.\n\n # Tag mappings between keyword arguments and long-form text.\n months = {\"m{}\".format(i): calendar.month_name[i].lower() for i in range(1, 13)}\n _attrs_mapping = {\n \"cell_methods\": {\n \"YS\": \"years\",\n \"MS\": \"months\",\n }, # I don't think this is necessary.\n \"long_name\": {\n \"YS\": \"Annual\",\n \"MS\": \"Monthly\",\n \"QS-DEC\": \"Seasonal\",\n \"DJF\": \"winter\",\n \"MAM\": \"spring\",\n \"JJA\": \"summer\",\n \"SON\": \"fall\",\n },\n \"description\": {\n \"YS\": \"Annual\",\n \"MS\": \"Monthly\",\n \"QS-DEC\": \"Seasonal\",\n \"DJF\": \"winter\",\n \"MAM\": \"spring\",\n \"JJA\": \"summer\",\n \"SON\": \"fall\",\n },\n \"var_name\": {\"DJF\": \"winter\", \"MAM\": \"spring\", \"JJA\": \"summer\", \"SON\": \"fall\"},\n }\n\n for k, v in _attrs_mapping.items():\n v.update(months)\n\n # Whether or not the compute function is a partial.\n _partial = False\n\n # Can be used to override the compute docstring.\n doc_template = None\n\n def __init__(self, **kwds):\n\n # Set instance attributes.\n for key, val in kwds.items():\n setattr(self, key, val)\n\n # Verify that the identifier is a proper slug\n if not re.match(r\"^[-\\w]+$\", self.identifier):\n warnings.warn(\n \"The identifier contains non-alphanumeric characters. It could make life \"\n \"difficult for downstream software reusing this class.\",\n UserWarning,\n )\n\n # Default value for `var_name` is the `identifier`.\n if self.var_name == \"\":\n self.var_name = self.identifier\n\n # Extract information from the `compute` function.\n # The signature\n self._sig = signature(self.compute)\n\n # The input parameter names\n self._parameters = tuple(self._sig.parameters.keys())\n # self._input_params = [p for p in self._sig.parameters.values() if p.default is p.empty]\n # self._nvar = len(self._input_params)\n\n # Copy the docstring and signature\n self.__call__ = wraps(self.compute)(self.__call__.__func__)\n if self.doc_template is not None:\n self.__call__.__doc__ = self.doc_template.format(i=self)\n\n # Fill in missing metadata from the doc\n meta = parse_doc(self.compute.__doc__)\n for key in [\"abstract\", \"title\", \"notes\", \"references\"]:\n setattr(self, key, getattr(self, key) or meta.get(key, \"\"))\n\n def __call__(self, *args, **kwds):\n # Bind call arguments. We need to use the class signature, not the instance, otherwise it removes the first\n # argument.\n if self._partial:\n ba = self._sig.bind_partial(*args, **kwds)\n for key, val in self.compute.keywords.items():\n if key not in ba.arguments:\n ba.arguments[key] = val\n else:\n ba = self._sig.bind(*args, **kwds)\n ba.apply_defaults()\n\n # Get history and cell method attributes from source data\n attrs = defaultdict(str)\n for i in range(self._nvar):\n p = self._parameters[i]\n for attr in [\"history\", \"cell_methods\"]:\n attrs[attr] += \"{}: \".format(p) if self._nvar > 1 else \"\"\n attrs[attr] += getattr(ba.arguments[p], attr, \"\")\n if attrs[attr]:\n attrs[attr] += \"\\n\" if attr == \"history\" else \" \"\n\n # Update attributes\n out_attrs = self.format(self.cf_attrs, ba.arguments)\n vname = self.format({\"var_name\": self.var_name}, ba.arguments)[\"var_name\"]\n\n # Update the signature with the values of the actual call.\n cp = OrderedDict()\n for (k, v) in ba.signature.parameters.items():\n if v.default is not None and isinstance(v.default, (float, int, str)):\n cp[k] = v.replace(default=ba.arguments[k])\n else:\n cp[k] = v\n\n attrs[\n \"history\"\n ] += \"[{:%Y-%m-%d %H:%M:%S}] {}: {}{} - xclim version: {}.\".format(\n dt.datetime.now(),\n vname,\n self.identifier,\n ba.signature.replace(parameters=cp.values()),\n xclim.__version__,\n )\n attrs[\"cell_methods\"] += out_attrs.pop(\"cell_methods\", \"\")\n attrs.update(out_attrs)\n\n # Assume the first arguments are always the DataArray.\n das = tuple(ba.arguments.pop(self._parameters[i]) for i in range(self._nvar))\n\n # Pre-computation validation checks\n for da in das:\n self.validate(da)\n self.cfprobe(*das)\n\n # Compute the indicator values, ignoring NaNs.\n out = self.compute(*das, **ba.kwargs)\n\n # Convert to output units\n out = convert_units_to(out, self.units, self.context)\n\n # Update netCDF attributes\n out.attrs.update(attrs)\n\n # Bind call arguments to the `missing` function, whose signature might be different from `compute`.\n mba = signature(self.missing).bind(*das, **ba.arguments)\n\n # Mask results that do not meet criteria defined by the `missing` method.\n mask = self.missing(*mba.args, **mba.kwargs)\n ma_out = out.where(~mask)\n\n return ma_out.rename(vname)\n\n @property\n def cf_attrs(self):\n \"\"\"CF-Convention attributes of the output value.\"\"\"\n names = [\n \"standard_name\",\n \"long_name\",\n \"units\",\n \"cell_methods\",\n \"description\",\n \"comment\",\n \"references\",\n ]\n return {k: getattr(self, k) for k in names if getattr(self, k)}\n\n def json(self, args=None):\n \"\"\"Return a dictionary representation of the class.\n\n Notes\n -----\n This is meant to be used by a third-party library wanting to wrap this class into another interface.\n\n \"\"\"\n names = [\"identifier\", \"var_name\", \"abstract\", \"keywords\"]\n out = {key: getattr(self, key) for key in names}\n out.update(self.cf_attrs)\n out = self.format(out, args)\n\n out[\"notes\"] = self.notes\n\n out[\"parameters\"] = str(\n {\n key: {\n \"default\": p.default if p.default != p.empty else None,\n \"desc\": \"\",\n }\n for (key, p) in self._sig.parameters.items()\n }\n )\n\n # if six.PY2:\n # out = walk_map(out, lambda x: x.decode('utf8') if isinstance(x, six.string_types) else x)\n\n return out\n\n def cfprobe(self, *das):\n \"\"\"Check input data compliance to expectations.\n Warn of potential issues.\"\"\"\n return True\n\n def compute(*args, **kwds):\n \"\"\"The function computing the indicator.\"\"\"\n raise NotImplementedError\n\n def format(self, attrs, args=None):\n \"\"\"Format attributes including {} tags with arguments.\n\n Parameters\n ----------\n attrs: dict\n Attributes containing tags to replace with arguments' values.\n args : dict\n Function call arguments.\n \"\"\"\n if args is None:\n return attrs\n\n out = {}\n for key, val in attrs.items():\n mba = {\"indexer\": \"annual\"}\n # Add formatting {} around values to be able to replace them with _attrs_mapping using format.\n for k, v in args.items():\n if isinstance(v, str) and v in self._attrs_mapping.get(key, {}).keys():\n mba[k] = \"{{{}}}\".format(v)\n elif isinstance(v, dict):\n if v:\n dk, dv = v.copy().popitem()\n if dk == \"month\":\n dv = \"m{}\".format(dv)\n mba[k] = \"{{{}}}\".format(dv)\n elif isinstance(v, units.Quantity):\n mba[k] = \"{:g~P}\".format(v)\n elif isinstance(v, (int, float)):\n mba[k] = \"{:g}\".format(v)\n else:\n mba[k] = v\n\n out[key] = val.format(**mba).format(**self._attrs_mapping.get(key, {}))\n\n return out\n\n @staticmethod\n def missing(*args, **kwds):\n \"\"\"Return whether an output is considered missing or not.\"\"\"\n from functools import reduce\n\n freq = kwds.get(\"freq\")\n miss = (checks.missing_any(da, freq) for da in args)\n return reduce(np.logical_or, miss)\n\n def validate(self, da):\n \"\"\"Validate input data requirements.\n Raise error if conditions are not met.\"\"\"\n checks.assert_daily(da)\n\n\nclass Indicator2D(Indicator):\n _nvar = 2\n\n\ndef parse_doc(doc):\n \"\"\"Crude regex parsing.\"\"\"\n if doc is None:\n return {}\n\n out = {}\n\n sections = re.split(r\"(\\w+)\\n\\s+-{4,50}\", doc) # obj.__doc__.split('\\n\\n')\n intro = sections.pop(0)\n if intro:\n content = list(map(str.strip, intro.strip().split(\"\\n\\n\")))\n if len(content) == 1:\n out[\"title\"] = content[0]\n elif len(content) == 2:\n out[\"title\"], out[\"abstract\"] = content\n\n for i in range(0, len(sections), 2):\n header, content = sections[i : i + 2]\n\n if header in [\"Notes\", \"References\"]:\n out[header.lower()] = content.replace(\"\\n \", \"\\n\")\n elif header == \"Parameters\":\n pass\n elif header == \"Returns\":\n match = re.search(r\"xarray\\.DataArray\\s*(.*)\", content)\n if match:\n out[\"long_name\"] = match.groups()[0]\n\n return out\n\n\ndef format_kwargs(attrs, params):\n \"\"\"Modify attribute with argument values.\n\n Parameters\n ----------\n attrs : dict\n Attributes to be assigned to function output. The values of the attributes in braces will be replaced the\n the corresponding args values.\n params : dict\n A BoundArguments.arguments dictionary storing a function's arguments.\n \"\"\"\n attrs_mapping = {\n \"cell_methods\": {\"YS\": \"years\", \"MS\": \"months\"},\n \"long_name\": {\"YS\": \"Annual\", \"MS\": \"Monthly\"},\n }\n\n for key, val in attrs.items():\n mba = {}\n # Add formatting {} around values to be able to replace them with _attrs_mapping using format.\n for k, v in params.items():\n if isinstance(v, str) and v in attrs_mapping.get(key, {}).keys():\n mba[k] = \"{\" + v + \"}\"\n else:\n mba[k] = v\n\n attrs[key] = val.format(**mba).format(**attrs_mapping.get(key, {}))\n\n\ndef wrapped_partial(func, *args, **kwargs):\n from functools import partial, update_wrapper\n\n partial_func = partial(func, *args, **kwargs)\n update_wrapper(partial_func, func)\n return partial_func\n","sub_path":"xclim/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":30761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"535643535","text":"'''\nDesign your implementation of the circular double-ended queue (deque).\n\nYour implementation should support following operations:\n\nMyCircularDeque(k): Constructor, set the size of the deque to be k.\ninsertFront(): Adds an item at the front of Deque. Return true if the operation is successful.\ninsertLast(): Adds an item at the rear of Deque. Return true if the operation is successful.\ndeleteFront(): Deletes an item from the front of Deque. Return true if the operation is successful.\ndeleteLast(): Deletes an item from the rear of Deque. Return true if the operation is successful.\ngetFront(): Gets the front item from the Deque. If the deque is empty, return -1.\ngetRear(): Gets the last item from Deque. If the deque is empty, return -1.\nisEmpty(): Checks whether Deque is empty or not. \nisFull(): Checks whether Deque is full or not.\n \n\nExample:\n\nMyCircularDeque circularDeque = new MycircularDeque(3); // set the size to be 3\ncircularDeque.insertLast(1); // return true\ncircularDeque.insertLast(2); // return true\ncircularDeque.insertFront(3); // return true\ncircularDeque.insertFront(4); // return false, the queue is full\ncircularDeque.getRear(); // return 2\ncircularDeque.isFull(); // return true\ncircularDeque.deleteLast(); // return true\ncircularDeque.insertFront(4); // return true\ncircularDeque.getFront(); // return 4\n'''\n\nclass Node:\n def __init__(self, x):\n self.val = x\n self.prev = None\n self.next = None\n\nclass MyCircularDeque:\n\n def __init__(self, k: int):\n \"\"\"\n Initialize your data structure here. Set the size of the deque to be k.\n \"\"\"\n self.head = self.rear = None\n self.capacity = k\n self.size = 0\n \n def insertFront(self, value: int) -> bool:\n \"\"\"\n Adds an item at the front of Deque. Return true if the operation is successful.\n \"\"\"\n if self.isFull():\n return False\n elif self.isEmpty():\n self.head = self.rear = Node(value)\n else:\n new_head = Node(value)\n new_head.next = self.head\n self.head.prev = new_head\n self.head = new_head\n self.size += 1\n return True\n\n def insertLast(self, value: int) -> bool:\n \"\"\"\n Adds an item at the rear of Deque. Return true if the operation is successful.\n \"\"\"\n if self.isFull():\n return False\n elif self.isEmpty():\n self.head = self.rear = Node(value) \n else:\n new_rear = Node(value)\n new_rear.prev = self.rear\n self.rear.next = new_rear \n self.rear = new_rear\n self.size += 1\n return True \n\n def deleteFront(self) -> bool:\n \"\"\"\n Deletes an item from the front of Deque. Return true if the operation is successful.\n \"\"\"\n if self.isEmpty(): \n return False\n elif self.size == 1:\n self.head = self.rear = None\n else: \n self.head = self.head.next\n self.head.prev = None\n self.size -= 1 \n return True \n\n def deleteLast(self) -> bool:\n \"\"\"\n Deletes an item from the rear of Deque. Return true if the operation is successful.\n \"\"\"\n if self.isEmpty(): \n return False \n elif self.size == 1:\n self.head = self.rear = None\n else:\n self.rear = self.rear.prev\n self.rear.next = None \n self.size -= 1\n return True \n \n def getFront(self) -> int:\n \"\"\"\n Get the front item from the deque.\n \"\"\"\n return -1 if self.isEmpty() else self.head.val\n\n def getRear(self) -> int:\n \"\"\"\n Get the last item from the deque.\n \"\"\"\n return -1 if self.isEmpty() else self.rear.val\n\n def isEmpty(self) -> bool:\n \"\"\"\n Checks whether the circular deque is empty or not.\n \"\"\"\n return self.size == 0\n\n def isFull(self) -> bool:\n \"\"\"\n Checks whether the circular deque is full or not.\n \"\"\"\n return self.size == self.capacity\n\n\n# Your MyCircularDeque object will be instantiated and called as such:\n# obj = MyCircularDeque(k)\n# param_1 = obj.insertFront(value)\n# param_2 = obj.insertLast(value)\n# param_3 = obj.deleteFront()\n# param_4 = obj.deleteLast()\n# param_5 = obj.getFront()\n# param_6 = obj.getRear()\n# param_7 = obj.isEmpty()\n# param_8 = obj.isFull()","sub_path":"algorithms/queues/circular_deque_implementation.py","file_name":"circular_deque_implementation.py","file_ext":"py","file_size_in_byte":4546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"12091731","text":"import urllib.request\nimport xlrd\nimport time\nfrom xlwt import Workbook\nimport os\n\nfile_location = os.getcwd()\n\nstart = time.time()\n\nfilename = \"/stocksconstituents.xlsx\"\n\nfile_location += filename\nL=[]\nL2=[]\nstock_data = ['', '', '', '', '', '', '']\n\nworkbook = xlrd.open_workbook(file_location)\nstock_constituents = workbook.sheet_by_index(0)\n\nfor s in workbook.sheets():\n for row in range(s.nrows):\n values = []\n for col in range(s.ncols):\n values.append(s.cell(row, col).value)\n\nfor row in range( stock_constituents.nrows):\n L.append(stock_constituents.cell_value(row, 0).strip('u'))\n\nwb=Workbook()\nbasic_data_sheet = wb.add_sheet('Sheet1')\n\n\ndef rTicker(ticker):\n stock_data[0] = (str(ticker))\n return\n\ndef price(input3,ticker):\n \n try:\n price=input3.split('')[1].split('')[0]\n pass\n except IndexError:\n print(\"error with \" + ticker)\n try:\n stock_data[1 ]=float(str(price.replace( ',', '' ) ) )\n pass\n except UnboundLocalError:\n print(\"error with \" + ticker)\n stock_data[1 ]=0\n return\n\n\ndef volatility( input2 ):\n cond = False\n try:\n vol = input2.split('>Volatility')[1].split('')[0]\n cond = True\n except IndexError:\n stock_data[2] = 0\n if cond:\n vol = vol.split( ' ' )\n v1 = float(vol[0].strip('%'))\n v2 = float(vol[1].strip('%'))\n v3 = (v1 + v2) / 2\n stock_data[2 ] = (round ( float ( v3 ), 2 ))\n return\n\n\ndef ev_ebitda(input3):\n if ('Enterprise Value/EBITDA (ttm)6:') in input3:\n ev_ebitda=input3.split('Enterprise Value/EBITDA (ttm)6:')[1].split('')[0]\n if '%' in str(ev_ebitda):\n stock_data[3 ]=float( ev_ebitda.strip( '%' ) )\n elif 'N/A' in str(ev_ebitda):\n stock_data[3 ]=(ev_ebitda)\n else:\n stock_data[3 ]=float( ev_ebitda )\n else :\n stock_data[3 ]=(float( 0 ))\n return\n\ndef revenue_growth_yoy(input3):\n if ('Qtrly Revenue Growth (yoy):') in input3:\n rev_gro=input3.split('Qtrly Revenue Growth (yoy):')[1].split('')[0]\n if '%' in str(rev_gro):\n stock_data[4 ]=float( rev_gro.strip( '%' ) )\n\n elif 'N/A' in str(rev_gro):\n stock_data[4 ]=str( rev_gro )\n else:\n stock_data[4 ]=float( 0 )\n else:\n stock_data[4 ]=float( 0 )\n return \n\ndef twodma(input3):\n if ('200-Day Moving Average3:') in input3:\n twohdma=input3.split('200-Day Moving Average3:')[1].split('')[0]\n else :\n twohdma=0\n try:\n stock_data[5 ]=float( twohdma )\n except:\n pass\n return\n\ndef twelwemonth_return(input3):\n if ('52-Week Change3:') in input3:\n twelwemonth_return=input3.split('52-Week Change3:')[1].split('')[0]\n if '%' in str(twelwemonth_return):\n stock_data[6 ]=float( twelwemonth_return.strip( '%' ) )\n elif 'N/A' in str(twelwemonth_return):\n stock_data[6 ]=(twelwemonth_return)\n else:\n stock_data[6 ]=float( 0 )\n else :\n stock_data[6 ]=float( 0 )\n #print(twelwemonth_return)\n return\n\n\n\n\nrow = 1\nfor ticker in L[1:501]:\n print(ticker)\n url2='http://finviz.com/quote.ashx?t='+ticker\n url3='http://finance.yahoo.com/q/ks?s='+ticker+'+Key+Statistics'\n try:\n with urllib.request.urlopen(url2) as url:\n input2 = url.read().decode()\n pass\n except urllib.error.HTTPError:\n print(\"error on finviz with \" + ticker)\n\n try:\n with urllib.request.urlopen(url3) as url:\n input3 = url.read().decode() #kind of a hack, don't ask exactly why\n pass\n except urllib.error.HTTPError:\n print(\"error on yahoo finance with \" + ticker)\n\n volatility(input2)\n ev_ebitda(input3)\n revenue_growth_yoy(input3)\n twodma(input3)\n twelwemonth_return(input3)\n price(input3, ticker)\n rTicker(ticker)\n\n flag = True\n for j in stock_data:\n if j == 'N/A' or j == 0 or j == 0.0:\n flag = False\n\n if flag:\n col = 0\n for j in stock_data:\n basic_data_sheet.write(row, col, j)\n col += 1\n row += 1\n\nbasic_data_sheet.write(0, 0, 'ticker')\nbasic_data_sheet.write(0, 1, 'price')\nbasic_data_sheet.write(0, 2, 'volatility')\nbasic_data_sheet.write(0, 3, 'ev/ebitda')\nbasic_data_sheet.write(0, 4, 'revenue_growth')\nbasic_data_sheet.write(0, 5, '200dma')\nbasic_data_sheet.write(0, 6, '12m return')\n\nprint('end')\nend = time.time()\nprint(end - start)\nimport time\n## dd/mm/yyyy format\ndate = time.strftime(\"%d_%m_%Y_\")\n\nwb.save(date + 'raw_data.xls')\n","sub_path":"web_scraper.py","file_name":"web_scraper.py","file_ext":"py","file_size_in_byte":5250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"562457435","text":"def buy_and_sell_stock(A):\n min_so_far = float('inf')\n max_profit = 0\n for price in A:\n today_profit = price - min_so_far\n max_profit = max(max_profit, today_profit)\n min_so_far = min(min_so_far, price)\n return max_profit\n\ndef buy_and_sell_stock_v2(prices):\n min_so_far = prices[0]\n max_profit = 0\n for i in range(1, len(prices)):\n today_profit = prices[i] - min_so_far\n max_profit = max(max_profit, today_profit)\n min_so_far = min(min_so_far, prices[i])\n return max_profit\n\nprint(buy_and_sell_stock_v2([310, 310, 390, 275, 260, 260, 260, 230, 290]))","sub_path":"epi/ch5/5_6.py","file_name":"5_6.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"503976379","text":"import os\nfrom pathlib import Path\nimport json\n\nlci_files_fp = Path(\"/home/plesage/scratch/preagg_ei36co/lci\")\nfor i in range(10):\n batch_dir = lci_files_fp / str(i)\n if batch_dir.is_dir():\n files = os.listdir(batch_dir)\n with open(lci_files_fp/\"{}.json\".format(i), \"w\") as f:\n json.dump(files, f)\n","sub_path":"io/cedar/done.py","file_name":"done.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"511957743","text":"\"\"\"App file for Cargamos® app\"\"\"\n# Flask\nfrom flask import Flask, render_template, make_response, request, flash, redirect, url_for\nfrom flask_sqlalchemy import SQLAlchemy\n# App imports\nfrom forms import NewProduct, NewShop, NewTransaction\n# SQLAlchemy\nfrom sqlalchemy.exc import IntegrityError\n# Utils\nfrom datetime import datetime\nimport pdb\n# from . import create_app\nfrom flask import Flask\nfrom config import Config\n\n\ndef create_app():\n app = Flask(__name__)\n app.config.from_object(Config)\n return app\n\n\napp = create_app()\ndb = SQLAlchemy()\nfrom models import *\ndb.init_app(app)\n\nwith app.app_context():\n db.create_all()\n\n@app.route('/home')\ndef admin():\n shop = Shop.query.all()\n products = Product.query.all()\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('admin.html', shop=shop, products=products), 200, headers)\n\n\n@app.route('/shop', methods=['GET', 'POST'])\ndef shop():\n new_shop = NewShop()\n shops = Shop.query.all()\n if new_shop.validate_on_submit():\n shop = Shop(name=new_shop.shop_name.data,\n direction=new_shop.shop_location.data,\n description=new_shop.shop_description.data,\n active=new_shop.shop_active.data\n )\n db.session.add(shop)\n try:\n db.session.commit()\n flash(f'Your Shop {new_shop.shop_name.data} has been added!', 'success')\n return redirect('/shop')\n except IntegrityError:\n db.session.rollback()\n flash(f'This shop already exists', 'danger')\n return redirect('/shop')\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('store_detail.html', shop=shops, form=new_shop), 200, headers)\n\n\n@app.route('/products', methods=['GET', 'POST'])\ndef product():\n new_product = NewProduct()\n products = Product.query.all()\n if new_product.validate_on_submit():\n product = Product(name=new_product.product_name.data,\n description=new_product.product_description.data,\n sku=new_product.product_sku.data,\n price=new_product.product_price.data,\n quantity=new_product.product_quantity.data\n )\n db.session.add(product)\n try:\n db.session.commit()\n flash(f'Your product {new_product.product_name.data} has been added!', 'success')\n return redirect('/products')\n except IntegrityError:\n db.session.rollback()\n flash(f'This product already exists', 'danger')\n return redirect('/products')\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template('product_detail.html', products=products, form=new_product), 200, headers)\n\n\n@app.route('/transactions', methods=['GET', 'POST'])\ndef transactions():\n product_list = []\n shop_list = ['Warehouse']\n new_transaction = NewTransaction()\n products = Product.query.all()\n all_transactions = Transaction.query.all()\n exist = bool(Transaction.query.all())\n if exist is False:\n flash('Add a new transaction', 'danger')\n\n # Choices for each product\n product_choices = Product.query.with_entities(Product.name).all()\n product_list += product_choices\n new_transaction.product_name.choices = product_list\n\n # Choices for each store\n shop_choices = Shop.query.with_entities(Shop.name).all()\n shop_list += shop_choices\n new_transaction.origin.choices = shop_list\n new_transaction.end.choices = shop_list\n\n if new_transaction.validate_on_submit() and request.method == 'POST':\n timestamp = datetime.now()\n validator = transaction_review(new_transaction.origin.data,\n new_transaction.end.data,\n new_transaction.product_name.data,\n new_transaction.product_quantity.data)\n if validator == 'Same point':\n flash('Try again, origin and end must be different', 'danger')\n elif validator == 'No prod':\n flash('Try again, there is no product', 'danger')\n elif validator is False:\n flash('Try again, quantity must be lower than existed', 'danger')\n else:\n transaction = Transaction(\n modified=timestamp,\n origin=new_transaction.origin.data,\n end=new_transaction.end.data,\n product_name=new_transaction.product_name.data,\n product_quantity=new_transaction.product_quantity.data\n )\n db.session.add(transaction)\n db.session.commit()\n flash(f'Your transaction has been added!', 'success')\n return redirect('/transactions')\n\n headers = {'Content-Type': 'text/html'}\n return make_response(render_template(\n 'transaction.html',\n transactions=all_transactions,\n form=new_transaction), 200, headers)\n\n\ndef transaction_review(origin, end, product_name, quantity):\n # pdb.set_trace()\n product_name = product_name.strip(\"()',\")\n origin = origin.strip(\"()',\")\n end = end.strip(\"()',\")\n if origin == end:\n return 'Same point'\n elif origin == 'Warehouse' and end != 'Warehouse':\n product = Product.query.filter_by(name=product_name).first()\n if product.quantity >= quantity:\n product.quantity -= quantity\n hold = Holder.query.filter_by(shop_name=origin, product_name=product_name).first()\n a = str(hold)\n if a == 'None':\n new = Holder(product_name=product_name,\n shop_name=end,\n quantity=quantity)\n db.session.add(new)\n else:\n hold.quantity += quantity\n db.session.commit()\n else:\n return False\n elif end == 'Warehouse' and origin != 'Warehouse':\n hold = Holder.query.filter_by(shop_name=origin, product_name=product_name).first()\n a = str(hold)\n if a == 'None':\n return 'No prod'\n else:\n if hold.quantity >= quantity:\n prodq = Product.query.filter_by(name=product_name).first()\n prodq.quantity = prodq.quantity + quantity\n hold.quantity -= quantity\n db.session.commit()\n else:\n return False\n\n else:\n bl = Holder.query.filter_by(shop_name=origin, product_name=product_name).first()\n a = str(bl)\n if a == 'None':\n return 'No prod'\n elif (bl.quantity - 100) > quantity:\n bal = Holder.query.filter_by(shop_name=end, product_name=product_name).first()\n a = str(bal)\n if a == 'None':\n new = Holder(product_name=product_name, shop_name=end, quantity=quantity)\n db.session.add(new)\n bl = Holder.query.filter_by(shop_name=origin, product_name=product_name).first()\n bl.quantity -= quantity\n db.session.commit()\n else:\n bal.quantity += quantity\n bl = Holder.query.filter_by(shop_name=origin, product_name=product_name).first()\n bl.quantity -= quantity\n db.session.commit()\n else:\n return False\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"220704631","text":"# coding: utf-8\nimport json\nimport oauth2\nimport tornado.web\n\nfrom api.v1_0.handlers.oauth import AuthController\n\n\nclass BaseAPIHandler(tornado.web.RequestHandler):\n\n def initialize(self):\n self._oauth = AuthController\n self._oauth.site_adapter.db = self.db\n\n if (\n 'Content-Type' in self.request.headers\n and self.request.headers['Content-Type'].startswith('application/json')\n ):\n attrs = json.loads(self.request.body)\n else:\n attrs = self.request.arguments\n\n @property\n def db(self):\n return self.application.db\n","sub_path":"api/v1_0/handlers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"512054244","text":"import sys\nimport parsing\nimport print_rubik\nimport move\nimport shuffle\nimport utils\n\nrubik = [\"Y\",\"Y\",\"Y\",\"Y\",\"Y\",\"Y\",\"Y\",\"Y\",\"Y\",\n \"O\",\"O\",\"O\",\"O\",\"O\",\"O\",\"O\",\"O\",\"O\",\n \"B\",\"B\",\"B\",\"B\",\"B\",\"B\",\"B\",\"B\",\"B\",\n \"R\",\"R\",\"R\",\"R\",\"R\",\"R\",\"R\",\"R\",\"R\",\n \"G\",\"G\",\"G\",\"G\",\"G\",\"G\",\"G\",\"G\",\"G\",\n \"W\",\"W\",\"W\",\"W\",\"W\",\"W\",\"W\",\"W\",\"W\"]\n\ndef main():\n if len(sys.argv) != 2:\n parsing.error(0, \"0\")\n inst = parsing.parsing(sys.argv[1])\n print_rubik.print_rubik(rubik)\n shuffle.shuffle(rubik, inst)\n if utils.check_rubik(rubik) == False:\n print(\"the cube is not solved\")\n else:\n print(\"the cube is solved\")\n\nmain()","sub_path":"rubik.py","file_name":"rubik.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552648889","text":"\"\"\"\nменее предпочтительный метод организации модальности диалога\n\"\"\"\nfrom tkinter import *\n\n\ndef dialog():\n win = Toplevel() # создать новое окно\n Label(win, text='Hard drive reformatted!').pack() # добавить виджеты\n Button(win, text='OK', command=win.quit).pack() # установить обр-к quit\n win.protocol('WM_DELETE_WINDOW', win.quit) # завершить и при закрытии окна!\n\n win.focus_set() # принять фокус ввода,\n win.grab_set() # запретить доступ к др. окнам, пока открыт диалог\n win.mainloop() # и запустить вложенный цикл обр. событий для ожидания\n win.destroy()\n print('dialog exit')\n\n\nroot = Tk()\nButton(root, text='popup', command=dialog).pack()\nroot.mainloop()\n","sub_path":"Gui/Tour/dlg-recursive.py","file_name":"dlg-recursive.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"427750803","text":"TITLE = u\"GISTS\"\nAPPS = (\n 'main',\n 'gists',\n)\n\nLOGIN_URL = \"/auth/login/\"\nCOOKIE_SECRET = \"Y2o1TzK2YQAGEYdkL5gmueJIFuY37EQm92XsTo1v/Wi=\"\n\nWEBMASTER = 'peterbe@gmail.com'\nADMIN_EMAILS = ['peterbe@gmail.com']\n\n#TWITTER_CONSUMER_KEY = ''\n#TWITTER_CONSUMER_SECRET = open('twitter_consumer_secret').read().strip()\n\nDEFAULT_DATABASE_NAME = 'gists'\n\noauth_settings = {\n 'client_id': '1ccb7f00082bc45047e7',\n 'client_secret': open('github_client_secret').read().strip(),\n 'base_url': 'https://github.com/login/oauth/',\n 'redirect_url': 'http://www.peterbe.com/tornadogists/callback' # can this be localhost:8000/...?\n #'redirect_url': 'http://localhost:8000/auth/github/',\n}","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"347584050","text":"from Utilities.PrimeGenerator import totient\n\n\ndef main():\n max_found = None\n max_value = -1\n for i in range(1, 1000001):\n phi = totient(i)\n if i * 1.0 / phi > max_value:\n max_found = i\n max_value = i * 1.0 / phi\n\n print(max_found)\n\nif __name__ == '__main__':\n main()\n","sub_path":"python35/solutions/Problem069.py","file_name":"Problem069.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"36487740","text":"#!/usr/bin/env python\n\n#CONTROLLER TEST\n\n'''\n\nTHE READING IN OF SERVO POSITION IS INSANLY SLOW!\nI don't know how to fix it but it does need to be fixed.\n\nIF someone gets it working it means that we have a lot more options\navailable to do even more cool stuff. : )\n\n'''\n\nfrom emuBot import *\nfrom controller import *\nimport time\n\n# for camera\nimport picamera\nimport os\nimport subprocess\n\n#initialise emuBot ... functions in emuBot.py\n\n#Wheels are 1,2,3,4\nwheelMode(1) \nwheelMode(2)\nwheelMode(3)\nwheelMode(4)\n\n#Joints are 5,6,7, 8\njointMode(5) #Limit 200 to 800 (512 is middle)\njointMode(6) #Limit 50 to 970 (650 if ID:5 is 200)\njointMode(7) #Limit 200 to 800\njointMode(8) #Limit above 512\n\n\n#start controller ... functions in controller.py\ngamepad = start_controller()\n\nslowed = False\n\n# servos:[position, min, max, moving]\nposes = {1:[0, 0, 0, False], 2:[0, 0, 0, False], 3:[0, 0, 0, False], 4:[0, 0, 0, False], 5:[201, 200, 950, False], 6:[51, 50, 970, False], 7:[512, 200, 800, False], 8:[530, 529, 1023, False]}\n# servos:[default position]\ndefaultPos = {1:[0], 2:[0], 3:[0], 4:[0], 5:[201], 6:[51], 7:[512], 8:[530]}\n\n# Camera settings (not all are necessary)\ncamera = picamera.PiCamera()\ncamera.preview_fullscreen = False\ncamera.preview_window = (600, 320, 640, 480)\ncamera.resolution = (640, 480)\n\ncamera.sharpness = 10\ncamera.contrast = 30\ncamera.vflip = True\ncamera.hflip = True\ncamera.exposure_mode = \"auto\"\ncamera.brightness = 60\n\ndef startCamera():\n print(\"Camera started\")\n camera.start_preview()\n \n '''\n fps = 5\n clientIP = \"192.168.100.117\"\n port = 5000\n height = 360\n width = 640\n time = 0\n start_command = \"/opt/vc/bin/raspivid -vf -fps %s -o - -w %s -h %s -t %s | nc.traditional %s %s\" % (fps, width, height, time, clientIP, port)\n subprocess.call(start_command, shell = True)'''\n\ndef stopCamera():\n camera.stop_preview()\n camera.close()\n print(\"Camera stopped\")\n \n '''\n os.system(\"killall -9 raspivid\")\n os.system(\"killall -9 netcat\")'''\n\ndef start_pos():\n ready = True\n print(\"Moving to start positions...\")\n for i in range(5, 9):\n moveJoint(i, defaultPos[i][0], 100)\n '''# checking if Emubot is ready\n if readDxl(i, \"j\") != defaultPos[i][0]:\n ready = False\n else:\n ready = True\n\n if ready == True:\n print(\"EmuBot ready...\")\n else:\n print(\"not ready\")'''\n \n print(\"EmuBot ready...\")\n\nstart_pos()\n\ndef stop(ID):\n print(\"stopping servo\")\n #moveJoint(ID, 512, 0)\n # setting joint to speed: 0, results in it going at its maximum speed\n\ndef changePos(ID, incriment, speed):\n maxx = poses[ID][2]\n minn = poses[ID][1]\n poses[ID][0] = int(poses[ID][0]) + incriment\n\n # checking for min/max ranges\n if poses[ID][0] < minn:\n poses[ID][0] = minn\n \n elif poses[ID][0] > maxx:\n poses[ID][0] = maxx\n\n # moving servo\n moveJoint(ID, poses[ID][0], speed)\n\ndef continueMovingToPos(ID, speed, started):\n poses[ID][3] = started\n if poses[ID][3] == True:\n changePos(ID, 2, 25)\n\ndef move(speed, direction, slowed):\n if speed > 1000:\n speed = 1000\n if slowed == True:\n speed = speed/2\n if speed > 200:\n if direction == 'forward' or direction == 'back':\n if direction == 'back':\n speed = -speed\n moveWheel(1, speed)\n moveWheel(2, -speed)\n moveWheel(3, -speed)\n moveWheel(4, speed)\n else:\n if direction == 'left':\n speed = -speed\n for i in range(1, 5):\n moveWheel(i, speed)\n else:\n for i in range(1, 5):\n moveWheel(i, speed)\n\ndef leftTurn(speed):\n moveWheel(2, speed)\n moveWheel(3, speed)\n\ndef rightTurn(speed):\n moveWheel(1, speed)\n moveWheel(4, speed)\n\nfor event in gamepad.read_loop():\n # ---------- TRIGGERS ----------\n # ----- Right Trigger -----\n if event.code == 5:\n leftTurn(-((event.value*1000)/255))\n \n # ----- Left Trigger -----\n elif event.code == 2:\n rightTurn(((event.value*1000)/255))\n\n # ---------- BUMPERS ----------\n if event.type == ecodes.EV_KEY:\n keyevent = categorize(event)\n if keyevent.keystate == KeyEvent.key_down:\n if event.code == 311:\n leftTurn(1000)\n elif event.code == 310:\n rightTurn(-1000)\n else:\n if event.code == 311:\n leftTurn(0)\n elif event.code == 310:\n rightTurn(0) \n \n # ---------- THUMBSTICKS ----------\n # ----- Right Stick ----- Up/Down\n if event.code == 4:\n if event.value > 1000:\n move((event.value/30), 'back', slowed)\n if event.value < -1000:\n move((-event.value/30), 'forward', slowed)\n\n # ----- Right Stick ----- Left/Right\n elif event.code == 3:\n if event.value > 1000:\n move((event.value/30), 'right', slowed)\n if event.value < -1000:\n move((-event.value/30), 'left', slowed)\n\n # ----- Left Stick -----\n '''elif event.code == 1:\n # check out event.code == 0 \n # --- Move the camera ---\n if event.value < 10000 and event.value > 500:\n #Camera Left\n moveJoint(7, 700, 100)\n \n elif event.value < -500 and event.value > -10000:\n #Camera Right\n moveJoint(7, 200, 100)\n \n elif event.value > -500 and event.value < 500:\n #Camera Centre\n moveJoint(7,512,100)\n \n # --- Tilt the camera ---\n elif event.value > 10000:\n moveJoint(7, 650, 100)\n elif event.value < -10000:\n moveJoint(7, 200, 100)\n elif event.value < 10000 and event.value > -10000:\n moveJoint(7, 512, 100)'''\n\n # ---------- BUTTONS ----------\n \n if event.type == ecodes.EV_KEY:\n keyevent = categorize(event)\n if keyevent.keystate == KeyEvent.key_down:\n print(keyevent.keycode)\n # --- Servo 5 ---\n if keyevent.keycode == \"BTN_Y\": # up\n changePos(5, 8, 25)\n elif keyevent.keycode[0] == \"BTN_A\": # down\n changePos(5, -8, 25)\n\n # --- Servo 8 ---\n if keyevent.keycode == \"BTN_X\": # up\n changePos(8, 8, 25)\n elif keyevent.keycode == \"BTN_B\": # down\n changePos(8, -8, 25)\n\n # --- Home button ---\n if keyevent.keycode == \"BTN_MODE\": # logitech button\n start_pos()\n\n # --- camera ---\n if keyevent.keycode == \"BTN_START\": # start button\n try:\n startCamera()\n except:\n print(\"Camera couldn't start\")\n elif keyevent.keycode == \"BTN_SELECT\": # back button\n try:\n stopCamera()\n except:\n print(\"Camera couldn't stop\")\n \n elif keyevent.keystate == KeyEvent.key_up:\n # --- Servo 5 ---\n if keyevent.keycode == \"BTN_Y\": # up\n changePos(5, 8, 25)\n if keyevent.keycode[0] == \"BTN_A\": # down\n changePos(5, -8, 25)\n\n # --- Servo 8 ---\n if keyevent.keycode == \"BTN_X\": # up\n changePos(8, 8, 25)\n if keyevent.keycode == \"BTN_B\": # down\n changePos(8, -8, 25)\n \n # ----- Arrows -----\n if event.code == 17:\n # --- Down ---\n if event.value == 1:\n changePos(6, 15, 25)\n\n # --- Up ---\n elif event.value == -1:\n changePos(6, -15, 25)\n \n if event.code == 16:\n # --- Right ---\n if event.value == 1:\n changePos(7, -15, 25)\n\n # --- Left ---\n elif event.value == -1:\n changePos(7, 15, 25)\n\n # ----- Back Button -----\n '''\n if event.code == 314:\n start_pos()\n '''\n\n\n\n'''\nHow to deal with buttons when reading position is faster:\n\nif blah blah blah\n moveJoint(ID, readDxl(ID, \"j\") + 15, 100)\n'''\n\n\n\n","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":8196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"646864478","text":"#!/usr/bin/env python\n\n#python imports\nimport subprocess\nimport os\n\n#ros imports\nimport rospy\nfrom std_msgs.msg import Int32\n\nclass TemperatureMonitor():\n def __init__(self):\n \n rospy.init_node(\"temperature_monitor\")\n\n # Settings\n self.path_to_cpu_temperature_meter = rospy.get_param(\"/temperature/logging/paths/cpu\")\n self.path_to_gpu_temperature_meter = rospy.get_param(\"/temperature/logging/paths/gpu\")\n self.interval = rospy.get_param(\"/temperature/logging/interval\") # How often the battery level is checked and published\n \n # Publisher\n self.cpu_temperature_pub = rospy.Publisher(\"/auv/temperature/cpu\", Int32, queue_size=1)\n self.gpu_temperature_pub = rospy.Publisher(\"/auv/temperature/gpu\", Int32, queue_size=1)\n \n # Main loop\n while not rospy.is_shutdown():\n\n self.measure_temp()\n self.cpu_temperature_pub.publish(self.cpu_temperature)\n self.gpu_temperature_pub.publish(self.gpu_temperature)\n\n rospy.sleep(self.interval)\n\n def measure_temp(self):\n\n # Record output from temperature meter command, decode from bytes object to string, convert from string to integer\n self.cpu_temperature = int(subprocess.check_output([\"cat\", self.path_to_cpu_temperature_meter]).decode(\"utf-8\"))\n self.gpu_temperature = int(subprocess.check_output([\"cat\", self.path_to_gpu_temperature_meter]).decode(\"utf-8\"))","sub_path":"mission/internal_status/src/temperature_monitor.py","file_name":"temperature_monitor.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"117757404","text":"print(\"업무1\")\n# f = open('나있는파일','r')\ntry:\n f = open('나없는파일','r')\n print(\"업무2\")\nexcept FileNotFoundError:\n print(\"\"\"\n[알림]\n'나없는파일'은 존재하지 않습니다.\n정상 수행을 위해 파일을 준비하세요.\n\"\"\")\nprint(\"프로그램 정상 종료.\")\n","sub_path":"01_Jump_to_Python/Chap05/229_Except_type2.py","file_name":"229_Except_type2.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"40569329","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Apr 24 20:12:20 2020\r\n\r\n@author: ANKUR\r\n\"\"\"\r\n\r\nfrom nltk.corpus import stopwords \r\nfrom nltk.stem import WordNetLemmatizer\r\nimport numpy\r\nfrom numpy import linalg as LA\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import style\r\nstyle.use(\"ggplot\")\r\nfrom sklearn.cluster import KMeans\r\nfrom scipy.spatial import distance\r\nimport math\r\nimport numpy as np\r\nimport sklearn.metrics.pairwise\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nimport statistics\r\nfrom statistics import mean\r\n\r\n\r\n\r\n\r\nf=open(\"C:\\\\Users\\\\ANKUR\\\\Desktop\\\\FINAL_YR_PROJECT\\\\FINAL_PROJECT\\\\PEARSON\\\\ankur.txt\", 'r', errors='ignore')\r\n#C:\\\\Users\\\\ANKUR\\\\MEDLINE(ORIGINAL,CONCEPTS)\\\\megha.txt\"\r\npunct = '''!()-[]{};:'\\,<>/=?\"@#$%^&*_~'''\r\nstop_words = set(stopwords.words('english'))\r\n\r\n#taking all sentences in an array\r\narr=[]\r\nfor line in f:\r\n for i in line.split(\". \"):\r\n arr.append(i)\r\nf.close()\r\n\r\n'''\r\n#printing the lines\r\nfor i in arr:\r\n print(i)\r\n print(arr.index(i))\r\n print(\"-----------------------------------------------\\n\")\r\n\r\n'''\r\n\r\n'''\r\n#taking all words in a single array\r\nwordvocab=[]\r\nfor each_sentence in arr:\r\n for each_word in each_sentence.split():\r\n wordvocab.append(each_word)\r\n\r\n#removng punctuation except \".\" \r\npunctremoved=[]\r\nfor a in wordvocab:\r\n c=\"\"\r\n for b in a:\r\n if b not in punct:\r\n c= c+b\r\n punctremoved.append(c.lower()) \r\n'''\r\n\r\n\r\n#other way---> first removing the punctuation from the sentences\r\nremoved=[]\r\nfor each in arr:\r\n x=\"\"\r\n for i in each:\r\n if i not in punct:\r\n x=x+i\r\n removed.append(x.lower()) \r\n\r\n#removing stopwords\r\nfiltered_sentences=[]\r\nfor sentence in removed:\r\n #print(sentence)\r\n filtered=[]\r\n for word in sentence.split():\r\n if not word in stop_words:\r\n filtered.append(word)\r\n filtered_sentences.append(filtered) \r\n\r\n#lemmatizing:\r\ntrain_vocab=[]\r\nlemmatizer=WordNetLemmatizer()\r\nfor each_list in filtered_sentences:\r\n vocabulary=[]\r\n for each_word in each_list:\r\n vocabulary.append(lemmatizer.lemmatize(each_word))\r\n train_vocab.append(vocabulary) \r\n \r\n#word to vector conversion\r\nfrom gensim.models import Word2Vec\r\nmodel= Word2Vec(train_vocab, min_count=1) #train model\r\nprint(\"The model is :\\n\", (model)) #summarize the loaded model \r\ndim=len(model[word])\r\nall_words = list(model.wv.vocab) #summarize vocabulary\r\n\r\n#access vector for one word\r\n#print(model['oral'])\r\n#reference: https://machinelearningmastery.com/develop-word-embeddings-python-gensim/\r\n\r\n\r\n#converting each sentence in vector form\r\nsummation=[]\r\nvectorized=[]\r\nfor sentence in train_vocab: \r\n # sum=np.zeros(100)\r\n sum=np.zeros(dim)\r\n for word in sentence:\r\n sum= sum + model[word]\r\n avg= sum/len(sentence)\r\n summation.append(sum)\r\n vectorized.append(avg) \r\n\r\n''' \r\n#writing into csv file:\r\nimport csv\r\nwith open('cluster.csv','wb') as file:\r\n for i in range(0, len(vectorized)):\r\n np.savetxt(file, [vectorized[i]],delimiter= ',', fmt='%f')\r\n'''\r\n\r\n#applying k-means\r\nfreq=[0]* len(train_vocab)\r\nk=math.ceil(0.4 * len(arr))\r\n#k=7\r\nx= np.array(vectorized)\r\n\r\nfor t in range(0, 50):\r\n \r\n kmeans= KMeans(n_clusters= k)\r\n kmeans.fit(x)\r\n\r\n centroids= kmeans.cluster_centers_\r\n labels= kmeans.labels_\r\n\r\n # print (\"centroids are: \", centroids)\r\n #print(\"labels are: \", labels)\r\n\r\n#forming lists of clusters:\r\n all_clusters=[]\r\n for i in range(0, kmeans.n_clusters):\r\n cluster=[]\r\n counter=0\r\n for j in range(len(x)):\r\n if labels[j]==i:\r\n cluster.append(x[j])\r\n # cluster.append(vectorized[counter])\r\n # counter=counter+1 \r\n all_clusters.append(cluster) \r\n#print(all_clusters[0][0])\r\n #print(len(all_clusters))\r\n #print(len(all_clusters[0]))\r\n #print(len(all_clusters[1]))\r\n #print(len(all_clusters[2]))\r\n\r\n\r\n#calculating the distances of the vectors(points) from the cluster centroids:\r\n represent=[]\r\n#for i in range(0, kmeans.n_clusters):\r\n for i in range(len(all_clusters)):\r\n #len(all_clusters):\r\n # s=[]\r\n # r=[]\r\n s=numpy.array(centroids[i])\r\n # min=distance.euclidean(all_clusters[i][0], centroids[i])\r\n r=numpy.array(all_clusters[i][0])\r\n sum1=0\r\n sum2=0\r\n m_r=mean(r)\r\n m_s=mean(s)\r\n for u in range(0, dim):\r\n sum1+=(r[u]-m_r)*(s[u]-m_s)\r\n sum2+=math.sqrt((r[u]-m_r)**2) * math.sqrt((s[u]-m_s)**2)\r\n max=sum1/sum2 \r\n ind=0\r\n p=len(all_clusters[i])\r\n for j in range(1, p):\r\n r=numpy.array(all_clusters[i][j])\r\n m_r=mean(r)\r\n sum1=0\r\n sum2=0\r\n for u in range(0, dim):\r\n sum1+=(r[u]-m_r)*(s[u]-m_s)\r\n sum2+=math.sqrt((r[u]-m_r)**2) * math.sqrt((s[u]-m_s)**2)\r\n \r\n d=sum1/sum2\r\n if d > max:\r\n max=d\r\n ind=j\r\n #rep.append(all_clusters[i][ind]) \r\n represent.append(ind)\r\n #print(represent)\r\n \r\n #summary of each iteration:\r\n sentence=[]\r\n for i in range(0, len(represent)):\r\n count=-1\r\n for j in range(0, len(labels)):\r\n if i == labels[j]:\r\n count+=1\r\n if count == represent[i]:\r\n sentence.append(i)\r\n break\r\n \r\n#sentence.sort()\r\n for i in range(0, len(sentence)):\r\n freq[sentence[i]]+= 1\r\n\r\n#final summary sentence index in sum_sent\r\nsum_sent=[]\r\nfor i in range(0, len(train_vocab)):\r\n sum_sent.append(i)\r\nfor i in range(1, len(train_vocab)-1):\r\n for j in range(0, len(train_vocab)-i):\r\n if freq[j] < freq[j+1]:\r\n freq[j], freq[j+1] = freq[j+1], freq[j]\r\n sum_sent[j], sum_sent[j+1] = sum_sent[j+1], sum_sent[j]\r\n\r\nfinal_sent=[]\r\nfor i in range(0, k):\r\n p=sum_sent[i]\r\n final_sent.append(p)\r\nfinal_sent.sort()\r\n \r\nf=open(\"C:\\\\Users\\\\ANKUR\\\\Desktop\\\\FINAL_YR_PROJECT\\\\FINAL_PROJECT\\\\PEARSON\\\\pearson_summary.txt\",\"w+\")\r\nc=0\r\nfor i in range(0, len(arr)):\r\n if i==final_sent[c]:\r\n f.write(arr[i])\r\n f.write(\".\\n\")\r\n #print(arr[i])\r\n c+=1\r\n if c>=len(final_sent):\r\n break\r\nf.close()","sub_path":"pearson.py","file_name":"pearson.py","file_ext":"py","file_size_in_byte":6358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"135026409","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/12/8 19:49\n# @Author : keh123000\n# @Email : 26467568@qq.com\n# @File : manage.py.py\n\nfrom .app import create_app\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=1680)\n","sub_path":"show_data/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"433569188","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\n@file c.py\n@brief \n@date 2018-09-10\n'''\nimport sys\n\n\nif __name__ == '__main__' :\n \n S = input()\n K = int(input())\n\n # Sが1で始まりかつKの長さがまで1が続くようであれば1\n for i in range(0,K):\n if S[i] == '1' and i < K:\n continue\n elif S[i] != '1':\n print(S[i])\n exit()\n print('1')\n \n","sub_path":"Atcoder/ABC106/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"519132726","text":"# Population script for WAD2 project 2018 by Euan McGrevey and Sam Griffin\n\nimport os\nos.environ.setdefault('DJANGO_SETTINGS_MODULE',\n\t\t\t\t\t 'uofgconnect.settings')\n\nimport random\n\nimport django\ndjango.setup()\nfrom social.models import University, College, Subject, Module, UserProfile, Follow, Post, Comment, Notification\nfrom django.contrib.auth.models import User\n\nfrom datetime import date\n\ndef populate():\n\n\tuserdata = [\n\t\t{\n\t\t\t\"fname\": \"John\",\n\t\t\t\"sname\": \"Doe\",\n\t\t\t\"matric\": \"1234567\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Jane\",\n\t\t\t\"sname\": \"Doe\",\n\t\t\t\"matric\": \"2234567\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"John\",\n\t\t\t\"sname\": \"Lennon\",\n\t\t\t\"matric\": \"3234567\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Terence\",\n\t\t\t\"sname\": \"Stephens\",\n\t\t\t\"matric\": \"4234567\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Sally\",\n\t\t\t\"sname\": \"Jones\",\n\t\t\t\"matric\": \"5234567\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Gary\",\n\t\t\t\"sname\": \"Jones\",\n\t\t\t\"matric\": \"6234567\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Sam\",\n\t\t\t\"sname\": \"Griffin\",\n\t\t\t\"matric\": \"2327827\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Euan\",\n\t\t\t\"sname\": \"McGrevey\",\n\t\t\t\"matric\": \"2255355\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Martin\",\n\t\t\t\"sname\": \"Ganly\",\n\t\t\t\"matric\": \"2325580\"\n\t\t},\n\t\t{\n\t\t\t\"fname\": \"Chak\",\n\t\t\t\"sname\": \"Ho\",\n\t\t\t\"matric\": \"2268750\"\n\t\t}\n\t]\n\n\tdata = {\n\t\t\"University of Glasgow\": { # University\n\t\t\t\"logo\": None,\n\t\t\t\"colour\": \"003865\",\n\t\t\t\"email_domain\": \"student.gla.ac.uk\",\n\t\t\t\"colleges\": { # Colleges\n\t\t\t\t\"College of Science and Engineering\": {\n\t\t\t\t\t\"Computing Science\": [ # Subject\n\t\t\t\t\t\t\"Computer Systems 2\", # Module\n\t\t\t\t\t\t\"Java Programming 2\",\n\t\t\t\t\t\t\"Object Oriented Software Engineering\",\n\t\t\t\t\t\t\"Algorithms and Data Structures\"\n\t\t\t\t\t],\n\t\t\t\t\t\"Physics\": [\n\t\t\t\t\t\t\"Programming C under Linux\",\n\t\t\t\t\t\t\"Forces\"\n\t\t\t\t\t],\n\t\t\t\t\t\"Chemistry\": [\n\t\t\t\t\t\t\"Acids\"\n\t\t\t\t\t]\n\t\t\t\t},\n\t\t\t\t\"College of Arts\": {\n\t\t\t\t\t\"Music\": [\n\t\t\t\t\t\t\"Music Theory\",\n\t\t\t\t\t\t\"Music History\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\t\"University of Sussex\": { # University\n\t\t\t\"logo\": None,\n\t\t\t\"colour\": \"003B49\",\n\t\t\t\"email_domain\": \"sussex.ac.uk\",\n\t\t\t\"colleges\": { # Colleges\n\t\t\t\t\"College of Science and Engineering\": {\n\t\t\t\t\t\"Computer Science and Artificial Intelligence\": [ # Subject\n\t\t\t\t\t\t\"Introduction to Programming\", # Module\n\t\t\t\t\t\t\"Mathematical Concepts\",\n\t\t\t\t\t\t\"Programming Concepts\",\n\t\t\t\t\t\t\"Computer Vision\",\n\t\t\t\t\t\t\"Intelligence in Animals and Machines\"\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\tfor uni, uni_data in data.items():\n\t\tu = add_uni(uni, uni_data['colour'], uni_data['email_domain'])\n\n\t\tuni_users = []\n\n\t\tfor x in range(random.randint(1, len(userdata))): # Will create at least one user at each university\n\t\t\tudata = random.choice(userdata); # Chooses data at random\n\n\t\t\t# Note: deliberately able to have 2 users with the same name, like the real world\n\t\t\tprint(\"Creating user: \" + udata['fname'] + \" \" + udata['sname'])\n\t\t\tuser = User.objects.create_user(udata['matric'] + str(x) + uni_data['email_domain'], udata['matric'] + \"@\" + uni_data['email_domain'], \"password\")\n\t\t\tuser.first_name = udata['fname']\n\t\t\tuser.last_name = udata['sname']\n\t\t\tuser.save()\n\n\t\t\tup = UserProfile.objects.get_or_create(user=user, university=u, dob=date(random.randint(1990,2018), random.randint(1,12), random.randint(1,28)))[0]\n\t\t\tup.save()\n\n\t\t\tuni_users.append(user)\n\n\t\tfor college, subjects in uni_data['colleges'].items():\n\t\t\tc = add_col(college, u)\n\n\t\t\tfor subject, modules in subjects.items():\n\t\t\t\ts = add_sub(subject, c)\n\n\t\t\t\tfor module in modules:\n\t\t\t\t\tm = add_module(module, s)\n\n\t\t\t\t\tnum_followers = random.randint(1, len(uni_users))\n\t\t\t\t\tprint(\"Adding \" + str(num_followers) + \" follower(s) for \" + m.name)\n\t\t\t\t\tfor x in range(num_followers):\n\t\t\t\t\t\tf = Follow.objects.get_or_create(user=random.choice(uni_users), module=m)[0]\n\t\t\t\t\t\tf.save()\n\n\n\t# Now to create some dummy people and posts\n\n\t# users = None\n\ndef add_module(name, sub):\n\tprint(\"Creating module: \" + name)\n\tm = Module.objects.get_or_create(subject=sub, name=name)[0]\n\tm.save()\n\treturn m\n\ndef add_sub(name, college):\n\tprint(\"Creating subject: \" + name)\n\ts = Subject.objects.get_or_create(name=name, college=college)[0]\n\ts.save()\n\treturn s\n\ndef add_col(name, uni):\n\tprint(\"Creating college: \" + name)\n\tc = College.objects.get_or_create(name=name, university=uni)[0]\n\tc.save()\n\treturn c\n\ndef add_uni(name, colour, domain, logo=None):\n\tprint(\"Creating university: \" + name)\n\tu = University.objects.get_or_create(name=name, colour=colour, email_domain=domain, logo=logo)[0]\n\tu.save()\n\treturn u\n\n\n\n\n# Execution\nif __name__ == '__main__':\n\tprint(\"Starting population script...\")\n\tpopulate()\n\tprint(\"Population script complete\")\n","sub_path":"population_script.py","file_name":"population_script.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"496651251","text":"#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport getpass\nimport json\nimport logging\nimport time\nfrom datetime import datetime\nfrom types import TracebackType\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple, Type, Union\n\nfrom pyre_extensions import none_throws\nfrom torchx.runner.events import log_event\nfrom torchx.schedulers import get_schedulers\nfrom torchx.schedulers.api import Scheduler\nfrom torchx.specs.api import (\n AppDef,\n AppDryRunInfo,\n AppHandle,\n AppStatus,\n RunConfig,\n SchedulerBackend,\n UnknownAppException,\n from_function,\n make_app_handle,\n parse_app_handle,\n runopts,\n)\nfrom torchx.specs.finder import get_component\n\n\nlogger: logging.Logger = logging.getLogger(__name__)\n\n\nNONE: str = \"\"\n\n# Unique identifier of the component, can be either\n# component name, e.g.: utils.echo or path to component function:\n# /tmp/foobar.py:component\nComponentId = str\n\n\nclass Runner:\n \"\"\"\n Torchx individual component runner. Has the methods for the user to\n act upon ``AppDefs``. The ``Runner`` will cache information about the\n launched apps if they were launched locally otherwise it's up to the\n specific scheduler implementation.\n \"\"\"\n\n def __init__(\n self,\n name: str,\n schedulers: Dict[SchedulerBackend, Scheduler],\n ) -> None:\n \"\"\"\n Creates a new runner instance.\n\n Args:\n name: the human readable name for this session. Jobs launched will\n inherit this name.\n schedulers: a list of schedulers the runner can use.\n \"\"\"\n if \"default\" not in schedulers:\n raise ValueError(\n f\"A `default` scheduler is required. Provided schedulers: {schedulers.keys()}\"\n )\n self._name: str = name\n self._schedulers = schedulers\n self._apps: Dict[AppHandle, AppDef] = {}\n\n def __enter__(self) -> \"Runner\":\n return self\n\n def __exit__(\n self,\n type: Optional[Type[BaseException]],\n value: Optional[BaseException],\n traceback: Optional[TracebackType],\n ) -> bool:\n # This method returns False so that if an error is raise within the\n # ``with`` statement, it is reraised properly\n # see: https://docs.python.org/3/reference/compound_stmts.html#with\n # see also: torchx/runner/test/api_test.py#test_context_manager_with_error\n #\n self.close()\n return False\n\n def close(self) -> None:\n \"\"\"\n Closes this runner and frees/cleans up any allocated resources.\n Transitively calls the ``close()`` method on all the schedulers.\n Once this method is called on the runner, the runner object is deemed\n invalid and any methods called on the runner object as well as\n the schedulers associated with this runner have undefined behavior.\n It is ok to call this method multiple times on the same runner object.\n \"\"\"\n\n for name, scheduler in self._schedulers.items():\n scheduler.close()\n\n def run_component(\n self,\n component_name: ComponentId,\n app_args: List[str],\n scheduler: SchedulerBackend = \"default\",\n cfg: Optional[RunConfig] = None,\n dryrun: bool = False,\n # pyre-ignore[24]: Allow generic AppDryRunInfo\n ) -> Union[AppHandle, AppDryRunInfo]:\n \"\"\"Resolves and runs the application in the specified mode.\n\n Retrieves application based on ``component_name`` and runs it in the specified mode.\n\n The ``component_name`` has the following resolution order(from high-pri to low-pri):\n * User-registered components. Users can register components via\n https://packaging.python.org/specifications/entry-points/. Method looks for\n entrypoints in the group ``torchx.components``.\n * Builtin components relative to `torchx.components`. The path to the component should\n be module name relative to `torchx.components` and function name in a format:\n ``$module.$function``.\n * File-based components in format: ``$FILE_PATH:FUNCTION_NAME``. Both relative and\n absolute paths supported.\n\n Usage:\n\n ::\n\n runner.run_component(\"distributed.ddp\", ...) - will be resolved to\n ``torchx.components.distributed`` module and ``ddp`` function.\n\n\n runner.run_component(\"~/home/components.py:my_component\", ...) - will be resolved to\n ``~/home/components.py`` file and ``my_component`` function.\n\n Args:\n component_name: The name of the component to lookup\n app_args: Arguments of the component function\n scheduler: Scheduler to execute component\n cfg: Scheduler run configuration\n dryrun: If True, the will return ``torchx.specs.AppDryRunInfo``\n\n\n Returns:\n An application handle that is used to call other action APIs on the app, or ````\n if it dryrun specified.\n\n Raises:\n `ComponentValidationException`: if component is invalid.\n `ComponentNotFoundException`: if the ``component_path`` is failed to resolve.\n \"\"\"\n component_def = get_component(component_name)\n app = from_function(component_def.fn, app_args)\n if dryrun:\n return self.dryrun(app, scheduler, cfg)\n else:\n return self.run(app, scheduler, cfg)\n\n def run(\n self,\n app: AppDef,\n scheduler: SchedulerBackend = \"default\",\n cfg: Optional[RunConfig] = None,\n ) -> AppHandle:\n \"\"\"\n Runs the given application in the specified mode.\n\n .. note:: sub-classes of ``Runner`` should implement ``schedule`` method\n rather than overriding this method directly.\n\n Returns:\n An application handle that is used to call other action APIs on the app.\n \"\"\"\n\n dryrun_info = self.dryrun(app, scheduler, cfg)\n return self.schedule(dryrun_info)\n\n # pyre-fixme[24]: AppDryRunInfo was designed to work with Any request object\n def schedule(self, dryrun_info: AppDryRunInfo) -> AppHandle:\n \"\"\"\n Actually runs the application from the given dryrun info.\n Useful when one needs to overwrite a parameter in the scheduler\n request that is not configurable from one of the object APIs.\n\n .. warning:: Use sparingly since abusing this method to overwrite\n many parameters in the raw scheduler request may\n lead to your usage of TorchX going out of compliance\n in the long term. This method is intended to\n unblock the user from experimenting with certain\n scheduler-specific features in the short term without\n having to wait until TorchX exposes scheduler features\n in its APIs.\n\n .. note:: It is recommended that sub-classes of ``Session`` implement\n this method instead of directly implementing the ``run`` method.\n\n Usage:\n\n ::\n\n dryrun_info = session.dryrun(app, scheduler=\"default\", cfg)\n\n # overwrite parameter \"foo\" to \"bar\"\n dryrun_info.request.foo = \"bar\"\n\n app_handle = session.submit(dryrun_info)\n\n \"\"\"\n scheduler_backend = none_throws(dryrun_info._scheduler)\n cfg = dryrun_info._cfg\n runcfg = json.dumps(cfg.cfgs) if cfg else None\n with log_event(\"schedule\", scheduler_backend, runcfg=runcfg) as logger_context:\n sched = self._scheduler(scheduler_backend)\n app_id = sched.schedule(dryrun_info)\n app_handle = make_app_handle(scheduler_backend, self._name, app_id)\n app = none_throws(dryrun_info._app)\n self._apps[app_handle] = app\n _, _, app_id = parse_app_handle(app_handle)\n logger_context._torchx_event.app_id = app_id\n return app_handle\n\n def name(self) -> str:\n return self._name\n\n def dryrun(\n self,\n app: AppDef,\n scheduler: SchedulerBackend = \"default\",\n cfg: Optional[RunConfig] = None,\n # pyre-fixme[24]: AppDryRunInfo was designed to work with Any request object\n ) -> AppDryRunInfo:\n \"\"\"\n Dry runs an app on the given scheduler with the provided run configs.\n Does not actually submit the app but rather returns what would have been\n submitted. The returned ``AppDryRunInfo`` is pretty formatted and can\n be printed or logged directly.\n\n Usage:\n\n ::\n\n dryrun_info = session.dryrun(app, scheduler=\"local\", cfg)\n print(dryrun_info)\n\n \"\"\"\n # input validation\n if not app.roles:\n raise ValueError(\n f\"No roles for app: {app.name}. Did you forget to add roles to AppDef?\"\n )\n\n for role in app.roles:\n if not role.entrypoint:\n raise ValueError(\n f\"No entrypoint for role: {role.name}.\"\n f\" Did you forget to call role.runs(entrypoint, args, env)?\"\n )\n if role.num_replicas <= 0:\n raise ValueError(\n f\"Non-positive replicas for role: {role.name}.\"\n f\" Did you forget to set role.num_replicas?\"\n )\n sched = self._scheduler(scheduler)\n sched._validate(app, scheduler)\n dryrun_info = sched.submit_dryrun(app, cfg or RunConfig())\n dryrun_info._scheduler = scheduler\n return dryrun_info\n\n def run_opts(self) -> Dict[str, runopts]:\n \"\"\"\n Returns the ``runopts`` for the supported scheduler backends.\n\n Usage:\n\n ::\n\n local_runopts = session.run_opts()[\"local\"]\n print(\"local scheduler run options: {local_runopts}\")\n\n Returns:\n A map of scheduler backend to its ``runopts``\n \"\"\"\n return {\n scheduler_backend: scheduler.run_opts()\n for scheduler_backend, scheduler in self._schedulers.items()\n }\n\n def scheduler_backends(self) -> List[SchedulerBackend]:\n \"\"\"\n Returns a list of all supported scheduler backends.\n All session implementations must support a \"default\"\n scheduler backend and document what the default\n scheduler is.\n \"\"\"\n return list(self._schedulers.keys())\n\n def status(self, app_handle: AppHandle) -> Optional[AppStatus]:\n \"\"\"\n Returns:\n The status of the application, or ``None`` if the app does not exist anymore\n (e.g. was stopped in the past and removed from the scheduler's backend).\n \"\"\"\n scheduler, scheduler_backend, app_id = self._scheduler_app_id(\n app_handle, check_session=False\n )\n with log_event(\"status\", scheduler_backend, app_id):\n desc = scheduler.describe(app_id)\n if not desc:\n # app does not exist on the scheduler\n # remove it from apps cache if it exists\n # effectively removes this app from the list() API\n self._apps.pop(app_handle, None)\n return None\n\n app_status = AppStatus(\n desc.state,\n desc.num_restarts,\n msg=desc.msg,\n structured_error_msg=desc.structured_error_msg,\n roles=desc.roles_statuses,\n )\n if app_status:\n app_status.ui_url = desc.ui_url\n return app_status\n\n def wait(\n self, app_handle: AppHandle, wait_interval: float = 10\n ) -> Optional[AppStatus]:\n \"\"\"\n Block waits (indefinitely) for the application to complete.\n Possible implementation:\n\n ::\n\n while(True):\n app_status = status(app)\n if app_status.is_terminal():\n return\n sleep(10)\n\n Args:\n app_handle: the app handle to wait for completion\n wait_interval: the minimum interval to wait before polling for status\n\n Returns:\n The terminal status of the application, or ``None`` if the app does not exist anymore\n \"\"\"\n scheduler, scheduler_backend, app_id = self._scheduler_app_id(\n app_handle, check_session=False\n )\n with log_event(\"wait\", scheduler_backend, app_id):\n while True:\n app_status = self.status(app_handle)\n\n if not app_status:\n return None\n if app_status.is_terminal():\n return app_status\n else:\n time.sleep(wait_interval)\n\n def list(self) -> Dict[AppHandle, AppDef]:\n \"\"\"\n Returns the applications that were run with this session mapped by the app handle.\n The persistence of the session is implementation dependent.\n \"\"\"\n with log_event(\"list\"):\n app_ids = list(self._apps.keys())\n for app_id in app_ids:\n self.status(app_id)\n return self._apps\n\n def stop(self, app_handle: AppHandle) -> None:\n \"\"\"\n Stops the application, effectively directing the scheduler to cancel\n the job. Does nothing if the app does not exist.\n\n .. note:: This method returns as soon as the cancel request has been\n submitted to the scheduler. The application will be in a\n ``RUNNING`` state until the scheduler actually terminates\n the job. If the scheduler successfully interrupts the job\n and terminates it the final state will be ``CANCELLED``\n otherwise it will be ``FAILED``.\n\n \"\"\"\n scheduler, scheduler_backend, app_id = self._scheduler_app_id(app_handle)\n with log_event(\"stop\", scheduler_backend, app_id):\n status = self.status(app_handle)\n if status is not None and not status.is_terminal():\n scheduler.cancel(app_id)\n\n def describe(self, app_handle: AppHandle) -> Optional[AppDef]:\n \"\"\"\n Reconstructs the application (to the best extent) given the app handle.\n Note that the reconstructed application may not be the complete app as\n it was submitted via the run API. How much of the app can be reconstructed\n is scheduler dependent.\n\n Returns:\n AppDef or None if the app does not exist anymore or if the\n scheduler does not support describing the app handle\n \"\"\"\n scheduler, scheduler_backend, app_id = self._scheduler_app_id(\n app_handle, check_session=False\n )\n\n with log_event(\"describe\", scheduler_backend, app_id):\n # if the app is in the apps list, then short circuit everything and return it\n app = self._apps.get(app_handle, None)\n if not app:\n desc = scheduler.describe(app_id)\n if desc:\n app = AppDef(name=app_id, roles=desc.roles)\n return app\n\n def log_lines(\n self,\n app_handle: AppHandle,\n role_name: str,\n k: int = 0,\n regex: Optional[str] = None,\n since: Optional[datetime] = None,\n until: Optional[datetime] = None,\n should_tail: bool = False,\n ) -> Iterable[str]:\n \"\"\"\n Returns an iterator over the log lines of the specified job container.\n\n .. note:: #. ``k`` is the node (host) id NOT the ``rank``.\n #. ``since`` and ``until`` need not always be honored (depends on scheduler).\n\n .. warning:: The semantics and guarantees of the returned iterator is highly\n scheduler dependent. See ``torchx.specs.api.Scheduler.log_iter``\n for the high-level semantics of this log iterator. For this reason\n it is HIGHLY DISCOURAGED to use this method for generating output\n to pass to downstream functions/dependencies. This method\n DOES NOT guarantee that 100% of the log lines are returned.\n It is totally valid for this method to return no or partial log lines\n if the scheduler has already totally or partially purged log records\n for the application.\n\n Usage:\n\n ::\n\n app_handle = session.run(app, scheduler=\"local\", cfg=RunConfig())\n\n print(\"== trainer node 0 logs ==\")\n for line in session.log_lines(app_handle, \"trainer\", k=0):\n print(line)\n\n Discouraged anti-pattern:\n\n ::\n\n # DO NOT DO THIS!\n # parses accuracy metric from log and reports it for this experiment run\n accuracy = -1\n for line in session.log_lines(app_handle, \"trainer\", k=0):\n if matches_regex(line, \"final model_accuracy:[0-9]*\"):\n accuracy = parse_accuracy(line)\n break\n report(experiment_name, accuracy)\n\n Args:\n app_handle: application handle\n role_name: role within the app (e.g. trainer)\n k: k-th replica of the role to fetch the logs for\n regex: optional regex filter, returns all lines if left empty\n since: datetime based start cursor. If left empty begins from the\n first log line (start of job).\n until: datetime based end cursor. If left empty, follows the log output\n until the job completes and all log lines have been consumed.\n\n Returns:\n An iterator over the role k-th replica of the specified application.\n\n Raise:\n UnknownAppException: if the app does not exist in the scheduler\n\n \"\"\"\n scheduler, scheduler_backend, app_id = self._scheduler_app_id(\n app_handle, check_session=False\n )\n with log_event(\"log_lines\", scheduler_backend, app_id):\n if not self.status(app_handle):\n raise UnknownAppException(app_handle)\n log_iter = scheduler.log_iter(\n app_id, role_name, k, regex, since, until, should_tail\n )\n return log_iter\n\n def _scheduler(self, scheduler: SchedulerBackend) -> Scheduler:\n sched = self._schedulers.get(scheduler)\n if not sched:\n raise KeyError(\n f\"Undefined scheduler backend: {scheduler}. Use one of: {self._schedulers.keys()}\"\n )\n return sched\n\n def _scheduler_app_id(\n self, app_handle: AppHandle, check_session: bool = True\n ) -> Tuple[Scheduler, str, str]:\n \"\"\"\n Returns the scheduler and app_id from the app_handle.\n Set ``check_session`` to validate that the session name in the app handle\n is the same as this session.\n\n Raises:\n ValueError - if ``check_session=True`` and the session in the app handle\n does not match this session's name\n KeyError - if no such scheduler backend exists\n \"\"\"\n\n scheduler_backend, _, app_id = parse_app_handle(app_handle)\n scheduler = self._scheduler(scheduler_backend)\n return scheduler, scheduler_backend, app_id\n\n def __repr__(self) -> str:\n return f\"Runner(name={self._name}, schedulers={self._schedulers}, apps={self._apps})\"\n\n\ndef get_runner(name: Optional[str] = None, **scheduler_params: Any) -> Runner:\n \"\"\"\n Convenience method to construct and get a Runner object. Usage:\n\n .. code-block:: python\n\n with get_runner() as runner:\n app_handle = runner.run(component(args), scheduler=\"kubernetes\", runcfg)\n print(runner.status(app_handle))\n\n Alternatively,\n\n .. code-block:: python\n\n runner = get_runner()\n try:\n app_handle = runner.run(component(args), scheduler=\"kubernetes\", runcfg)\n print(runner.status(app_handle))\n finally:\n runner.close()\n\n Args:\n name: human readable name that will be included as part of all launched\n jobs.\n scheduler_params: extra arguments that will be passed to the constructor\n of all available schedulers.\n\n\n \"\"\"\n if not name:\n name = f\"torchx_{getpass.getuser()}\"\n\n schedulers = get_schedulers(session_name=name, **scheduler_params)\n return Runner(name, schedulers)\n","sub_path":"torchx/runner/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":20669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"609369613","text":"# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Free University\n# Berlin, 14195 Berlin, Germany.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation and/or\n# other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nr\"\"\"This module provides functions for the coputation of stationary\nvectors of stochastic matrices\n\n.. moduleauthor:: B.Trendelkamp-Schroer \n\n\"\"\"\nfrom __future__ import absolute_import, division\nimport numpy as np\nfrom scipy.linalg import eig, lu_factor, lu_solve\n\n\ndef backward_iteration(A, mu, x0, tol=1e-14, maxiter=100):\n r\"\"\"Find eigenvector to approximate eigenvalue via backward iteration.\n\n Parameters\n ----------\n A : (N, N) ndarray\n Matrix for which eigenvector is desired\n mu : float\n Approximate eigenvalue for desired eigenvector\n x0 : (N, ) ndarray\n Initial guess for eigenvector\n tol : float\n Tolerace parameter for termination of iteration\n\n Returns\n -------\n x : (N, ) ndarray\n Eigenvector to approximate eigenvalue mu\n\n \"\"\"\n T = A - mu * np.eye(A.shape[0])\n \"\"\"LU-factor of T\"\"\"\n lupiv = lu_factor(T)\n \"\"\"Starting iterate with ||y_0||=1\"\"\"\n r0 = 1.0 / np.linalg.norm(x0)\n y0 = x0 * r0\n \"\"\"Local variables for inverse iteration\"\"\"\n y = 1.0 * y0\n r = 1.0 * r0\n for i in range(maxiter):\n x = lu_solve(lupiv, y)\n r = 1.0 / np.linalg.norm(x)\n y = x * r\n if r <= tol:\n return y\n msg = \"Failed to converge after %d iterations, residuum is %e\" % (maxiter, r)\n raise RuntimeError(msg)\n\n\ndef stationary_distribution_from_backward_iteration(P, eps=1e-15):\n r\"\"\"Fast computation of the stationary vector using backward\n iteration.\n\n Parameters\n ----------\n P : (M, M) ndarray\n Transition matrix\n eps : float (optional)\n Perturbation parameter for the true eigenvalue.\n\n Returns\n -------\n pi : (M,) ndarray\n Stationary vector\n\n \"\"\"\n A = np.transpose(P)\n mu = 1.0 - eps\n x0 = np.ones(P.shape[0])\n y = backward_iteration(A, mu, x0)\n pi = y / y.sum()\n return pi\n\n\ndef stationary_distribution_from_eigenvector(T):\n r\"\"\"Compute stationary distribution of stochastic matrix T.\n\n The stationary distribution is the left eigenvector corresponding to the\n non-degenerate eigenvalue :math: `\\lambda=1`.\n\n Input:\n ------\n T : numpy array, shape(d,d)\n Transition matrix (stochastic matrix).\n\n Returns\n -------\n mu : numpy array, shape(d,)\n Vector of stationary probabilities.\n\n \"\"\"\n val, L = eig(T, left=True, right=False)\n\n \"\"\" Sorted eigenvalues and left and right eigenvectors. \"\"\"\n perm = np.argsort(val)[::-1]\n\n val = val[perm]\n L = L[:, perm]\n \"\"\" Make sure that stationary distribution is non-negative and l1-normalized \"\"\"\n nu = np.abs(L[:, 0])\n mu = nu / np.sum(nu)\n return mu\n","sub_path":"msmtools/analysis/dense/stationary_vector.py","file_name":"stationary_vector.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"407400754","text":"class Queue:\n def __init__(self, limit):\n self.que = []\n self.limit = limit\n self.front = None\n self.rear = None\n self.size = 0\n\n def isEmpty(self):\n return self.size <= 0\n\n def enqueue(self, item):\n if self.size >= self.limit:\n self.resize()\n self.que.append(item)\n if self.front == None:\n self.front = self.rear = 0\n else:\n self.rear = self.size\n self.size += 1\n print(\"Queue after enqueue\",self.que)\n\n def dequeue(self):\n if self.size <= 0:\n print(\"Queue underflow\")\n return 0\n else:\n self.que.pop(0)\n self.size -= 1\n if self.size == 0:\n self.front = self.rear = None\n else:\n self.rear = self.size - 1\n print(\"Queue after dequeue\",self.que)\n\n def queueRear(self):\n if self.rear == None:\n print(\"Queue is empty\")\n raise IndexError\n return self.que[self.rear]\n\n def queueFront(self):\n if self.front == None:\n print(\"Queue is empty\")\n raise IndexError\n return self.que[self.front]\n\n def size(self):\n return self.size\n\n def resize(self):\n newQue = list(self.que)\n self.limit = 2*self.limit\n self.que = newQue\n\nque = Queue(5)\nque.enqueue(1)\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\nque.enqueue(2)\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\nque.enqueue(3)\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\nque.enqueue(4)\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\nque.enqueue(5)\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\nque.enqueue(6)\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\nque.dequeue()\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\nque.dequeue()\nprint(\"Front\",que.front)\nprint(\"Rear\",que.rear)\n\n\n\n\n\n\n\n\n","sub_path":"Queue/QueueOperations.py","file_name":"QueueOperations.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"390235366","text":"#!/usr/bin/python\n\nimport math\n\n\ndef recipe_batches(recipe, ingredients):\n \"\"\"\n -Initialize an empty list of possible batches\n -Check if all recipe ingredients are on hand; if not, return 0\n -Compare each corresponding ingredient\n -If ingredients on hand are less than recipe ingredients, return 0\n -Else, divide ingredients on hand by recipe ingredients\n -Append the result to the list of possible batches\n -Return the lowest possible batch\n \"\"\"\n list_batches = []\n r = set(recipe.keys())\n\n for key in r:\n if key not in ingredients:\n return 0\n elif recipe[key] > ingredients[key]:\n return 0\n else:\n result = math.floor(ingredients[key] / recipe[key])\n list_batches.append(result)\n\n return min(list_batches)\n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test\n # your implementation with different inputs\n recipe = {'milk': 100, 'butter': 50, 'flour': 5}\n ingredients = {'milk': 132, 'butter': 50, 'flour': 51}\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(\n batches=recipe_batches(recipe, ingredients), ingredients=ingredients))\n","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"468229946","text":"# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\"\"\"Master Key Providers for use with AWS KMS\"\"\"\nimport abc\nimport functools\nimport logging\n\nimport attr\nimport boto3\nimport botocore.client\nimport botocore.config\nimport botocore.session\nimport six\nfrom botocore.exceptions import ClientError\n\nfrom aws_encryption_sdk.exceptions import (\n ConfigMismatchError,\n DecryptKeyError,\n EncryptKeyError,\n GenerateKeyError,\n MasterKeyProviderError,\n UnknownRegionError,\n)\nfrom aws_encryption_sdk.identifiers import USER_AGENT_SUFFIX\nfrom aws_encryption_sdk.internal.arn import arn_from_str\nfrom aws_encryption_sdk.internal.str_ops import to_str\nfrom aws_encryption_sdk.key_providers.base import MasterKey, MasterKeyConfig, MasterKeyProvider, MasterKeyProviderConfig\nfrom aws_encryption_sdk.structures import DataKey, EncryptedDataKey, MasterKeyInfo\n\n_LOGGER = logging.getLogger(__name__)\n\n_PROVIDER_ID = \"aws-kms\"\n\n\ndef _region_from_key_id(key_id, default_region=None):\n \"\"\"Determine the target region from a key ID, falling back to a default region if provided.\n\n :param str key_id: AWS KMS key ID\n :param str default_region: Region to use if no region found in key_id\n :returns: region name\n :rtype: str\n :raises UnknownRegionError: if no region found in key_id and no default_region provided\n \"\"\"\n try:\n region_name = key_id.split(\":\", 4)[3]\n except IndexError:\n if default_region is None:\n raise UnknownRegionError(\n \"No default region found and no region determinable from key id: {}\".format(key_id)\n )\n region_name = default_region\n return region_name\n\n\n@attr.s(hash=True)\nclass DiscoveryFilter(object):\n \"\"\"DiscoveryFilter to control accounts and partitions that can be used by a KMS Master Key Provider.\n\n :param list account_ids: List of AWS Account Ids that are allowed to be used for decryption\n :param str partition: The AWS partition to which account_ids belong\n \"\"\"\n\n account_ids = attr.ib(\n default=attr.Factory(tuple), hash=True, validator=attr.validators.instance_of(tuple), converter=tuple\n )\n partition = attr.ib(default=None, hash=True, validator=attr.validators.optional(attr.validators.instance_of(str)))\n\n\n@attr.s(hash=True)\nclass KMSMasterKeyProviderConfig(MasterKeyProviderConfig):\n \"\"\"Configuration object for KMSMasterKeyProvider objects.\n\n :param botocore_session: botocore session object (optional)\n :type botocore_session: botocore.session.Session\n :param list key_ids: List of KMS CMK IDs with which to pre-populate provider (optional)\n :param list region_names: List of regions for which to pre-populate clients (optional)\n :param DiscoveryFilter discovery_filter: Filter indicating AWS accounts and partitions whose keys will be trusted\n for decryption\n \"\"\"\n\n botocore_session = attr.ib(\n hash=True,\n default=attr.Factory(botocore.session.Session),\n validator=attr.validators.instance_of(botocore.session.Session),\n )\n key_ids = attr.ib(\n hash=True, default=attr.Factory(tuple), validator=attr.validators.instance_of(tuple), converter=tuple\n )\n region_names = attr.ib(\n hash=True, default=attr.Factory(tuple), validator=attr.validators.instance_of(tuple), converter=tuple\n )\n discovery_filter = attr.ib(\n hash=True, default=None, validator=attr.validators.optional(attr.validators.instance_of(DiscoveryFilter))\n )\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass BaseKMSMasterKeyProvider(MasterKeyProvider):\n \"\"\"Master Key Provider for KMS.\n\n .. note::\n Cannot be instantiated directly. Callers should use one of the implementing classes.\n\n \"\"\"\n\n provider_id = _PROVIDER_ID\n _config_class = KMSMasterKeyProviderConfig\n default_region = None\n\n def __init__(self, **kwargs): # pylint: disable=unused-argument\n \"\"\"Prepares mutable attributes.\"\"\"\n self._regional_clients = {}\n self._process_config()\n\n @abc.abstractmethod\n def validate_config(self):\n \"\"\"Validates the provided configuration.\n\n .. note::\n Must be implemented by specific KMSMasterKeyProvider implementations.\n \"\"\"\n\n def _process_config(self):\n \"\"\"Traverses the config and adds master keys and regional clients as needed.\"\"\"\n self._user_agent_adding_config = botocore.config.Config(user_agent_extra=USER_AGENT_SUFFIX)\n\n self.validate_config()\n\n if self.config.region_names:\n self.add_regional_clients_from_list(self.config.region_names)\n self.default_region = self.config.region_names[0]\n else:\n self.default_region = self.config.botocore_session.get_config_variable(\"region\")\n if self.default_region is not None:\n self.add_regional_client(self.default_region)\n\n if self.config.key_ids:\n self.add_master_keys_from_list(self.config.key_ids)\n\n def _wrap_client(self, region_name, method, *args, **kwargs):\n \"\"\"Proxies all calls to a kms clients methods and removes misbehaving clients\n\n :param str region_name: AWS Region ID (ex: us-east-1)\n :param callable method: a method on the KMS client to proxy\n :param tuple args: list of arguments to pass to the provided ``method``\n :param dict kwargs: dictonary of keyword arguments to pass to the provided ``method``\n \"\"\"\n try:\n return method(*args, **kwargs)\n except botocore.exceptions.BotoCoreError:\n self._regional_clients.pop(region_name)\n _LOGGER.error(\n 'Removing regional client \"%s\" from cache due to BotoCoreError on %s call', region_name, method.__name__\n )\n raise\n\n def _register_client(self, client, region_name):\n \"\"\"Uses functools.partial to wrap all methods on a client with the self._wrap_client method\n\n :param botocore.client.BaseClient client: the client to proxy\n :param str region_name: AWS Region ID (ex: us-east-1)\n \"\"\"\n for item in client.meta.method_to_api_mapping:\n method = getattr(client, item)\n wrapped_method = functools.partial(self._wrap_client, region_name, method)\n setattr(client, item, wrapped_method)\n\n def add_regional_client(self, region_name):\n \"\"\"Adds a regional client for the specified region if it does not already exist.\n\n :param str region_name: AWS Region ID (ex: us-east-1)\n \"\"\"\n if region_name not in self._regional_clients:\n session = boto3.session.Session(botocore_session=self.config.botocore_session)\n client = session.client(\"kms\", region_name=region_name, config=self._user_agent_adding_config)\n self._register_client(client, region_name)\n self._regional_clients[region_name] = client\n\n def add_regional_clients_from_list(self, region_names):\n \"\"\"Adds multiple regional clients for the specified regions if they do not already exist.\n\n :param list region_names: List of regions for which to pre-populate clients\n \"\"\"\n for region_name in region_names:\n self.add_regional_client(region_name)\n\n def _client(self, key_id):\n \"\"\"Returns a Boto3 KMS client for the appropriate region.\n\n :param str key_id: KMS CMK ID\n \"\"\"\n region_name = _region_from_key_id(key_id, self.default_region)\n self.add_regional_client(region_name)\n return self._regional_clients[region_name]\n\n def _new_master_key(self, key_id):\n \"\"\"Returns a KMSMasterKey for the specified key_id.\n\n :param bytes key_id: KMS CMK ID\n :returns: KMS Master Key based on key_id\n :rtype: aws_encryption_sdk.key_providers.kms.KMSMasterKey\n :raises InvalidKeyIdError: if key_id is not a valid KMS CMK ID to which this key provider has access\n :raises MasterKeyProviderError: if this MasterKeyProvider is in discovery mode and key_id is not allowed\n \"\"\"\n _key_id = to_str(key_id) # KMS client requires str, not bytes\n\n if self.config.discovery_filter:\n arn = arn_from_str(_key_id)\n\n if (\n arn.partition != self.config.discovery_filter.partition\n or arn.account_id not in self.config.discovery_filter.account_ids\n ):\n raise MasterKeyProviderError(\"Key {} not allowed by this Master Key Provider\".format(key_id))\n\n return KMSMasterKey(config=KMSMasterKeyConfig(key_id=key_id, client=self._client(_key_id)))\n\n\nclass StrictAwsKmsMasterKeyProvider(BaseKMSMasterKeyProvider):\n \"\"\"Strict Master Key Provider for KMS. It is configured with an explicit list of AWS KMS master keys that\n should be used for encryption in decryption. On encryption, the plaintext will be encrypted with all configured\n master keys. On decryption, the ciphertext will be decrypted with the first master key that can decrypt. If the\n ciphertext is encrypted with a master key that was not explicitly configured, decryption will fail.\n\n >>> import aws_encryption_sdk\n >>> kms_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(key_ids=[\n ... 'arn:aws:kms:us-east-1:2222222222222:key/22222222-2222-2222-2222-222222222222',\n ... 'arn:aws:kms:us-east-1:3333333333333:key/33333333-3333-3333-3333-333333333333'\n ... ])\n\n .. note::\n If no botocore_session is provided, the default botocore session will be used.\n\n .. note::\n If multiple AWS Identities are needed, one of two options are available:\n\n * Additional KMSMasterKeyProvider instances may be added to the primary MasterKeyProvider.\n\n * KMSMasterKey instances may be manually created and added to this KMSMasterKeyProvider.\n\n :param config: Configuration object (optional)\n :type config: aws_encryption_sdk.key_providers.kms.KMSMasterKeyProviderConfig\n :param botocore_session: botocore session object (optional)\n :type botocore_session: botocore.session.Session\n :param list key_ids: List of KMS CMK IDs with which to pre-populate provider (optional)\n :param list region_names: List of regions for which to pre-populate clients (optional)\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Sets configuration required by this provider type.\"\"\"\n super(StrictAwsKmsMasterKeyProvider, self).__init__(**kwargs)\n\n self.vend_masterkey_on_decrypt = False\n\n def validate_config(self):\n \"\"\"Validates the provided configuration.\"\"\"\n if not self.config.key_ids:\n raise ConfigMismatchError(\"To enable strict mode you must provide key ids\")\n\n for key_id in self.config.key_ids:\n if not key_id:\n raise ConfigMismatchError(\"Key ids must be valid AWS KMS ARNs\")\n\n if self.config.discovery_filter:\n raise ConfigMismatchError(\"To enable discovery mode, use a DiscoveryAwsKmsMasterKeyProvider\")\n\n\nclass DiscoveryAwsKmsMasterKeyProvider(BaseKMSMasterKeyProvider):\n \"\"\"Discovery Master Key Provider for KMS. This can only be used for decryption. It is configured with an optional\n Discovery Filter containing AWS account ids and partitions that should be trusted for decryption. If a ciphertext\n was encrypted with an AWS KMS master key that matches an account and partition listed by this provider, decryption\n will succeed. Otherwise, decryption will fail. If no Discovery Filter is configured, the provider will attempt\n to decrypt any ciphertext created by an AWS KMS Master Key Provider.\n\n >>> import aws_encryption_sdk\n >>> kms_key_provider = aws_encryption_sdk.DiscoveryAwsKmsMasterKeyProvider(discovery_filter=DiscoveryFilter(\n ... account_ids=['2222222222222', '3333333333333']\n ... )\n\n .. note::\n If no botocore_session is provided, the default botocore session will be used.\n\n :param config: Configuration object (optional)\n :type config: aws_encryption_sdk.key_providers.kms.KMSMasterKeyProviderConfig\n :param botocore_session: botocore session object (optional)\n :type botocore_session: botocore.session.Session\n :param list key_ids: List of KMS CMK IDs with which to pre-populate provider (optional)\n :param list region_names: List of regions for which to pre-populate clients (optional)\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"Sets configuration required by this provider type.\"\"\"\n super(DiscoveryAwsKmsMasterKeyProvider, self).__init__(**kwargs)\n\n self.vend_masterkey_on_decrypt = True\n\n def validate_config(self):\n \"\"\"Validates the provided configuration.\"\"\"\n if self.config.key_ids:\n raise ConfigMismatchError(\n \"To explicitly identify which keys should be used, use a \" \"StrictAwsKmsMasterKeyProvider.\"\n )\n\n if self.config.discovery_filter:\n if not self.config.discovery_filter.account_ids or not self.config.discovery_filter.partition:\n raise ConfigMismatchError(\n \"When specifying a discovery filter you must include both account ids and \" \"partition\"\n )\n for account in self.config.discovery_filter.account_ids:\n if not account:\n raise ConfigMismatchError(\n \"When specifying a discovery filter, account ids must be non-empty \" \"strings\"\n )\n\n\n@attr.s(hash=True)\nclass KMSMasterKeyConfig(MasterKeyConfig):\n \"\"\"Configuration object for MasterKey objects.\n\n :param str key_id: KMS CMK ID\n :param client: Boto3 KMS client\n :type client: botocore.client.KMS\n :param list grant_tokens: List of grant tokens to pass to KMS on CMK operations\n \"\"\"\n\n provider_id = _PROVIDER_ID\n client = attr.ib(hash=True, validator=attr.validators.instance_of(botocore.client.BaseClient))\n grant_tokens = attr.ib(\n hash=True, default=attr.Factory(tuple), validator=attr.validators.instance_of(tuple), converter=tuple\n )\n\n @client.default\n def client_default(self):\n \"\"\"Create a client if one was not provided.\"\"\"\n try:\n region_name = _region_from_key_id(to_str(self.key_id))\n kwargs = dict(region_name=region_name)\n except UnknownRegionError:\n kwargs = {}\n botocore_config = botocore.config.Config(user_agent_extra=USER_AGENT_SUFFIX)\n return boto3.session.Session(**kwargs).client(\"kms\", config=botocore_config)\n\n\nclass KMSMasterKey(MasterKey):\n \"\"\"Master Key class for KMS CMKs.\n\n :param config: Configuration object (config or individual parameters required)\n :type config: aws_encryption_sdk.key_providers.kms.KMSMasterKeyConfig\n :param bytes key_id: KMS CMK ID\n :param client: Boto3 KMS client\n :type client: botocore.client.KMS\n :param list grant_tokens: List of grant tokens to pass to KMS on CMK operations\n \"\"\"\n\n provider_id = _PROVIDER_ID\n _config_class = KMSMasterKeyConfig\n\n def __init__(self, **kwargs): # pylint: disable=unused-argument\n \"\"\"Performs transformations needed for KMS.\"\"\"\n self._key_id = to_str(self.key_id) # KMS client requires str, not bytes\n\n def _generate_data_key(self, algorithm, encryption_context=None):\n \"\"\"Generates data key and returns plaintext and ciphertext of key.\n\n :param algorithm: Algorithm on which to base data key\n :type algorithm: aws_encryption_sdk.identifiers.Algorithm\n :param dict encryption_context: Encryption context to pass to KMS\n :returns: Generated data key\n :rtype: aws_encryption_sdk.structures.DataKey\n \"\"\"\n kms_params = {\"KeyId\": self._key_id, \"NumberOfBytes\": algorithm.kdf_input_len}\n if encryption_context is not None:\n kms_params[\"EncryptionContext\"] = encryption_context\n if self.config.grant_tokens:\n kms_params[\"GrantTokens\"] = self.config.grant_tokens\n # Catch any boto3 errors and normalize to expected EncryptKeyError\n try:\n response = self.config.client.generate_data_key(**kms_params)\n plaintext = response[\"Plaintext\"]\n ciphertext = response[\"CiphertextBlob\"]\n key_id = response[\"KeyId\"]\n except (ClientError, KeyError):\n error_message = \"Master Key {key_id} unable to generate data key\".format(key_id=self._key_id)\n _LOGGER.exception(error_message)\n raise GenerateKeyError(error_message)\n return DataKey(\n key_provider=MasterKeyInfo(provider_id=self.provider_id, key_info=key_id),\n data_key=plaintext,\n encrypted_data_key=ciphertext,\n )\n\n def _encrypt_data_key(self, data_key, algorithm, encryption_context=None):\n \"\"\"Encrypts a data key and returns the ciphertext.\n\n :param data_key: Unencrypted data key\n :type data_key: :class:`aws_encryption_sdk.structures.RawDataKey`\n or :class:`aws_encryption_sdk.structures.DataKey`\n :param algorithm: Placeholder to maintain API compatibility with parent\n :param dict encryption_context: Encryption context to pass to KMS\n :returns: Data key containing encrypted data key\n :rtype: aws_encryption_sdk.structures.EncryptedDataKey\n :raises EncryptKeyError: if Master Key is unable to encrypt data key\n \"\"\"\n kms_params = {\"KeyId\": self._key_id, \"Plaintext\": data_key.data_key}\n if encryption_context:\n kms_params[\"EncryptionContext\"] = encryption_context\n if self.config.grant_tokens:\n kms_params[\"GrantTokens\"] = self.config.grant_tokens\n # Catch any boto3 errors and normalize to expected EncryptKeyError\n try:\n response = self.config.client.encrypt(**kms_params)\n ciphertext = response[\"CiphertextBlob\"]\n key_id = response[\"KeyId\"]\n except (ClientError, KeyError):\n error_message = \"Master Key {key_id} unable to encrypt data key\".format(key_id=self._key_id)\n _LOGGER.exception(error_message)\n raise EncryptKeyError(error_message)\n return EncryptedDataKey(\n key_provider=MasterKeyInfo(provider_id=self.provider_id, key_info=key_id), encrypted_data_key=ciphertext\n )\n\n def _decrypt_data_key(self, encrypted_data_key, algorithm, encryption_context=None):\n \"\"\"Decrypts an encrypted data key and returns the plaintext.\n\n :param data_key: Encrypted data key\n :type data_key: aws_encryption_sdk.structures.EncryptedDataKey\n :type algorithm: `aws_encryption_sdk.identifiers.Algorithm` (not used for KMS)\n :param dict encryption_context: Encryption context to use in decryption\n :returns: Decrypted data key\n :rtype: aws_encryption_sdk.structures.DataKey\n :raises DecryptKeyError: if Master Key is unable to decrypt data key\n \"\"\"\n edk_key_id = to_str(encrypted_data_key.key_provider.key_info)\n if edk_key_id != self._key_id:\n raise DecryptKeyError(\n \"Cannot decrypt EDK wrapped by key_id={}, because it does not match this \"\n \"provider's key_id={}\".format(edk_key_id, self._key_id)\n )\n\n kms_params = {\"CiphertextBlob\": encrypted_data_key.encrypted_data_key, \"KeyId\": edk_key_id}\n if encryption_context:\n kms_params[\"EncryptionContext\"] = encryption_context\n if self.config.grant_tokens:\n kms_params[\"GrantTokens\"] = self.config.grant_tokens\n # Catch any boto3 errors and normalize to expected DecryptKeyError\n try:\n response = self.config.client.decrypt(**kms_params)\n\n returned_key_id = response[\"KeyId\"]\n if returned_key_id != edk_key_id:\n error_message = \"AWS KMS returned unexpected key_id {returned} (expected {key_id})\".format(\n returned=returned_key_id, key_id=edk_key_id\n )\n _LOGGER.exception(error_message)\n raise DecryptKeyError(error_message)\n plaintext = response[\"Plaintext\"]\n except (ClientError, KeyError):\n error_message = \"Master Key {key_id} unable to decrypt data key\".format(key_id=self._key_id)\n _LOGGER.exception(error_message)\n raise DecryptKeyError(error_message)\n return DataKey(\n key_provider=self.key_provider, data_key=plaintext, encrypted_data_key=encrypted_data_key.encrypted_data_key\n )\n","sub_path":"src/aws_encryption_sdk/key_providers/kms.py","file_name":"kms.py","file_ext":"py","file_size_in_byte":21007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"37024158","text":"from GameState2 import GameState\nfrom Evaluator import Evaluator\n\nclass AiMove():\n\n def predictMove(self,game_state: GameState):\n util_value, prob_state = self.tapToAll(game_state)\n prob_state_iter = prob_state.copy()\n best_util = None;\n\n for iterr in range(0):\n for i in range(len(prob_state_iter)):\n best_util = None\n if util_value[i] is not None:\n util_value2, prob_state2 = self.tapToAll(prob_state_iter[i])\n print(\"iter ke i\",i)\n for y in range(len(util_value2)):\n if util_value2[y] is not None:\n if best_util is None:\n best_util = util_value2[y]\n elif best_util > util_value2[y]:\n best_util = util_value2[y]\n print(\"Minim UTIL kecil\", best_util)\n\n\n if best_util is not None and best_util < util_value[i]:\n print(\"pindah dari \",util_value[i], \" util ke \", best_util)\n util_value[i] = best_util\n prob_state_iter = prob_state2.copy()\n\n # for i\n\n\n best_finger = None\n best_util = None\n for i in range(len(util_value)):\n if util_value[i] is not None:\n if best_util is None:\n best_util = util_value[i]\n best_finger = i\n elif best_util < util_value[i]:\n best_util = util_value[i]\n best_finger = i\n\n\n print(util_value)\n print(\"BEST UTIL \", best_util, \" finger \", best_finger, \" state \", end='')\n prob_state[best_finger].print()\n return best_finger, best_util, prob_state[best_finger]\n\n def tapToAll(self,game_state: GameState):\n self.eval = Evaluator()\n\n player_left = game_state.values[0][0]\n player_right = game_state.values[0][1]\n ai_left = game_state.values[1][0]\n ai_right = game_state.values[1][1]\n\n probability_move = []\n utility_value = [0, 0, 0, 0, 0]\n\n if(game_state.player == 1): #Ai turn\n probability_move.append(\n GameState(0, (player_left + ai_left) % 5, player_right, ai_left, ai_right))\n probability_move.append(\n GameState(0, player_left, (player_right + ai_left) % 5, ai_left, ai_right))\n probability_move.append(\n GameState(0, (player_left + ai_right) % 5, player_right, ai_left, ai_right))\n probability_move.append(\n GameState(0, player_left, (player_right + ai_right) % 5, ai_left, ai_right))\n if ((ai_left + ai_right) % 2 ==0):\n probability_move.append(\n GameState(0, player_left, player_right, int((ai_left + ai_right)/2), int((ai_left + ai_right)/2)))\n else: #Player turn\n probability_move.append(\n GameState(1, player_left, player_right, (player_left + ai_left) % 5,ai_right))\n probability_move.append(\n GameState(1, player_left, player_right, (player_right + ai_left) % 5, ai_right))\n probability_move.append(\n GameState(1, player_left, player_right, ai_left, (player_left + ai_right) % 5))\n probability_move.append(\n GameState(1, player_left, player_right, ai_left, (player_right + ai_right) % 5))\n if ((player_left + player_right) % 2 ==0):\n probability_move.append(\n GameState(1, int((player_left + player_right)/2), int((player_left + player_right)/2), ai_left, ai_right))\n\n for i in range(len(probability_move)):\n print(\"i:\",i ,end=' \\t')\n probability_move[i].print()\n if ai_left == 0:\n utility_value[0] = utility_value[1] = None\n if ai_right == 0:\n utility_value[2] = utility_value[3] = None\n if player_left == 0:\n utility_value[0] = utility_value[2] = None\n if player_right == 0:\n utility_value[1] = utility_value[3] = None\n\n\n if ((ai_left == ai_right) or (((ai_left+ai_right) %2)!=0)) and probability_move[i].player == 0:\n utility_value[4] = None\n if ((player_left == player_right) or ((player_left+player_right) %2) != 0) and probability_move[i].player == 1:\n utility_value[4] = None\n\n if utility_value[i] is not None:\n utility_value[i] = self.eval.evaluate(probability_move[i],1)\n\n print(\"UTILITY \", utility_value)\n\n return utility_value, probability_move\n\n","sub_path":"AiMove10.py","file_name":"AiMove10.py","file_ext":"py","file_size_in_byte":4717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"640881896","text":"import tkinter as tk\n\n\nroot = tk.Tk()\nroot.title(\"Main Window\")\nroot.geometry(\"640x480\")\n\nsub = tk.Toplevel(root)\nsub.transient(root) #Keeps sub window on top of root\nsub.title('Sub Window')\nsub.minsize(320, 240)\nsub.maxsize(320, 240)\n\npos = []\n\ndef main_move(event):\n #When the main window moves, adjust the sub window to move with it\n if pos:\n sub.geometry(\"+{0}+{1}\".format(pos[0], pos[1]))\n # Change pos[0] and pos[1] to defined values (eg 50) for fixed position from main\n\ndef sub_move(event):\n # Set the min values\n min_w = root.winfo_rootx()\n min_h = root.winfo_rooty()\n # Set the max values minus the buffer for window border\n max_w = root.winfo_rootx() + root.winfo_width() - 15\n max_h = root.winfo_rooty() + root.winfo_height() - 35\n\n # Conditional statements to keep sub window inside main\n if event.x < min_w:\n sub.geometry(\"+{0}+{1}\".format(min_w, event.y))\n\n elif event.y < min_h:\n sub.geometry(\"+{0}+{1}\".format(event.x, min_h))\n\n elif event.x + event.width > max_w:\n sub.geometry(\"+{0}+{1}\".format(max_w - event.width, event.y))\n\n elif event.y + event.height > max_h:\n sub.geometry(\"+{0}+{1}\".format(event.x, max_h - event.height))\n\n global pos\n # Set the current sub window position\n pos = [event.x, event.y] \n\nroot.bind('', main_move)\nsub.bind('', sub_move)\n\n\nroot.mainloop()","sub_path":"extra/TKiternal.py","file_name":"TKiternal.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"312294731","text":"import sys\nfrom using_adjacency_list import Vertex, Graph\nfrom queue_implementation import Node, Queue\n\n\ndef UnweightedShortestPath(G, s):\n source = G.getVertex(s)\n source.setDistance(0)\n source.setPrevious(None)\n vertQueue = Queue()\n vertQueue.enQueue(source)\n while (vertQueue.size > 0):\n currentVert = vertQueue.deQueue()\n for nbr in currentVert.getConnections():\n # print(\"The current neighbor distance is: \", nbr.getDistance())\n if nbr.getDistance() == -1:\n # print(\"The vertex \", nbr.getVertexID(), \"distance is: \", currentVert.getDistance())\n nbr.setDistance(currentVert.getDistance() + 1)\n nbr.setPrevious(currentVert)\n vertQueue.enQueue(nbr)\n for v in G.vertDictionary.values():\n print(source.getVertexID(), \" to \", v.getVertexID(), \"-->\", v.getDistance())\n\n\nif __name__ == '__main__':\n G = Graph()\n G.addVertex('A')\n G.addVertex('B')\n G.addVertex('C')\n G.addVertex('D')\n G.addVertex('E')\n G.addVertex('F')\n G.addVertex('G')\n G.addVertex('H')\n G.addVertex('I')\n G.addEdge('A', 'B')\n G.addEdge('A', 'C')\n G.addEdge('A', 'G')\n G.addEdge('A', 'E')\n G.addEdge('B', 'C')\n G.addEdge('C', 'G')\n G.addEdge('D', 'E')\n G.addEdge('D', 'F')\n G.addEdge('F', 'H')\n G.addEdge('E', 'H')\n G.addEdge('H', 'I')\n print('Graph data:')\n print(G.getEdges())\n UnweightedShortestPath(G, 'A')","sub_path":"Algos/graphs/unweighted_shortest_graph.py","file_name":"unweighted_shortest_graph.py","file_ext":"py","file_size_in_byte":1471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"461219145","text":"from tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\n\nroot = Tk()\nroot.title('Currency convertor')\nroot.geometry(\"280x500\")\nroot.config(bg=\"yellow\")\n\n\nimport requests\n\n\n\nmy_notebook = ttk.Notebook(root)\nmy_notebook.place(x=20, y=20)\n\ninformation = requests.get('https://v6.exchangerate-api.com/v6/89dcd9e8cc7777ded2575ce1/latest/ZAR')\ninformation_json = information.json()\n\nconversion_rate = information_json['conversion_rates']\n\ncurrency_frame = Frame(my_notebook, width=480, height=480, bg=\"yellow\")\nconvertor_frame = Frame(my_notebook, width=480, height=480, bg=\"yellow\")\n\ncurrency_frame.pack(fill=\"both\", expand=1)\nconvertor_frame.pack(fill=\"both\", expand=1)\n\nmy_notebook.add(currency_frame, text='currencies')\nmy_notebook.add(convertor_frame, text='conversions')\n\nhome = LabelFrame(currency_frame, text=\"Conversion from ZAR\", bg=\"grey\")\nhome.pack(pady=20)\n\nhome_entry = Entry(home, font=24)\nhome_entry.pack(padx=10, pady=10)\n\nconversion = LabelFrame(currency_frame, text='conversion currency', bg=\"grey\")\nconversion.pack(pady=20)\n\nconvert = Label(conversion, text=\"Convert To:\", font=(\"Arial\", 20))\nconvert.config(bg=\"grey\")\nconvert.pack()\n\nconvert_list = Listbox(conversion, width=20)\nfor i in conversion_rate.keys():\n convert_list.insert(END, str(i))\nconvert_list.pack()\n\nconvert_label = Label(convertor_frame, text=\"Converted to: \", font=(\"Arial\", 20))\nconvert_label.config(bg=\"grey\")\nconvert_label.pack()\n\n\ndef convert_curr():\n try:\n num = float(home_entry.get())\n print(information_json['conversion_rates'][convert_list.get(ACTIVE)])\n ans = num * information_json['conversion_rates'][convert_list.get(ACTIVE)]\n convert_label['text'] = round(ans, 2)\n my_notebook.select(1)\n except ValueError:\n messagebox.showerror(\"error\", \"PLease enter a number\")\n except requests.exceptions.ConnectionError as x:\n messagebox.showerror(\"error\", \"No internet connection\")\n\n\nconvert_btn = Button(currency_frame, command=convert_curr, text=\"Convert\", font=(\"Arial\", 20), width=10)\nconvert_btn.config(bg=\"grey\")\nconvert_btn.pack()\n\n\nroot.mainloop()\n","sub_path":"currency.py","file_name":"currency.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"340835796","text":"import cv2\nimport depthai as dai\nfrom PIL import ImageTk, Image\nfrom datetime import datetime\nimport logging\nfrom openvino.inference_engine import IECore\nfrom time import sleep\nfrom gpiozero import LED, Buzzer\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nfrom aux_constants import colors_hex, colors_bgr, welcome\nfrom aux_constants import multilabel_labels, multilabel_help, multilabel_error\nfrom aux_constants import detection_labels, detection_help, detection_error\nfrom aux_constants import multiclass_labels, multiclass_help, multiclass_error\n\nnumber_of_models = 3\nnumber_of_steps = 8\nnumber_of_messages = [\n len(multilabel_help), len(detection_help), len(multiclass_help)]\n\nstep_validations = {}\nfor step in range(number_of_steps):\n step_validations[str(step)] = 0\n\nmessage_waitings = {}\nfor model in range(number_of_models):\n for message in range(number_of_messages[model]):\n message_waitings[str(model) + str(message)] = 0\n\nwaiting_millis = 3\nwaiting_frames = 20\n\nmin_validations = 20\n\nwelcome_message = welcome\nwelcome_waiting = 0\n\ncurrent_step = 0\ncurrent_model = 0\ncurrent_message = 0\n\nassembly_completed = False\ncompleted_count = 0\n\nparts_counting = True\npart_counts_ok = 0\npart5_max = 4\npart6_max = 1\n\noring_tracking = False\npart4_detected = False\noring_counts_ok = 0\n\nglove_tracking = False\nhand_detected = False\nglove_detected = False\n\noperator_tracking = False\noperator_detected = False\n\nframe_number = 0\n\nprint('[ SVPy ] Spatial Vision Poka-yoke launched')\n\nlogging.basicConfig(format='[ %(levelname)s ] New Image Capture | Frame Count %(message)s | %(asctime)s', level=logging.INFO)\n\nfrom custom_vision_classification import ImageClassification\nfrom custom_vision_detection import ObjectDetection\nfrom aux_classes import Validation\n\ninference_engine = IECore()\nprint('[ SVPy ] OpenVINO Inference Engine created')\n\nglove_class = ImageClassification(inference_engine, 'models/gloves_classification/openvino/', 0.5, 1)\nprint('[ SVPy ] Gloves Classification model loaded')\npart_count = ObjectDetection(inference_engine, 'models/part_count_detection/openvino/', 0.2, 5)\nprint('[ SVPy ] Part Count Detection model loaded')\nmultilabel = ImageClassification(inference_engine, 'models/multilabel_classification/openvino/', 0.5, 3)\nprint('[ SVPy ] Multilabel Classification model loaded')\ndetection = ObjectDetection(inference_engine, 'models/objects_detection/openvino/', 0.5, 5)\nprint('[ SVPy ] Objects Detection model loaded')\nmulticlass = ImageClassification(inference_engine, 'models/multiclass_classification/openvino/', 0.5, 1)\nprint('[ SVPy ] Multiclass Classification model loaded')\npart_4_det = ObjectDetection(inference_engine, 'models/hidden_part_detection/openvino/', 0.5, 1)\nprint('[ SVPy ] Hidden Part Detection model loaded')\noring_class = ImageClassification(inference_engine, 'models/oring_classification/openvino/', 0.5, 1)\nprint('[ SVPy ] O-Ring Classification model loaded')\n\nfrom aux_camera import Camera\n\ncamera = Camera()\nprint('[ SVPy ] Depth AI RGB Camera device created')\n\nled_green = LED(21)\nled_white = LED(16)\nled_red = LED(12)\nled_yellow = LED(1)\nled_blue = LED(8)\n\nleds = [led_green, led_white, led_red, led_yellow, led_blue]\n\nbuzzer = Buzzer(24)\n\nbuzzer_active = False\nbuzzer_final = True\n\ndef leds_loading():\n print('[ SVPy ] LEDs and Buzzer GPIO Pins added')\n sleep(0.50)\n for led in leds:\n led.on()\n sleep(0.25)\n buzzer.on()\n sleep(0.25)\n buzzer.off()\n for led in leds:\n led.off()\n sleep(0.25)\n\nleds_loading()\n\nfrom aux_interface import Window\n\nwindow = Window()\nprint('[ SVPy ] Graphical User Interface loaded')\n\nfrom aux_images import color_images, progress_images\nfrom aux_images import assembly_images, validation_images\nfrom aux_images import completed_image, completed_mask\nfrom aux_images import gloves_image, gloves_mask\nfrom aux_images import caution_image, caution_mask\n\ndef video_streaming():\n global frame_number\n global welcome_message\n global welcome_waiting\n global parts_counting\n global oring_tracking\n global part4_detected\n global oring_counts_ok\n global min_validations\n global glove_tracking\n global hand_detected\n global glove_detected\n global operator_tracking\n global operator_detected\n global assembly_completed\n global completed_count\n\n time_total_start = datetime.now().microsecond\n logging.info(str(frame_number).zfill(6))\n time_inference_start = 0\n time_inference_end = 0\n \n image = camera.Frame\n\n if welcome_waiting > waiting_frames:\n image_crop = image[0:480, 80:560]\n predictions = []\n time_inference_start = datetime.now().microsecond\n if parts_counting:\n predictions = part_count.Infer(image_crop)\n elif oring_tracking:\n predictions = part_4_det.Infer(image_crop)\n if len(predictions) > 0:\n part4_detected = True\n else:\n part4_detected = False\n else:\n if current_model == 0:\n predictions = multilabel.Infer(image_crop)\n elif current_model == 1:\n predictions = detection.Infer(image_crop)\n elif current_model == 2:\n predictions = multiclass.Infer(image_crop)\n if glove_tracking:\n glove_detected = False\n hand_detected = False\n tracking = glove_class.Infer(image_crop)\n if len(tracking) > 0:\n predictions.append(tracking[0])\n if 'Glove' in tracking[0].Label:\n glove_detected = True\n if 'Hand' in tracking[0].Label:\n hand_detected = True\n if operator_tracking:\n tracking = glove_class.Infer(image_crop)\n if len(tracking) > 0:\n predictions.append(tracking[0])\n if 'Negative' in tracking[0].Label:\n operator_detected = False\n else:\n operator_detected = True\n time_inference_end = datetime.now().microsecond\n if parts_counting:\n validations = process_part_count(predictions)\n image = draw_part_count(image, validations)\n window.assembly.config(image=assembly_images[6])\n window.currently.config(text='Part counting detections:')\n elif oring_tracking:\n detections = process_part_4_det(predictions)\n image = draw_detections(image, detections)\n checking_value = 'aux'\n if hand_detected:\n text = 'SAFETY GLOVES ARE NEEDED TO RESUME ASSEMBLY'\n else:\n text = 'INSERT THE BLACK O-RING ON THE GREY ROTOR PART'\n if part4_detected:\n zoom = detections[0].Box\n x1 = int(round(zoom.Left * 480))\n xw = int(round(zoom.Width * 480))\n x2 = x1 + xw\n y1 = int(round(zoom.Top * 480))\n yh = int(round(zoom.Height * 480))\n y2 = y1 + yh\n image_zoom = image_crop[y1:y2, x1:x2]\n if image_zoom.size != 0:\n validations = oring_class.Infer(image_zoom)\n if len(validations) > 0:\n predictions.append(validations[0])\n if 'True' in validations[0].Label:\n color = colors_bgr['yes']\n if glove_detected:\n checking_value = 'yes'\n oring_counts_ok = oring_counts_ok + 1\n if oring_counts_ok > min_validations:\n oring_tracking = False\n glove_tracking = False\n glove_detected = False\n hand_detected = False\n else:\n checking_value = 'no'\n color = colors_bgr['no']\n cv2.putText(image, 'O-Ring', (x1 + 85, y1 + 25), fontFace=cv2.FONT_HERSHEY_DUPLEX, \n fontScale=0.9, thickness=2, color=color, bottomLeftOrigin=False)\n if not hand_detected:\n draw_validation(checking_value)\n led_routing(checking_value)\n window.instruction.config(text=text)\n window.assembly.config(image=assembly_images[4])\n window.currently.config(text='Part 4 + O-Ring detections:')\n else:\n if current_model == 0:\n process_multilabel(predictions)\n elif current_model == 1:\n detections = process_detection(predictions)\n image = draw_detections(image, detections)\n elif current_model == 2:\n process_multiclass(predictions)\n window.assembly.config(image=assembly_images[current_step])\n print_currently(len(predictions))\n if operator_tracking:\n if operator_detected:\n draw_validation('no')\n led_routing('no')\n window.instruction.config(text='CAUTION! THE ASSEMBLY AREA SHOULD BE CLEAR NOW')\n window.assembly.config(image=assembly_images[7])\n window.currently.config(text='Assembly Area detections:')\n print_detections(predictions)\n print_inference_time(time_inference_start, time_inference_end)\n else:\n write_instruction(welcome_message)\n welcome_waiting = welcome_waiting + 1\n if assembly_completed:\n if completed_count < 40:\n completed_count = completed_count + 1\n cv2_array = draw_completed(image)\n else:\n cv2_array = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)\n assembly_completed = False\n operator_tracking = True\n elif operator_tracking:\n if operator_detected:\n cv2_array = draw_caution(image)\n else:\n draw_validation('aux')\n led_routing('aux')\n buzzer_alert_off()\n cv2_array = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)\n elif hand_detected:\n cv2_array = draw_gloves(image)\n else:\n cv2_array = cv2.cvtColor(image, cv2.COLOR_BGR2RGBA)\n pil_image = Image.fromarray(cv2_array)\n image_tk = ImageTk.PhotoImage(image=pil_image)\n window.streaming.image_tk = image_tk\n window.streaming.config(image=image_tk)\n frame_number = frame_number + 1\n print_total_time(time_total_start)\n window.streaming.after(waiting_millis, video_streaming)\n\ndef process_multilabel(predictions):\n global current_message\n global oring_tracking\n global glove_tracking\n global current_step\n global step_validations\n message = multilabel_help[current_message]\n checking_value = 'aux'\n detected_labels = []\n for prediction in predictions:\n detected_labels.append(prediction.Label)\n if current_message != 0:\n if current_message == 1 and multilabel_labels[9] in detected_labels:\n checking_value = 'no'\n message = multilabel_error[0]\n elif multilabel_labels[5] in detected_labels:\n checking_value = 'no'\n message = multilabel_error[1]\n elif multilabel_labels[8] in detected_labels:\n checking_value = 'no'\n message = multilabel_error[2]\n if multilabel_labels[11] in detected_labels:\n message = multilabel_error[3]\n elif len(detected_labels) > 0:\n if current_step == 3:\n condition_1 = multilabel_labels[3] in detected_labels\n condition_2 = multilabel_labels[4] in detected_labels\n if condition_1 and condition_2:\n checking_value = 'yes'\n update_message()\n update_progress()\n # Activate Part 4 + O-Ring Step\n if step_validations['3'] == min_validations:\n oring_tracking = True\n glove_tracking = True\n elif condition_1:\n checking_value = 'aux'\n elif current_step == 4:\n condition_1 = multilabel_labels[6] in detected_labels\n condition_2 = multilabel_labels[7] in detected_labels\n if condition_1 and condition_2:\n checking_value = 'yes'\n update_message()\n update_progress()\n elif condition_1:\n checking_value = 'aux'\n else:\n for label in detected_labels:\n if str(current_step) in label:\n checking_value = 'yes'\n update_message()\n update_progress()\n break\n draw_validation(checking_value)\n led_routing(checking_value)\n write_instruction(message)\n if current_message == 0:\n update_message()\n window.bar_images[0].config(image=color_images[0])\n window.bar_progress[0].config(image=progress_images['aux'])\n if current_message == len(multilabel_help) - 1:\n update_model()\n\ndef process_detection(predictions):\n global current_message\n message = detection_help[current_message]\n checking_value = 'aux'\n selected_predictions = []\n for prediction in predictions:\n if str(current_step) in prediction.Label:\n selected_predictions.append(prediction)\n selected_labels = []\n for prediction in selected_predictions:\n selected_labels.append(prediction.Label)\n if current_message != 0:\n if detection_labels[2] in selected_labels:\n error_predictions = []\n for prediction in selected_predictions:\n if prediction.Label == detection_labels[2]:\n error_predictions.append(prediction)\n break\n selected_predictions = error_predictions\n checking_value = 'no'\n message = detection_error[0]\n if current_step == 5:\n part_labels = 0\n for label in selected_labels:\n if label == detection_labels[1]:\n part_labels = part_labels + 1\n if part_labels == 4:\n checking_value = 'yes'\n update_message()\n update_progress()\n if current_step == 6:\n if detection_labels[4] in selected_labels:\n checking_value = 'yes'\n update_message()\n update_progress()\n draw_validation(checking_value)\n led_routing(checking_value)\n write_instruction(message)\n if current_message == 0:\n update_message()\n if current_message == len(detection_help) - 1:\n update_model()\n return selected_predictions\n\ndef process_multiclass(predictions):\n global current_message\n global current_step\n global current_model\n global assembly_completed\n global operator_tracking\n checking_value = 'aux'\n if current_message == len(multiclass_help):\n current_message = len(multiclass_help) - 1\n current_step = 7\n current_model = 2\n assembly_completed = True\n message = multiclass_help[current_message]\n detected_labels = []\n for prediction in predictions:\n detected_labels.append(prediction.Label)\n if current_message != 0 and current_message != len(multiclass_help) - 1:\n if len(detected_labels) > 0:\n if multiclass_labels[2] in detected_labels:\n checking_value = 'no'\n message = multiclass_error[0]\n elif multiclass_labels[3] in detected_labels:\n checking_value = 'no'\n message = multiclass_error[1]\n elif multiclass_labels[1] in detected_labels:\n checking_value = 'yes'\n update_message()\n if current_message == len(multiclass_help) - 1:\n checking_value = 'yes'\n if assembly_completed:\n checking_value = 'yes'\n if operator_tracking:\n checking_value = 'aux'\n draw_validation(checking_value)\n if not assembly_completed and not operator_tracking:\n led_routing(checking_value)\n write_instruction(message)\n if current_message == 0:\n update_message()\n if current_message == len(multiclass_help) - 1:\n window.bar_images[current_step].config(\n image=color_images[current_step], bg=colors_hex['yes'])\n window.bar_progress[current_step].config(\n image=progress_images['yes'], bg=colors_hex['yes'])\n update_message()\n\ndef process_part_4_det(predictions):\n selected_predictions = []\n for prediction in predictions:\n selected_predictions.append(prediction)\n return selected_predictions\n\ndef process_part_count(predictions):\n global part5_max\n global part6_max\n part5_count = 0\n part6_count = 0\n checking_value = 'aux'\n if len(predictions) > 0:\n predictions = order_predictions(predictions)\n for prediction in predictions:\n if 'False' in prediction.Label:\n checking_value = 'no'\n else:\n if '5.T' in prediction.Label:\n part5_count = part5_count + 1\n elif '6.T' in prediction.Label:\n part6_count = part6_count + 1\n if part5_count > part5_max or part6_count > part6_max:\n checking_value = 'no'\n if part5_count == part5_max and part6_count == part6_max:\n checking_value = 'yes'\n validations = make_validations(predictions)\n draw_validation(checking_value)\n led_routing(checking_value)\n return validations\n\ndef order_predictions(predictions):\n predictions.sort(key=lambda x: x.Box.Top)\n return predictions\n\ndef make_validations(predictions):\n global min_validations\n global parts_counting\n global part_counts_ok\n global part5_max\n global part6_max\n part5_count = 0\n part6_count = 0\n validations = []\n for prediction in predictions:\n color = colors_bgr['aux']\n thickness = 2\n text = ''\n if 'False' in prediction.Label:\n color = colors_bgr['no']\n thickness = 6\n elif 'True' in prediction.Label:\n color = colors_bgr['yes']\n thickness = 4\n if '5' in prediction.Label:\n part5_count = part5_count + 1\n if part5_count > part5_max:\n color = colors_bgr['no']\n text = f'{part5_count}/{part5_max}'\n elif '6' in prediction.Label:\n part6_count = part6_count + 1\n if part6_count > part6_max:\n color = colors_bgr['no']\n text = f'{part6_count}/{part6_max}'\n validation = Validation(prediction.Label, prediction.Score, \n prediction.Box.Left, prediction.Box.Top, prediction.Box.Width, prediction.Box.Height, \n color, thickness, text)\n validations.append(validation)\n part5_total = part5_max - part5_count\n part6_total = part6_max - part6_count\n part5_prefix = ''\n part6_prefix = ''\n if part5_total > 0:\n part5_prefix = '+'\n if part6_total > 0:\n part6_prefix = '+'\n message = f'{part5_prefix}{part5_total} GREEN AND {part6_prefix}{part6_total} ORANGE PARTS NEEDED TO START'\n if part5_count == part5_max and part6_count == part6_max:\n part_counts_ok = part_counts_ok + 1\n else:\n part_counts_ok = 0\n if part_counts_ok == min_validations:\n buzzer_verify()\n parts_counting = False\n window.instruction.config(text=message)\n return validations\n\ndef validate_step():\n global current_step\n global step_validations\n current = str(current_step)\n step_validations[current] = step_validations[current] + 1\n return current\n\ndef update_progress():\n global current_step\n global step_validations\n current = validate_step()\n if step_validations[current] == min_validations:\n buzzer_verify()\n window.bar_images[current_step].config(\n image=color_images[current_step], bg=colors_hex['yes'])\n window.bar_progress[current_step].config(\n image=progress_images['yes'], bg=colors_hex['yes'])\n current_step = current_step + 1\n window.bar_images[current_step].config(\n image=color_images[current_step])\n window.bar_progress[current_step].config(\n image=progress_images['aux'], bg=colors_hex['aux'])\n\ndef wait_message():\n global current_model\n global current_message\n global message_waitings\n current = str(current_model) + str(current_message)\n message_waitings[current] = message_waitings[current] + 1\n return current\n\ndef update_message():\n global message_waitings\n global current_message\n current = wait_message()\n if message_waitings[current] == waiting_frames:\n current_message = current_message + 1\n\ndef update_model():\n global message_waitings\n global current_message\n global current_model\n current = wait_message()\n if message_waitings[current] == waiting_frames:\n current_message = 0\n current_model = current_model + 1\n\ndef print_currently(count):\n if count > 0:\n text = 'Current detections in Step #%s:' % current_step\n else:\n text = 'No objects detected in Step #%s.' % current_step\n window.currently.config(text=text)\n\ndef print_detections(predictions):\n text = ''\n for prediction in predictions:\n text += prediction.__str__() + '\\n'\n window.detections.config(text=text)\n\ndef print_inference_time(start, end):\n ms = (end-start)/1000\n if ms > 0:\n text = 'Infer: {:.1f}ms'.format(ms)\n window.inference.config(text=text)\n\ndef print_total_time(start):\n end = datetime.now().microsecond\n ms = (end-start)/1000\n if ms > 0:\n text = 'Total: {:.1f}ms'.format(ms)\n window.total.config(text=text)\n\ndef write_instruction(message):\n window.instruction.config(text=message)\n\ndef draw_detections(image, predictions):\n for prediction in predictions:\n if 'hole' in prediction.Label:\n image = draw_rectangle(image, prediction.Box, colors_bgr['aux'], 2)\n elif 'part' in prediction.Label:\n image = draw_rectangle(image, prediction.Box, colors_bgr['yes'], 4)\n elif 'error' in prediction.Label:\n image = draw_rectangle(image, prediction.Box, colors_bgr['no'], 6)\n elif 'Part4' in prediction.Label:\n image = draw_rectangle(image, prediction.Box, colors_bgr['aux'], 2)\n return image\n\ndef draw_part_count(image, validations):\n for validation in validations:\n image = draw_rectangle(image, validation.Detection.Box, validation.Color, validation.Thickness)\n x = int(round(validation.Detection.Box.Left * 480))\n y = int(round(validation.Detection.Box.Top * 480))\n cv2.putText(image, validation.Text, (x + 85, y + 25), fontFace=cv2.FONT_HERSHEY_DUPLEX, \n fontScale=0.9, thickness=2, color=validation.Color, bottomLeftOrigin=False)\n return image\n\ndef draw_validation(checking_value):\n window.validation.config(\n image=validation_images[checking_value], bg=colors_hex[checking_value])\n window.assembly.config(bg=colors_hex[checking_value])\n\ndef draw_rectangle(image, box, color, thick):\n x1 = int(round(box.Left * 480 + 80))\n y1 = int(round(box.Top * 480))\n x2 = x1 + int(round(box.Width * 480))\n y2 = y1 + int(round(box.Height * 480))\n cv2.rectangle(image, (x1, y1), (x2, y2), color, thick)\n return image\n\ndef draw_completed(image):\n draw_validation('yes')\n led_green_on()\n buzzer_completed()\n completed = cv2.imread(completed_image)\n mask = cv2.imread(completed_mask, cv2.IMREAD_GRAYSCALE)\n background = cv2.bitwise_or(image, image, mask = mask)\n added_image = cv2.bitwise_or(background, completed)\n cv2_array = cv2.cvtColor(added_image, cv2.COLOR_BGR2RGBA)\n return cv2_array\n\ndef draw_gloves(image):\n draw_validation('no')\n led_blue_on()\n buzzer_gloves()\n gloves = cv2.imread(gloves_image)\n mask = cv2.imread(gloves_mask, cv2.IMREAD_GRAYSCALE)\n background = cv2.bitwise_or(image, image, mask = mask)\n added_image = cv2.bitwise_or(background, gloves)\n cv2_array = cv2.cvtColor(added_image, cv2.COLOR_BGR2RGBA)\n return cv2_array\n\ndef draw_caution(image):\n draw_validation('no')\n led_yellow_on()\n buzzer_alert_on()\n caution = cv2.imread(caution_image)\n mask = cv2.imread(caution_mask, cv2.IMREAD_GRAYSCALE)\n background = cv2.bitwise_or(image, image, mask = mask)\n added_image = cv2.bitwise_or(background, caution)\n cv2_array = cv2.cvtColor(added_image, cv2.COLOR_BGR2RGBA)\n return cv2_array\n\nfrom threading import Thread\n\ndef leds_off():\n for led in leds:\n led.off()\n\ndef led_routing(text: str):\n if text == 'yes':\n led_green_on()\n elif text == 'aux':\n led_white_on()\n elif text == 'no':\n led_red_on()\n\ndef led_green_on():\n leds_off()\n led_green.on()\n\ndef led_white_on():\n leds_off()\n led_white.on()\n\ndef led_red_on():\n leds_off()\n led_red.on()\n\ndef led_blue_on():\n leds_off()\n led_blue.on()\n led_red.on()\n\ndef led_yellow_on():\n leds_off()\n led_yellow.on()\n led_red.on()\n\ndef buzzer_triple_beep():\n global buzzer_active\n buzzer_active = True\n buzzer.on()\n sleep(0.050)\n buzzer.off()\n sleep(0.025)\n buzzer.on()\n sleep(0.050)\n buzzer.off()\n sleep(0.025)\n buzzer.on()\n sleep(0.050)\n buzzer.off()\n sleep(1.500)\n buzzer_active = False\n\ndef buzzer_long_beep():\n global buzzer_final\n buzzer.on()\n sleep(0.600)\n buzzer.off()\n buzzer_final = False\n\ndef buzzer_verify():\n buzzer.on()\n sleep(0.200)\n buzzer.off()\n\ndef buzzer_gloves():\n global buzzer_active\n if not buzzer_active:\n Thread(target=buzzer_triple_beep, daemon=True).start()\n\ndef buzzer_completed():\n global buzzer_final\n if buzzer_final:\n Thread(target=buzzer_long_beep, daemon=True).start()\n\ndef buzzer_alert():\n global buzzer_active\n buzzer_active = True\n buzzer.blink(0.150, 0.050)\n\ndef buzzer_alert_on():\n global buzzer_active\n if not buzzer_active:\n Thread(target=buzzer_alert, daemon=True).start()\n\ndef buzzer_alert_off():\n global buzzer_active\n buzzer_active = False\n buzzer.off()\n\ndef main():\n video_streaming()\n window.root.mainloop()\n\nif __name__ == '__main__':\n main()","sub_path":"SVPy/svpy.py","file_name":"svpy.py","file_ext":"py","file_size_in_byte":26560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"472501398","text":"\"\"\"Binary to Decimal and Back Converter - Develop a converter to convert a decimal number\nto binary or a binary number to its decimal equivalent.\n\"\"\"\nimport sys\n\nprint(\n 'This program converts a number from Binary to Decimal or from Decimal to Binary.')\n\n\ndef binary_to_decimal(n):\n print(int(str(n), 2), '\\n')\n\n\ndef decimal_to_binary(n):\n print(format(int(n), 'b'), '\\n')\n\n\ndef convert_again():\n prompt = input('Run the program again? (Y/N)\\n')\n if prompt == 'Y':\n converter()\n elif prompt == 'N':\n print('Bye!')\n sys.exit()\n else:\n print(\"You typed '{0}'.'.format{0}\\n\")\n convert_again()\n\n\ndef converter():\n print('-------------------------------------------\\n')\n choice = input(\n \"To convert from Binary to Decimal, type 'b'.\\nTo convert from Decimal to Binary, type 'd'.\\n\")\n if choice == 'b':\n print('---------------------------------------')\n print('Converting from Binary to Decimal...\\n')\n number = input('Enter the number you want to convert: \\n')\n binary_to_decimal(number)\n convert_again()\n\n elif choice == 'd':\n print('---------------------------------------')\n print('Converting from Binary to Decimal...\\n')\n number = input('Enter the number you want to convert: \\n')\n decimal_to_binary(number)\n convert_again()\n\n else:\n print(\"You typed '{0}'.\".format(choice))\n converter()\n print('\\n')\n\n\nconverter()\n","sub_path":"binarytodecimalconverter.py","file_name":"binarytodecimalconverter.py","file_ext":"py","file_size_in_byte":1485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"70054864","text":"# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport os\n\nimport six\nfrom six.moves import configparser as ConfigParser\n\nfrom .. import compat\nfrom .. import ODPS\nfrom ..tunnel import TableTunnel\n\nLOGGING_CONFIG = {\n 'version': 1,\n \"filters\": {\n \"odps\": {\n \"name\": \"odps\"\n },\n },\n \"formatters\": {\n \"msgonly\": {\n \"format\": \"%(message)s\"\n },\n },\n \"handlers\": {\n \"console\": {\n \"class\": \"logging.StreamHandler\",\n \"level\": 'INFO',\n \"formatter\": \"msgonly\",\n \"filters\": [\"odps\",],\n },\n },\n \"root\": {\n \"level\": \"NOTSET\",\n \"handlers\": [\"console\"]\n },\n \"disable_existing_loggers\": False\n}\n\n\nclass Config(object):\n config = None\n odps = None\n tunnel = None\n admin = None\n\n\ndef get_config():\n global LOGGING_CONFIG\n\n if not Config.config:\n config = ConfigParser.ConfigParser()\n Config.config = config\n config_path = os.path.join(os.path.dirname(__file__), 'test.conf')\n if not os.path.exists(config_path):\n raise Exception('Please configure test.conf (you can rename'\n ' test.conf.template)')\n config.read(config_path)\n access_id = config.get(\"odps\", \"access_id\")\n secret_access_key = config.get(\"odps\", \"secret_access_key\")\n project = config.get(\"odps\", \"project\")\n endpoint = config.get(\"odps\", \"endpoint\")\n try:\n tunnel_endpoint = config.get(\"tunnel\", \"endpoint\")\n except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):\n tunnel_endpoint = None\n\n try:\n datahub_endpoint = config.get(\"datahub\", \"endpoint\")\n except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):\n datahub_endpoint = None\n\n config.odps = ODPS(access_id, secret_access_key, project, endpoint,\n tunnel_endpoint=tunnel_endpoint)\n config.tunnel = TableTunnel(config.odps, endpoint=tunnel_endpoint)\n config.datahub_endpoint = datahub_endpoint\n logging_level = config.get('test', 'logging_level')\n LOGGING_CONFIG['handlers']['console']['level'] = logging_level\n else:\n config = Config.config\n\n compat.dictconfig(LOGGING_CONFIG)\n return config\n\n\ndef to_str(s):\n if isinstance(s, six.binary_type):\n s = s.decode('utf-8')\n return s\n\n\nclass TestBase(compat.unittest.TestCase):\n\n def setUp(self):\n self.config = get_config()\n self.odps = self.config.odps\n self.tunnel = self.config.tunnel\n self.datahub_endpoint = self.config.datahub_endpoint\n self.setup()\n\n def tearDown(self):\n self.teardown()\n\n def setup(self):\n pass\n\n def teardown(self):\n pass\n","sub_path":"odps/tests/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"370879691","text":"\"\"\"Number of Coin Changes.\n\nCount how many distinct ways you can make change that amount.\nAssume that you have an infinite number of each kind of coin.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\ndef _change_recur(amount, coins, n):\n \"\"\"Helper function for num_coin_changes_recur().\"\"\"\n # Base cases.\n if amount < 0:\n return 0\n if amount == 0:\n return 1\n\n # When number of coins is 0 but there is still amount remaining.\n if n <= 0 and amount > 0:\n return 0\n\n # Sum num of ways with coin n included & excluded.\n n_changes = (_change_recur(amount - coins[n - 1], coins, n)\n + _change_recur(amount, coins, n - 1))\n return n_changes\n\n\ndef num_coin_changes_recur(amount, coins):\n \"\"\"Number of coin changes by recursion.\n\n Time complexity: O(2^n), where n is number of coins.\n Space complexity: O(1).\n \"\"\"\n n = len(coins)\n return _change_recur(amount, coins, n)\n\n\ndef _change_memo(amount, coins, T, n):\n \"\"\"Helper function for num_coin_changes_memo().\"\"\"\n # Base cases.\n if amount < 0:\n return 0\n if amount == 0:\n return 1\n\n if n <= 0 and amount > 0:\n return 0\n\n # Apply memoization.\n if T[n][amount]:\n return T[n][amount]\n\n # Sum num of ways with coin n included & excluded.\n T[n][amount] = (_change_memo(amount - coins[n - 1], coins, T, n)\n + _change_memo(amount, coins, T, n - 1))\n\n return T[n][amount]\n\n\ndef num_coin_changes_memo(amount, coins):\n \"\"\"Number of coin changes by top-down dynamic programming:\n recursion + memoization.\n\n Time complexity: O(a*n), where a is amount, and n is number of coins.\n Space complexity: O(a*n).\n \"\"\"\n # Apply top-down DP with memoization tabular T: (n+1)x(amount+1).\n n = len(coins)\n T = [[0] * (amount + 1) for c in range(n + 1)]\n\n # For amount 0, set T[c][0] equal 1.\n for c in range(1, n + 1):\n T[c][0] = 1\n\n return _change_memo(amount, coins, T, n)\n\n\ndef num_coin_changes_dp(amount, coins):\n \"\"\"Number of coin changes by bottom-up dynamic programming.\n\n Time complexity: O(a*n), where a is amount, and n is number of coins.\n Space complexity: O(a*n).\n \"\"\"\n # Apply bottom-up DP with memoization tabular T: (n+1)x(amount+1).\n n = len(coins)\n T = [[0] * (amount + 1) for c in range(n + 1)]\n\n # For amount 0, set T[c][0] equal 1.\n for c in range(1, n + 1):\n T[c][0] = 1\n\n for c in range(1, n + 1):\n for a in range(1, amount + 1):\n if coins[c - 1] <= a:\n # If can change, sum num of ways with coin n included & excluded.\n T[c][a] = T[c][a - coins[c - 1]] + T[c - 1][a]\n else:\n # Cannot make a change by coin c.\n T[c][a] = T[c - 1][a]\n\n return T[-1][-1]\n\n\ndef main():\n import time\n\n # Ans = 5.\n amount = 5\n coins = [1, 2, 3]\n\n start_time = time.time()\n print('By recursion: {}'\n .format(num_coin_changes_recur(amount, coins)))\n print('Time: {}'.format(time.time() - start_time))\n\n start_time = time.time()\n print('By memo: {}'\n .format(num_coin_changes_memo(amount, coins)))\n print('Time: {}'.format(time.time() - start_time))\n\n start_time = time.time()\n print('By DP: {}'\n .format(num_coin_changes_dp(amount, coins)))\n print('Time: {}'.format(time.time() - start_time))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"alg_num_coin_changes.py","file_name":"alg_num_coin_changes.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"49041718","text":"\n\nfrom xai.brain.wordbase.verbs._orbit import _ORBIT\n\n#calss header\nclass _ORBITING(_ORBIT, ):\n\tdef __init__(self,): \n\t\t_ORBIT.__init__(self)\n\t\tself.name = \"ORBITING\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"orbit\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_orbiting.py","file_name":"_orbiting.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"606894729","text":"import numpy as np\n\narray= np.loadtxt('D:/Data/magic04.txt', delimiter=',', usecols=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9))\nMat=np.mat(array)\nmean = np.mean(array, axis=0)\nrow=Mat.shape[0] #得到总的行数\ni=1\nout=(Mat[0]-mean).T*(Mat[0]-mean) #计算外积\nwhile i List[List[int]]:\n res = []\n self.helper(nums,res,[])\n return res\n\n def helper(self,nums,res,temp):\n if len(temp) == len(nums):\n res.append(temp[:])\n for j in range(len(nums)):\n if nums[j] not in temp:\n temp.append(nums[j])\n self.helper(nums,res,temp)\n temp.pop()\n\n# @lc code=end\n\n","sub_path":"Week_03/46.全排列.py","file_name":"46.全排列.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"481227753","text":"import unittest\n\nfrom stackcite.api import testing\n\n\ndef _make_request(key):\n from pyramid.testing import DummyRequest\n api_header = {'API_KEY': key}\n request = DummyRequest()\n request.headers.update(api_header)\n return request\n\n\nclass AuthPolicyIntegrationTestCase(unittest.TestCase):\n\n layer = testing.layers.MongoTestLayer\n\n def setUp(self):\n from .. import policies\n from .. import models\n from bson import ObjectId\n from stackcite.api import auth\n self.auth_pol = policies.AuthTokenAuthenticationPolicy()\n self.user = models.SessionUser(str(ObjectId()), [auth.USERS])\n\n def test_authenticated_userid_returns_user_id(self):\n \"\"\"AuthTokenAuthenticationPolicy.authenticated_userid() returns an authenticated ObjectId\n \"\"\"\n from pyramid.testing import DummyRequest\n request = DummyRequest()\n expected = self.user.id\n request.user = self.user\n result = self.auth_pol.authenticated_userid(request)\n self.assertEqual(expected, result)\n\n def test_effective_principals_includes_authenticated_user_id(self):\n \"\"\"AuthTokenAuthenticationPolicy.effective_principals() includes an authenticated ObjectId\n \"\"\"\n from pyramid.testing import DummyRequest\n request = DummyRequest()\n request.user = self.user\n expected = self.user.id\n result = self.auth_pol.effective_principals(request)\n self.assertIn(expected, result)\n\n def test_effective_principals_includes_everyone_for_unauthenticated_user(self):\n \"\"\"AuthTokenAuthenticationPolicy.effective_principals() includes Everyone for an authenticated user\n \"\"\"\n from pyramid.testing import DummyRequest\n from pyramid.authentication import Everyone\n request = DummyRequest()\n request.user = None\n result = self.auth_pol.effective_principals(request)\n self.assertIn(Everyone, result)\n\n def test_effective_principals_exclude_authenticated_for_unauthenticated_user(self):\n \"\"\"AuthTokenAuthenticationPolicy.effective_principals() excludes \"Authenticated\" for an authenticated user\n \"\"\"\n from pyramid.testing import DummyRequest\n from pyramid.authentication import Authenticated\n request = DummyRequest()\n request.user = None\n result = self.auth_pol.effective_principals(request)\n self.assertNotIn(Authenticated, result)\n\n def test_effective_principals_include_authenticated_for_authenticated_user(self):\n \"\"\"AuthTokenAuthenticationPolicy.effective_principals() excludes \"Authenticated\" for an authenticated user\n \"\"\"\n from pyramid.testing import DummyRequest\n from pyramid.authentication import Authenticated\n request = DummyRequest()\n request.user = self.user\n result = self.auth_pol.effective_principals(request)\n self.assertIn(Authenticated, result)\n\n def test_effective_principals_include_assigned_groups_for_authenticated_user(self):\n \"\"\"AuthTokenAuthenticationPolicy.effective_principals() includes assigned groups for an authenticated user\n \"\"\"\n from pyramid.testing import DummyRequest\n request = DummyRequest()\n request.user = self.user\n result = self.auth_pol.effective_principals(request)\n for expected in self.user.groups:\n self.assertIn(expected, result)\n","sub_path":"stackcite/api/auth/tests/test_policies.py","file_name":"test_policies.py","file_ext":"py","file_size_in_byte":3417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"614582424","text":"\"\"\"ReChord_frontend.py construct a flask app and calls on search.py for searching\"\"\"\n# pylint: disable=invalid-name\n\nimport os\nimport tempfile\nfrom io import BytesIO\nfrom flask import Flask, request, render_template, flash, redirect, abort\nfrom werkzeug.utils import secure_filename\nfrom lxml import etree\nfrom search import text_box_search_folder, snippet_search_folder, prepare_tree\n\nALLOWED_EXTENSIONS = {'xml', 'mei'}\n\n# initiate the app\napp = Flask(__name__) # pylint: disable=invalid-name\napp.secret_key = '\\x82\\xebT\\x17\\x07\\xbbx\\xd9\\xe1dxR\\x11\\x8b\\x0ci\\xe1\\xb7\\xa8\\x97\\n\\xd6\\x01\\x99'\n\n\ndef allowed_file(filename):\n \"\"\"check the file name to avoid possible hack\n Arguments: uploaded file's name\n Return: rendered result page 'result.html'\n \"\"\"\n return '.' in filename and \\\n filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\n\n@app.route('/')\ndef form():\n \"\"\"render front page template\n Return: rendered front page 'index.html'\n \"\"\"\n return render_template('index.html')\n\n\n@app.route('/documentation')\ndef documentation():\n \"\"\"render front page template\n Return: rendered front page 'index.html'\n \"\"\"\n return render_template('documentation.html')\n\n\n@app.route('/', methods=['POST'])\ndef form_post(): # pylint: disable=too-many-return-statements\n \"\"\"the view function which return the result page by using the input pass to the back end\n Arguments: forms submitted in index.html\n Return: rendered result page 'result.html' by call on helper functions\n \"\"\"\n\n # Snippet search in ReChord Database\n if request.form['submit'] == 'Search Snippet In Our Database':\n path = 'database/MEI_Complete_examples'\n return search_snippet(path, request.form['text'])\n\n # Terms search in ReChord Database\n elif request.form['submit'] == 'Search Terms In Our Database':\n tag = request.form['term']\n para = request.form['parameter']\n path = 'database/MEI_Complete_examples'\n return search_terms(path, tag, para)\n\n # Snippet search using user submitted library\n elif request.form['submit'] == 'Upload and Search Your Snippet':\n with tempfile.TemporaryDirectory() as tmpdirname:\n try:\n path = upload_file(\"base_file\", tmpdirname)\n return search_snippet(path, request.form['text'])\n except NameError as error_msg:\n return render_template('result.html', errors=str(error_msg))\n\n # Terms search with user submitted library\n elif request.form['submit'] == 'Upload and Search Parameter':\n tag = request.form['term']\n para = request.form['parameter']\n with tempfile.TemporaryDirectory() as tmpdirname:\n try:\n path = upload_file(\"base_file\", tmpdirname)\n return search_terms(path, tag, para)\n except NameError as error_msg:\n return render_template('result.html', errors=str(error_msg))\n else:\n abort(404)\n return None\n\n\n# Helper functions\n\ndef get_mei_from_folder(path):\n \"\"\"gets a list of MEI files from a given folder path\n Arguments: path [string]: absolute or relative path to folder\n Returns: all_mei_files: List: list of mei files in path\n \"\"\"\n return [path + \"/\" + filename for filename in os.listdir(path) if\n filename.endswith('.mei') or filename.endswith('.xml')]\n\n\ndef search_snippet(path, snippet):\n \"\"\"search the snippet from the given database\n Arguments:\n snippet of xml that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n \"\"\"\n xml = BytesIO(snippet.encode())\n error_msg = \"\"\n try:\n input_xml_tree, _ = prepare_tree(xml) # pylint: disable=c-extension-no-member\n\n named_tuples_ls = snippet_search_folder(path, input_xml_tree)\n if named_tuples_ls:\n return render_template('result.html', origins=named_tuples_ls)\n else:\n error_msg = \"No matched snippet found, maybe try something else?\"\n return render_template('result.html', nomatch=error_msg)\n except (etree.XMLSyntaxError, ValueError):\n error_msg = \"Invalid MEI snippet inputs. Please double check the source and try it again!\"\n except KeyError:\n error_msg = \"Invalid upload file. Please double check the source and try it again!\"\n return render_template('result.html', errors=error_msg)\n\n\ndef search_terms(path, tag, para):\n \"\"\" search terms in the database\n Arguments:\n tags of term that want to search for\n para(meters) of tags that want to search for\n tree of xml base that needed to be searched in\n Return: rendered result page 'result.html'\n \"\"\"\n error_msg = \"\"\n try:\n named_tuples_ls = text_box_search_folder(path, tag, para)\n if named_tuples_ls:\n return render_template('result.html', origins=named_tuples_ls)\n else:\n error_msg = \"No matched term found, maybe try something else?\"\n return render_template('result.html', nomatch=error_msg)\n except KeyError:\n error_msg = \"Invalid upload file. Please double check the source and try it again!\"\n return render_template('result.html', errors=error_msg)\n\n\ndef upload_file(name_tag, tmpdirname):\n \"\"\"pass the upload files and store them in uploads folder's unique sub-folder\n Arguments: name_tag that used in html\n Return: upload path name\n \"\"\"\n # check if the post request has the file part\n if 'base_file' not in request.files:\n flash('No file part')\n return redirect(request.url)\n else:\n files = request.files.getlist(name_tag)\n\n for file in files:\n # if user does not select file, browser also submit a empty part without filename\n if file.filename == '':\n flash('No selected file')\n return redirect(request.url)\n\n # if properly uploaded\n elif file:\n if allowed_file(file.filename):\n file.save(os.path.join(tmpdirname, secure_filename(file.filename)))\n else:\n raise NameError(file.filename + ' is not a allowed name or the file extension is not .mei or .xml.')\n return tmpdirname\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"ReChord_frontend.py","file_name":"ReChord_frontend.py","file_ext":"py","file_size_in_byte":6358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"20"} +{"seq_id":"71725765","text":"import os.path\nfrom subprocess import call\nimport logging as log\nimport random\nimport string\n\nclass Blast:\n\n\tdef __init__ (self, args):\n\t\tself.check_args(args)\n\t\tself.cmd = []\n\t\tself.ssh_cmd = []\n\t\tif self.execution == 1:\n\t\t\tself.create_cmd()\n\n\n\n\tdef create_cmd (self):\n\t\tssh_cmd = self._get_exec_script()\n\t\tif self.server != 'enki':\n\t\t\tcmd = 'scp ' + self.contigs + ' ' + self.params['servers'][self.server]['adress'] + ':' + self.params['servers'][self.server]['scratch']\n\t\t\tlog.debug(cmd)\n\t\t\tself.cmd.append(cmd)\n\t\t\tfw = open(self.remote_cmd_file, mode='w')\n\t\t\tfw.write(ssh_cmd)\n\t\t\tfw.close()\n\t\t\tcmd = 'ssh stheil@' + self.params['servers'][self.server]['adress'] + ' \\'bash -s\\' < ' + self.remote_cmd_file\n\t\t\tlog.debug(cmd)\n\t\t\tself.cmd.append(cmd)\n\t\t\tcmd = 'scp stheil@' + self.params['servers'][self.server]['adress'] + ':' + self.params['servers'][self.server]['scratch'] + '/' + self.out_dir + '/' + os.path.basename(self.out) + ' ' + self.wd\n\t\t\tlog.debug(cmd)\n\t\t\tself.cmd.append(cmd)\n\t\telif self.server == 'enki':\n\t\t\tself.cmd.append(ssh_cmd)\n\n\n\tdef _get_exec_script (self):\n\t\tssh_cmd = ''\n\t\tif self.server != 'enki':\n\t\t\tssh_cmd += 'if [ -f ~/.bashrc ]; then' + \"\\n\"\n\t\t\tssh_cmd += 'source ~/.bashrc' + \"\\n\"\n\t\t\tssh_cmd += 'elif [ -f ~/.profile ]; then' + \"\\n\"\n\t\t\tssh_cmd += 'source ~/.profile' + \"\\n\"\n\t\t\tssh_cmd += 'elif [ -f ~/.bash_profile ]; then' + \"\\n\"\n\t\t\tssh_cmd += 'source /etc/profile' + \"\\n\"\n\t\t\tssh_cmd += 'source ~/.bash_profile' + \"\\n\"\n\t\t\tssh_cmd += 'else' + \"\\n\"\n\t\t\tssh_cmd += 'echo \"source not found.\"' + \"\\n\"\n\t\t\tssh_cmd += 'fi' + \"\\n\"\n\t\t\tssh_cmd += 'cd ' + self.params['servers'][self.server]['scratch'] + \"\\n\"\n\t\t\tssh_cmd += 'mkdir ' + self.params['servers'][self.server]['scratch'] + '/' + self.out_dir + \"\\n\"\n\t\t\tssh_cmd += 'mv ' + self.params['servers'][self.server]['scratch'] + '/' + os.path.basename(self.contigs) + ' ' + self.out_dir + \"\\n\"\n\t\t\tssh_cmd += 'cd ' + self.params['servers'][self.server]['scratch'] + '/' + self.out_dir + \"\\n\"\n\n\t\tif self.server == 'genotoul':\n\t\t\tssh_cmd += 'echo \"'\n\t\tssh_cmd += 'blast_launch.py -c ' + self.server + ' -n ' + self.num_chunk + ' --n_cpu ' + self.n_cpu + ' --tc ' + self.tc + ' -d ' + self.params['servers'][self.server]['db'][self.db]\n\t\tif self.server != 'enki':\n\t\t\tssh_cmd += ' -s ' + os.path.basename(self.contigs)\n\t\telse:\n\t\t\tssh_cmd += ' -s ' + self.contigs\n\n\t\tssh_cmd += ' --prefix ' + self.out_dir\n\t\tssh_cmd += ' -p ' + self.type + ' -o ' + os.path.basename(self.out) + ' -r ' + ' --outfmt 5'\n\t\tssh_cmd += ' --max_target_seqs ' + self.max_target_seqs\n\t\tif self.server == 'genotoul':\n\t\t\tssh_cmd += '\"'\n\t\t\tssh_cmd += ' | qsub -sync yes -V -wd ' + self.params['servers'][self.server]['scratch'] + '/' + self.out_dir + ' -N ' + self.sample\n\t\tlog.debug(ssh_cmd)\n\t\treturn ssh_cmd\n\n\n\tdef check_args (self, args: dict):\n\t\tif 'sample' in args:\n\t\t\tself.sample = str(args['sample'])\n\t\tself.wd = os.getcwd() + '/' + self.sample\n\t\taccepted_type = ['tblastx','blastx','blastn','blastp','rpstblastn']\n\t\tif 'contigs' in args:\n\t\t\tif os.path.exists(self.wd + '/' + args['contigs']):\n\t\t\t\tself.contigs = self.wd + '/' + args['contigs']\n\t\t\t\tself.execution = 1;\n\t\t\telse:\n\t\t\t\tself.execution = 0;\n\t\t\t\tlog.critical('Input fasta file do not exists.')\n\t\tif 'type' in args:\n\t\t\tif args['type'] in accepted_type:\n\t\t\t\tself.type = args['type']\n\t\t\telse:\n\t\t\t\tlog.critical('Wrong blast type. ' + accepted_type)\n\t\telse:\n\t\t\tlog.critical('Blast type is mandatory.')\n\t\tif 'n_cpu' in args:\n\t\t\tself.n_cpu = str(args['n_cpu'])\n\t\telse:\n\t\t\tlog.debug('n_cpu option not found. default 1')\n\t\t\tself.n_cpu = '1'\n\t\tif 'sge' in args:\n\t\t\tself.sge = bool(args['sge'])\n\t\telse:\n\t\t\tself.sge = False\n\t\tif 'tc' in args:\n\t\t\tself.tc = str(args['tc'])\n\t\telse:\n\t\t\tself.tc = '5'\n\t\tif 'max_target_seqs' in args:\n\t\t\tself.max_target_seqs = str(args['max_target_seqs'])\n\t\telse:\n\t\t\tself.max_target_seqs = '5'\n\n\t\tif 'num_chunk' in args:\n\t\t\tself.num_chunk = str(args['num_chunk'])\n\t\telse:\n\t\t\tself.num_chunk = '100'\n\t\tif 'out' in args:\n\t\t\tself.out = args['out']\n\t\tif 'params' in args:\n\t\t\tself.params = args['params']\n\t\tif 'server' in args:\n\t\t\tself.server = args['server']\n\t\tif 'db' in args:\n\t\t\tif args['db'] not in self.params['servers'][self.server]['db']:\n\t\t\t\tlog.critical(arg['db'] + ' not defined in parameters file')\n\t\t\telse:\n\t\t\t\tself.db = args['db']\n\t\telse:\n\t\t\tlog.critical('You must provide a database name.')\n\t\tself.cmd_file = self.wd + '/' + self.sample + '_' + self.type + '_' + self.db + '_blast_cmd.txt'\n\t\tself.remote_cmd_file = self.wd + '/' + self.sample + '_' + self.type + '_' + self.db + '_remote_blast_cmd.txt'\n\t\tself.random_string = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(4))\n\t\tself.out_dir = self.random_string + '_' + self.sample + '_' + self.type\n\n\n\tdef _check_file (self,f):\n\t\ttry:\n\t\t\topen(f)\n\t\t\treturn f\n\t\texcept IOError:\n\t\t\tprint('File not found ' + f)\n\n\n\tdef check_seq_format (self, in_file):\n\t\tin_file = str(object=in_file)\n\t\tself._check_file(in_file)\n\t\tout = ''\n\t\tif in_file.lower().endswith('.fa') or in_file.lower().endswith('.fasta') or in_file.lower().endswith('.fas'):\n\t\t\tout = os.path.splitext(in_file)[0] + '.fq'\n\t\t\tif not self._check_file(out):\n\t\t\t\tcmd = 'fasta_to_fastq' + ' ' + in_file + ' > ' + out\n\t\t\t\tlog.debug(str(cmd))\n\t\t\t\tself.cmd.append(cmd)\n\t\t\treturn out\n\t\telse:\n\t\t\tlog.debug('Format seems to be fastq.')\n\t\t\treturn in_file\n","sub_path":"launchers/Blast.py","file_name":"Blast.py","file_ext":"py","file_size_in_byte":5312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"581658361","text":"import sys\r\nimport os\r\nimport comtypes.client\r\n\r\n\r\ndef main(arg):\r\n WDFORMATPDF = 17\r\n\r\n in_file = os.path.abspath(sys.argv[1])\r\n out_file = os.path.splitext(sys.argv[1])[0] + '.pdf'\r\n\r\n word = comtypes.client.CreateObject('Word.Application')\r\n doc = word.Documents.Open(in_file)\r\n doc.SaveAs(out_file, FileFormat=WDFORMATPDF)\r\n doc.Close()\r\n word.Quit()\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) <= 1:\r\n sys.exit('No Arguments')\r\n main(sys.argv[1])\r\n","sub_path":"Applications/Word2PDF/Word2PDF.pyw","file_name":"Word2PDF.pyw","file_ext":"pyw","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"549899137","text":"from django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic.edit import FormView\n\nfrom .models import Activity, TimeSpend\nfrom .forms import ActivityForm, TimeSpendForm\n\ntime = TimeSpend()\n\n\ndef check_owner(request, activity):\n if activity.owner != request.user:\n raise Http404\n\n\n@login_required()\ndef index(request):\n \"\"\"homepage with activities\"\"\"\n activities = Activity.objects.filter(owner=request.user).order_by('date_added')\n user = request.user\n work_statistic = time.work_activity_time_sum(user)\n other_statistic = time.other_activity_time_sum(user)\n percentage_w_to_all = time.percentage(user)\n all_time = time.all_activity_time(user)\n return render(request, 'trackers/index.html', {\n 'activities': activities,\n 'work_statistic': work_statistic,\n 'other_statistic': other_statistic,\n 'percentage_w_to_all': percentage_w_to_all,\n 'all_time': all_time,\n })\n\n\nclass ActivityCreate(FormView):\n template_name = 'trackers/add_activity.html'\n form_class = ActivityForm\n\n def form_valid(self, form):\n form.set_owner(self.request)\n form.save()\n return HttpResponseRedirect(reverse('trackers:index'))\n\n\n@login_required()\ndef add_duration(request, activity_id):\n activity = get_object_or_404(Activity, id=activity_id)\n check_owner(request, activity)\n if request.method == 'POST':\n form = TimeSpendForm(request.POST)\n if form.is_valid():\n form.set_activity(activity)\n form.save()\n return HttpResponseRedirect(reverse('trackers:index'))\n else:\n form = TimeSpendForm()\n\n return render(request, 'trackers/add_duration.html', {'activity': activity, 'form': form})\n","sub_path":"timetracker/trackers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"388496680","text":"import inspect\nimport re\nimport sys\nimport datetime\nimport urllib\n\n\nclass Matcher(object):\n \"\"\"Create a Python dictionary from a line/chunk of text (using named regex)\n\n Sub-class Matcher, define a compiled regular expression (with NAMED\n GROUPS) for `rx` or `rx_iter`, and create methods using the group names in\n the regular expression.\n\n - only ONE named group may be used with `rx_iter`\n - only `rx` OR `rx_iter` may be defined for a Matcher sub-class (not both)\n\n A `finalize` method can be defined to perform any extra processing on the\n 'results' dict before returning. (Accept the results dict, update it, and\n return it).\n\n - Methods of the sub-class should accept a 'text' parameter and return a\n Python object\n \"\"\"\n rx = None\n rx_iter = None\n\n def __call__(self, text):\n # Complain if rx and rx_iter are defined (only one allowed)\n if self.rx and self.rx_iter:\n message = 'Cannot specify both \"rx\" and \"rx_iter\" for {}'\n raise ValueError(message.format(self.__class__.__name__))\n\n try:\n match_dict = self.rx.match(text).groupdict()\n except AttributeError:\n match_dict = {}\n\n try:\n match_iter_list = [x.groupdict() for x in self.rx_iter.finditer(text)]\n except AttributeError:\n match_iter_list = []\n\n if match_dict:\n # Collect methods of sub-class as the `methods` dict\n methods = dict(filter(\n lambda x: x[0] in match_dict.keys(),\n inspect.getmembers(self)\n ))\n\n if match_iter_list:\n # Complain if rx_iter has more than one named group\n named_groups = match_iter_list[0].keys()\n if len(named_groups) > 1:\n message = '\"rx_iter\" has more than 1 named group for {}: {}'\n raise ValueError(message.format(\n self.__class__.__name__, repr(named_groups))\n )\n\n # Collect methods of sub-class as the `methods2` dict\n _keys = set([key for k in match_iter_list for key in k.keys()])\n methods2 = dict(filter(\n lambda x: x[0] in _keys,\n inspect.getmembers(self)\n ))\n\n results = {}\n\n for group, text in match_dict.items():\n try:\n results[group] = methods[group](text)\n except KeyError:\n results[group] = text\n\n for d in match_iter_list:\n for group, text in d.items():\n key = '{}_list'.format(group)\n try:\n value = methods2[group](text)\n except KeyError:\n value = text\n try:\n results[key].append(value)\n except KeyError:\n results[key] = [value]\n\n results = self.finalize(results)\n return results\n\n def finalize(self, results):\n return results\n\n\nclass MultiMatcher(object):\n \"\"\"Multiple Matcher sub-classes in a single object\"\"\"\n def __init__(self, matchers=None, debug=False):\n \"\"\"Initialize with a list of matcher instances\n\n If debug is True, include a '_key_matcher_dict' key (in the return dict)\n containing fields that were matched, and the matcher instance that\n updated the field's data.\n \"\"\"\n if matchers:\n self.matchers = matchers\n else:\n self.matchers = []\n\n self.debug = debug\n\n def __call__(self, text):\n \"\"\"\n \"\"\"\n if self.debug:\n results = {'_key_matcher_dict': {}}\n else:\n results = {}\n\n for matcher in self.matchers:\n res = matcher(text)\n results.update(res)\n\n if self.debug:\n # Add the Matcher sub-class name for returned fields\n results['_key_matcher_dict'].update(\n dict([(k, matcher.__class__.__name__) for k in res.keys()]))\n return results\n\n def add_matcher_instances(self, *matchers):\n self.matchers.extend(matchers)\n\n\nclass IdentityMatcher(Matcher):\n \"\"\"Match the entire line\"\"\"\n rx = re.compile(r'^(?P.*)$')\n\n\nclass LeadingSpacesMatcher(Matcher):\n \"\"\"Match number of leading spaces (replacing any tabs with 4 spaces)\"\"\"\n rx = re.compile(r'^(?P\\s+)')\n\n def leading_spaces(self, text):\n # Replace any tab characters with 4 spaces\n text = text.replace('\\t', ' '*4)\n return len(text)\n\n\nclass DoubleQuoteMatcher(Matcher):\n \"\"\"Match text between double quotes\"\"\"\n rx_iter = re.compile(r'\\\"(?P[^\"]+)\\\"')\n\n\nclass SingleQuoteMatcher(Matcher):\n \"\"\"Match text between single quotes, but not single quotes inside words\"\"\"\n rx_iter = re.compile(r\"(^|\\s|\\b|[^\\w])\\'(?P[^']+)\\'[^\\w]\")\n\n\nclass BacktickMatcher(Matcher):\n \"\"\"Match text between backticks\"\"\"\n rx_iter = re.compile(r'\\`(?P[^`]+)\\`')\n\n\nclass MentionMatcher(Matcher):\n \"\"\"Match all @mentions, preceeded by a space or \"start of line\"\n\n Ignore any '@' that are in the middle of a string (like in an email address).\n \"\"\"\n rx_iter = re.compile(r'(^|\\s)@(?P\\S+)')\n\n\nclass TagMatcher(Matcher):\n \"\"\"Match all #tags, preceeded by a space or \"start of line\"\n\n Ignore any tags that are in the middle of a string (like in a URL).\n \"\"\"\n rx_iter = re.compile(r'(^|\\s)#(?P\\S+)')\n\n\nclass CommentMatcher(Matcher):\n \"\"\"Match comments (after #) and non-comment text\"\"\"\n rx = re.compile(r'^(?P.*?)#\\s+(?P.*)$')\n\n def non_comment(self, text):\n return text.strip()\n\n\nclass CapitalizedPhraseMatcher(Matcher):\n \"\"\"Match a capitalized phrase (but not smart enough to capture \"of/in/a\"..\n\n Enhanced version of http://stackoverflow.com/a/4113070\n \"\"\"\n rx_iter = re.compile(r'(^|\\s|\\\"|\\()(?P[A-Z][\\w\\-\\.,]*(\\s+[A-Z][\\w\\-\\.,]*)*)')\n\n\nclass AllCapsPhraseMatcher(Matcher):\n \"\"\"Match phrases/words written in ALL CAPS\"\"\"\n rx_iter = re.compile(r'(^|\\s|\\\"|\\()(?P[A-Z][A-Z\\-\\.,]+(\\s+[A-Z][A-Z\\-\\.,]+)*)')\n\n\nclass CurlyMatcher(Matcher):\n \"\"\"Match text between curly braces\n\n No attempt to perform nested matching.\n \"\"\"\n rx_iter = re.compile(r'\\{(?P[^\\}]+)\\}')\n\n\nclass ParenMatcher(Matcher):\n \"\"\"Match text between parentheses\n\n Ignore any parentheses groups where the opening paren is not preceeded by a\n space or isn't the start of a line\n\n Also, no attempt to perform nested matching.\n \"\"\"\n rx_iter = re.compile(r'(^|\\s)\\((?P[^\\)]+)\\)')\n\n\nclass DollarCommandMatcher(Matcher):\n \"\"\"Match text in the parentheses of $()\"\"\"\n rx_iter = re.compile(r'(^|\\s)\\$\\((?P[^\\)]+)\\)')\n\n\nclass DatetimeMatcher(Matcher):\n \"\"\"Match ISO 8691 formatted datetimes 'YYYY' to 'YYYY-MM-DD HH:MM:SS.f'\n\n See: https://www.iso.org/iso-8601-date-and-time-format.html\n \"\"\"\n rx_iter = re.compile(r\"\"\"\n (^|\\s|\\b)(?P\n \\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\.\\d+|\n \\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}:\\d{2}:\\d{2}|\n \\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}:\\d{2}|\n \\d{4}\\-\\d{2}\\-\\d{2}\\s\\d{2}|\n \\d{4}\\-\\d{2}\\-\\d{2}|\n \\d{4}\\-\\d{2}|\n \\d{4}\n )(\\s|\\b|$)\n \"\"\", re.VERBOSE)\n\n\nclass _UrlDetailsMatcher(Matcher):\n \"\"\"Match a URL and split into details\n\n Primarily intended to be used by the `UrlMatcher`.\n \"\"\"\n rx = re.compile(r\"\"\"\n (?P\n (?P\\w+)://(www\\.)?\n (?P[^/\\s]+)\n (?P([/]\\S+)?))\n \"\"\", re.VERBOSE)\n\n def path(self, text):\n if not text:\n return {}\n\n try:\n uri, querystring = text.split('?')\n except ValueError:\n uri = text\n querystring = ''\n\n if not querystring:\n return {'full_path': text, 'uri': uri}\n\n parameters = {}\n for param in querystring.split('&'):\n try:\n key, val = param.split('=')\n except ValueError:\n key = param\n val = None\n parameters[key] = val\n\n return {\n 'full_path': text,\n 'uri': uri,\n 'querystring': querystring,\n 'parameters': parameters}\n\n def finalize(self, results):\n if not results['path']:\n results.pop('path')\n\n # The 'filename_prefix' is safe to use as part of a filename\n results['filename_prefix'] = urllib.parse.quote_plus(\n results['full_url'].split('://')[1]\n ).replace('%2F', '--')\n\n return results\n\n\nclass UrlDetailsMatcher(Matcher):\n \"\"\"Match all URLs on a line and return details about the parts of each\"\"\"\n rx_iter = re.compile(r'(?P\\w+://\\S+)')\n udm = _UrlDetailsMatcher()\n\n def url_details(self, text):\n return self.udm(text.strip(')').strip(']'))\n\n\nclass UrlMatcher(Matcher):\n \"\"\"Match all URLs on a line\"\"\"\n rx_iter = re.compile(r'(?P\\w+://\\S+)')\n\n\nclass NonUrlTextMatcher(Matcher):\n \"\"\"For lines with URL(s), return the text that is not part of the URL(s)\n\n Kinda hacky...\n \"\"\"\n rx = re.compile(r'^(?P.*\\w+://\\S+.*)$')\n rx_url = re.compile(r'\\w+://\\S+')\n\n def non_url_text(self, text):\n \"\"\"\n Replace any URLs with an empty string, then split/join remaining text\n to ensure there are not multiple consecutive spaces.\n \"\"\"\n text = self.rx_url.sub('', text)\n return ' '.join(text.split())\n\n\nclass ScrotFileMatcher(Matcher):\n \"\"\"Match `scrot` filenames that were created with the following command\n\n scrot -s '%Y_%m%d--%H%M_%S--'$(hostname)'--$wx$h.png'\n \"\"\"\n rx = re.compile(r\"\"\"\n ^(?P\n (?P\\d{4}_\\d{4}--\\d{4}_\\d{2})--\n (?P.*)--\n (?P\\d+x\\d+).png)\n \"\"\", re.VERBOSE)\n\n def datestamp(self, text):\n return datetime.datetime.strptime(text, '%Y_%m%d--%H%M_%S')\n\n def dimensions(self, text):\n width, height = text.split('x')\n return {\n 'text': text,\n 'width': int(width),\n 'height': int(height),\n 'area': int(width) * int(height)}\n\n\nclass ScrotFileMatcher2(ScrotFileMatcher):\n \"\"\"Match `scrot` filenames that have standard format\n\n 2015-06-23-205812_1916x1048_scrot.png\n \"\"\"\n rx = re.compile(r\"\"\"\n ^(?P\n (?P\\d{4}-\\d{2}-\\d{2}-\\d{6})_\n (?P\\d+x\\d+)_scrot.png)\n \"\"\", re.VERBOSE)\n\n def datestamp(self, text):\n return datetime.datetime.strptime(text, '%Y-%m-%d-%H%M%S')\n\n\nclass FehSaveFileMatcher(Matcher):\n \"\"\"Match files saved with the 's' hotkey while viewing with `feh`\"\"\"\n rx = re.compile(r\"\"\"\n ^(?P\n (?Pfeh_\\d{6}_\\d{6}_)\n (?P.*))$\n \"\"\", re.VERBOSE)\n\n\nclass PsOutputMatcher(Matcher):\n \"\"\"Match output of `ps -eo user,pid,ppid,tty,cmd:200`\"\"\"\n rx = re.compile(r\"\"\"\n ^(?P[\\S]+)[\\s]+\n (?P[\\d]+)[\\s]+\n (?P[\\d]+)[\\s]+\n (?P[\\S]+)[\\s]+\n (?P.*$)\"\"\", re.VERBOSE)\n\n def pid(self, text):\n return int(text)\n\n def ppid(self, text):\n return int(text)\n\n\nclass ZshHistoryLineMatcher(Matcher):\n \"\"\"Match lines from the zsh history file (using `setopt extendedhistory`)\"\"\"\n rx = re.compile(r\"\"\"\n ^:\\s*\n (?P\\d+):\n (?P\\d+);\n (?P.*$)\n \"\"\", re.VERBOSE)\n\n def timestamp(self, text):\n return datetime.datetime.fromtimestamp(int(text))\n\n def duration(self, text):\n return int(text)\n\n\nclass SpecialTextMultiMatcher(MultiMatcher):\n def __init__(self, debug=False):\n super().__init__(debug=debug)\n self.add_matcher_instances(\n DoubleQuoteMatcher(), SingleQuoteMatcher(), BacktickMatcher(),\n MentionMatcher(), TagMatcher(), CommentMatcher(),\n CapitalizedPhraseMatcher(), AllCapsPhraseMatcher(),\n ParenMatcher(), UrlMatcher(), NonUrlTextMatcher(),\n IdentityMatcher(), CurlyMatcher(),\n )\n\n\nclass FilenameMultiMatcher(MultiMatcher):\n def __init__(self, debug=False):\n super().__init__(debug=debug)\n self.add_matcher_instances(\n ScrotFileMatcher(), ScrotFileMatcher2(), FehSaveFileMatcher(),\n )\n\n\nclass MasterMatcher(MultiMatcher):\n \"\"\"Use most sub-classes of Matcher defined in this module\n\n Ignore any sub-classes that have a name that starts with '_'\n \"\"\"\n def __init__(self, debug=False):\n global MATCHER_INSTANCES\n super().__init__(debug=debug)\n self.add_matcher_instances(*MATCHER_INSTANCES)\n\n\nMATCHER_INSTANCES = [\n c[1]()\n for c in inspect.getmembers(sys.modules[__name__], inspect.isclass)\n if issubclass(c[1], Matcher) and c[0] != 'Matcher' and not c[0].startswith('_')\n]\n","sub_path":"input_helper/matcher.py","file_name":"matcher.py","file_ext":"py","file_size_in_byte":13084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"67006578","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='LastChange',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('created_at', models.DateTimeField(verbose_name='Создано', auto_now_add=True)),\n ('updated_at', models.DateTimeField(verbose_name='Обновлено', auto_now=True)),\n ('commit', models.CharField(max_length=7, blank=True, null=True, verbose_name='Первые 7 символов хэша коммита')),\n ('changeDate', models.DateTimeField(verbose_name='Дата обновления', default=django.utils.timezone.now, blank=True, null=True)),\n ('description', models.TextField(max_length=255, blank=True, null=True, verbose_name='Описание изменений')),\n ],\n options={\n 'verbose_name_plural': 'обновления',\n 'verbose_name': 'обновление',\n 'get_latest_by': 'changeDate',\n 'ordering': ['-changeDate', '-created_at'],\n },\n ),\n migrations.CreateModel(\n name='Plan',\n fields=[\n ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')),\n ('is_complited', models.BooleanField(verbose_name='Выполнено?', default=False)),\n ('created_at', models.DateTimeField(verbose_name='Создано', auto_now_add=True)),\n ('updated_at', models.DateTimeField(verbose_name='Обновлено', auto_now=True)),\n ('description', models.TextField(max_length=255, blank=True, null=True, verbose_name='Описание пункта плана')),\n ],\n options={\n 'verbose_name_plural': 'планы',\n 'verbose_name': 'план',\n 'get_latest_by': 'created_at',\n 'ordering': ['created_at'],\n },\n ),\n ]\n","sub_path":"app/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"125629972","text":"'''\neasyTest全局配置文件\n'''\n\n# 测试用例及测试方案相关配置\nTESTCASE = {\n\t'runType': 'Browser', # 运行模式(Remote,Browser)\n\t'xmlDir': 'script/config/', # 测试方案配置文件夹路径(支持绝对路径)\n\t'testCaseDir': 'script/testCase/', # 测试用例配置文件夹路径(必须相对于项目根目录)\n\t'filesDir': 'script/files/', # 待上传文件路径\n}\n\n# 参数化数据相关配置\nPARAMETERIZATION = {\n\t'runTime': 1, # 单个场景运行次数(说明:如果设置成2,那么每个场景运行2次后,再运行下一个场景)\n\t'dataDir': '/script/data/',\n}\n\n# 本地报告日志相关配置\nREPORT = {\n\t'isScreenShot': True, # 截图开关:True:开启截图,False:关闭截图\n\t'isWriteLog': True, # 打印测试日志开关:True:开启打印日志,False:关闭打印日志\n\t'isWriteSysLog': True, # 打印系统日志开关:True:开启打印日志,False:关闭打印日志\n\t'showFindElementLog': True, # 日志中是否显示查找元素信息:True:显示,False:不显示\n\t'logLevel': 3, # 日志打印级别 1级:业务级别 2级:包含断言(默认) 3级:代码级别\n\t'logDir': '/script/report/log/', # 本地日志文件夹路径,也可以使用绝对路径\n\t'screenShotDir': '/script/report/image/', # 本地截图文件夹路径\n}\n\n# 服务器接收报告相关配置\nSERVER = {\n\t'isRequest': True, # 发送日志到服务器的开关:True:发送日志,False 不发送日志\n\t'requestURL': '', # 日志发送URL\n}\n\n# 驱动相关配置\nDRIVER = {\n\t'implicitlyWait': 50, # 查找元素隐式等待时间(秒)\n\t'afterFindElementWait': 0.5, # 找到元素后固定的等待时间(秒)\n\t'afterActionWait': 1, # 操作(如点击)后固定的等待时间(秒)\n\t'repeatFindTime': 10, # 当找不到元素时重复查找的次数\n\t'repeatDoTime': 10, # 当操作(如点击)失败后重复操作的次数\n\t'waitForSERException': 1, # 当定位元素出现StaleElementReferenceException异常时,进行下次重复查找的间隔时间\n\t'waitForNAPException': 1, # 当关闭警告窗,出现NoAlertPresentException异常时,进行下次重复查找的间隔时间\n\t'waitForWDException': 1, # 当操作(如点击)失败后,等待的时间间隔\n\t'maximizeWindow': True, # 启动浏览器最大化窗口\n}\n\n# 本地浏览器相关配置(非远程主机)\nBROWSER = {\n\t'fireFox': { # 本地火狐浏览器参数配置\n\t\t'binary_location': '', # 启动程序路径\n\t},\n\t'chrome': { # 本地谷歌浏览器参数配置\n\t\t'binary_location': '', # 启动程序路径\n\t},\n}\n# xml配置文件Tag标签及属性的名称\nXML_TAG = {\n\t'testPlan': {\n\t\t'connection': 'connection',\n\t\t'scene': 'scene',\n\t\t'sceneid': 'schemeId',\n\t\t'scriptId': 'scriptId',\n\t\t'enabled': 'enabled',\n\t\t'browser': 'browser',\n\t\t'paramPath': 'paramPath',\n\t\t'testCase': 'testCase',\n\t\t'hub': 'hub'\n\t},\n\t'testParam': {\n\t\t'param': 'param',\n\t\t'id': 'id',\n\t\t'description': 'description'\n\t}\n}\n\n# 模板相关配置\nTEMPLATES = {\n\t'storeTemplateDir': 'SRC/template/', # 存放模板的目录\n\t'templateDir': [\n\t\t'测试方案模板.xml', # 测试方案模板\n\t\t'测试用例模板.py', # 测试用例模板\n\t\t'参数化模板.xml' # 参数化模板\n\t]\n}\n","sub_path":"database/schemes/U易联_服务_专属客服管理/SRC/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552184930","text":"##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n## Created by: Hang Zhang\n## Email: zhanghang0704@gmail.com\n## Copyright (c) 2020\n##\n## LICENSE file in the root directory of this source tree \n##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nimport torch\nimport torchvision.transforms as transforms\nfrom .autoaug import RandAugment\ndef get_transforms(rand_aug=True):\n\n normalize = transforms.Lambda(lambda img: img * 2.0 - 1.0) \n if rand_aug:\n transform_train = transforms.Compose([\n RandAugment(2, 10),\n transforms.ToTensor(),\n normalize,\n ])\n else:\n transform_train = transforms.Compose([\n transforms.ColorJitter(0.05, 0.05, 0.05, 0.05),\n transforms.ToTensor(),\n normalize\n ])\n\n transform_val = transforms.Compose([\n transforms.ToTensor(),\n normalize\n ])\n\n \n return transform_train, transform_val\n\n","sub_path":"tumbocr/utils/transforms/get_transforms.py","file_name":"get_transforms.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"124140333","text":"from tool.some_tool import SomeTool\n\nclass CommentTool:\n @staticmethod\n def get_comment(db, contentId):\n # 获取评论列表\n cursor = db.cursor()\n sql = 'SELECT cm.email, cm.comment, cm.created, t.userId, cm.id, c.id FROM comment cm, content c, title t ' \\\n 'WHERE cm.contentId = {} AND c.titleId = t.id AND c.id = {} AND cm.hidden = 0 ' \\\n 'ORDER BY cm.id DESC'.format(contentId, contentId)\n cursor.execute(sql)\n results = cursor.fetchall()\n cursor.close()\n return results\n\n @staticmethod\n def add_comment(db, contentId, email, comment):\n # 新增评论\n cursor = db.cursor()\n sql = 'INSERT INTO comment (email, comment, contentId, created, hidden) VALUES ' \\\n '(\"{}\", \\'{}\\', {}, \"{}\", 0)'.format(email, str(comment).replace('\\'', '\"'), contentId, SomeTool.current_date())\n cursor.execute(sql)\n cursor.close()\n try:\n db.commit()\n return True\n except:\n db.rollback()\n return False\n\n @staticmethod\n def delete_comment(db, commentId):\n # 删除评论\n cursor = db.cursor()\n sql = 'UPDATE comment SET hidden = 1 WHERE id = {}'.format(commentId)\n cursor.execute(sql)\n cursor.close()\n try:\n db.commit()\n return True\n except:\n db.rollback()\n return False","sub_path":"tool/comment_tool.py","file_name":"comment_tool.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"312702352","text":"# Date: 2020/11/18\n# CourseID: 10910QF 510300\n# Course: Special Topics on Financial Engineering (Graduated)\n#\n# Writer_ID: 109062631\n# Writer_Name: Wang, Chuan-Chun\n# Environment:\n# [Configuration 1]\n# SW: Python 3.8.5 on 64-bit Windows 10 Pro (2004)\n# HW: Intel i7-10510U, 16GB DDR4 non-ECC ram, and no discrete GPU\n# [Configuration 2]\n# SW: Python 3.8.5 on Ubuntu 20.04.1 LTS (Linux 5.4.0-54-generic x86_64)\n# HW: AMD Ryzen 5 3400G, 64GB DDR4 non-ECC ram, and no discrete GPU\nimport itertools\nimport math\nimport matplotlib.pyplot as pyplot\nfrom multiprocessing import Pool\nimport numpy\nimport os\nimport pandas\nimport pickle\nimport random\nfrom sklearn.preprocessing import LabelEncoder\nimport time\nimport zlib\n\n\n########## Classes ##########\nclass CONST:\n # Define some constants\n tv_ratio = lambda : 0.8 # training validation ratio\n batch_size = lambda : 8192\n epoch_num = lambda : 100\n lr_rate = lambda : 0.5\n dp_ratio = lambda : 0.3\n id_col = lambda : ['id', 'member_id']\n redundant_col = lambda : ['annual_inc_joint', 'collection_recovery_fee', \n 'debt_settlement_flag_date', 'desc', \n 'earliest_cr_line', 'emp_title', \n 'fico_range_high', 'hardship_end_date', \n 'hardship_length', 'hardship_reason', \n 'hardship_start_date', 'issue_d', \n 'last_credit_pull_d', 'last_pymnt_d', \n 'num_sats', 'payment_plan_start_date', \n 'sec_app_earliest_cr_line', 'settlement_date', \n 'tot_hi_cred_lim', 'total_il_high_credit_limit', \n 'url', 'zip_code']\n mean_fill = lambda : ['bc_open_to_buy', 'dti', \n 'mths_since_recent_bc_dlq', 'mths_since_recent_revol_delinq', \n 'pct_tl_nvr_dlq', 'sec_app_mths_since_last_major_derog']\n median_fill = lambda : ['all_util', 'avg_cur_bal', \n 'bc_util', 'dti_joint', \n 'hardship_last_payment_amount', 'hardship_payoff_balance_amount', \n 'il_util', 'inq_fi', \n 'inq_last_12m', 'max_bal_bc', \n 'mo_sin_old_il_acct', 'mths_since_last_delinq', \n 'mths_since_last_major_derog', 'mths_since_last_record', \n 'mths_since_rcnt_il', 'mths_since_recent_bc', \n 'mths_since_recent_inq', 'num_rev_accts', \n 'open_act_il', 'open_il_24m', \n 'open_rv_12m', 'open_rv_24m', \n 'orig_projected_additional_accrued_interest', \n 'percent_bc_gt_75', 'revol_bal_joint', \n 'sec_app_fico_range_high', 'sec_app_fico_range_low', \n 'sec_app_num_rev_accts', 'sec_app_open_acc', \n 'sec_app_open_act_il', 'sec_app_revol_util', \n 'settlement_amount', 'settlement_percentage', \n 'settlement_term', 'total_bal_il']\n zlibCompress = lambda x : zlib.compress(pickle.dumps(x), level=9) # Use highest level of compression\n zlibDecompress = lambda x : pickle.loads(zlib.decompress(x))\n percent2f = lambda x : (float(str(x).strip('%')) + 0.0) * 1e-2 # Adding 0.0 is used to prevent negative zero\n month2i = lambda x : int(str(x).strip(' months')) if str(x) != 'nan' else 0\n category2i = lambda x, ct_dict: ct_dict[x] if x in ct_dict else 0\n\n\nclass DROP:\n col_dict = {}\n row_dict = {}\n\n\n########## Functions ##########\ndef compColDescription():\n with open('DataDictionary.xlsx', 'rb') as fp1, open('./Training/X_train.csv', 'r') as fp2:\n input_df = pandas.read_excel(fp1, skiprows=[0], sheet_name='LoanStats', header=None)\n xlsx_col = [FUNC.tokenize(i)[0] for i in list(input_df[0])] # Discard whitespace at the end of string\n data_col = FUNC.tokenize(fp2.readline())\n \n for i in xlsx_col:\n if i not in data_col:\n print(i)\n else:\n pass\n\n\ndef readCSV(file_path):\n with open(file_path, 'r', encoding='utf-8') as fp:\n input_df = pandas.read_csv(fp)\n return input_df.rename(columns={'Unnamed: 0': 'upload_index'})\n\n\ndef processTrain(train):\n pool, drop = Pool(), DROP()\n \n # FIND columns and rows with specific attributes\n # (1) Rows contain only NaN\n all_nan_rows = pool.map(checkAllNaNRow, itertools.product(train['X'].index, [train['X'].drop(CONST.id_col()+['upload_index'], axis=1)]))\n all_nan_rows = list(set(all_nan_rows)) # Remove duplicated rows\n all_nan_rows.remove(-1) # Pop out the 1st element '-1'\n drop.row_dict['all_nan'] = all_nan_rows\n \n \n # (2) Columns contain only id\n drop.col_dict['id'] = CONST.id_col() + ['upload_index']\n \n # (3) Columns that are redundant or contain too many attributes\n drop.col_dict['redundant'] = CONST.redundant_col()\n \n # (4) 'title' column\n drop.col_dict['title'] = ['title']\n \n \n # DROP columns and rows\n # (1) Rows\n for key in drop.row_dict.keys():\n train['X'] = train['X'].drop(drop.row_dict[key], errors='ignore')\n train['Y'] = train['Y'].drop(drop.row_dict[key], errors='ignore')\n \n # (2) Columns\n for key in drop.col_dict.keys():\n train['X'] = train['X'].drop(drop.col_dict[key], axis=1, errors='ignore')\n train['Y'] = train['Y'].drop(drop.col_dict[key], axis=1, errors='ignore')\n \n \n # FILL nan value\n # (1) With Mean of that columns\n for key in CONST.mean_fill():\n train['X'][key] = train['X'][key].fillna(train['X'][key].mean())\n \n # (2) With Medians\n for key in CONST.median_fill():\n train['X'][key] = train['X'][key].fillna(train['X'][key].mean())\n \n # (3) With specific tricks\n train['X']['deferral_term'].fillna(value=2.0, inplace=True)\n train['X']['emp_length'].fillna(value='<1 year', inplace=True)\n train['X']['hardship_amount'].fillna(value=0.0, inplace=True)\n train['X']['hardship_dpd'].fillna(value=0.0, inplace=True)\n train['X']['hardship_flag'].fillna(value='N', inplace=True)\n train['X']['hardship_loan_status'].fillna(value='Wedonotknow', inplace=True)\n train['X']['hardship_status'].fillna(value='Wedonotknow', inplace=True)\n train['X']['hardship_type'].fillna(value='Wedonotknow', inplace=True)\n train['X']['inq_last_6mths'].fillna(value=0.0, inplace=True)\n train['X']['next_pymnt_d'].fillna(value='Sep-20', inplace=True)\n train['X']['num_tl_120dpd_2m'].fillna(value=0.0, inplace=True)\n train['X']['open_acc_6m'].fillna(value=0.0, inplace=True)\n train['X']['open_il_12m'].fillna(value=0.0, inplace=True)\n train['X']['revol_util'].fillna(value='47.8%', inplace=True) # '47.8%' is the mean of that column\n train['X']['sec_app_chargeoff_within_12_mths'].fillna(value=0.0, inplace=True)\n train['X']['sec_app_collections_12_mths_ex_med'].fillna(value=0.0, inplace=True)\n train['X']['sec_app_inq_last_6mths'].fillna(value=0.0, inplace=True)\n train['X']['sec_app_mort_acc'].fillna(value=0.0, inplace=True)\n train['X']['settlement_status'].fillna(value='Wedonotknow', inplace=True)\n train['X']['total_cu_tl'].fillna(value=0.0, inplace=True)\n train['X']['verification_status_joint'].fillna(value='Wedonotknow', inplace=True)\n \n \n # Special value conversion\n train['X']['int_rate'] = train['X']['int_rate'].apply(CONST.percent2f)\n train['X']['revol_util'] = train['X']['revol_util'].apply(CONST.percent2f)\n train['X']['term'] = train['X']['term'].apply(CONST.month2i)\n \n \n # Normalization all numerical columns so far\n for col_name in train['X'].columns:\n if train['X'][col_name].dtype != 'object':\n train['X'][col_name] = (train['X'][col_name] - train['X'][col_name].mean()) / (train['X'][col_name].std() + 1e-8)\n \n \n # Label encode train['X'] on string columns whose ordering matter\n # (1) 'A'-'G' into 7-1 and others into 0\n encode_dict = {'A':7, 'B':6, 'C':5, 'D':4, 'E':3, 'F':2, 'G':1}\n train['X']['grade'] = train['X']['grade'].apply(lambda x : CONST.category2i(x, encode_dict)).astype('uint8')\n del encode_dict\n \n # (2) 'A1'-'A5' into 35-31,... , 'G1'-'G5' into 5-1, and others into 0\n encode_dict = {'A1':35, 'A2':34, 'A3':33, 'A4':32, 'A5':31, \n 'B1':30, 'B2':29, 'B3':28, 'B4':27, 'B5':26, \n 'C1':25, 'C2':24, 'C3':23, 'C4':22, 'C5':21, \n 'D1':20, 'D2':19, 'D3':18, 'D4':17, 'D5':16, \n 'E1':15, 'E2':14, 'E3':13, 'E4':12, 'E5':11, \n 'F1':10, 'F2': 9, 'F3': 8, 'F4': 7, 'F5': 6, \n 'G1': 5, 'G2': 4, 'G3': 3, 'G4': 2, 'G5': 1}\n train['X']['sub_grade'] = train['X']['sub_grade'].apply(lambda x : CONST.category2i(x, encode_dict)).astype('uint8')\n del encode_dict\n \n # (3) Text descriptions of years into integers\n encode_dict = {'<1 year' : 0, '1 year' : 1, '2 years' : 2, '3 years' : 3,\n '4 years' : 4, '5 years' : 5, '6 years' : 6, '7 years' : 7, \n '8 years' : 8, '9 years' : 9, '10+ years':19} \n train['X']['emp_length'] = train['X']['emp_length'].apply(lambda x : CONST.category2i(x, encode_dict)).astype('uint8')\n del encode_dict\n \n \n # One-hot encode train['X'] on the remaining string columns whose ordering do not matter\n train['X'] = pandas.get_dummies(train['X'], prefix_sep='=', dummy_na=True, drop_first=True)\n \n \n # Label encode train['Y']: Label='Y' into 1 and 'N' into 0\n sklearn_LE = LabelEncoder()\n sklearn_LE.fit(['N', 'Y'])\n train['Y']['loan_status'] = sklearn_LE.transform(train['Y']['loan_status'])\n \n pool.close()\n return train\n\n\ndef processTest(test):\n pool,drop = Pool(), DROP()\n \n # FIND columns and rows with specific attributes\n \n # (1) Rows contain only NaN\n all_nan_rows = pool.map(checkAllNaNRow, itertools.product(test['X'].index, [test['X'].drop(CONST.id_col()+['upload_index'], axis=1)]))\n all_nan_rows = list(set(all_nan_rows)) # Remove duplicated rows\n all_nan_rows.remove(-1) # Pop out the 1st element '-1'\n drop.row_dict['all_nan'] = all_nan_rows\n \n # (2) Columns contain only id\n drop.col_dict['id'] = CONST.id_col() + ['upload_index']\n \n # (3) Columns that are redundant or contain too many attributes\n drop.col_dict['redundant'] = CONST.redundant_col()\n \n # (4) 'title' column\n drop.col_dict['title'] = ['title']\n \n \n # DROP columns and rows\n # (1) Rows: Cannot drop any row in testing data, but we will fill some values later\n pass\n \n # (2) Columns\n for key in drop.col_dict.keys():\n test['X'] = test['X'].drop(drop.col_dict[key], axis=1, errors='ignore')\n test['Y'] = test['Y'].drop(drop.col_dict[key], axis=1, errors='ignore')\n \n \n # FILL nan value\n # (1) With Mean of that columns\n for key in CONST.mean_fill():\n test['X'][key] = test['X'][key].fillna(test['X'][key].mean())\n \n # (2) With Medians\n for key in CONST.median_fill():\n test['X'][key] = test['X'][key].fillna(test['X'][key].mean())\n \n # (3) With specific tricks\n test['X']['deferral_term'].fillna(value=2.0, inplace=True)\n test['X']['emp_length'].fillna(value='<1 year', inplace=True)\n test['X']['grade'].fillna(value='B', inplace=True)\n test['X']['hardship_amount'].fillna(value=0.0, inplace=True)\n test['X']['hardship_dpd'].fillna(value=0.0, inplace=True)\n test['X']['hardship_flag'].fillna(value='N', inplace=True)\n test['X']['hardship_loan_status'].fillna(value='Wedonotknow', inplace=True)\n test['X']['hardship_status'].fillna(value='Wedonotknow', inplace=True)\n test['X']['hardship_type'].fillna(value='Wedonotknow', inplace=True)\n test['X']['inq_last_6mths'].fillna(value=0.0, inplace=True)\n test['X']['next_pymnt_d'].fillna(value='Sep-20', inplace=True)\n test['X']['num_tl_120dpd_2m'].fillna(value=0.0, inplace=True)\n test['X']['open_acc_6m'].fillna(value=0.0, inplace=True)\n test['X']['open_il_12m'].fillna(value=0.0, inplace=True)\n test['X']['revol_util'].fillna(value='47.8%', inplace=True) # '47.8%' is the mean of that column\n test['X']['sec_app_chargeoff_within_12_mths'].fillna(value=0.0, inplace=True)\n test['X']['sec_app_collections_12_mths_ex_med'].fillna(value=0.0, inplace=True)\n test['X']['sec_app_inq_last_6mths'].fillna(value=0.0, inplace=True)\n test['X']['sec_app_mort_acc'].fillna(value=0.0, inplace=True)\n test['X']['settlement_status'].fillna(value='Wedonotknow', inplace=True)\n test['X']['total_cu_tl'].fillna(value=0.0, inplace=True)\n test['X']['verification_status_joint'].fillna(value='Wedonotknow', inplace=True)\n \n # (4) Spacial unknown label is only contained by testing data\n test['X']['hardship_loan_status'].replace(to_replace='CLOSED', value='ACTIVE', inplace=True)\n \n \n # Special value conversion\n test['X']['int_rate'] = test['X']['int_rate'].apply(CONST.percent2f)\n test['X']['revol_util'] = test['X']['revol_util'].apply(CONST.percent2f)\n test['X']['term'] = test['X']['term'].apply(CONST.month2i)\n \n \n # Deal with those all-nan rows\n col_name_list = [col_name for col_name in test['X'].columns if col_name not in (CONST.id_col()+['upload_index'])]\n for index in drop.row_dict['all_nan']:\n for col_name in col_name_list:\n test['X'].loc[index, col_name] = test['X'][col_name].mode()[0]\n \n \n # Normalization all numerical columns so far\n for col_name in test['X'].columns:\n if test['X'][col_name].dtype == 'object':\n pass\n else:\n test['X'][col_name] = (test['X'][col_name] - test['X'][col_name].mean()) / (test['X'][col_name].std() + 1e-8)\n \n \n # Label encode test['X'] on string columns whose ordering matter\n # (1) 'A'-'G' into 7-1 and others into 0\n encode_dict = {'A':7, 'B':6, 'C':5, 'D':4, 'E':3, 'F':2, 'G':1}\n test['X']['grade'] = test['X']['grade'].apply(lambda x : CONST.category2i(x, encode_dict)).astype('uint8')\n del encode_dict\n \n # (2) 'A1'-'A5' into 35-31,... , 'G1'-'G5' into 5-1, and others into 0\n encode_dict = {'A1':35, 'A2':34, 'A3':33, 'A4':32, 'A5':31, \n 'B1':30, 'B2':29, 'B3':28, 'B4':27, 'B5':26, \n 'C1':25, 'C2':24, 'C3':23, 'C4':22, 'C5':21, \n 'D1':20, 'D2':19, 'D3':18, 'D4':17, 'D5':16, \n 'E1':15, 'E2':14, 'E3':13, 'E4':12, 'E5':11, \n 'F1':10, 'F2': 9, 'F3': 8, 'F4': 7, 'F5': 6, \n 'G1': 5, 'G2': 4, 'G3': 3, 'G4': 2, 'G5': 1}\n test['X']['sub_grade'] = test['X']['sub_grade'].apply(lambda x : CONST.category2i(x, encode_dict)).astype('uint8')\n del encode_dict\n \n # (3) Text descriptions of years into integers\n encode_dict = {'<1 year' : 0, '1 year' : 1, '2 years' : 2, '3 years' : 3,\n '4 years' : 4, '5 years' : 5, '6 years' : 6, '7 years' : 7, \n '8 years' : 8, '9 years' : 9, '10+ years':19} \n test['X']['emp_length'] = test['X']['emp_length'].apply(lambda x : CONST.category2i(x, encode_dict)).astype('uint8')\n del encode_dict\n \n \n # One-hot encode test['X'] on the remaining string columns whose ordering do not matter\n test['X'] = pandas.get_dummies(test['X'], prefix_sep='=', dummy_na=True, drop_first=True)\n \n pool.close()\n return test\n\n\ndef checkAllNaNRow(pack_tuple):\n row_index, pandas_df = pack_tuple\n if pandas_df.iloc[row_index].isnull().all() == True:\n return row_index\n else:\n return -1\n\n\ndef overSample(df_X, df_Y):\n combined_df = pandas.concat([df_X, df_Y], axis=1) \n label_col_name = list(df_Y.columns)[0]\n \n lrgest_class_size = combined_df[label_col_name].value_counts().max()\n to_df_list = [combined_df]\n for _, group in combined_df.groupby(label_col_name):\n surplus_num = lrgest_class_size - len(group)\n to_df_list.append(group.sample(surplus_num, replace=True)) # Sample with replacement\n combined_df = pandas.concat(to_df_list).reset_index(drop=True)\n \n # Update training dataset with oversampling version\n X_part_cols = [col_name for col_name in combined_df.columns if col_name not in [label_col_name]]\n Y_part_cols = [label_col_name]\n return combined_df[X_part_cols], combined_df[Y_part_cols]\n\n\ndef saveDataToPK(data, file_name):\n with open('./PKs/' + file_name, 'wb') as f:\n pickle.dump(data, f)\n print(\"Save {} under directory 'PKs'\".format(file_name))\n\n\n########## Main function ##########\nif __name__ == \"__main__\":\n print(\"Generate train.pk and test.pk will take ~42 GB ram.\")\n \n # Display pandas DataFrame without truncation\n pandas.set_option('display.max_columns', None)\n pandas.set_option('display.max_rows', None)\n \n # Read raw *_train csv files, process data, and then store them into a .pk file\n print(\"Read training data .csv\")\n train = {'X': readCSV('./Training/X_train.csv'), 'Y': readCSV('./Training/Y_train.csv')}\n print(\"Do some data cleaning on training data\")\n train = processTrain(train)\n print(\"Oversample training data\")\n train['X'], train['Y'] = overSample(train['X'], train['Y'])\n saveDataToPK(train, 'train.pk')\n del train\n \n # Read raw *_test csv files, process data, and then store them into a .pk file\n print(\"Read testing data .csv\")\n test = {'X': readCSV('./Testing/X_test.csv'), 'Y': readCSV('./Testing/Y_test.csv')}\n print(\"Do some data cleaning on testing data\")\n test = processTest(test)\n saveDataToPK(test, 'test.pk')\n del test\n","sub_path":"AIFinPitch/save_pk.py","file_name":"save_pk.py","file_ext":"py","file_size_in_byte":18375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"577261691","text":"# -*- coding: utf-8 -*-\n\"\"\"\n/***************************************************************************\nName : menu_from_project plugin\nDescription : Build layers shortcut menu based on QGis project\nDate : 10/11/2011 \ncopyright : (C) 2011 by AEAG\nemail : xavier.culos@eau-adour-garonne.fr \n***************************************************************************/\n\n/***************************************************************************\n* *\n* This program is free software; you can redistribute it and/or modify *\n* it under the terms of the GNU General Public License as published by *\n* the Free Software Foundation; either version 2 of the License, or *\n* (at your option) any later version. *\n* *\n***************************************************************************/\n\n\"\"\"\n\n# Import the PyQt and QGIS libraries\nimport os\nimport sys\nfrom qgis.core import *\n\n#from qgis.PyQt.QtWebEngine import *\nfrom qgis.PyQt.QtCore import * \nfrom qgis.PyQt.QtGui import *\nfrom qgis.PyQt.QtWidgets import *\n\nfrom qgis.PyQt import QtXml\nfrom .ui_browser import Ui_browser\n\nfrom .menu_conf_dlg import menu_conf_dlg\n\n# Initialize Qt resources from file resources.py\nfrom . import resources\n\n\ndef getFirstChildByTagNameValue(elt, tagName, key, value):\n nodes = elt.elementsByTagName(tagName)\n for node in (nodes.at(i) for i in range(nodes.size())):\n #for node in nodes:\n idNode = node.namedItem(key)\n if idNode and value == idNode.firstChild().toText().data():\n # layer founds\n return node\n \n return None\n\nclass menu_from_project: \n\n def __init__(self, iface):\n self.path = QFileInfo(os.path.realpath(__file__)).path()\n self.iface = iface\n self.toolBar = None\n \n # new multi projects var\n self.projects = []\n self.menubarActions = []\n self.canvas = self.iface.mapCanvas()\n self.optionTooltip = (False)\n self.optionCreateGroup = (False)\n self.optionLoadAll = (False)\n self.read() \n \n # default lang\n locale = QSettings().value(\"locale/userLocale\")\n self.myLocale = locale[0:2]\n # dictionnary\n localePath = self.path+\"/i18n/menu_from_project_\" + self.myLocale + \".qm\"\n # translator\n if QFileInfo(localePath).exists():\n self.translator = QTranslator()\n self.translator.load(localePath)\n if qVersion() > '4.3.3':\n QCoreApplication.installTranslator(self.translator)\n\n def store(self):\n s = QSettings()\n s.remove(\"menu_from_project/projectFilePath\")\n\n s.setValue(\"menu_from_project/optionTooltip\", (self.optionTooltip))\n s.setValue(\"menu_from_project/optionCreateGroup\", (self.optionCreateGroup))\n s.setValue(\"menu_from_project/optionLoadAll\", (self.optionLoadAll))\n \n s.beginWriteArray(\"menu_from_project/projects\")\n for i, project in enumerate(self.projects):\n s.setArrayIndex(i)\n s.setValue(\"file\", project[\"file\"])\n s.setValue(\"name\", project[\"name\"])\n \n s.endArray()\n\n def read(self):\n s = QSettings()\n try:\n # old single project conf \n filePath = s.value(\"menu_from_project/projectFilePath\", \"\")\n \n if filePath:\n title = str(filePath).split('/')[-1]\n title = str(title).split('.')[0]\n self.projects.append({\"file\":filePath, \"name\":title})\n self.store()\n else:\n # patch : lecture ancienne conf\n size = s.beginReadArray(\"projects\")\n for i in range(size):\n s.setArrayIndex(i)\n file = ((s.value(\"file\").toString()))\n name = ((s.value(\"name\").toString()))\n if file:\n self.projects.append({\"file\":file, \"name\":(name)})\n s.endArray()\n\n size = s.beginReadArray(\"menu_from_project/projects\")\n for i in range(size):\n s.setArrayIndex(i)\n file = s.value(\"file\", \"\")\n name = s.value(\"name\", \"\")\n if file != \"\":\n self.projects.append({\"file\":file, \"name\":name})\n \n s.endArray()\n \n self.optionTooltip = s.value(\"menu_from_project/optionTooltip\", (True), type=bool)\n \n # create group option only since 1.9\n self.optionCreateGroup = s.value(\"menu_from_project/optionCreateGroup\", (False), type=bool)\n self.optionLoadAll = s.value(\"menu_from_project/optionLoadAll\", (False), type=bool)\n \n except:\n pass\n \n def isAbsolute(self, doc):\n absolute = False\n try:\n props = doc.elementsByTagName(\"properties\")\n if props.count()==1:\n node = props.at(0)\n pathNode = node.namedItem(\"Paths\")\n absoluteNode = pathNode.namedItem(\"Absolute\")\n absolute = (\"true\" == absoluteNode.firstChild().toText().data())\n except:\n pass\n \n return absolute\n\n def _actionHovered(self, action): \n tip = action.toolTip() \n if (tip != \"-\"):\n QToolTip.showText(QCursor.pos(), tip)\n else: \n QToolTip.hideText()\n \n def getMaplayerDomFromQgs(self, fileName, layerId):\n xml = open(str(fileName)).read()\n doc = QtXml.QDomDocument()\n doc.setContent(xml)\n \n maplayers = doc.elementsByTagName(\"maplayer\")\n for ml in (maplayers.item(i) for i in range(maplayers.size())):\n idelt = ml.namedItem(\"id\") \n if idelt and layerId == idelt.firstChild().toText().data():\n return ml\n \n return None\n \n def addMenuItem(self, filename, node, menu, domdoc):\n yaLayer = False\n initialFilename = filename\n if node == None:\n return yaLayer\n \n element = node.toElement()\n \n # if legendlayer tag\n if node.nodeName() == \"legendlayer\":\n try:\n legendlayerfileElt = element.firstChild().firstChildElement(\"legendlayerfile\")\n layerId = legendlayerfileElt.attribute(\"layerid\")\n action = QAction(element.attribute(\"name\"), self.iface.mainWindow())\n if (self.optionTooltip == (True)): \n try:\n maplayers = domdoc.elementsByTagName(\"maplayer\")\n for ml in (maplayers.item(i) for i in range(maplayers.size())):\n idelt = ml.namedItem(\"id\")\n id = \"\"\n \n if (idelt != None):\n id = idelt.firstChild().toText().data()\n \n attrEmbedded = ml.toElement().attribute(\"embedded\", \"0\")\n if (attrEmbedded == \"1\"):\n id = ml.toElement().attribute(\"id\", \"\")\n \n if (id == layerId):\n # embedded layers ?\n embeddedFilename = \"\"\n if (attrEmbedded == \"1\"):\n try:\n embeddedFilename = ml.toElement().attribute(\"project\", \"\")\n # read embedded project\n if not self.absolute and (embeddedFilename.find(\".\")==0):\n embeddedFilename = self.projectpath + \"/\" + embeddedFilename\n\n ml = self.getMaplayerDomFromQgs(embeddedFilename, id)\n filename = embeddedFilename\n except:\n pass\n \n if ml != None:\n try:\n title = ml.namedItem(\"title\").firstChild().toText().data()\n abstract = ml.namedItem(\"abstract\").firstChild().toText().data()\n \n action.setStatusTip(title)\n if (abstract != \"\") and (title == \"\"):\n action.setToolTip(\"

    %s

    \" % (\"
    \".join(abstract.split(\"\\n\"))))\n else:\n if (abstract != \"\" or title != \"\"):\n action.setToolTip(\"%s
    %s\" % (title, \"
    \".join(abstract.split(\"\\n\"))))\n else:\n action.setToolTip(\"-\")\n except:\n pass\n else:\n QgsMessageLog.logMessage(\"Menu from layer: \" + id + \" not found in project \" + embeddedFilename, 'Extensions')\n \n break\n except:\n pass\n \n menu.addAction(action)\n yaLayer = True\n helper = lambda _filename,_who,_menu: (lambda: self.do_aeag_menu(_filename, _who, _menu))\n action.triggered.connect(helper(filename, layerId, menu))\n except:\n pass\n \n nextNode = node.nextSibling()\n if (nextNode != None):\n # ! recursion\n self.addMenuItem(initialFilename, nextNode, menu, domdoc)\n # / if element.tagName() == \"legendlayer\":\n \n # if legendgroup tag\n if node.nodeName() == \"legendgroup\":\n name = element.attribute(\"name\")\n if name == \"-\":\n menu.addSeparator()\n nextNode = node.nextSibling()\n if (nextNode != None):\n # ! recursion\n self.addMenuItem(initialFilename, nextNode, menu, domdoc)\n\n elif name.startswith(\"-\"):\n action = QAction(name[1:], self.iface.mainWindow())\n font = QFont()\n font.setBold(True)\n action.setFont(font)\n menu.addAction(action) \n\n nextNode = node.nextSibling()\n if (nextNode != None):\n # ! recursion\n self.addMenuItem(initialFilename, nextNode, menu, domdoc)\n \n else:\n #messageLog(\"Group %s\" % (element.attribute(\"name\")))\n \n # construire sous-menu\n sousmenu = menu.addMenu('&'+element.attribute(\"name\"))\n sousmenu.menuAction().setToolTip(\"-\")\n\n childNode = node.firstChild()\n\n # ! recursion\n r = self.addMenuItem(initialFilename, childNode, sousmenu, domdoc)\n\n if r and self.optionLoadAll and (len(sousmenu.actions()) > 1):\n action = QAction(QApplication.translate(\"menu_from_project\", \"&Load all\", None), self.iface.mainWindow())\n font = QFont()\n font.setBold(True)\n action.setFont(font)\n sousmenu.addAction(action) \n helper = lambda _filename,_who,_menu: (lambda: self.do_aeag_menu(_filename, _who, _menu))\n action.triggered.connect(helper(None, None, sousmenu))\n \n nextNode = node.nextSibling()\n if (nextNode != None):\n # ! recursion\n self.addMenuItem(initialFilename, nextNode, menu, domdoc)\n # / if element.tagName() == \"legendgroup\":\n \n return yaLayer\n \n def addMenu(self, name, filename, domdoc):\n # main project menu\n menuBar = self.iface.editMenu().parentWidget()\n projectMenu = QMenu('&'+name, menuBar)\n\n if (self.optionTooltip == (True)): \n projectMenu.hovered.connect(self._actionHovered)\n\n projectAction = menuBar.addMenu(projectMenu)\n self.menubarActions.append(projectAction);\n\n self.absolute = self.isAbsolute(domdoc)\n self.projectpath = QFileInfo(os.path.realpath(filename)).path()\n\n # build menu on legend schema\n legends = domdoc.elementsByTagName(\"legend\")\n if (legends.length() > 0):\n node = legends.item(0)\n if node:\n node = node.firstChild()\n self.addMenuItem(filename, node, projectMenu, domdoc)\n \n def initMenus(self):\n menuBar = self.iface.editMenu().parentWidget()\n for action in self.menubarActions:\n menuBar.removeAction(action)\n del(action)\n \n self.menubarActions = []\n\n QgsApplication.setOverrideCursor(Qt.WaitCursor)\n for project in self.projects:\n QgsMessageLog.logMessage('Menu from layer: Loading ' + project[\"file\"] + ' in menu ' + project[\"name\"] + '...', 'Extensions')\n try:\n xml = open(project[\"file\"]).read()\n doc = QtXml.QDomDocument()\n doc.setContent(xml)\n \n self.addMenu(project[\"name\"], project[\"file\"], doc)\n except Exception as e: \n QgsMessageLog.logMessage('Menu from layer: Invalid ' + str(project[\"file\"]) + '. ' + format(e), 'Extensions')\n pass\n \n QgsApplication.restoreOverrideCursor()\n \n def initGui(self): \n self.act_aeag_menu_config = QAction(QApplication.translate(\"menu_from_project\", \"Projects configuration\", None)+\"...\", self.iface.mainWindow())\n self.iface.addPluginToMenu(QApplication.translate(\"menu_from_project\", \"&Layers menu from project\", None), self.act_aeag_menu_config)\n # Add actions to the toolbar\n self.act_aeag_menu_config.triggered.connect(self.do_aeag_menu_config)\n\n self.act_aeag_menu_help = QAction(QApplication.translate(\"menu_from_project\", \"Help\", None)+\"...\", self.iface.mainWindow())\n self.iface.addPluginToMenu(QApplication.translate(\"menu_from_project\", \"&Layers menu from project\", None), self.act_aeag_menu_help)\n self.act_aeag_menu_help.triggered.connect(self.do_help)\n \n # build menu\n self.initMenus()\n\n\n def unload(self):\n menuBar = self.iface.editMenu().parentWidget()\n for action in self.menubarActions:\n menuBar.removeAction(action)\n\n self.iface.removePluginMenu(QApplication.translate(\"menu_from_project\", \"&Layers menu from project\", None), self.act_aeag_menu_config)\n self.iface.removePluginMenu(QApplication.translate(\"menu_from_project\", \"&Layers menu from project\", None), self.act_aeag_menu_help)\n self.act_aeag_menu_config.triggered.disconnect(self.do_aeag_menu_config)\n self.act_aeag_menu_help.triggered.disconnect(self.do_help)\n\n self.store()\n\n def do_aeag_menu_config(self):\n dlg = menu_conf_dlg(self.iface.mainWindow(), self)\n dlg.setModal(True)\n \n dlg.show()\n result = dlg.exec_()\n del dlg\n \n if result != 0:\n self.initMenus()\n\n # run method that performs all the real work\n def do_aeag_menu(self, filename, who, menu=None):\n self.canvas.freeze(True)\n self.canvas.setRenderFlag(False)\n idxGroup = None\n theLayer = None\n groupName = None\n QgsApplication.setOverrideCursor(Qt.WaitCursor)\n\n try:\n if type(menu.parentWidget()) == QMenu and self.optionCreateGroup:\n groupName = menu.title().replace(\"&\", \"\")\n\n idxGroup = self.iface.legendInterface().groups().index(groupName) if groupName in self.iface.legendInterface().groups() else -1\n \n if idxGroup < 0:\n idxGroup = self.iface.legendInterface().addGroup(groupName, True)\n \n # load all layers\n if filename == None and who == None and self.optionLoadAll:\n for action in reversed(menu.actions()):\n if action.text() != QApplication.translate(\"menu_from_project\", \"&Load all\", None):\n action.trigger()\n else:\n # read QGis project\n xml = open(str(filename)).read()\n doc = QtXml.QDomDocument()\n doc.setContent(xml)\n\n # is project in relative path ? \n absolute = self.isAbsolute(doc)\n\n node = getFirstChildByTagNameValue(doc.documentElement(), \"maplayer\", \"id\", who)\n if node:\n idNode = node.namedItem(\"id\")\n # give it a new id (for multiple import)\n try:\n import uuid\n import re\n newLayerId = \"L%s\" % re.sub(\"[{}-]\", \"\", QUuid.createUuid().toString())\n idNode.firstChild().toText().setData(newLayerId)\n except:\n pass\n\n # if relative path, adapt datasource\n if not absolute:\n try:\n datasourceNode = node.namedItem(\"datasource\")\n datasource = datasourceNode.firstChild().toText().data()\n providerNode = node.namedItem(\"provider\")\n provider = providerNode.firstChild().toText().data()\n \n if provider == \"ogr\" and (datasource.find(\".\")==0):\n projectpath = QFileInfo(os.path.realpath(filename)).path()\n newlayerpath = projectpath + \"/\" + datasource \n datasourceNode.firstChild().toText().setData(newlayerpath)\n except:\n pass\n \n # read modified layer node\n QgsProject.instance().read(node)\n \n if self.optionCreateGroup:\n theLayer = QgsMapLayerRegistry.instance().mapLayer(newLayerId)\n \n if idxGroup >= 0 and theLayer != None:\n #self.iface.mainWindow().statusBar().showMessage(\"Move to group \"+str(idxGroup))\n self.iface.legendInterface().refreshLayerSymbology(theLayer)\n self.iface.legendInterface().moveLayer(theLayer, idxGroup)\n self.iface.legendInterface().refreshLayerSymbology(theLayer)\n \n \n except:\n QgsMessageLog.logMessage('Menu from layer: Invalid ' + filename, 'Extensions')\n pass\n \n self.canvas.freeze(False) \n self.canvas.setRenderFlag(True)\n self.canvas.refresh()\n QgsApplication.restoreOverrideCursor()\n \n \n def do_help(self):\n try:\n self.hdialog = QDialog()\n self.hdialog.setModal(True)\n self.hdialog.ui = Ui_browser()\n self.hdialog.ui.setupUi(self.hdialog)\n \n # FIXME: Migrate WebView\n #if os.path.isfile(self.path+\"/help_\"+self.myLocale+\".html\"):\n # self.hdialog.ui.helpContent.setUrl(QUrl(self.path+\"/help_\"+self.myLocale+\".html\"))\n #else:\n # self.hdialog.ui.helpContent.setUrl(QUrl(self.path+\"/help.html\"))\n\n #self.hdialog.ui.helpContent.page().setLinkDelegationPolicy(QtWebEngineKit.QWebEnginePage.DelegateExternalLinks) # Handle link clicks by yourself\n #self.hdialog.ui.helpContent.linkClicked.connect(self.doLink)\n \n #self.hdialog.ui.helpContent.page().currentFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOn)\n \n self.hdialog.show()\n result = self.hdialog.exec_()\n del self.hdialog\n except:\n QgsMessageLog.logMessage(sys.exc_info()[0], 'Extensions')\n pass\n \n def doLink( self, url ):\n if url.host() == \"\" :\n self.hdialog.ui.helpContent.page().currentFrame().load(url)\n else:\n QDesktopServices.openUrl( url )\n","sub_path":"menu_from_project/menu_from_project.py","file_name":"menu_from_project.py","file_ext":"py","file_size_in_byte":21164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"315014389","text":"from django import template\n\nfrom ..search import search_registry\n\nregister = template.Library()\n\n\n@register.inclusion_tag(\"helper/search/search_list.html\", takes_context=True)\ndef render_search_list(context, current, num_results=None, query=\"\"):\n searches = search_registry.get_searches(context[\"request\"])\n return {\n \"current\": current,\n \"num_results\": num_results,\n \"searches\": searches,\n \"query\": query,\n }\n","sub_path":"froide/helper/templatetags/search_helper.py","file_name":"search_helper.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"536398860","text":"''' GNG1103 Prototype #2\nGoal:\n- read text file that contains \"reset image\" and \"email image\" information\n- integrate email functionality\n- fix errors in Prototype #1 and create restrictions for get_coordinate method\n- read text file and run code whenever a new version is saved\n'''\n\nimport emailer\nimport math\nimport pygame\nimport csv\nimport time\nimport serial\n\n# Board Constants / Vars\nASPECT_RATIO = 9 / 16\nBOARD_WIDTH = 4\nBOARD_HEIGHT = BOARD_WIDTH * ASPECT_RATIO\nSPOOL_DISTANCE = 0.6\nSIDE_GAP = 0.0\nX_PIXELS = 4500\nY_PIXELS = int(round(X_PIXELS * ASPECT_RATIO))\nlengths = []\n\n# Drawing Constants / Vars\nWHITE = (255,255,255)\nBLACK = (0,0,0)\nPEN_THICKNESS = 5\nIMAGE_NAME = \"whiteboard.jpg\"\nLENGTH_COEFF = 0.0009\n\n# Update Constants / Vars\nIMAGE_UPDATE = 2 # Minimum time between saving new images when updates occurr\nRECIEVE_UPDATE = 2 # Minimum time between clearing or sending emails\nimage_last_time = time.time()\nrecieve_last_time = time.time()\nimage_modified = False\nwriting = False\n\n\n# Init\nprint(\"Establishing Serial Connection\", end='')\nser = serial.Serial('COM6', 2000000, timeout=.1)\nprint(\" - Done\")\ncanvas = pygame.Surface((X_PIXELS, Y_PIXELS))\ncanvas.fill(WHITE)\n\n\ndef recieve():\n global writing\n line = str(ser.readline())[2:-5:]\n if line == 'START':\n writing = True\n print(\"Writing Started\")\n elif line == 'END':\n writing = False\n print(\"Writing Complete\")\n elif len(line) > 2:\n split = line.split(', ')\n #print(split[0], split[1])\n lengths.append((float(split[0]), float(split[1])))\n\n\ndef get_coordinate(lengths):\n '''(float, float) -> (int, int)\n takes two lengths and returns a tuple with the corresponding x and y coordinates'''\n a = lengths[0]\n b = lengths[1]\n\n ab_angle = (math.pow(SPOOL_DISTANCE,2)-math.pow(a,2)-math.pow(b,2)) / (-2*a*b)\n if ab_angle>=1 or ab_angle<=-1: #THIS IS SUPER SKETCH AND ONLY FOR TESTING BECAUSE I USED SOME RANDOM COORDINATES\n ab_angle = 0.5\n x_length = a * b * math.sin(ab_angle) / SPOOL_DISTANCE\n\n b_angle = (b*math.sin(ab_angle)/SPOOL_DISTANCE)\n if b_angle>=1 or b_angle<=-1: #THIS IS ALSO SUPER SKETCH! FIX THIS LATER! FIGURE OUT HOW TO JUST USE LAST POINT OR TO IGNORE POINTS NOT IN DRAWING AREA\n b_angle = 0.5\n y_length = BOARD_HEIGHT - ( (BOARD_HEIGHT-SPOOL_DISTANCE) / 2 + a*math.cos(math.asin(b_angle)) )\n\n x_coord = round(x_length / BOARD_WIDTH * X_PIXELS) + (X_PIXELS/10)\n y_coord = round(y_length / BOARD_HEIGHT * Y_PIXELS)\n\n return((x_coord,y_coord))\n\n\ndef draw_image():\n global image_modified\n print('Updating Image', end='')\n coords = []\n for length in lengths:\n coords.append(get_coordinate((LENGTH_COEFF*float(length[0]),LENGTH_COEFF*float(length[1]))))\n pygame.draw.lines(canvas, BLACK, False, coords, PEN_THICKNESS)\n coords.clear()\n lengths.clear()\n print(' - Done')\n image_modified = True\n\n\ndef check_dashboard():\n email_file = open('email.txt', 'r')\n email_info = email_file.readline()\n email_file.close()\n\n reset_file = open('reset.txt', 'r')\n reset_info = reset_file.readline()\n reset_file.close()\n\n if '*' not in email_info:\n emailer.send_email(email_info)\n # overwrite file with '*'\n email_file = open('email.txt', 'w')\n email_file.write('*')\n print(\"email sent\")\n \n if '1' in reset_info:\n canvas.fill(WHITE)\n pygame.image.save(canvas,IMAGE_NAME)\n reset_file = open('reset.txt', 'w')\n reset_file.write('0')\n print(\"canvas cleared\")\n\n# Main update loop\nwhile True:\n # Recieve serial data until pen is released\n while ser.in_waiting or writing:\n if ser.in_waiting:\n recieve()\n\n if len(lengths) > 1:\n # Update image after pen is released\n draw_image()\n\n # Check for erase and email commands from dashboard\n current_time = time.time()\n if current_time >= recieve_last_time + RECIEVE_UPDATE:\n recieve_last_time = current_time\n check_dashboard()\n\n # Create new image if modified at most every IMAGE_UPDATE seconds\n current_time = time.time()\n if current_time >= image_last_time + IMAGE_UPDATE:\n image_last_time = current_time\n if image_modified:\n print('Saving Image', end='')\n pygame.image.save(canvas,IMAGE_NAME)\n print(' - Done')\n image_modified = False\n","sub_path":"Server/prototypes/Prototype2.py","file_name":"Prototype2.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"35426931","text":"from random import *\nfrom inside import is_inside\n\nshapes = [\n {\n 'text': 'blue',\n 'color': '#3F51B5',\n 'rect': [20, 60, 100, 100]\n },\n {\n 'text': 'red',\n 'color': '#C62828',\n 'rect': [140, 60, 100, 100]\n },\n {\n 'text': 'yellow',\n 'color': '#FFD600',\n 'rect': [20, 180, 100, 100]\n },\n {\n 'text': 'green',\n 'color': '#4CAF50',\n 'rect': [140, 180, 100, 100]\n }\n]\n\n\ndef get_shapes():\n return shapes\n\n\ndef generate_quiz():\n text = []\n color = []\n \n for box in shapes:\n text.append(box['text'].upper())\n for box in shapes:\n color.append(box['color'].upper())\n\n return [\n choice(text),\n choice(color),\n randint(0, 1) # 0 : meaning, 1: color\n ]\n\ndef mouse_press(x, y, text, color, quiz_type):\n rect_answer = []\n for box in shapes:\n if quiz_type == 0:\n if box['text'].upper() == text:\n rect_answer = box['rect']\n elif quiz_type == 1:\n if box['color'] == color:\n rect_answer = box['rect']\n \n if is_inside([x, y], rect_answer):\n return True\n else:\n return False\n\n","sub_path":"Lab03/HW/back-color-problem/back_color.py","file_name":"back_color.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"366352521","text":"# -*- coding: utf-8 -*-\nfrom selenium.webdriver.support.ui import Select\nfrom model.project import Project\n\n\nclass ProjectHelper:\n def __init__(self, app):\n self.app = app\n\n def create_project(self, project):\n wd = self.app.wd\n self.open_create_page()\n self.select_to_add()\n self.fill_group_form(project)\n wd.find_element_by_xpath(\"//input[@value='Add Project']\").click()\n\n def fill_group_form(self, project):\n self.change_field_value('name', project.name)\n self.change_field_value('description', project.description)\n self.change_list('status', project.status)\n self.change_list(\"view_state\", project.view_status)\n\n def change_field_value(self, field_name, text):\n wd = self.app.wd\n if text is not None:\n wd.find_element_by_name(field_name).click()\n wd.find_element_by_name(field_name).clear()\n wd.find_element_by_name(field_name).send_keys(text)\n\n def change_list(self, field_name, field_text):\n wd = self.app.wd\n if field_text is not None:\n wd.find_element_by_name(field_name).click()\n Select(wd.find_element_by_name(field_name)).select_by_value(field_text)\n #wd.find_element_by_name(field_name).click()\n\n def open_create_page(self):\n wd = self.app.wd\n wd.find_element_by_link_text(\"Manage\").click()\n wd.find_element_by_link_text(\"Manage Projects\").click()\n\n def select_to_add(self):\n wd = self.app.wd\n wd.find_element_by_xpath(\"//input[@value='Create New Project']\").click()\n\n def delete_project_by_id(self, id):\n wd = self.app.wd\n self.open_create_page()\n self.select_project(id)\n wd.find_element_by_xpath(\"//input[@value='Delete Project']\").click()\n wd.find_element_by_xpath(\"//input[@value='Delete Project']\").click()\n\n def select_project(self, id):\n wd = self.app.wd\n wd.find_element_by_xpath(\"//a[contains(@href, 'manage_proj_edit_page.php?project_id=%s')]\" %id).click()\n\n def get_project_list(self, count):\n wd = self.app.wd\n self.open_create_page()\n self.project_catch = []\n row_number = 1\n for i in range(count):\n row = wd.find_element_by_css_selector(\"tr.row-%s\" % (row_number))\n elements_td = row.find_elements_by_tag_name('td')\n name = elements_td[0].text\n description = elements_td[4].text\n self.project_catch.append(Project(name=name, description=description))\n if row_number == 1:\n row_number = 2\n else:\n row_number = 1\n return list(self.project_catch)\n","sub_path":"fixture/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"303577612","text":"#!/usr/bin/env python\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\"\"\"Lists the most recent versions in the deliverable files.\n\"\"\"\n\nfrom __future__ import print_function\n\nimport argparse\nimport os.path\nimport re\nimport subprocess\n\nimport yaml\n\n\nPRE_RELEASE_RE = re.compile('''\n \\.(\\d+(?:[ab]|rc)+\\d*)$\n''', flags=re.VERBOSE | re.UNICODE)\n\n\ndef find_modified_deliverable_files(reporoot):\n \"Return a list of files modified by the most recent commit.\"\n results = subprocess.check_output(\n ['git', 'diff', '--name-only', '--pretty=format:', 'HEAD^'],\n cwd=reporoot,\n )\n filenames = [\n l.strip()\n for l in results.splitlines()\n if l.startswith('deliverables/')\n ]\n return filenames\n\n\ndef get_modified_deliverable_file_content(reporoot, filenames):\n \"\"\"Return a sequence of tuples containing the new versions.\n\n Return tuples containing (deliverable name, series name, version\n number, repository name, hash SHA, include pypi link, first full\n version)\n\n \"\"\"\n # Determine which deliverable files to process by taking our\n # command line arguments or by scanning the git repository\n # for the most recent change.\n deliverable_files = filenames\n if not deliverable_files:\n deliverable_files = find_modified_deliverable_files(\n reporoot\n )\n\n for basename in deliverable_files:\n filename = os.path.join(reporoot, basename)\n if not os.path.exists(filename):\n # The file must have been deleted, skip it.\n continue\n with open(filename, 'r') as f:\n deliverable_data = yaml.load(f.read())\n\n # If there are no releases listed in this file, skip it.\n if not deliverable_data.get('releases'):\n continue\n\n # Determine whether announcements should include a PyPI\n # link. Default to no, for service projects, because it is\n # less irksome to fail to include a link to a thing that\n # exists than to link to something that does not.\n include_pypi_link = deliverable_data.get(\n 'include-pypi-link',\n False,\n )\n include_pypi_link = 'yes' if include_pypi_link else 'no'\n\n # The series name is part of the filename, rather than the file\n # body. That causes release.sh to be called with series=\"_independent\"\n # for release:independent projects, and release.sh to use master branch\n # to evaluate fixed bugs.\n series_name = os.path.basename(\n os.path.dirname(os.path.abspath(filename))\n ).lstrip('_')\n deliverable_name = os.path.splitext(os.path.basename(filename))[0]\n\n all_versions = {\n rel['version']: rel for rel in deliverable_data['releases']\n }\n version = deliverable_data['releases'][-1]['version']\n this_version = all_versions[version]\n final_versions = [\n r['version']\n for r in deliverable_data['releases']\n if not PRE_RELEASE_RE.search(r['version'])\n ]\n first_full_release = 'yes' if (\n final_versions and\n this_version['version'] == final_versions[0]\n ) else 'no'\n diff_start = this_version.get('diff-start', '-')\n for project in this_version['projects']:\n yield (deliverable_name, series_name, version,\n diff_start,\n project['repo'], project['hash'],\n include_pypi_link,\n first_full_release)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'deliverable_file',\n nargs='*',\n help='paths to YAML files specifying releases',\n )\n parser.add_argument(\n '--releases-repo', '-r',\n default='.',\n help='path to the releases repository for automatic scanning',\n )\n args = parser.parse_args()\n\n results = get_modified_deliverable_file_content(\n args.releases_repo,\n args.deliverable_file,\n )\n for r in results:\n print(' '.join(r))\n return 0\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"jenkins/scripts/release-tools/list_deliverable_changes.py","file_name":"list_deliverable_changes.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"373013990","text":"# 练习2:\n# 在控制台中获取两个变量,然后交换数据,最后显示结果.\n# “请输入第一个变量:”\n# “请输入第二个变量:”\n# 交换\n# “第一个变量是:”\n# “第二个变量是:”\n\ndata01 = input(\"请输入第一个变量:\")\ndata02 = input(\"请输入第二个变量:\")\n# 版本1:所有语言通用思想\n# temp = data01\n# data01 = data02\n# data02 = temp\n# 版本2:适合python\ndata01, data02 = data02, data01\nprint(\"第一个变量是:\" + data01)\nprint(\"第二个变量是:\" + data02)\n# 11:29\n","sub_path":"python_one_learn/day02/exercise02.py","file_name":"exercise02.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"243665343","text":"# Create a cylinder, translate it, and use iterative closest point to\n# align mesh to its original position.\n#\nimport pyvista as pv\nimport numpy as np\nsource = pv.Cylinder(resolution=30).triangulate().subdivide(1)\ntransformed = source.rotate_y(20).translate([-0.75, -0.5, 0.5])\naligned = transformed.align(source)\n_, closest_points = aligned.find_closest_cell(\n source.points, return_closest_point=True\n)\ndist = np.linalg.norm(source.points - closest_points, axis=1)\n#\n# Visualize the source, transformed, and aligned meshes.\n#\npl = pv.Plotter(shape=(1, 2))\n_ = pl.add_text('Before Alignment')\n_ = pl.add_mesh(\n source, style='wireframe', opacity=0.5, line_width=2\n)\n_ = pl.add_mesh(transformed)\npl.subplot(0, 1)\n_ = pl.add_text('After Alignment')\n_ = pl.add_mesh(\n source, style='wireframe', opacity=0.5, line_width=2\n)\n_ = pl.add_mesh(\n aligned,\n scalars=dist,\n scalar_bar_args={\n 'title': 'Distance to Source',\n 'fmt': '%.1E',\n },\n)\npl.show()\n#\n# Show that the mean distance between the source and the target is\n# nearly zero.\n#\nnp.abs(dist).mean() # doctest:+SKIP\n# Expected:\n## 9.997635192915073e-05\n","sub_path":"version/0.39/api/core/_autosummary/pyvista-DataSetFilters-align-1.py","file_name":"pyvista-DataSetFilters-align-1.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"190105178","text":"import numpy as np\r\nfrom spatialmath import *\r\nimport roboticstoolbox as rtb\r\nfrom roboticstoolbox.tools.trajectory import *\r\nimport math as m\r\n\r\nrobot = rtb.models.Panda()\r\nvia_pt = []\r\nfor t in range(0, 24):\r\n x = 0.1 * m.cos(t * np.pi / 12)+0.65\r\n y = 0.1 * m.sin(t * np.pi / 12)+0.2\r\n macierz = SE3(x,y,0.15)*SE3.Ry(np.pi)\r\n iksolution = robot.ikine_LMS(macierz)\r\n via_pt.append(iksolution.q)\r\n plt.scatter(x,y)\r\nplt.show()\r\nprint(iksolution.q)\r\ntraj = mstraj(np.asarray(via_pt), dt=0.1, tacc=0.2, qdmax=2.0)\r\nrobot.plot(traj.q, backend = 'pyplot', movie='panda_pyplot.gif')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"209075881","text":"print(\"Bienvenidos a nuestro maravilloso entorno web!!!!\")\r\n\r\n#variables\r\n #numeros = [n for n in range(10, 12) if +1] \r\nrespuesta_else = (\"Vuelve en\")\r\nnumeros = [1, 2, 3, 4, 5]\r\npregunta = input(\"Nombre y apellido:\")\r\nprint(\"Hola, Santiago\")\r\npregunta_edad = int(input(\"¿Que edad tienes?\"))\r\n\r\nif pregunta_edad >= 20:\r\n print(\"Bienvenido!!!\")\r\nelse:\r\n print(respuesta_else)\r\n\r\ndef calculo():\r\n if pregunta_edad == 19:\r\n print(numeros[0] , 'año')\r\n \r\ndef calculo2():\r\n if pregunta_edad == 18:\r\n print(numeros[1] , 'años') \r\n\r\ndef calculo3():\r\n if pregunta_edad == 17:\r\n print(numeros[2] , 'años') \r\n\r\ndef calculo4():\r\n if pregunta_edad == 16:\r\n print(numeros[3] , 'años') \r\n\r\ndef calculo5():\r\n if pregunta_edad == 15:\r\n print(numeros[4] , 'años') \r\n \r\ncalculo()\r\ncalculo2()\r\ncalculo3()\r\ncalculo4()\r\ncalculo5()\r\n\r\n\"\"\"while < 20:\r\n print(respuesta_else_3)\r\n respuesta_else_4 += 1\"\"\"\r\n\r\n#def ejemplo() \r\n#condiciones\r\n# if, else, elif\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"352349355","text":"import json\nimport sys\n\nimport requests\nfrom flask import Flask\nfrom flask import render_template\nfrom flask import request\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/', methods=['POST'])\ndef add_city():\n city_name = request.form[\"city_name\"]\n r = requests.get(f\"https://api.openweathermap.org/data/2.5/weather?q={city_name}\"\n f\"&appid=58058341b60d9730423df34082a652e2\")\n weather_data: dict = json.loads(r.content)\n data = {\"temp\": int(weather_data[\"main\"][\"temp\"]) - 273, \"city\": city_name, }\n\n return render_template('index.html', weather=data)\n\n\n# don't change the following way to run flask:\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n arg_host, arg_port = sys.argv[1].split(':')\n app.run(host=arg_host, port=arg_port)\n else:\n app.run()\n","sub_path":"Weather App/task/web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"325051234","text":"#_*_ encoding:utf-8 _*_\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\n#elapsed-响应时间\n#grpThreads|allThreads-运行的总线程数\n\n\n#将65473转换成类似66000、70000。varDig是保留几位整数值\ndef getMoreIntegerThan(varValue,varDig):\n dig=int(varDig)\n length=len(str(varValue))-dig\n moreInteger=int(str(varValue)[:dig])+1\n for i in range(length):\n moreInteger*=10\n return moreInteger\n#65473转换成类似65000、60000\ndef getLessIntegerThan(varValue,varDig):\n dig=int(varDig)\n length=len(str(varValue))-dig\n lessInteger=int(str(varValue)[:dig])\n for i in range(length):\n lessInteger*=10\n return lessInteger\n#根据最大值、最小值、生成元素个数产生List\ndef getList(maxValue,minValue,num,digit):\n intMax=int(maxValue)\n intMin=int(minValue)\n integral=getMoreIntegerThan(int((intMax-intMin)/num),digit)\n listVar=[0]\n for i in range(int(num)+1):\n listVar.append(intMin+i*integral)\n return listVar\n\n\n\njtl=\"canger50Line.jtl\"\ntotalLine=1\ntimes,elapseds,threads=[],[],[]\n\nwith open(jtl,'r',encoding='utf-8') as file_object:\n # print(\" --total lines is:\"+str(len(file_object.readlines())))\n # 使用这种方式,会导致下面的csv.reader无法再次打开文件\n reader=csv.reader(file_object)\n header_row=next(reader)\n\n print(\" --header of file :\\n\" + str(header_row) + '\\n')\n print(\" --index, column_name of header is:\")\n for index,column_header in enumerate(header_row):\n print(index,column_header)\n\n for row in reader:\n totalLine+=1\n time=row[0]\n latency=row[13]\n thread=row[12]\n times.append(time)\n elapseds.append(int(latency))\n threads.append(int(thread))\n\n\n#打印文件的总行数(包含标题行)\nprint(\"\\n --total lines is: \"+str(totalLine))\n\n#获取Latencys的最大值和最小值\nsortedLatencys=sorted(elapseds)\ny_min=sortedLatencys[0]\ny_max=sortedLatencys[-1]\nprint(\"\\n -- Latencys's actual max_value is: \\n\"+str(y_max))\n#转换最大值取整\ny_max=getMoreIntegerThan(y_max,2)\ny_min=getLessIntegerThan(y_min,1)\nprint(\"\\n -- Latencys's min_value and max_value are: \\n\"+str(y_min)+','+str(y_max))\n\n\nsortedTimes=sorted(times)\nx_min=sortedTimes[0]\nx_max=sortedTimes[-1]\n\n\n\n#设置纵坐标\n# np.linspace这种方式生成的数值,取整后,每个坐标的间隔不相同,视觉效果不好\n# y_ticks=np.linspace(0,y_max,20) \n# y_ticks=[getMoreIntegerThan(int(a),2) for a in y_ticks]\ny_ticks=getList(maxValue=y_max,minValue=y_min,num=3,digit=1)\nprint(\"\\n --y's values are :\\n\"+str(y_ticks))\n\n#####to do,to do \n#获取times的最大值和最小值\nsortedLatencys=sorted(times)\nx_min=sortedLatencys[0]\nx_max=sortedLatencys[-1]\nprint(\"\\n -- Times's min_value and max_value are: \\n\"+x_min+\",\",x_max)\n# #设置纵坐标\n# x_ticks=np.linspace(int(x_min),int(x_max),20)\n# print(\"\\n --x's values are :\\n\"+str(x_ticks))\n\n\nplt.yticks(y_ticks)\n\n\nplt.plot(times,elapseds)\nplt.plot(times,threads)\n\n#展示图表\nplt.show()\n\n\n\n\n# #保存图表\n# plt.savefig('plot1.png', format='png')\n","sub_path":"book/matplotlib/analyseJtl/fenxiJtl.py","file_name":"fenxiJtl.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"361599623","text":"import csv\nimport time\nfrom datetime import datetime\nf1=open(\"/Users/StanleyLIn/Desktop/專題研究/2014.csv\")\nf2=open(\"2014F_data.csv\",'w')\nf3=open(\"2014M_data.csv\",'w')\nwriter_F= csv.writer(f2, delimiter=',',dialect='excel')\nwriter_M= csv.writer(f3, delimiter=',',dialect='excel')\ncount=0\nfor row in csv.DictReader(f1):\n\tcount+=1\n\tif(count==1):\n\t\twriter_F.writerow(row)\n\t\twriter_M.writerow(row)\n\tprint(count)\n\tif(row[\"DEP_TIME\"]!=\"\"):\n\t\tif(row[\"SEX\"]==\"F\"):\n\t\t\twriter_F.writerow(row.values())\n\t\tif(row[\"SEX\"]==\"M\"):\n\t\t\twriter_M.writerow(row.values())\n\t","sub_path":"First Semester/2014_Gender.py","file_name":"2014_Gender.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"482863616","text":"import numpy as np \nimport matplotlib.pyplot as plt\nimport collections\nimport datetime as dt \nimport tremor_io\nimport tremor_tools\nimport netcdf_read_write\nimport sys\n\nTremorCat = collections.namedtuple(\"TremorCat\",['dtarray','lonarray','latarray']);\n\ndef configure():\n\ttremor_type = \"wech_custom_no_depth\";\n\tbounds = [-125,-120,38,43];\n\tspacing = 0.1; \n\toutfile=\"tremor_density.txt\";\n\treturn [tremor_type, bounds, spacing, outfile];\n\ndef compute(tremor, bounds, spacing):\n\txarray = np.arange(bounds[0], bounds[1], spacing);\n\tyarray = np.arange(bounds[2], bounds[3], spacing);\n\tprint(yarray);\n\tprint(xarray);\n\tdensity = np.zeros([len(yarray), len(xarray)]);\n\tfor i in range(len(yarray)):\n\t\tfor j in range(len(xarray)):\n\t\t\tbox_interest = [xarray[j], xarray[j]+spacing, yarray[i], yarray[i]+spacing];\n\t\t\trestricted = tremor_tools.restrict_to_box(tremor, box_interest);\n\t\t\tdensity[i][j] = len(restricted.lonarray);\n\treturn xarray, yarray, density;\n\ndef outputs(xarray, yarray, spacing, density, outfile):\n\tofile=open(outfile,'w');\n\tfor i in range(len(yarray)):\n\t\tfor j in range(len(xarray)):\n\t\t\txpos = xarray[j]+spacing/2.0;\n\t\t\typos = yarray[i]+spacing/2.0;\n\t\t\tofile.write(\"%f %f %d\\n\" % (xpos, ypos, density[i][j]) );\n\tofile.close();\n\treturn;\n\ndef plot_outfile(bounds, spacing, outfile):\n\t[lon, lat, d] = np.loadtxt(outfile,unpack=True);\n\tplt.figure(figsize=(8,6));\n\tplt.scatter(lon, lat, c=d, s=60, marker='s');\n\tplt.colorbar();\n\tplt.savefig('tremor_density');\n\n\t# Building a new GRD file\n\t# The lines below are for floating point errors. \n\txarray = np.arange(bounds[0], bounds[1], spacing);\n\txarray = [np.round(i,2) for i in xarray];\n\tx_lonequiv = [i+0.05 for i in xarray];\n\tx_lonequiv = [np.round(i,2) for i in x_lonequiv];\n\tyarray = np.arange(bounds[2], bounds[3], spacing);\n\tyarray = [np.round(i,2) for i in yarray];\t\n\ty_lonequiv = [i+spacing/2.0 for i in yarray];\n\ty_lonequiv = [np.round(i,2) for i in y_lonequiv];\n\tdensity = np.zeros([len(yarray), len(xarray)]);\t\n\t\n\tfor k in range(len(lon)):\n\t\txind = np.where(x_lonequiv==lon[k])[0];\n\t\tyind = np.where(y_lonequiv==lat[k])[0];\n\t\txind = xind[0];\n\t\tyind = yind[0];\n\t\tdensity[yind][xind] = d[k];\n\tprint(density);\n\n\tnetcdfname='density.nc';\n\tnetcdf_read_write.produce_output_netcdf(xarray, yarray, density, 'counts', netcdfname);\n\tnetcdf_read_write.flip_if_necessary(netcdfname);\n\treturn;\n\nif __name__==\"__main__\":\n\t[tremor_type, bounds, spacing, outfile] = configure();\n\t# tremor = tremor_tools.read_custom_tremor(tremor_type);\n\t# tremor = TremorCat(dtarray=[dt.datetime.strptime(\"20140202\",\"%Y%m%d\")], lonarray=[-122.9],latarray=[40.3]); # a test case \n\t# xarray, yarray, density = compute(tremor, bounds, spacing);\n\t# outputs(xarray, yarray, spacing, density, outfile);\n\tplot_outfile(bounds, spacing, outfile);\n","sub_path":"Tremor/density/get_density.py","file_name":"get_density.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"589624193","text":"# -*- coding: utf-8 -*-\n\nimport time\nimport imghdr\nimport os\nimport glob\nimport xlrd\nimport shutil\n\n\n__all__ = [\"rename_batch\", \"picture_format_trans\", \"files_info\"]\n\n\n# rename_batch(path, file_prep='', file_format = ('.jpg','png','jpeg'))\n# picture_format_trans(path)\n# files_info(path, file_type='all', recursive=False)\n\n\n\ndef coll_tiff(path):\n dirname = '{}/raw'.format(path)\n if not os.path.exists(dirname):\n os.mkdir(dirname)\n for name in os.listdir(path):\n if name.endswith('tiff'):\n file_local = '{}/{}'.format(path, name)\n shutil.move(file_local, dirname)\n\n\n\ndef re_sep(path):\n jpeg_set = set()\n tiff_set = set()\n jpeg_list = []\n tiff_list = []\n list = os.listdir(path)\n for name in list:\n if name.endswith('jpeg'):\n jpeg_set.add(name)\n elif name.endswith('tiff'):\n tiff_set.add(name)\n for j in jpeg_set:\n j_f, _ = os.path.splitext(j)\n for t in tiff_set:\n t_f, _ = os.path.splitext(t)\n if j_f == t_f:\n jpeg_list.append(j)\n tiff_list.append(t)\n rename(path, jpeg_list)\n rename(path, tiff_list)\n\n\ndef rename(path, some_list):\n i = 1\n _, file_prep = os.path.split(path) \n for name in some_list:\n _, fext = os.path.splitext(name) \n new_name = '{}-{}{}'.format(file_prep,i,fext)\n new_file = os.path.join(path, new_name)\n i += 1\n os.rename(os.path.join(path, name), new_file)\n\n\n\n\ndef rename_batch(path, file_prep='', file_format = ('.jpg','png','jpeg')):\n \"\"\"Batch renaming of files with the same format\"\"\"\n i = 1\n _, file_prep = os.path.split(path) \n if not os.path.isdir(path):\n return \"current directory not exist\"\n try:\n for name in os.listdir(path):\n if name.endswith(file_format):\n _, fext = os.path.splitext(name) \n while True:\n new_name = '{}-{}{}'.format(file_prep,i,fext)\n new_file = os.path.join(path,new_name)\n i += 1\n if not os.path.exists(new_file): break \n os.rename(os.path.join(path,name), new_file)\n print(\"success batch rename\")\n except:\n print(\"running wrong\")\n\n\ndef picture_format_trans(path):\n \"\"\"translate the pictures format correctly\"\"\"\n\n if not os.path.exists(path):\n return \"current path not exist\"\n \n if os.path.isfile(path):\n file_pattern = path\n else:\n file_pattern = os.path.join(path, '*.*')\n\n file_list = glob.glob(file_pattern)\n\n for file in file_list:\n if not imghdr.what(file):continue\n pref, fext = os.path.splitext(file) \n file_format = imghdr.what(file)\n if fext[1:] is not file_format:\n new_file = '{}.{}'.format(pref, imghdr.what(file))\n os.rename(file, new_file)\n\n\nprint_file_info = {\n 'all':'*',\n 'picture':'*',\n 'excel':'*.xlsx',\n 'text':'*.txt',\n 'python':'*.py',\n 'excel_spec':'*.xlsx',\n }\n\n\ndef files_info(path, file_type='all', recursive=False):\n \"\"\"打印当前文件下的所有文件或指定类型文件\"\"\" \n \n if not os.path.exists(path):\n return \"current path not exist\"\n if os.path.isfile(path):\n file_iterator = glob.iglob(path)\n else:\n for the_type in print_file_info:\n if the_type == file_type:\n file_end = print_file_info[the_type]\n if not recursive:\n file_iterator = glob.iglob(os.path.join(path, file_end))\n else:\n file_iterator = glob.iglob(os.path.join(path, '**',file_end))\n \n if file_type == 'excel_spec':\n _excels_info(file_iterator)\n elif file_type == 'picture':\n _pictures_info(file_iterator)\n else:\n _files_info_output(file_iterator)\n \n\ndef _files_info_output(file_iterator):\n print(\"{0:25}{1:12}{2:23}{3:23}\".format(\"file_name\",\"size\",\"update_time\",\"create_time\"))\n i = 0\n for file in file_iterator:\n i += 1\n file_info = _file_specific_info(file)\n print(file_info)\n print('***Number of files: {}'.format(i))\n \n\ndef _file_specific_info(path):\n file_infor = os.stat(path) \n file_name = os.path.basename(path)\n file_size = file_infor.st_size\n if file_size < 2**20:\n file_size = '{} (K)'.format(int(file_size/2**10))\n else:\n file_size = '{:.2f} (M)'.format(file_size/2**20)\n file_update_time_local = time.localtime(file_infor.st_mtime)\n file_create_time_local = time.localtime(file_infor.st_ctime) \n file_update_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", file_update_time_local)\n file_create_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", file_create_time_local)\n file_info_output = \"{0:25}{1:12}{2:23}{3:23}\".format(file_name,file_size,\\\n file_update_time,file_create_time)\n return file_info_output\n\n\ndef _excels_info(file_iterator):\n \"\"\"return excels information in current path\"\"\"\n for i,file in enumerate(file_iterator):\n workbook = xlrd.open_workbook(file) \n print('{}.{}'.format(i+1, os.path.basename(file)))\n print('Number of worksheets:{}'.format(workbook.nsheets))\n for worksheet in workbook.sheets():\n print('Worksheet name:{},\\tRows:{},\\tColumns:{}'.format(worksheet.name,worksheet.nrows,worksheet.ncols))\n\n\ndef _pictures_info(file_iterator):\n \"\"\"return picture information in current path\"\"\" \n pictures = []\n for file in file_iterator:\n if not imghdr.what(file):continue \n pictures.append(file)\n _files_info_output(pictures)\n\n\nif __name__ == '__main__':\n path = r'D:\\摄影图库\\照片\\新建文件夹'\n # glob.glob(r'D:\\all_picture\\pil_practice\\**\\*.*',recursive=True) \n \n # rename_batch(path, 'zijin')\n picture_format_trans(path)\n # files_info(path,recursive=True)\n\n\n\n\n\n\n","sub_path":"文件操作/small_application/files_operation.py","file_name":"files_operation.py","file_ext":"py","file_size_in_byte":6001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"645035777","text":"import random\nimport csv\n\n# All living organisms\nants = []\n\n# Specify maximum starting conditions\nsampleSize = 10\nmaxWeight = 10\nmaxSpeed = 10\nmaxMetabolism = 10\nmaxUgliness = 10\nmaxIterations = 1000\n\n# How many iterations have passed\ngeneration = 0\n\n\n# Utility functions\ndef gamma(n1, n2, delta):\n if n1 > n2:\n if n1 - n2 <= delta:\n return True\n else:\n if n2 - n1 <= delta:\n return True\n return False\n\n\nclass Ant():\n \"\"\"Represents a basic organism and all of its properties\"\"\"\n\n def __init__(self, weight, speed, metabolism, ugliness, gender):\n # Set initial properties\n self.weight = weight\n self.speed = speed\n self.metabolism = metabolism\n self.ugliness = ugliness\n self.gender = gender\n self.age = 0\n self.isAlive = True\n\n # Check if organism should die off\n self.isAlive = self.checkForLife()\n\n def findPartner(self):\n candidates = [x for x in getLivingAnts() if x.gender != self.gender]\n\n for ant in candidates:\n compatible = gamma(ant.ugliness, self.ugliness, 5)\n\n if compatible and not random.randint(0, 10) == 0:\n return ant\n\n def checkForLife(self):\n isAlive = self.isAlive\n\n if self.weight == 0:\n isAlive = False\n\n if self.speed == 0:\n isAlive = False\n\n if self.metabolism == 0:\n isAlive = False\n\n if self.speed <= 2:\n isAlive = False\n\n return isAlive\n\n\ndef reproduce(ant1, ant2):\n weight = ant1.weight + ant2.weight\n speed = ant1.speed + ant2.speed\n metabolism = ant1.metabolism + ant2.metabolism\n ugliness = 0\n\n if ant2.ugliness > ant1.ugliness:\n ugliness = ant1.ugliness - ant1.ugliness\n else:\n ugliness = ant1.ugliness - ant2.ugliness\n\n for i in range(random.randint(0, 2)):\n ants.append(Ant(\n weight=weight,\n speed=speed,\n metabolism=metabolism,\n ugliness=ugliness,\n gender=random.randint(0, 1),\n ))\n\n\ndef getLivingAnts():\n alives = [x for x in ants if x.isAlive]\n return alives\n\n\ndef doTurn():\n global generation\n generation += 1\n\n alives = getLivingAnts()\n\n for ant in alives:\n # Die of old age\n if ant.age == 10 and random.randint(0, 10) == 0:\n ant.isAlive = False\n else:\n ant.age += 1\n\n if ant.age == 20:\n ant.isAlive = False\n\n # Reproduce\n if ant.age == 5:\n partner = ant.findPartner()\n if partner:\n reproduce(ant, partner)\n\n with open('data.csv', 'a+') as csvfile:\n fieldnames = ['generation', 'alive']\n\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writerow({\n 'generation': generation,\n 'alive': len(getLivingAnts()),\n })\n\n\ndef main():\n # Set up export\n with open('data.csv', 'a+') as csvfile:\n fieldnames = ['generation', 'alive']\n\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n\n # Populate the inital colony of ants\n for i in range(0, sampleSize):\n ants.append(Ant(\n weight=random.randint(0, maxWeight),\n speed=random.randint(0, maxSpeed),\n metabolism=random.randint(0, maxMetabolism),\n ugliness=random.randint(0, maxUgliness),\n gender=random.randint(0, 1),\n ))\n\n # Run simulation\n for i in range(0, maxIterations):\n doTurn()\n print(len(getLivingAnts()))\n\nif __name__ == '__main__':\n main()\n","sub_path":"lib/maze.py","file_name":"maze.py","file_ext":"py","file_size_in_byte":3646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"637390920","text":"from crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit\nfrom django import forms\n\nfrom .models import Codelist, CodelistVersion\n\n\nclass CodelistForm(forms.ModelForm):\n csv_data = forms.FileField(label=\"CSV data\")\n\n class Meta:\n model = Codelist\n fields = [\"name\", \"coding_system_id\", \"description\", \"methodology\", \"csv_data\"]\n\n def __init__(self, *args, **kwargs):\n self.helper = FormHelper()\n self.helper.add_input(Submit(\"submit\", \"Submit\"))\n super().__init__(*args, **kwargs)\n\n\nclass CodelistVersionForm(forms.Form):\n csv_data = forms.FileField(label=\"CSV data\")\n\n class Meta:\n model = CodelistVersion\n fields = [\"csv_data\"]\n\n def __init__(self, *args, **kwargs):\n self.helper = FormHelper()\n self.helper.add_input(Submit(\"submit\", \"Submit\"))\n super().__init__(*args, **kwargs)\n","sub_path":"codelists/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552374600","text":"# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\n\n# You may assume that each input would have exactly one solution, and you may not use the same element twice.\n\n# You can return the answer in any order.\n\n# Example 1:\n\n# Input: nums = [2,7,11,15], target = 9\n# Output: [0,1]\n# Output: Because nums[0] + nums[1] == 9, we return [0, 1].\n\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n seen = {}\n for i, v in enumerate(nums):\n remaining = target - v\n if remaining in seen:\n return [seen[remaining], i]\n seen[v] = i\n return \n\n# nums同士を合計すると必ずtargetの値があるという前提がポイント\n","sub_path":"1.TwoSum.py","file_name":"1.TwoSum.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"530227326","text":"import sys\nimport time\nimport boto3\nimport requests\nfrom botocore.exceptions import ClientError\n\n\nLG_IMAGE_ID = 'ami-013666ca8430e3646'\nWS_IMAGE_ID = 'ami-01b6328e1cc04b493'\nINSTANCE_TYPE = 'm3.medium'\nKEY_NAME = 'key_pair_iam'\n\nSTART_EC2_ERROR = 'start_instance_error'\nSTART_EC2_SUCCESS = 'start_instance_success'\n\nSUBMISSION_USERNAME = ''\nSUBMISSION_PASSWORD = ''\n\nLG_INSTANCE_DNS = ''\nLG_INSTANCE_ID = ''\nWS_INSTANCE_DNS_list = []\nWS_INSTANCE_ID_list = []\nTEST_NUMBER = ''\n\nADDING_WS_DELAY = 105\nCHECK_URL_DELAY = 5\nINIT_INSTANCE_MAX_TRY = 60\nLOG_RETRIEVE_GAP = 2\nLOG_RETRIEVE_MAX_TRY = 1000\nTARGET_RPS = 60.0\n\nFLAG_ADD_WS = 1\nFLAG_KEEP_WS = 0\nFLAG_LOG_NOT_READY = -1\n\ntags = [\n {'Key': 'Project', 'Value': '2.1'},\n]\ntag_specification = [{'ResourceType': 'instance', 'Tags': tags}, ]\n\nec2 = boto3.resource('ec2', region_name=\"us-east-1\")\n\n\n# Launch a new instance\ndef launch_instance(image_id):\n global LG_INSTANCE_DNS\n global LG_INSTANCE_ID\n global WS_INSTANCE_DNS_list\n global WS_INSTANCE_ID_list\n\n try:\n new_instances = ec2.create_instances(\n ImageId=image_id,\n InstanceType=INSTANCE_TYPE,\n KeyName=KEY_NAME,\n MaxCount=1,\n MinCount=1,\n TagSpecifications=tag_specification,\n )\n new_instance = new_instances[0]\n new_instance.wait_until_running()\n new_instance.load()\n\n if image_id == LG_IMAGE_ID:\n LG_INSTANCE_DNS = new_instance.public_dns_name\n LG_INSTANCE_ID += new_instance.instance_id\n print(\"Workload Generator instance starts\")\n else:\n WS_INSTANCE_DNS_list.append(new_instance.public_dns_name)\n WS_INSTANCE_ID_list.append(new_instance.instance_id)\n print(\"\\nWeb Service instance starts\")\n print(\"Instance Id: \" + new_instance.instance_id +\n \", Public DNS: \" + new_instance.public_dns_name)\n\n return new_instance.public_dns_name\n except ClientError as e:\n print(e)\n return START_EC2_ERROR\n\n\n# initialize an instance\ndef start_instance(image_id, new_ws):\n instance_DNS = launch_instance(image_id)\n if instance_DNS == START_EC2_ERROR:\n return START_EC2_ERROR\n init_url = ''\n if image_id == LG_IMAGE_ID:\n init_url += 'http://' + LG_INSTANCE_DNS + '/password'\n param_url = {\n 'passwd': SUBMISSION_PASSWORD,\n 'username': SUBMISSION_USERNAME}\n else:\n if new_ws is False:\n init_url += 'http://' + LG_INSTANCE_DNS + '/test/horizontal'\n else:\n init_url += 'http://' + LG_INSTANCE_DNS + '/test/horizontal/add'\n param_url = {'dns': instance_DNS}\n\n init_count = 0\n while init_count < INIT_INSTANCE_MAX_TRY:\n init_count += 1\n try:\n response = requests.get(init_url, params=param_url)\n if response.text != '':\n if image_id == LG_IMAGE_ID:\n print(response.url)\n break\n else:\n print(response.url)\n if (response.text).find('running') == -1:\n print(\"Web Server not ready yet, wait...\")\n time.sleep(CHECK_URL_DELAY)\n else:\n global TEST_NUMBER\n start_index = (response.text).find('name=test.', 0)\n start_index += len('name=test.')\n end_index = (response.text).find('.log',\n start_index)\n TEST_NUMBER = (response.text)[start_index:\n end_index]\n break\n\n except Exception as e:\n print(\"Load Generator not ready yet, wait...\")\n print(e)\n time.sleep(CHECK_URL_DELAY)\n if init_count == INIT_INSTANCE_MAX_TRY - 1:\n print(\"max attempt time exceeds\")\n return START_EC2_ERROR\n\n return START_EC2_SUCCESS\n\n\n# check the test log\ndef check_test_log():\n init_url = 'http://' + LG_INSTANCE_DNS + '/log'\n param_url = {'name': 'test.' + TEST_NUMBER + '.log'}\n init_count = 0\n while init_count < INIT_INSTANCE_MAX_TRY:\n init_count += 1\n try:\n response = requests.get(init_url, params=param_url)\n if response.text != '':\n print(response.url)\n break\n except Exception as e:\n print(\"log not ready yet, wait for the next attempt\")\n time.sleep(CHECK_URL_DELAY)\n if init_count == INIT_INSTANCE_MAX_TRY - 1:\n print(\"max attempt time exceeds\")\n\n log_retrieve_count = 0\n while log_retrieve_count < LOG_RETRIEVE_MAX_TRY:\n log_retrieve_count += 1\n add_new_ws = FLAG_LOG_NOT_READY\n try:\n response = requests.get(init_url, params=param_url)\n if response.text != '':\n add_new_ws = read_log(response.text)\n except Exception as e:\n print(\"log not ready yet, wait for the next attempt\")\n time.sleep(CHECK_URL_DELAY)\n if init_count == INIT_INSTANCE_MAX_TRY - 1:\n print(\"max attempt time exceeds\")\n\n if add_new_ws == FLAG_ADD_WS:\n time.sleep(ADDING_WS_DELAY)\n\n if add_new_ws == FLAG_KEEP_WS:\n print(\"reach target rps, exitting now\")\n break\n\n\n# parse and read the test log\ndef read_log(log_text):\n for current_minute in range(31, 0, -1):\n current_time = 'Minute ' + str(current_minute)\n start_index = log_text.find(current_time)\n if start_index != -1:\n rps_start_index = log_text.find('[Current rps=', start_index)\n rps_start_index += len('[Current rps=')\n rps_end_index = log_text.find(']', rps_start_index)\n current_rps = float(log_text[rps_start_index: rps_end_index])\n print(\"\\ncurrent rps: \" + str(current_rps))\n break\n\n if current_rps < TARGET_RPS:\n print(\"start adding new WS instance\")\n start_instance(WS_IMAGE_ID, True)\n print(\"end adding new WS instance\")\n return FLAG_ADD_WS\n else:\n return FLAG_KEEP_WS\n\n\n# main function\ndef main():\n global SUBMISSION_USERNAME\n global SUBMISSION_PASSWORD\n with open('tpz_usenamer_passwd.txt') as f_input:\n for line in f_input:\n SUBMISSION_USERNAME = (line.strip()).split(',')[0]\n SUBMISSION_PASSWORD = (line.strip()).split(',')[1]\n break\n\n start_instance_result = start_instance(LG_IMAGE_ID, False)\n if start_instance_result == START_EC2_ERROR:\n print(\"start load generator error, now exiting\")\n return\n\n start_instance_result = start_instance(WS_IMAGE_ID, False)\n if start_instance_result == START_EC2_ERROR:\n print(\"start first web server error, now exiting\")\n return\n\n print(\"\\nWG and WS init finished\\n\")\n\n check_test_log()\n\n print(\"load generator: \")\n print(\"ID: \" + LG_INSTANCE_ID + \", DNS: \" + LG_INSTANCE_DNS)\n\n\n# go to main function\nif __name__ == \"__main__\":\n main()\n","sub_path":"p2_1/horizontal_scaling.py","file_name":"horizontal_scaling.py","file_ext":"py","file_size_in_byte":7218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"}
    \n
    \n
    \n
    \n