\n\n Example::\n\n TwoFields(\n HTML(
Information Saved),\n Submit('Save', 'Save', css_class='ui button')\n )\n \"\"\"\n template = \"%s/layout/twofields.html\"\n\n def __init__(self, *fields, **kwargs):\n self.fields = list(fields)\n self.template = kwargs.pop('template', self.template)\n self.attrs = kwargs\n if 'css_class' in self.attrs:\n self.attrs['class'] = self.attrs.pop('css_class')\n\n def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):\n html = u''\n for field in self.fields:\n html += render_field(field, form, form_style, context, template_pack=template_pack, **kwargs)\n extra_context = {\n 'twofields': self,\n 'fields_output': html\n }\n template = self.template % template_pack\n return render_to_string(template, extra_context,\n request=getattr(context, 'request', None))\n\n def flat_attrs(self):\n return flatatt(self.attrs)\n\nclass ButtonAppendedIcon(Div):\n template = \"%s/appended_icon.html\"\n\n def __init__(self, *fields, **kwargs):\n self.fields = list(fields)\n\n if hasattr(self, 'css_class') and 'css_class' in kwargs or hasattr(self, 'icon_class') and 'icon_class' in kwargs:\n self.css_class += ' %s' % kwargs.pop('css_class')\n self.icon_class += ' %s' % kwargs.pop('icon_class')\n if not hasattr(self, 'css_class'):\n self.css_class = kwargs.pop('css_class', None)\n self.icon_class = kwargs.pop('icon_class', None)\n\n self.css_id = kwargs.pop('css_id', '')\n self.button_text = kwargs.pop('button_text', '')\n self.template = kwargs.pop('template', self.template)\n self.flat_attrs = flatatt(kwargs)\n\n def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):\n fields = ''\n for field in self.fields:\n fields += render_field(\n field, form, form_style, context, template_pack=template_pack, **kwargs\n )\n\n template = self.template % template_pack\n return render_to_string(template, {'icon_appended': self, 'fields': fields})\n\n\n\nclass PrependedAppendedText(Field):\n template = \"%s/layout/prepended_appended_text.html\"\n\n def __init__(self, field, prepended_text=None, appended_text=None, *args, **kwargs):\n self.field = field\n self.appended_text = appended_text\n self.prepended_text = prepended_text\n if 'active' in kwargs:\n self.active = kwargs.pop('active')\n \n #SO FAR IT ONLY APPENDS ASTERISK \n #self.input_size = None\n #css_class = kwargs.get('css_class', '')\n #if css_class.find('input-lg') != -1: self.input_size = 'input-lg'\n #if css_class.find('input-sm') != -1: self.input_size = 'input-sm'\n\n super(PrependedAppendedText, self).__init__(field, *args, **kwargs)\n\n def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, extra_context=None, **kwargs):\n # THIS EXTRA CONTEXT IS DISABLED FOR NOW\n #extra_context = {\n # 'crispy_appended_text': self.appended_text,\n # 'crispy_prepended_text': self.prepended_text,\n # 'input_size' : self.input_size,\n # 'active': getattr(self, \"active\", False)\n #}\n template = self.template % template_pack\n return render_field(\n self.field, form, form_style, context,\n template=template, attrs=self.attrs,\n #template_pack=template_pack, extra_context=extra_context, **kwargs\n template_pack=template_pack, **kwargs\n )\n \nclass AppendedText(PrependedAppendedText):\n def __init__(self, field, text, *args, **kwargs):\n kwargs.pop('appended_text', None)\n kwargs.pop('prepended_text', None)\n self.text = text\n super(AppendedText, self).__init__(field, appended_text=text, **kwargs)\n\n\n\nclass FormActions(LayoutObject):\n \"\"\"\n Bootstrap layout object. It wraps fields in a
\n\n Example::\n\n FormActions(\n HTML(Information Saved),\n Submit('Save', 'Save', css_class='btn-primary')\n )\n \"\"\"\n template = \"%s/layout/formactions.html\"\n\n def __init__(self, *fields, **kwargs):\n self.fields = list(fields)\n self.template = kwargs.pop('template', self.template)\n self.attrs = kwargs\n if 'css_class' in self.attrs:\n self.attrs['class'] = self.attrs.pop('css_class')\n\n def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):\n html = u''\n for field in self.fields:\n html += render_field(field, form, form_style, context, template_pack=template_pack, **kwargs)\n extra_context = {\n 'formactions': self,\n 'fields_output': html\n }\n template = self.template % template_pack\n return render_to_string(template, extra_context,\n request=getattr(context, 'request', None))\n\n def flat_attrs(self):\n return flatatt(self.attrs)\n\n\n\nclass Segment(Div):\n \"\"\"\n Base class used for `Tab` and `AccordionGroup`, represents a basic container concept\n \"\"\"\n css_class = \"\"\n\n def __init__(self, name, *fields, **kwargs):\n super(Container, self).__init__(*fields, **kwargs)\n self.template = kwargs.pop('template', self.template)\n self.name = name\n self._active_originally_included = \"active\" in kwargs\n self.active = kwargs.pop(\"active\", False)\n if not self.css_id:\n self.css_id = slugify(self.name)\n\n def __contains__(self, field_name):\n \"\"\"\n check if field_name is contained within tab.\n \"\"\"\n return field_name in map(lambda pointer: pointer[1], self.get_field_names())\n\n def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):\n if self.active:\n if not 'active' in self.css_class:\n self.css_class += ' active'\n else:\n self.css_class = self.css_class.replace('active', '')\n return super(Container, self).render(form, form_style, context, template_pack)\n\n\nclass Modal(Div):\n \"\"\"\n `Alert` generates markup in the form of an alert dialog\n\n Alert(content='Warning! Best check yo self, you're not looking too good.')\n \"\"\"\n template = \"%s/layout/alert.html\"\n css_class = \"alert\"\n\n def __init__(self, content, dismiss=True, block=False, **kwargs):\n fields = []\n if block:\n self.css_class += ' alert-block'\n Div.__init__(self, *fields, **kwargs)\n self.template = kwargs.pop('template', self.template)\n self.content = content\n self.dismiss = dismiss\n\n def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):\n template = self.template % template_pack\n return render_to_string(\n template,\n {'alert': self, 'content': self.content, 'dismiss': self.dismiss},\n request=getattr(context, 'request', None)\n )\n\n\nclass Dimmer(Div):\n \"\"\"\n `Alert` generates markup in the form of an alert dialog\n\n Alert(content='Warning! Best check yo self, you're not looking too good.')\n \"\"\"\n template = \"%s/layout/alert.html\"\n css_class = \"alert\"\n\n def __init__(self, content, dismiss=True, block=False, **kwargs):\n fields = []\n if block:\n self.css_class += ' alert-block'\n Div.__init__(self, *fields, **kwargs)\n self.template = kwargs.pop('template', self.template)\n self.content = content\n self.dismiss = dismiss\n\n def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):\n template = self.template % template_pack\n return render_to_string(\n template,\n {'alert': self, 'content': self.content, 'dismiss': self.dismiss},\n request=getattr(context, 'request', None)\n )\n","sub_path":"crispy_forms/semanticui.py","file_name":"semanticui.py","file_ext":"py","file_size_in_byte":8649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"259419309","text":"from django.utils.dateparse import parse_datetime\nfrom services.google_calendar import GoogleCalendarClient\n\n\nISO_FORMAT = '%Y-%m-%dT%H:%M:%S%z'\nSTATUS_CANCELLED = 'cancelled'\nSTATUS_CONFIRMED = 'confirmed'\n\n\ndef persist_gc_event_changes(event, gc_event):\n start_datetime = None\n if gc_event.get('start', {}).get('dateTime'):\n start_datetime = parse_datetime(gc_event['start']['dateTime'])\n\n end_datetime = None\n if gc_event.get('end', {}).get('dateTime'):\n end_datetime = parse_datetime(gc_event['end']['dateTime'])\n\n event.summary = gc_event.get('summary', '')\n event.description = gc_event.get('description', '')\n event.start = start_datetime\n event.end = end_datetime\n event.google_calendar_event_etag = gc_event.get('etag', '')\n event.is_deleted = gc_event['status'] == STATUS_CANCELLED\n\n event.save(sync_to_google_calendar=False)\n\n\ndef pull_changes_from_gc(integration):\n from events.models import Event\n\n api_client = GoogleCalendarClient(integration.user)\n\n gc_events, next_sync_token = api_client.get_all_events(\n integration.calendar_id,\n next_sync_token=integration.next_sync_token,\n )\n\n for gc_event in gc_events:\n start_data = gc_event.get('start', {})\n if start_data.get('date'):\n # We don't support full day events\n continue\n\n try:\n event = Event.objects.get(\n google_calendar_event_id=gc_event['id'],\n google_calendar_integration=integration,\n )\n except Event.DoesNotExist:\n event = Event(\n google_calendar_event_id=gc_event['id'],\n google_calendar_integration=integration,\n )\n\n persist_gc_event_changes(event, gc_event)\n\n integration.next_sync_token = next_sync_token\n integration.save()\n\n\ndef serialize_event(event):\n return {\n 'summary': event.summary,\n 'description': event.description,\n 'start': {\n 'dateTime': event.start.strftime(ISO_FORMAT),\n 'timeZone': 'UTC',\n },\n 'end': {\n 'dateTime': event.end.strftime(ISO_FORMAT),\n 'timeZone': 'UTC',\n },\n 'status': STATUS_CANCELLED if event.is_deleted else STATUS_CONFIRMED,\n }\n\n\ndef push_event_to_gc(event):\n integration = event.google_calendar_integration\n\n serialized_event = serialize_event(event)\n\n api_client = GoogleCalendarClient(integration.user)\n\n if event.google_calendar_event_id:\n response = api_client.update_event(\n integration.calendar_id,\n event.google_calendar_event_id,\n serialized_event\n )\n else:\n response = api_client.create_event(\n integration.calendar_id,\n serialized_event\n )\n\n event.google_calendar_event_id = response['id']\n event.save(sync_to_google_calendar=False)\n\n return response\n","sub_path":"services/calendar_syncing.py","file_name":"calendar_syncing.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"164771993","text":"# 1、写代码,传入一个qq群号\n# 859536221\n# 天秤座\n# 现场-乔美玲.jpg\n# 现场-周永波.jpg\n# 8595362232\n# 天蝎座\n# 现场-乔美玲.jpg\n# 现场-周永波.jpg\n# https://q4.qlogo.cn/g?b=qq&nk=564428155&s=140#获取个人头像的url\n# 然后把这个群里面的群成员的头像下载到本地,照片以群昵称命名,如果没有群昵称,用昵称\n# def get_logos(qq_num):\n\n\n\n# 输入qq号的接口,获取QQ群名\n# 拿到该群的所有QQ\n# 根据头像的接口下载头像并根据要求命名\nimport json\nimport os\nfrom collections import Iterable\n\nimport requests\n\n# 获取QQ群的信息\ndef get_info(qq_num):\n # cookie 和bkn 会改变\n url = 'https://qun.qq.com/cgi-bin/qun_mgr/search_group_members'\n header = {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'cookie': 'pgv_pvid=4386116750; pgv_pvi=1828338688; pt2gguin=o0892254410; RK=2FpVOVbAFd; ptcz=44374f0f0172d55cc360c148513cd9e7f0951f18615f4761335c862391f64d0c; pgv_si=s4387110912; p_uin=o0892254410; enc_uin=2xOW0PHhbamvqljRhlxYOw; ptisp=cm; uin=o0892254410; skey=@jKN2DFuhr; pt4_token=LTUT1jAaHp*a0glTcB5Omucln2R2aYch2loZ-rS1QX8_; p_skey=gN3ZH9Gzek9RoM2gw6FzmXciiftXMPQB7WK96P04AZg_'\n }\n data = 'gc=%s&st=0&end=200&sort=0&bkn=419014259'%qq_num\n res = requests.post(url, data=data, headers=header).json()\n mems = res.get('mems')\n print(mems)\n return mems\n\n\n# 创建文件夹,下载图片\ndef save_info(qq_num):\n mems = get_info(qq_num)\n group_name = get_name(qq_num)\n dir_name = '{}-{}'.format(qq_num, group_name)\n print(dir_name)\n # 判断群文件夹是否存在\n if not os.path.isdir(dir_name):\n os.mkdir(dir_name)\n for m in mems:\n jpg_url = 'https://q4.qlogo.cn/g?b=qq&nk={}&s=140'.format(m.get('uin'))\n if m.get('card'):\n jpg_path = os.path.join(dir_name, '%s.jpg')%m.get('card')\n else:\n jpg_path = os.path.join(dir_name, '%s.jpg')%m.get('nick')\n with open(jpg_path, 'wb') as f:\n f.write(requests.get(jpg_url).content)\n\n\n# 获取QQ群名\ndef get_name(qq_num):\n url = 'https://qun.qq.com/cgi-bin/qun_mgr/get_group_list'\n headers = {\n 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'cookie': 'pgv_pvid=4386116750; pgv_pvi=1828338688; pt2gguin=o0892254410; RK=2FpVOVbAFd; ptcz=44374f0f0172d55cc360c148513cd9e7f0951f18615f4761335c862391f64d0c; pgv_si=s4387110912; p_uin=o0892254410; enc_uin=2xOW0PHhbamvqljRhlxYOw; ptisp=cm; uin=o0892254410; skey=@jKN2DFuhr; pt4_token=LTUT1jAaHp*a0glTcB5Omucln2R2aYch2loZ-rS1QX8_; p_skey=gN3ZH9Gzek9RoM2gw6FzmXciiftXMPQB7WK96P04AZg_'\n }\n data = 'bkn=419014259'\n res = requests.post(url, data=data, headers=headers).json()\n for k, v in res.items():\n if isinstance(v, Iterable):\n for m in v:\n if m.get('gc') == qq_num:\n print(m.get('gn'))\n return m.get('gn')\n\n\nsave_info()","sub_path":"homework/day 8/get_qq_logos.py","file_name":"get_qq_logos.py","file_ext":"py","file_size_in_byte":3100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"122113600","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2016 matsumotoyasuyuki\n#\n# Distributed under terms of the MIT license.\n\n\"\"\"\n\n\"\"\"\nimport unmo\n\n\ndef prompt(unmo):\n return unmo.name + ':' + unmo.responder_name() + '> '\n\nif __name__ == '__main__':\n print('Unmo System prototype: proto')\n proto = unmo.Unmo('proto')\n while True:\n print('> ', end='')\n i = input()\n if i == '':\n break\n\n response = proto.dialogue(i)\n print(prompt(proto) + response)\n\n","sub_path":"pylove/noby/proto/proto.py","file_name":"proto.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"144755572","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Ref: http://doc.qt.io/qt-5/modelview.html#2-1-a-read-only-table\n\nimport sys\nfrom PySide6 import QtCore, QtWidgets\n\nfrom PySide6.QtCore import Qt\nfrom PySide6.QtWidgets import QApplication, QTableView\nfrom PySide6.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel\n\n\n# INIT THE DATABASE #############################\n\ndb = QSqlDatabase.addDatabase(\"QSQLITE\")\ndb.setDatabaseName(\":memory:\") # or put the path of the database here...\nassert db.open()\n\n# CREATE TABLE\n\nq = QSqlQuery()\nassert q.exec(\"CREATE TABLE employee(id iNTEGER PRIMARY KEY, first_name VARCHAR, last_name VARCHAR)\")\n\n# INSERT VALUES\n\nassert q.prepare(\"INSERT INTO employee(first_name, last_name) VALUES(?, ?)\")\n\nq.addBindValue(\"Jean\")\nq.addBindValue(\"Dupont\")\nq.exec()\n\nq.addBindValue(\"Paul\")\nq.addBindValue(\"Dupond\")\nq.exec()\n\n\n#################################################\n\napp = QApplication(sys.argv)\n\ntable_view = QTableView()\n\nmodel = QSqlQueryModel()\nmodel.setQuery(\"SELECT * FROM employee\")\n\ntable_view.setModel(model)\ntable_view.show()\n\n# The mainloop of the application. The event handling starts from this point.\nexit_code = app.exec()\n\n# The sys.exit() method ensures a clean exit.\n# The environment will be informed, how the application ended.\nsys.exit(exit_code)\n","sub_path":"python/pyside/pyside6/widget_QSqlQueryModel_sqlite_in_memory.py","file_name":"widget_QSqlQueryModel_sqlite_in_memory.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"151933096","text":"#-\n# SPDX-License-Identifier: BSD-2-Clause\n#\n# Copyright (c) 2020 Michael Dodson\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n#\n\ndef options(ctx):\n ctx.load('compiler_c');\n\n ctx.add_option('--target',\n action='store',\n default='freertos',\n help='Target OS for the build (supported: linux/freertos, default: freertos)')\n\n ctx.add_option('--endpoint',\n action='store',\n default='server',\n help='Build a Modbus client or server (supported: client/server, default: server)')\n\ndef configure_modbus_options(ctx):\n modbus_options = [\"macro\", # Compile FreeRTOS Modbus server for microbenchmarking and set execution period\n \"micro\", # Compile FreeRTOS Modbus server for macrobenchmarking and set simulated network delay (default = 0)\n \"net\", # Compile FreeRTOS Modbus server to use network capabilities\n \"obj\", # Compile FreeRTOS Modbus server to use local object capabilities\n \"objstubs\", # Compile FreeRTOS Modbus server to call into, but not use, the local object capabilities layer. Used to measure cost of the object capabilities shim layer.\n \"execperiod\", # The execution period for the Modbus server in milliseconds (default = 0)\n \"netdelay\", # The simulated network delay for the Modbus server in milliseconds (default = 0)\n ]\n\n ctx.env.MODBUS_MACROBENCHMARK = 0\n ctx.env.MODBUS_MICROBENCHMARK = 0\n ctx.env.MODBUS_EXEC_PERIOD = 0\n ctx.env.MODBUS_NETWORK_DELAY = 0\n\n demo = ctx.env.PROG\n demo_options = demo.split('-')\n\n for option in demo_options:\n if any(option in opt for opt in modbus_options):\n if \"macro\" in option:\n ctx.env.MODBUS_MACROBENCHMARK = 1\n if \"micro\" in option:\n ctx.env.MODBUS_MICROBENCHMARK = 1\n if \"obj\" in option:\n ctx.env.MODBUS_OBJECT_CAPS = 1\n if \"objstubs\" in option:\n ctx.env.MODBUS_OBJECT_CAPS_STUBS = 1\n if \"net\" in option:\n ctx.env.MODBUS_NETWORK_CAPS = 1\n if \"execperiod\" in option:\n ctx.env.MODBUS_EXEC_PERIOD = option.split('_')[1]\n if \"netdelay\" in option:\n ctx.env.MODBUS_NETWORK_DELAY = option.split('_')[1]\n\ndef configure(ctx):\n print(\"Configuring modcap @\", ctx.path.abspath())\n\n ctx.load('compiler_c');\n\n # ENV - Save options for build stage\n try:\n ctx.env.TARGET = ctx.options.target\n except:\n ctx.env.TARGET = 'freertos'\n\n # If this wscript is being consumed by a larger project, options() is never called,\n # so we need to set suitable defaults, since ctx.options.target/endpoint will\n # cause an exception.\n try:\n ctx.env.ENDPOINT = ctx.options.endpoint\n except:\n ctx.env.ENDPOINT = 'server'\n\n # Check for a supported target/endpoint combination\n if ctx.env.TARGET == 'freertos':\n if ctx.env.ENDPOINT != 'server':\n ctx.fatal('Only Modbus servers are supported for FreeRTOS')\n elif ctx.env.TARGET == 'linux':\n if ctx.env.ENDPOINT != 'client':\n ctx.fatal('Only Modbus clients are supported for Linux')\n else:\n ctx.fatal('Unsupported target (only freertos and linux are supported)')\n\n ctx.env.append_value('INCLUDES', [\n ctx.path.abspath(),\n ctx.path.abspath() + '/include',\n ctx.path.abspath() + '/libmodbus/',\n ctx.path.abspath() + '/libmodbus/src/',\n ctx.path.abspath() + '/libmodbus/include/',\n ctx.path.abspath() + '/libmacaroons/include/',\n ctx.path.abspath() + '/libmodbus_object_caps/include/',\n ctx.path.abspath() + '/libmodbus_network_caps/include/',\n ctx.path.abspath() + '/modbus_benchmarks/include/',\n ])\n\n # Additional library dependencies and includes if we're targeting freertos\n if ctx.env.TARGET == 'freertos':\n\n # Configure modbus options\n configure_modbus_options(ctx)\n\n ctx.env.append_value('DEFINES', [\n 'configPROG_ENTRY = main_modbus',\n ])\n\n ctx.env.append_value('LIB_DEPS', ['freertos_tcpip', 'virtio'])\n\n if ctx.env.ENDPOINT == 'server':\n ctx.env.append_value('INCLUDES', [\n ctx.path.abspath() + '/modbus_server/include/',\n ])\n\n # Generic defines\n ctx.define('configCOMPARTMENTS_NUM', 1024)\n ctx.define('configMAXLEN_COMPNAME', 255)\n\n # Modbus defines\n if ctx.env.MODBUS_MICROBENCHMARK:\n ctx.define('MODBUS_MICROBENCHMARK', 1)\n ctx.define('NDEBUG', 1)\n\n if ctx.env.MODBUS_MACROBENCHMARK:\n ctx.define('MODBUS_MACROBENCHMARK', 1)\n ctx.define('NDEBUG', 1)\n\n if ctx.env.MODBUS_EXEC_PERIOD:\n ctx.define('modbusEXEC_PERIOD_MS', int(ctx.env.MODBUS_EXEC_PERIOD))\n\n if ctx.env.MODBUS_NETWORK_DELAY:\n ctx.define('modbusNETWORK_DELAY_MS', int(ctx.env.MODBUS_NETWORK_DELAY))\n\n if ctx.env.MODBUS_OBJECT_CAPS:\n ctx.define('MODBUS_OBJECT_CAPS', 1)\n\n if ctx.env.MODBUS_OBJECT_CAPS_STUBS:\n ctx.define('MODBUS_OBJECT_CAPS_STUBS', 1)\n\n if ctx.env.MODBUS_NETWORK_CAPS:\n ctx.define('MODBUS_NETWORK_CAPS', 1)\n\ndef build(bld):\n print(\"Building modcap\")\n\n MODBUS_SERVER_DIR = 'modbus_server/'\n MODBUS_CLIENT_DIR = 'modbus_client/'\n LIBMACAROONS_DIR = 'libmacaroons/'\n LIBMODBUS_DIR = 'libmodbus/'\n LIBMODBUS_OBJECT_CAPS_DIR = 'libmodbus_object_caps/'\n LIBMODBUS_NETWORK_CAPS_DIR = 'libmodbus_network_caps/'\n MODBUS_BENCHMARKS_DIR = 'modbus_benchmarks/'\n\n if bld.env.TARGET == 'linux' and bld.env.ENDPOINT == 'client':\n bld.stlib(features=['c'],\n source=[\n LIBMODBUS_DIR + 'src/modbus.c',\n LIBMODBUS_DIR + 'src/modbus-data.c',\n LIBMODBUS_DIR + 'src/modbus-helpers.c',\n LIBMODBUS_DIR + 'src/modbus-tcp.c',\n LIBMODBUS_DIR + 'src/modbus-rtu.c',\n ],\n use=[],\n target='modbus')\n\n bld.stlib(\n features=['c'],\n source=[\n LIBMACAROONS_DIR + 'src/base64.c',\n LIBMACAROONS_DIR + 'src/explicit_bzero.c',\n LIBMACAROONS_DIR + 'src/macaroons.c',\n LIBMACAROONS_DIR + 'src/packet.c',\n LIBMACAROONS_DIR + 'src/port.c',\n LIBMACAROONS_DIR + 'src/sha256.c',\n LIBMACAROONS_DIR + 'src/shim.c',\n LIBMACAROONS_DIR + 'src/slice.c',\n LIBMACAROONS_DIR + 'src/timingsafe_bcmp.c',\n LIBMACAROONS_DIR + 'src/tweetnacl.c',\n LIBMACAROONS_DIR + 'src/v1.c',\n LIBMACAROONS_DIR + 'src/v2.c',\n LIBMACAROONS_DIR + 'src/varint.c'\n ],\n use=[],\n target=\"macaroons\")\n\n bld.stlib(features=['c'],\n source=[LIBMODBUS_NETWORK_CAPS_DIR + 'src/modbus_network_caps.c'],\n use=[\n \"macaroons\",\n \"modbus\"],\n target=\"modbus_network_caps\")\n\n bld.stlib(features=['c'],\n source=[MODBUS_BENCHMARKS_DIR + 'src/microbenchmark.c'],\n use=[\"modbus\"],\n target=\"modbus_benchmarks\")\n\n # build a basic modbus client to test a modbus server\n bld.program(features=['c'],\n source=[MODBUS_CLIENT_DIR + 'modbus_test_client.c'],\n use=['modbus'],\n target='modbus_test_client')\n\n # build a modbus client to benchmark a modbus server\n bld.program(features=['c'],\n source=[MODBUS_CLIENT_DIR + 'modbus_test_client.c'],\n use=[\n 'modbus',\n 'modbus_benchmarks',\n ],\n defines=bld.env.DEFINES + ['MODBUS_BENCHMARK=1'],\n target='modbus_test_client_bench')\n\n # build a modbus client to test a modbus server with network capabiliies\n bld.program(features=['c'],\n source=[MODBUS_CLIENT_DIR + 'modbus_test_client.c'],\n use=[\n 'modbus',\n 'modbus_network_caps'\n ],\n defines=bld.env.DEFINES + ['MODBUS_NETWORK_CAPS=1'],\n target='modbus_test_client_network_caps')\n\n # build a modbus client to benchmark a modbus server with network capabiliies\n bld.program(features=['c'],\n source=[MODBUS_CLIENT_DIR + 'modbus_test_client.c'],\n use=[\n 'modbus',\n 'modbus_benchmarks',\n 'modbus_network_caps'\n ],\n defines=bld.env.DEFINES + [\n 'MODBUS_NETWORK_CAPS=1',\n 'MODBUS_BENCHMARK=1'\n ],\n target='modbus_test_client_network_caps_bench')\n\n if bld.env.TARGET == 'freertos' and bld.env.ENDPOINT == 'server':\n cflags = []\n\n if bld.env.COMPARTMENTALIZE:\n cflags = ['-cheri-cap-table-abi=gprel']\n\n bld.stlib(features=['c'],\n source=[\n LIBMODBUS_DIR + 'src/modbus.c',\n LIBMODBUS_DIR + 'src/modbus-data.c',\n LIBMODBUS_DIR + 'src/modbus-tcp.c',\n LIBMODBUS_DIR + 'src/modbus-helpers.c'\n ],\n use=[\n \"freertos_core\",\n \"freertos_bsp\",\n \"freertos_tcpip\"\n ],\n target=\"modbus\")\n\n bld.stlib(\n features=['c'],\n source=[\n LIBMACAROONS_DIR + 'src/base64.c',\n LIBMACAROONS_DIR + 'src/explicit_bzero.c',\n LIBMACAROONS_DIR + 'src/macaroons.c',\n LIBMACAROONS_DIR + 'src/packet.c', LIBMACAROONS_DIR + 'src/port.c',\n LIBMACAROONS_DIR + 'src/sha256.c', LIBMACAROONS_DIR + 'src/shim.c',\n LIBMACAROONS_DIR + 'src/slice.c',\n LIBMACAROONS_DIR + 'src/timingsafe_bcmp.c',\n LIBMACAROONS_DIR + 'src/tweetnacl.c',\n LIBMACAROONS_DIR + 'src/v1.c', LIBMACAROONS_DIR + 'src/v2.c',\n LIBMACAROONS_DIR + 'src/varint.c'\n ],\n use=[\n \"freertos_core\",\n \"freertos_bsp\"\n ],\n target=\"macaroons\")\n\n if bld.env.PURECAP:\n bld.stlib(features=['c'],\n source=[LIBMODBUS_OBJECT_CAPS_DIR + 'src/modbus_object_caps.c'],\n use=[\n \"freertos_core\",\n \"freertos_bsp\",\n \"freertos_tcpip\"\n ],\n defines=bld.env.DEFINES + ['MODBUS_OBJECT_CAPS=1'],\n target=\"modbus_object_caps\")\n\n bld.stlib(features=['c'],\n source=[LIBMODBUS_NETWORK_CAPS_DIR + 'src/modbus_network_caps.c'],\n use=[\n \"freertos_core\",\n \"freertos_bsp\",\n \"freertos_tcpip\",\n \"macaroons\"\n ],\n target=\"modbus_network_caps\")\n\n bld.stlib(features=['c'],\n source=[MODBUS_BENCHMARKS_DIR + 'src/microbenchmark.c'],\n use=[\n \"modbus\",\n \"freertos_core\",\n \"freertos_bsp\",\n \"freertos_tcpip\",\n ],\n target=\"modbus_benchmarks\")\n\n bld.stlib(\n features=['c'],\n cflags = bld.env.CFLAGS + cflags,\n source=[\n MODBUS_SERVER_DIR + 'src/main_modbus.c',\n MODBUS_SERVER_DIR + 'src/ModbusServer.c',\n ],\n use=[\n \"freertos_core_headers\", \"freertos_bsp_headers\", \"freertos_tcpip_headers\",\n \"freertos_libdl_headers\", \"virtio_headers\", \"cheri_headers\", \"modbus\",\n \"modbus_object_caps\", \"modbus_network_caps\", \"modbus_benchmarks\", \"virtio\"\n ],\n target=bld.env.PROG)\n","sub_path":"wscript","file_name":"wscript","file_ext":"","file_size_in_byte":13786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"149107943","text":"from django.conf.urls import url\n\nfrom . import views\n\n\"\"\"Form URL documentation\n\nurlpatterns sorts urls based on characters after form in the url\n\nif no characters it goes to form,\nif it begins with your it goes to the index test page\n\nthanks will redirect to form unless directed to by form, in which case it\nreturns the reverse of the string in the your_name entry in the post dictionary\n\n\"\"\"\n\nurlpatterns = [\n\turl(r'^$',views.get_name, name = 'name'),\n\turl(r'^thanks',views.thanks, name = 'thanks'),\n\turl(r'^your',views.index, name= 'test'),\n\turl(r'^', views.formredirect, name = 'redirect'),\n]","sub_path":"proteins/form/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"626547304","text":"import tensorflow as tf\nimport torchfile\n\nclass VGG19:\n def __init__(self, t7_file):\n \"\"\"\n :param input img to vgg19 inputwork \n :param t7_file path to trained torch files provided here https://s3.amazonaws.com/xunhuang-public/adain/*\n\n borrowed https://github.com/jonrei/tf-AdaIN/blob/master/AdaIN.py\n \"\"\"\n self.t7_restored_model = torchfile.load(t7_file, force_8bytes_long=False)\n # end\n\n def get_rep(self, input):\n layers = []\n for idx, module in enumerate(self.t7_restored_model.modules):\n if module._typename == b'nn.SpatialReflectionPadding':\n left = module.pad_l\n right = module.pad_r\n top = module.pad_t\n bottom = module.pad_b\n input = tf.pad(input, [[0, 0], [top, bottom], [left, right], [0, 0]], 'REFLECT')\n layers.append(input)\n elif module._typename == b'nn.SpatialConvolution':\n weight = module.weight.transpose([2, 3, 1, 0])\n bias = module.bias\n strides = [1, module.dH, module.dW, 1] # Assumes 'NHWC'\n input = tf.nn.conv2d(input, weight, strides, padding='VALID')\n input = tf.nn.bias_add(input, bias)\n layers.append(input)\n elif module._typename == b'nn.ReLU':\n input = tf.nn.relu(input)\n layers.append(input)\n elif module._typename == b'nn.SpatialUpSamplingNearest':\n d = tf.shape(input)\n size = [d[1] * module.scale_factor, d[2] * module.scale_factor]\n input = tf.image.resize_nearest_neighbor(input, size)\n layers.append(input)\n elif module._typename == b'nn.SpatialMaxPooling':\n input = tf.nn.max_pool(input, ksize=[1, module.kH, module.kW, 1], strides=[1, module.dH, module.dW, 1],\n\t\t\t padding='VALID', name=str(module.name, 'utf-8'))\n layers.append(input)\n else:\n raise NotImplementedError(module._typename)\n return input, layers\n # end\n# end\n","sub_path":"webServer/www/style_transfer/src/vgg19.py","file_name":"vgg19.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"73322652","text":"#!usr/bin/env python3\r\n\"\"\"Playground for testing JSON.\"\"\"\r\n\r\nimport json\r\na = [1, 2, 3, 5, 9, 7]\r\n\r\nfor i in a:\r\n print(i)\r\nprint('======')\r\n\r\n #__iter__() #get the iterator\r\n #__next__() #gets the next iterator\r\n\r\na = [1, 5]\r\nit = iter(a) #used to get the iterator object, can use to call all alues in collections\r\nb = next(it) #get first item in list\r\nprint(b)\r\nb = next(it) #get next item in list\r\nprint(b)\r\nb = next(it) #out of iterables, should throw \"StopIteration\"\r\nprint(b)\r\n\r\n# can loop over iterations\r\n","sub_path":"vagrant/json_tutorial/python_json_iterators.py","file_name":"python_json_iterators.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"202998829","text":"#!/usr/bin/env python3\nimport os\nimport requests\n\nfrom selfdrive.test.process_replay.test_processes import segments\nfrom selfdrive.test.process_replay.process_replay import CONFIGS\n\nBASE_URL = \"https://github.com/martinl/openpilot-ci/raw/master/process_replay/\"\n\nprocess_replay_dir = os.path.dirname(os.path.abspath(__file__))\nref_commit = open(os.path.join(process_replay_dir, \"ref_commit\")).read().strip()\n\nfor car_brand, segment in segments:\n for cfg in CONFIGS:\n cmp_log_url = (BASE_URL + \"%s/%s_%s_%s.bz2\" % (ref_commit, segment.replace(\"|\", \"_\"), cfg.proc_name, ref_commit))\n cmp_log_fn = os.path.join(process_replay_dir, \"%s_%s_%s.bz2\" % (segment, cfg.proc_name, ref_commit))\n r = requests.get(cmp_log_url)\n if r.status_code == 200:\n with open(cmp_log_fn, 'wb') as f:\n f.write(r.content)\n else:\n print(\"Failed to download: \" + cmp_log_url)\n","sub_path":"selfdrive/test/process_replay/download_ref_logs.py","file_name":"download_ref_logs.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"532198290","text":"count=0\r\nfor i in range(0,1440):\r\n time_i=int(i/60)*100 + int((i%60))\r\n isnum=list(str(time_i))\r\n a=0\r\n for three in isnum:\r\n if three == '3' and a==0:\r\n count += 1\r\n a=1\r\n\r\nprint(count*60)\r\n","sub_path":"01.jump to python/codingdojang/3cnt.py","file_name":"3cnt.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"511836024","text":"\nfrom copy import copy, deepcopy\nfrom fractions import Fraction\n\n__author__ = \"Justin Traglia\"\n__email__ = \"jwt0006@uah.edu\"\n\nclass Matrix:\n\n\t\"\"\" Class for matrices. Allows easier matrix operations\n\t\"\"\"\n\n\tvalues = []\n\n\tdef __init__(self, matrix):\n\n\t\t\"\"\" Function to create matrix. Supports both string and list based\n\t\tmatrices. \n\n\t\tA = Matrix('1 2 3; 4 5 6; 7 8 9')\n\t\tB = Matrix([[1,2,3],[4,5,6],[7,8,9]])\n\n\t\tA == B\n\n\t\t\"\"\"\n\n\t\tif not matrix:\n\t\t\traise Exception(\"Empty matrix.\")\n\n\t\t# handle string matrix\n\n\t\tif isinstance(matrix, str):\n\t\t\tmatrix = matrix.split(';')\n\t\t\tmatrix = [e.split() for e in matrix]\n\t\t\tmatrix = [map(float, a) for a in matrix]\n\n\t\t# check that all rows are the same length\n\n\t\tfor row in matrix:\n\t\t\tif len(row) != len(matrix[0]):\n\t\t\t\traise Exception(\"Not all rows are the same length\")\n\n\t\tself.values = matrix\n\n\t\n\t@staticmethod\n\tdef is_even(n):\n\t\treturn n % 2 is 0\n\n\n\t@staticmethod\n\tdef dot(v1, v2):\n\n\t\t\t\"\"\" Returns the dot product of two vectors.\n\t\t\t\"\"\"\n\n\t\t\tif len(v1) != len(v2):\n\t\t\t\t\traise Exception(\"These vectors can't be multiplied.\")\n\n\t\t\tdot_product = 0\n\n\t\t\tfor r, c in zip(v1, v2):\n\t\t\t\t\tdot_product += r * c\n\n\t\t\treturn dot_product\n\n\n\t@staticmethod\n\tdef check_size(size):\n\n\t\t\t\"\"\" Raises exception if either length is less than one.\n\t\t\t\"\"\"\n\n\t\t\tif size[0] < 1 or size[1] < 1:\n\t\t\t\t\traise Exception(\"Bad matrix size\")\n\n\n\t@staticmethod\n\tdef zero_matrix(size):\n\n\t\t\t\"\"\" Returns a zero matrix of specified size.\n\t\t\t\"\"\"\n\n\t\t\tMatrix.check_size(size)\n\n\t\t\tC = [[0 for x in range(size[1])] for x in range(size[0])]\n\n\t\t\treturn Matrix(C)\n\n\n\t@staticmethod\n\tdef one_matrix(size):\n\n\t\t\t\"\"\" Returns a matrix full of ones of specified size.\n\t\t\t\"\"\"\n\n\t\t\tMatrix.check_size(size)\n\n\t\t\tC = [[1 for x in range(size[1])] for x in range(size[0])]\n\n\t\t\treturn Matrix(C)\n\n\n\t@staticmethod\n\tdef identity_matrix(size):\n\n\t\t\t\"\"\" Returns a zero matrix of specified size.\n\t\t\t\"\"\"\n\n\t\t\trows = None\n\t\t\tcols = None\n\n\t\t\tif isinstance(size, tuple):\n\t\t\t\t\tMatrix.check_size(size)\n\n\t\t\t\t\tif size[0] != size[1]:\n\t\t\t\t\t\t\traise Exception(\"Identity matrix must be square.\")\n\n\t\t\t\t\trows = size[0]\n\t\t\t\t\tcols = size[1]\n\t\t\telse:\n\t\t\t\t\trows = size\n\t\t\t\t\tcols = size\n\n\t\t\tC = Matrix.zero_matrix((rows, cols)).values\n\n\t\t\tfor r in range(0, rows):\n\t\t\t\t\tfor c in range(0, cols):\n\t\t\t\t\t\t\tif r == c: C[r][c] = 1\n\n\t\t\treturn Matrix(C)\n\n\n\tdef size(self):\n\t\t\n\t\t\"\"\" Returns a tuple with the row and column length. The format is\n\t\t(num_of_rows, num_of_columns)\n\t\t\"\"\"\n\n\t\treturn (len(self.values), len(self.values[0]))\n\n\n\tdef row(self, index):\n\n\t\t\"\"\" Returns a copy of the matrix's row.\n\t\t\"\"\"\n\n\t\treturn copy(self.values[index-1])\n\n\n\tdef num_of_rows(self):\n\n\t\t\"\"\" Returns the number of rows the matrix has.\n\t\t\"\"\"\n\n\t\treturn len(self.values)\n\n\n\tdef column(self, index):\n\n\t\t\"\"\" Returns a copy of the matrix's column.\n\t\t\"\"\"\n\n\t\treturn [item[index-1] for item in self.values]\n\n\n\tdef num_of_columns(self):\n\n\t\t\"\"\" Returns the number of columns the matrix has.\n\t\t\"\"\"\n\n\t\treturn len(self.row(0))\n\n\n\tdef __add__(self, other):\n\n\t\t\"\"\" Adds matrix to self. Returns a new matrix.\n\t\t\"\"\"\n\n\t\tif self.size() != other.size():\n\t\t\traise Exception(\"Matrices must be the same size\")\n\n\t\tC = []\n\n\t\tfor A, B in zip(self.values, other.values):\n\t\t\trow = [a + b for a, b in zip(A, B)]\n\t\t\tC.append(row)\n\n\t\treturn Matrix(C)\n\n\n\tdef __sub__(self, other):\n\n\t\t\"\"\" Subtracts matrix from self. Returns a new matrix.\n\t\t\"\"\"\n\n\t\tif self.size() != other.size():\n\t\t\traise Exception(\"Matrices must be the same size\")\n\n\t\tC = []\n\n\t\tfor A, B in zip(self.values, other.values):\n\t\t\trow = [a - b for a, b in zip(A, B)]\n\t\t\tC.append(row)\n\n\t\treturn Matrix(C)\n\n\n\tdef __rmul__(self, other):\n\n\t\t\"\"\" Right side multiplication of matrix. Calls left side because the\n\t\ttwo methods should produce the same result.\n\n\t\tKeep in mind that A x B is not always the same as B x A\n\n\t\tThis isn't a problem though, because a matrix times another matrix will\n\t\talways try to call the left object's method.\n\n\t\tReturns new matrix.\n\t\t\"\"\"\n\n\t\treturn self * other\n\n\n\tdef __mul__(self, other):\n\n\t\t\"\"\" Handles scalar and matrix multiplication. If the matrix is being\n\t\tmultiplied by a scalar, each element in the matrix is multiplied by the\n\t\tscalar. If the matrix is being multiplied by another matrix, the dot\n\t\tproduct of each row / column is done to produce a new matrix.\n\t\t\"\"\"\n\n\t\tC = []\n\n\t\tif isinstance(other, int) or isinstance(other, float):\n\n\t\t\t# scalar multiplication\n\n\t\t\tfor row in self.values:\n\t\t\t\tnew_row = [ other * e for e in row]\n\t\t\t\tC.append(new_row)\n\n\t\telif isinstance(other, Matrix):\n\n\t\t\t# matrix multiplication\n\n\t\t\trows = self.num_of_rows()\n\t\t\tcols = other.num_of_columns()\n\n\t\t\t# columns of A must be == rows of B\n\n\t\t\tif self.num_of_columns() != other.num_of_rows():\n\t\t\t\traise Exception(\"Can not multiply these matrices.\")\n\n\t\t\tC = Matrix.zero_matrix((rows, cols)).values\n\n\t\t\tfor x in range(0, rows):\n\t\t\t\tfor y in range(0, cols):\n\t\t\t\t\trow = self.row(x+1)\n\t\t\t\t\tcol = other.column(y+1)\n\t\t\t\t\tC[x][y] = Matrix.dot(row, col)\n\n\t\treturn Matrix(C)\n\n\n\tdef __pow__(self, times):\n\n\t\t\"\"\" Handles matrix powers. Returns new matrix.\n\t\t\"\"\"\n\n\t\tC = self\n\n\t\tfor x in range(1, times):\n\t\t\tC = C * self\n\n\t\treturn C\n\n\n\tdef __rdiv__(self, other):\n\n\t\t\"\"\" Here just incase someone trys to divide a matrix by some value.\n\t\tWill always raise an exception.\n\t\t\"\"\"\n\n\t\traise Exception(\"Division not supported\")\n\n\n\tdef __div__(self, other):\n\n\t\t\"\"\" Here just incase someone trys to divide a matrix by some value.\n\t\tWill always raise an exception.\n\t\t\"\"\"\n\n\t\traise Exception(\"Division not supported\")\n\n\tdef __neg__(self):\n\n\t\t\"\"\" When a negative sign is appended to matrix. Returns the matrix\n\t\ttimes -1. Returns a matrix.\n\t\t\"\"\"\n\n\t\treturn -1 * self\n\n\n\tdef __eq__(self, other):\n\n\t\t\"\"\" Compare the contents of self and other. Returns True if the\n\t\tcontents are the same. Returns False if anything is different.\n\n\t\tBe cautious of floating point comparisions.\n\t\t\"\"\"\n\n\t\tif self.size() != other.size():\n\t\t\treturn False\n\n\t\tfor x in range(0, self.num_of_rows()):\n\t\t\tfor y in range(0, self.num_of_columns()):\n\t\t\t\ta = Fraction(self.values[x][y]).limit_denominator(1000)\n\t\t\t\tb = Fraction(other.values[x][y]).limit_denominator(1000)\n\t\t\t\tif a != b: return False\n\n\t\treturn True\n\n\n\tdef __ne__(self, other):\n\n\t\t\"\"\" Compare the contents of self and other. Returns True if anything is\n\t\tdifferent. Returns False if the contents are the same.\n\n\t\tBe cautious of floating point comparisions.\n\t\t\"\"\"\n\t\t\n\t\treturn not (self == other)\n\n\n\tdef __str__(self):\n\n\t\t\"\"\" Returns the string representation of the matrix. The output looks\n\t\tpretty good in my opinion. Columns are equally spaced apart, fractions\n\t\tare supported, there will be no decimal places, enclosed by side bars.\n\t\t\"\"\"\n\t\t\n\t\ts = \"\"\n\t\twidth = None\n\t\tpretty_vals = []\n\n\t\tfor row in self.values:\n\t\t\tpretty_row = []\n\n\t\t\tfor val in row:\n\t\t\t\tprettiest = int(val) if val % 1 == 0 else Fraction(val).limit_denominator(1000)\n\t\t\t\tpretty_row.append(prettiest)\n\t\t\t\twidth = max(width, len(str(prettiest)))\n\n\t\t\tpretty_vals.append(pretty_row)\n\n\t\tfor row in pretty_vals:\n\t\t\ts += \"\\t|\"\n\t\t\tfor val in row:\n\t\t\t\tval_len = len(str(val))\n\t\t\t\ts += (\" \" * (width - val_len + 1)) + str(val)\n\t\t\ts += \" |\\n\"\n\n\t\treturn s\n\n\n\tdef rank(self):\n\n\t\t\"\"\" Determines matrix's rank and returns it. Will return a scalar, not\n\t\ta matrix.\n\n\t\tSide note of better way to do this: To find the rank of a matrix, we\n\t\tsimply transform the matrix to its row echelon form and count the\n\t\tnumber of non-zero rows.\n\t\t\"\"\"\n\n\t\tratio = lambda a, b: a / b if b != 0 else 0\n\n\t\tdef unique_products(vals):\n\n\t\t\t\"\"\" Returns a list of the unique products of a two\n\t\t\tdimensional list.\n\t\t\t\"\"\"\n\n\t\t\tups = []\n\n\t\t\tfor i in range(len(vals)):\n\t\t\t\tfor j in range(i, len(vals)):\n\t\t\t\t\tif i == j: continue\n\t\t\t\t\tups.append((vals[i], vals[j]))\n\n\t\t\treturn ups\n\n\t\trank = min(self.size())\n\n\t\tfor up in unique_products(self.values):\n\t\t\ta, b = up[0], up[1]\n\t\t\ttop_ratio = ratio(a[0], b[0])\n\t\t\tlinear = True\n\n\t\t\tfor i in range(1, len(a)):\n\t\t\t\tif ratio(a[i], b[i]) != top_ratio:\n\t\t\t\t\tlinear = False\n\n\t\t\tif linear: rank -=1\n\n\t\treturn rank\n\n\n\tdef determinant(self):\n\n\t\t\"\"\" Recursive function for computing the determinant of a matrix.\n\t\tBreaks matrix down until it reaches a 2 x 2 matrix.\n\n\t\tThe thought for a recursive determinant came from:\n\t\t\thttp://nebula.deanza.edu/~bloom/math43/Determinant4x4Matrix.pdf\n\n\t\tReturns a scalar, not a matrix.\n\t\t\"\"\"\n\n\t\tif self.size() == (1,1):\n\t\t\treturn self.values[0][0]\n\n\t\tif self.size() == (2,2):\n\t\t\ta = self.values\n\t\t\treturn (a[0][0] * a[1][1]) - (a[0][1] * a[1][0])\n\n\t\tdeterm = 0\n\t\ttop = self.row(1)\n\n\t\tfor i in range(0, len(top)):\n\t\t\tsd = top[i] * self.minor(0, i).determinant()\n\t\t\tdeterm += sd if self.is_even(i) else -sd\n\n\t\treturn determ\n\n\n\tdef transpose(self):\n\n\t\t\"\"\" Returns the transpose of matrix self. Swaps all of the rows with\n\t\tthe columns.\n\t\t\"\"\"\n\n\t\tC = []\n\n\t\tfor i in range(1, self.num_of_columns() + 1):\n\t\t\tC.append(self.column(i))\n\n\t\treturn Matrix(C)\n\n\n\tdef minor(self, row, col):\n\n\t\t\"\"\" Makes a copy of self, then deletes the row and column from it.\n\t\tReturns new matrix.\n\t\t\"\"\"\n\n\t\tC = deepcopy(self.values)\n\t\tdel C[row]\n\n\t\tfor row in C:\n\t\t\tdel row[col]\n\n\t\treturn Matrix(C)\n\n\n\tdef cofactor(self, row, col):\n\n\t\t\"\"\" Calculates the cofactor of element. Needs the matrix, because the\n\t\tcofactor is location dependent. There is a special case for a 2 x 2\n\t\tmatrix. Returns a scalar value.\n\t\t\"\"\"\n\n\t\tif self.size() == (1,1):\n\t\t\treturn 1\n\n\t\tif self.size() == (2,2):\n\t\t\treturn (-1)**(row+col) * (self.values[1-row][1-col])\n\n\t\td = self.minor(row, col).determinant()\n\t\tcofactor = d if self.is_even(row) == self.is_even(col) else -d\n\n\t\treturn cofactor\n\n\n\tdef cofactor_matrix(self):\n\n\t\t\"\"\" Generates full cofactor matrix. Uses the cofactor function to do\n\t\tso. Returns new matrix.\n\t\t\"\"\"\n\n\t\trows = self.num_of_rows()\n\t\tcols = self.num_of_columns()\n\t\tC = Matrix.zero_matrix((rows, cols)).values\n\n\t\tfor x in range(0, rows):\n\t\t\tfor y in range(0, cols):\n\t\t\t\tC[x][y] = self.cofactor(x, y)\n\n\t\treturn Matrix(C)\n\n\n\tdef adjoint_matrix(self):\n\n\t\t\"\"\" Generates adjoint matrix, which is the transpose of the cofactor\n\t\tmatrix. Returns a new matrix.\n\t\t\"\"\"\n\n\t\treturn self.cofactor_matrix().transpose()\n\n\n\tdef inverse(self):\n\n\t\t\"\"\" Calculates the inverse of the matrix self. Does so by the adjoint\n\t\tmatrix method. The formula for this method is:\n\n\t\tself' = (1/determinant of self) x adjoint matrix of self\n\n\t\tChecks that there is an inverse by seeing if the determinant is zero.\n\t\tIf the determinant is zero, then the matrix does not have an inverse.\n\t\tReturns a new matrix.\n\t\t\"\"\"\n\n\t\tsize = self.size()\n\n\t\tif size[0] != size[1]:\n\t\t\traise Exception(\"Non-square matrices do not have inverses\")\n\n\t\tdeterm = self.determinant()\n\t\tif determ == 0: return None\n\n\t\treturn (1.0/determ) * self.adjoint_matrix()\n\n\t\treturn 'matrix: \\n%s' % s\n\n","sub_path":"src/trixxy.py","file_name":"trixxy.py","file_ext":"py","file_size_in_byte":10654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"521631628","text":"\"\"\"\nTraining the speaker identification model\n\"\"\"\nimport re\nimport os\nimport argparse\nfrom logzero import logger\n\nfrom interface import ModelInterface\nfrom utils import read_wav\n\n\ndef train(train_data_dir, model_path):\n m = ModelInterface()\n files = [f for f in os.listdir(train_data_dir) if re.search(r\"\\.wav\", f)]\n for f in files:\n label, _ = f.split(\"_\")\n file = os.path.join(train_data_dir, f)\n try:\n fs, signal = read_wav(file)\n m.enroll(label, fs, signal)\n logger.info(\"wav %s has been enrolled\" % (file))\n except Exception as e:\n logger.info(file + \" error %s\" % (e))\n\n m.train()\n m.dump(model_path)\n\n\ndef evaluate(eval_data_dir, model_path):\n m = ModelInterface.load(model_path)\n files = [f for f in os.listdir(eval_data_dir) if re.search(r\"\\.wav\", f)]\n total, n_correct = 0, 0\n for f in files:\n total += 1\n label, _ = f.split(\"_\")\n file = os.path.join(eval_data_dir, f)\n fs, signal = read_wav(file)\n pred, _ = m.predict(fs, signal)\n logger.info(\"Input: {}, Output: {}\".format(file, pred))\n if label == pred:\n n_correct += 1\n logger.info(\"Accuracy: {}\".format(n_correct/total))\n \n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--model_path\",\n required=True,\n help=\"Path to model file\"\n )\n parser.add_argument(\n \"--train_data_dir\",\n default=\"/Users/minhpham/nlp/data/speech/elsdsr/train\",\n help=\"Path to ELSDSR training data directory\"\n )\n parser.add_argument(\n \"--eval_data_dir\",\n default=\"/Users/minhpham/nlp/data/speech/elsdsr/test\",\n help=\"Path to evaluation data\"\n )\n parser.add_argument(\"--do_train\", action=\"store_true\", help=\"Whether to train the model\")\n parser.add_argument(\"--do_eval\", action=\"store_true\", help=\"Whether to evaluate the model\")\n args = parser.parse_args()\n \n logger.info(args)\n \n if args.do_train:\n logger.info(\"Training speaker recognition model\")\n train(args.train_data_dir, args.model_path)\n \n if args.do_eval:\n evaluate(args.eval_data_dir, args.model_path)\n \n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"run_speaker_recognition.py","file_name":"run_speaker_recognition.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"32800805","text":"\n\nfrom collections import Counter, namedtuple\nimport os\nimport urllib.request\nimport pathlib\n\n# prep\n\ntempfile = pathlib.Path(\"temporary/costam\")\nurllib.request.urlretrieve('http://bit.ly/2ABUTjv', tempfile)\n\nIGNORE = 'static templates data pybites bbelderbos hobojoe1848'.split()\n\nusers, popular_challenges = Counter(), Counter()\n\n\n\n\n\n\n\n# code\n\ndef gen_files():\n \"\"\"Return a generator of dir names reading in tempfile\n\n tempfile has this format:\n\n challenge/file_or_dir,is_dir\n 03/rss.xml,False\n 03/tags.html,False\n ...\n 03/mridubhatnagar,True\n 03/aleksandarknezevic,True\n\n -> use last column to filter out directories (= True)\n \"\"\"\n with open(tempfile, \"r\") as pliczek:\n\n lista_logow = pliczek.read().split()\n for l in lista_logow:\n pojedynczy_log = l.split(',')\n if pojedynczy_log[1] == \"True\" and not (pojedynczy_log[0].split(r\"/\")[1] in IGNORE): \n yield tuple(pojedynczy_log[0].split(r\"/\"))\n\n\ndef diehard_pybites():\n \"\"\"Return a Stats namedtuple (defined above) that contains the user that\n made the most PRs (ignoring the users in IGNORE) and a challenge tuple\n of most popular challenge and the amount of PRs for that challenge.\n Calling this function on the dataset (held tempfile) should return:\n Stats(user='clamytoe', challenge=('01', 7))\n \"\"\"\n Stats = namedtuple(\"Stats\",[\"user\",\"challenge\"])\n popular_challenge = Counter(s[0] for s in gen_files()).most_common(1)\n active_user = Counter(s[1] for s in gen_files()).most_common(1)\n wynik = Stats(user=active_user[0][0],challenge=popular_challenge[0])\n\n return wynik\n\n\nsiemanero_generator = gen_files()\n\na = next(siemanero_generator)\nres = diehard_pybites()\nprint(res)\n\n\n","sub_path":"6_Generator_Exercices_Days_16_18/pybytes6_generator.py","file_name":"pybytes6_generator.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"347013485","text":"# SETUP#\t\t#########################################################################################################################################\n\n# libraries I use\nimport random, sys\n # sys is for errors\n\nimport time #from time import sleep # this is temporary\n# time is for the delays and pauses\n\n# hides errors, puts errors to devNull, which 'pass', does nothing\nclass devNull(): pass\n#sys.stderr = devNull()\n\ndef sleep(x): # temporary, to remove pauses\n x = None\n time.sleep(0)\n\ndef pr(string): print(string, end=' ')\n# prints text on same line, so i don't have to add \"end=' '\" to each line of print\n\ndef clear(): print(\"\\n\" * 50)\n# 'clear' clears the screen, by making new lines 50 times\n\ndef wait(): input(\": \")\n# pauses game, press 'enter' to continue\n\ndef print_Back():\n print(\"99 ) Go back\")\n print(\"100 ) Main menu\")\ndef input_Back(x, pos):\n if x == 99: pos()\n elif x == 100: Startup()\n else: pass\n\ndef game_Over():\n inp = input(\"Would you like to continue? > \")\n try: # this is if somebody inputs something that is not usable it goes to except, instead of crasing\n if inp in ('y', 'yes'): Startup() # if inputted 'y' or 'yes' it goes back to main menu\n else: # if anything else, it quits the game\n print(\"Thanks for playing!\")\n exit()\n except: pass\n\ndef error(): input(\"That didn't work : \") # simple error message\n\n# leave the text in the lists, because later when the game is finished i'm going to add another version of the text\n\n# GAME#\t\t####################################################################################################################################\nclass Game0: # jump off rock > ask for last words > go to hell or die ..\n\n def __init__(self): self.Game_0() # init function calles 'Game_0' when 'Game0' class is called\n\n def Game_0(self): # jumping off\n # Text ##### ##### ##### ##### #####\n # you're falling > still falling > any last words?\n G0 = [\"You're now falling to you're DOOM\", \"Still falling\", \"Any last words?\"]\n # thanks that did nothing > falling..falling > SPLAT > GAME OVER\n G0_1 = [\"Thanks, that did nothing\", \"Falling...Falling...Falling\", \"SPLAT...you dead!\", \"GAME OVER\"]\n # keywords to go to Hell. kw = keywords\n G0_H_kw = [\"dark lord satan, i offer thee my soul\", \"test\", \"1\"]\n ##### ##### ##### ##### ##### #####\n\n clear()\n for i in range(len(G0)):\n print(G0[i]) # Prints >> falling to you're DOOM > still falling > any last words\n sleep(4) # waits for 4 seconds after everytime it loops and prints text\n\n inp = input(\"Word(s) > \") # ask for last words before you die\n\n if inp.lower() in G0_H_kw: # checks if you entered a keyword from the keyword list(G2_H_kw)\n self.Game_0_1() # if so, it starts the next game\n else:\n for i in range(len(G0_1)): # if you didn't input keywords it prints..\n print(G0_1[i]) # Prints >> thanks that did nothing > Falling.. > SPLAT > GAME OVER\n sleep(3) # pauses for 3 seconds every loop\n game_Over() # exits game\n\n def Game_0_1(self): # in hell\n # Text ##### ##### ##### ##### #####\n # Game_0_1 Hell\n # offer soul to Satan > going to hell > HELL LEVEL 1 > you see Satan on his throne > what are you going ot do now?\n G01 = [\"You offer to make a pack with Satan to save you're soul\", \"Now you're going to hell\", \"HELL LEVEL \",\n \"Youre now in Hell, and first thing you see is Satan sitting on dark throne\",\n \"What the hell ya going to do now?\"]\n # Hell level input\n G01_M = [\"Attempt to sneak away\", \"Beg for soul back even though you just sold it\",\n \"Live for enternity in Hell\"]\n ##### ##### ##### ##### ##### #####\n\n for i in range(len(G01)):\n print(G01[i])\n sleep(3)\n # going to hell > offer the make a pack > HELL LEVEL\n\n clear()\n print(\"\\n\", G01[3]) # Now in Hell, see satan.\n print(\"\\n\", G01[4]) # what are you going to do now\n for i in range(len(G01_M)):\n print(i, ')', G01_M[i])\n # 0 attempt to sneak away, 1, beg for soul, 2 stay for ever.\n\n print_Back()\n run = [] # input options\n inp = input(\"Soo > \") # input for this level\n\n try:\n inp = int(inp)\n input_Back(inp, Startup) # runs input_Back function, for if you want to go back to main menu\n run[x]()\n exit()\n except:\n error()\n self.Game_0_1()\n\nclass Game1: # Game 2, ask rock, ground,\n\n def __init__(self): self.Game_1()\n\n def Game_1(self): # ask rock to go to ground\n # Text ##### ##### ##### ##### #####\n # asking rock to fly down\n # how to ask rock\n G2_a = [\"How would you like to ask the rock to fly down?\"]\n # Game_1 asking, and responding. y, you, r, rock\n G2_y = [\"You told the rock \"]\n G2_r = [\"The rock says \"]\n # Game_1 else response\n G2_e = [\"Well that got you nowhere! \"]\n # Ways to ask rock, and rock responses\n waysTooAsk = {1: \"May you please fly down to the ground, thank you\",\n 2: \"Fly down to the ground right now, or i'll spit on you\",\n 3: \"you better fly down there right now or i'm going to whoop you up real good(in a sassy way)\",\n 4: \"i'll give you whatever you want except wanting me to stay here\",\n 5: \"if you don't let me down right now i'll kill your family and then you!\"}\n rockAnswers = {1: \"OK fine\",\n 2: \"then I'll drop you from 100ft\",\n 3: \"oh don't you talk to me like that(in a sassy rock way(i guess))\",\n 4: \"I wish to stay here and you can move to the right 1ft, and you won't be in the same place\",\n 5: \"Then i'll find you fimaly and murder then and then the human race! MWHAHAHAHAHA!!!\"}\n\n ##### ##### ##### ##### ##### #####\n\n clear()\n\n print(\"\\n\", G2_a) # How would you like to ask\n print(\"\\n1. nicely, 2. Rudely, 3. Sassy, 4. Bribe, .\")\n print_Back()\n\n inp = input(\"Choose one > \")\n\n try: # tries to convert the input to a usable integer for this part\n x = int(inp)\n input_Back(inp, Startup)\n except:\n self.Game_1() # if it fails, it runs this code(Game_1) again\n\n print(G2_y[0], \"\\n >> \", waysTooAsk[x]) # you say >\n wait()\n print(G2_r[0], \"\\n >> \", rockAnswers[x]) # rock responds with >\n wait()\n\n if x == 1: # if you choose option 1 you go to the ground\n self.Game_1_1() # starts the next game 'Game_1_1'\n else:\n input(\"\\n\", G2_e[0]) # prints got you nowhere\n wait()\n Game1() # re-runs the program(Game_1)\n\n def Game_1_1(self): # on the ground\n # Text ##### ##### ##### ##### #####\n # Story. on ground now\n G21_S = [\"YAY you're on the ground now, so now what?\"]\n G2_1_M = [\"Go back to rock\"]\n ##### ##### ##### ##### ##### #####\n\n clear()\n\n print(G21_S[0])\n for i in range(len(G2_1_M)):\n print(i, ')', G2_1_M[i])\n print_Back()\n\n inp = input()\n try:\n inp = int(inp)\n input_Back(inp, Game1)\n except: pass\n\n wait()\n Startup()\n\nclass Game2: # yelling > nothing\n\n def __init__(self): self.Game_2()\n\n def Game_2(self): \n # Text ##### ##### ##### ##### #####\n # now yelling at rock\n G3 = [\"You are now yelling at the rock!\"]\n # .............\n G3_1 = [\"..................\"]\n ##### ##### ##### ##### ##### #####\n\n print(G3) # yelling at rock\n print(\"The rock responds : \")\n print(G3_1) # .............\n input(\"That got did nothing, try something else : \")\n\n wait()\n Startup()\n\nclass Game3: # Begging > nothing\n\n def __init__(self): self.Game_3()\n\n def Game_3(self):\n # Text ##### ##### ##### ##### #####\n G4 = []\n G4_M = []\n ##### ##### ##### ##### ##### #####\n\n print(G4)\n for i in range(len(G4_M)):\n print(i, ')', G4_M[i])\n wait()\n\nclass Game4: # Sleep > Dreamworld > ..\n timeSlept = 12 # sets timeSlept variable, starts at 12,\n\n def __init__(self): self.Game_4()\n\n def Game_4(self): # sleeping\n global timeSlept\n clear()\n # Text ##### ##### ##### ##### #####\n # going to bed\n G5 = [\"You are thinking that you can't get off this rock so you decide to go to bed\"]\n # you\"re now sleeping\n G5_1 = [\"You're now sleeping\"]\n # hope you rested well\n G5_2 = [\"Hope you rested well\"]\n # morning\n G5_3 = [\"Morning, you slept in total of > \"]\n G5_Snores = ['zz', 'ZzZ', 'ZZzz', 'zzZzZ', 'ZzZzzZ']\n ##### ##### ##### ##### ##### #####\n\n print(G5) # thinking can't get off\n print(G5_1) # go to bed. 2 now sleeping\n amount = random.randint(1, 5) # this generates random number 1-10\n # random number is to print 'z'(s) in random number of times, just because\n for i in range(5): # loops the print statment 5 times\n print(G5_Snores[i] * amount) # prints zz(s) from the list by a random amount\n #\tsleep(amoun)\n print(G5_2) # rested well message\n sleep(.3) # pauses for 5secs\n print(G5_3, timeSlept, \"hours\") # prints morning message and tells you how long you slept for in total\n wait()\n timeSlept = timeSlept + 12 * 1.2 # adds time to total time slept,\n # ^ everytime you sleep, you longer you sleep. 1.2x longer everytime\n if timeSlept > 84: # checks to see if you slept over 84 hours\n self.Game_4_1() # if you slept for more then 84 hours, you go to dreamworld\n else: # else you it goes back to main menu\n clear()\n Startup() # go to main menu\n\n def Game_4_1(self): # dream\n clear()\n # Text ##### ##### ##### ##### #####\n # Dreamworld\n # now in dream world, congrats\n G51 = [\"You slept for too long, you are now in a dream!\"]\n # you're trapped, you slept for too long\n G51_2 = [\"Since you slept for too long, you're not trapped in a dream world. whatcha going to do?\"]\n # Dreamworld menu\n G51_M = [\"Go eat the candy\", \"Find a ginger-bread house\", \"Find a way out\"]\n # this looks like a nice place\n G51_M_1 = [\"this place look and smell nice, look huge lollipops, rainbows, and candy!\"]\n ##### ##### ##### ##### ##### #####\n\n for i in range(len(G51_M)): # loop to print out menu\n print(i, ')', G51_M[i])\n\n print(G51) # prints you slept for too long, now in dreamworld\n print(G51_2) # since you slept for too long you're stuck in dreamworld\n print(G51_M_1) # extra menu message\n\n inp = input(G51_i)\n\nclass Quit: # quit function, prints message and quits game\n\n def __init__(self):\n input(\"Thanks for playing : \")\n quit() # built-in quit funciton\n\n# STARTUP#\t\t#####################################################################################################################################\n\nclass LoadingScreens:\n\n def Loading_screen_0(): # nice loading screen, <(^.^)> (kirby)\n clear()\n\n Kirby = ['LOADING ', '<', '(', '^', '.', '^', ')', '>', ' ', '\\n:', ')', 'WELCOME']\n # Kirby loading screen items\n for i in range(len(Kirby)):\n print(i)\n sleep(2)\n # finds the length of the 'Kirby' list, so it knows how long to loop.\n # then for each item in list it gives it the variable 'i'; just for one loop.\n # then on next loop it changes the 'i' value to the next item in list, then prints it out, each loop it pauses for 2sec\n\n input(\"CONTINUE > \") # waits until user presses 'Enter'\n\nclass Startup:\n\n def __init__(self): self.Start_menu()\n\n def Start_menu(self):\n # Text ##### ##### ##### ##### #####\n # Startup menu/Main menu\n Story = [\"You are on a floating rock 1000ft above ground, and all that you have is a bed(for some reason), so what do you do\"]\n # Start menu, sm=start menu\n Sm = [\"Jump off(need work)\" ,\n \"Ask rock to go down(need work)\",\n \"Yell at rock(need changing)\",\n \"Beg rock to go down(need changing)\",\n \"Go to sleep(need work)\",\n \"Quit\"]\n # in the main menu punch in these numbers, it well print these.\n extra = {69: [\"really!?!?\"],\n 666: [\"HAIL HYDRA!!!\"],\n 777: [\"A blue box well show up soon\"]\n }\n ##### ##### ##### ##### ##### #####\n\n clear()\n\n print(\"THE STORY \")\n print(Story) # the story\n for i in range(len(Sm)):\n print(i, ')', Sm[i]) # this makes it easy to print out all of the options for the menu, instad of using print over and over again\n # 0 jump off, 1 yell at rock, 2 beg rock, 3 sleep, 4 quit\n\n run = [Game0, Game1, Game2, Game3, Game4, Quit] # list of the functions for the different options\n inp = input(\"choose > \") # ask user to for what option they want to do, and then goes and runs it\n\n try: # try and except is for when you know you're code might break,\n # if the 'try' code fails the program goes to except, instead of crashing\n inp = int(inp) # tries to convert input to integer\n if inp > 5:\n print(extra[inp])\n self.Start_menu() # checks to see if what you inputted is a extra\n else:\n run[inp]() # runs the game that corresponds to input\n except:\n error()\n self.Start_menu() # gives error, then goes back to main menu\n\n\nif __name__ == '__main__': # checks if this script is being run directly, if not it runs nothing, if so it runs 'Start()'\n Startup() # starts the program, without this it won't run\n###################################################################################################################################################\n","sub_path":"flying_Rock.py.py","file_name":"flying_Rock.py.py","file_ext":"py","file_size_in_byte":15300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"456341521","text":"# -*- encoding: utf8 -*-\nimport unittest\nfrom arky.utils.decorators import setInterval\nfrom threading import Event\nfrom six import PY3\n\n\nclass TestUtilsDecorators(unittest.TestCase):\n\n def test_setInterval(self):\n @setInterval(30)\n def testfn():\n print(\"tick\")\n\n event = testfn()\n assert event.is_set() is False\n if PY3:\n assert isinstance(event, Event)\n else:\n # py2 doesn't support Event object in isinstance\n assert event.__module__ == 'threading'\n event.set()\n assert event.is_set() is True\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/utils/test_decorators.py","file_name":"test_decorators.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"230067607","text":"import requests\n\nfrom mbtaw.errors import RateLimitError, InvalidQueryParameterError\nfrom mbtaw import endpoints\n\n\nclass Client():\n \"\"\"\n Class providing a client connection to the MBTA API.\n \"\"\"\n def __init__(self, api_key: str):\n \"\"\"\n Create a new Mbta Client object.\n\n Args:\n api_key: str\n Your MBTA api key.\n \"\"\"\n self._session = requests.Session()\n self._session.headers = {\n 'X-API-Key': api_key\n }\n\n self.rate_limit = {\n 'x-ratelimit-limit': 20,\n 'x-ratelimit-reset': 0,\n 'x-ratelimit-remaining': 20,\n }\n\n def get_rate_limit(self):\n \"\"\"The maximum number of requests you’re allowed to make per time window.\"\"\"\n return self.rate_limit['x-ratelimit-limit']\n\n def get_rate_limit_remaining(self):\n \"\"\"The number of requests remaining in the current time window.\"\"\"\n return self.rate_limit['x-ratelimit-remaining']\n\n def get_rate_limit_reset(self):\n \"\"\"The time at which the current rate limit time window ends in UTC epoch seconds.\"\"\"\n return float(self.rate_limit['x-ratelimit-reset'])\n\n def get_lines(self,\n page_offset: int = None,\n page_limit: int = None,\n sort: str = None,\n fields_line: str = None,\n include: str = None,\n filter_id: str = None):\n \"\"\"List of lines. A line is a combination of routes. This concept can be used to group similar routes when displaying them to customers, such as for routes which serve the same trunk corridor or bus terminal.\n\n Args:\n page_offset:\n Offset (0-based) of first element in the page\n page_limit:\n Max number of elements to return\n sort:\n Sort options:\n - color\n - long_name\n - short_name\n - sort_order\n - text_color\n fields_line:\n Fields to include with the response. Multiple fields MUST be a comma-separated (U+002C COMMA, “,”) list.\n include:\n Relationships to include\n - routes\n filter_id:\n Filter by multiple IDs. MUST be a comma-separated (U+002C COMMA, “,”) list.\n\n Return:\n requests.Response\n A list of lines.\n \"\"\"\n url = endpoints.LINES\n params = {}\n\n if page_offset:\n params['page[offset]'] = page_offset\n\n if page_limit:\n params['page[limit]'] = page_limit\n\n if sort:\n if sort in ('color', '-color', 'long_name', '-long_name', 'short_name', '-short_name', 'sort_order', '-sort_order', 'text_color', '-text_color'):\n params['sort'] = sort\n else:\n raise InvalidQueryParameterError('Invalid query parameter value for sort: ' + sort)\n\n if fields_line:\n params['fields[line]'] = fields_line\n\n if include:\n if include == 'routes':\n params['include'] = include\n else:\n raise InvalidQueryParameterError('Invalid query parameter value for include: ' + include)\n\n if filter_id:\n params['filter[id]'] = filter_id\n\n resp = self._request(url, params)\n return resp\n\n def get_lines_id(self,\n line_id: str,\n fields_line: str = None,\n include: str = None):\n \"\"\"Single line, which represents a combination of routes.\n\n Args:\n line_id: (required)\n Unique ID for a line\n fields_line:\n Fields to include with the response. Multiple fields MUST be a comma-separated (U+002C COMMA, “,”) list.\n include:\n Relationships to include\n - routes\n Return:\n requests.Response\n A single line.\n \"\"\"\n url = endpoints.LINES + line_id\n params = {}\n\n if line_id == '':\n raise InvalidQueryParameterError('line_id cannot be empty. If you do not need a specific line, use get_lines() instead')\n\n if fields_line:\n params['fields[line]'] = fields_line\n\n if include:\n if include == 'routes':\n params['include'] = include\n else:\n raise InvalidQueryParameterError('Invalid query parameter value for include: ' + include)\n\n resp = self._request(url, params)\n return resp\n\n def _request(self, url, params):\n \"\"\"\n HTTP request to MBTA api.\n\n Args:\n url:\n The full url endpoint we want to retrieve data from.\n params:\n The query parameters being sent in the request.\n\n Return:\n requests.Response\n \"\"\"\n # Check if rate limit exceeded before making request\n if self.rate_limit['x-ratelimit-remaining'] <= 0:\n raise RateLimitError('Rate limit exceeded.')\n\n # Make request\n resp = self._session.get(url, params=params)\n\n # Set rate limit status\n for key in self.rate_limit:\n self.rate_limit[key] = resp.headers.get(key)\n\n return resp\n","sub_path":"mbtaw/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"280003016","text":"# Definition for a binary tree node.\n# class 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 dfs(self, root, answer):\n if root:\n self.dfs(root.left, answer)\n answer.append(root.val)\n self.dfs(root.right, answer)\n\n def kthSmallest_rec(self, root, k):\n answer = []\n self.dfs(root, answer)\n return answer[k - 1]\n \n def kthSmallest(self, root, k):\n stack = []\n node = root\n while stack or node:\n if node:\n stack.append(node)\n node = node.left\n else:\n node = stack.pop()\n if k > 1:\n k -= 1\n else:\n return node.val\n \n node = node.right\n","sub_path":"python/Kth Smallest Element in a BST.py","file_name":"Kth Smallest Element in a BST.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"55717741","text":"from PyQt5 import QtCore, QtGui, uic,QtWidgets\nimport sys\nimport sqlite3\n\nclass Ui_Dialog(object):\n def setupUi(self, Dialog):\n Dialog.setObjectName(\"Dialog\")\n Dialog.resize(570, 546)\n self.widget = QtWidgets.QWidget(Dialog)\n self.widget.setGeometry(QtCore.QRect(20, 50, 531, 411))\n self.widget.setStyleSheet(\"background-color: rgb(29, 92, 132);\\n\"\n\"border-radius:20px;\")\n self.widget.setObjectName(\"widget\")\n self.lineEdit = QtWidgets.QLineEdit(self.widget)\n self.lineEdit.setGeometry(QtCore.QRect(110, 260, 311, 20))\n self.lineEdit.setStyleSheet(\"background-color: rgb(62, 62, 62);\\n\"\n\"border: 1px solid rgba(0, 0, 0, 0);\\n\"\n\"border-bottom-color:rgba(46, 82, 101, 255);\\n\"\n\"color:rgb(255, 155, 255);\\n\"\n\"padding-bottom:7px\")\n self.lineEdit.setEchoMode(QtWidgets.QLineEdit.Password)\n self.lineEdit.setObjectName(\"lineEdit\")\n self.lineEdit_2 = QtWidgets.QLineEdit(self.widget)\n self.lineEdit_2.setGeometry(QtCore.QRect(110, 220, 311, 20))\n self.lineEdit_2.setStyleSheet(\"background-color: rgb(62, 62, 62);\\n\"\n\"border: 1px solid rgba(0, 0, 0, 0);\\n\"\n\"border-bottom-color:rgba(46, 82, 101, 255);\\n\"\n\"color:rgb(255, 155, 255);\\n\"\n\"padding-bottom:7px\")\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.loginButton = QtWidgets.QPushButton(self.widget)\n self.loginButton.setGeometry(QtCore.QRect(110, 320, 141, 51))\n font = QtGui.QFont()\n font.setFamily(\"Arial Black\")\n font.setPointSize(12)\n font.setBold(True)\n font.setWeight(75)\n self.loginButton.setFont(font)\n self.loginButton.setStyleSheet(\"QPushButton#loginButton{\\n\"\n\"background-color:rgba(2, 65, 118, 255);\\n\"\n\"color:rgba(255, 255, 255, 200);\\n\"\n\"border-radius:5px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QPushButton#loginButton:pressed{\\n\"\n\"padding-left:5px;\\n\"\n\"padding-top:5px;\\n\"\n\"background-color:qlineargradient(spread:pad, x1:1, y1:1, x2:1, y2:0, stop:0 rgba(66, 199, 255, 100), stop:1 rgba(255, 255, 255, 100));\\n\"\n\"}\\n\"\n\"\\n\"\n\"QPushButton#loginButton{\\n\"\n\"background-color:rgba(2, 65, 118, 255);\\n\"\n\"}\\n\"\n\"\")\n self.loginButton.setObjectName(\"loginButton\")\n self.label = QtWidgets.QLabel(self.widget)\n self.label.setGeometry(QtCore.QRect(220, 100, 151, 101))\n font = QtGui.QFont()\n font.setPointSize(60)\n self.label.setFont(font)\n self.label.setStyleSheet(\"background-color: 0\")\n self.label.setObjectName(\"label\")\n self.msg_label = QtWidgets.QLabel(self.widget)\n self.msg_label.setGeometry(QtCore.QRect(120, 290, 281, 16))\n self.msg_label.setText(\"\")\n self.msg_label.setObjectName(\"msg_label\")\n self.cadastrarButton = QtWidgets.QPushButton(self.widget)\n self.cadastrarButton.setGeometry(QtCore.QRect(280, 320, 141, 51))\n font = QtGui.QFont()\n font.setFamily(\"Arial Black\")\n font.setPointSize(12)\n font.setBold(True)\n font.setWeight(75)\n self.cadastrarButton.setFont(font)\n self.cadastrarButton.setStyleSheet(\"\\n\"\n\"QPushButton#cadastrarButton{\\n\"\n\"background-color:rgba(2, 65, 118, 255);\\n\"\n\"color:rgba(255, 255, 255, 200);\\n\"\n\"border-radius:5px;\\n\"\n\"}\\n\"\n\"\\n\"\n\"QPushButton#cadastrarButton:pressed{\\n\"\n\"padding-left:5px;\\n\"\n\"padding-top:5px;\\n\"\n\"background-color:qlineargradient(spread:pad, x1:1, y1:1, x2:1, y2:0, stop:0 rgba(66, 199, 255, 100), stop:1 rgba(255, 255, 255, 100));\\n\"\n\"}\\n\"\n\"\\n\"\n\"QPushButton#cadastrarButton{\\n\"\n\"background-color:rgba(2, 65, 118, 255);\\n\"\n\"}\\n\"\n\"\")\n self.cadastrarButton.setObjectName(\"cadastrarButton\")\n\n self.retranslateUi(Dialog)\n QtCore.QMetaObject.connectSlotsByName(Dialog)\n\n def retranslateUi(self, Dialog):\n _translate = QtCore.QCoreApplication.translate\n Dialog.setWindowTitle(_translate(\"Dialog\", \"Dialog\"))\n self.lineEdit.setPlaceholderText(_translate(\"Dialog\", \"Digite a senha\"))\n self.lineEdit_2.setPlaceholderText(_translate(\"Dialog\", \"Usuario\"))\n self.loginButton.setText(_translate(\"Dialog\", \"Login\"))\n self.label.setText(_translate(\"Dialog\", \"\"))\n self.cadastrarButton.setText(_translate(\"Dialog\", \"Cadastrar\"))\n\ndef call_tela_main():\n tela_login.msg_label.setText(\"\")\n nome_usuario = tela_login.lineEdit_2.text()\n senha = tela_login.lineEdit.text()\n banco = sqlite3.connect('banco_stonks.db')\n cursor = banco.cursor()\n try:\n cursor.execute(\"SELECT senha FROM cadastro WHERE login = '{}'\".format(nome_usuario))\n senha_bd = cursor.fetchall()\n print(senha_bd[0][0])\n banco.close()\n except:\n print(\"Erro ao validar o Login\")\n\n if senha == senha_bd[0][0] :\n\n tela_login.msg_label.setText(\"Dados de login CORRETOS!\")\n tela_login.close()\n tela_main.show()\n if senha != senha_bd[0][0] :\n tela_login.msg_label.setText(\"Dados de login incorretos!\")\n\ndef logout():\n\n tela_login.show()\n\ndef call_tela_cadastro():\n tela_cadastro.show()\n\n\ndef cadastrar():\n nome = tela_cadastro.cadastro_usuario.text()\n login = tela_cadastro.cadastro_usuario.text()\n senha = tela_cadastro.cadastro_password.text()\n c_senha = tela_cadastro.repeat_password.text()\n\n if (senha == c_senha):\n try:\n banco = sqlite3.connect('banco_stonks.db')\n cursor = banco.cursor()\n cursor.execute(\"CREATE TABLE IF NOT EXISTS cadastro (nome text,login text,senha text, id_usuario int PRIMARY KEY autoincrement)\")\n cursor.execute(\"INSERT INTO cadastro VALUES ('\"+nome+\"','\"+login+\"','\"+senha+\"', NULL)\")\n banco.commit()\n banco.close()\n tela_cadastro.msg_label2.setText(\"Usuario cadastrado com sucesso\")\n\n except sqlite3.Error as erro:\n print(\"Erro ao inserir os dados: \",erro)\n\n else:\n tela_cadastro.label.setText(\"As senhas digitadas estão diferentes\")\n\n\n\nif __name__==\"__main__\":\n app=QtWidgets.QApplication(sys.argv)\n tela_login = uic.loadUi(\"tela_login.ui\")\n tela_cadastro = uic.loadUi(\"tela_cadastro.ui\")\n tela_main = uic.loadUi(\"tela_main.ui\")\n tela_login.cadastrarButton.clicked.connect(call_tela_cadastro)\n tela_cadastro.cadastrarButton.clicked.connect(cadastrar)\n tela_login.loginButton.clicked.connect(call_tela_main)\n Form = QtWidgets.QWidget()\n ui = Ui_Dialog()\n ui.setupUi(Form)\n tela_login.show()\n app.exec()\n\n","sub_path":"backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":6397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"642394955","text":"def quickSort(ar):\n quickSortHelper(ar,0,len(ar)-1)\n\ndef quickSortHelper(ar,first,last):\n if first= pivotvalue and rightmark >= leftmark:\n rightmark = rightmark -1\n\n if rightmark < leftmark:\n done = True\n else:\n temp = ar[leftmark]\n ar[leftmark] = ar[rightmark]\n ar[rightmark] = temp\n\n temp = ar[first]\n ar[first] = ar[rightmark]\n ar[rightmark] = temp\n\n\n return rightmark\n\nm = input()\nar = [int(i) for i in raw_input().strip().split()]\n\nquickSort(ar)\n\nprint(ar)\n","sub_path":"quicksortalgorithm.py","file_name":"quicksortalgorithm.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"389763395","text":"import numpy as np\nimport tensorly as tl\n\n\ndef tensorify(X, y, shape):\n tensor = np.full(shape, np.nan)\n\n for i, d in enumerate(X):\n lat, lon, t = d.astype(np.int)\n tensor[lat, lon, t] = y[i]\n\n return tensor\n\n\ndef center_mat(mat):\n nan_mask = np.isnan(mat)\n temp_mat = mat.copy()\n temp_mat[nan_mask] = 0\n\n m0 = temp_mat.mean(axis=0)\n for i in range(temp_mat.shape[0]):\n temp_mat[i, :] -= m0\n\n m1 = temp_mat.mean(axis=1)\n for i in range(temp_mat.shape[1]):\n temp_mat[:, i] -= m1\n\n temp_mat[nan_mask] = np.nan\n return temp_mat, m0, m1\n\n\ndef decenter_mat(mat, m0, m1):\n temp_mat = mat.copy()\n\n for i in range(temp_mat.shape[0]):\n temp_mat[i, :] += m0\n\n for i in range(temp_mat.shape[1]):\n temp_mat[:, i] += m1\n\n return temp_mat\n\n\ndef center_3d_tensor(tensor, lat_lon_separately=True):\n temp_tensor = tensor.copy()\n\n # Spatial centering\n spatial_means = []\n if lat_lon_separately:\n m0 = np.nanmean(temp_tensor, axis=0)\n m0[np.isnan(m0)] = 0\n for i in range(temp_tensor.shape[0]):\n temp_tensor[i, :, :] -= m0\n spatial_means.append(m0)\n\n m1 = np.nanmean(temp_tensor, axis=1)\n m1[np.isnan(m1)] = 0\n for i in range(temp_tensor.shape[1]):\n temp_tensor[:, i, :] -= m1\n spatial_means.append(m1)\n else:\n # For each day unified spatial mean (in flattened spatial array)\n for t in range(temp_tensor.shape[-1]):\n mat_mean = np.nanmean(temp_tensor[:, :, t])\n if np.isnan(mat_mean):\n mat_mean = 0\n temp_tensor[:, :, t] -= mat_mean\n spatial_means.append(mat_mean)\n\n # Time centering\n m2 = np.nanmean(temp_tensor, axis=2)\n m2[np.isnan(m2)] = 0\n for i in range(temp_tensor.shape[2]):\n temp_tensor[:, :, i] -= m2\n\n return temp_tensor, spatial_means, m2\n\n\ndef decenter_3d_tensor(tensor, spatial_means, m2, lat_lon_separately=True):\n temp_tensor = tensor.copy()\n\n # Spatial decentering\n if lat_lon_separately:\n m0, m1 = spatial_means\n for i in range(temp_tensor.shape[0]):\n temp_tensor[i, :, :] += m0\n for i in range(temp_tensor.shape[1]):\n temp_tensor[:, i, :] += m1\n else:\n for t in range(temp_tensor.shape[-1]):\n temp_tensor[:, :, t] += spatial_means[t]\n\n # Time decentering\n for i in range(temp_tensor.shape[2]):\n temp_tensor[:, :, i] += m2\n\n return temp_tensor\n\n\ndef rectify_tensor(tensor):\n rect_mat = []\n for t in range(tensor.shape[-1]):\n rect_mat.append(tensor[:, :, t].flatten())\n rect_mat = np.array(rect_mat)\n rect_mat = np.moveaxis(rect_mat, 0, -1)\n return rect_mat\n\n\ndef unrectify_mat(mat, spatial_shape):\n tensor = []\n\n for t in range(mat.shape[-1]):\n col = mat[:, t]\n unrectified_col = col.reshape(spatial_shape)\n tensor.append(unrectified_col)\n\n tensor = np.array(tensor)\n tensor = np.moveaxis(tensor, 0, -1)\n\n return tensor\n\n\ndef nrmse(y_hat, y):\n \"\"\"\n Normalized root mean squared error\n \"\"\"\n meaned_sqd_diff = np.mean(np.power(y_hat - y, 2))\n return np.sqrt(meaned_sqd_diff) / np.std(y)\n\n\ndef calculate_mat_energy(mat, s):\n sample_count_0 = mat.shape[1]\n sample_coef_0 = 1 / (sample_count_0 - 1)\n total_energy_0 = np.array([sample_coef_0 * np.trace(mat @ mat.T) for _ in range(len(s))])\n expl_energy_0 = -np.sort(-sample_coef_0 * s * s)\n expl_energy_ratio_0 = expl_energy_0 / total_energy_0\n\n sample_count_1 = mat.shape[0]\n sample_coef_1 = 1 / (sample_count_1 - 1)\n total_energy_1 = np.array([sample_coef_1 * np.trace(mat.T @ mat) for _ in range(len(s))])\n expl_energy_1 = -np.sort(-sample_coef_1 * s * s)\n expl_energy_ratio_1 = expl_energy_1 / total_energy_1\n\n return np.array([[total_energy_0, expl_energy_0, expl_energy_ratio_0],\n [total_energy_1, expl_energy_1, expl_energy_ratio_1]])\n\ndef calculate_tucker_energy(tensor, A):\n energy_stack = []\n for i in range(tensor.ndim):\n sample_count_i = np.prod(tensor.shape) / tensor.shape[i]\n sample_coef_i = 1 / (sample_count_i - 1)\n unfold_i = tl.unfold(tensor, i)\n tensor_proj_i = tl.tenalg.mode_dot(tensor, A[i].T, i)\n tensor_proj_unfold_i = tl.unfold(tensor_proj_i, i)\n\n full_cov_i = sample_coef_i * unfold_i @ unfold_i.T\n tensor_proj_cov_i = sample_coef_i * tensor_proj_unfold_i @ tensor_proj_unfold_i.T\n\n total_energy_i = np.trace(full_cov_i)\n expl_energy_i_per_component = -np.sort(-tensor_proj_cov_i.diagonal())\n expl_energy_ratio_i_per_component = expl_energy_i_per_component / total_energy_i\n total_energy_i_per_component = [total_energy_i for _ in range(len(expl_energy_i_per_component))]\n\n energy_stack.append([total_energy_i_per_component,\n expl_energy_i_per_component,\n expl_energy_ratio_i_per_component])\n energy_stack = np.array(energy_stack)\n\n return energy_stack\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"327831053","text":"import os\n\nfrom flask import Flask, render_template\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=['GET'])\ndef index():\n data = {\n \"title\": \"うえええええ\",\n \"message\": \"こんにちは\"\n }\n flask_env = os.environ[\"FLASK_ENV\"]\n\n return render_template('index.html', data=data, flask_env=flask_env)\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000, debug=True)","sub_path":"app/backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"565971403","text":"class Graph:\n adj = []\n\n # Function to fill empty adjacency matrix \n def __init__(self, v, e):\n\n self.v = v\n self.e = e\n Graph.adj = [[0 for i in range(v)]\n for j in range(v)]\n\n # Function to add an edge to the graph\n\n def addEdge(self, start, e):\n\n # Considering a bidirectional edge \n Graph.adj[start][e] = 1\n Graph.adj[e][start] = 1\n\n # Function to perform DFS on the graph \n def DFS(self, start, visited):\n\n # Print current node \n print(start, end=' ')\n\n # Set current node as visited \n visited[start] = True\n\n # For every node of the graph \n for i in range(self.v):\n\n # If some node is adjacent to the \n # current node and it has not \n # already been visited \n if (Graph.adj[start][i] == 1 and\n (not visited[i])):\n self.DFS(i, visited)\n\n # Driver code\n\n\nv, e = 6, 5\n\n# Create the graph \nG = Graph(v, e)\nG.addEdge(0, 1)\nG.addEdge(0, 2)\nG.addEdge(2, 1)\nG.addEdge(0, 3)\nG.addEdge(0, 4)\nG.addEdge(2, 5)\n\n# Visited vector to so that a vertex \n# is not visited more than once \n# Initializing the vector to false as no \n# vertex is visited at the beginning \nvisited = [False] * v\n\n# Perform DFS \nG.DFS(0, visited)\n","sub_path":"com/leo/python_complex_algorithm_problems/depth_first_analysis_using_matrix_representation.py","file_name":"depth_first_analysis_using_matrix_representation.py","file_ext":"py","file_size_in_byte":1332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"650050792","text":"\"\"\"QALD-9.\"\"\"\n\nimport json\nimport os\nimport ast\n\nimport datasets\n\nlogger = datasets.logging.get_logger(__name__)\n\n_CITATION = \"\"\"\\\n @inproceedings{Usbeck20189thCO,\n title={9th Challenge on Question Answering over Linked Data (QALD-9) (invited paper)},\n author={Ricardo Usbeck and Ria Hari Gusmita and Axel-Cyrille Ngonga Ngomo and Muhammad Saleem},\n booktitle={Semdeep/NLIWoD@ISWC},\n year={2018}\n }\n \"\"\"\n\n_DESCRIPTION = \"\"\"\\\n QALD-9 Dataset Description\n\"\"\"\n\n_URL = \"https://github.com/ag-sc/QALD\"\n\n_QALD9_URLS = {\n \"train\": \"https://raw.githubusercontent.com/ag-sc/QALD/master/9/data/qald-9-train-multilingual.json\",\n \"test\": \"https://raw.githubusercontent.com/ag-sc/QALD/master/9/data/qald-9-test-multilingual.json\"\n}\n\nclass QALDConfig(datasets.BuilderConfig):\n \"\"\"BuilderConfig for QALD\"\"\"\n def __init__(self,\n data_url,\n data_dir,\n **kwargs):\n \"\"\"BuilderConfig for QALD.\n Args:\n **kwargs: keyword arguments forwarded to super.\n \"\"\"\n super(QALDConfig, self).__init__(**kwargs)\n self.data_url = data_url\n self.data_dir = data_dir\n\nclass QALDQuestions(datasets.GeneratorBasedBuilder):\n \"\"\"QALD.\"\"\"\n BUILDER_CONFIGS = [\n QALDConfig(\n name=\"qald\",\n description=\"QALD\",\n data_url=\"\",\n data_dir=\"QALD\"\n )\n ]\n\n def _info(self):\n return datasets.DatasetInfo(\n description=_DESCRIPTION,\n supervised_keys=None,\n homepage=_URL,\n citation=_CITATION,\n features=datasets.Features(\n {\n \"id\": datasets.Value(\"string\"),\n \"answertype\": datasets.Value(\"string\"),\n \"aggregation\": datasets.Value(\"bool\"),\n \"onlydbo\": datasets.Value(\"bool\"),\n \"hybrid\": datasets.Value(\"bool\"),\n \"question\": datasets.Value(\"string\"),\n \"query\": datasets.Features(\n {\n \"sparql\": datasets.Value(\"string\")\n }\n ),\n \"answers\": datasets.Value(\"string\")\n }\n )\n )\n\n def _split_generators(self, dl_manager):\n data_dir = None\n qald_files = dl_manager.download(\n {\n \"train\": _QALD9_URLS[\"train\"],\n \"test\": _QALD9_URLS[\"test\"]\n }\n )\n return [\n datasets.SplitGenerator(\n name=datasets.Split.TRAIN,\n gen_kwargs={\n \"data_file\": os.path.join(data_dir or \"\", qald_files[\"train\"]),\n \"split\": \"train\"\n }\n ),\n datasets.SplitGenerator(\n name=datasets.Split.TEST,\n gen_kwargs={\n \"data_file\": os.path.join(data_dir or \"\", qald_files[\"test\"]),\n \"split\": \"test\"\n }\n )\n ]\n\n def _generate_examples(self, data_file, **kwargs):\n with open(data_file, encoding=\"utf-8\") as f:\n qald = json.load(f)\n for idx, question in enumerate(qald[\"questions\"]):\n question[\"question\"] = json.dumps(question[\"question\"])\n question[\"answers\"] = json.dumps(question[\"answers\"])\n\n yield idx, question\n","sub_path":"qald/qald-9.py","file_name":"qald-9.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"253787145","text":"import csv\n\n\ndef main():\n a = input('Enter the name of file (without .csv) to make a map: ')\n z = input('Enter the name of map you want to create (without .txt): ')\n loadMap(a, z)\n \n \ndef loadMap(filename, mapname):\n\n try:\n mapFile = open(filename + '.csv')\n except IOError as err:\n print(\"Error I/O error: {0}\".format(err))\n\n mapReader = csv.reader(mapFile)\n \n count = 0\n new = open(mapname + '.txt', 'w')\n for row in mapReader:\n for each in row:\n if each == '#':\n new.write(each)\n new.write(str(count))\n count += 1\n elif each == ',': #add more elif each == 'sign'\n count += 1 #to add different stuff etc.\n else:\n count +=1\n new.write('\\n')\n count = 0\n new.close()\n mapFile.close()\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"fromCSVtoTXTmapEditor.py","file_name":"fromCSVtoTXTmapEditor.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"399180500","text":"\"\"\"\nName : __main__.py\nAuthor : David Carpenter\nDate : 2021-10-01\nDescription : A program to assist me in entering data into a database.\n\"\"\"\n\nimport argparse\nimport csv\nimport pathlib\nfrom typing import List\n\nfrom exceptions import DataEntryHelperException\nfrom display import page_through\n\n\ndef validate_path(path_as_string: str) -> pathlib.Path:\n \"\"\"\n Ensures that the passed file name exists\n and is of the appropriate file type.\n \"\"\"\n path = pathlib.Path(path_as_string)\n\n if not path.exists():\n raise DataEntryHelperException(f\"the path {path_as_string} does not exist\")\n\n if path.suffix != \".csv\":\n raise DataEntryHelperException(f\"the extension {path.suffix} is not supported\")\n\n return path\n\n\ndef get_data(path: pathlib.Path) -> List[dict]:\n \"\"\"\n Gets all data from the passed csv file\n and returns a list of all of the entries.\n \"\"\"\n data = []\n with path.open() as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n data.append(row)\n return data\n\n\ndef main() -> None:\n \"\"\"\n Main method of the program.\n \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Step-by-step instructions on what data to enter into the database.\"\n )\n parser.add_argument(\"path\", type=str, help=\"path to the csv file containing info\")\n parser.add_argument(\n \"-r\",\n \"--remaining\",\n type=int,\n help=\"start paging at this value of remaining entries\",\n )\n args = parser.parse_args()\n path_as_string: str = args.path\n remaining: int = args.remaining\n\n try:\n path = validate_path(path_as_string)\n data = get_data(path)\n\n if remaining is None:\n remaining = len(data)\n\n start = len(data) - remaining\n page_through(data, start)\n except DataEntryHelperException as ex:\n parser.error(ex)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"479616392","text":"# !/use/bin/env python\n# -*-conding:utf-8-*-\n\n#author:shanshan\n\n\n\nfrom appium import webdriver\nimport time as t\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom appium_test.util.read_init import ReadIni\nfrom appium_test.util.get_by_local import GetByLocal\n\ndef get_driver():\n desired_caps = {\n \"platformName\": \"Android\",\n \"deviceName\": \"127.0.0.1:62025\",\n \"app\": \"F:\\\\testiTools\\\\APK\\\\yangshipin.apk\",\n #\"appActivity\": \"com.tencent.videolite.android.ui.GuidePageActivity\"\n #\"appwaitActivity\": \"com.tencent.videolite.android.ui.SplashActivity\",\n \"noReset\":\"true\"\n }\n\n driver = webdriver.Remote(\"http://127.0.0.1:4723/wd/hub\",desired_caps)\n return driver\n\nt.sleep(5)#休息五秒\n\n\ndef get_point():\n point = driver.get_window_size()\n #print(point)\n return point\n\n#向左滑动(Y轴是不变的,X轴由大变小)\ndef swipe_lift():\n start_x = get_point()['width']/10*9#把X轴分为了10分,从9/10的位置滑动到1/10的位置\n end_x = get_point()['width']/10\n y = get_point()['height']/2\n driver.swipe(start_x, y,end_x,y,2000)\n print(\"向左滑动成功\")\n\n#向右滑动(Y轴是不变的,X轴由小变大)\ndef swipe_right():\n start_x = get_point()['width']/10#把X轴分为了10分,从1/10的位置滑动到9/10的位置\n end_x = get_point()['width']/10*9\n y = get_point()['height']/2\n driver.swipe(start_x=start_x,start_y=y,end_x=end_x,end_y=y,duration=2000)\n print(\"向右滑动成功\")\n\n#向上滑动(X轴是不变的,Y轴由大变小)\ndef swipe_up():\n x = get_point()['width']/2#把X轴分为了10分,从9/10的位置滑动到1/10的位置\n start_y = get_point()['height']/10*9\n end_y = get_point()['height']/10\n driver.swipe(start_x=x,start_y=start_y,end_x=x,end_y=end_y,duration=2000)\n print(\"向上滑动成功\")\n\n#向左滑动(Y轴是不变的,X轴由小变大)\ndef swipe_down():\n x = get_point()['width'] / 2 # 把X轴分为了10分,从1/10的位置滑动到9/10的位置\n start_y = get_point()['height'] / 10\n end_y = get_point()['height'] / 10*9\n driver.swipe(start_x=x, start_y=start_y, end_x=x, end_y=end_y,duration=2000)\n print(\"向下滑动成功\")\n\ndef swipe_on(fangxiang):\n \"\"\"\n 穿一个方向,即可调用响应的方向滑动函数\n :return 如果方向错误返回None\n \"\"\"\n try:\n if fangxiang == \"left\":\n swipe_lift()\n elif fangxiang == \"right\":\n swipe_right()\n elif fangxiang == \"up\":\n swipe_up()\n elif fangxiang == \"down\":\n swipe_down()\n except Exception as e:\n print(e.args)\n\n\n# swipe_on('left')\n# t.sleep(1)\n# swipe_on('left')\n# t.sleep(1)\n# swipe_on('left')\n#swipe_on('xxx')\n\ndef click_yinsizhengce():\n \"第一次启动时,出现的隐私政策弹窗处理\"\n #点击立即体验\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/btn_login\").click()\n t.sleep(5)\n #点击隐私政策“同意”按钮\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/button2\").click()\n t.sleep(5)\n\ndef select_login_type(loginType,code=000000):\n t.sleep(2)\n if loginType == \"wx\":\n # 选择“微信”登录\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/mRlLoginWX\").click()\n elif loginType == \"wb\":\n # 选择“微博”登录\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/mTvLoginWeiBo\").click()\n driver.find_element_by_id(\"com.sina.weibo:id/etLoginUsername\").send_keys('18601919819')\n driver.find_element_by_id(\"com.sina.weibo:id/etPwd\").send_keys(\"18601919819ayf\")\n elif loginType == \"qq\":\n # 选择“QQ”登陆\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/mRlLoginQQ\").click()\n elif loginType == \"iphone\":\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/mTvLoginMobile\").click()\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/mEdtPhoneNum\").send_keys('18601919819')\n driver.find_element_by_id('com.cctv.yangshipin.app.androidp:id/mBtn').click()#发送验证码\n driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/mEdt\").send_keys(code)\n\n\ndef click_my():\n # 点击“我的”按钮\n element = driver.find_element_by_id(\"com.cctv.yangshipin.app.androidp:id/home_tab_recycler_view\")\n elements = element.find_elements_by_class_name(\"android.widget.LinearLayout\")\n elements[3].click()\n print(\"点击到了我的页面\")\n t.sleep(2)\n\ndef login_wx():\n get_by_local = GetByLocal(driver)\n get_by_local.get_element('login_element','click_login').click()\n get_by_local.get_element('login_element','wx_login').click()\n t.sleep(10)\n driver.find_element_by_android_uiautomator('new UiSelector().text(\"请填写微信号/QQ号/邮箱\")').send_keys('1105614374')\n t.sleep(2)\n driver.find_element_by_android_uiautomator('new UiSelector().text(\"请填写密码\")').send_keys('18601919819ayf')\n t.sleep(2)\n driver.find_element_by_id('com.tencent.mm:id/ch7').click()\n\n\ndriver = get_driver()\nt.sleep(10)\ndriver.find_element_by_android_uiautomator('new UiSelector().text(\"我的\")').click()\nlogin_wx()\n\n\n\n\n# click_my()\n# click_goLogin()\n# select_login_type('wx')\n\n#使用UiSelector()定位\n# driver.find_element_by_android_uiautomator('new UiSelector().text(\"我的\")').click()\n# driver.find_element_by_android_uiautomator('new UiSelector().text(\"用户反馈\")').click()\n\n\n# def get_host():\n# tost_element = ('xpath','//*[contains(@text,\"验证码错误,请检查后重试\")]')\n# WebDriverWait(driver,10,0.1).until(EC.presence_of_element_located(tost_element))\n#\n# driver.keyevent(4)\n# get_host()","sub_path":"case/start_appium.py","file_name":"start_appium.py","file_ext":"py","file_size_in_byte":5830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"69812434","text":"# -*- coding: utf-8 -*-\n###############################################################################\n# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #\n# All rights reserved. #\n# This file is part of the AiiDA-FLEUR package. #\n# #\n# The code is hosted on GitHub at https://github.com/JuDFTteam/aiida-fleur #\n# For further information on the license, see the LICENSE.txt file #\n# For further information please visit http://www.flapw.de or #\n# http://aiida-fleur.readthedocs.io/en/develop/ #\n###############################################################################\n\"\"\"\nContains verdi commands for fleurinpdata\n\"\"\"\nfrom __future__ import absolute_import\nimport click\nfrom aiida.cmdline.commands.cmd_data.cmd_list import query, list_options\nfrom aiida.cmdline.params import arguments, options, types\nfrom aiida.cmdline.utils import decorators, echo\nfrom aiida.cmdline.params.types import DataParamType\nfrom aiida.plugins import DataFactory\n#from aiida_fleur.data.fleurinp import FleurinpData\nfrom . import cmd_data\nFleurinpData = DataFactory('fleur.fleurinp')\n\n\n@click.group('fleurinp')\ndef cmd_fleurinp():\n \"\"\"Commands to handle `FleurinpData` nodes.\"\"\"\n\n\ncmd_data.add_command(cmd_fleurinp)\n\n\n@cmd_fleurinp.command('list')\n@list_options # usual aiida list options\n@click.option('--uuid/--no-uuid', default=False, show_default=True, help='Display uuid of nodes.')\n@click.option('--ctime/--no-ctime', default=False, show_default=True, help='Display ctime of nodes.')\n@click.option('--extras/--no-extras', default=True, show_default=True, help='Display extras of nodes.')\n@click.option('--strucinfo/--no-strucinfo',\n default=False,\n show_default=True,\n help='Perpare additional information on the crystal structure to show. This slows down the query.')\n@decorators.with_dbenv()\ndef list_fleurinp(raw, past_days, groups, all_users, strucinfo, uuid, ctime, extras):\n \"\"\"\n List stored FleurinpData in the database with additional information\n \"\"\"\n # do a query and list all reuse AiiDA code\n from tabulate import tabulate\n list_project_headers = ['Id', 'Label', 'Description', 'Files'] # these we always get\n # 'UUID', 'Ctime',\n columns_dict = {\n 'ID': 'id',\n 'Id': 'id',\n 'UUID': 'uuid',\n 'Ctime': 'ctime',\n 'Label': 'label',\n 'Description': 'description',\n 'Files': 'attributes.files',\n 'Extras': 'attributes.extras'\n }\n\n if uuid:\n list_project_headers.append('UUID')\n if ctime:\n list_project_headers.append('Ctime')\n if extras:\n list_project_headers.append('Extras')\n\n project = [columns_dict[k] for k in list_project_headers]\n group_pks = None\n if groups is not None:\n group_pks = [g.pk for g in groups]\n\n data_fleurinp = query(FleurinpData, project, past_days, group_pks, all_users)\n if strucinfo: # second query\n # we get the whole node to get some extra information\n project2 = '*'\n fleurinps = query(FleurinpData, project2, past_days, group_pks, all_users)\n list_project_headers.append('Formula')\n counter = 0\n fleurinp_list_data = list()\n\n # , 'Formula', 'Symmetry'\n # It is fastest for list commands to only display content from a query\n if not raw:\n fleurinp_list_data.append(list_project_headers)\n for j, entry in enumerate(data_fleurinp):\n #print(entry)\n for i, value in enumerate(entry):\n if isinstance(value, list):\n new_entry = list()\n for elm in value:\n if elm is None:\n new_entry.append('')\n else:\n new_entry.append(elm)\n entry[i] = ','.join(new_entry)\n if strucinfo:\n structure = fleurinps[j][0].get_structuredata_ncf()\n formula = structure.get_formula()\n entry.append(formula)\n for i in range(len(entry), len(list_project_headers)):\n entry.append(None)\n counter += 1\n fleurinp_list_data.extend(data_fleurinp)\n if raw:\n echo.echo(tabulate(fleurinp_list_data, tablefmt='plain'))\n else:\n echo.echo(tabulate(fleurinp_list_data, headers='firstrow'))\n echo.echo('\\nTotal results: {}\\n'.format(counter))\n\n\n@cmd_fleurinp.command('cat')\n@arguments.NODE('node', type=DataParamType(sub_classes=('aiida.data:fleur.fleurinp',)))\n@click.option('-f',\n '--filename',\n 'filename',\n default='inp.xml',\n show_default=True,\n help='Disply the file content of the given filename.')\ndef cat_file(node, filename):\n \"\"\"\n Dumb the content of a file contained in given fleurinpdata, per default dump\n inp.xml\n \"\"\"\n echo.echo(node.get_content(filename=filename))\n\n\n'''\n@cmd_fleurinp.command('info')\ndef info():\n \"\"\"\n Shows some basic information about the fleurinp datastructure and dumbs the\n inp.xml\n \"\"\"\n click.echo('Not implemented yet, sorry. Please implement me!')\n\n\n@cmd_fleurinp.command('show')\ndef cmd_show():\n \"\"\"\n Shows the content of a certain file\n \"\"\"\n click.echo('Not implemented yet, sorry. Please implement me!')\n\n\n@cmd_fleurinp.command('open')\ndef open_inp():\n \"\"\"\n opens the inp.xml in some editor, readonly.\n inp.xml this way looking at xml might be more convenient.\n \"\"\"\n click.echo('Not implemented yet, sorry. Please implement me!')\n\n\n# this is a maybe\n@cmd_fleurinp.command()\ndef get_structure():\n \"\"\"\n Prints some basic information about the structure data and return a structure uuid/pk\n \"\"\"\n click.echo('Not implemented yet, sorry. Please implement me!')\n\n\n@cmd_fleurinp.command()\ndef get_kpoints():\n \"\"\"\n Prints some basic information about the kpoints data and returns a kpoints uuid/pk\n \"\"\"\n click.echo('Not implemented yet, sorry. Please implement me!')\n\n\n@cmd_fleurinp.command()\ndef get_parameters():\n \"\"\"\n Prints some basic information about the parameter data and returns a\n parameter data uuid/pk\n \"\"\"\n click.echo('Not implemented yet, sorry. Please implement me!')\n'''\n","sub_path":"aiida_fleur/cmdline/data/fleurinp.py","file_name":"fleurinp.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"624458085","text":"# solution1: O(nlogn)\nclass Solution1:\n def wiggleSort(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n nums.sort()\n half = len(nums[::2])\n nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1]\n\n# solution2: O(n)\nclass Solution2:\n def wiggleSort(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: void Do not return anything, modify nums in-place instead.\n \"\"\"\n def findKthLargest(nums, k):\n def partition(nums, pivot, start, end):\n nums[pivot], nums[start] = nums[start], nums[pivot]\n j = start + 1\n for i in range(start + 1, end + 1):\n if nums[i] >= nums[start]:\n nums[j], nums[i] = nums[i], nums[j]\n j += 1\n nums[start], nums[j - 1] = nums[j - 1], nums[start]\n\n return j - 1\n\n start, end = 0, len(nums) - 1\n while start <= end:\n pivot = random.randint(start, end)\n n = partition(nums, pivot, start, end)\n if k == n + 1:\n return nums[n]\n elif k > n + 1:\n start = n + 1\n else:\n end = n - 1\n \n def newIndex(i, n):\n return (2 * i + 1) % (n | 1)\n \n n = len(nums)\n mid = findKthLargest(nums, (n + 1) // 2)\n i, left, right = 0, 0, n - 1\n \n while i <= right:\n ni = newIndex(i, n)\n if nums[ni] > mid:\n nl = newIndex(left, n)\n nums[ni], nums[nl] = nums[nl], nums[ni]\n left += 1\n i += 1\n elif nums[ni] < mid:\n nr = newIndex(right, n)\n nums[ni], nums[nr] = nums[nr], nums[ni]\n right -= 1\n else:\n i += 1\n","sub_path":"python/324-wiggle-sort-2.py","file_name":"324-wiggle-sort-2.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"327286694","text":"import numpy as np\nimport copy\n\n#https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life\n\nclass Game:\n def __init__(self, width=6, height=6, beacon=None):\n self.board_size = (width, height)\n if beacon is None:\n self.beacon = np.zeros(self.board_size)\n else:\n self.beacon = beacon\n self.state = self.beacon\n\n\n def _numNeighbors(self, x, y, debugMode=0):\n if debugMode == 1:\n print ('---Game.py _numNeighbours ---')\n print ('Debug Mode: ON')\n print (' x=' + str(x) + ' y=' + str(y))\n print (self.state)\n startX = 0\n startY = 0\n endX = 0\n endY = 0\n neighbors = 0\n boardWidth = self.board_size[0]\n boardHeight = self.board_size[1]\n if debugMode ==1:\n print ('Board width = ' + str(boardWidth) + ' height = ' + str(boardHeight))\n\n if (x > 0):\n startX = -1\n if (y > 0):\n startY = -1\n\n #Need to subtract 1 from the board width and height for this comparison, due to the grid being 0-based\n if x < boardWidth - 1:\n endX = 1\n if y < boardHeight - 1:\n endY = 1\n\n if debugMode == 1:\n print (' startX: ' + str(startX) + ' to endX: ' + str(endX))\n print (' startY: ' + str(startY) + ' to endY: ' + str(endY))\n\n# if debugMode == 1:\n# #here because of my lack of understanding of Python\n# print 'checking X range'\n# for b in range(startX, endX + 1): #needs a +1 on the endX range to include it\n# print ' value = ' + str(b)\n \n# if debugMode == 1:\n# #here because of my lack of understanding of Python\n# print 'checking Y range'\n# for b in range(startY, endY + 1): #needs a +1 on the endY range to include it\n# print ' value = ' + str(b)\n\n if debugMode == 1:\n print ('Starting to check the ranges for all neighbours')\n\n\n for checkY in range(y + startY, y + endY + 1):\n if debugMode ==1:\n print (' --> Row:' + str(checkY))\n for checkX in range(x + startX, x + endX + 1):\n if debugMode ==1:\n print (' checking ' + str(checkX) + ', ' + str(checkY))\n print ('state: ' + str(self.state[checkX][checkY]))\n\n #print 'checking truthy test '\n #print (checkX == x and checkY == y)\n\n if (checkX == x and checkY == y):\n if debugMode ==1:\n print (' skipping the x, y co-ordinate start point')\n\n if not (checkX == x and checkY == y):\n #if debugMode == 1:\n #print ' checking state'\n #print ' state :' + str(self.state[checkX][checkY])\n #The Y and X are the 'wrong way round' for me, logically, but this is because of the way we use a list of lists.\n if (self.state[checkY][checkX] == 1): \n neighbors += 1\n\n if debugMode == 1:\n print (' found a neighbour at ' + str(checkX) + ', ' + str(checkY) + '. That''s ' + str(neighbors) + ' found.')\n if debugMode ==1:\n print ('state: ' + str(self.state[checkX][checkY]))\n\n\n if debugMode == 1:\n print ('finished checking row ' + str(checkY))\n \n if debugMode == 1:\n print ('finished checking all the rows')\n return neighbors\n\n def step(self):\n # Enumerate over every element and determine its number of neighbors\n # For each cell, check all eight neighbors and turn on or off\n processingState = copy(self.state)\n for x, y in np.ndenumerate(self.state):\n #This is an additional line that I want to remove later. (Testing git commit -i hunk staging)\n if (self._numNeighbors(x, y) < 2):\n processingState[x, y] = 0\n\n self.state = processingState\n # This is a comment to remove, also\n\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"542399316","text":"from module.sentence_data import SentenceData\nfrom module.bag_words import BagOfWords\nfrom sklearn.externals import joblib\nfrom keras.models import load_model\nfrom json import load\nimport pandas as pd\nimport numpy as np\n\nclf2 = joblib.load('model/clf2.pkl')\nmodel = load_model('model/model.h5')\n\nwith open('model/dicts.json', 'r') as fp:\n dicts = load(fp)\n \nwith open('model/vocab.json', 'r') as fp:\n vocab = load(fp)\n vocab = {int(k):vocab[k] for k in vocab}\n vocab_data = BagOfWords(vocab)\n \nwith open('model/intent.json', 'r') as fp:\n intent = load(fp)\n intent = {int(k):intent[k] for k in intent}\n\nw2idx, labels2idx = dicts['words2idx'], dicts['labels2idx']\nidx2w = {w2idx[k]:k for k in w2idx}\nidx2la = {labels2idx[k]:k for k in labels2idx}\n\ntext = \"tolong putarkan lagu separuh aku dari noah terima kasih\"\ntext = SentenceData(text)\n\ntext_predict = np.array(list(map(lambda x: w2idx[x], text.get(\"text\").split())))\ntext_predict = text_predict[np.newaxis,:]\npred = model.predict_on_batch(np.array(text_predict))\npred = np.argmax(pred,-1)[0]\n\npredword_val = []\nfor label in pred:\n x = idx2la[label]\n predword_val.append(x)\ntext.set(\"entities\", predword_val)\n\nlabels = vocab_data.create_labels()\nbow_tuple = [tuple(vocab_data.create_bow(text.token_to_ent()))]\n\ndf = pd.DataFrame.from_records(bow_tuple, columns=labels)\n\nidxIntent = clf2.predict(df)\nidxIntent = idxIntent[0]\n\nresponse = {}\nresponse[\"text\"] = text.get(\"text\")\nresponse[\"intent\"] = intent[idxIntent]\nresponse[\"entities\"] = text.extract_entity()\nprint(response)","sub_path":"classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"345810684","text":"import pkg_resources\nimport importlib\nimport requests\nimport os\n\n\nfrom dlhub_sdk.models import BaseMetadataModel\n\n\nclass BaseServableModel(BaseMetadataModel):\n \"\"\"Base class for servables\"\"\"\n\n def __init__(self):\n super(BaseServableModel, self).__init__()\n\n # Add the resource type\n # I chose \"InteractiveResource\" as the point of DLHub is to provide\n # web servies for interacting with these models (\"query/response portals\" are\n # defined as \"InteractiveResources\") rather than downloading the source code\n # (which would fit the definition of software)\n self._output['datacite']['resourceType'] = {'resourceTypeGeneral': 'InteractiveResource'}\n\n # Initialize the model running-information\n self._output['servable'] = {\n 'methods': {'run': {}},\n 'shim': self._get_handler(),\n 'type': self._get_type(),\n 'dependencies': {'python': {}}\n }\n\n def _get_handler(self):\n \"\"\"Generate the name of the servable class that DLHub will use to read this metadata\n\n Returns:\n (string) path to the python class (e.g., \"python.PythonStaticMethod\")\n \"\"\"\n raise NotImplementedError()\n\n def _get_type(self):\n \"\"\"Get a human-friendly name for this type of servable\n\n Returns:\n (string): Human-friendly name of an object\n \"\"\"\n raise NotImplementedError()\n\n def register_function(self, name, inputs, outputs, parameters=None, method_details=None):\n \"\"\"Registers a new function to this servable\n\n See :code:`compose_argument_type` utility function for how to define the inputs\n and outputs to this function.\n\n Args:\n name (string): Name of the function (e.g., \"run\")\n inputs (dict): Description of inputs to the function\n outputs (dict): Description of the outputs of the function\n parameters (dict): Any additional parameters for the function and their default values\n method_details (dict): Any options used when constructing a shim to run this function.\n \"\"\"\n\n # Check defaults\n if method_details is None:\n method_details = {}\n if parameters is None:\n parameters = {}\n\n # Add the function\n self._output[\"servable\"][\"methods\"][name] = {\n 'input': inputs,\n 'output': outputs,\n 'parameters': parameters,\n 'method_details': method_details\n }\n\n return self\n\n def to_dict(self, simplify_paths=False, save_class_data=False):\n # Make sure the inputs and outputs have been set\n if len(self._output[\"servable\"][\"methods\"][\"run\"].get(\"input\", {})) == 0:\n raise ValueError('Inputs have not been defined')\n if len(self._output[\"servable\"][\"methods\"][\"run\"].get(\"output\", {})) == 0:\n raise ValueError('Outputs have not been defined')\n\n return super(BaseServableModel, self).to_dict(simplify_paths)\n\n def add_requirement(self, library, version=None):\n \"\"\"Add a required Python library.\n\n The name of the library should be either the name on PyPI, or a link to the\n\n Args:\n library (string): Name of library\n version (string): Required version. 'latest' to use the most recent version on PyPi (if\n available). 'detect' will attempt to find the version of the library installed on\n the computer running this software.\n \"\"\"\n\n # Attempt to determine the version automatically\n if version == \"detect\":\n try:\n module = importlib.import_module(library)\n version = module.__version__\n except:\n version = pkg_resources.get_distribution(library).version\n elif version == \"latest\":\n pypi_req = requests.get('https://pypi.org/pypi/{}/json'.format(library))\n version = pypi_req.json()['info']['version']\n\n # Set the requirements\n self._output[\"servable\"][\"dependencies\"][\"python\"][library] = version\n return self\n\n def add_requirements(self, requirements):\n \"\"\"Add a dictionary of requirements\n\n Utility wrapper for `add_requirement`\n\n Args:\n requirements (dict): Keys are names of library (str), values are the version\n \"\"\"\n for p, v in requirements.items():\n self.add_requirement(p, v)\n return self\n\n def parse_repo2docker_configuration(self, directory=None):\n \"\"\"Gathers information about required environment from repo2docker configuration files.\n\n See https://repo2docker.readthedocs.io/en/latest/config_files.html for more details\n\n Args:\n directory (str): Path to directory containing configuration files\n (default: current working directory)\n \"\"\"\n\n # Get a list of all files\n config_files = ['environment.yml', 'requirements.txt', 'setup.py', 'REQUIRE', 'install.R',\n 'apt.txt', 'DESCRIPTION', 'manifest.xml', 'postBuild', 'start',\n 'runtime.txt', 'default.nix', 'Dockerfile']\n\n # Get the directory name if `None`\n if directory is None:\n directory = os.getcwd()\n\n # Add every file we can find\n for file in config_files:\n path = os.path.join(directory, file)\n if os.path.isfile(path):\n self.add_file(path)\n\n return self\n","sub_path":"dlhub_sdk/models/servables/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"394962424","text":"import numpy as np\n\nvender_map = {} # key: mac, '00:00:01', value: ('short name', 'long name')\nmanuf_path = 'MAC_OUI/manuf.txt'\n\ndef load_vender_map():\n with open(manuf_path) as f:\n for line in f:\n line = line.strip()\n if not line: continue\n if line.startswith('#'): continue\n if '#' in line: line = line[:line.index('#')].strip()\n \n lsp = list(filter(None, line.split('\\t')))\n assert 2 <= len(lsp) <= 3, f'{line}, {lsp}'\n\n if len(lsp) == 2: mac, sname, lname = lsp[0], lsp[1], lsp[1]\n else: mac, sname, lname = lsp\n\n if mac.endswith('/28'): # eample: 00:55:DA:00:00:00/28\n mac = mac[:10]\n \n vender_map[mac] = (sname, lname)\n\n\ndef get_vendor(mac: str):\n mac = mac.upper()\n if mac == 'None':\n return 'None'\n if mac.startswith('00:00:00'):\n return 'None'\n if mac.startswith('FF:FF:FF'):\n return 'None'\n if mac[:8] in vender_map.keys():\n return vender_map[mac[:8]][0]\n if mac[:10] in vender_map.keys():\n return vender_map[map[:10]][0]\n return 'None'\n\n\ndef get_top_vendors(pd_sample, n: int=10):\n num_samples = pd_sample.shape[0]\n\n from collections import Counter\n\n unique_macs = set([row.name for _, row in pd_sample.iterrows()])\n\n c = Counter([get_vendor(mac) for mac in unique_macs])\n \n top_vendors = []\n\n for vendor, n_packets in c.most_common():\n if vendor == '00:00:00': continue\n if len(top_vendors) >= n: break\n if vendor == 'None': continue\n # if n_packets < num_samples / 100: break\n\n top_vendors.append(vendor)\n\n return top_vendors\n\n\ndef label_packets(pd_packets, vendors):\n samples = []\n labels = []\n samples_without_vendor = []\n\n for _, row in pd_packets.iterrows():\n vendor = get_vendor(row.name)\n \n if vendor == 'None':\n samples_without_vendor.append(np.array(row))\n else: \n samples.append(np.array(row))\n if vendor in vendors:\n labels.append(vendor)\n else:\n labels.append('Others')\n\n return samples, labels, samples_without_vendor\n\n\nload_vender_map()\n\n","sub_path":"py_classifier/mac_vendor.py","file_name":"mac_vendor.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"136384558","text":"#!/usr/bin/env python\n# coding: utf8\n\n'''\nhong edit\nto check app\n20160822 fisrt\n20160829 scrond\n'''\n\nimport os\nimport pprint\n\n#变量,可以通过脚本执行的参数传入\napp = \"redis\" #sys.argv[1]\nversion = \"3.0.1\" #sys.argv[2]\nport = \"6943\" #sys.argv[3]\n\n#根据目录命名规则初始化含端口号的目录名\napp_name = app\napp_svr = app + '-' + version\nif port != '':\n app_name = app_name + '_' + port #软连接\n app_svr = app_svr + '_' + port #实体\n\nnjInfo = {'status': 'True', 'errLog': '', 'content': {}}\n#初始化常用的几个目录名(/apps/目录下),不同服务不必重新写,直接引用即可。\napp_conf_dir = \"/apps/conf/%s/\" % app_name\napp_run_dir = \"/apps/run/%s/\" % app_name\napp_logs_dir = \"/apps/logs/%s/\" % app_name\napp_svr_dir = \"/apps/svr/%s/\" % app_svr\napp_data_dir = \"/apps/data/%s/\" % app_name\napp_sh_dir = \"/apps/sh/\"\napp_link_dir = '/apps/svr/%s/' % app_name\napp_dir = (app_conf_dir, app_run_dir, app_logs_dir, app_svr_dir, app_data_dir, app_sh_dir, app_link_dir)\n#初始化常用的几个文件名,不同服务不必重新写,直接引用即可。\napp_conf_file = app_conf_dir + \"%s.conf\" % app\napp_run_file = app_run_dir + \"%s.pid\" % app_name\napp_logs_file = app_logs_dir + \"%s.log\" % app_name\napp_sh_file = app_sh_dir + \"%s.sh\" % app_name\n\n#初始化常用的几个软连接名,不同服务不必重新写,直接引用即可。\napp_slink_svr_dir = \"/apps/svr/%s/\" % app_name\napp_slink_conf_dir = app_slink_svr_dir + 'conf'\napp_slink_run_dir = app_slink_svr_dir + 'run'\napp_slink_logs_dir = app_slink_svr_dir + 'logs'\napp_slink_data_dir = app_slink_svr_dir + 'data'\napp_slink_dir = (app_slink_conf_dir, app_slink_data_dir, app_slink_svr_dir, app_slink_run_dir, app_slink_logs_dir)\n#定义需要检查软连接\napp_slink_check = ((app_slink_svr_dir, app_svr_dir), (app_conf_dir, app_slink_conf_dir), (app_run_dir, app_slink_run_dir), (app_logs_dir, app_slink_logs_dir), (app_data_dir, app_slink_data_dir))\n#初始化常用的文件权限【username,groupname,facl】,\"['755','775']\"是为了考虑有的文件权限可以为755或775的情况\nfacl_apps_apps_755 = ('apps', 'apps', ('755', '775'))\nfacl_apps_apps_777 = ('apps', 'apps', '777')\n\n#定义要检查的目录及其权限,引用上面定义的目录和权限\ncheck_list_redis_directory = {app_dir: facl_apps_apps_755}\n#定义要检查的文件及其权限,引用上面定义的文件和权限\ncheck_list_redis_file = {app_conf_file: facl_apps_apps_755, app_sh_file: facl_apps_apps_755}\n#定义要检查的目录及其权限(目录下的所有文件权限值都相同),引用上面定义的目录和权限\ncheck_list_redis_allfiles_in_directory = {app_svr_dir: facl_apps_apps_755}\n#定义要检查的软连接及其权限,引用上面定义的软连接和权限\ncheck_list_redis_softlink = {app_slink_check: facl_apps_apps_755}\n\n#汇总所有检查项\ncheck_list_redis = {'directory': check_list_redis_directory, 'file': check_list_redis_file, 'allfiles': check_list_redis_allfiles_in_directory, 'softlink': check_list_redis_softlink}\n\nwith open('/etc/passwd') as passwd:\n for i in passwd.readlines():\n if facl_apps_apps_755[0] == i.split(\":\")[0]:\n uid = i.split(\":\")[2]\n\nwith open('/etc/group') as group:\n for i in group.readlines():\n if facl_apps_apps_755[1] == i.split(':')[0]:\n gid = i.split(':')[2]\n\n\ndef is_dir(filepath): #是否是目录\n if os.path.isdir(filepath):\n return True\n\n\ndef is_file(filepath): #是否是文件\n if os.path.isfile(filepath):\n return True\n\n\ndef is_dir_soft_link(filepath): #是否是软连接\n if os.path.islink(filepath):\n return True\n\n\ndef get_file_acl(filepath): #获取文件权限(如:755)\n try:\n if os.path.exists(filepath):\n return oct(os.stat(filepath).st_mode)[-3:]\n except OSError:\n return False\n\n\ndef get_file_user(filepath): #获取文件用户名\n try:\n if os.path.exists(filepath):\n return str(os.stat(filepath).st_uid)\n except OSError:\n return None\n\n\ndef get_install_user(filepath): # 获取文件用户名\n try:\n ou = str(os.stat(filepath).st_uid)\n with open('/etc/passwd') as passwd:\n for i in passwd.readlines():\n if ou == i.split(\":\")[2]:\n return i.split(\":\")[0]\n except OSError:\n return False\n\n\ndef get_file_group(filepath):\n try:\n if os.path.exists(filepath):\n return str(os.stat(filepath).st_gid)\n except OSError:\n return None\n\n\ndef get_install_group(filepath):\n try:\n with open('/etc/group') as group:\n for i in group.readlines():\n if str(os.stat(filepath).st_gid) == i.split(\":\")[2]:\n return i.split(\":\")[0]\n except OSError:\n return False\n\n\ndef get_all_files_from_directory(filepath, filelist): #获取目录下所有文件\n try:\n if os.path.exists(filepath):\n for root, dirs, files in os.walk(filepath):\n for f in files:\n filelist.append(os.path.join(root, f))\n except OSError:\n return False\n\n\ndef is_soft_link_right(sourcepath, destpath): #��连接指向是否正确\n try:\n if not os.path.samefile(sourcepath, destpath):\n njInfo['status'] = 'False'\n njInfo['content'][sourcepath] = 'check failed. %s soft link is not %s' % (sourcepath, destpath)\n except OSError:\n if not os.path.exists(sourcepath):\n njInfo['status'] = 'False'\n njInfo['content'][sourcepath] = 'check failed. %s soft link is not exists' % sourcepath\n if not os.path.exists(destpath):\n njInfo['status'] = 'False'\n njInfo['content'][destpath] = 'check failed. %s soft link is not exists' % destpath\n\n\ndef check_facl(i, facl_list): #根据传入路径的用户、属组、权限list,检查路径权限:不区分目录和文件\n # facl_list 类似于 ['apps', 'apps', ['755', '775']],分别为用户,别组,权限码\n if get_file_user(i) != uid or get_file_group(i) != gid or get_file_acl(i) not in facl_list[2]:\n njInfo['status'] = 'False'\n njInfo['content'][i] = '%s: check failed. facl is \"%s %s %s\" and right is \"%s %s %s\"' % (i, get_install_user(i), get_install_group(i), get_file_acl(i), facl_list[0], facl_list[1], ' or '.join(facl_list[2]))\n\n\ndef check_directory(path, facl_list): #检查目录的权限\n # facl_list 类似于 ['apps', 'apps', ['755', '775']],分别为用户,别组,权限码\n if is_dir(path):\n check_facl(path, facl_list)\n\n\ndef check_file(path, facl_list): #检查文件权限\n if is_file(path):\n check_facl(path, facl_list)\n\n\ndef check_all_files(path, facl_list): #检查目录下所有文件的权限\n if is_dir(path):\n filelist = []\n get_all_files_from_directory(path, filelist)\n for files in filelist:\n check_facl(files, facl_list)\n\n\ndef check_softlink(src): #检查软连接的权限\n if os.path.samefile(os.path.join('/apps/%s/%s' % (src, app_name)), os.path.join(app_link_dir, src)):\n return True\n\n#usage: ./check_file_acl.py service version port(if has)\n#example: ./check_file_acl.py redis 3.0.1 6379\nif __name__ == '__main__':\n #根据app名称,获取上面定义的全量检查list,如: check_list_redis()\n check_dict = eval('check_list_' + app)\n #遍历每个检查项\n for k, v in check_dict.items():\n if k == 'directory': #检查apps下面各个文件夹的权限\n for key in check_dict['directory']:\n for i in key:\n check_directory(i, facl_apps_apps_755)\n\n elif k == 'file': #检查指定文件的权限\n for key in check_dict['file']:\n check_file(key, facl_apps_apps_755)\n\n elif k == 'softlink': #检查需要做软连接的目录的权限和软连接是否正常\n for key in check_dict['softlink']:\n for x, y in key:\n is_soft_link_right(x, y)\n\n elif k == 'allfiles': #暂时不做判断\n pass\n ouput = pprint.PrettyPrinter(indent=4)\n ouput.pprint(njInfo)\n\n\n\n","sub_path":"cmcc/file_acl_check.py","file_name":"file_acl_check.py","file_ext":"py","file_size_in_byte":8445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"424672052","text":"import os\nimport json\nimport requests\nimport logging\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\ndef handler(event, context):\n try:\n logger.debug(event['queryStringParameters'])\n\n params = event['queryStringParameters']\n access_token = os.environ['ACCESS_TOKEN']\n\n rep = query_interest(**params, token=access_token)\n\n response = {\n \"statusCode\": 200,\n \"body\": json.dumps(rep)\n }\n\n return response\n\n except Exception as e:\n logger.exception(e)\n raise e\n\n\ndef query_interest(interest=None, limit=10, locale=None, token=None):\n try:\n main_url = 'https://graph.facebook.com'\n endpoint = '/search'\n params = {\n 'type': 'adinterest',\n 'q': interest,\n 'limit': limit,\n 'locale': locale,\n 'access_token': token\n }\n rep = requests.get(\n f'{main_url}{endpoint}',\n params=params\n )\n logger.debug(rep)\n\n if rep.ok:\n return rep.json()\n\n else:\n return rep.content\n\n except Exception as e:\n logger.exception(e)\n raise e\n","sub_path":"src/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"9144056","text":"from pybrain.datasets import ClassificationDataSet\nfrom pybrain.utilities import percentError\nfrom pybrain.tools.shortcuts import buildNetwork\nfrom pybrain.supervised.trainers import BackpropTrainer\nfrom pybrain.structure.modules import SoftmaxLayer\n\nfrom sklearn import preprocessing\nimport pandas as pd\n\ndataframe = pd.read_csv('../../data/signals_nabil.csv', index_col = 0, parse_dates = True)\n# normalization\n# cp = dataframe.pop(' Close Price')\n# x = cp.values\n# min_max_scaler = preprocessing.MinMaxScaler()\n# x_scaled = min_max_scaler.fit_transform(x)\n# dataframe[' Close Price'] = x_scaled\n \nalldata = ClassificationDataSet(1, 1, nb_classes=3, class_labels = ['hold','sell','buy'])\ninp = dataframe[['madiff','signal']]\nfor b,c in inp.values:\n # if c=='hold': c = 0\n # elif c == 'buy': c = 1\n # else: c =2\n alldata.addSample([b],c)\ntstdata_temp, trndata_temp = alldata.splitWithProportion( 0.25 )\n\n# to convert supervised datasets to classification datasets\ntstdata = ClassificationDataSet(1, 1, nb_classes=3)\nfor n in range(0, tstdata_temp.getLength()):\n tstdata.addSample( tstdata_temp.getSample(n)[0], tstdata_temp.getSample(n)[1] )\ntrndata = ClassificationDataSet(1, 1, nb_classes=3)\nfor n in range(0, trndata_temp.getLength()):\n trndata.addSample( trndata_temp.getSample(n)[0], trndata_temp.getSample(n)[1])\n# \ntrndata._convertToOneOfMany()\ntstdata._convertToOneOfMany()\n#\n# print (\"Number of training patterns: \", len(trndata))\n# print (\"Input and output dimensions: \", trndata.indim, trndata.outdim)\n# print (\"(input, target, class):\")\n# print (trndata['input'][0], trndata['target'][0], trndata['class'][0])\n\n# build network\nfnn = buildNetwork(trndata.indim, 20, trndata.outdim, outclass = SoftmaxLayer, bias = True)\n# set up brckprop trainer\ntrainer = BackpropTrainer(fnn, dataset = trndata, learningrate = 0.001, momentum = 0.1, verbose = True )\n\n#start training iterations\n# for i in range(10):\n# trainer.trainEpochs(1)\n# trnresult = percentError(trainer.testOnClassData(),trndata['class'])\n# tstresult = percentError(trainer.testOnClassData(dataset = tstdata),tstdata['class'])\n# print(\"epoch: %4d\"%trainer.totalepochs,\"\\ntrain error: %5.2f%%\"%trnresult,\"\\ntest error: %5.2f%%\"%tstresult)\n\ntrainer.trainUntilConvergence(verbose=True,\n trainingData=trndata,\n validationData=tstdata,\n maxEpochs=10)\nout = fnn.activateOnDataset(tstdata)\n\n","sub_path":"src/prediction/classi_nabil.py","file_name":"classi_nabil.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"326273758","text":"from typing import Sequence\n\nfrom snapflow.schema.base import Schema\nfrom snapflow.storage.data_copy.base import (\n Conversion,\n DiskToMemoryCost,\n NetworkToBufferCost,\n NetworkToMemoryCost,\n datacopy,\n)\nfrom snapflow.storage.data_formats import (\n DatabaseTableFormat,\n DatabaseTableRefFormat,\n DataFormat,\n RecordsFormat,\n RecordsIteratorFormat,\n)\nfrom snapflow.storage.db.api import DatabaseStorageApi\nfrom snapflow.storage.storage import (\n DatabaseStorageClass,\n PythonStorageApi,\n PythonStorageClass,\n StorageApi,\n)\n\n\n@datacopy(\n from_storage_classes=[PythonStorageClass],\n from_data_formats=[RecordsFormat],\n to_storage_classes=[DatabaseStorageClass],\n to_data_formats=[DatabaseTableFormat],\n cost=NetworkToMemoryCost,\n)\ndef copy_records_to_db(\n from_name: str,\n to_name: str,\n conversion: Conversion,\n from_storage_api: StorageApi,\n to_storage_api: StorageApi,\n schema: Schema,\n):\n assert isinstance(from_storage_api, PythonStorageApi)\n assert isinstance(to_storage_api, DatabaseStorageApi)\n mdr = from_storage_api.get(from_name)\n to_storage_api.bulk_insert_records(to_name, mdr.records_object, schema)\n\n\n@datacopy(\n from_storage_classes=[PythonStorageClass],\n from_data_formats=[RecordsIteratorFormat],\n to_storage_classes=[DatabaseStorageClass],\n to_data_formats=[DatabaseTableFormat],\n cost=NetworkToBufferCost,\n)\ndef copy_records_iterator_to_db(\n from_name: str,\n to_name: str,\n conversion: Conversion,\n from_storage_api: StorageApi,\n to_storage_api: StorageApi,\n schema: Schema,\n):\n assert isinstance(from_storage_api, PythonStorageApi)\n assert isinstance(to_storage_api, DatabaseStorageApi)\n mdr = from_storage_api.get(from_name)\n for records in mdr.records_object:\n to_storage_api.bulk_insert_records(to_name, records, schema)\n","sub_path":"snapflow/storage/data_copy/memory_to_database.py","file_name":"memory_to_database.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"334436677","text":"# This script gets quality metrics for the outputs.\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nfrom covid_bronx.quality import fasta_files, sam_files\nfrom covid_bronx.quality.gaps import *\n\nprimer_binding_sites = \"data/external/amplicon_binding_sites.csv\"\n\nsample_ids = {\n \"reinfection01\": \"sample_barcode01\",\n \"reinfection02\": \"sample_barcode02\",\n \"reinfection03\": \"sample_barcode03\",\n \"reinfection04\": \"sample_barcode04\",\n \"reinfection05\": \"sample_barcode05\",\n \"reinfection06\": \"sample_barcode06\",\n \"reinfection07\": \"sample_barcode07\",\n \"reinfection08\": \"sample_barcode08\",\n \"reinfection09\": \"sample_barcode09\",\n}\n\nfasta_dict = {k: f\"data/final/reinfection/output/{v}.consensus.fasta\" for k,v in sample_ids.items()}\nsam_dict = {k: f\"data/final/reinfection/output/{v}.primertrimmed.rg.sorted.bam\" for k,v in sample_ids.items()}\n\nfor sample_id, fasta_file in tqdm(fasta_dict.items()):\n\n\n consensus_fasta = fasta_file\n consensus_sam = sam_dict[sample_id]\n out = f\"data/processed/reinfection/{sample_id}_gaps\"\n df = compute_primer_coverages(consensus_sam, consensus_fasta, primer_binding_sites, out)\n df.to_csv(f\"data/processed/reinfection/{sample_id}.csv\")\n","sub_path":"scripts/reinfection/run_quality.py","file_name":"run_quality.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"596022902","text":"def main():\n stack = set()\n for i in range(100, 1000):\n for j in range(i, 1000):\n if is_palindrome(i * j):\n stack.add(i * j)\n print(max(stack))\n\n\ndef is_palindrome(x):\n s = str(x)\n return s == s[::-1]\n\n\nif __name__ == '__main__':\n main()","sub_path":"p004.py","file_name":"p004.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"294697807","text":"boo = 0\r\nanswers = []\r\n\r\nwith open('lastwordinput.txt', 'r') as fi:\r\n for line in fi:\r\n if boo == 0:\r\n boo = 1\r\n continue\r\n \r\n vals = str(line.split()[0])\r\n #print vals\r\n \r\n lastword = str(vals[0])\r\n vals = vals[1:]\r\n\r\n for letter in vals:\r\n if letter >= lastword[0]:\r\n lastword = str(letter) + lastword\r\n else:\r\n lastword = lastword + str(letter)\r\n\r\n answers.append(lastword)\r\n \r\n fi.close\r\n\r\nval = 1\r\nwith open('lastwordoutput.txt', 'a') as fi:\r\n for answer in answers:\r\n fi.write('Case #' + str(val) + ': ' + str(answer) + '\\n')\r\n val += 1\r\n fi.close\r\n","sub_path":"codes/CodeJamCrawler/16_1_1_neat/16_1_1_Trid3nt_Code Jam A.py","file_name":"16_1_1_Trid3nt_Code Jam A.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}