diff --git "a/5574.jsonl" "b/5574.jsonl" new file mode 100644--- /dev/null +++ "b/5574.jsonl" @@ -0,0 +1,689 @@ +{"seq_id":"373005432","text":"# coding: utf-8\n\n\"\"\"\n ORY Hydra\n\n Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. # noqa: E501\n\n The version of the OpenAPI document: v1.7.0\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom ory_hydra_client.configuration import Configuration\n\n\nclass LogoutRequest(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'request_url': 'str',\n 'rp_initiated': 'bool',\n 'sid': 'str',\n 'subject': 'str'\n }\n\n attribute_map = {\n 'request_url': 'request_url',\n 'rp_initiated': 'rp_initiated',\n 'sid': 'sid',\n 'subject': 'subject'\n }\n\n def __init__(self, request_url=None, rp_initiated=None, sid=None, subject=None, local_vars_configuration=None): # noqa: E501\n \"\"\"LogoutRequest - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._request_url = None\n self._rp_initiated = None\n self._sid = None\n self._subject = None\n self.discriminator = None\n\n if request_url is not None:\n self.request_url = request_url\n if rp_initiated is not None:\n self.rp_initiated = rp_initiated\n if sid is not None:\n self.sid = sid\n if subject is not None:\n self.subject = subject\n\n @property\n def request_url(self):\n \"\"\"Gets the request_url of this LogoutRequest. # noqa: E501\n\n RequestURL is the original Logout URL requested. # noqa: E501\n\n :return: The request_url of this LogoutRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._request_url\n\n @request_url.setter\n def request_url(self, request_url):\n \"\"\"Sets the request_url of this LogoutRequest.\n\n RequestURL is the original Logout URL requested. # noqa: E501\n\n :param request_url: The request_url of this LogoutRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._request_url = request_url\n\n @property\n def rp_initiated(self):\n \"\"\"Gets the rp_initiated of this LogoutRequest. # noqa: E501\n\n RPInitiated is set to true if the request was initiated by a Relying Party (RP), also known as an OAuth 2.0 Client. # noqa: E501\n\n :return: The rp_initiated of this LogoutRequest. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._rp_initiated\n\n @rp_initiated.setter\n def rp_initiated(self, rp_initiated):\n \"\"\"Sets the rp_initiated of this LogoutRequest.\n\n RPInitiated is set to true if the request was initiated by a Relying Party (RP), also known as an OAuth 2.0 Client. # noqa: E501\n\n :param rp_initiated: The rp_initiated of this LogoutRequest. # noqa: E501\n :type: bool\n \"\"\"\n\n self._rp_initiated = rp_initiated\n\n @property\n def sid(self):\n \"\"\"Gets the sid of this LogoutRequest. # noqa: E501\n\n SessionID is the login session ID that was requested to log out. # noqa: E501\n\n :return: The sid of this LogoutRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._sid\n\n @sid.setter\n def sid(self, sid):\n \"\"\"Sets the sid of this LogoutRequest.\n\n SessionID is the login session ID that was requested to log out. # noqa: E501\n\n :param sid: The sid of this LogoutRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._sid = sid\n\n @property\n def subject(self):\n \"\"\"Gets the subject of this LogoutRequest. # noqa: E501\n\n Subject is the user for whom the logout was request. # noqa: E501\n\n :return: The subject of this LogoutRequest. # noqa: E501\n :rtype: str\n \"\"\"\n return self._subject\n\n @subject.setter\n def subject(self, subject):\n \"\"\"Sets the subject of this LogoutRequest.\n\n Subject is the user for whom the logout was request. # noqa: E501\n\n :param subject: The subject of this LogoutRequest. # noqa: E501\n :type: str\n \"\"\"\n\n self._subject = subject\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, LogoutRequest):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, LogoutRequest):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"clients/hydra/python/ory_hydra_client/models/logout_request.py","file_name":"logout_request.py","file_ext":"py","file_size_in_byte":6090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"78767319","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n Fichier cartel.py\n import cartels depuis un fichier text\n The format for cartel.txt is a plain text file beginning with the first cartel,\n one line of the file for each line of the address.\n No blank lines inside the address, and a single blank line between the addresses and *two* blank lines after\n the last address. \n\"\"\"\n\n#import csv\nimport os\nfrom scribus import *\n\n# config\nmyFile_In = \"/Users/macmini/Documents/Scribus/cartel.txt\"\n\n# imput values\nlargeur_page = float(scribus.valueDialog(\n 'Largeur du cartel', 'Largeur en mm du cartel\\n(valeur par default)', '200'))\nhauteur_page = float(scribus.valueDialog(\n 'Hauteur du cartel', 'Hauteur en mm du cartel\\n(valeur par default)', '200'))\nmarges_page = int(scribus.valueDialog('Marges du cartel',\n 'Marges en mm du cartel\\n(valeur par default)', '20'))\nfont_size = float(scribus.valueDialog('Taille du Text',\n 'Taille de la police en pt\\n(valeur par default)', '12'))\ninterlignage_size = float(scribus.valueDialog(\n 'Interlignage', 'Interlignage en pt\\n(valeur par default)', str(font_size + 2)))\n\n\nif scribus.newDoc((hauteur_page, largeur_page), (marges_page, marges_page, marges_page, marges_page), scribus.LANDSCAPE, 1, scribus.UNIT_MILLIMETERS, scribus.NOFACINGPAGES, scribus.FIRSTPAGERIGHT):\n #scribus.createParagraphStyle(\"cartel_style\", 0, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, \"charstyle\")\n\n f_in = open(myFile_In, 'r')\n add = ''\n page = 0\n while 1:\n info = file.readline(f_in)\n if not info:\n break\n if info != '\\n':\n add = add + info\n else:\n if page:\n scribus.newPage(-1)\n textbox = scribus.createText(\n marges_page, marges_page, largeur_page - 2 * marges_page, hauteur_page - 2 * marges_page)\n scribus.setText(add, textbox)\n scribus.setTextAlignment(scribus.ALIGN_LEFT, textbox)\n scribus.setFont(\"Avenir Medium\", textbox)\n scribus.setFontSize(font_size, textbox)\n scribus.setLineSpacing(interlignage_size, textbox)\n #scribus.setStyle(\"cartel_style\", textbox)\n\n add = ''\n page = page + 1\n\nf_in.close()\n","sub_path":"cartel/cartel.py","file_name":"cartel.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"456113307","text":"'''\nMultiplication table printer\n'''\ndef multi_table(a, n):\n for i in range(1, n+1):\n print('{0} x {1} = {2}'.format(a, i, a*i))\n\nif __name__ == '__main__':\n a = input('Enter a number: ')\n n = input('Enter number of multiples: ')\n multi_table(float(a), int(n))","sub_path":"multiTable.py","file_name":"multiTable.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"108738278","text":"import argparse\nimport os\nimport subprocess\n\nfrom platform import python_version\nfrom py3status.version import version\n\nLIST_EPILOG = \"\"\"\nexamples:\n list:\n # list one or more modules\n py3status list clock loadavg xrandr # full\n py3status list coin* git* w* # fnmatch\n\n # list all modules\n py3status list --all\n\n # show full (i.e. docstrings)\n py3status list -f static_string\n\"\"\"\n\nDOCSTRING_EPILOG = \"\"\"\nexamples:\n check:\n # check one or more docstrings\n py3status docstring --check clock loadavg xrandr\n\n # check all docstrings\n py3status docstring --check\n\n diff:\n # show diff docstrings\n py3status docstring --diff\n\n update:\n # update one or more docstrings\n py3status docstring --update clock loadavg xrandr\n\n # update modules according to README.md\n py3status docstring --update modules\n\"\"\"\n\n\ndef parse_cli():\n \"\"\"\n Parse the command line arguments\n \"\"\"\n # get config paths\n home_path = os.path.expanduser(\"~\")\n xdg_home_path = os.environ.get(\"XDG_CONFIG_HOME\", \"{}/.config\".format(home_path))\n xdg_dirs_path = os.environ.get(\"XDG_CONFIG_DIRS\", \"/etc/xdg\")\n\n # get i3status path\n try:\n with open(os.devnull, \"w\") as devnull:\n command = [\"which\", \"i3status\"]\n i3status_path = (\n subprocess.check_output(command, stderr=devnull).decode().strip()\n )\n except subprocess.CalledProcessError:\n i3status_path = None\n\n # i3status config file default detection\n # respect i3status' file detection order wrt issue #43\n i3status_config_file_candidates = [\n \"{}/.i3status.conf\".format(home_path),\n \"{}/i3status/config\".format(xdg_home_path),\n \"{}/.config/i3/i3status.conf\".format(home_path),\n \"{}/.i3/i3status.conf\".format(home_path),\n \"{}/i3status/config\".format(xdg_dirs_path),\n \"/etc/i3status.conf\",\n ]\n for fn in i3status_config_file_candidates:\n if os.path.isfile(fn):\n i3status_config_file_default = fn\n break\n else:\n # if files does not exists, defaults to ~/.i3/i3status.conf\n i3status_config_file_default = i3status_config_file_candidates[3]\n\n class Parser(argparse.ArgumentParser):\n # print usages and exit on errors\n def error(self, message):\n print(\"\\x1b[1;31merror: \\x1b[0m{}\".format(message))\n self.print_help()\n self.exit(1)\n\n # hide docstring on errors\n def _check_value(self, action, value):\n if action.choices is not None and value not in action.choices:\n raise argparse.ArgumentError(\n action, \"invalid choice: '{}'\".format(value)\n )\n\n class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):\n def _format_action_invocation(self, action):\n metavar = self._format_args(action, action.dest.upper())\n return \"{} {}\".format(\", \".join(action.option_strings), metavar)\n\n # command line options\n parser = Parser(\n description=\"The agile, python-powered, i3status wrapper\",\n formatter_class=HelpFormatter,\n )\n parser.add_argument(\n \"-b\",\n \"--dbus-notify\",\n action=\"store_true\",\n dest=\"dbus_notify\",\n help=\"send notifications via dbus instead of i3-nagbar\",\n )\n parser.add_argument(\n \"-c\",\n \"--config\",\n action=\"store\",\n default=i3status_config_file_default,\n dest=\"i3status_config_path\",\n help=\"load config\",\n metavar=\"FILE\",\n type=str,\n )\n parser.add_argument(\n \"-d\",\n \"--debug\",\n action=\"store_true\",\n help=\"enable debug logging in syslog and --log-file\",\n )\n parser.add_argument(\n \"-g\",\n \"--gevent\",\n action=\"store_true\",\n dest=\"gevent\",\n help=\"enable gevent monkey patching\",\n )\n parser.add_argument(\n \"-i\",\n \"--include\",\n action=\"append\",\n dest=\"include_paths\",\n help=\"append additional user-defined module paths\",\n metavar=\"PATH\",\n )\n parser.add_argument(\n \"-l\",\n \"--log-file\",\n action=\"store\",\n dest=\"log_file\",\n help=\"enable logging to FILE\",\n metavar=\"FILE\",\n type=str,\n )\n parser.add_argument(\n \"-s\",\n \"--standalone\",\n action=\"store_true\",\n dest=\"standalone\",\n help=\"run py3status without i3status\",\n )\n parser.add_argument(\n \"-t\",\n \"--timeout\",\n action=\"store\",\n default=60,\n dest=\"cache_timeout\",\n help=\"default module cache timeout in seconds\",\n metavar=\"INT\",\n type=int,\n )\n parser.add_argument(\n \"-m\",\n \"--disable-click-events\",\n action=\"store_true\",\n dest=\"disable_click_events\",\n help=\"disable all click events\",\n )\n parser.add_argument(\n \"-u\",\n \"--i3status\",\n action=\"store\",\n default=i3status_path,\n dest=\"i3status_path\",\n help=\"specify i3status path\",\n metavar=\"PATH\",\n type=str,\n )\n parser.add_argument(\n \"-v\",\n \"--version\",\n action=\"store_true\",\n dest=\"print_version\",\n help=\"show py3status version and exit\",\n )\n # deprecations\n parser.add_argument(\"-n\", \"--interval\", help=argparse.SUPPRESS)\n\n # make subparsers\n subparsers = parser.add_subparsers(dest=\"command\", metavar=\"{list}\")\n sps = {}\n\n # list subparser and its args\n sps[\"list\"] = subparsers.add_parser(\n \"list\",\n epilog=LIST_EPILOG,\n formatter_class=argparse.RawTextHelpFormatter,\n help=\"list modules\",\n )\n sps[\"list\"].add_argument(\n \"-f\", \"--full\", action=\"store_true\", help=\"show full (i.e. docstrings)\"\n )\n list_group = sps[\"list\"].add_mutually_exclusive_group()\n for name in [\"all\", \"core\", \"user\"]:\n list_group.add_argument(\n \"--%s\" % name, action=\"store_true\", help=\"show %s modules\" % name\n )\n\n # docstring subparser and its args\n sps[\"docstring\"] = subparsers.add_parser(\n \"docstring\",\n epilog=DOCSTRING_EPILOG,\n formatter_class=argparse.RawTextHelpFormatter,\n # help=\"docstring utility\",\n )\n docstring_group = sps[\"docstring\"].add_mutually_exclusive_group()\n for name in [\"check\", \"diff\", \"update\"]:\n docstring_group.add_argument(\n \"--%s\" % name, action=\"store_true\", help=\"%s docstrings\" % name\n )\n\n # modules not required\n for name in [\"list\", \"docstring\"]:\n sps[name].add_argument(nargs=\"*\", dest=\"module\", help=\"module name\")\n\n # parse options, command, etc\n options = parser.parse_args()\n\n # make versions\n options.python_version = python_version()\n options.version = version\n if options.print_version:\n msg = \"py3status version {version} (python {python_version})\"\n print(msg.format(**vars(options)))\n parser.exit()\n\n # make it i3status if None\n if not options.i3status_path:\n options.i3status_path = \"i3status\"\n\n # make include path to search for user modules if None\n if not options.include_paths:\n options.include_paths = [\n \"{}/.i3/py3status/\".format(home_path),\n \"{}/.config/i3/py3status/\".format(home_path),\n \"{}/i3status/py3status\".format(xdg_home_path),\n \"{}/i3/py3status\".format(xdg_home_path),\n ]\n\n # handle py3status list and docstring options\n if options.command:\n import py3status.docstrings as docstrings\n\n # init\n options.include_paths = options.include_paths or []\n config = vars(options)\n modules = [x.rsplit(\".py\", 1)[0] for x in config[\"module\"]]\n # list module names and details\n if config[\"command\"] == \"list\":\n tests = [not config[x] for x in [\"all\", \"user\", \"core\"]]\n if all([not modules] + tests):\n msg = \"missing positional or optional arguments\"\n sps[\"list\"].error(msg)\n docstrings.show_modules(config, modules)\n # docstring formatting and checking\n elif config[\"command\"] == \"docstring\":\n if config[\"check\"]:\n docstrings.check_docstrings(False, config, modules)\n elif config[\"diff\"]:\n docstrings.check_docstrings(True, config, None)\n elif config[\"update\"]:\n if not modules:\n msg = \"missing positional arguments or `modules`\"\n sps[\"docstring\"].error(msg)\n if \"modules\" in modules:\n docstrings.update_docstrings()\n else:\n docstrings.update_readme_for_modules(modules)\n else:\n msg = \"missing positional or optional arguments\"\n sps[\"docstring\"].error(msg)\n parser.exit()\n\n # defaults\n del options.command\n del options.interval\n del options.print_version\n options.minimum_interval = 0.1 # minimum module update interval\n options.click_events = not options.__dict__.pop(\"disable_click_events\")\n\n # all done\n return options\n","sub_path":"py3status/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":9272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"530258939","text":"from setuptools import setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name='wavinfo',\n version='1.3',\n author='Jamie Hardt',\n author_email='jamiehardt@me.com',\n description='Probe WAVE Files for iXML, Broadcast-WAVE and other metadata.',\n long_description_content_type=\"text/markdown\",\n long_description=long_description,\n url='https://github.com/iluvcapra/wavinfo',\n project_urls={\n 'Source':\n 'https://github.com/iluvcapra/wavinfo',\n 'Documentation':\n 'https://wavinfo.readthedocs.io/',\n 'Issues':\n 'https://github.com/iluvcapra/wavinfo/issues',\n },\n classifiers=['Development Status :: 5 - Production/Stable',\n 'License :: OSI Approved :: MIT License',\n 'Topic :: Multimedia',\n 'Topic :: Multimedia :: Sound/Audio',\n \"Programming Language :: Python :: 3.5\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\"],\n packages=['wavinfo'],\n keywords='waveform metadata audio ebu smpte avi library film tv editing editorial',\n install_requires=['lxml']\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"273458918","text":"import CoolProp.CoolProp as CP\nimport components\nfrom openpyxl import load_workbook\nimport math\nimport numpy as np\n\ninitial_conditions = 'input 100MW.xlsx'\n\ndef main():\n\tMCarray = np.empty([81, 9], dtype=np.float64)\n\n\tfor pd in range(0, 3):\n\t\tfor rt in range(0, 3):\n\t\t\tprint([pd, rt])\n\t\t\tfor di in range(0, 3):\n\t\t\t\tfor mv in range(0, 3):\n\t\t\t\t\tfor rxp in range(1, 151):\n\t\t\t\t\t\tdictionary = {}\n\t\t\t\t\t\tbalance_design_point(dictionary, pd, rt, di, mv, rxp, MCarray)\n\n\tnp.savetxt('mcarray.csv', MCarray, fmt='%.8f', delimiter=',', newline='\\n')\n\n\treturn 0\n\n#Design point calculations are currently not working properly, instead we are using time series at 900 for design point values. TODO: figure out how to make it work for less effort\ndef balance_design_point(dictionary, pd, rt, di, mv, rxp, MCarray):\n\twb = load_workbook(initial_conditions, data_only=True)\n\tws = wb['Sheet1'] # ws is now an IterableWorksheet\n\tfor x in ws.rows:\n\t dictionary[x[0].value] = x[4].value\n\n\tSR3_temps = [[],[],[],[],[]] # 0->inner wall, 1->interm inner wall, 2->interm outer wall, 3->outer wall, 4->ambient\n\tROx_temps = [[],[],[],[]] # 0->inner, 1->inner wall, 2->outer wall, 3-> ambient\n\tHS_temps = [[],[],[],[]] # 0->inner, 1->inner wall, 2->outer wall, 3-> ambient\n\tCS_temps = [[],[],[],[]] # 0->inner, 1->inner wall, 2->outer wall, 3-> ambient\n\n\tmol_abo3_max = dictionary['mol_abo3_max']\n\tsolar_multiple = dictionary['solar_multiple']\n\tdictionary['A_sf'] = dictionary['A_sf'] * solar_multiple\n\tcomponents.solve_delta(dictionary)\n\n\tdictionary['temp_6'] = dictionary['temp_6']\n\tdictionary['temp_12'] = dictionary['temp_12']\n\n\tdictionary['mol_abo3_12'] = mol_abo3_max * 0.5\n\tdictionary['mol_air_12'] = ((mol_abo3_max - dictionary['mol_abo3_12']) * dictionary['rho_abo3'] / dictionary['dens_abo3']) * (1.0 + dictionary['ullage']) * dictionary['p0air'] / (dictionary['temp_12']*dictionary['R'])\n\tcp_air_12 = CP.PropsSI('CPMOLAR', 'T', dictionary['temp_12'],'P', dictionary['p0air'], 'Air')\n\tdictionary['energy_12'] = dictionary['mol_abo3_12'] * dictionary['cp_abo3'] * (dictionary['temp_12']-dictionary['temp_0']) + dictionary['mol_air_12'] * cp_air_12 * (dictionary['temp_12']-dictionary['temp_0'])\n\tdictionary['energy_12'] = dictionary['energy_12'] / 3600.0\n\n\tdictionary['mol_abo3_6'] = mol_abo3_max * 0.5\n\tdictionary['mol_N_6'] = ((mol_abo3_max - dictionary['mol_abo3_6']) * dictionary['rho_abo3'] / dictionary['dens_abo3']) * (1.0 + dictionary['ullage']) * dictionary['p0air'] / (dictionary['temp_6']*dictionary['R'])\n\tcp_N_6 = CP.PropsSI('CPMOLAR', 'T', dictionary['temp_6'],'P', dictionary['p0air'], 'Nitrogen')\n\tdictionary['energy_6'] = dictionary['mol_abo3_6'] * dictionary['cp_abo3'] * (dictionary['temp_6']-dictionary['temp_0']) + dictionary['mol_N_6'] * cp_N_6 * (dictionary['temp_6']-dictionary['temp_0']) + dictionary['mol_abo3_6'] * 0.5 * dictionary['delta'] * dictionary['H_rxn']\n\tdictionary['energy_6'] = dictionary['energy_6'] / 3600.0\n\n\tdictionary['i'] = 0\n\tdictionary['temp_7'] = dictionary['temp_6']\n\tdictionary['temp_13'] = dictionary['temp_12']\n\n\tdni = 900.0\n\n\t# Solve power block\n\tcomponents.solve_power_block(dictionary)\n\n\tdictionary['part_pack_dens'] = 0.0003 + 0.0001*pd\n\tdictionary['time_res'] = 4 + 3*rt\n\tdictionary['particle_diameter'] = 0.0001 + 0.00003*di\n\tdictionary['rho_abo3'] = 0.0000276 + 0.0000069*mv\n\tdictionary['ROx_pipes'] = rxp\n\tdictionary['part_vel'] = 0.\n\tdictionary['air_vel'] = 0.\n\n\ttarget_rox_pipe_diameter = 2.8 #m\n\n\t# Step 3. Solve ROx\n\tcomponents.calibrate_ROx(dictionary)\n\tif rxp > 1:\n\t\tif math.fabs(dictionary['D_ROx'] - target_rox_pipe_diameter) < math.fabs(MCarray[27*pd + 9*rt + 3*di + mv, 6] - target_rox_pipe_diameter):\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 0] = dictionary['part_pack_dens']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 1] = dictionary['time_res']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 2] = dictionary['particle_diameter']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 3] = dictionary['rho_abo3']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 4] = dictionary['ROx_pipes']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 5] = dictionary['L_ROx']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 6] = dictionary['D_ROx']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 7] = dictionary['part_vel']\n\t\t\tMCarray[27*pd + 9*rt + 3*di + mv, 8] = dictionary['air_vel']\n\t\telse:\n\t\t\treturn 0\n\telse:\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 0] = dictionary['part_pack_dens']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 1] = dictionary['time_res']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 2] = dictionary['particle_diameter']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 3] = dictionary['rho_abo3']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 4] = dictionary['ROx_pipes']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 5] = dictionary['L_ROx']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 6] = dictionary['D_ROx']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 7] = dictionary['part_vel']\n\t\tMCarray[27*pd + 9*rt + 3*di + mv, 8] = dictionary['air_vel']\n\n\t# Step 2. Balance SR3 and HX\n\tmols_delta = 1.0\n\twhile mols_delta > 0.001:\n\t delta0 = dictionary['mol_abo3_1413']\n\t components.solve_SR3(dictionary, dni, SR3_temps)\n\t UA_HX, HX_eff = components.calibrate_HX(dictionary)\n\t delta1 = dictionary['mol_abo3_1413']\n\t mols_delta = math.fabs(delta0 - delta1)\n\n\t# Step 4. Solve HS + nitrogen blanket\n\tr_sb, A_hs, volume_hs = components.solve_HS(dictionary, mol_abo3_max, HS_temps)\n\n\t# Step 5. Solve CS\n\tcomponents.solve_cold_storage(dictionary, CS_temps)\n\n\t# Step 6. Solve lift\n\tcomponents.solve_work_lift(dictionary)\n\n\t# Step 7. Solve oxygen pump\n\tcomponents.vacuum_pump(dictionary)\n\n\t# print('SR3: Solar field area is', dictionary['A_sf'], 'm^2 at solar multiple of', solar_multiple)\n\t# print('SR3: The number of receivers is', dictionary['number_of_receivers'], '(rounded up) at the input concentration factor of', dictionary['concentration_factor'], 'MW/m^2')\n\t# print('HS/CS: If the max number of particle mols is', mol_abo3_max, ', the volume of the storage units are', volume_hs, 'm^3')\n\t# print('Storage: Expected number of moles for 1 hour capacity', dictionary['mol_abo3_710']*3600)\n\t# print('ROx: At particle T_high of', dictionary['temp_7']-273.15, 'C and particle T_low of', dictionary['temp_10']-273.15,'C one pipe has length and diameter of', dictionary['L_ROx'], dictionary['D_ROx'], 'm')\n\t# print('HX: At DNI', dni, 'and particle inlet temp', dictionary['temp_13']-273.15, 'C and effectiveness of', HX_eff, 'the UA value is', UA_HX)\n\t# print('')\n\t# print('System: SR3-ROx productivity ratio', 100.0*dictionary['mol_abo3_1413']/dictionary['mol_abo3_710'], '%')\n\t# print('')\n\n\treturn 0\n\nif __name__ == '__main__':\n\tmain()","sub_path":"montecarlo.py","file_name":"montecarlo.py","file_ext":"py","file_size_in_byte":6552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"264294953","text":"\"\"\"\nPlotting helper function for PLA/PSI NUDZ project.\n\"\"\"\n\nfrom collections import namedtuple\nfrom itertools import combinations\n\nimport matplotlib.pyplot as plt\nimport mne\nimport numpy as np\nfrom helpers import get_microstate_names\nfrom matplotlib.colorbar import ColorbarBase\nfrom matplotlib.patches import Rectangle\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nPoint = namedtuple(\"Point\", [\"x\", \"y\"], verbose=False)\nDPI = 300\n\n\ndef plot_microstate_maps(\n states,\n channel_file,\n xlabels=None,\n tit=None,\n fname=None,\n plot_minmax_vec=True,\n):\n \"\"\"\n Plots microstate maps.\n\n states - microstates (or similar) to plot\n channel_file - file with electrodes defintion\n xlabels - labels for maps (usually correlation)\n tit - suptitle for the plot\n fname - filename for the plot, if None show\n plot_minmax_vec - whether to plot vector between minimum and maximum\n \"\"\"\n\n pos = np.loadtxt(channel_file)[:, 1:]\n\n plt.figure(figsize=((np.ceil(states.shape[0] / 2.0)) * 5, 12))\n\n tits = [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\"]\n\n if xlabels is None:\n xlabels = [\"\" for i in range(states.shape[0])]\n\n for i, t, xlab in zip(range(states.shape[0]), tits, xlabels):\n plt.subplot(2, int(np.ceil(states.shape[0] / 2.0)), i + 1)\n mne.viz.plot_topomap(states[i, :], pos, show=False, contours=10)\n\n if plot_minmax_vec:\n max_sen = np.argmax(states[i, :])\n min_sen = np.argmin(states[i, :])\n pos_int, _ = mne.viz.topomap._check_outlines(pos, \"head\", None)\n plt.gca().plot(\n [pos_int[min_sen, 0], pos_int[max_sen, 0]],\n [pos_int[min_sen, 1], pos_int[max_sen, 1]],\n \"ko-\",\n markersize=7,\n lw=2.2,\n )\n plt.title(t, fontsize=25)\n plt.xlabel(xlab, fontsize=22)\n\n if tit is not None:\n plt.suptitle(tit, fontsize=30)\n\n if fname is None:\n plt.show()\n else:\n plt.savefig(fname, bbox_inches=\"tight\", dpi=DPI)\n plt.close()\n\n\ndef plot_timeseries_like(dataframe, stat, no_of_mstates, filename=None):\n \"\"\"\n Plots stat data per group - subject like time series\n\n dataframe - input dataframe\n stat - which microstate parameter to compute\n no_of_mstates - number of microstates\n filename - filename for the plot, if None show\n \"\"\"\n # MS names (alphabet)\n ms_names = get_microstate_names(no_of_mstates)\n plt.figure()\n plt.subplots_adjust(wspace=0.3, hspace=0.4)\n vmin, vmax = dataframe[stat].min(), dataframe[stat].max()\n groups = list(dataframe.groupby([\"group_cond\"]))\n for i, group in enumerate(groups):\n plt.subplot(2, 2, i + 1)\n for mstate in ms_names:\n data = group[1]\n data = data[data[\"MS\"] == mstate].reset_index()\n plt.plot(data[stat], \"o-\", label=mstate)\n plt.legend()\n plt.ylim([vmin * 0.95, vmax * 1.05])\n plt.xticks(\n np.arange(len(data[stat])), data[\"subject\"].values, rotation=30\n )\n plt.title(group[0])\n if i % 2 == 0:\n plt.ylabel(stat.upper())\n\n if filename is None:\n plt.show()\n else:\n plt.savefig(filename, bbox_inches=\"tight\", dpi=DPI)\n plt.close()\n\n\ndef plot_transition_rate_agg(dataframe, no_mstates, filename=None):\n \"\"\"\n Plot transition rates as a square plots\n\n dataframe - input dataframe\n no_mstates - number of microstates\n filename - filename for the plot, if None show\n \"\"\"\n plt.figure()\n plt.subplots_adjust(wspace=0.3, hspace=0.4)\n box_colors = ['#444444'] * no_mstates\n for subplt, (group, data) in enumerate(dataframe.groupby('group_cond')):\n ax = plt.subplot(2, 2, subplt + 1)\n plot_data = {transition: trans_data.mean()['transitions']\n for transition, trans_data in data.groupby('from_to')}\n ax = plot_single_transition_matrix(\n no_mstates, plot_data, colors=box_colors, axis=ax)\n ax.set_title(group.upper())\n\n if filename is None:\n plt.show()\n else:\n plt.savefig(filename, bbox_inches=\"tight\", dpi=DPI)\n plt.close()\n\n\ndef plot_boxplot_agg(dataframe, stat, filename=None):\n \"\"\"\n Plots stat data as a box plot\n\n dataframe - input dataframe\n stat - which microstate parameter to compute\n filename - filename for the plot, if None show\n \"\"\"\n plt.figure()\n plt.subplots_adjust(wspace=0.3, hspace=0.4)\n ax1 = plt.subplot(221)\n ms_mean = list(dataframe.groupby([\"MS\"])[stat])\n xlabels = [group[0] for group in ms_mean]\n data = [group[1] for group in ms_mean]\n plt.boxplot(data, showmeans=True, meanline=True, notch=True)\n plt.xticks(np.arange(1, len(xlabels) + 1), xlabels)\n plt.ylabel(stat.upper())\n plt.title(\"MICROSTATE\")\n\n plt.subplot(222, sharey=ax1)\n group_mean = list(dataframe.groupby([\"group_cond\"])[stat])\n xlabels = [group[0] for group in group_mean]\n data = [group[1] for group in group_mean]\n plt.boxplot(data, showmeans=True, meanline=True, notch=True)\n plt.xticks(np.arange(1, len(xlabels) + 1), xlabels)\n plt.title(\"GROUP\")\n\n groups = xlabels\n\n for i, gr in enumerate(groups):\n if i == 0:\n ax2 = plt.subplot(2, 4, i + 5)\n plt.ylabel(stat.upper())\n else:\n plt.subplot(2, 4, i + 5, sharey=ax2)\n df_temp = dataframe[dataframe[\"group_cond\"] == gr]\n interaction_mean = list(df_temp.groupby([\"MS\"])[stat])\n xlabels = [group[0] for group in interaction_mean]\n data = [group[1] for group in interaction_mean]\n plt.boxplot(data, showmeans=True, meanline=True, notch=True)\n plt.xticks(np.arange(1, len(xlabels) + 1), xlabels, size=10)\n plt.title(gr, size=12)\n\n if filename is None:\n plt.show()\n else:\n plt.savefig(filename, bbox_inches=\"tight\", dpi=DPI)\n plt.close()\n\n\ndef plot_permutation_test(test_result, perm_options, filename=None):\n \"\"\"\n Plot permutation test as histograms.\n\n test_result - result of the permutation test\n perm_options - options for permuting\n filename - filename for the plot, if None show\n \"\"\"\n plt.figure()\n for comb, col in enumerate(combinations(perm_options, 2)):\n plt.subplot(2, 6, col + 1)\n perms = test_result[comb[0] + \" x \" + comb[1] + \"-corr_sum\"][1]\n data = test_result[comb[0] + \" x \" + comb[1] + \"-corr_sum\"][0]\n plt.hist(perms, bins=21, color=\"#555555\", alpha=0.7)\n plt.axvline(data, 0, 1, color=\"k\", linewidth=1.4)\n plt.xticks(size=13)\n plt.yticks(size=13)\n plt.xlim([0.5, 1])\n pval = 1.0 - np.sum(np.less_equal(data, perms)) / float(perms.shape[0])\n # pval = 2 * np.minimum(pval, 1. - pval)\n plt.title(\"%s x %s \\n %.4f\" % (comb[0], comb[1], pval), size=14)\n if col == 0:\n plt.ylabel(\"mean correlation\")\n\n plt.subplot(2, 6, 6 + col + 1)\n perms = test_result[comb[0] + \" x \" + comb[1] + \"-avg_gmd\"][1]\n data = test_result[comb[0] + \" x \" + comb[1] + \"-avg_gmd\"][0]\n plt.hist(perms, bins=21, color=\"#555555\", alpha=0.7)\n plt.xticks(size=13)\n plt.yticks(size=13)\n plt.xlim([0.2, 1.6])\n plt.axvline(data, 0, 1, color=\"k\", linewidth=1.4)\n pval = 1.0 - np.sum(np.greater_equal(data, perms)) / float(\n perms.shape[0]\n )\n # pval = 2 * np.minimum(pval, 1. - pval)\n plt.title(\"%s x %s \\n %.4f\" % (comb[0], comb[1], pval), size=14)\n if col == 0:\n plt.ylabel(\"mean global map diss.\")\n\n if filename is None:\n plt.show()\n else:\n plt.savefig(filename, bbox_inches=\"tight\", dpi=DPI)\n plt.close()\n\n\ndef plot_single_transition_matrix(no_of_mstates, significant, colors,\n axis=plt.gca(), cmap='gist_heat_r'):\n \"\"\"\n Plot single schematic transition matrix plot.\n\n no_of_mstates - number of microstates\n significant - significant interactions: list of pairs e.g. \"A->B\"\n when list passed, will plot only significant\n when dict with values, will plot based on that plus colorbar\n colors - colors to use for the rectangles\n axis - axis on which to plot\n cmap - colormap when plotting values\n \"\"\"\n assert no_of_mstates <= 4, 'Maximum 4 microstates currently supported'\n # MS names (alphabet)\n squares = get_microstate_names(no_of_mstates)\n assert len(colors) == len(\n squares\n ), \"Number of colors does not match number of microstates\"\n\n # set constants\n SQUARE_SIZE = 0.66\n LINE_START = 0.25\n SQUARE_COORDS = {\n \"A\": (-1.0, 0.33),\n \"B\": (0.33, 0.33),\n \"C\": (-1.0, -1.0),\n \"D\": (0.33, -1.0),\n }\n LINE_COORDS = {\n \"A-B\": [\n Point(-LINE_START, SQUARE_SIZE),\n Point(LINE_START, SQUARE_SIZE),\n ],\n \"A-C\": [\n Point(-SQUARE_SIZE, LINE_START),\n Point(-SQUARE_SIZE, -LINE_START),\n ],\n \"A-D\": [Point(-LINE_START, LINE_START), Point(LINE_START, -LINE_START)],\n \"B-C\": [Point(LINE_START, LINE_START), Point(-LINE_START, -LINE_START)],\n \"B-D\": [\n Point(SQUARE_SIZE, LINE_START),\n Point(SQUARE_SIZE, -LINE_START),\n ],\n \"C-D\": [\n Point(-LINE_START, -SQUARE_SIZE),\n Point(LINE_START, -SQUARE_SIZE),\n ],\n }\n LETTER_COORDS = {\n \"A\": (-SQUARE_SIZE, SQUARE_SIZE),\n \"B\": (SQUARE_SIZE, SQUARE_SIZE),\n \"C\": (-SQUARE_SIZE, -SQUARE_SIZE),\n \"D\": (SQUARE_SIZE, -SQUARE_SIZE)\n }\n\n # set figure\n axis.set_xlim([-1.0, 1.0])\n axis.set_ylim([-1.0, 1.0])\n axis.set_aspect(aspect=\"equal\")\n axis.set_xticks([], [])\n axis.set_yticks([], [])\n\n # do squares\n for square, color in zip(squares, colors):\n patch = Rectangle(SQUARE_COORDS[square], SQUARE_SIZE, SQUARE_SIZE,\n linewidth=1, edgecolor=\"k\", facecolor=color,\n alpha=0.5)\n axis.add_patch(patch)\n axis.text(LETTER_COORDS[square][0], LETTER_COORDS[square][1], square,\n horizontalalignment=\"center\", verticalalignment=\"center\",\n fontdict={\"size\": 25})\n\n # do schematic lines\n for sq_i, sq_j in combinations(squares, 2):\n line_coords = LINE_COORDS[\"%s-%s\" % (sq_i, sq_j)]\n axis.plot([line_coords[0].x, line_coords[1].x],\n [line_coords[0].y, line_coords[1].y], \"--\", linewidth=0.8,\n color='gray')\n\n # do significance lines\n colormap = plt.get_cmap(cmap)\n if isinstance(significant, list):\n significant = {sign_pair: '#222222' for sign_pair in significant}\n plot_colorbar = False\n elif isinstance(significant, dict):\n significant = {sign_pair: colormap(value) for sign_pair, value in\n significant.iteritems()}\n plot_colorbar = True\n else:\n raise ValueError('not supported')\n\n for sign_pair, color in significant.iteritems():\n # try first order\n try:\n first, second = LINE_COORDS[sign_pair.replace(\">\", \"\")]\n # if not then just rotate letters\n except KeyError:\n first, second = sign_pair.split(\"->\")\n second, first = LINE_COORDS[\"%s-%s\" % (second, first)]\n axis.arrow(first.x, first.y, second.x - first.x, second.y - first.y,\n length_includes_head=True, width=0.25, color=color,\n alpha=0.9, head_length=0.2, head_width=0.5, shape='left')\n\n if plot_colorbar:\n divider = make_axes_locatable(axis)\n cax = divider.append_axes('bottom', size='5%', pad=0.05)\n ColorbarBase(cax, cmap=colormap, orientation='horizontal')\n\n return axis\n","sub_path":"plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":11807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"125868171","text":"# Python module external to Maya\n\nimport socket\nimport serial\n\nARDUINO = \"/dev/tty.usbmodem141201\"\nport_id = 7777\nhost_adress = \"127.0.0.1\"\n\ndef main():\n maya = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n maya.connect((host_adress, port_id))\n ser = serial.Serial(ARDUINO, timeout=1)\n prevVal = None\n\n while 1:\n # Read the serial value\n ser.flushInput()\n\n serialValue = ser.readline().strip()\n\n # Catch any bad serial data:\n try:\n if serialValue != prevVal:\n # Print the value if it differs from the prevVal:\n maya.send(str(serialValue))\n prevVal = serialValue\n except ValueError:\n pass\n\nif __name__ == '__main__':\n main()\n","sub_path":"arduinoToMaya.py","file_name":"arduinoToMaya.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"267803575","text":"def binarySearch(a_list,item):\n if len(a_list) == 0:\n return -1\n else:\n mid = len(a_list)//2\n if a_list[mid] == item:\n return mid\n elif item < a_list[mid]:\n index = binarySearch(a_list[:mid],item)\n return index\n elif item> a_list[mid]:\n index = binarySearch(a_list[mid+1:],item)\n return index+mid+1\n\nmylist=[8,12,22,27,38]\nprint(binarySearch(mylist,22))\n","sub_path":"lab12/example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"240694497","text":"#!/usr/bin/python3\nimport codecs\n\n#constants\nMAX_DATA_SIZE = 32768\nMAX_PACKET_SIZE = MAX_DATA_SIZE + 7\nDATA = 0x0\nACK = 0x1\nFIN = 0x2\nFIN_ACK = 0x3\n\n\n\n#split num into one byte chunks and turn it into ascii character\n#num is an integer\n#zero padding is and integer annotating the number of zero to pad in to the result\ndef int_to_ascii(num, zero_padding=0): #this method contains some weird bug\n\t\n\t#get hex value from num\n\tnum = str(hex(num))[2:].zfill(zero_padding)\n\t\n\tresult = ''\n\tfor i in range(0,len(num), 2):\n\t\tresult += chr(int(num[i:i+2], 16))\n\n\n\treturn result\n\n#this method is just like int_to_ascii, but returns bytes instead of string\n#i hope there is no more weird bug\ndef imp_int_to_ascii(num, zero_padding=2):\n\tdecode_hex = codecs.getdecoder(\"hex_codec\")\n\tnum = str(hex(num))[2:].zfill(zero_padding)\n\n\tresult = decode_hex(num)[0]\n\treturn result\n\n\n\n#this method return int value for a string\ndef ascii_to_int(stream):\n\tresult = 0\n\tfor i in stream:\n\t\tresult = result*16 + ord(i)\n\n\treturn result\n\n#validate a packet by comparing its checksum\n#packet is an encoded string\n#returns True if packet is valid and False if not valid\ndef is_valid(packet):\n\tgiven_checksum = int(packet.hex()[10:14], 16) #get given checksum\n\tpurged_packet = packet[:5] + packet[7:] #exlude the checksum from the packet\n\t\n\t#count the new checksum\n\tnew_checksum = 0x0\n\tfor i in range(0, len(purged_packet), 2):\n\t\tchunks = int(purged_packet[i]/16) * (16**3) + (purged_packet[i]%16) * (16**2) \n\n\t\tif (i+1 < len(purged_packet)):\n\t\t\tchunks += int(purged_packet[i+1]/16) * (16**1) + (purged_packet[i+1]%16) * (16**0)\n\n\t\tnew_checksum ^= chunks\n\n\treturn new_checksum == given_checksum\n\n\n\n\n#build method\n#build a packet from TYPE, ID, SEQUENCE_NUMBER, and DATA\n#TYPE is an integer, as long as ID and SEQUENCE_NUMBER\n#DATA is a string\n#this method return an encoded string which is the packet\ndef build_packet(TYPE, ID, SEQUENCE_NUMBER, DATA=None):\n\t\n\t#set the first byte, consist of TYPE and ID\n\tfirst_byte = (TYPE << 4) + ID\n\n\t#set packet LENGTH\n\tLENGTH = 7\n\tif (DATA != None):\n\t\tLENGTH += len(DATA)\n\n\ttemp = imp_int_to_ascii(first_byte) + imp_int_to_ascii(SEQUENCE_NUMBER, 4) + imp_int_to_ascii(LENGTH, 4)\n\tif (DATA != None):\n\t\ttemp += DATA\n\t\t# temp += DATA.encode()\n\n\tchecksum = 0x0\n\n\tfor i in range(0, len(temp), 2):\n\t\tchunks = int(temp[i]/16) * (16**3) + (temp[i]%16) * (16**2) \n\n\t\tif (i+1 < len(temp)):\n\t\t\tchunks += int(temp[i+1]/16) * (16**1) + (temp[i+1]%16) * (16**0)\n\n\t\tchecksum ^= chunks\t\n\n\t#compose the packet\n\t\n\tresult = imp_int_to_ascii(first_byte) + imp_int_to_ascii(SEQUENCE_NUMBER, 4) + imp_int_to_ascii(LENGTH, 4) + imp_int_to_ascii(checksum, 4)\n\n\tif (DATA != None):\n\t\t# result += DATA.encode()\n\t\tresult += DATA\n\treturn result\n\n\n\n\n#extract data from a packet, packet is assumed to be valid\n#packet is an encoded string\n#this method return TYPE, ID, SEQUENCE_NUMBER and DATA\ndef extract_packet(packet):\n\n\tpacket = packet.hex()\n\n\t#set value for TYPE, ID and DATA\n\tTYPE = int(packet[0],16)\n\tID = int(packet[1],16)\n\tSEQUENCE_NUMBER = int(packet[2:6],16)\n\tDATA = None\n\n\n\tif(TYPE != ACK and TYPE != FIN_ACK):\n\t\tDATA = packet[14:]\n\n\treturn TYPE, ID, SEQUENCE_NUMBER, DATA\n\n","sub_path":"src/packethandler.py","file_name":"packethandler.py","file_ext":"py","file_size_in_byte":3158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"414827691","text":"from grabbit import Layout, Entity, File\nimport os\nimport grabbids\nimport re\n\n__all__ = ['BIDSLayout']\n\n\nclass BIDSLayout(Layout):\n\n def __init__(self, path, config=None):\n if config is None:\n root = os.path.dirname(grabbids.__file__)\n config = os.path.join(root, 'config', 'bids.json')\n super(BIDSLayout, self).__init__(path, config)\n\n def find_match(self, target, source=None):\n\n # Try to take the easy way out\n if source is not None:\n _target = source.split('.')[0] + '.' + target\n if os.path.exists(_target):\n return target\n\n if target in list(self.entities.keys()):\n candidates = list(self.entities[target].files.keys())\n else:\n candidates = []\n\n for root, directories, filenames in os.walk(self.root):\n for f in filenames:\n if re.search(target + '$', f):\n candidates.append(f)\n\n if source is None:\n return candidates\n\n # Walk up the file hierarchy from source, find first match\n if not os.path.exists(source):\n raise OSError(\"The file '%s' doesn't exist.\" % source)\n elif not source.startswith(self.root):\n raise ValueError(\"The file '%s' is not contained within the \"\n \"current project directory (%s).\" % (source, self.root))\n rel = os.path.relpath(os.path.dirname(source), self.root)\n sep = os.path.sep\n chunks = rel.split(sep)\n n_chunks = len(chunks)\n for i in range(n_chunks, -1, -1):\n path = os.path.join(self.root, *chunks[:i])\n patt = path + '\\%s[^\\%s]+$' % (sep, sep)\n matches = [x for x in candidates if re.search(patt, x)]\n if matches:\n if len(matches) == 1:\n return matches[0]\n else:\n raise ValueError(\"Ambiguous target: more than one candidate \"\n \"file found in directory '%s'.\" % path)\n return None\n","sub_path":"grabbids/bids.py","file_name":"bids.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"534695189","text":"import cv2\r\nimport matplotlib.pyplot as plt\r\n\r\n##read image\r\nimg = cv2.imread('D:\\Ashish\\Projects\\OpenCv\\FirstTrial\\sample_images\\einstein.png' , 1)\r\n\r\nimg1 = cv2.cvtColor(img , cv2.COLOR_BGR2RGB)\r\n\r\nplt.imshow(img1 , cmap='gray')\r\nplt.title('Gray Colormap')\r\nplt.xticks([]) ## Removes x axis numbers from image\r\nplt.yticks([]) ## Removes y axis numbers from image\r\nplt.show()\r\n\r\nplt.imshow(img1)\r\nplt.title('image with RGB')\r\nplt.show()\r\n\r\nplt.imshow(img1 , cmap='Blues')\r\nplt.title('Blue colormap')\r\nplt.show()","sub_path":"cv_with_matplotlib.py","file_name":"cv_with_matplotlib.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"326350333","text":"import os\r\n\r\ndef walker():\r\n for root, dirs, files in os.walk('C:/Users/Public'):\r\n print(files)\r\n\r\ndef takeAlpha():\r\n alphaGruz = {}\r\n alpha = open('alphabet_gruz.txt', 'r', encoding = 'utf-8')\r\n for stroka in alpha:\r\n stroka = stroka.split()\r\n alphaGruz[stroka[0]] = stroka[1]\r\n alpha.close()\r\n return alphaGruz\r\n\r\ndef readText():\r\n f = open('gruz_text1.txt', 'r', encoding = 'utf-8')\r\n text = f.read()\r\n letterList = list(text)\r\n f.close()\r\n return letterList\r\n\r\ndef convertToIPA():\r\n f = open('gruz_text_IPA.txt', 'w', encoding = 'utf-8')\r\n letterList = readText()\r\n ipa = takeAlpha()\r\n for letter in letterList:\r\n if letter in ipa:\r\n letter = ipa[letter]\r\n f.write(letter)\r\n f.close()\r\n \r\n\r\nif __name__ == '__main__':\r\n convertToIPA()\r\n \r\n \r\n","sub_path":"12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"162753774","text":"import numpy as np\nimport random\nimport time\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nfrom matplotlib.ticker import LinearLocator, FormatStrFormatter\n\n\"\"\" A basic evolutionary algorithm. \"\"\"\nclass eggholderEA:\n\n \"\"\" Initialize the evolutionary algorithm solver. \"\"\"\n def __init__(self, fun):\n self.alpha = 0.05 \t\t# Mutation probability\n self.lambdaa = 100 \t\t# Population size\n self.mu = self.lambdaa * 2\t# Offspring size\n self.k = 3 \t\t# Tournament selection\n self.intMax = 500 \t\t# Boundary of the domain, not intended to be changed.\n self.numIters = 20\t\t# Maximum number of iterations\n self.objf = fun\n\n \"\"\" The main evolutionary algorithm loop. \"\"\"\n def optimize( self, plotFun = lambda x : None):\n # Initialize population\n population = self.intMax * np.random.rand(self.lambdaa, 2)\n\n plotFun((population, self.intMax))\n for i in range(self.numIters):\n # The evolutionary algorithm\n start = time.time()\n selected = self.selection(population, self.k)\n offspring = self.crossover(selected)\n joinedPopulation = np.vstack((self.mutation(offspring, self.alpha), population))\n population = self.elimination(joinedPopulation, self.lambdaa)\n itT = time.time() - start\n\n # Show progress\n fvals = self.objf(population)\n meanObj = np.mean(fvals)\n bestObj = np.min(fvals)\n print(f'{itT: .2f}s:\\t Mean fitness = {meanObj: .5f} \\t Best fitness = {bestObj: .5f}')\n plotFun((population, self.intMax))\n\n print('Done')\n\n \"\"\" Perform k-tournament selection to select pairs of parents. \"\"\"\n def selection(self, population, k):\n selected = np.zeros((self.mu, 2))\n for ii in range( self.mu ):\n ri = random.choices(range(np.size(population,0)), k = self.k)\n min = np.argmin( self.objf(population[ri, :]) )\n selected[ii,:] = population[ri[min],:]\n\n return selected\n\n \"\"\" Perform box crossover as in the slides. \"\"\"\n def crossover(self, selected):\n weights = 3*np.random.rand(self.lambdaa,2) - 1\n offspring = np.zeros((self.lambdaa, 2))\n lc = lambda x, y, w: np.clip(x + w * (y-x), 0, self.intMax)\n for ii, _ in enumerate(offspring):\n offspring[ii,:] = lc(selected[2*ii, :], selected[2*ii+1, :], weights[ii, :])\n return offspring\n\n \"\"\" Perform mutation, adding a random Gaussian perturbation. \"\"\"\n def mutation(self, offspring, alpha):\n ii = np.where(np.random.rand(np.size(offspring,0)) <= alpha)\n offspring[ii,:] = offspring[ii,:] + 10*np.random.randn(np.size(ii),2)\n offspring[ii,:] = np.clip(offspring[ii,:], 0, self.intMax)\n return offspring\n\n \"\"\" Eliminate the unfit candidate solutions. \"\"\"\n def elimination(self, joinedPopulation, keep):\n fvals = self.objf(joinedPopulation)\n perm = np.argsort(fvals)\n survivors = joinedPopulation[perm[1:keep],:]\n return survivors\n\n\n\"\"\" Compute the objective function at the vector of (x,y) values. \"\"\"\ndef myfun(x):\n if np.size(x) == 2:\n x = reshape(x, (1,2))\n\n sas = np.sqrt(np.abs(x[:,0]+x[:,1]))\n sad = np.sqrt(np.abs(x[:,0]-x[:,1]))\n f = -x[:,1] * np.sin(sas) - x[:,0] * np.sin(sad)\n return f\n\n\"\"\"\nMake a 3D visualization of the optimization landscape and the location of the\ngiven candidate solutions (x,y) pairs in input[0].\n\"\"\"\ndef plotPopulation3D(input):\n population = input[0]\n\n x = np.arange(0,input[1],0.5)\n y = np.arange(0,input[1],0.5)\n X, Y = np.meshgrid(x, y)\n Z = myfun(np.transpose(np.vstack((X.flatten('F'),Y.flatten('F')))))\n Z = np.reshape(Z, (np.size(x), np.size(y)))\n\n fig = plt.gcf()\n fig.clear()\n ax = fig.gca(projection='3d')\n ax.scatter(population[:,0], population[:,1], myfun(population)+1*np.ones(population.shape[0]), c='r', marker='o')\n ax.plot_surface(X, Y, Z, cmap=cm.coolwarm, linewidth=1, antialiased=False, alpha=0.2)\n plt.pause(0.05)\n\n\"\"\"\nMake a 2D visualization of the optimization landscape and the location of the\ngiven candidate solutions (x,y) pairs in input[0].\n\"\"\"\ndef plotPopulation2D(input):\n population = input[0]\n\n x = np.arange(0,input[1],1)\n y = np.arange(0,input[1],1)\n X, Y = np.meshgrid(x, y)\n Z = myfun(np.transpose(np.vstack((X.flatten('F'),Y.flatten('F')))))\n Z = np.reshape(Z, (np.size(x), np.size(y)))\n\n # Determine location of minimum\n rowMin = np.min(Z, axis=0)\n minj = np.argmin(rowMin)\n colMin = np.min(Z, axis=1)\n mini = np.argmin(colMin)\n\n fig = plt.gcf()\n fig.clear()\n ax = fig.gca()\n ax.imshow(Z.T)\n ax.scatter(population[:,0], population[:,1], marker='o', color='r')\n ax.scatter(mini, minj, marker='*', color='yellow')\n plt.pause(0.05)\n\n\neggEA = eggholderEA(myfun)\neggEA.optimize(plotPopulation2D)\nplt.show()\n","sub_path":"EA_HOPS2_diversity_and_multiobjective_optimization/eggholderEA.py","file_name":"eggholderEA.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588609994","text":"import pandas as pd\nimport requests\nimport pickle\nfrom bs4 import BeautifulSoup\nfrom time import time\n\n\n# Get the movie details\nmovies = pd.read_excel('./movies_list.xlsx').to_dict('records')\n\n\n# Start a requests session\ns = requests.Session()\n\n\n# Iterate over the movies\nt0 = time()\nfinal_result = []\nfor m in movies:\n # Get the movie url from the rotten tomatoes api\n r = s.get('https://www.rottentomatoes.com/api/private/v2.0/search', params={'q': m['movie_name']})\n search_result = r.json()['movies']\n url = [i['url'] for i in search_result if i['name'] == m['movie_name'] and i['year'] == m['year']][0]\n\n # Get the number of pages of reviews\n url_reviews = 'https://www.rottentomatoes.com' + url + '/reviews'\n r = s.get(url_reviews, params={'type': 'user', 'page': 1})\n r.encoding = 'utf-8'\n soup = BeautifulSoup(r.text, 'lxml')\n pages = int(soup.select_one('.pageInfo').text[10:])\n\n # Iterate through the reviews pages\n reviews = []\n for p in range(min(20, pages)):\n r = s.get(url_reviews, params={'type': 'user', 'page': p})\n r.encoding = 'utf-8'\n tags = BeautifulSoup(r.text, 'lxml').select('.col-xs-16')\n for t in tags:\n rating = t.find('div', attrs={'class': 'scoreWrapper'}).span['class']\n review = t.find('div', attrs={'class': 'user_review'}).text\n reviews.append({'rating': rating, 'review': review})\n\n # Storing the results\n movie_result = {'reviews': reviews}\n movie_result.update(m)\n final_result.append(movie_result)\n print('{0} is done. Time taken so far is {1} mins.'.format(m['movie_name'], round((time() - t0) / 60, 1)))\n\n\n# Deleting all reviews which don't have a rating and converting to a 5 point scale\nfor m in final_result:\n m['reviews'] = [{'review': r['review'], 'rating': int(r['rating'][0]) / 10}\n for r in m['reviews'] if r['rating'][0].isnumeric()]\n\n\n# Exporting the results\nwith open('movie_reviews.pickle', 'wb') as f:\n pickle.dump(final_result, f)\n","sub_path":"rotten_tomatoes_reviews_scraper.py","file_name":"rotten_tomatoes_reviews_scraper.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"288915687","text":"import smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom model.CustomerRequest import CustomerRequest\nfrom string import Template \n\nEMAIL_ADDRESS = \"YOUR_EMAIL\"\nEMAIL_PASSWORD = \"YOUR_PASSWORD\"\n\nTITLE_TEMPLATE_FILE = \"TITLE_TEMPLATE.txt\"\nBODY_TEMPLATE_FILE = \"BODY_TEMPLATE.html\"\nMESSAGE_SIGNATURE = \"YOUR_SIGNATURE_FILE.PNG\"\n\ndef setup_smtp_server():\n print(\"Connecting to SMTP server as : %s\" % (EMAIL_ADDRESS))\n smtp = smtplib.SMTP(host=\"smtp-mail.outlook.com\", port=\"587\")\n smtp.starttls()\n smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)\n return smtp\n\ndef read_template(filename):\n with open(filename, 'r', encoding='UTF-8') as template_file:\n content = template_file.read()\n return(Template(content))\n\ndef prepare_email(from_address, customer, title_template, body_template):\n msg = MIMEMultipart()\n msg['From'] = from_address\n msg['To'] = customer.email\n manga_str = \", \".join(customer.orders)\n title_content = title_template.substitute(MANGA=manga_str)\n msg['Subject'] = title_content\n message_body = body_template.substitute(CUSTOMER_NAME=customer.name)\n msg.attach(MIMEText(message_body,'html'))\n \n img = MIMEImage(open(MESSAGE_SIGNATURE,'rb').read(),'png')\n img.add_header('Content-ID', '')\n img.add_header('Content-Disposition','inline',filename=\"otaku_signature.png\")\n msg.attach(img)\n return msg\n\n\ndef send_emails(customers):\n smtp = setup_smtp_server()\n title_template = read_template(TITLE_TEMPLATE_FILE)\n body_template = read_template(BODY_TEMPLATE_FILE)\n for customer in customers:\n msg = prepare_email(EMAIL_ADDRESS,customer , title_template, body_template)\n smtp.send_message(msg)\n del msg\n smtp.quit() \n print(\"Emails sent ...\")\n\n ","sub_path":"csv_sender/helpers/emailUtils.py","file_name":"emailUtils.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"614168045","text":"import json\nimport math\nfrom tornado.web import RequestHandler\nimport motor.motor_tornado\nimport geopy.distance\nimport datetime\nfrom pending import confirm_pending_visitor\n\nclient = motor.motor_tornado.MotorClient()\ndb = client['otpmap']\ncollection = db['withdrawal_codes']\n\nclass WithdrawalQRCodeService(RequestHandler): \n def set_default_headers(self):\n # For prototyping\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')\n \n async def get(self, uuid):\n amount = int(self.get_argument(\"amount\", 0, True))\n atm_id = self.get_argument(\"atm_id\", 0, True)\n\n await clear_pending_withdrawal_codes(uuid)\n\n data = await generate_withdrawal_code(uuid, atm_id, amount)\n self.write(json.dumps({'type': 'qrcode', 'data': data}))\n\n await confirm_pending_visitor(uuid, atm_id)\n\nasync def clear_pending_withdrawal_codes(uuid):\n collection.delete_many({\"uuid\": uuid})\n\nasync def generate_withdrawal_code(uuid, atm_id, amount):\n qr_code = {'uuid': uuid, 'amount': amount, 'atm_id': atm_id}\n result = await collection.insert_one(qr_code)\n qr_code['_id'] = str(result.inserted_id)\n return qr_code\n","sub_path":"qr.py","file_name":"qr.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"311761731","text":"\"\"\"Intents for the Shopping List integration.\"\"\"\nfrom openpeerpower.helpers import intent\nimport openpeerpower.helpers.config_validation as cv\n\nfrom . import DOMAIN, EVENT\n\nINTENT_ADD_ITEM = \"OppShoppingListAddItem\"\nINTENT_LAST_ITEMS = \"OppShoppingListLastItems\"\n\n\nasync def async_setup_intents(opp):\n \"\"\"Set up the Shopping List intents.\"\"\"\n intent.async_register(opp, AddItemIntent())\n intent.async_register(opp, ListTopItemsIntent())\n\n\nclass AddItemIntent(intent.IntentHandler):\n \"\"\"Handle AddItem intents.\"\"\"\n\n intent_type = INTENT_ADD_ITEM\n slot_schema = {\"item\": cv.string}\n\n async def async_handle(self, intent_obj):\n \"\"\"Handle the intent.\"\"\"\n slots = self.async_validate_slots(intent_obj.slots)\n item = slots[\"item\"][\"value\"]\n await intent_obj.opp.data[DOMAIN].async_add(item)\n\n response = intent_obj.create_response()\n response.async_set_speech(f\"I've added {item} to your shopping list\")\n intent_obj.opp.bus.async_fire(EVENT)\n return response\n\n\nclass ListTopItemsIntent(intent.IntentHandler):\n \"\"\"Handle AddItem intents.\"\"\"\n\n intent_type = INTENT_LAST_ITEMS\n slot_schema = {\"item\": cv.string}\n\n async def async_handle(self, intent_obj):\n \"\"\"Handle the intent.\"\"\"\n items = intent_obj.opp.data[DOMAIN].items[-5:]\n response = intent_obj.create_response()\n\n if not items:\n response.async_set_speech(\"There are no items on your shopping list\")\n else:\n response.async_set_speech(\n \"These are the top {} items on your shopping list: {}\".format(\n min(len(items), 5),\n \", \".join(itm[\"name\"] for itm in reversed(items)),\n )\n )\n return response\n","sub_path":"openpeerpower/components/shopping_list/intent.py","file_name":"intent.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"235613992","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom .response import Response\n\n\nclass ImageInsights(Response):\n \"\"\"The top-level object that the response includes when an image insights\n request succeeds. For information about requesting image insights, see the\n [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken)\n query parameter. The modules query parameter affects the fields that Bing\n includes in the response. If you set\n [modules](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#modulesrequested)\n to only Caption, then this object includes only the imageCaption field.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :param _type: Constant filled by server.\n :type _type: str\n :ivar id: A String identifier.\n :vartype id: str\n :ivar read_link: The URL that returns this resource.\n :vartype read_link: str\n :ivar web_search_url: The URL To Bing's search result for this item.\n :vartype web_search_url: str\n :ivar image_insights_token: A token that you use in a subsequent call to\n the Image Search API to get more information about the image. For\n information about using this token, see the insightsToken query parameter.\n This token has the same usage as the token in the Image object.\n :vartype image_insights_token: str\n :ivar best_representative_query: The query term that best represents the\n image. Clicking the link in the Query object, takes the user to a webpage\n with more pictures of the image.\n :vartype best_representative_query:\n ~azure.cognitiveservices.search.imagesearch.models.Query\n :ivar image_caption: The caption to use for the image.\n :vartype image_caption:\n ~azure.cognitiveservices.search.imagesearch.models.ImageInsightsImageCaption\n :ivar related_collections: A list of links to webpages that contain\n related images.\n :vartype related_collections:\n ~azure.cognitiveservices.search.imagesearch.models.RelatedCollectionsModule\n :ivar pages_including: A list of webpages that contain the image. To\n access the webpage, use the URL in the image's hostPageUrl field.\n :vartype pages_including:\n ~azure.cognitiveservices.search.imagesearch.models.ImagesModule\n :ivar shopping_sources: A list of merchants that offer items related to\n the image. For example, if the image is of an apple pie, the list contains\n merchants that are selling apple pies.\n :vartype shopping_sources:\n ~azure.cognitiveservices.search.imagesearch.models.AggregateOffer\n :ivar related_searches: A list of related queries made by others.\n :vartype related_searches:\n ~azure.cognitiveservices.search.imagesearch.models.RelatedSearchesModule\n :ivar recipes: A list of recipes related to the image. For example, if the\n image is of an apple pie, the list contains recipes for making an apple\n pie.\n :vartype recipes:\n ~azure.cognitiveservices.search.imagesearch.models.RecipesModule\n :ivar visually_similar_images: A list of images that are visually similar\n to the original image. For example, if the specified image is of a sunset\n over a body of water, the list of similar images are of a sunset over a\n body of water. If the specified image is of a person, similar images might\n be of the same person or they might be of persons dressed similarly or in\n a similar setting. The criteria for similarity continues to evolve.\n :vartype visually_similar_images:\n ~azure.cognitiveservices.search.imagesearch.models.ImagesModule\n :ivar visually_similar_products: A list of images that contain products\n that are visually similar to products found in the original image. For\n example, if the specified image contains a dress, the list of similar\n images contain a dress. The image provides summary information about\n offers that Bing found online for the product.\n :vartype visually_similar_products:\n ~azure.cognitiveservices.search.imagesearch.models.ImagesModule\n :ivar recognized_entity_groups: A list of groups that contain images of\n entities that match the entity found in the specified image. For example,\n the response might include images from the general celebrity group if the\n entity was recognized in that group.\n :vartype recognized_entity_groups:\n ~azure.cognitiveservices.search.imagesearch.models.RecognizedEntitiesModule\n :ivar image_tags: A list of characteristics of the content found in the\n image. For example, if the image is of a person, the tags might indicate\n the person's gender and the type of clothes they're wearing.\n :vartype image_tags:\n ~azure.cognitiveservices.search.imagesearch.models.ImageTagsModule\n \"\"\"\n\n _validation = {\n '_type': {'required': True},\n 'id': {'readonly': True},\n 'read_link': {'readonly': True},\n 'web_search_url': {'readonly': True},\n 'image_insights_token': {'readonly': True},\n 'best_representative_query': {'readonly': True},\n 'image_caption': {'readonly': True},\n 'related_collections': {'readonly': True},\n 'pages_including': {'readonly': True},\n 'shopping_sources': {'readonly': True},\n 'related_searches': {'readonly': True},\n 'recipes': {'readonly': True},\n 'visually_similar_images': {'readonly': True},\n 'visually_similar_products': {'readonly': True},\n 'recognized_entity_groups': {'readonly': True},\n 'image_tags': {'readonly': True},\n }\n\n _attribute_map = {\n '_type': {'key': '_type', 'type': 'str'},\n 'id': {'key': 'id', 'type': 'str'},\n 'read_link': {'key': 'readLink', 'type': 'str'},\n 'web_search_url': {'key': 'webSearchUrl', 'type': 'str'},\n 'image_insights_token': {'key': 'imageInsightsToken', 'type': 'str'},\n 'best_representative_query': {'key': 'bestRepresentativeQuery', 'type': 'Query'},\n 'image_caption': {'key': 'imageCaption', 'type': 'ImageInsightsImageCaption'},\n 'related_collections': {'key': 'relatedCollections', 'type': 'RelatedCollectionsModule'},\n 'pages_including': {'key': 'pagesIncluding', 'type': 'ImagesModule'},\n 'shopping_sources': {'key': 'shoppingSources', 'type': 'AggregateOffer'},\n 'related_searches': {'key': 'relatedSearches', 'type': 'RelatedSearchesModule'},\n 'recipes': {'key': 'recipes', 'type': 'RecipesModule'},\n 'visually_similar_images': {'key': 'visuallySimilarImages', 'type': 'ImagesModule'},\n 'visually_similar_products': {'key': 'visuallySimilarProducts', 'type': 'ImagesModule'},\n 'recognized_entity_groups': {'key': 'recognizedEntityGroups', 'type': 'RecognizedEntitiesModule'},\n 'image_tags': {'key': 'imageTags', 'type': 'ImageTagsModule'},\n }\n\n def __init__(self):\n super(ImageInsights, self).__init__()\n self.image_insights_token = None\n self.best_representative_query = None\n self.image_caption = None\n self.related_collections = None\n self.pages_including = None\n self.shopping_sources = None\n self.related_searches = None\n self.recipes = None\n self.visually_similar_images = None\n self.visually_similar_products = None\n self.recognized_entity_groups = None\n self.image_tags = None\n self._type = 'ImageInsights'\n","sub_path":"azure-cognitiveservices-search-imagesearch/azure/cognitiveservices/search/imagesearch/models/image_insights.py","file_name":"image_insights.py","file_ext":"py","file_size_in_byte":7929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"622010134","text":"from django.shortcuts import render, redirect\nfrom oddjob_app.forms import *\nfrom oddjob_app.errors import error\nfrom oddjob_app.forms import JobForm\n\n\ndef index(request):\n if request.user.is_authenticated():\n return redirect('home')\n\n auth_form = AuthForm()\n return render(request, 'index.html', {\n 'auth_form': auth_form,\n })\n\n\ndef home(request):\n job_form = JobForm()\n return render(request, 'home.html', {\n 'job_form': job_form,\n })\n\n\ndef job(request, job_id=None):\n try:\n job = Job.objects.get(pk=job_id)\n except Job.DoesNotExist:\n return error(404, 'job not found')\n\n if job.creator != request.user:\n return error(403, 'not your job')\n\n job_form = JobForm(instance=job)\n return render(request, 'job.html', {\n 'job_form': job_form,\n 'job': job,\n })\n","sub_path":"oddjob_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"75978617","text":"from base64 import b64encode, b64decode\nfrom time import sleep\nfrom flask import json, request\n\nfrom models.agent import Agent\nfrom models.staging_response import StagingResponse\n\nfrom backend.rabbitmq import rabbit_consumer\nfrom backend.rabbitmq import rabbit_producer\nfrom logger import log\n\n\ndef staging_message_json(staging_message):\n log(\"staging_message_json\", \"Working on %s\" % staging_message)\n result = dict({\n 'PayloadName': staging_message.PayloadName,\n 'IV': staging_message.IV,\n 'HMAC': staging_message.HMAC,\n 'Message': staging_message.Message\n })\n return result\n\n\ndef staging_response_json(staging_response):\n result = dict({\n 'AgentName' : staging_response.AgentName,\n 'IV': staging_response.IV,\n 'HMAC': staging_response.HMAC,\n 'Message' : staging_response.Message\n })\n return result\n\n\ndef staging_response_envelope(agentName, message):\n result = dict({\n 'Success': True,\n \"AgentName\": agentName,\n \"Message\": message\n })\n return result\n\n\ndef get_staging_response(staging_id):\n response = None\n agent = Agent.query.filter_by(StagingId=staging_id).first()\n if agent and agent.StagingResponseId:\n response = StagingResponse.query.filter_by(Id=agent.StagingResponseId).filter_by(Sent=False).last()\n if response:\n response_json = staging_message_json(response)\n results = []\n results.append(response_json)\n return results\n return dict({\n \"Success\":False,\n \"Message\": \"No staging response available for ID: {0}\".format(staging_id)\n })\n\n\ndef new_staging_message(payload_name, staging_id, transport_id, message, source_ip=None):\n log(\"staging_message:new_staging_message\", \"Got staging request. PayloadName: {0} ID: {1}\".format(payload_name, staging_id))\n\n response = get_staging_response(staging_id)\n if response['Success']:\n return response\n else:\n decoded_response = b64decode(message)\n response_dict = json.loads(decoded_response)\n response_dict[\"PayloadName\"] = payload_name\n response_dict[\"TransportId\"] = transport_id\n if source_ip == None:\n source_ip = request.remote_addr\n response_dict[\"SourceIp\"] = source_ip\n\n\n log(\"staging_message:new_staging_message\", \"Publishing: {0}\".format(response_dict))\n message_id = rabbit_producer.send_request('NewStagingMessage', response_dict, callback=True)\n\n # Wait for our response\n log(\"staging_message:new_staging_message\", \"Waiting for 10 seconds\")\n i = 0\n while rabbit_consumer.queue[message_id] is None and i < 10:\n log(\"staging_message:new_staging_message\", \"Waiting for {0} seconds\".format(10 - i))\n sleep(1)\n i += 1\n\n # Return data\n message = rabbit_consumer.queue[message_id]\n\n if message:\n log(\"staging_message\", \"Got response from Core: {0}\".format(message))\n return json.loads(message)\n else:\n log(\"staging_message\", \"Timed out.\")\n return \"ERROR\"\n","sub_path":"processing/staging.py","file_name":"staging.py","file_ext":"py","file_size_in_byte":3038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"208578609","text":"from bs4 import BeautifulSoup\nimport requests\nimport os\nimport pandas as pd\nfrom urllib.request import urlopen\nimport os\n\nurl_head = \"https://search.kyobobook.co.kr/web/search?vPstrKeyWord=\"\nurl_tail = \"&searchPcondition=1&searchCategory=%EA%B5%AD%EB%82%B4%EB%8F%84%EC%84%9C@KORBOOK@@%EC%BB%B4%ED%93%A8%ED%84%B0/IT@33&collName=KORBOOK&from_CollName=%EC%A0%84%EC%B2%B4@UNION&vPstrTab=PRODUCT&from_coll=KORBOOK¤tPage=1&orderClick=LIZ\"\n# 제목 #search_list > tr:nth-child(6) > td.detail > div.title > a > strong\n# 가격 #search_list > tr:nth-child(6) > td.price > div.sell_price > strong\n# search_list > tr:nth-child(6) > td.price > div.sell_price > strong\n# 저자 #search_list > tr:nth-child(6) > td.detail > div.author > a:nth-child(1)\n# 이미지 #search_list > tr:nth-child(6) > td.image > div.cover > a > img\n\nurl_dict = {}\nu_list = ['html', 'django', 'machine+learning', 'java+spring', 'docker+kubernetes']\n\nfor i in u_list:\n url_dict[i] = url_head + i + url_tail\nfinal_list = []\nfor book_key, url in url_dict.items():\n book_key = book_key.replace('+', '_')\n response = requests.get(url)\n html = response.text\n soup = BeautifulSoup(html, 'html.parser')\n books = soup.select(\"#search_list tr \")\n\n n = 1\n for i in soup.select('#search_list tr td.image div.cover a img'):\n print(i['src'])\n\n img_url = i['src']\n with urlopen(img_url) as f:\n with open('C:/Users/wnssp/PycharmProjects/lecture_review_site/lecture/static/img/' + book_key + str(n) + '.jpg', 'wb') as h:\n ima = f.read()\n h.write(ima)\n n += 1\n if n > 10:\n break\n\n cnt = 1\n for book in books:\n book_dic = {}\n title = book.select('td.detail div.title a strong')[0].text\n author = book.select('td.detail div.author a')[0].text\n lin = book.select('td.detail div.title a')[0]['href']\n price = book.select('td.price div.sell_price strong')\n if not book.select('td.info div.review.klover a b'):\n like = 0\n else:\n like = book.select('td.info div.review.klover a b')[0].text\n\n if len(price) != 0:\n price = price[0].text\n else:\n price = 0\n\n book_dic['book_title'] = title\n book_dic['book_author'] = author\n book_dic['book_price'] = price\n book_dic['book_like'] = like\n book_dic['book_kind'] = book_key\n book_dic['book_link'] = lin\n final_list.append(book_dic)\n print(title)\n cnt += 1\n if cnt == 11:\n break\n\nbook_list = pd.DataFrame(columns=['book_title', 'book_author', 'book_price', 'book_like', 'book_link'])\nfor i in final_list:\n tmp = pd.Series(i)\n book_list = book_list.append(tmp, ignore_index=True)\n\nbook_list\n\nimport pymysql\nimport sqlalchemy\npymysql.install_as_MySQLdb()\nfrom sqlalchemy import create_engine\n\nengine = create_engine(\"mysql+mysqldb://django:\"+\"django1234\"+\"@database-1.c0hm91gdojzz.ap-northeast-2.rds.amazonaws.com:3306/django_db?charset=utf8\",encoding=\"utf-8\")\nconn = engine.connect()\n\nbook_list.to_sql(name='lecture_book', con=engine, if_exists='replace', index=True, index_label='id')","sub_path":"0914_북스크래핑_aws.py","file_name":"0914_북스크래핑_aws.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"519019189","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\ndata1 = tf.constant(2.5)\ndata2 = tf.Variable(10, name='var')\nprint(data1)\nprint(data2)\nwith tf.Session() as sess:\n print(sess.run(data1))\n init = tf.global_variables_initializer()\n sess.run(init)\n print(sess.run(data2))","sub_path":"2/2_11tf_hw.py","file_name":"2_11tf_hw.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"409672509","text":"import datetime\nimport pytz\nimport json\nfrom django.contrib.auth.models import User\nfrom appraisal.models import Appraisal, Comment\nfrom appraisal.forms import FormComment\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom appraisal.data import getAppraisalFromRequest\nfrom list.views import render_appraisals_table, render_appraisals_row\nfrom django.http import JsonResponse\ntimezone_cl = pytz.timezone('Chile/Continental')\n\ndef main(request):\n return HttpResponse('')\n\ndef ajax_logbook(request):\n '''\n Called when opening the logbook modal, through AJAX. Returns the comments of the relevant appraisal.\n '''\n appraisal_id = int(request.GET['appraisal_id'])\n appraisal = Appraisal.objects.get(id=appraisal_id)\n comments = appraisal.comments.select_related('user').all().order_by('-timeCreated')\n form_comment = FormComment(label_suffix='')\n\n form_comment.fields['event'].choices = appraisal.getCommentChoices(comments,state=appraisal.state,user=request.user)\n\n notifications = request.user.profile.notifications.all()\n notifications_comment_ids = notifications.values_list('comment_id', flat=True) \n\n groups = request.user.groups.values_list('name',flat=True)\n\n reports = appraisal.report_set.order_by('time_uploaded')\n\n comment_mp = Comment.__dict__\n comment_dict = {}\n for k, v in comment_mp.items():\n if isinstance(v,type('')) or isinstance(v,type(1)):\n comment_dict[k] = v\n comment_class = json.dumps(comment_dict)\n\n return render(request,'logbook/modals_logbook.html',\n {'appraisal':appraisal,\n 'comments':comments,\n 'form_comment':form_comment,\n 'groups':groups,\n 'reports':reports,\n 'comment_class':comment_class,\n 'notifications_comment_ids':notifications_comment_ids})\n\ndef ajax_logbook_close(request):\n '''\n Called when closing the logbook modal, through AJAX.\n 1. Deletes notifications.\n 2. Saves modified variables\n '''\n print(request.POST)\n appraisal_id = int(request.POST['appraisal_id'])\n request.user.profile.removeNotification(ntype=\"comment\",appraisal_id=appraisal_id)\n\n appraisal = Appraisal.objects.get(id=appraisal_id)\n\n if request.POST['valorUF'] in [\"None\",\"\"]:\n appraisal.valorUF = None\n else:\n appraisal.valorUF = request.POST['valorUF']\n\n if request.POST['solicitanteEjecutivo'] in [\"None\",\"\"]:\n appraisal.solicitanteEjecutivo = None\n else:\n appraisal.solicitanteEjecutivo = request.POST['solicitanteEjecutivo']\n if request.POST['solicitanteEjecutivoEmail'] in [\"None\",\"\"]:\n appraisal.solicitanteEjecutivoEmail = None\n else:\n appraisal.solicitanteEjecutivoEmail = request.POST['solicitanteEjecutivoEmail']\n if request.POST['solicitanteEjecutivoTelefono'] in [\"None\",\"\"]:\n appraisal.solicitanteEjecutivoTelefono = None\n else:\n appraisal.solicitanteEjecutivoTelefono = request.POST['solicitanteEjecutivoTelefono']\n\n if request.POST['contacto'] in [\"None\",\"\"]:\n appraisal.contacto = None\n else:\n appraisal.contacto = request.POST['contacto']\n if request.POST['contactoEmail'] in [\"None\",\"\"]:\n appraisal.contactoEmail = None\n else:\n appraisal.contactoEmail = request.POST['contactoEmail']\n if request.POST['contactoTelefono'] in [\"None\",\"\"]:\n appraisal.contactoTelefono = None\n else:\n appraisal.contactoTelefono = request.POST['contactoTelefono']\n\n if request.POST['cliente'] in [\"None\",\"\"]:\n appraisal.cliente = None\n else:\n appraisal.cliente = request.POST['cliente']\n if request.POST['clienteEmail'] in [\"None\",\"\"]:\n appraisal.clienteEmail = None\n else:\n appraisal.clienteEmail = request.POST['clienteEmail']\n if request.POST['clienteTelefono'] in [\"None\",\"\"]:\n appraisal.clienteTelefono = None\n else:\n appraisal.clienteTelefono = request.POST['clienteTelefono']\n appraisal.save()\n\n return HttpResponse('')\n\ndef ajax_logbook_change_event(request):\n '''\n '''\n\n #if request['event'] == \n\n return JsonResponse({'comment_id':comment_id})\n\ndef ajax_accept_appraisal(request):\n '''\n Called from logbook. Tasador or superuser accepts an appraisal assigned to him.\n '''\n # Change appraisal state\n appraisal = getAppraisalFromRequest(request)\n appraisal.state = Appraisal.STATE_IN_APPRAISAL\n # Add comment\n appraisal.addComment(Comment.EVENT_SOLICITUD_ACEPTADA,request.user,datetime.datetime.now(timezone_cl))\n appraisal.save()\n \n return render_appraisals_table(request, Appraisal.STATE_IN_APPRAISAL)\n \ndef ajax_reject_appraisal(request):\n '''\n Called from logbook. Tasador asignado rechaza la solicitud de tasación.\n '''\n # Change appraisal state\n appraisal = getAppraisalFromRequest(request)\n appraisal.state = Appraisal.STATE_NOT_ASSIGNED\n # Change tasador user of appraisal\n appraisal.tasadorUser = None\n # Add comment\n comment = appraisal.addComment(Comment.EVENT_SOLICITUD_RECHAZADA,request.user,datetime.datetime.now(timezone_cl))\n appraisal.save()\n # Add notification\n for user in User.objects.filter(groups__name='asignador'):\n user.profile.addNotification(ntype=\"comment\",appraisal_id=appraisal.id,comment_id=comment.id)\n\n return render_appraisals_table(request, Appraisal.STATE_NOT_ASSIGNED)\n\ndef ajax_enviar_a_visador(request):\n '''\n Appraisal is sent to the visador, after the tasador has done its work.\n '''\n # Change appraisal state\n appraisal = getAppraisalFromRequest(request)\n appraisal.state = Appraisal.STATE_IN_REVISION\n # Add comment\n comment = appraisal.addComment(Comment.EVENT_ENVIADA_A_VISADOR,request.user,datetime.datetime.now(timezone_cl))\n # Add notification\n if appraisal.visadorUser:\n appraisal.visadorUser.profile.addNotification(\"comment\",appraisal.id,comment.id)\n #Save\n appraisal.save()\n\n return JsonResponse({})\n\n\ndef ajax_devolver_a_tasador(request):\n '''\n Appraisal is sent back by the visador to the tasador.\n '''\n appraisal = getAppraisalFromRequest(request)\n appraisal.state = Appraisal.STATE_IN_APPRAISAL\n # Add comment\n comment = appraisal.addComment(Comment.EVENT_DEVUELTA_A_TASADOR,request.user,datetime.datetime.now(timezone_cl))\n # Add notification\n if appraisal.tasadorUser:\n appraisal.tasadorUser.profile.addNotification(\"comment\",appraisal.id,comment.id)\n # Save\n appraisal.save()\n\n return JsonResponse({})\n\n\ndef ajax_enviar_a_cliente(request):\n '''\n Appraisal must be sent back to in revision state. Therefore notify the visador.\n '''\n appraisal = getAppraisalFromRequest(request)\n appraisal.state = Appraisal.STATE_SENT\n # Add comment\n comment = appraisal.addComment(Comment.EVENT_ENTREGADO_AL_CLIENTE,request.user,datetime.datetime.now(timezone_cl))\n # Add notification\n if appraisal.tasadorUser:\n appraisal.tasadorUser.profile.addNotification(\"comment\",appraisal.id,comment.id)\n # Save\n appraisal.save()\n\n return JsonResponse({})\n\ndef ajax_devolver_a_visador(request):\n '''\n Appraisal must be sent back to the visador.\n '''\n appraisal = getAppraisalFromRequest(request)\n appraisal.state = Appraisal.STATE_IN_REVISION\n # Add comment\n comment = appraisal.addComment(Comment.EVENT_DEVUELTA_A_VISADOR,request.user,datetime.datetime.now(timezone_cl))\n # Add notification\n if appraisal.tasadorUser:\n appraisal.tasadorUser.profile.addNotification(\"comment\",appraisal.id,comment.id)\n # Save\n appraisal.save()\n\n return JsonResponse({})","sub_path":"web/logbook/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"491215385","text":"import tkinter as tk \n\ndef new_window(Win_class):\n global win2\n try:\n if win2.state() == \"normal\": win2.focus()\n except:\n win2 = tk.Toplevel(win)\n Win_class(win2)\n\nclass Win2:\n def __init__(self, root):\n self.root = root\n self.root.geometry(\"300x300+500+200\")\n self.root[\"bg\"] = \"navy\"\n\nwin = tk.Tk()\nwin.geometry(\"200x200+200+100\")\nbutton = tk.Button(win, text=\"Open new window\")\nbutton['command'] = lambda: new_window(Win2)\nbutton.pack()\ntext = tk.Text(win, bg='cyan')\ntext.pack()\nwin.mainloop()\n","sub_path":"files/new-window.py","file_name":"new-window.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"391965889","text":"import enum\nimport numpy as np\n\nfrom skimage import exposure\nfrom scipy.misc import imresize\nfrom scipy.ndimage.interpolation import rotate\n\n# %% List of allowable transformation function\n\n\nclass Allo(object):\n FlipLR = 'FlipLR'\n FlipUD = 'FlipUD'\n PermCH = 'PermCH'\n CutOut = 'CutOut'\n RndCrop = 'RndCrop'\n RndRotate = 'RndRotate'\n Translate = 'Translate'\n Correction = 'Correction'\n\n# %% Util functions\n\n\ndef FlipLR(img):\n return np.fliplr(img)\n\n\ndef FlipUD(img):\n return np.flipud(img)\n\n\ndef Correction(img):\n rnd = np.random.rand()\n if rnd < 0.5:\n return exposure.adjust_log(img)\n elif rnd < 1:\n return exposure.adjust_sigmoid(img)\n\n\ndef PermCH(img):\n noch = img.shape[2] if len(img.shape) > 2 else False\n if noch:\n R = img[:, :, 0]\n G = img[:, :, 1]\n B = img[:, :, 2]\n colors = np.random.permutation([R, G, B])\n return np.moveaxis(np.array(colors), 0, 2)\n else:\n return img\n\n\ndef RndCrop(img, rate=1.1):\n crop_size = img.shape\n img = imresize(img, rate)\n h, w = img.shape if len(\n img.shape) == 2 else (img.shape[0], img.shape[1])\n top = np.random.randint(0, h - crop_size[0])\n left = np.random.randint(0, w - crop_size[1])\n bottom = top + crop_size[0]\n right = left + crop_size[1]\n img = img[top:bottom, left:right]\n return img\n\n\ndef RndRotate(img, angle_range=(-15, 15)):\n h, w = img.shape if len(\n img.shape) == 2 else (img.shape[0], img.shape[1])\n angle = np.random.randint(*angle_range)\n img = rotate(img, angle)\n img = imresize(img, (h, w))\n return img\n\n\ndef CutOut(img, s=(0.01, 0.1)):\n rnd = np.random.rand()\n if rnd < 0.5:\n mask_value = img.mean()\n else:\n mask_value = 0\n h, w = img.shape if len(\n img.shape) == 2 else (img.shape[0], img.shape[1])\n mask_area = np.random.randint(h * w * s[0], h * w * s[1])\n mask_aspect_ratio = np.random.rand() * 2\n if mask_aspect_ratio < 0.5:\n mask_aspect_ratio += 0.5\n if mask_aspect_ratio > 1.5:\n mask_aspect_ratio -= 0.5\n mask_height = int(np.sqrt(mask_area * mask_aspect_ratio))\n if mask_height > h - 1:\n mask_height = h - 1\n mask_aspect_ratio = np.random.rand() * 2\n if mask_aspect_ratio < 0.5:\n mask_aspect_ratio += 0.5\n if mask_aspect_ratio > 1.5:\n mask_aspect_ratio -= 0.5\n mask_width = int(mask_aspect_ratio * mask_height)\n if mask_width > w - 1:\n mask_width = w - 1\n top = np.random.randint(0, h - mask_height)\n left = np.random.randint(0, w - mask_width)\n bottom = top + mask_height\n right = left + mask_width\n img[top:bottom, left:right].fill(mask_value)\n return img\n\n\ndef Translate(img, rate=0.1):\n HEIGHT, WIDTH = img.shape if len(\n img.shape) == 2 else (img.shape[0], img.shape[1])\n rnd = np.random.rand()\n if rnd < 0.5:\n rnd = np.random.rand()\n if rnd < 0.25: # Shifting Left\n pix = int(rate*WIDTH)\n img[:, :-pix] = img[:, pix:]\n img[:, -pix:] = 0\n elif rnd < 0.5: # Shifting Right\n pix = int(rate*WIDTH)\n img[:, pix:] = img[:, :-pix]\n img[:, :pix] = 0\n elif rnd < 0.75: # Shifting Up\n pix = int(rate*HEIGHT)\n img[:-pix, :] = img[pix:, :]\n img[-pix:, :] = 0\n elif rnd < 1: # Shifting Down\n pix = int(rate*HEIGHT)\n img[pix:, :] = img[:-pix, :]\n img[:pix, :] = 0\n else :\n rnd = np.random.rand()\n if rnd < 0.25: # Shifting Up-Left\n pix = int(rate*WIDTH)\n img[:-pix, :-pix] = img[pix:, pix:]\n img[:, -pix:] = 0\n img[-pix:, :] = 0\n elif rnd < 0.5: # Shifting Up-Right\n pix = int(rate*WIDTH)\n img[:-pix, pix:] = img[pix:, :-pix]\n img[:, :pix] = 0\n img[-pix:, :] = 0\n elif rnd < 0.75: # Shifting Down-Left\n pix = int(rate*WIDTH)\n img[pix:, :-pix] = img[:-pix, pix:]\n img[:, -pix:] = 0\n img[:pix, :] = 0\n elif rnd < 1: # Shifting Down-Right\n pix = int(rate*WIDTH)\n img[pix:, pix:] = img[:-pix, :-pix]\n img[:, :pix] = 0\n img[:pix, :] = 0\n return img\n","sub_path":"MyCode-01/Generator/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":4300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"464062996","text":"class LazyProperty:\n # 包装器\n def __init__(self, func):\n print('set func {}'.format(func.__name__))\n self.func = func\n\n # 描述器\n def __get__(self, instance, owner):\n if instance is None:\n return self\n val = self.func(instance) # 调用实际方法\n instance.__dict__[self.func.__name__] = val # 设置到实例的__dict__\n return val\n\n\ndef lazy_property(func):\n attr = '_lazy_' + func.__name__ # !!必须判断不存在的属性!!\n\n @property\n def _lazy_property(self):\n if not hasattr(self, attr):\n setattr(self, attr, func(self))\n\n return getattr(self, attr)\n\n return _lazy_property\n\n\nclass Person:\n def __init__(self, name):\n self.name = name\n\n @LazyProperty\n def child(self):\n print('too much time...') # 解决:每一次获取值都相同,但计算很耗时\n return 'children'\n\n @lazy_property\n def parent(self):\n print('too much time...')\n return 'parents'\n\n\nif __name__ == '__main__':\n p = Person('pp')\n print(Person.__dict__) # 所有类的方法都属于class,储存在class的__dict__中\n print(p.__dict__)\n\n # 1、初始化:包装child方法为LazyProperty对象,它持有child方法\n # 2、获取值:1)查找实例__dict__不存在;2)查找类__dict__存在,并且是描述器,包含__get__执行,将结果存储在实例__dict__\n print(p.child)\n print(Person.__dict__)\n print(p.__dict__)\n\n # 3、获取值:1)查找实例__dict__,存在直接返回\n print(p.child)\n\n print('*' * 40)\n\n print(Person.__dict__)\n print(p.__dict__)\n print(p.parent)\n print(Person.__dict__)\n print(p.__dict__)\n print(p.parent)\n","sub_path":"pattern/creational/lazy_evaluation.py","file_name":"lazy_evaluation.py","file_ext":"py","file_size_in_byte":1762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"506225352","text":"\r\n\"\"\"import sys\"\"\"\r\nimport random\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.patches import Circle\r\n\r\nc = input(\"Charges multiplier?: \")\r\n#d= input(\"Charges multiplier?: \")\r\n#k = 4*np.pi*(8.854**(-12))\r\n\r\nModulo = input(\"\\nWhich modulo do you want to run? (1, 2, 3, or 4): \")\r\n\r\ndef E(q, r0, x, y):\r\n \"\"\"Return the electric field vector E=(Ex,Ey) due to charge q at r0.\"\"\"\r\n den = np.hypot(x-r0[0], y-r0[1])**3\r\n return q * (x - r0[0]) / den, q * (y - r0[1]) / den\r\n\r\n\r\n\"\"\"Grid of x, y points\"\"\"\r\nnx, ny = 64, 64\r\nx = np.linspace(-2, 2, nx)\r\ny = np.linspace(-2, 2, ny)\r\nX, Y = np.meshgrid(x, y)\r\n\r\n\r\n\"\"\"Grid of x, y points for less detailed wider view\"\"\"\r\n##nx, ny = 256, 256\r\n##x = np.linspace(-4, 4, nx)\r\n##y = np.linspace(-4, 4, ny)\r\n##X, Y = np.meshgrid(x, y)\r\n\r\n\r\n\"\"\"Create a multipole with nq charges of alternating signs, positive signs ,or negative signs, equally spaced\"\"\"\r\n# nq = 2**int(sys.argv[2])\r\nnQ = 2**int(0)\r\nnq = 2**int(c)\r\ncharges = []\r\nfor i in range(nq):\r\n Aq = i%2 * 2 - 1 # atlernating charges\r\n #Pq = i % 2 * 2 + 1 # only positive charges\r\n Pq = 1 \r\n #Nq = -(i % 2 * 2 + 1) # only negative charges\r\n Nq = -1\r\n \r\n \"\"\" Create a multipole with nq charges of alternating sign, equally spaced\"\"\" \"\"\"Modulo 1\"\"\"\r\n \"\"\" on the unit circle. ORIGINAL\"\"\"\r\n\r\n \"\"\" A small ring of charges above a line of charges\"\"\" \"\"\"Modulo 2\"\"\"\r\n\r\n \"\"\" Two vertical parallel lines with opposite charges\"\"\" \"\"\"Modulo 3\"\"\"\r\n\r\n \"\"\" Creates a horizontal plate and a single point charge above it\"\"\" \"\"\"Modulo 4\"\"\"\r\n \r\n if Modulo == '1':\r\n charges.append((Aq, (np.cos(2*np.pi*i/nq), np.sin(2*np.pi*i/nq)))) # on the unit circle\r\n \r\n #charges.append((q, (np.cos(2*np.pi*i/nq), 2*np.sin(2*np.pi*i/nq)))) # on an ellipse \r\n\r\n elif Modulo == '2':\r\n charges.append((Nq, (np.cos(2*np.pi*i/nq), np.sin(0*np.pi*i/nq)-1.6))) # on a line on the x-axis\r\n charges.append((Pq, (.6*np.cos(2*np.pi*i/nq), .6*np.sin(2*np.pi*i/nq)+1))) # .6* a unit circle center at (0,1)\r\n\r\n\r\n elif Modulo == '3':\r\n charges.append((Nq, (np.cos(0*np.pi*i/nq)-2, np.sin(2*np.pi*i/nq)))) # vertical line on x = -1\r\n charges.append((Pq, (np.cos(0*np.pi*i/nq), np.sin(2*np.pi*i/nq)))) # vertical line on x = 1\r\n\r\n\r\n elif Modulo == '4':\r\n charges.append((Nq, (np.cos(2*np.pi*i/nQ)-1, np.sin(2*np.pi*i/nQ)+.6))) # a single point charge at (0, .6)\r\n charges.append((Pq, (np.cos(2*np.pi*i/nq), np.sin(0*np.pi*i/nq-1)))) # a horizontal line at y = -2\r\n\r\n\r\n elif Modulo == '5':\r\n charges.append((Pq, 1/nq, 2/nq))\r\n\r\n else:\r\n print(\"\\nThis modulo doesn't exist\")\r\n\r\n\r\n\"\"\"Use below if you want to add a new set of points with a different charge multiplier\"\"\"\r\n\"\"\"If you just want a single point set d = 0\"\"\"\r\n\r\n##nQ = 2**int(d) \r\n##for i in range(nQ):\r\n## q= (i%2*2+1)\r\n## charges.append((q, (np.cos(2*np.pi*i/nQ), np.sin(2*np.pi*i/nQ)+1.5)))\r\n\r\n \r\n\"\"\"Electric field vector, E=(Ex, Ey), as separate components\"\"\"\r\nEx, Ey = np.zeros((ny, nx)), np.zeros((ny, nx))\r\nfor charge in charges:\r\n ex, ey = E(*charge, x=X, y=Y)\r\n Ex += ex\r\n Ey += ey\r\n\r\nfig = plt.figure()\r\nax = fig.add_subplot(111)\r\n\r\n\"\"\"Plot the streamlines with an appropriate colormap and arrow style\"\"\"\r\ncolor = 2 * np.log(np.hypot(Ex, Ey))\r\nax.streamplot(x, y, Ex, Ey, color=color, linewidth=1, cmap=plt.cm.inferno,\r\n density=2.5, arrowstyle='->', arrowsize=1.0)\r\n\r\n\"\"\"Add filled circles for the charges themselves\"\"\"\r\ncharge_colors = {True: '#aa0000', False: '#0000aa'}\r\nfor q, pos in charges:\r\n ax.add_artist(Circle(pos, 0.035, color=charge_colors[q>0]))\r\n\r\nax.set_xlabel('$x$')\r\nax.set_ylabel('$y$')\r\nax.set_xlim(-2,2)\r\nax.set_ylim(-2,2)\r\nax.set_aspect('equal')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n","sub_path":"Electric fields of Distributions.py","file_name":"Electric fields of Distributions.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"290488017","text":"from __future__ import print_function\n\nimport sys\nfrom keras.layers import *\nfrom keras.models import Model\nfrom scipy.io import wavfile\nfrom resampy import resample\nimport numpy as np\nfrom numpy.lib.stride_tricks import as_strided\n\n\n# open the file and read the data\nif len(sys.argv) < 2:\n print(\"usage: %s wav_file_path [output_tsv_file_path]\" % sys.argv[0],\n file=sys.stderr)\n sys.exit(-1)\n\nfilename = sys.argv[1]\n\ntry:\n srate, data = wavfile.read(filename)\n if len(data.shape) == 2:\n data = data.mean(1)\n if srate != 16000:\n data = resample(data, srate, 16000)\n srate = 16000\nexcept:\n print(\"could not read %s\" % filename)\n sys.exit(-1)\n\n\n# build the CNN model\nlayers = [1, 2, 3, 4, 5, 6]\nfilters = [1024, 128, 128, 128, 256, 512]\nwidths = [512, 64, 64, 64, 64, 64]\nstrides = [(4, 1), (1, 1), (1, 1), (1, 1), (1, 1), (1, 1)]\n\nx = Input(shape=(1024, 1, 1), dtype='float32')\ny = x\n\nfor layer, filters, width, strides in zip(layers, filters, widths, strides):\n y = BatchNormalization(name=\"conv%d-BN\" % layer)(y)\n y = Conv2D(filters, (width, 1), strides=strides, padding='same',\n activation='relu', name=\"conv%d\" % layer)(y)\n y = MaxPooling2D(pool_size=(2, 1), strides=None, padding='valid',\n name=\"conv%d-maxpool\" % layer)(y)\n y = Dropout(0.25, name=\"conv%d-dropout\" % layer)(y)\n\ny = Permute((2, 1, 3), name=\"transpose\")(y)\ny = Flatten(name=\"flatten\")(y)\ny = Dense(360, activation='sigmoid', name=\"classifier\")(y)\n\nmodel = Model(inputs=x, outputs=y)\nmodel.load_weights(\"crepe.h5\")\nmodel.compile('adam', 'binary_crossentropy')\n\n\n# transform the WAV data to frames\ndata = data.astype(np.float32)\n\nhop_length = int(srate / 100)\nn_frames = 1 + int((len(data) - 1024) / hop_length)\nframes = as_strided(data, shape=(1024, n_frames),\n strides=(data.itemsize, hop_length * data.itemsize))\nframes = frames.transpose().reshape((n_frames, 1024, 1, 1))\n\n\n# run prediction and convert the frequency bin weights to Hz\nprediction = model.predict(frames, verbose=1)\ncents_mapping = np.expand_dims(np.linspace(0, 7180, 360) + 1997.3794084376191,\n axis=0)\nprediction_cents = (np.sum(cents_mapping * prediction, axis=1) /\n np.sum(prediction, axis=1))\nprediction_hz = 10 * (2 ** (prediction_cents / 1200))\nprediction_hz[np.isnan(prediction_hz)] = 0\n\n# write prediction as TSV\noutfile = len(sys.argv) > 2 and sys.argv[2] or filename + \".f0.tsv\"\nwith open(outfile, 'w') as out:\n for i, freq in enumerate(prediction_hz):\n print(\"%.2f\\t%.3f\" % (i * 0.01, freq), file=out)\n","sub_path":"crepe.py","file_name":"crepe.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588384194","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/7/23 08:22\n# @Author : Greens\n\n\ndef quick_sort(nums):\n return sort1(nums, 0, len(nums) - 1)\n\n\ndef sort1(nums, l, r):\n if l < r:\n p = partition(nums, l, r)\n sort1(nums, l, p - 1)\n sort1(nums, p + 1, r)\n return nums\n\ndef partition(nums, l, r):\n x = nums[r]\n index = l - 1\n for i in range(l, r):\n\n if nums[i] < x:\n index += 1\n nums[i], nums[index] = nums[index], nums[i]\n nums[index + 1], nums[r] = nums[r], nums[index + 1]\n return index + 1\n\n\nif __name__ == '__main__':\n my_list = [3, 1, 5, 8, 3, 5]\n aaa = quick_sort(my_list)\n print(aaa)\n","sub_path":"code/2020_07/快排.py","file_name":"快排.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"138423879","text":"import speech_recognition as sr\nimport pyttsx3\n\n# get audio from the microphone\nr = sr.Recognizer()\nwith sr.Microphone() as source:\n print(\"Speak:\")\n audio = r.listen(source)\n\ntry:\n\n engine = pyttsx3.init()\n engine.say('You said')\n engine.say(str(r.recognize_google(audio)))\n engine.runAndWait()\n\n # print(\"You said \" + r.recognize_google(audio))\nexcept sr.UnknownValueError:\n print(\"Could not understand audio\")\nexcept sr.RequestError as e:\n print(\"Could not request results; {0}\".format(e))\n","sub_path":"Main-Audio.py","file_name":"Main-Audio.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"617699517","text":"#!/usr/local/lib\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nfrom keras.models import Sequential \nfrom keras.layers.core import Dense, Activation \nfrom keras.layers.recurrent import LSTM\n\ndef make_wavedata(plot_number,wavecycle_number,datalength,batch):\n\twave=np.arange(plot_number).astype(np.float32)\n\twave=wave*(2*np.pi*wavecycle_number/plot_number)\n\twave=np.sin(wave)\n\n\tprint(wave)\n\t# plt.plot(wave)\n\t# plt.show()\n\n\tbatchs=[]\n\tt_data=[]\n\trandom_batchs=np.random.randint(0,plot_number-datalength-1,batch)\n\tfor i in range(batch):\n\t\tprint(i)\n\t\tbatchs.append(wave[random_batchs[i]:random_batchs[i]+datalength])\n\t\tt_data.append(wave[random_batchs[i]+datalength+1])\n\n\tbatchs=np.array(batchs).reshape(-1,datalength,1)\n\tt_data=np.array(t_data).reshape(-1,1)\n\tprint(batchs.shape)\n\tprint(t_data.shape)\n\n\treturn batchs,t_data\n\n\n\n\n\nif __name__ == '__main__':\n\n\tlength_of_sequences=100\n\tx_train,y_train=make_wavedata(10000,10,length_of_sequences,10000)\n\n\n\n\n\tin_out_neurons = 1\n\thidden_neurons = 1000\n\n\tmodel = Sequential() \n\tmodel.add(LSTM(hidden_neurons, batch_input_shape=(None, length_of_sequences, in_out_neurons), return_sequences=False)) \n\tmodel.add(Dense(in_out_neurons)) \n\tmodel.add(Activation(\"linear\")) \n\n\n\tmodel.compile(loss=\"mean_squared_error\", optimizer=\"rmsprop\")\n\tmodel.fit(x_train, y_train, batch_size=100, nb_epoch=15, validation_split=0.05) \n\n\n\n\t\n","sub_path":"makedataset.py","file_name":"makedataset.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"18365936","text":"import pytest\nfrom selenium import webdriver\nimport time\n\n@pytest.fixture\ndef driver(request):\n wd = webdriver.Chrome()\n request.addfinalizer(wd.quit)\n return wd\n\n#проверка того, что ссылки рядом с новыми полями, имеют аттрибут таргет\ndef test_check_attribute(driver):\n #переход на главную\n driver.get(\"http://localhost/litecart/admin/\")\n driver.find_element_by_xpath(\"//*[@id='box-login']/form/div[1]/table/tbody/tr[1]/td[2]/span/input\").send_keys(\"admin\")\n driver.find_element_by_xpath(\"//*[@id='box-login']/form/div[1]/table/tbody/tr[2]/td[2]/span/input\").send_keys(\"admin\")\n driver.find_element_by_xpath(\"//*[@id='box-login']/form/div[2]/button\").click()\n driver.find_element_by_xpath(\"//ul[@id='box-apps-menu']/li[3]\").click()\n driver.find_element_by_xpath(\"//*[@id='content']/div/a\").click()\n #ищем все элементы, у которых есть ссылка\n targets = driver.find_elements_by_xpath(\"//*[@id='content']/form/table[1]/tbody/tr/td/a\")\n #сколько таких элементов найдено\n count = len(targets)\n #для каждого элемента проверим, что ссылка имеет атрибут таргет\n for i in range(count):\n targetElement = targets[i]\n target = targetElement.get_attribute(\"target\")\n if target == \"_blank\":\n print(\"Link OK\")\n else:\n (\"Go to home\")\n\n\n\n#проверка открытия в новом окне\ndef test_open_new_window(driver):\n # переход на главную\n driver.get(\"http://localhost/litecart/admin/\")\n driver.find_element_by_xpath(\"//*[@id='box-login']/form/div[1]/table/tbody/tr[1]/td[2]/span/input\").send_keys(\"admin\")\n driver.find_element_by_xpath(\"//*[@id='box-login']/form/div[1]/table/tbody/tr[2]/td[2]/span/input\").send_keys(\"admin\")\n driver.find_element_by_xpath(\"//*[@id='box-login']/form/div[2]/button\").click()\n driver.find_element_by_xpath(\"//ul[@id='box-apps-menu']/li[3]\").click()\n driver.find_element_by_xpath(\"//*[@id='content']/div/a\").click()\n #ищем все элементы, у которых есть ссылка\n targets = driver.find_elements_by_xpath(\"//*[@id='content']/form/table[1]/tbody/tr/td/a/i\")\n #сколько таких элементов найдено\n count = len(targets)\n #для каждого элемента что-то сделаем\n for i in range(count):\n #посмотрим, сколько окон открыто\n handles_old = driver.window_handles\n count_handles_old = len(handles_old)\n #работаем с объектом i\n targetElement = targets[i]\n #открыли ссылку\n targetElement.click()\n # посмотрим, сколько окон стало\n handles_new = driver.window_handles\n count_handles_new = len(handles_new)\n #если прибавилось одно окно, продолжаем\n if (count_handles_new - count_handles_old) == 1:\n #делаем новое окно активным\n driver.switch_to_window(handles_new[1])\n #смотрим на него две секунды\n time.sleep(0.5)\n #закрываем это окно\n driver.close()\n #делаем активным предыдущее окно\n driver.switch_to_window(handles_new[0])\n #если вдруг открылось не одно окно или новое не открылось, то пишем ошибку\n else:\n print(\"UPS, Error\")","sub_path":"test_14.py","file_name":"test_14.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"485174401","text":"import time\r\nimport numpy as np\r\nimport pandas as pd\r\nimport seaborn as sns\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom scipy.integrate import solve_ivp, odeint\r\nfrom pyDOE import lhs\r\n\r\n\r\ndef f_ty(dynamical_model, shape):\r\n '''\r\n for use in ode_solvers : scipy.integrate.solve_ivp\r\n (i) transform 1-dim input to n-dim input\r\n (ii) transform (y, t)->f(y) to (y, t)->f(t, y)\r\n '''\r\n def func(t, y):\r\n y = y.reshape(-1, shape[1])\r\n \r\n result = np.zeros(shape)\r\n res_y = dynamical_model.f()(y)\r\n #res_y = result.numpy()\r\n result[...,:3] = res_y\r\n return result.reshape(-1)\r\n \r\n return func\r\n\r\n\r\ndef f_yt(dynamical_model, shape):\r\n '''\r\n for use in ode_solvers : scipy.integrate.odeint and formal_ode_solver\r\n (i) transform 1-dim input to n-dim input\r\n (ii) transform (y, t)->f(y) to (y, t)->f(y, t)\r\n '''\r\n def func(y, t):\r\n y = y.reshape(-1, shape[1])\r\n result = np.zeros(shape)\r\n res_y = dynamical_model.f()(y)\r\n #res_y = result.numpy()\r\n result[...,:3] = res_y\r\n return result.reshape(-1)\r\n \r\n return func\r\n\r\n\r\ndef formal_ode_solver(f, x0, time, method='RK4', x_bounds=None, verbose=False):\r\n '''\r\n \r\n Numerical integration of:\r\n dx / dt = f(t, x) or f(x, t)\r\n x(t=0) = x0\r\n\r\n - method == 'Euler' : explicit (Euler) integration\r\n - method == 'RK4' : fourth-order Runge-Kutta scheme\r\n \r\n x_bounds = (xmin, xmax, freq_chk_bounds); default : None\r\n freq_chk_bounds (unit : dt) : check_bounds (xmin/xmax) frequency \r\n\r\n '''\r\n solution = np.zeros([time.size, x0.size])\r\n solution[0, :] = x0\r\n sTime = time.size - 1\r\n\r\n if x_bounds is None:\r\n freq_chk_bounds = sTime + 1\r\n else:\r\n xmin, xmax, freq_chk_bounds = x_bounds\r\n i_last_check = 1\r\n \r\n # indexes of stable orbits\r\n ista = np.ones(*x0.shape, dtype=bool)\r\n \r\n def stable_orbits(sol_, xmin, xmax, verbose=False):\r\n '''\r\n '''\r\n # sol_n.shape : number of timesteps, number of orbits, number of model dimension (*xmin.shape)\r\n sol_n = sol_.reshape((sol_.shape[0], -1, *xmin.shape))\r\n imin = np.sum(sol_n < xmin, axis=(0, 2))\r\n imax = np.sum(sol_n > xmax, axis=(0, 2))\r\n # ista_ : indexes of 'new' stable orbits\r\n ista_ = ( imin + imax == 0 )\r\n # istab : indexes of 'new' stable orbits (*ndim)\r\n istab = np.repeat(ista_, *xmin.shape)\r\n # print list of 'new' unstable orbits\r\n if verbose and any(ista_ == 0):\r\n indexes = np.arange(len(ista_))\r\n print(' > unstable solutions for orbits: ', indexes[ista_==0])\r\n return istab\r\n \r\n if method == 'RK4':\r\n for i in range(sTime):\r\n h = time[i+1] - time[i]\r\n k1 = f(solution[i, ista], time[i]) \r\n k2 = f(solution[i, ista] + 0.5 * h * k1, time[i] + 0.5*h)\r\n k3 = f(solution[i, ista] + 0.5 * h * k2, time[i] + 0.5*h)\r\n k4 = f(solution[i, ista] + h * k3, time[i+1])\r\n solution[i+1, ista] = solution[i, ista] + h * ( k1 + 2 * k2 + 2 * k3 + k4 ) / 6.\r\n if (i+1)%freq_chk_bounds == 0:\r\n if verbose:\r\n print('check bounds @timestep %6d'%(i+1))\r\n ista = ista & stable_orbits(solution[i_last_check:i+2, :], xmin, xmax, verbose=verbose)\r\n solution[i+2:, ~ista] = np.nan\r\n i_last_check += freq_chk_bounds\r\n nsta = np.sum(ista) / len(xmin)\r\n if verbose:\r\n print('number of stable orbits = %4d'%nsta)\r\n if nsta == 0:\r\n print('> stop integration @timestep %6d for method %s'%(i+1, method))\r\n return solution\r\n return solution\r\n\r\n elif method == 'Euler':\r\n for i in range(sTime):\r\n h = time[i+1] - time[i]\r\n solution[i+1,:] = solution[i,:] + h * f(solution[i,:], time[i])\r\n if (i+1)%freq_chk_bounds == 0:\r\n if verbose:\r\n print('check bounds @timestep %6d'%(i+1))\r\n ista = ista & stable_orbits(solution[i_last_check:i+2, :], xmin, xmax, verbose=verbose)\r\n solution[i+2:, ~ista] = np.nan\r\n i_last_check += freq_chk_bounds\r\n nsta = np.sum(ista) / len(xmin)\r\n if verbose:\r\n print('number of stable orbits = %4d'%nsta)\r\n if nsta == 0:\r\n print('> stop integration @timestep %6d for method %s'%(i+1, method))\r\n return solution\r\n return solution\r\n \r\n else:\r\n print('formal_ode_solver: solver_method %s not known'%method) \r\n return solution\r\n\r\n\r\ndef orbits(f, x0, n_steps=200, dt=0.01, solver='formal', method='RK4', \r\n x_bounds=None):\r\n '''\r\n \r\n Numerical integration of:\r\n dx / dt = f(t, x) or f(x, t)\r\n x(t=0) = x0\r\n\r\n Use solver (default:'formal') and method (default:'RK4') for integration\r\n\r\n - solver == 'formal' : use function formal_ode_solver\r\n - method == 'Euler' : explicit (Euler) integration\r\n - method == 'RK4' : fourth-order Runge-Kutta scheme\r\n - solver == 'odeint' : use scipy.integrate.odeint\r\n - solver == 'solve_ivp' : use scipy.integrate.solve_ivp\r\n - method == 'RK45_p' : method == 'RK45' and rtol = atol = 1.49012e-8\r\n - method == 'LSODA_p' : method == 'LSODA' and rtol = atol = 1.49012e-8\r\n \r\n x0 initial condtions : (n_orbits, ndim) or (ndim,)\r\n n_steps number of steps/iterations for each orbit \r\n dt timestep\r\n\r\n x_bounds = (xmin, xmax, freq_chk_bounds); default : None\r\n freq_chk_bounds (unit : dt) : check_bounds (xmin/xmax) frequency\r\n\r\n Returns: a numpy.ndarray sol(n_steps, *x0.shape)\r\n\r\n '''\r\n ishp = x0.shape # initial shape\r\n x0_1d = x0.reshape(-1)\r\n \r\n t_star = np.arange(0., n_steps*dt, dt)\r\n\r\n if x_bounds is not None:\r\n xmin, xmax, freq_chk_bounds = x_bounds\r\n x_bounds = xmin, xmax, freq_chk_bounds\r\n\r\n if solver == 'formal':\r\n sol = formal_ode_solver(f, x0_1d, t_star, method, x_bounds)\r\n sol = sol.reshape(-1, *ishp)\r\n\r\n elif solver == 'odeint':\r\n sol = odeint(f, x0_1d, t_star)\r\n sol = sol.reshape(-1, *ishp)\r\n\r\n elif solver == 'solve_ivp':\r\n if method == 'RK45_p':\r\n sol = solve_ivp(f, t_span=[t_star.min(), t_star.max()], y0=x0_1d, t_eval=t_star, method='RK45', rtol=1.49012e-8, atol=1.49012e-8)\r\n elif method == 'LSODA_p':\r\n sol = solve_ivp(f, t_span=[t_star.min(), t_star.max()], y0=x0_1d, t_eval=t_star, method='LSODA', rtol=1.49012e-8, atol=1.49012e-8) \r\n else:\r\n sol = solve_ivp(f, t_span=[t_star.min(), t_star.max()], y0=x0_1d, t_eval=t_star, method=method)\r\n sol = sol.y.T.reshape(-1, *ishp)\r\n\r\n else:\r\n print('orbits: solver %s not known'%solver)\r\n sol = None\r\n\r\n return sol\r\n\r\n\r\ndef generate_data(dynamical_model, x0, n_steps=100, dt=0.01, \\\r\n compute_y=True, normalization=False, solver='formal', method='RK4', \r\n x_bounds=None):\r\n '''\r\n\r\n Numerical integration of:\r\n dx / dt = f(t, x) or f(x, t)\r\n x(t=0) = x0\r\n\r\n Use solver (default:'formal') and method (default:'RK4') for integration \r\n \r\n The object 'dynamical_model' should have at least the attribute:\r\n dynamical_model.f() : callable, x \\mapsto f(x), with x : n-dimensional\r\n used to compute f(x(t)) given x(t)\r\n \r\n dynamical_model.f() is transformed to : f(t, x) or f(x, t) with x : 1-dimensional\r\n using f_ty or f_yt\r\n\r\n x0 initial condtions : (n_orbits, ndim) or (ndim,)\r\n n_steps number of steps/iterations for each orbit \r\n dt timestep\r\n\r\n x_bounds = (xmin, xmax, freq_chk_bounds); default : None\r\n freq_chk_bounds (unit : dt) : check_bounds (xmin/xmax) frequency\r\n\r\n Returns: a dictionary 'output' with\r\n - output['x'] : (n_steps, *x0.shape)\r\n - output['y'] : (n_steps, *x0.shape) = f(x) if compute_y = True\r\n - normalized values if normalization = True\r\n output['x_norm'] and output['y_norm']\r\n and the corresponding norms : output['norms'] = np.array([mean_x, mean_y, std_x, std_y])\r\n\r\n '''\r\n output = {}\r\n \r\n if len(x0.shape) == 1:\r\n x0 = x0.reshape(1, *x0.shape)\r\n \r\n if hasattr(dynamical_model, '_orbits'):\r\n xt = dynamical_model._orbits(x0, n_steps=n_steps, dt=dt, solver=solver, method=method, x_bounds=x_bounds)\r\n else :\r\n if solver == 'solve_ivp':\r\n f = f_ty(dynamical_model, x0.shape)\r\n else:\r\n f = f_yt(dynamical_model, x0.shape)\r\n\r\n xt = orbits(f, x0, n_steps=n_steps, dt=dt, solver=solver, method=method, \r\n x_bounds=x_bounds)\r\n\r\n output['x'] = xt\r\n\r\n if compute_y:\r\n yt = dynamical_model.f()(xt)\r\n output['y'] = yt\r\n \r\n if normalization:\r\n x_n, mean_x, std_x = normalize(xt)\r\n y_n, mean_y, std_y = normalize(yt)\r\n norms_ = np.array([mean_x, mean_y, std_x, std_y])\r\n output['x_norm'] = x_n\r\n output['y_norm'] = y_n\r\n output['norms'] = norms_\r\n\r\n return output\r\n\r\n\r\n\r\ndef generate_data_solvers(lst_solvers, dynamical_model, x_0, n_steps=100, dt=0.01, x_bounds=None, elapsed_time=False):\r\n '''\r\n\r\n Execute the function 'generate_data' for a list of (solver, method)\r\n\r\n Returns:\r\n a numpy.ndarray (n_solvers, n_steps, *x_0.shape)\r\n\r\n '''\r\n n_solvers = len(lst_solvers)\r\n xt = np.zeros([n_solvers, n_steps, *x_0.shape])\r\n\r\n if elapsed_time:\r\n elapsed_t = np.zeros([n_solvers])\r\n\r\n i = 0 \r\n for solver_, method_ in lst_solvers:\r\n if elapsed_time:\r\n start_t = time.time()\r\n output = generate_data(dynamical_model, x_0, n_steps=n_steps, dt=dt, \\\r\n compute_y=False, solver=solver_, method=method_, x_bounds=x_bounds)\r\n if elapsed_time:\r\n end_t = time.time()\r\n elapsed_t[i] = end_t - start_t \r\n xt[i, ...] = output['x']\r\n i += 1\r\n \r\n if elapsed_time:\r\n return xt, elapsed_t\r\n else:\r\n return xt\r\n\r\n\r\ndef save_orbits(xt_, lst_solvers, model_name, eL63_model=None, elapsed_times=None):\r\n '''\r\n '''\r\n df_ = pd.DataFrame()\r\n \r\n assert len(xt_.shape) == 4, 'len(xt.shape) must be equal to 4'\r\n n_solvers, n_steps, n_orbits, n_dim = xt_.shape\r\n\r\n if eL63_model is not None:\r\n zt_ = eL63_model.Bx_to_Bz(xt_)\r\n\r\n for i in range(n_solvers):\r\n solver, method = lst_solvers[i]\r\n # save only 4 components...\r\n for j in range(np.min([n_dim, 4])):\r\n for k in range(n_orbits):\r\n if eL63_model is not None:\r\n xdata = np.zeros([n_steps, 2])\r\n if np.isnan(np.sum(xt_[i, :, k, j])):\r\n xt_[i, :, k, j] = np.nan\r\n zt_[i, :, k, j] = np.nan\r\n xdata[..., 0] = xt_[i, :, k, j]\r\n xdata[..., 1] = zt_[i, :, k, j]\r\n df_ijk = pd.DataFrame(xdata, columns=['x', 'z'])\r\n df_ijk['timestep'] = np.arange(len(xdata))\r\n else:\r\n df_ijk = pd.DataFrame(xt_[i, :, k, j], columns=['x'])\r\n\r\n df_ijk['model'] = model_name+'_d'+str(n_dim)\r\n df_ijk['solver'] = solver[0]+'_'+method\r\n df_ijk['i'] = j+1\r\n df_ijk['orbit'] = k+1\r\n if elapsed_times is not None:\r\n df_ijk['elapsed_t'] = elapsed_times[i]\r\n df_ = pd.concat([df_, df_ijk])\r\n\r\n return df_\r\n\r\n\r\ndef generate_LHS(dynamical_model, xmin, xmax, n_samples=100, normalization=True):\r\n '''\r\n '''\r\n lhs_x = (lhs(dynamical_model.ndim, samples=n_samples, criterion='center'))*(np.array(xmax)-np.array(xmin)) + np.array(xmin)\r\n lhs_y = dynamical_model.f()(lhs_x)\r\n \r\n if normalization:\r\n x_n, mean_x, std_x = normalize(lhs_x)\r\n y_n, mean_y, std_y = normalize(lhs_y)\r\n norms_ = np.array([mean_x, mean_y, std_x, std_y])\r\n return lhs_x, lhs_y, x_n, y_n, norms_\r\n else:\r\n return lhs_x, lhs_y\r\n\r\n\r\ndef normalize(x):\r\n mean_ = np.mean(x, axis=tuple(range(0, x.ndim-1)))\r\n std_ = np.std(x, axis=tuple(range(0, x.ndim-1)))\r\n std_ = np.where(std_ == 0, 1.0, std_)\r\n x_n = (x - mean_) / std_\r\n return x_n, mean_, std_\r\n\r\n\r\ndef plot_orbits_distribution(df_, title, figname, figtype, palette='rocket', xaxis='i', yaxis='z', hue='orbit', col='model'):\r\n '''\r\n '''\r\n plt.figure()\r\n sns.set_theme(style='ticks', palette=palette)\r\n if col is None:\r\n sns_plot = sns.barplot(data=df_, x=xaxis, y=yaxis, hue=hue) \r\n else:\r\n sns_plot = sns.catplot(data=df_, x=xaxis, y=yaxis, hue=hue, col=col, kind='box', showfliers=False)\r\n plt.savefig(figname+'.'+figtype)\r\n\r\n\r\n\r\ndef generate_x0(xt_truth, n_snapshots) :\r\n '''\r\n '''\r\n min_bounds = np.array([-10., -10., 10.])\r\n max_bounds = np.array([10., 10., 30.])\r\n index_valid = np.random.randint(0, xt_truth.shape[0]-1, n_snapshots)\r\n\r\n x0 = np.zeros((n_snapshots, 6))\r\n x0[:, :3] = xt_truth[index_valid]\r\n x0[:, 3:] = (lhs(3, samples=n_snapshots))*(max_bounds-min_bounds)+min_bounds\r\n\r\n return x0\r\n","sub_path":"L63/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":13528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"25123321","text":"# -*-coding:utf-8-*-\r\n\r\n'''\r\nCreated on 2018年1月27日\r\n@author:mengshuai@100tal.com\r\n'''\r\n\r\nimport numpy as np\r\nfrom pandas import DataFrame\r\n\r\n\r\ndef per_posi(stu_ans):\r\n\r\n '''\r\n :param stu_ans:\r\n :print: the percentage of positive sample\r\n '''\r\n len_1 = len(np.where(stu_ans == 1)[0])\r\n len_0 = len(np.where(stu_ans == -1)[0])\r\n\r\n tf = float(len_1) / (len_1 + len_0)\r\n tf *= 100\r\n print('the percentage of positive is {:4.2f}%'.format(tf))\r\n\r\ndef modify(score):\r\n\r\n return score\r\n\r\n '''\r\n if score >= 0:\r\n score = 1\r\n else:\r\n score = -1\r\n return score\r\n if score > 1.5:\r\n score = 2\r\n else:\r\n score = 1\r\n return score\r\n '''\r\n\r\ndef train_test_split(stu_ans):\r\n\r\n '''\r\n random split\r\n :param stu_ans:\r\n :return: train, test\r\n '''\r\n\r\n test = np.zeros(stu_ans.shape)\r\n train = stu_ans.copy()\r\n num = 0\r\n for user in range(stu_ans.shape[0]):\r\n len_ = len(stu_ans[user, :].nonzero()[0])\r\n len_ = len_/4\r\n # len_ = 10\r\n test_ratings = np.random.choice(stu_ans[user, :].nonzero()[0], size=int(len_), replace=False)\r\n train[user, test_ratings] = 0.\r\n test[user, test_ratings] = stu_ans[user, test_ratings]\r\n # Test and training are truly disjoint\r\n # print(np.all((train * test) == 0))\r\n return train, test\r\n\r\ndef train_test(stu_ans):\r\n\r\n '''\r\n simulate split\r\n :param stu_ans:\r\n :return: train, test\r\n '''\r\n\r\n test = np.zeros(stu_ans.shape)\r\n train = stu_ans.copy()\r\n lis_sam = [i for i in range(stu_ans.shape[0])]\r\n slice = np.random.choice(np.array(lis_sam).nonzero()[0], size=200, replace=False)\r\n for user in range(stu_ans.shape[0]):\r\n if user in slice:\r\n continue\r\n test_ratings = stu_ans[user, :].nonzero()[0][-5:]\r\n train[user, test_ratings] = 0.\r\n test[user, test_ratings] = stu_ans[user, test_ratings]\r\n # Test and training are truly disjoint\r\n # print(np.all((train * test) == 0))\r\n return train, test\r\n\r\ndef save2csv(result):\r\n '''\r\n result to csv\r\n :param result:\r\n '''\r\n result_ = DataFrame(result)\r\n result_.to_csv()\r\n\r\n","sub_path":"utils/data_process.py","file_name":"data_process.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"589843181","text":"import re\nimport cStringIO\nfrom PIL import Image\nimport numpy as np\nimport cv2\nfrom imutils.object_detection import non_max_suppression\n\nIMAGE_SIZE = 80.0\nIMAGE_PADDING = 5\nMATCH_THRESHOLD = 15\norb = cv2.ORB(1000, 1.2)\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n#cascade = cv2.CascadeClassifier('classifier/fifa.xml')\n#reference = cv2.imread('images/fifaref2.jpg')\ncascade = cv2.CascadeClassifier('classifier/swbattlefront_small.xml')\nreference = cv2.imread('images/swbattlefront.jpg')\n\nreference = cv2.cvtColor(reference, cv2.COLOR_RGB2GRAY)\nratio = IMAGE_SIZE/reference.shape[1]\nreference = cv2.resize(\n reference, (int(IMAGE_SIZE), int(reference.shape[0]*ratio)))\nkp_r, des_r = orb.detectAndCompute(reference, None)\n\n\ndef process(content, app):\n if not isinstance(content, unicode):\n return []\n image_data = re.sub('^data:image/.+;base64,', '', content).decode('base64')\n image = Image.open(cStringIO.StringIO(image_data))\n image = cv2.cvtColor(np.array(image), 2)\n # cv2.imwrite('image.jpg', image)\n\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n\n faces = cascade.detectMultiScale(image, 1.03, 10, minSize=(15, 15))\n\n if(len(faces) <= 0):\n return []\n app.logger.info('faces {0}'.format(len(faces)))\n\n rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in faces])\n pick = non_max_suppression(rects, probs=None, overlapThresh=0.15)\n app.logger.info('pick {0}'.format(len(pick)))\n\n good = []\n for (x, y, x2, y2) in pick:\n\n obj = gray[(y-IMAGE_PADDING):(y2+IMAGE_PADDING),\n (x-IMAGE_PADDING):(x2+IMAGE_PADDING)]\n if obj.shape[0] == 0 or obj.shape[1] == 0:\n continue\n ratio = IMAGE_SIZE/obj.shape[1]\n obj = cv2.resize(obj, (int(IMAGE_SIZE), int(obj.shape[0]*ratio)))\n # find the keypoints and descriptors for object\n kp_o, des_o = orb.detectAndCompute(obj, None)\n if len(kp_o) == 0:\n continue\n\n # match descriptors\n matches = bf.match(des_r, des_o)\n app.logger.info('matches {0}'.format(len(matches)))\n if(len(matches) >= MATCH_THRESHOLD):\n good.append(\n {'x': x*1, 'y': y*1, 'width': (x2-x)*1, 'height': (y2-y)*1})\n\n # for f in good:\n # cv2.rectangle(\n # image,\n # (f.get('x'), f.get('y')),\n # (f.get('width'), f.get('height')),\n # (0, 255, 0), 6)\n # cv2.imwrite('image.jpg', image)\n app.logger.info('good {0}'.format(len(good)))\n return good\n","sub_path":"video3.py","file_name":"video3.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"133395621","text":"\"\"\"landsat_mosaic_tiler.utils: utility functions.\"\"\"\n\nimport hashlib\nimport json\nfrom typing import Any, Tuple\nfrom urllib.parse import urlencode\n\nimport numpy\nfrom rio_color.operations import parse_operations\nfrom rio_color.utils import scale_dtype, to_math_type\nfrom rio_tiler.utils import linear_rescale\n\n\ndef get_tilejson(mosaic_def, url, tile_scale, tile_format, host, path=\"\", **kwargs):\n \"\"\"Construct tilejson definition\n\n Note, this is mostly copied from a PR to cogeo-mosaic-tiler. Could be imported from\n there in the future.\n \"\"\"\n bounds = mosaic_def[\"bounds\"]\n center = [\n (bounds[0] + bounds[2]) / 2,\n (bounds[1] + bounds[3]) / 2,\n mosaic_def[\"minzoom\"],\n ]\n\n kwargs.update({\"url\": url})\n\n if tile_format in [\"pbf\", \"mvt\"]:\n tile_url = f\"{host}{path}/{{z}}/{{x}}/{{y}}.{tile_format}\"\n elif tile_format in [\"png\", \"jpg\", \"webp\", \"tif\", \"npy\"]:\n tile_url = f\"{host}{path}/{{z}}/{{x}}/{{y}}@{tile_scale}x.{tile_format}\"\n else:\n tile_url = f\"{host}{path}/{{z}}/{{x}}/{{y}}@{tile_scale}x\"\n\n qs = urlencode(list(kwargs.items()))\n if qs:\n tile_url += f\"?{qs}\"\n\n meta = {\n \"bounds\": bounds,\n \"center\": center,\n \"maxzoom\": mosaic_def[\"maxzoom\"],\n \"minzoom\": mosaic_def[\"minzoom\"],\n \"name\": url,\n \"tilejson\": \"2.1.0\",\n \"tiles\": [tile_url],\n }\n return (\"OK\", \"application/json\", json.dumps(meta))\n\n\ndef get_hash(**kwargs: Any) -> str:\n \"\"\"Create hash from dict.\"\"\"\n return hashlib.sha224(\n json.dumps(kwargs, sort_keys=True, default=str).encode()\n ).hexdigest()\n\n\ndef post_process_tile(\n tile: numpy.ndarray,\n mask: numpy.ndarray,\n rescale: str = None,\n color_formula: str = None,\n) -> Tuple[numpy.ndarray, numpy.ndarray]:\n \"\"\"Tile data post processing.\"\"\"\n if rescale:\n rescale_arr = (tuple(map(float, rescale.split(\",\"))),) * tile.shape[0]\n for bdx in range(tile.shape[0]):\n tile[bdx] = numpy.where(\n mask,\n linear_rescale(\n tile[bdx], in_range=rescale_arr[bdx], out_range=[0, 255]\n ),\n 0,\n )\n tile = tile.astype(numpy.uint8)\n\n if color_formula:\n if issubclass(tile.dtype.type, numpy.floating):\n tile = tile.astype(numpy.int16)\n\n # make sure one last time we don't have\n # negative value before applying color formula\n tile[tile < 0] = 0\n for ops in parse_operations(color_formula):\n tile = scale_dtype(ops(to_math_type(tile)), numpy.uint8)\n\n return tile\n","sub_path":"landsat_mosaic_tiler/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"2040253","text":"from datetime import datetime, timedelta\nimport sys\nimport mybook\n\n\ndef create_daily_journal(date, content=''):\n \"\"\"\n Create a daily journal of given date. \n Creation time will be equal to the date. \n\n @date: datetime object\n @content: string, when empty, load from local template\n @return: (title, content, created_time)\n \"\"\"\n title = date.strftime('%Y.%m.%d')\n if not content:\n content = open('template.daily_journal.html', 'r').read()\n return (title, content, date)\n\n\ndef create_weekly_summary(date, content=''):\n \"\"\"\n Create a weekly summary journal of given date. \n Creation time will be equal to the date. \n\n @date: datetime object\n @content: string, when empty, load from local template\n @return: (title, content, created_time)\n \"\"\"\n title = date.strftime('%Y.%m.%d Weekly Summary')\n if not content:\n content = open('template.weekly_summary.html', 'r').read()\n return (title, content, date)\n\n\nif __name__ == '__main__':\n if len(sys.argv) == 1:\n print('Generate journals template for next 7 days')\n dt = datetime.today()\n elif len(sys.argv) == 2:\n dt = datetime.strptime(sys.argv[1], '%Y-%m-%d')\n\n mybook = mybook.MyBook()\n\n dt = datetime(dt.year, dt.month, dt.day)\n end = dt + timedelta(days=7)\n while dt <= end:\n print('Create Daily Journal: %s' % dt.strftime('%Y-%m-%d'))\n title, content, created = create_daily_journal(dt)\n mybook.create_note(title, content, created=created, notebook_name='Memories')\n if dt.weekday() == 6:\n print('Create Weely Summary: %s' % dt.strftime('%Y-%m-%d'))\n title, content, created = create_weekly_summary(dt + timedelta(seconds=1))\n mybook.create_note(title, content, created=created, notebook_name='Memories')\n dt += timedelta(days=1)\n","sub_path":"Evernote/JournalTemplate.py","file_name":"JournalTemplate.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"365180798","text":"# Import sample infrastructure\nfrom itertools import product\n\nfrom microscopemetrics.samples import *\n\nfrom typing import Union, Tuple, List\n\n# Import analysis tools\nimport numpy as np\nfrom pandas import DataFrame\nfrom skimage.transform import hough_line # hough_line_peaks, probabilistic_hough_line\nfrom scipy.signal import find_peaks\nfrom scipy.optimize import curve_fit\nfrom scipy.interpolate import griddata\nfrom statistics import median, mean\nfrom microscopemetrics.analysis.tools import segment_image, compute_distances_matrix, compute_spots_properties\nfrom ..utilities.utilities import multi_airy_fun, airy_fun\n\n\nclass ArgolightConfigurator(Configurator):\n \"\"\"This class handles the configuration properties of the argolight sample\n - Defines configuration properties\n - Helps in the generation of analysis_config files\"\"\"\n\n CONFIG_SECTION = \"ARGOLIGHT\"\n\n def define_metadata(self):\n metadata_defs = [\n {}\n ]\n\n def __init__(self, config):\n super().__init__(config)\n\n\n@ArgolightConfigurator.register_sample_analysis\nclass ArgolightBAnalysis(Analysis):\n \"\"\"This class handles the analysis of the Argolight sample pattern B\n \"\"\"\n\n def __init__(self):\n super().__init__(output_description=\"Analysis output of the 'SPOTS' matrix (pattern B) from the argolight sample. \"\n \"It contains chromatic shifts and homogeneity.\"\n )\n self.add_requirement(name='spots_distance',\n description='Distance between argolight spots',\n data_type=float,\n units='MICRON',\n optional=False,\n default=None)\n self.add_requirement(name='pixel_size',\n description='Physical size of the voxel in z, y and x',\n data_type=Tuple[float, float, float],\n units='MICRON',\n optional=False,\n default=None)\n self.add_requirement(name='sigma',\n description='Smoothing factor for objects detection',\n data_type=Tuple[float, float, float],\n optional=True,\n default=(1, 3, 3))\n self.add_requirement(name='lower_threshold_correction_factors',\n description='Correction factor for the lower thresholds. Must be a tuple with len = nr '\n 'of channels or a float if all equal',\n data_type=Union[List[float], Tuple[float], float],\n optional=True,\n default=None)\n self.add_requirement(name='upper_threshold_correction_factors',\n description='Correction factor for the upper thresholds. Must be a tuple with len = nr '\n 'of channels or a float if all equal',\n data_type=Union[List[float], Tuple[float], float],\n optional=True,\n default=None)\n self.add_requirement(name='remove_center_cross',\n description='Remove the center cross found in some Argolight patterns',\n data_type=bool,\n optional=True,\n default=False)\n\n @register_image_analysis\n def run(self):\n logger.info(\"Validating requirements...\")\n if not self.validate_requirements():\n logger.error(\"Metadata requirements ara not valid\")\n return False\n\n logger.info(\"Analyzing spots image...\")\n\n # Calculating the distance between spots in pixels with a security margin\n min_distance = round(\n (self.get_metadata_values('spots_distance') * 0.3) / max(self.get_metadata_values(\"pixel_size\")[-2:])\n )\n\n # Calculating the maximum tolerated distance in microns for the same spot in a different channels\n max_distance = self.get_metadata_values(\"spots_distance\") * 0.4\n\n labels = segment_image(\n image=self.input.data['argolight_b'],\n min_distance=min_distance,\n sigma=self.get_metadata_values('sigma'),\n method=\"local_max\",\n low_corr_factors=self.get_metadata_values(\"lower_threshold_correction_factors\"),\n high_corr_factors=self.get_metadata_values(\"upper_threshold_correction_factors\"),\n )\n\n self.output.append(model.Image(name=list(self.input.data.keys())[0],\n description=\"Labels image with detected spots. \"\n \"Image intensities correspond to roi labels.\",\n data=labels)\n )\n\n spots_properties, spots_positions = compute_spots_properties(\n image=self.input.data['argolight_b'], labels=labels,\n remove_center_cross=self.get_metadata_values('remove_center_cross'),\n )\n\n distances_df = compute_distances_matrix(\n positions=spots_positions,\n max_distance=max_distance,\n pixel_size=self.get_metadata_values('pixel_size'),\n )\n\n properties_kv = {}\n properties_df = DataFrame()\n\n for ch, ch_spot_props in enumerate(spots_properties):\n ch_df = DataFrame()\n ch_df['channel'] = [ch for _ in ch_spot_props]\n ch_df[\"mask_labels\"] = [p[\"label\"] for p in ch_spot_props]\n ch_df[\"volume\"] = [p[\"area\"] for p in ch_spot_props]\n ch_df[\"roi_volume_units\"] = \"VOXEL\"\n ch_df[\"max_intensity\"] = [p[\"max_intensity\"] for p in ch_spot_props]\n ch_df[\"min_intensity\"] = [p[\"min_intensity\"] for p in ch_spot_props]\n ch_df[\"mean_intensity\"] = [p[\"mean_intensity\"] for p in ch_spot_props]\n ch_df[\"integrated_intensity\"] = [p[\"integrated_intensity\"] for p in ch_spot_props]\n ch_df[\"z_weighted_centroid\"] = [p[\"weighted_centroid\"][0] for p in ch_spot_props]\n ch_df[\"y_weighted_centroid\"] = [p[\"weighted_centroid\"][1] for p in ch_spot_props]\n ch_df[\"x_weighted_centroid\"] = [p[\"weighted_centroid\"][2] for p in ch_spot_props]\n ch_df[\"roi_weighted_centroid_units\"] = \"PIXEL\"\n\n # Key metrics for spots intensities\n properties_kv[f\"nr_of_spots_ch{ch:02d}\"] = len(ch_df)\n properties_kv[f\"max_intensity_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].max().item()\n properties_kv[f\"max_intensity_roi_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].argmax().item()\n properties_kv[f\"min_intensity_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].min().item()\n properties_kv[f\"min_intensity_roi_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].argmin().item()\n properties_kv[f\"mean_intensity_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].mean().item()\n properties_kv[f\"median_intensity_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].median().item()\n properties_kv[f\"std_mean_intensity_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].std().item()\n properties_kv[f\"mad_mean_intensity_ch{ch:02d}\"] = ch_df[\"integrated_intensity\"].mad().item()\n properties_kv[f\"min-max_intensity_ratio_ch{ch:02d}\"] = (properties_kv[f\"min_intensity_ch{ch:02d}\"] /\n properties_kv[f\"max_intensity_ch{ch:02d}\"])\n\n properties_df = properties_df.append(ch_df)\n\n channel_shapes = [model.Point(x=p[\"weighted_centroid\"][2].item(),\n y=p[\"weighted_centroid\"][1].item(),\n z=p[\"weighted_centroid\"][0].item(),\n c=ch,\n label=f'{p[\"label\"]}')\n for p in ch_spot_props\n ]\n self.output.append(model.Roi(name=f'Centroids_ch{ch:03d}',\n description=f\"weighted centroids channel {ch}\",\n shapes=channel_shapes)\n )\n\n distances_kv = {\"distance_units\": self.get_metadata_units('pixel_size')}\n\n for a, b in product(distances_df.channel_a.unique(), distances_df.channel_b.unique()):\n temp_df = distances_df[(distances_df.channel_a == a) & (distances_df.channel_b == b)]\n a = int(a)\n b = int(b)\n\n distances_kv[f'mean_3d_dist_ch{a:02d}_ch{b:02d}'] = temp_df.dist_3d.mean().item()\n distances_kv[f'median_3d_dist_ch{a:02d}_ch{b:02d}'] = temp_df.dist_3d.median().item()\n distances_kv[f'std_3d_dist_ch{a:02d}_ch{b:02d}'] = temp_df.dist_3d.std().item()\n distances_kv[f'mad_3d_dist_ch{a:02d}_ch{b:02d}'] = temp_df.dist_3d.mad().item()\n distances_kv[f'mean_z_dist_ch{a:02d}_ch{b:02d}'] = temp_df.z_dist.mean().item()\n distances_kv[f'median_z_dist_ch{a:02d}_ch{b:02d}'] = temp_df.z_dist.median().item()\n distances_kv[f'std_z_dist_ch{a:02d}_ch{b:02d}'] = temp_df.z_dist.std().item()\n distances_kv[f'mad_z_dist_ch{a:02d}_ch{b:02d}'] = temp_df.z_dist.mad().item()\n\n self.output.append(model.KeyValues(name='Intensity Key Annotations',\n description='Key Intensity Measurements on Argolight D spots',\n key_values=properties_kv)\n )\n\n self.output.append(model.KeyValues(name='Distances Key Annotations',\n description='Key Distance Measurements on Argolight D spots',\n key_values=distances_kv)\n )\n\n self.output.append(model.Table(name='Properties',\n description=\"Analysis_argolight_D_properties\",\n table=properties_df)\n )\n\n self.output.append(model.Table(name='Distances',\n description=\"Analysis_argolight_D_distances\",\n table=distances_df)\n )\n\n return True\n\n\n@ArgolightConfigurator.register_sample_analysis\nclass ArgolightEAnalysis(Analysis):\n \"\"\"This class handles the analysis of the Argolight sample pattern E with lines along the X or Y axis\n \"\"\"\n def __init__(self):\n super().__init__(\n output_description=\"Analysis output of the lines (pattern E) from the argolight sample. \"\n \"It contains resolution data on the axis indicated:\"\n \"- axis 1 = Y resolution = lines along X axis\"\n \"- axis 2 = X resolution = lines along Y axis\"\n )\n self.add_requirement(name='pixel_size',\n description='Physical size of the voxel in z, y and x',\n data_type=Tuple[float, float, float],\n units='MICRON',\n optional=False\n )\n self.add_requirement(name='axis',\n description='axis along which resolution is being measured. 1=Y, 2=X',\n data_type=int,\n optional=False\n )\n self.add_requirement(name='measured_band',\n description='Fraction of the image across which intensity profiles are measured',\n data_type=float,\n optional=True,\n default=.4\n )\n\n @register_image_analysis\n def run(self):\n \"\"\"A intermediate function to specify the axis to be analyzed\"\"\"\n\n logger.info(\"Validating requirements...\")\n if not self.validate_requirements():\n logger.error(\"Metadata requirements ara not valid\")\n return False\n\n logger.info(\"Analyzing resolution...\")\n\n return self._analyze_resolution(image=self.input.data['argolight_e'],\n axis=self.get_metadata_values('axis'),\n measured_band=self.get_metadata_values(\"measured_band\"),\n pixel_size=self.get_metadata_values('pixel_size'),\n pixel_size_units=self.get_metadata_units('pixel_size'))\n\n def _analyze_resolution(self, image, axis, measured_band, pixel_size, pixel_size_units):\n (\n profiles,\n z_planes,\n peak_positions,\n peak_heights,\n resolution_values,\n resolution_indexes,\n resolution_method,\n ) = _compute_resolution(\n image=image,\n axis=axis,\n measured_band=measured_band,\n prominence=0.264,\n do_angle_refinement=False,\n )\n # resolution in native units\n resolution_values = [x * pixel_size[axis] for x in resolution_values]\n\n key_values = {\n f\"ch{ch:02d}_{resolution_method}_resolution\": res.item()\n for ch, res in enumerate(resolution_values)\n }\n\n key_values[\"resolution_units\"] = pixel_size_units\n key_values[\"resolution_axis\"] = axis\n key_values[\"measured_band\"] = measured_band\n\n for ch, indexes in enumerate(resolution_indexes):\n key_values[f\"peak_positions_ch{ch:02d}\"] = [\n (peak_positions[ch][ind].item(), peak_positions[ch][ind + 1].item())\n for ind in indexes\n ]\n key_values[f\"peak_heights_ch{ch:02d}\"] = [\n (peak_heights[ch][ind].item(), peak_heights[ch][ind + 1].item())\n for ind in indexes\n ]\n key_values[f\"focus_ch{ch:02d}\"] = z_planes[ch].item()\n\n out_tables = {}\n\n # Populate tables and rois\n for ch, profile in enumerate(profiles):\n out_tables.update(_profile_to_table(profile, ch))\n shapes = []\n for pos in key_values[f\"peak_positions_ch{ch:02d}\"]:\n for peak in pos:\n # Measurements are taken at center of pixel so we add .5 pixel to peak positions\n if axis == 1: # Y resolution -> horizontal rois\n axis_len = image.shape[-2]\n x1_pos = int(\n (axis_len / 2)\n - (axis_len * measured_band / 2)\n )\n y1_pos = peak + 0.5\n x2_pos = int(\n (axis_len / 2)\n + (axis_len * measured_band / 2)\n )\n y2_pos = peak + 0.5\n elif axis == 2: # X resolution -> vertical rois\n axis_len = image.shape[-1]\n y1_pos = int(\n (axis_len / 2)\n - (axis_len * measured_band / 2)\n )\n x1_pos = peak + 0.5\n y2_pos = int(\n (axis_len / 2)\n + (axis_len * measured_band / 2)\n )\n x2_pos = peak + 0.5\n\n shapes.append(model.Line(x1=x1_pos,\n y1=y1_pos,\n x2=x2_pos,\n y2=y2_pos,\n z=z_planes[ch],\n c=ch)\n )\n\n self.output.append(model.Roi(name=f\"Peaks_ch{ch:03d}\",\n description=f\"Lines where highest Rayleigh resolution was found in channel {ch}\",\n shapes=shapes)\n )\n self.output.append(model.KeyValues(name='Key-Value Annotations',\n description=f'Measurements on Argolight E pattern along axis={axis}',\n key_values=key_values)\n )\n self.output.append(model.Table(name='Profiles',\n description='Raw and fitted profiles across the center of the image along the '\n 'defined axis',\n table=DataFrame.from_dict(out_tables))\n )\n\n return True\n\n\nclass ArgolightReporter(Reporter):\n \"\"\"Reporter subclass to produce Argolight sample figures\"\"\"\n\n def __init__(self):\n image_report_to_func = {\n \"spots\": self.full_report_spots,\n \"vertical_resolution\": self.full_report_vertical_resolution,\n \"horizontal_resolution\": self.full_report_horizontal_resolution,\n }\n\n super().__init__(image_report_to_func=image_report_to_func)\n\n def produce_image_report(self, image):\n pass\n\n def full_report_spots(self, image):\n pass\n\n def full_report_vertical_resolution(self, image):\n pass\n\n def full_report_horizontal_resolution(self, image):\n pass\n\n def plot_homogeneity_map(self, image):\n nr_channels = image.getSizeC()\n x_dim = image.getSizeX()\n y_dim = image.getSizeY()\n\n tables = self.get_tables(\n image, namespace_start=\"metrics\", name_filter=\"properties\"\n )\n if len(tables) != 1:\n raise Exception(\n \"There are none or more than one properties tables. Verify data integrity.\"\n )\n table = tables[0]\n\n row_count = table.getNumberOfRows()\n col_names = [c.name for c in table.getHeaders()]\n wanted_columns = [\n \"channel\",\n \"max_intensity\",\n \"mean_intensity\",\n \"integrated_intensity\",\n \"x_weighted_centroid\",\n \"y_weighted_centroid\",\n ]\n\n fig, axes = plt.subplots(\n ncols=nr_channels, nrows=3, squeeze=False, figsize=(3 * nr_channels, 9)\n )\n\n for ch in range(nr_channels):\n data = table.slice(\n [col_names.index(w_col) for w_col in wanted_columns],\n table.getWhereList(\n condition=f\"channel=={ch}\",\n variables={},\n start=0,\n stop=row_count,\n step=0,\n ),\n )\n max_intensity = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"max_intensity\"\n ]\n )\n integrated_intensity = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"integrated_intensity\"\n ]\n )\n x_positions = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"x_weighted_centroid\"\n ]\n )\n y_positions = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"y_weighted_centroid\"\n ]\n )\n grid_x, grid_y = np.mgrid[0:x_dim, 0:y_dim]\n image_intensities = get_intensities(image, c_range=ch, t_range=0).max(0)\n\n try:\n interpolated_max_int = griddata(\n np.stack((x_positions, y_positions), axis=1),\n max_intensity,\n (grid_x, grid_y),\n method=\"linear\",\n )\n interpolated_intgr_int = griddata(\n np.stack((x_positions, y_positions), axis=1),\n integrated_intensity,\n (grid_x, grid_y),\n method=\"linear\",\n )\n except Exception as e:\n # TODO: Log a warning\n interpolated_max_int = np.zeros((256, 256))\n\n ax = axes.ravel()\n ax[ch] = plt.subplot(3, 4, ch + 1)\n\n ax[ch].imshow(np.squeeze(image_intensities), cmap=\"gray\")\n ax[ch].set_title(\"MIP_\" + str(ch))\n\n ax[ch + nr_channels].imshow(\n np.flipud(interpolated_intgr_int),\n extent=(0, x_dim, y_dim, 0),\n origin=\"lower\",\n cmap=cm.hot,\n vmin=np.amin(integrated_intensity),\n vmax=np.amax(integrated_intensity),\n )\n ax[ch + nr_channels].plot(x_positions, y_positions, \"k.\", ms=2)\n ax[ch + nr_channels].set_title(\"Integrated_int_\" + str(ch))\n\n ax[ch + 2 * nr_channels].imshow(\n np.flipud(interpolated_max_int),\n extent=(0, x_dim, y_dim, 0),\n origin=\"lower\",\n cmap=cm.hot,\n vmin=np.amin(image_intensities),\n vmax=np.amax(image_intensities),\n )\n ax[ch + 2 * nr_channels].plot(x_positions, y_positions, \"k.\", ms=2)\n ax[ch + 2 * nr_channels].set_title(\"Max_int_\" + str(ch))\n\n plt.show()\n\n def plot_distances_map(self, image):\n nr_channels = image.getSizeC()\n x_dim = image.getSizeX()\n y_dim = image.getSizeY()\n\n tables = get_tables(image, namespace_start=\"metrics\", name_filter=\"distances\")\n if len(tables) != 1:\n raise Exception(\n \"There are none or more than one distances tables. Verify data integrity.\"\n )\n table = tables[0]\n row_count = table.getNumberOfRows()\n col_names = [c.name for c in table.getHeaders()]\n\n # We need the positions too\n pos_tables = get_tables(\n image, namespace_start=\"metrics\", name_filter=\"properties\"\n )\n if len(tables) != 1:\n raise Exception(\n \"There are none or more than one positions tables. Verify data integrity.\"\n )\n pos_table = pos_tables[0]\n pos_row_count = pos_table.getNumberOfRows()\n pos_col_names = [c.name for c in pos_table.getHeaders()]\n\n fig, axes = plt.subplots(\n ncols=nr_channels - 1,\n nrows=nr_channels,\n squeeze=False,\n figsize=((nr_channels - 1) * 3, nr_channels * 3),\n )\n\n ax_index = 0\n for ch_A in range(nr_channels):\n pos_data = pos_table.slice(\n [\n pos_col_names.index(w_col)\n for w_col in [\n \"channel\",\n \"mask_labels\",\n \"x_weighted_centroid\",\n \"y_weighted_centroid\",\n ]\n ],\n pos_table.getWhereList(\n condition=f\"channel=={ch_A}\",\n variables={},\n start=0,\n stop=pos_row_count,\n step=0,\n ),\n )\n\n mask_labels = np.array(\n [\n val\n for col in pos_data.columns\n for val in col.values\n if col.name == \"mask_labels\"\n ]\n )\n x_positions = np.array(\n [\n val\n for col in pos_data.columns\n for val in col.values\n if col.name == \"x_weighted_centroid\"\n ]\n )\n y_positions = np.array(\n [\n val\n for col in pos_data.columns\n for val in col.values\n if col.name == \"y_weighted_centroid\"\n ]\n )\n positions_map = np.stack((x_positions, y_positions), axis=1)\n\n for ch_B in [i for i in range(nr_channels) if i != ch_A]:\n data = table.slice(\n list(range(len(col_names))),\n table.getWhereList(\n condition=f\"(channel_A=={ch_A})&(channel_B=={ch_B})\",\n variables={},\n start=0,\n stop=row_count,\n step=0,\n ),\n )\n labels_map = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"ch_A_roi_labels\"\n ]\n )\n labels_map += 1 # Mask labels are augmented by one as 0 is background\n distances_map_3d = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"distance_3d\"\n ]\n )\n distances_map_x = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"distance_x\"\n ]\n )\n distances_map_y = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"distance_y\"\n ]\n )\n distances_map_z = np.array(\n [\n val\n for col in data.columns\n for val in col.values\n if col.name == \"distance_z\"\n ]\n )\n\n filtered_positions = positions_map[\n np.intersect1d(\n mask_labels, labels_map, assume_unique=True, return_indices=True\n )[1],\n :,\n ]\n\n grid_x, grid_y = np.mgrid[0:x_dim:1, 0:y_dim:1]\n interpolated = griddata(\n filtered_positions,\n distances_map_3d,\n (grid_x, grid_y),\n method=\"cubic\",\n )\n\n ax = axes.ravel()\n ax[ax_index].imshow(\n np.flipud(interpolated),\n extent=(0, x_dim, y_dim, 0),\n origin=\"lower\",\n cmap=cm.hot,\n vmin=np.amin(distances_map_3d),\n vmax=np.amax(distances_map_3d),\n )\n ax[ax_index].set_title(f\"Distance Ch{ch_A}-Ch{ch_B}\")\n\n ax_index += 1\n\n plt.show()\n\n\ndef _profile_to_table(profile, channel):\n table = {f'raw_profile_ch{channel:02d}': [v.item() for v in profile[0, :]]}\n\n for p in range(1, profile.shape[0]):\n table.update({f'fitted_profile_ch{channel:03d}_peak{p:03d}': [v.item() for v in profile[p, :]]})\n\n return table\n\n\ndef _fit(\n profile, peaks_guess, amp=4, exp=2, lower_amp=3, upper_amp=5, center_tolerance=1\n):\n guess = []\n lower_bounds = []\n upper_bounds = []\n for p in peaks_guess:\n guess.append(p) # peak center\n guess.append(amp) # peak amplitude\n lower_bounds.append(p - center_tolerance)\n lower_bounds.append(lower_amp)\n upper_bounds.append(p + center_tolerance)\n upper_bounds.append(upper_amp)\n\n x = np.linspace(0, profile.shape[0], profile.shape[0], endpoint=False)\n\n popt, pcov = curve_fit(\n multi_airy_fun, x, profile, p0=guess, bounds=(lower_bounds, upper_bounds)\n )\n\n opt_peaks = popt[::2]\n # opt_amps = [a / 4 for a in popt[1::2]] # We normalize back the amplitudes to the unity\n opt_amps = popt[1::2]\n\n fitted_profiles = np.zeros((len(peaks_guess), profile.shape[0]))\n for i, (c, a) in enumerate(zip(opt_peaks, opt_amps)):\n fitted_profiles[i, :] = airy_fun(x, c, a)\n\n return opt_peaks, opt_amps, fitted_profiles\n\n\ndef _compute_channel_resolution(\n channel, axis, prominence, measured_band, do_fitting=True, do_angle_refinement=False\n):\n \"\"\"Computes the resolution on a pattern of lines with increasing separation\"\"\"\n # find the most contrasted z-slice\n z_stdev = np.std(channel, axis=(1, 2))\n z_focus = np.argmax(z_stdev)\n focus_slice = channel[z_focus]\n\n # TODO: verify angle and correct\n if do_angle_refinement:\n # Set a precision of 0.1 degree.\n tested_angles = np.linspace(-np.pi / 2, np.pi / 2, 1800)\n h, theta, d = hough_line(focus_slice, theta=tested_angles)\n\n # Cut a band of that found peak\n # Best we can do now is just to cut a band in the center\n # We create a profiles along which we average signal\n axis_len = focus_slice.shape[-axis]\n weight_profile = np.zeros(axis_len)\n # Calculates a band of relative width 'image_fraction' to integrate the profile\n weight_profile[\n int((axis_len / 2) - (axis_len * measured_band / 2)): int(\n (axis_len / 2) + (axis_len * measured_band / 2)\n )\n ] = 1\n profile = np.average(focus_slice, axis=-axis, weights=weight_profile)\n\n normalized_profile = (profile - np.min(profile)) / np.ptp(profile)\n\n # Find peaks: We implement Rayleigh limits that will be refined downstream\n peak_positions, properties = find_peaks(\n normalized_profile, height=0.3, distance=2, prominence=prominence / 4,\n )\n\n # From the properties we are interested in the amplitude\n # peak_heights = [h for h in properties['peak_heights']]\n ray_filtered_peak_pos = []\n ray_filtered_peak_heights = []\n\n for peak, height, prom in zip(\n peak_positions, properties[\"peak_heights\"], properties[\"prominences\"]\n ):\n if (\n prom / height\n ) > prominence: # This is calculating the prominence in relation to the local intensity\n ray_filtered_peak_pos.append(peak)\n ray_filtered_peak_heights.append(height)\n\n peak_positions = ray_filtered_peak_pos\n peak_heights = ray_filtered_peak_heights\n\n if do_fitting:\n peak_positions, peak_heights, fitted_profiles = _fit(\n normalized_profile, peak_positions\n )\n normalized_profile = np.append(\n np.expand_dims(normalized_profile, 0), fitted_profiles, axis=0\n )\n\n # Find the closest peaks to return it as a measure of resolution\n peaks_distances = [\n abs(a - b) for a, b in zip(peak_positions[0:-2], peak_positions[1:-1])\n ]\n res = min(peaks_distances) # TODO: capture here the case where there are no peaks!\n res_indices = [i for i, x in enumerate(peaks_distances) if x == res]\n\n return normalized_profile, z_focus, peak_positions, peak_heights, res, res_indices\n\n\ndef _compute_resolution(\n image, axis, measured_band, prominence, do_angle_refinement=False\n):\n profiles = list()\n z_planes = []\n peaks_positions = list()\n peaks_heights = []\n resolution_values = []\n resolution_indexes = []\n resolution_method = \"rayleigh\"\n\n for c in range(image.shape[1]): # TODO: Deal with Time here\n prof, zp, pk_pos, pk_heights, res, res_ind = _compute_channel_resolution(\n channel=np.squeeze(image[:, c, ...]),\n axis=axis,\n prominence=prominence,\n measured_band=measured_band,\n do_angle_refinement=do_angle_refinement,\n )\n profiles.append(prof)\n z_planes.append(zp)\n peaks_positions.append(pk_pos)\n peaks_heights.append(pk_heights)\n resolution_values.append(res)\n resolution_indexes.append(res_ind)\n\n return (\n profiles,\n z_planes,\n peaks_positions,\n peaks_heights,\n resolution_values,\n resolution_indexes,\n resolution_method,\n )\n\n# Calculate 2D FFT\n# slice_2d = raw_img[17, ...].reshape([1, n_channels, x_size, y_size])\n# fft_2D = fft_2d(slice_2d)\n\n# Calculate 3D FFT\n# fft_3D = fft_3d(spots_image)\n#\n# plt.imshow(np.log(fft_3D[2, :, :, 1])) # , cmap='hot')\n# # plt.imshow(np.log(fft_3D[2, 23, :, :])) # , cmap='hot')\n# plt.show()\n#\n","sub_path":"microscopemetrics/samples/argolight.py","file_name":"argolight.py","file_ext":"py","file_size_in_byte":33120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"115938556","text":"\"\"\"\nStudent Name: Ethan Matthews\nProgram Title: GRAPHICAL USER INTERFACE (GUI) PROGRAMMING - Final Project\nDescription: Use PyQT and Visual Studio Code to create a graphical application\n (.pyw and supporting .py files) in which you’ll code the solution to this program. \n\"\"\"\n\n\"\"\"\n 1. Create muliple objects in pyqt5. List Widget x1, list labels x8, push buton x1, scroll bar x1, menu actions x2, line edit x1,\n radio buttons x2, combo box x1, group box x1 and one object for flag display (not sure what that will be yet).\n 2. Add slots for all objects that hav actions when program runs. Some lables are static and won't need any slots.\n 3. Connect slots with appropriate functions. Any Object that has an action when the program is running will have there own functions.\n 4. Add Helper functions for reusable calculations I.E percent of world population, conversions between miles and KM, loading and saving from files\n and when the line changes in the list widget.\n 5. Opaque object will need to be loaded automatically to cover all controls until user loads a file. \n 6. CSS will need to be applied to GUI interface for nice look. (Done in pyqt5 itself.)\n 7. Add comments to code when program is almost complete, or through-out development.\n 8. BACKUP ALL WORK ON ONEDRIVE/GITHUB!!!!!\n 9. Upload phases to git hub and bright space as they're due.\n10. Pray to PC gods that your hard drive doesn't buy the Farm. (Sacrifice at the very least, one goat and three chickens per week.) \n\"\"\" \n\nimport sys, csv\n\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox\n\nfrom PyQt5.QtGui import QPixmap\n\n#ADD IMPORT STATEMENT FOR YOUR GENERATED UI.PY FILE HERE\nimport Ui_Final_Project\n# ^^^^^^^^^^^ Change this!\n\n#CHANGE THE SECOND PARAMETER (Ui_ChangeMe) TO MATCH YOUR GENERATED UI.PY FILE\nclass MyForm(QMainWindow, Ui_Final_Project.Ui_MainWindow):\n# ^^^^^^^^^^^ Change this!\n\n CountriesList = []\n\n # DO NOT MODIFY THIS CODE\n def __init__(self, parent=None):\n super(MyForm, self).__init__(parent)\n self.setupUi(self)\n # END DO NOT MODIFY\n\n \n\n # ADD SLOTS HERE, indented to this level (ie. inside def __init__)\n self.actionLoad_File.triggered.connect(self.LoadCountryMenu_Triggered)\n self.actionSave_File.triggered.connect(self.SaveCountryMenu_Triggered)\n self.listWidgetCountry.currentRowChanged.connect(self.ListRow_Changed)\n self.listWidgetCountry.currentRowChanged.connect(self.flagImage)\n self.listWidgetCountry.currentRowChanged.connect(self.radioButton_Miles)\n self.listWidgetCountry.currentRowChanged.connect(self.ComoboBox_Mile_KM)\n self.radioButtonSquareMile.clicked.connect(self.radioButton_Miles)\n self.radioButtonSquareKM.clicked.connect(self.radioButton_KM)\n self.pushButtonUpdatePopulation.clicked.connect(self.upDateFile)\n self.verticalScrollBarCountryLists.sliderMoved.connect(self.listScroll)\n\n # ADD SLOT FUNCTIONS HERE\n # These are the functions your slots will point to\n # Indent to this level (ie. inside the class, at same level as def __init__)\n\n def LoadCountryMenu_Triggered(self):\n self.loadFromFile()\n self.LoadintoListWidget()\n self.actionLoad_File.setEnabled(False)\n\n def SaveCountryMenu_Triggered(self):\n pass\n\n def ListRow_Changed(self, Index):\n countryName = self.CountriesList[Index][0]\n totalPopulation = self.CountriesList[Index][1]\n totalAreaCountry = self.CountriesList[Index][2]\n\n countryPercent = self.countryPercentPop(totalPopulation, self.CountriesList)\n\n self.labelVarCountryName.setText(countryName)\n self.lineEditPopulation.setText(totalPopulation)\n self.labelVarTotalAreaIn.setText(\"{0:.1f}\".format(float(totalAreaCountry)))\n self.labelPercentPopDisplay.setText(countryPercent)\n \n def radioButton_Miles(self, Index):\n self.radioButtonSquareMile.setText(\"\")\n self.radioButtonSquareMile.setChecked(True)\n totalPopulation = self.CountriesList[Index][1]\n totalAreaCountry = self.CountriesList[Index][2]\n \n popPerSqrMile = float(totalPopulation) / float(totalAreaCountry)\n\n self.labelSquareAreaDisplay.setText(\"{0:.2f}\".format(popPerSqrMile))\n\n def radioButton_KM(self, Index):\n self.radioButtonSquareKM.setText(\"\")\n self.radioButtonSquareKM.setChecked(True)\n totalPopulation = self.CountriesList[Index][1]\n totalAreaCountry = self.CountriesList[Index][2]\n\n KMs = float(totalAreaCountry) * 2.59\n \n popPerSqrKM = float(totalPopulation) / KMs\n\n self.labelSquareAreaDisplay.setText(\"{0:.2f}\".format(popPerSqrKM))\n \n def ComoboBox_Mile_KM(self):\n self.comboBoxMilesToKM.addItem(\"Sq. Miles\")\n self.comboBoxMilesToKM.addItem(\"Sq. KM\")\n\n def upDateFile(self):\n pass\n\n def listScroll(self):\n pass\n\n def CheckedBox_Changed(self, state):\n pass\n\n def flagImage(self, Index):\n flagName = self.CountriesList[Index][0]\n space = \" \"\n underscore = \"_\"\n if flagName.__contains__(space):\n flagName = flagName.replace(space, underscore)\n countryflag = QPixmap(\"Flags\\{0}.png\".format(flagName))\n self.labelImage.setQPixmap(countryflag)\n else:\n countryflag = QPixmap(\"Flags\\{0}.png\".format(flagName))\n self.labelImage.setQPixmap(countryflag)\n\n\n#Example Slot Function\n# def SaveButton_Clicked(self):\n# Make a call to the Save() helper function here\n\n #ADD HELPER FUNCTIONS HERE\n # These are the functions the slot functions will call, to \n # contain the custom code that you'll write to make your progam work.\n # Indent to this level (ie. inside the class, at same level as def __init__)\n def loadFromFile(self):\n fileName = \"countries.txt\"\n accessMode = \"r\"\n with open(fileName, accessMode) as myFile:\n countryData = csv.reader(myFile)\n for row in countryData:\n self.CountriesList.append(row)\n\n def LoadintoListWidget(self):\n self.listWidgetCountry.clear()\n for personrow in self.CountriesList:\n self.listWidgetCountry.addItem(personrow[0])\n\n def countryPercentPop(self, totalPopulation, CountriesList):\n totalWorld = 0\n for counter in range(len(CountriesList)):\n countryPop = int(CountriesList[counter][1])\n totalWorld += countryPop\n countryPercent = float(totalPopulation) / totalWorld\n return str(\"{0:.4f}%\".format(countryPercent))\n\n def ToggleImage(self, state, Index):\n countryName = self.CountriesList[Index][0]\n if state == 2:\n image = QPixmap(\"images\\{0}.png\".format(countryName))\n else:\n image = QPixmap()\n\n self.labelImage.setPixmap(image)\n\n\n#Example Helper Function\n# def Save(self):\n# Implement the save functionality here\n\n# DO NOT MODIFY THIS CODE\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n the_form = MyForm()\n the_form.show()\n sys.exit(app.exec_())\n# END DO NOT MODIFY","sub_path":"Assignments/Final_Project_Ethan_Matthews/Final_Project_GUI-Laptop.pyw","file_name":"Final_Project_GUI-Laptop.pyw","file_ext":"pyw","file_size_in_byte":7188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"120121944","text":"import unittest\nfrom python.aios.skill.test.SkillTest import SkillTest\nimport pathlib\nimport os\n\n\nclass SomeTest(SkillTest):\n \"\"\" This test shows the simplest setup to run a basic skill unit test. \"\"\"\n\n def setUp(self) -> None:\n self.skill_config_path = os.path.join(pathlib.Path().absolute(), 'skill.yml')\n self.contract_path = os.path.join(pathlib.Path().absolute(), 'contract.dbs')\n self.handler_path = 'python.test.handler'\n\n def test_evaluate(self):\n skill_ref = SkillTest.get_skill(skill_config_path=self.skill_config_path,\n contract_path=self.contract_path,\n handler_path=self.handler_path,\n provision_parameter={\"ACTIVATE_SCORES\": \"activate\"})\n skill_ref.evaluate({\"data\": \"test\"})\n\n @unittest.skip(reason=\"testing validation\")\n def test_on_started(self):\n skill_ref = SkillTest.get_skill(skill_config_path=self.skill_config_path,\n contract_path=self.contract_path,\n handler_path=self.handler_path)\n skill_ref.on_started()\n\n @unittest.skip(reason=\"testing validation\")\n def test_on_stopped(self):\n skill_ref = SkillTest.get_skill(skill_config_path=self.skill_config_path,\n contract_path=self.contract_path,\n handler_path=self.handler_path)\n skill_ref.on_stopped()\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"python/test/skill_test.py","file_name":"skill_test.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"266363979","text":"import time\r\nimport urllib\r\nfrom selenium import webdriver\r\n\r\n#https://stackoverflow.com/questions/28070315/python-disable-images-in-selenium-google-chromedriver\r\n\r\n\r\nchrome_options = webdriver.ChromeOptions()\r\nchrome_options.add_argument('--disable-extensions')\r\npreferences = {\"profile.managed_default_content_settings.images\" : 2, \"safebrowsing.enabled\": True, \"profile.default_content_setting_values.geolocation\" :2 }\r\nchrome_options.add_experimental_option(\"prefs\", preferences)\r\ndriver = webdriver.Chrome('C:/Python/Drivers/chromedriver.exe', chrome_options=chrome_options)\r\n\r\n\r\nurl = \"https://www.danmurphys.com.au/current-offers?filters=variety(spirits)\"\r\n\r\ndriver.get(url)\r\n\r\nf = open(\"dan_murphys_spirits.txt\", \"w\")\r\n\r\ntime.sleep(1)\r\ndriver.refresh()\r\ntime.sleep(3)\r\n\r\n\r\nitems = driver.find_element_by_xpath(\"//span[@class='count bold']\")\r\nitems = items.text\r\n\r\nstr_len = len(items)\r\nitems = items[0:3]\r\n\r\npage = round(int(items)/20)\r\n\r\nprint(str(items))\r\nprint(page)\r\n\r\ncurrent_page = 1\r\n\r\nwhile (current_page <= page):\r\n x = 0\r\n max_len = len(driver.find_elements_by_xpath(\"//div[@class='product-content default-content']\"))\r\n\r\n while (x < (max_len*2)):\r\n\r\n brand = driver.find_elements_by_xpath(\"//div[@class='product-content default-content']/h2/a/span\")[x]\r\n brand = brand.text\r\n\r\n y = round(x/2)\r\n print(str(x) + ' | ' + str(y))\r\n\r\n link = driver.find_elements_by_xpath(\"//div[@class='product-content default-content']/h2/a/span/parent::a\")[y]\r\n link = link.get_attribute(\"href\")\r\n print(link)\r\n\r\n variant = driver.find_elements_by_xpath(\"//div[@class='product-content default-content']/h2/a/span\")[x+1]\r\n variant = variant.text\r\n\r\n driver.get(link)\r\n time.sleep(2)\r\n\r\n price = driver.find_elements_by_xpath(\"//div[@class='pack-breakdown ng-star-inserted']/p[@class='ng-star-inserted']\")[0]\r\n price = price.text\r\n\r\n print(price)\r\n\r\n x_pos = 0\r\n while (x_pos < (len(price) - 1)):\r\n sub_str = price[x_pos:(x_pos + 1)]\r\n if sub_str == ' ':\r\n end = x_pos\r\n break\r\n x_pos = x_pos + 1\r\n\r\n str_len = len(price)\r\n quantity = price[(str_len - 2):str_len]\r\n price = price[1:x_pos]\r\n\r\n if (quantity == 'Can') or (quantity == 'le'):\r\n quantity = 1\r\n\r\n quantity = str(quantity)\r\n\r\n print('price: ' + str(price))\r\n print('qty : ' + str(quantity))\r\n print('')\r\n\r\n print(brand)\r\n print(variant)\r\n print('')\r\n\r\n\r\n driver.get(url)\r\n time.sleep(2)\r\n\r\n f.write(price + \"\\n\")\r\n f.write(quantity + \"\\n\")\r\n f.write(brand + \"\\n\")\r\n f.write(variant + \"\\n\")\r\n f.write(link + \"\\n\")\r\n f.write(\"\\n\")\r\n x = x + 2\r\n\r\n if current_page < page:\r\n current_page += 1\r\n url = \"https://www.danmurphys.com.au/current-offers?filters=variety(spirits)&page=\" + str(current_page)\r\n driver.get(url)\r\n else:\r\n break\r\n\r\n time.sleep(2)\r\n\r\nf.close()\n\r\nprint('finshed')\r\n","sub_path":"dan_murphy_spirits.py","file_name":"dan_murphy_spirits.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"572364165","text":"import huffman\nimport bitio\nfrom util import *\n\nLOG_TAG = \"----- tests.py -----\"\n\ndef _get_tree_string(tree_node):\n \"\"\"Prints contents of huffman tree using inorder traversal.\"\"\"\n if isinstance(tree_node, huffman.TreeBranch):\n contents = [\n _get_tree_string(tree_node.left),\n \"~\",\n _get_tree_string(tree_node.right)\n ]\n return \"\".join(contents)\n elif isinstance(tree_node, huffman.TreeLeaf):\n if tree_node.value:\n return str(tree_node.value)\n else:\n return \"EOF\"\n return \"\"\n\n\ndef _test_read_encoding():\n \"\"\"Test that trees are decoded correctly.\"\"\"\n a_leaf, eof_leaf, b_leaf = huffman.TreeLeaf(\n ord('A')), huffman.TreeLeaf(None), huffman.TreeLeaf(ord('B'))\n tree_write = huffman.TreeBranch(\n huffman.TreeBranch(a_leaf, eof_leaf), b_leaf)\n\n TEST_FILE = \"_test_read_encoding.txt\"\n TEST_TAG = \"----- TEST: READ ENCODING -----\"\n\n encoded_tree = \"110101000001000101000010\"\n\n with open(TEST_FILE, 'wb') as fil:\n writer = bitio.BitWriter(fil)\n for c in encoded_tree:\n writer.writebit(True if c == \"1\" else False)\n writer.flush()\n\n with open(TEST_FILE, 'rb') as fil2:\n tree_read = read_tree(bitio.BitReader(fil2))\n\n assert(_get_tree_string(tree_write) == _get_tree_string(tree_read)\n ), \"{} Error - trees not the same.\".format(TEST_TAG)\n\n\ndef _test_write_encoding():\n \"\"\"Test that trees are encoded correctly.\"\"\"\n a_leaf, eof_leaf, b_leaf = huffman.TreeLeaf(\n ord('A')), huffman.TreeLeaf(None), huffman.TreeLeaf(ord('B'))\n tree_write = huffman.TreeBranch(\n huffman.TreeBranch(a_leaf, eof_leaf), b_leaf)\n\n TEST_FILE = \"_test_write_encoding.txt\"\n TEST_TAG = \"----- TEST: WRITE ENCODING -----\"\n\n encoded_tree = \"110101000001000101000010\"\n\n with open(TEST_FILE, 'wb') as fil:\n write_tree(tree_write, bitio.BitWriter(fil))\n\n with open(TEST_FILE, 'rb') as fil:\n reader = bitio.BitReader(fil)\n for c in encoded_tree:\n bit_read = reader.readbit()\n assert(bit_read == int(c)\n ), \"{} Error - bit read not the same\".format(TEST_TAG)\n\n\ndef _test_tree_read_write():\n \"\"\"Creates a huffman tree, uses write_tree() to write bitstring encoding of the tree\n to a textfile, and then decodes the written bit string with read_tree(). Raises an\n assertion error if the trees are not equal.\n\n Status: PASSING.\n\n Simple Tree (encoded as the bitstring 110101000001000101000010):\n\n o\n / \\\n o 'B'\n / \\\n 'A' EOF\n\n Notes:\n - Automatically generates a file '_test_read_write.txt' in the working directory.\n \"\"\"\n a_leaf, eof_leaf, b_leaf = huffman.TreeLeaf(\n ord('A')), huffman.TreeLeaf(None), huffman.TreeLeaf(ord('B'))\n tree_write = huffman.TreeBranch(\n huffman.TreeBranch(a_leaf, eof_leaf), b_leaf)\n\n TEST_FILE = \"_test_tree_read_write.txt\"\n TEST_TAG = \"----- TEST: READ/WRITE -----\"\n\n with open(TEST_FILE, 'wb') as fil_write:\n writer = bitio.BitWriter(fil_write)\n write_tree(tree_write, writer)\n writer.flush()\n\n with open(TEST_FILE, 'rb') as fil_read:\n reader = bitio.BitReader(fil_read)\n tree_read = read_tree(reader)\n\n assert(_get_tree_string(tree_write) == _get_tree_string(tree_read)\n ), \"{} Error - trees not the same.\".format(TEST_TAG)\n\n\ndef _test_tree_decode_byte():\n \"\"\"Creates a huffman tree and encodes characters to a test file, then uses 'decode_byte' to\n read the characters from the encoded bit string. Raises an assertion error if the encoded/decoded\n bytes differ.\n\n Status: PASSING.\n\n Notes:\n - Uses the same simple tree as '_test_tree_read_write()' by default.\n - Automatically generates a file '_test_tree_decode_byte.txt' in the working directory.\n \"\"\"\n\n a_leaf, eof_leaf, b_leaf = huffman.TreeLeaf(\n ord('A')), huffman.TreeLeaf(None), huffman.TreeLeaf(ord('B'))\n simple_tree = huffman.TreeBranch(\n huffman.TreeBranch(a_leaf, eof_leaf), b_leaf)\n\n TEST_FILE = \"_test_tree_decode_byte.txt\"\n TEST_TAG = \"----- TEST: DECODE BYTE -----\"\n\n chars = [\n (\"A\", \"00\"),\n (\"B\", \"1\"),\n (None, \"01\")\n ]\n\n with open(TEST_FILE, 'wb') as fil_write:\n writer = bitio.BitWriter(fil_write)\n for _, encoding in chars:\n for c in encoding:\n writer.writebit(True if c == '1' else False)\n writer.flush()\n\n with open(TEST_FILE, 'rb') as file_read:\n reader = bitio.BitReader(file_read)\n contents = []\n for _ in range(len(chars)):\n byte = decode_byte(simple_tree, reader)\n contents.append(chr(byte) if byte else None)\n\n assert([val for val, _ in chars] ==\n contents), \"{} Error - encoded/decoded bytes not the same.\".format(TEST_TAG)\n\n\ndef _test_compress_decompress():\n \"\"\"Compresses the 'ORIGINAL_FILE' into 'COMPRESSED_FILE' and then decompresses 'COMPRESSED_FILE' into\n 'DECOMPRESSED_FILE'. Raises an assertion error if any exceptions are thrown during the process. RESULTS\n MUST BE CHECKED FROM COMMAND LINE--see note below.\n\n Status: PASSING.\n\n Note:\n - Automatically generates files '_test_data.txt', '_test_data.txt.huf', '_test_data_decompressed.txt'\n in the current working directory.\n - To keep the test clean, use $ cmp 'ORIGINAL_FILE' 'DECOMPRESSED_FILE' from the command line to\n compare the results of the test.\n \"\"\"\n import compress\n\n ORIGINAL_FILE = \"bitio.pdf\"\n COMPRESSED_FILE = \"bitio.pdf.huf\"\n DECOMPRESSED_FILE = \"bitio_decompressed.pdf\"\n\n compress.run_compressor(ORIGINAL_FILE)\n\n with open(COMPRESSED_FILE, 'rb') as comp, open(DECOMPRESSED_FILE, 'wb') as decomp:\n decompress(comp, decomp)\n\n\nif __name__ == \"__main__\":\n _test_tree_read_write()\n _test_tree_decode_byte()\n _test_compress_decompress()\n _test_read_encoding()\n _test_write_encoding()","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"475898068","text":"from gym_jobshop.envs.src import environment, global_settings\n\n\ndef verify_machines():\n if global_settings.shop_type == \"flow_shop\":\n # Raise error if number of orders in any machine exceeds 1\n list_of_machines = environment.list_of_all_machines\n list_of_allowed_product_types = [\n [1, 2, 3, 4, 5, 6], [1, 2, 3], [4, 5, 6], [1, 4], [2, 5], [3, 6]\n ]\n for machine in list_of_machines:\n if len(machine.orders_inside_the_machine) > 1:\n raise ValueError(\"Too many orders inside machine \" + str(machine.name))\n elif len(machine.orders_inside_the_machine) == 1:\n if machine.orders_inside_the_machine[0].product_type not in (\n list_of_allowed_product_types[list_of_machines.index(machine)]):\n raise ValueError(\"step \" + str(global_settings.current_time) +\n \" Wrong product type in machine \" + str(machine.name) +\n \" || product type \" + str(machine.orders_inside_the_machine[0].product_type))\n\n ######## JOB SHOP NOT YET IMPLEMENTED\n elif global_settings.shop_type == \"flow_shop\":\n list_of_machines = environment.list_of_all_machines\n list_of_allowed_product_types = [\n [1, 2, 3, 4, 5, 6], [1, 2, 3], [4, 5, 6], [1, 4], [2, 5], [3, 6]\n ]\n return\n\n\n# def verify_wips(): # THIS FUNCTION MIGHT BE UNNECESSARY (checking the machines is enough)\n# # Raise error if a machine contains the wrong product type\n# for order_element in environment.wip_B:\n# if order_element.product_type in (4, 5, 6):\n# raise ValueError(\"Wrong product type in wip \")\n# for order_element in environment.wip_C:\n# if order_element.product_type in (1, 2, 3):\n# raise ValueError(\"Wrong product type in wip \")\n# for order_element in environment.wip_D:\n# if order_element.product_type in (2, 3, 5, 6):\n# raise ValueError(\"Wrong product type in wip \")\n# for order_element in environment.wip_E:\n# if order_element.product_type in (1, 3, 4, 6):\n# raise ValueError(\"Wrong product type in wip \")\n# for order_element in environment.wip_F:\n# if order_element.product_type in (1, 2, 4, 5):\n# raise ValueError(\"Wrong product type in wip \")\n# return\n\n\ndef verify_policies():\n # Raise error if order release policy has been entered incorrectly\n if global_settings.order_release_policy not in (\"periodic\", \"bil\", \"lums\"):\n raise ValueError(\"There was a problem with the selected order release policy. \"\n \"Please review order_release_policy at global_settings.py \")\n # Raise error if scheduling policy has been entered incorrectly\n if global_settings.scheduling_policy != \"first_come_first_serve\":\n raise ValueError(\"There was a problem with the selected scheduling policy. \"\n \"Please review scheduling_policy at global_settings.py \")\n return\n\n # This runs over every order in the finished goods inventory to see if there are orders left\n # which should have been removed long ago. WARNING: takes a lot of resources, only run at the very end\n\n\ndef verify_fgi():\n # Raise error if there are orders in the FGI (finished goods inventory) even though they shouldn't be there\n # if len(environment.finished_goods_inventory) > 0:\n # for order_element in environment.finished_goods_inventory:\n # if order_element.due_date < global_settings.current_time:\n # raise ValueError(\"Programming error in finished goods inventory: \"\n # \"overdue order is still inside the inventory. \")\n return\n\n\ndef verify_all():\n # The following checks are performed every 50 steps of the simulation\n if global_settings.current_time % 50 == 0:\n verify_machines()\n # verify_wips() --> we don't need to verify wips, as a wrong product type would be noticed in verify_machines\n # The following checks are only performed in the first step of the simulation\n if global_settings.current_time == 0:\n verify_policies()\n # The following checks are only performed in the last step of the simulation\n if global_settings.current_time == global_settings.maximum_simulation_duration - 1:\n verify_fgi()\n\ndef verify_reset():\n # print(\"Settings reset. Current time: \" + str(global_settings.current_time) +\n # \" | FGI \" + str(len(environment.finished_goods_inventory)) +\n # \" | WIPs \" + str(len(environment.wip_A)+len(environment.wip_B)+len(environment.wip_C)+len(environment.wip_D)+len(environment.wip_E)+len(environment.wip_F)) +\n # \" | Machines \" + str(len(environment.machine_A.orders_inside_the_machine)+len(environment.machine_B.orders_inside_the_machine)+len(environment.machine_C.orders_inside_the_machine)+len(environment.machine_D.orders_inside_the_machine)+len(environment.machine_E.orders_inside_the_machine)+len(environment.machine_F.orders_inside_the_machine)) +\n # \" | total cost \" + str(global_settings.total_cost) +\n # \" | Order pool: \" + str(len(environment.order_pool)) +\n # \" | Next order at step: \" + str(global_settings.time_of_next_order_arrival)\n # )\n return\n\n\n\n","sub_path":"gym-jobshop/gym_jobshop/envs/src/debugging.py","file_name":"debugging.py","file_ext":"py","file_size_in_byte":5344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"629297169","text":"from math import *\r\n\r\ndef combinaciones(x, y):\r\n return factorial(x) / float(factorial(y)*factorial(x-y))\r\n\r\ndef probabilidad(p, i):\r\n sup = floor((p-i)/float(6))+1\r\n a = 0\r\n for n in range(sup):\r\n x1 = (-1)**n;\r\n x2 = combinaciones(i, n)\r\n x3 = combinaciones(p-(6*n)-1, i-1)\r\n a += (x1 * x2 * x3)\r\n return a / float(6**i)\r\n\r\nn = float(input(\"Ingrese la cantidad de dados\\n\"))\r\n\r\n\r\ns = float(input(\"Ingrese la suma cuya probabilidad desea saber\\n\"))\r\n\r\n\r\nprint (\"El porcentaje de probabilidad es\")\r\nprint(str((probabilidad(s,n))*100))\r\n","sub_path":"Dados.py","file_name":"Dados.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"72070553","text":"from datetime import datetime as dt\nimport datetime\nimport random\n\nfrom django.core.management.base import BaseCommand, CommandError\nfrom app.models import Person\n\n\nclass Command(BaseCommand):\n args = 'count'\n help = 'add in db field '\n\n def add_arguments(self, parser):\n parser.add_argument('count')\n\n def handle(self, *args, **options):\n count = int(options['count'])\n name = [\n \"Andrew\",\n \"Anna\",\n \"Augusta\",\n \"Alison\",\n \"Cliff\",\n \"James\",\n \"Louis\",\n \"Sarah\",\n \"Stacey\",\n ]\n l_name = [\n \"London\",\n \"Peacock\",\n \"Cook\",\n \"Ross\",\n \"Ross\",\n \"Blare\",\n \"Archibald\",\n \"Leapman\",\n \"Grant\",\n ]\n for i in range(count):\n d = dt.today() - datetime.timedelta(days=random.randint(0, 1000))\n d = d.strftime('%Y-%m-%d')\n last_name = l_name[random.randint(0, 8)]\n first_name = name[random.randint(0, 8)]\n price = random.randint(0, 10000)\n\n p = Person(\n first_name=first_name,\n last_name=last_name,\n date=d,\n price=price,\n )\n p.save()\n\n print(\"complite in base adding \",count,\"card\")\n","sub_path":"app/management/commands/fielddb.py","file_name":"fielddb.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"244626589","text":"import firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom constants import DISPENSER_ID, SERVICES_PATH\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import firestore\nfrom erogation import Erogazione\nfrom notification import Notifica\n\nclass DatabaseService:\n \n def __init__(self):\n self.services_path = SERVICES_PATH\n self.cred = credentials.Certificate('bridge/services/' + self.services_path)\n self.db_ref = None\n\n def initialize_connection(self):\n firebase_admin.initialize_app(self.cred)\n self.db_ref = firestore.client()\n print('Collegamento con il database avvenuto con successo!\\n')\n\n def get_doc_ref(self, collection_name, doc_id):\n doc_ref = self.db_ref.collection(collection_name).document(doc_id)\n return doc_ref\n\n def update_available_ration(self, collar_id, ration, is_animal_detected):\n animal_ref = self.get_doc_ref('Animal', collar_id)\n disp_ref = self.get_doc_ref('Dispenser', DISPENSER_ID)\n\n dispenser = disp_ref.get().to_dict()\n animal = animal_ref.get().to_dict()\n available_ration = animal['availableRation']\n food_counter = animal['foodCounter']\n rimasto_disp = dispenser['cibo_rimasto']\n\n if is_animal_detected:\n food_counter += 1\n\n #se la available diventa negativa allora la settiamo a 0\n #questo si verifica quando dall'app diamo la possibilità\n #di erogare più di quello a disposizione\n if(ration >= available_ration):\n available_ration = 0 \n else:\n available_ration -= ration\n \n rimasto_disp -= ration \n \n animal_ref.update({'availableRation':available_ration, 'foodCounter': food_counter})\n disp_ref.update({'cibo_rimasto': rimasto_disp})\n\n def get_available_ration(self, collar_id):\n animal_ref = self.get_doc_ref('Animal', collar_id)\n animal = animal_ref.get().to_dict()\n return animal['availableRation']\n\n def get_food_counter(self, collar_id):\n animal_ref = self.get_doc_ref('Animal', collar_id)\n animal = animal_ref.get().to_dict()\n return animal['foodCounter']\n\n def get_nameAnimal_fromCollar(self, collar_id):\n animal_ref = self.get_doc_ref('Animal', collar_id)\n animal = animal_ref.get().to_dict()\n return animal['name']\n\n #funzione utile nel caso non usiamo gli ibeacon\n def get_user_animals(self, user_id):\n collar_id_list = []\n animals_ref = self.db_ref.collection('Animal')\n query = animals_ref.where('userId', '==', user_id)\n animals = query.stream()\n for animal in animals:\n collar_id_list.append(animal.to_dict()['collarId'])\n \n return collar_id_list\n\n def get_user_from_dispenser(self):\n dispenser_ref = self.get_doc_ref('Dispenser', DISPENSER_ID)\n dispenser = dispenser_ref.get().to_dict()\n return dispenser['userId']\n \n def reset_dispenser_state(self, dispenser_ref):\n doc_ref = self.db_ref.collection('Dispenser').document(DISPENSER_ID)\n dispenser_ref['qtnRation'] = 0\n #RIMETTO A NULL L'ANIMALE INTERESSATO!\n dispenser_ref['collarId'] = None\n doc_ref.set(dispenser_ref)\n\n \n def add_prediction(self, collarId, qnt, dispenser_id):\n print(\"Raccolta dati sull' erogazione...\")\n\n pred = Erogazione(collar_id = collarId, qnt = qnt, dispenser_id = dispenser_id)\n self.db_ref.collection('Erogation Data').add(pred.to_dict())\n\n\n def getAllCollection(self, collection_name):\n doc_coll = self.db_ref.collection(collection_name).stream()\n return doc_coll\n \n def get_Dispenser_curr_foodState(self):\n dispenser_ref = self.get_doc_ref('Dispenser', DISPENSER_ID)\n dispenser = dispenser_ref.get().to_dict()\n return dispenser['food_state']\n\n def update_FoodStateDispenser(self, val):\n dispenser_ref = self.get_doc_ref('Dispenser', DISPENSER_ID)\n curr_foodState = self.get_Dispenser_curr_foodState()\n \n\n if(val == False):\n #c'erano i croccantini, ora cambio stato\n curr_foodState = True\n #qua il led dovrebbe essere acceso\n print(\"LED SI ACCENDE --- RISCHIO CROCCANTINI\")\n #inserisco la notifica per utente\n self.set_notifica()\n\n else:\n #mancavano i crocc ma li ho aggiunti\n curr_foodState = False\n self.delete_notifica()\n \n dispenser_ref.update({'food_state':curr_foodState})\n\n def set_notifica(self):\n dispenser_ref = self.get_doc_ref('Dispenser', DISPENSER_ID)\n user_id = dispenser_ref.get().to_dict()['userId']\n notifica = Notifica(dispenser_id = DISPENSER_ID, user_id =user_id )\n print(\"Invio notifica in corso...\")\n self.db_ref.collection('Notifiche').document(DISPENSER_ID).set(notifica.to_dict())\n\n def delete_notifica(self):\n dispenser_ref = self.get_doc_ref('Dispenser', DISPENSER_ID)\n doc_ref = self.db_ref.collection('Notifiche').document(DISPENSER_ID)\n print(\"STO ELIMINANDO LA NOTIFICA PER L'UTENTE\")\n doc_ref.delete()\n","sub_path":"bridge/services/db_service.py","file_name":"db_service.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"21820349","text":"# Run on cmd: C:\\Python27\\ArcGISx6410.2\\python.exe G:\\ohiprep\\Israel\\Hamaarag-Regions_v2014a\\model.py\n\n# packages\nimport arcpy, os, socket, numpy, numpy.lib.recfunctions, pandas, time\n\n# paths\nwd = 'G:/ohiprep/Israel/Hamaarag-Regions_v2014a'\ntmp = 'C:/tmp/Israel/Hamaarag-Regions_v2014a'\ngdb = '%s/geodb.gdb' % tmp\neco_shp = r'N:\\git-annex\\Israel\\Hamaarag-Regions_v2014a\\Subregions_Int.shp'\neco_haifabay_shp = '%s/raw\\HaifaBay_offshore_inland5km_manualedit.shp' % wd\neco_redsea_shp = '%s/raw\\RedSea_rectangle_for_removal.shp' % wd\nshp_out = '%s/data/regions_gcs.shp' % wd\ncsv_out = '%s/data/regions_gcs_data.shp' % wd\nsp_gdb = r'C:\\tmp\\Global\\NCEAS-Regions_v2014\\geodb.gdb' # neptune_data:git-annex/Global/NCEAS-Regions_v2014/geodb.gdb\npol_gadm = r'C:\\tmp\\Global\\GL-GADM-AdminAreas_v2\\data\\gadm2.gdb\\gadm2' # neptune_data:stable/GL-GADM-AdminAreas_v2/data/gadm2.gdb\ncountries = ['Israel','Palestina'] # special case for Israel: excise Palestina in GADM from Israel in MarineRegions (offshore and inland)\ncountry = 'Israel'\n\n# projections\nsr_mol = arcpy.SpatialReference('Mollweide (world)') # projected Mollweide (54009)\nsr_gcs = arcpy.SpatialReference('WGS 1984') # geographic coordinate system WGS84 (4326)\n\n# initialize\nos.chdir(wd)\nif not os.path.exists('tmp'): os.makedirs('tmp')\nif not os.path.exists('data'): os.makedirs('data')\nif not os.path.exists(tmp): os.makedirs(tmp)\nif not arcpy.Exists(gdb): arcpy.CreateFileGDB_management(os.path.dirname(gdb), os.path.basename(gdb))\n\n# environment\narcpy.env.workspace = gdb\narcpy.env.overwriteOutput = True\narcpy.env.outputCoordinateSystem = sr_gcs\n\n# copy\nif not arcpy.Exists('eco'):\n arcpy.CopyFeatures_management(eco_shp, 'eco')\nif not arcpy.Exists('eco_haifabay'):\n arcpy.CopyFeatures_management(eco_haifabay_shp, 'eco_haifabay')\n arcpy.AlterField_management('eco_haifabay', 'Region_Eng', 'NAME_1', 'NAME_1')\nif not arcpy.Exists('eco_redsea'):\n arcpy.CopyFeatures_management(eco_redsea_shp, 'eco_redsea')\nif not arcpy.Exists('pol'):\n arcpy.Select_analysis(pol_gadm, 'pol', \"\\\"NAME_0\\\" IN ('%s')\" % \"','\".join(countries))\nif not arcpy.Exists('sp'):\n arcpy.Select_analysis('%s/sp_gcs' % sp_gdb, 'sp', \"\\\"sp_name\\\" = '%s'\" % country)\n\n# dissolve to district for Israel and Palestina districts to remove after extending: West Bank, Gaza\narcpy.Dissolve_management('pol', 'pol_d', ['NAME_1'])\n\n# setup for theissen polygons\narcpy.env.extent = 'sp'\narcpy.env.outputCoordinateSystem = sr_mol\narcpy.CopyFeatures_management('pol_d', 'pol_t')\narcpy.Densify_edit('pol_t', 'DISTANCE', '1 Kilometers')\narcpy.FeatureVerticesToPoints_management('pol_t', 'pol_t_pts', 'ALL')\n \n# delete interior points to make thiessen calculate faster\narcpy.Dissolve_management('pol_t', 'pol_t_d')\narcpy.MakeFeatureLayer_management('pol_t_pts', 'lyr_pts')\narcpy.SelectLayerByLocation_management('lyr_pts', 'WITHIN_CLEMENTINI', 'pol_t_d')\narcpy.DeleteFeatures_management('lyr_pts')\narcpy.Delete_management('lyr_pts')\n\n# generate thiessen polygons, in Mollweide\narcpy.CreateThiessenPolygons_analysis('pol_t_pts', 'pol_thie', 'ALL')\narcpy.Dissolve_management('pol_thie', 'pol_thie_d', ['NAME_1'])\narcpy.RepairGeometry_management('pol_thie_d')\n\n# burn land pol back in\narcpy.Erase_analysis('pol_thie_d', 'pol_d', 'pol_thie_d_e')\narcpy.Merge_management(['pol_d', 'pol_thie_d_e'], 'pol_thie_m')\narcpy.Dissolve_management('pol_thie_m', 'pol_thie_mol', ['NAME_1'])\n \n# remove districts in Palestina: West Bank, Gaza\n# remove districts without any offshore waters: Golan, Jerusalem\narcpy.MakeFeatureLayer_management('pol_thie_mol', 'lyr')\narcpy.SelectLayerByAttribute_management('lyr', 'NEW_SELECTION', \"NAME_1 IN ('West Bank','Gaza','Golan','Jerusalem')\")\narcpy.DeleteFeatures_management('lyr')\narcpy.Delete_management('lyr')\n\n# setup Haifa Bay with inland component\n## arcpy.Select_analysis(eco_shp, 'eco_haifabay', \"\\\"Region_Eng\\\" = 'Haifa Bay'\")\n## arcpy.Buffer_analysis('eco_haifabay', 'eco_haifabay_buf5km', '5 kilometers')\n## manually: copied feature class and edited vertices to create HaifaBay_shp\narcpy.Erase_analysis('pol_thie_mol', 'eco_haifabay', 'pol_thie_mol_e')\narcpy.Merge_management(['pol_thie_mol_e', 'eco_haifabay'], 'pol_thie_mol_e_m')\n\n# dissolve to just field NAME_1 and rename to rgn_name\narcpy.Dissolve_management('pol_thie_mol_e_m', 'pol_thie_mol_e_m_d', ['NAME_1'])\narcpy.AlterField_management('pol_thie_mol_e_m_d', 'NAME_1', 'rgn_name_e', 'rgn_name_e')\n\n# add fields rgn_name (in Hebrew) and rgn_id\nr = arcpy.da.TableToNumPyArray('pol_thie_mol_e_m_d', ['OBJECTID','rgn_name_e'])\nh = dict(arcpy.da.TableToNumPyArray('eco', ['Region_Eng','Region_Heb']))\nh[u'HaZafon'] = h[u'Northern']\nh[u'HaMerkaz'] = h[u'Central']\nh[u'HaDarom'] = h[u'Southern']\nrgn_name = numpy.array([(h[x],) for x in r['rgn_name_e']], dtype=[('rgn_name', '/-\", methods=[\"GET\"])\n@pages_blueprint.route(\"//-/summary.html\", methods=[\"GET\"])\n@context.security.authentication_required\n@context.security.authorization_required(\"read\")\ndef mainSummary(instrument_name, experiment_id, experiment_name):\n instrument_name = instrument_name.lower()\n # First check to see if the run summary folder exists for the experiment\n expResultsFolder = os.path.join(EXP_RESULTS_FOLDER, instrument_name, experiment_name, \"stats\", \"summary\")\n logger.debug(\"Looking for summary results for experiment {} in folder {}\".format(experiment_name, expResultsFolder))\n\n if not os.path.exists(expResultsFolder):\n logger.debug(\"Cannot find the folder %s; note this could also be a problem with file system permissions.\", expResultsFolder)\n return Response(\"There are no summary stats for {}\".format(experiment_name), mimetype='text/html')\n\n logger.debug(\"Found the path %s\", expResultsFolder)\n if not os.path.isdir(expResultsFolder):\n return Response(\"The summary stats path {} is not a folder for {}\".format(expResultsFolder, experiment_name), mimetype='text/html')\n\n logger.debug(\"Found the folder %s\", expResultsFolder)\n if os.path.exists(os.path.join(expResultsFolder, \"report.html\")):\n logger.debug(\"Found an report.html\")\n return send_file(os.path.join(expResultsFolder, \"report.html\"), mimetype='text/html')\n\n # The default is to send a list of folders as links.\n links = []\n for folderName in sorted(os.listdir(expResultsFolder)):\n if os.path.isdir(os.path.join(expResultsFolder, folderName)) and os.path.exists(os.path.join(expResultsFolder, folderName, \"report.html\")):\n links.append(folderName)\n else:\n logger.debug(\"'{}' does not exist?\".format(os.path.join(expResultsFolder, \"report.html\")))\n\n return render_template(\"expsummary.html\",\n links=links,\n experiment_id=experiment_id,\n experiment_name=experiment_name\n )\n\n\n@pages_blueprint.route(\"//-/\", methods=[\"GET\"])\n@context.security.authentication_required\n@context.security.authorization_required(\"read\")\ndef otherPages(instrument_name, experiment_id, experiment_name, page):\n instrument_name = instrument_name.lower()\n # First check to see if the run summary folder exists for the experiment\n expResultsPage = os.path.join(EXP_RESULTS_FOLDER, instrument_name, experiment_name, \"stats\", \"summary\", page)\n logger.debug(\"Looking for page {} for experiment {} in folder {}\".format(page, experiment_name, expResultsPage))\n\n if not os.path.exists(expResultsPage):\n abort(404)\n return\n return send_file(expResultsPage, mimetypes.guess_type(expResultsPage)[0])\n","sub_path":"pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":3283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"110002113","text":"'''\nYou are given an integer array nums and two integers minK and maxK.\n\nA fixed-bound subarray of nums is a subarray that satisfies the following conditions:\n\nThe minimum value in the subarray is equal to minK.\nThe maximum value in the subarray is equal to maxK.\nReturn the number of fixed-bound subarrays.\n\nA subarray is a contiguous part of an array.\n\n \n\nExample 1:\n\nInput: nums = [1,3,5,2,7,5], minK = 1, maxK = 5\nOutput: 2\nExplanation: The fixed-bound subarrays are [1,3,5] and [1,3,5,2].\nExample 2:\n\nInput: nums = [1,1,1,1], minK = 1, maxK = 1\nOutput: 10\nExplanation: Every subarray of nums is a fixed-bound subarray. There are 10 possible subarrays.\n \n\nConstraints:\n\n2 <= nums.length <= 105\n1 <= nums[i], minK, maxK <= 106\n'''\n\nclass Solution:\n def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:\n answer = 0\n min_position = max_position = left_bound = -1\n \n for i, number in enumerate(nums):\n if number < minK or number > maxK:\n left_bound = i\n if number == minK:\n min_position = i\n if number == maxK:\n max_position = i\n \n answer += max(0, min(min_position, max_position) - left_bound)\n \n return answer\n\n","sub_path":"problems/2444_count_subarrays_with_fixed_bounds.py","file_name":"2444_count_subarrays_with_fixed_bounds.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"174093739","text":"\"\"\"\r\n\"\"\"\r\ntype_hierarchy = {\r\n 30: 4,\r\n 36: 5\r\n}\r\n\r\nstatus = {\r\n 'under way using engine': 6,\r\n 'not under command': 1,\r\n 'at anchor': 1,\r\n 'engaged in fishing': 4,\r\n 'restricted maneuverability': 1,\r\n 'under way sailing': 5,\r\n 'power driven vessel towing astern': 6,\r\n 'constrained by her draught': 6,\r\n 'power-driven vessel pushing ahead or towing alongside': 6\r\n}\r\n\r\n\r\ndef hierarchy_row(ship1, ship2):\r\n \"\"\"\r\n \"\"\"\r\n try:\r\n vessel_type_1 = ship1['VesselType']\r\n except KeyError:\r\n vessel_type_1 = 6\r\n\r\n try:\r\n vessel_type_2 = ship2['VesselType']\r\n except KeyError:\r\n vessel_type_2 = 6\r\n\r\n place_1 = min(type_hierarchy[vessel_type_1], status[ship1['Status']])\r\n place_2 = min(type_hierarchy[vessel_type_2], status[ship2['Status']])\r\n\r\n if place_1 < place_2:\r\n return \"Ship 1 stand on vessel, ship 2 give way vessel\"\r\n if place_1 > place_2:\r\n return \"Ship 1 give way vessel, ship 2 stand on vessel\"\r\n else:\r\n return \"Determine COLREGs interaction\"\r\n","sub_path":"scripts/right_of_way.py","file_name":"right_of_way.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"70137129","text":"#Well, I don't know how to do md5 stuff yet... Let's learn.\n\nimport hashlib\n\nsecretKey = b'iwrupvqb'\n\nparentHasher = hashlib.md5()\n\nparentHasher.update(secretKey)\n\ni = 1\nwhile True:\n h = parentHasher.copy()\n h.update(bytes(str(i), 'utf-8'))\n if str(h.hexdigest())[:5] == '00000':\n print(i)\n break\n i += 1\n\n","sub_path":"4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"369361851","text":"import sys\nfrom PyQt5.QtCore import QDir\nfrom PyQt5.QtWidgets import QApplication, QWidget, QTreeView, QDirModel, QLabel, QVBoxLayout\n\n\nclass Demo(QWidget):\n def __init__(self):\n super(Demo, self).__init__()\n self.resize(600, 300)\n self.model = QDirModel(self) # 1\n self.model.setReadOnly(False)\n self.model.setSorting(QDir.Name | QDir.IgnoreCase)\n\n self.tree = QTreeView(self) # 2\n self.tree.setModel(self.model)\n self.tree.clicked.connect(self.show_info)\n self.index = self.model.index(QDir.currentPath())\n self.tree.expand(self.index)\n self.tree.scrollTo(self.index)\n\n self.info_label = QLabel(self) # 3\n\n self.v_layout = QVBoxLayout()\n self.v_layout.addWidget(self.tree)\n self.v_layout.addWidget(self.info_label)\n self.setLayout(self.v_layout)\n\n def show_info(self): # 4\n index = self.tree.currentIndex()\n file_name = self.model.fileName(index)\n file_path = self.model.filePath(index)\n file_info = 'File Name: {}\\nFile Path: {}'.format(file_name, file_path)\n self.info_label.setText(file_info)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n demo = Demo()\n demo.show()\n sys.exit(app.exec_())","sub_path":"assembly/0427/explore_qt/20/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"344034132","text":"from django.views.generic import TemplateView\nfrom django.shortcuts import render, HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import redirect\nfrom django.core.urlresolvers import reverse\n\nfrom django.contrib import auth\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\n\nfrom .forms import RegistroUserForm, PayCheckForm, PayCheckEditarForm\n\nfrom dashboard.models import Bank, PayCheck, Mensajes\n\nimport json\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# index\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n@login_required\ndef index_view(request):\n banks = Bank.objects.all()\n form = PayCheckForm()\n context = {\n 'banks' : banks,\n 'form' : form\n }\n return render(request, 'components/index.html', context)\n\n\n\n\nclass BlankView(TemplateView):\n template_name = \"components/blank.html\"\n\n def get_context_data(self, **kwargs):\n context = super(BlankView, self).get_context_data(**kwargs)\n context.update({'title': \"Blank Page\"})\n return context\n\n\nclass ButtonsView(TemplateView):\n template_name = \"components/buttons.html\"\n\n def get_context_data(self, **kwargs):\n context = super(ButtonsView, self).get_context_data(**kwargs)\n context.update({'title': \"Buttons\"})\n return context\n\n\nclass FlotView(TemplateView):\n template_name = \"components/flot.html\"\n\n def get_context_data(self, **kwargs):\n context = super(FlotView, self).get_context_data(**kwargs)\n context.update({'title': \"Flot Charts\"})\n return context\n\n\nclass FormsView(TemplateView):\n template_name = \"components/forms.html\"\n\n def get_context_data(self, **kwargs):\n context = super(FormsView, self).get_context_data(**kwargs)\n context.update({'title': \"Forms\"})\n return context\n\n\nclass GridView(TemplateView):\n template_name = \"components/grid.html\"\n\n def get_context_data(self, **kwargs):\n context = super(GridView, self).get_context_data(**kwargs)\n context.update({'title': \"Grid\"})\n return context\n\n\nclass IconsView(TemplateView):\n template_name = \"components/icons.html\"\n\n def get_context_data(self, **kwargs):\n context = super(IconsView, self).get_context_data(**kwargs)\n context.update({'title': \"Icons\"})\n return context\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# login view\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\ndef login_view(request):\n message = ''\n # Si el usuario esta ya logueado, lo redireccionamos a index_view\n if request.user.is_authenticated():\n return redirect(reverse('dashboard:index'))\n\n if request.method == 'POST':\n username = request.POST.get('username')\n password = request.POST.get('password')\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_staff and user.is_active:\n login(request, user)\n return redirect(reverse('dashboard:index'))\n\n # verificar que halla verificado su cuenta desde el link de activacion enviado en el email\n \"\"\"if UserProfile.objects.get(user=user.id).verificado_email != 1:\n print(\"no ha verificado el email\")\n message = 'Para acceder al sitio debe de verificar su email. Reenviar email.' % (\n user.id)\n form = Forgot_Password_Form()\n context = {\n 'form': form,\n 'message': message,\n }\n return render(request, 'accounts/login.html', {'message': message})\"\"\"\n if user.is_active:\n login(request, user)\n return redirect(reverse('dashboard:index'))\n else:\n message = 'Su cuenta no esta activa.'\n return render(request, 'components/login.html', {'message': message})\n else:\n # Redireccionar informando que la cuenta esta inactiva\n pass\n message = 'Nombre de usuario o contraseña incorrecto.'\n\n #form = Forgot_Password_Form()\n context = {\n #'form': form,\n 'message': message,\n }\n\n return render(request, 'components/login.html', context)\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# logout_view\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\ndef logout_view(request):\n logout(request)\n #message.success(request, 'Te has desconectado con exito.')\n return redirect(reverse('dashboard:login'))\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# Registrar Usuario\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\ndef registro_usuario_view(request):\n\tif request.method == 'POST':\n\t# Si el method es post, obtenemos los datos del formulario\n\t\tform = RegistroUserForm(request.POST, request.FILES)\n\t\t\t# Comprobamos si el formulario es valido\n\t\tif form.is_valid():\n\t\t\t# En caso de ser valido, obtenemos los datos del formulario.\n\t\t\t# form.cleaned_data obtiene los datos limpios y los pone en un\n\t\t\t# diccionario con pares clave/valor, donde clave es el nombre del campo\n\t\t\t# del formulario y el valor es el valor si existe.\n\t\t\tcleaned_data = form.cleaned_data\n\t\t\tusername = cleaned_data.get('username')\n\t\t\tpassword = cleaned_data.get('password')\n\t\t\temail = cleaned_data.get('email')\n\t\t\tphoto = cleaned_data.get('photo')\n\t\t\tnombre = cleaned_data.get('nombre')\n\t\t\tapellidos = cleaned_data.get('apellidos')\n\t\t\t# E instanciamos un objeto User, con el username y password\n\t\t\tuser_model = User.objects.create_user(username=username, password=password)\n\t\t\t# Añadimos el email\n\t\t\tuser_model.nombre = nombre\n\t\t\tuser_model.apellidos = apellidos\n\t\t\tuser_model.email = email\n\t\t\t# Y guardamos el objeto, esto guardara los datos en la db.\n\t\t\tuser_model.save()\n\n\n\n\t\t\t# Se llama al proceso que envía el mail\n\t\t\t# Email.enviar_correo_registro_usuario(usuario = user_profile, host = request.get_host())\n\n\t\t\tmessage = 'Para acceder al sitio debe de verificar su email.'\n\t\t\treturn render(request, 'components/login.html', {'message': message})\n\telse:\n\t# Si el mthod es GET, instanciamos un objeto RegistroUserForm vacio\n\t\tform = RegistroUserForm()\n\t# Creamos el contexto\n\tcontext = {'form': form}\n\t# Y mostramos los datos\n\treturn render(request, 'components/singup_user.html', context)\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# chekes\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n@login_required\ndef chekes_view(request):\n if request.method == 'POST':\n print(\"+++++++++++++++++++++++++Post\")\n # Si el method es post, obtenemos los datos del formulario\n form = PayCheckForm(request.POST, request.FILES)\n # Comprobamos si el formulario es valido\n if form.is_valid():\n print(\"+++++++++++++++++++++++++Valido\")\n cleaned_data = form.cleaned_data\n bank = cleaned_data.get('bank')\n\n emission_date = cleaned_data.get('emission_date')\n at_date = cleaned_data.get('at_date')\n post_date = cleaned_data.get('post_date')\n\n check_number = cleaned_data.get('check_number')\n beneficiary = cleaned_data.get('beneficiary')\n concept = cleaned_data.get('concept')\n notes = cleaned_data.get('notes')\n\n nuevoCheke = PayCheck(user = request.user, bank = bank, emission_date = emission_date)\n nuevoCheke.check_number = check_number\n nuevoCheke.beneficiary = beneficiary\n nuevoCheke.concept = concept\n nuevoCheke.notes = notes\n\n if at_date != '':\n nuevoCheke.at_date = at_date\n if post_date != '':\n nuevoCheke.post_date = post_date\n nuevoCheke.save()\n datos = {\n 'bandera': 1,\n 'mensaje': 'Se ha creado correctamente',\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n else:\n datos = {\n 'bandera': 0,\n 'mensaje': 'Existe un checke con ese número en nuestros registros',\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n # obtener todos los chekes del usuario logueado\n chekes = PayCheck.objects.filter(user = request.user.id)\n form = PayCheckForm()\n context = {\n 'chekes' : chekes,\n 'form' : form,\n }\n return render(request, 'components/chekes.html', context)\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# chekes\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n@login_required\ndef chekes2_view(request, id):\n if request.method == 'POST':\n print(\"+++++++++++++++++++++++++Post\")\n # Si el method es post, obtenemos los datos del formulario\n form = PayCheckEditarForm(request.POST, request.FILES)\n # Comprobamos si el formulario es valido\n if form.is_valid():\n print(\"+++++++++++++++++++++++++Valido\")\n cleaned_data = form.cleaned_data\n bank = cleaned_data.get('bank_e')\n chekEliminar = cleaned_data.get('chekEliminar_e')\n\n emission_date = cleaned_data.get('emission_date_e')\n at_date = cleaned_data.get('at_date_e')\n post_date = cleaned_data.get('post_date_e')\n\n check_number = cleaned_data.get('check_number_e')\n beneficiary = cleaned_data.get('beneficiary_e')\n concept = cleaned_data.get('concept_e')\n notes = cleaned_data.get('notes_e')\n\n method = request.POST.get('method')\n\n\n\n\n editarCheke = PayCheck.objects.get(id = id)\n\n\n if method == \"delete\":\n editarCheke.delete()\n datos = {\n 'bandera': 1,\n 'mensaje': 'Ha sido eliminado',\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n\n if editarCheke.check_number != int(check_number) and PayCheck.objects.filter(check_number=check_number):\n datos = {\n 'bandera': 0,\n 'mensaje': 'Existe un checke con ese número en nuestros registros',\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n else:\n editarCheke.bank = bank\n editarCheke.beneficiary = beneficiary\n editarCheke.concept = concept\n editarCheke.notes = notes\n\n editarCheke.emission_date = emission_date\n if at_date != '':\n editarCheke.at_date = at_date\n if post_date != '':\n editarCheke.post_date = post_date\n\n editarCheke.save()\n\n datos = {\n 'bandera': 1,\n 'mensaje': 'Se ha actualizado correctamente',\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n\n\n elif request.method == 'DELETE':\n print(\"+++++++++++++++++++++++++eliminar\")\n editarCheke = PayCheck.objects.get(id=id).delete()\n chekes = PayCheck.objects.filter(user=request.user.id)\n form = PayCheckForm()\n context = {\n 'chekes': chekes,\n 'form': form,\n }\n return render(request, 'components/chekes.html', context)\n elif request.method == 'GET':\n print(\"+++++++++++++++++++++++++get\")\n cheke = PayCheck.objects.get(id = id)\n form = PayCheckEditarForm(initial={\n 'bank_e': cheke.bank,\n 'check_number_e': cheke.check_number,\n 'beneficiary_e': cheke.beneficiary,\n 'concept_e': cheke.concept,\n 'notes_e': cheke.notes,\n 'emission_date_e': cheke.emission_date,\n 'at_date_e': cheke.at_date,\n 'post_date_e': cheke.post_date,\n\n })\n context = {\n 'form' : form,\n 'id' : id,\n }\n return render(request, 'components/chekes_modal_editar.html', context)\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# cheque modal\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\ndef cheque_modal_view(request):\n form = PayCheckForm()\n context = {\n 'form' : form\n }\n return render(request, 'components/chekes_modal.html', context)\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# filtro\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\ndef filtrar_view(request):\n if request.method == 'POST':\n\n emission_date_start = request.POST.getlist('emission_date_start')\n emission_date_end = request.POST.getlist('emission_date_end')\n\n at_date_start = request.POST.getlist('at_date_start')\n at_date_end = request.POST.getlist('at_date_end')\n\n post_date_start = request.POST.getlist('post_date_start')\n post_date_end = request.POST.getlist('post_date_end')\n\n\n print(\"}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}\")\n chekes = PayCheck.objects.filter(emission_date__gte = emission_date_start)\n context = {\n 'chekes' : chekes\n }\n return render(request, 'components/filtrar.html', context)\n #return render(request, 'components/chekes.html')\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n\nclass MorrisView(TemplateView):\n template_name = \"components/morris.html\"\n\n def get_context_data(self, **kwargs):\n context = super(MorrisView, self).get_context_data(**kwargs)\n context.update({'title': \"Morris Charts\"})\n return context\n\n\nclass NotificationsView(TemplateView):\n template_name = \"components/notifications.html\"\n\n def get_context_data(self, **kwargs):\n context = super(NotificationsView, self).get_context_data(**kwargs)\n context.update({'title': \"Notifications\"})\n return context\n\n\nclass PanelsView(TemplateView):\n template_name = \"components/panels-wells.html\"\n\n def get_context_data(self, **kwargs):\n context = super(PanelsView, self).get_context_data(**kwargs)\n context.update({'title': \"Panels and Wells\"})\n return context\n\n\nclass TablesView(TemplateView):\n template_name = \"components/tables.html\"\n\n def get_context_data(self, **kwargs):\n context = super(TablesView, self).get_context_data(**kwargs)\n context.update({'title': \"Tables\"})\n return context\n\n\nclass TypographyView(TemplateView):\n template_name = \"components/typography.html\"\n\n def get_context_data(self, **kwargs):\n context = super(TypographyView, self).get_context_data(**kwargs)\n context.update({'title': \"Typography\"})\n return context\n\n\n# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# mostrar_mensajes\n# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\ndef mostrar_mensajes(request):\n # primero mostrar los mensajes con prioridad 3 que sera con los cuales el usuario\n # podra tomar la decision de relanzar el pedido o cancelarlo al pasar un tiempo sin que nadie\n # escoja su pedido\n\n if Mensajes.objects.filter(user=request.user.id, leido=\"no\", prioridad=3):\n mensajes = Mensajes.objects.filter(user=request.user.id, leido=\"no\", prioridad=3)[0]\n try:\n pedido = UserPedido.objects.get(id=mensajes.pedido_id)\n except:\n pedido = \"\"\n\n datos = {\n 'prioridad': 3,\n 'mensajes': mensajes.mensaje,\n 'id': mensajes.id\n }\n\n return HttpResponse(json.dumps(datos), content_type='application/json')\n\n elif Mensajes.objects.filter(user=request.user.id, leido=\"no\", prioridad=4):\n mensajes = Mensajes.objects.filter(user=request.user.id, leido=\"no\", prioridad=4)[0]\n try:\n pedido = UserPedido.objects.get(id=mensajes.pedido_id)\n except:\n pedido = \"\"\n\n datos = {\n 'prioridad': 4,\n 'mensajes': mensajes.mensaje,\n 'id': mensajes.id\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n\n elif Mensajes.objects.filter(user=request.user.id, leido=\"no\", prioridad=2):\n mensajes = Mensajes.objects.filter(user=request.user.id, leido=\"no\", prioridad=2)[0]\n try:\n pedido = UserPedido.objects.get(id=mensajes.pedido_id)\n except:\n pedido = \"\"\n\n datos = {\n 'prioridad': 2,\n 'mensajes': mensajes.mensaje,\n 'id': mensajes.id\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n\n try:\n mensajes = Mensajes.objects.filter(user=request.user.id, leido=\"no\")[0]\n datos = {\n 'prioridad': 1,\n 'mensajes': mensajes.mensaje,\n 'id': mensajes.id\n }\n\n mensajes.leido = \"si\"\n mensajes.save()\n\n return HttpResponse(json.dumps(datos), content_type='application/json')\n except:\n datos = {\n 'prioridad': 0,\n 'mensajes': \"No tiene mensajes\",\n }\n return HttpResponse(json.dumps(datos), content_type='application/json')\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n# eliminar mensaje\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\ndef eliminar_mensaje(request, id_mensaje):\n id_user = request.user.id\n try:\n mensaje = Mensajes.objects.get(id=id_mensaje, user=id_user)\n mensaje.delete()\n\n datos = {\n 'prioridad': 1,\n 'mensajes': \"Ha sido eliminado el mensaje\",\n }\n\n\n return HttpResponse(json.dumps(datos), content_type='application/json')\n except:\n\n datos = {\n 'prioridad': 0,\n 'mensajes': \"Ha ocurrido un error\",\n }\n\n return HttpResponse(json.dumps(datos), content_type='application/json')","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"59368417","text":"A=list(input())\nnA=len(A)\nnewA=[]\nfor i in range(nA):\n if A[i].isdecimal():\n newA.append(int(A[i]))\nn=newA[0]\nk=newA[1]\n#print('n=',n,'k=',k)\nB=list(input())\nnB=len(B)\nnewB=[]\nfor j in range(nB):\n if B[j].isdecimal():\n newB.append(int(B[j]))\ndef bestbucket(K,S):\n n=len(S)\n new=[]\n for i in range(n):\n if S[i]==0:\n pass\n elif K%(S[i])==0:\n new.append(S[i])\n #print(new)\n t=1\n for i in range(len(new)):\n if new[i]>t:\n t=new[i]\n minitime=int(k/t)\n print(minitime)\n return 0\nbestbucket(k,newB)","sub_path":"Code/CodeRecords/2878/60746/320493.py","file_name":"320493.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"624730173","text":"from bioservices import biomart\nimport pandas as pd\nimport io\nimport requests\nimport sys\nfrom Bio import SeqIO\n\n\n# Load annotation\ngene_table_file = sys.argv[1]\ngene_table = pd.read_csv(gene_table_file)\ngene_table.set_index('acc',inplace=True)\n# Define column data types\ngene_table['chromosome'] = gene_table['chromosome'].astype(str)\nfor col in ['start','end','length','strand']:\n gene_table[col] = gene_table[col].astype(int)\n\n# Number of genes to be analyzed at a time\nchunk_size = int(sys.argv[2])\n# Setup server\nb = biomart.BioMart()\nb.host = 'www.ensembl.org'\n\ndatasets = b.datasets(\"ENSEMBL_MART_ENSEMBL\")\n\n# Set sequence file name\nseq_file = 'all_seqs.fa'\nfileO = open(seq_file,'a')\n# Record downloaded sequences\ndownloaded = [gene.name.split(\"|\")[2] for gene in SeqIO.parse(seq_file,'fasta')]\n\n# Filter table so that only non downloaded genes are processed\ngene_table = gene_table.loc[~(gene_table.index.isin(downloaded))]\n# Group table by species and chromosome\n# gene_table.set_index(['species','chromosome'],inplace=True)\n# Iterate over species and chromosomes\nfor sp, chrom in set(gene_table.set_index(['species','chromosome']).index):\n print(\"{}\\t{}\".format(sp,chrom))\n # Get dataset for each species\n sp_code = sp[0]+sp.split(\"_\")[-1]\n selected_dataset = ''\n for sp_dataset in datasets:\n if sp_code in sp_dataset.lower():\n selected_dataset = sp_dataset\n break\n assert selected_dataset != '', 'Dataset {} was not found'.format(sp_code)\n chrom_table = gene_table.loc[(gene_table['species']==sp)&\n (gene_table['chromosome']==chrom)]\n ids = chrom_table.index\n id_chunks = [ids[i:i+chunk_size] for i in range(0,len(ids),chunk_size)]\n # Configure search\n for chunk in id_chunks:\n b.new_query()\n b.add_dataset_to_xml(sp_dataset)\n b.add_attribute_to_xml('ensembl_gene_id')\n b.add_attribute_to_xml('peptide')\n ids_str = ','.join(chunk)\n b.add_filter_to_xml('ensembl_gene_id',ids_str)\n xml = b.get_xml()\n result = requests.get('http://useast.ensembl.org/biomart/martservice?query='+xml)\n try:\n tab_result = pd.read_csv(io.StringIO(result.text), sep='\\t',header=None)\n except:\n print(result.text)\n print(chunk)\n tab_result = tab_result.loc[:,['seq','acc']]\n tab_result.columns = ['seq','acc']\n #tab_result.set_index('acc',inplace=True)\n tab_result = tab_result.loc[tab_result['seq'] != 'Sequence unavailable']\n tab_result['length'] = tab_result['seq'].map(lambda x:len(x))\n # If there are more than one isoform with the max length, keep the first one\n tab_result.drop_duplicates(['acc','length'], inplace=True)\n max_isoforms = tab_result.groupby('acc').max()\n max_dict = max_isoforms['seq'].to_dict()\n max_genes = max_isoforms.index\n gene_slice = chrom_table.loc[max_genes] \n gene_slice['seq'] = gene_slice.index.map(lambda x: max_dict[x])\n gene_slice.reset_index(inplace=True)\n selected_data = gene_slice[['species','chromosome','acc','symbol',\n 'start','end','strand','seq']]\n selected_data = selected_data.astype(str)\n data_string = selected_data.set_index('species').to_records()\n formatted_list = ''\n for data_item in data_string:\n data = list(data_item)\n formatted_list += '>' + '|'.join(data[0:7]) + '\\n' + data[7] + '\\n'\n fileO.write(formatted_list)\n fileO.flush()\n","sub_path":"extras/get_sequences.py","file_name":"get_sequences.py","file_ext":"py","file_size_in_byte":3574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"357451841","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 16 20:52:55 2020\n\n@author: psardin\n\"\"\"\n\nfrom matplotlib import pyplot\nimport numpy as np\nimport pandas as pd\nimport math\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom statsmodels.tsa.arima_model import ARIMA\nimport statsmodels.api as sm\nfrom datetime import datetime\nfrom statsmodels.graphics.tsaplots import plot_acf, plot_pacf\n\n\n\n\n# Für das SARIMAX Modell wurde nur ein univariate Dataset verwendet, als \"prices\"\n# Die Vorhersage ist nicht gut gefallen, wahrscheinlich weil die Preise im Jahr 2018 im vergleich zum restlichen Datensatz höher sind.\n \ndef split_dataset(data):\n train_data, test_data = data[:train_split], data[train_split:]\n return train_data, test_data \n\ndef plotting_dalyPrices(train_data, test_data):\n plt.figure(figsize=(16,6))\n plt.plot(train_data.index, train_data, label = \"Train\")\n plt.plot(test_data.index, test_data, label = \"Test\")\n plt.legend()\n plt.grid(True)\n plt.show()\n \ndef the_modell(train_data):\n modell = sm.tsa.statespace.SARIMAX(train_data, order=(7,0,1), seasonal_order=(0, 1, 1,7)).fit()\n #modell = sm.tsa.statespace.SARIMAX(train_data, order=(7,0,1)).fit()\n return modell\n\n\n\n\n\n\ndata_rw = pd.read_pickle('data').reset_index()\ndata = data_rw[\"prices\"]\n\n# plt.matshow(data.corr())\n# plt.xticks(range(data.shape[1]), data, fontsize=14, rotation=90)\n# plt.gca().xaxis.tick_bottom()\n# plt.yticks(range(data.shape[1]), data, fontsize=14)\n\n# cb = plt.colorbar()\n# cb.ax.tick_params(labelsize=14)\n# plt.title(\"Feature Correlation Heatmap\", fontsize=14)\n# plt.show()\n\n\n\n\nscaler = MinMaxScaler(feature_range=(0, 1))\n# data = scaler.fit_transform(data_.values.reshape(-1))\n\n\ntrain_split = round(0.8569*len(data_rw))\n#val_split = round(0.18*train_split)\ntest_split = round(0.1430*len(data_rw))\n\n\nplot_acf(data)\n\n\ntrain_data, test_data = split_dataset(data)\nplotting_dalyPrices(train_data, test_data)\n\nmodell = the_modell(train_data)\n\nprice_pred = modell.predict(start = 1090, end = 1271, dynamic = False)\nprice_pred.index = test_data.index\n\n\nplt.figure(figsize=(20,6))\nplt.plot(train_data.index, train_data, label = \"Train\")\nplt.plot(test_data.index, test_data, label = \"Test\")\nplt.plot(price_pred, label = \"perd\")\nplt.legend()\nplt.grid(True)\nplt.show()\nplt.close()\n\n\n\n\n","sub_path":"patrick_task/modell_sarimax.py","file_name":"modell_sarimax.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"624893814","text":"import os\nfrom setuptools import find_packages, setup\n\n\ndef read(fname):\n with open(os.path.join(os.path.dirname(__file__), fname)) as f:\n return f.read()\n\n\nsetup(name='mumble', version='0.1.3', description='Python library for Mumble.',\n author='Tony Young', author_email='tony@rfw.name',\n url='https://github.com/rfw/python-mumble', license='MIT',\n packages=find_packages(), long_description=read('README.md'),\n classifiers=['Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.5'],\n install_requires=['protobuf>=3.0.0b1.post1', 'cffi'])\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"187889246","text":"try:\r\n # for Python2\r\n import Tkinter as tk\r\nexcept ImportError:\r\n # for Python3\r\n import tkinter as tk\r\n\r\nimport field, controls\r\n\r\nclass Application(tk.Tk):\r\n def __init__(self, *args, **kwargs):\r\n tk.Tk.__init__(self, *args, **kwargs)\r\n\r\n self.field = field.Field(self)\r\n self.field.pack(side=tk.BOTTOM)\r\n\r\n self.controls = controls.Controls(self)\r\n self.controls.pack(side=tk.TOP, expand=True, fill=tk.X)\r\n\r\nif __name__ == '__main__':\r\n app = Application()\r\n app.title(\"Conway's Game of Life\")\r\n app.mainloop()\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"69023303","text":"import logging\nimport re\nimport uuid\nfrom typing import Callable, Dict, List, Optional\n\nfrom actstream import action\nfrom django.conf import settings\nfrom django.db.models import Model\nfrom django.db.models.signals import m2m_changed, post_delete, post_save\nfrom django.http import HttpRequest, HttpResponse\n\nfrom server.apps.main.models import Consent, LegalBasis\n\nlogger = logging.getLogger(__name__)\n\n\nclass AuditLogMiddleware:\n def __init__(self, get_response) -> None:\n self.get_response = get_response\n\n def __call__(self, request) -> HttpResponse:\n\n signal_calls = self.get_signal_calls(request)\n\n for call in signal_calls:\n call[\"signal\"].connect(weak=False, **call[\"kwargs\"])\n\n response = self.get_response(request)\n\n for call in signal_calls:\n call[\"signal\"].disconnect(**call[\"kwargs\"])\n\n return response\n\n def get_signal_calls(self, request: HttpRequest) -> List[Dict]:\n return [\n {\n \"signal\": post_save,\n \"kwargs\": {\n \"sender\": LegalBasis,\n \"receiver\": self.make_save_signal_receiver(request),\n \"dispatch_uid\": uuid.uuid4(),\n },\n },\n {\n \"signal\": post_delete,\n \"kwargs\": {\n \"sender\": LegalBasis,\n \"receiver\": self.make_delete_signal_receiver(request),\n \"dispatch_uid\": uuid.uuid4(),\n },\n },\n {\n \"signal\": m2m_changed,\n \"kwargs\": {\n \"sender\": LegalBasis.consents.through,\n \"receiver\": self.make_m2m_signal_receiver(request),\n \"dispatch_uid\": uuid.uuid4(),\n },\n },\n ]\n\n def make_m2m_signal_receiver(self, request: HttpRequest) -> Callable:\n def inner(sender: Model, **kwargs) -> None:\n action_kwargs = {\n \"sender\": request.user,\n \"remote_addr\": self.get_remote_addr(request),\n }\n\n if kwargs[\"action\"] in [\"post_add\", \"post_remove\"]:\n self.handle_m2m_post_add_remove_actions(\n instance=kwargs[\"instance\"],\n action_kwargs=action_kwargs,\n action_name=kwargs[\"action\"],\n pk_set=kwargs[\"pk_set\"],\n )\n\n if kwargs[\"action\"] == \"post_clear\":\n self.handle_m2m_post_clear_action(\n instance=kwargs[\"instance\"], action_kwargs=action_kwargs\n )\n\n return inner\n\n def handle_m2m_post_add_remove_actions(\n self, instance: Model, action_kwargs: Dict, action_name: str, pk_set: List\n ) -> None:\n for pk in pk_set:\n action_kwargs[\"verb\"] = \"Add\" if action_name == \"post_add\" else \"Remove\"\n action_kwargs[\"action_object\"] = Consent.objects.get(pk=pk)\n action_kwargs[\"target\"] = instance\n\n action.send(**action_kwargs)\n logger.info(f\"Action sent: {action_kwargs}\")\n\n def handle_m2m_post_clear_action(\n self, instance: Model, action_kwargs: Dict\n ) -> None:\n action_kwargs[\"verb\"] = \"Update\"\n action_kwargs[\"action_object\"] = instance\n\n action.send(**action_kwargs)\n logger.info(f\"Action sent: {action_kwargs}\")\n\n def make_save_signal_receiver(self, request: HttpRequest) -> Callable:\n def inner(sender: Model, **kwargs) -> None:\n action_kwargs = {\n \"sender\": request.user,\n \"action_object\": kwargs[\"instance\"],\n \"verb\": \"Create\" if kwargs.get(\"created\") is True else \"Update\",\n \"remote_addr\": self.get_remote_addr(request),\n }\n\n action.send(**action_kwargs)\n logger.info(f\"Action sent: {action_kwargs}\")\n\n return inner\n\n def make_delete_signal_receiver(self, request: HttpRequest) -> Callable:\n def inner(sender: Model, **kwargs) -> None:\n action_kwargs = {\n \"sender\": request.user,\n \"action_object\": kwargs[\"instance\"],\n \"verb\": \"Delete\",\n \"remote_addr\": self.get_remote_addr(request),\n }\n\n action.send(**action_kwargs)\n logger.info(f\"Action sent: {action_kwargs}\")\n\n return inner\n\n def get_remote_addr(self, request: HttpRequest) -> Optional[str]:\n remote_addr = request.META.get(\"HTTP_X_FORWARDED_FOR\")\n if remote_addr is not None:\n return remote_addr.split(\",\")[0]\n return request.META.get(\"REMOTE_ADDR\")\n\n\nclass NeverCacheMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n response[\"Cache-Control\"] = \"no-cache, no-store, must-revalidate, private\"\n response[\"Pragma\"] = \"no-cache\"\n return response\n\n\nclass SslRedirectExemptHostnamesMiddleware:\n \"\"\"\n Exempts requests from SSL redirect based on hostname\n \"\"\"\n\n def __init__(self, get_response=None):\n self.get_response = get_response\n self.redirect = settings.SECURE_SSL_REDIRECT\n self.redirect_host = settings.SECURE_SSL_HOST\n self.redirect_exempt_hostnames = [\n re.compile(r) for r in settings.SECURE_SSL_REDIRECT_EXEMPT_HOSTNAMES\n ]\n\n def __call__(self, request):\n request.is_allow_secure_middleware_active = True\n host = self.redirect_host or request.get_host()\n\n if self.redirect and any(\n pattern.search(host) for pattern in self.redirect_exempt_hostnames\n ):\n request.is_allow_secure_middleware_active = False\n request.META[\"HTTP_X_FORWARDED_PROTO\"] = \"https\"\n return self.get_response(request)\n","sub_path":"server/apps/main/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":5914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84465344","text":"import logging\nimport asyncio\nfrom aiohttp import web\nimport numpy as np\nimport png\nimport io\n\nlogger = logging.getLogger(__name__)\n\nclass HttpServer:\n\n def __init__(self, port, loop=None):\n self._loop = loop or asyncio.get_event_loop()\n self._port = port\n\n self._app = None\n self._connections_factory = None\n self._server = None\n\n def configure_router(self, router):\n router.add_route('GET', '/', self.get_main_page)\n router.add_route('GET', '/map', self.request_map)\n router.add_route('GET', '/overlay', self.request_overlay)\n router.add_route('GET', '/terrain/{detail}/{y}/{x}.terrain', self.request_terrain)\n router.add_route('GET', '/terrain/layer.json', self.request_terrain_layer_json)\n router.add_static('/', 'static')\n\n @asyncio.coroutine\n def start(self):\n self._app = web.Application()\n self.configure_router(self._app.router)\n self._connections_factory = self._app.make_handler()\n self._server = yield from self._loop.create_server(self._connections_factory, '0.0.0.0', self._port)\n logger.info('Server started at port={}.'.format(self._port))\n\n @asyncio.coroutine\n def stop(self):\n self._server.close()\n yield from self._connections_factory.finish_connections()\n yield from self._app.finish()\n\n @asyncio.coroutine\n def request_map(self, request):\n pixels = np.zeros((256, 256, 3), np.uint8)\n pixels[:] = (0, 255, 0)\n buf = io.BytesIO()\n png.from_array(pixels, mode='RGB').save(buf)\n return web.Response(body=buf.getvalue())\n\n @asyncio.coroutine\n def request_overlay(self, request):\n pixels = np.zeros((256, 256, 4), np.uint8)\n pixels[:] = (255, 0, 0, 100)\n pixels[::16, :, :] = (255, 0, 0, 255)\n pixels[:, ::32, :] = (255, 0, 0, 255)\n buf = io.BytesIO()\n png.from_array(pixels, mode='RGBA').save(buf)\n return web.Response(body=buf.getvalue())\n\n @asyncio.coroutine\n def request_terrain(self, request):\n heights = np.zeros((65, 65), np.uint16)\n heights[:] = np.arange(0, 65000, 1000)\n heights = heights.reshape(-1)\n meta = np.array([15, 0], np.uint8)\n return web.Response(body=heights.tostring() + meta.tostring())\n\n @asyncio.coroutine\n def request_terrain_layer_json(self, request):\n return web.Response(text=\"\"\"\n{\n \"tilejson\": \"2.1.0\",\n \"format\": \"heightmap-1.0\",\n \"version\": \"1.0.0\",\n \"scheme\": \"tms\",\n \"tiles\": [\"{z}/{x}/{y}.terrain\"]\n}\n\"\"\", headers={'Access-Control-Allow-Origin': '*'})\n\n @asyncio.coroutine\n def get_main_page(self, request):\n with open('static/index.html', 'rb') as inp:\n return web.Response(body=inp.read())","sub_path":"src/pancake/web/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"57391883","text":"from jqdata import *\nimport pandas as pd\n\nauth('18867101271','157268ak')\nq = query(jy.LC_IndexDerivative.TradingDay,\n jy.LC_IndexDerivative.PB_LF,\n\n ).filter(jy.LC_IndexDerivative.IndexCode == \"4978\",\n jy.LC_IndexDerivative.TradingDay<='2020-04-17'\n ).order_by(\n jy.LC_IndexDerivative.TradingDay)\ndf = jy.run_query(q).set_index(\"TradingDay\")\ndf.index = pd.to_datetime(df.index)\nprice_df = get_price(\"000905.XSHG\",end_date='2020-04-17',start_date=df.index[0],fields='close').close\n\ndef max_down_num(x): #计算回撤超过20%的天数\n returns = (x - x[0])/x[0]\n return (returns<-0.2).sum()\n\ndf['max_down_count'] = price_df.rolling(252).apply(max_down_num,raw=True).shift(-252)\ndf['max_down_count2'] = price_df.rolling(252*2).apply(max_down_num,raw=True).shift(-252*2)\n\ndf['is_in_limit'] = (df.PB_LF< df.PB_LF.iloc[-1]+0.3)&(df.PB_LF>df.PB_LF.iloc[-1]-0.3)","sub_path":"500oneyear.py","file_name":"500oneyear.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"33408067","text":"'''This is the main file for the tetris API.\n\nIt makes calls to the Postgres DB.\n'''\n\nimport datetime\nfrom typing import Tuple, Any\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import Flask, request, jsonify, Blueprint, Response\n\nfrom .config import DB_URI\nfrom .constants import ERROR_MESSAGE, SUCCESS_MESSAGE\n\nAPP = Flask(__name__)\nAPP.config.update(\n SQLALCHEMY_DATABASE_URI=DB_URI,\n SQLALCHEMY_TRACK_MODIFICATIONS=False,\n)\n\nDB = SQLAlchemy(APP)\nAPI_BLUEPRINT = Blueprint('api', __name__, url_prefix='/flask')\n\nclass Leaderboard(DB.Model): #type:ignore\n '''SQLAlchemy Leaderboard table model for the API.'''\n id = DB.Column(DB.Integer, primary_key=True) #pylint: disable=no-member\n name = DB.Column(DB.String(50), nullable=False) #pylint: disable=no-member\n\n score = DB.Column(DB.Integer, nullable=False) #pylint: disable=no-member\n\n date_time = DB.Column( #pylint: disable=no-member\n DB.TIMESTAMP, #pylint: disable=no-member\n nullable=False,\n default=datetime.datetime.utcnow,\n )\n\n def __repr__(self) -> str:\n return '%s,%s' % (self.name, self.score)\n\n@API_BLUEPRINT.route('/register', methods=('POST',))\ndef register() -> Tuple[str, int]:\n name = request.form.get('name')\n score: Any = request.form.get('score')\n\n if not name:\n error = 'A name should be sent.'\n return jsonify({'message': ERROR_MESSAGE, 'error': error}), 400\n\n try:\n score = int(float(score))\n except (TypeError, ValueError):\n error = 'A score should be sent.'\n return jsonify({'message': ERROR_MESSAGE, 'error': error}), 400\n\n new_registry = Leaderboard(name=name, score=score)\n DB.session.add(new_registry) #pylint: disable=no-member\n DB.session.commit() #pylint: disable=no-member\n\n post_response = {\n 'registry': {\n 'id': new_registry.id,\n 'name': new_registry.name,\n 'score': new_registry.score,\n 'date_time': new_registry.date_time,\n },\n 'message': SUCCESS_MESSAGE,\n }\n return jsonify(post_response), 200\n\n@API_BLUEPRINT.route('/leaderboard', methods=('GET',))\ndef leaderboard() -> Tuple[str, int]:\n posts = Leaderboard.query.order_by(\n Leaderboard.score.desc(), Leaderboard.name.asc()).limit(10).all()\n\n # the parens make the post_response a generator\n posts_response = (\n {\n 'name': ranker.name,\n 'score': ranker.score,\n }\n for ranker in posts\n )\n # by calling list(generator) python iterates through the generator and\n # creates a list with its components\n return jsonify(list(posts_response)), 200\n\n@API_BLUEPRINT.route('/rankings', methods=('GET',))\ndef rankings() -> Tuple[str, int]:\n ranking = Leaderboard.query.order_by(\n Leaderboard.score.desc(), Leaderboard.name.asc()).all()\n\n post_response = (\n {\n 'id': ranker.id,\n 'name': ranker.name,\n 'score': ranker.score,\n 'date_time': ranker.date_time,\n }\n for ranker in ranking\n )\n return jsonify(list(post_response)), 200\n\nAPP.register_blueprint(API_BLUEPRINT)\n\n@APP.route('/')\ndef index() -> str:\n return 'Flask API Running'\n","sub_path":"api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"467061599","text":"import os\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.files.storage import FileSystemStorage\nfrom django.db.models.fields.files import FileField\nfrom django.core.files.storage import default_storage\n\n\ndef file_cleanup(sender, **kwargs):\n for fieldname in [f.name for f in sender._meta.get_fields()]:\n try:\n field = sender._meta.get_field(fieldname)\n except:\n field = None\n if field and isinstance(field, FileField):\n inst = kwargs['instance']\n f = getattr(inst, fieldname)\n m = inst.__class__._default_manager\n if hasattr(f, 'path') and os.path.exists(f.path) \\\n and not m.filter(**{'%s__exact' % fieldname: getattr(inst, fieldname)})\\\n .exclude(pk=inst._get_pk_val()):\n try:\n #os.remove(f.path)\n default_storage.delete(f.path)\n except:\n pass","sub_path":"yoohalal/apps/career/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"451444248","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of Invenio.\n# Copyright (C) 2016-2021 CERN.\n#\n# Invenio is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Command-line tools for demo module.\"\"\"\n\nimport click\nfrom faker import Faker\nfrom flask.cli import with_appcontext\nfrom invenio_access.permissions import system_identity\nfrom invenio_communities.proxies import current_communities\n\nfrom .fixtures.demo import create_fake_community\nfrom .fixtures.tasks import create_demo_community\n\n\n@click.group()\ndef communities():\n \"\"\"Invenio communities commands.\"\"\"\n\n\n@communities.command('demo')\n@with_appcontext\ndef demo():\n \"\"\"Create 100 fake communities for demo purposes.\"\"\"\n click.secho('Creating demo communities...', fg='green')\n faker = Faker()\n for _ in range(100):\n fake_data = create_fake_community(faker)\n create_demo_community.delay(fake_data)\n\n click.secho('Created communities!', fg='green')\n\n\n@communities.command(\"rebuild-index\")\n@with_appcontext\ndef rebuild_index():\n click.secho(\"Reindexing communities...\", fg=\"green\")\n\n communities_service = current_communities.service\n communities_service.rebuild_index(identity=system_identity)\n\n click.secho(\"Reindexed communities!\", fg=\"green\")\n","sub_path":"invenio_communities/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"605356704","text":"#! /usr/bin/env python\n\n#Import\nimport sys\nimport ctypes\nimport numpy as np\nfrom OpenGL.GL import *\nimport glfw\n\n#Variables\nvertex_code = open(\"shader_vertex\", 'r').read()\nfragment_code = open(\"shader_fragment\", 'r').read()\n\n#----------------------------------------------------------#\n#\t\t\t\t\t\t\tGLFW\n#----------------------------------------------------------#\ndef GLFWinit():\n\tglobal window\n\t# Initialize the library\n\tif not glfw.init():\n\t\treturn\n\n\t# Create a windowed mode window and its OpenGL context\n\twindow = glfw.create_window(640, 480, \"Hello World\", None, None)\n\tif not window:\n\t\tglfw.terminate()\n\t\treturn\n\n\t# Make the window's context current\n\tglfw.make_context_current(window)\n\ndef GLFWloop():\n\t# Loop until the user closes the window\n\twhile not glfw.window_should_close(window):\n\t\t# Render here, e.g. using pyOpenGL\n\t\tdisplay()\n\t\t# Swap front and back buffers\n\t\tglfw.swap_buffers(window)\n\n\t\t# Poll for and process events\n\t\tglfw.poll_events()\n\n\tglfw.terminate()\n\ndef display():\n glClear(GL_COLOR_BUFFER_BIT)\n glDrawArrays(GL_TRIANGLE_STRIP, 0, 4)\n\nGLFWinit()\n#----------------------------------------------------------#\n#\t\t\t\t\t\t Build data\n#----------------------------------------------------------#\ndata = np.zeros(4, [(\"position\", np.float32, 2),\n\t\t\t\t\t(\"color\", np.float32, 4)])\ndata['color'] = [(1,1,1,1)]\ndata['position'] = [(-0.4,-0.4), (-0.4,+0.4), (+0.4,-0.4), (+0.4,+0.4)]\n\n#----------------------------------------------------------#\n#\t\t\t\t\tBuild shaders\n#----------------------------------------------------------#\n# Request a program and shader slots from GPU\nprogram = glCreateProgram()\nvertex = glCreateShader(GL_VERTEX_SHADER)\nfragment = glCreateShader(GL_FRAGMENT_SHADER)\n\n# Set shaders source\nglShaderSource(vertex, vertex_code)\nglShaderSource(fragment, fragment_code)\n\n# Compile shaders\nglCompileShader(vertex)\nglCompileShader(fragment)\n\n# Attach shader objects to the program\nglAttachShader(program, vertex)\nglAttachShader(program, fragment)\n\n# Build program\nglLinkProgram(program)\n\n# Get rid of shaders (no more needed)\nglDetachShader(program, vertex)\nglDetachShader(program, fragment)\n\n# Make program the default program\nglUseProgram(program)\n\n#----------------------------------------------------------#\n# \t\t\t\t\t\tBuild buffer\n#----------------------------------------------------------#\n\n# Request a buffer slot from GPU\nbuffer = glGenBuffers(1)\n\n# Make this buffer the default one\nglBindBuffer(GL_ARRAY_BUFFER, buffer)\n\n# Upload data\nglBufferData(GL_ARRAY_BUFFER, data.nbytes, data, GL_DYNAMIC_DRAW)\n\n# Bind attributes\nstride = data.strides[0]\noffset = ctypes.c_void_p(0)\nloc = glGetAttribLocation(program, \"position\")\nglEnableVertexAttribArray(loc)\nglBindBuffer(GL_ARRAY_BUFFER, buffer)\nglVertexAttribPointer(loc, 3, GL_FLOAT, False, stride, offset)\n\noffset = ctypes.c_void_p(data.dtype[\"position\"].itemsize)\nloc = glGetAttribLocation(program, \"color\")\nglEnableVertexAttribArray(loc)\nglBindBuffer(GL_ARRAY_BUFFER, buffer)\nglVertexAttribPointer(loc, 4, GL_FLOAT, False, stride, offset)\n\n# Bind uniforms\nloc = glGetUniformLocation(program, \"scale\")\nglUniform1f(loc, 1.0)\n\n#----------------------------------------------------------#\n# \t\t\t\t\t\tMain()\n#----------------------------------------------------------#\nGLFWloop()\n","sub_path":"2d_map.py","file_name":"2d_map.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"354410404","text":"\nclass Player:\n\n\n def __init__(self, castles):\n self.__life = 10\n self.__treasure = 0\n self.__castles = castles\n\n\n\n def get_life(self):\n return self.__life\n\n\n\n def select_castle(self, castles):\n try:\n castle_id = int(input(f'Select Castle! (1-{len(castles)}): '))\n return self.__castles[castle_id-1]\n except Exception:\n self.select_castle(castles)\n\n\n\n def select_room(self, castle):\n try:\n print(castle)\n room_id = int(input(f'Select Room! (1-{castle.get_room_number()}): '))\n return castle.get_room(room_id - 1)\n except Exception:\n self.select_room(castle)\n\n\n\n def fight(self, room):\n room.get_creature().fight()\n self.__life -= 1\n self.__treasure += room.get_treasure_value()\n print(f'You killed the monster! HP={self.__life}')\n\n\n\n def bluff(self, room):\n if room.get_creature().bluffing():\n print('Successful bluff!')\n self.__treasure += room.get_treasure_value()\n else:\n print('Next time Bro!')\n\n\n\n def interact_room(self, room):\n if room.is_free():\n option = int(input('Fight or Bluff? (1-2): '))\n if option == 1:\n self.fight(room)\n elif option == 2:\n self.bluff(room) \n\n\n\n def act(self):\n castle = self.select_castle(self.__castles)\n room = self.select_room(castle)\n self.interact_room(room) \n\n","sub_path":"castles_and_creatures/Player.py","file_name":"Player.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"472184788","text":"\"\"\"PyAudio Example: Play a WAVE file.\"\"\"\n\nimport pyaudio\nimport wave\nimport sys\nimport audioop\nimport glob\n\n\nCHUNK = 1024\n\nif len(sys.argv) < 2:\n print(\"Plays a wave file.\\n\\nUsage: %s filename.wav\" % sys.argv[0])\n sys.exit(-1)\n\n# print(sys.argv)\n\n\nfor file in glob.glob(sys.argv[1]):\n print(file)\n\n wf = wave.open(file, 'rb')\n\n wf2 = wave.open('dist/' + file, 'wb');\n wf2.setnchannels(wf.getnchannels())\n wf2.setsampwidth(wf.getsampwidth())\n wf2.setframerate(wf.getframerate())\n\n # p = pyaudio.PyAudio()\n # stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),\n # channels=wf.getnchannels(),\n # rate=wf.getframerate(),\n # output=True)\n\n last_rms = -1\n merge = False\n seg = []\n w_seg = []\n v_seg = []\n i = 0\n frames = []\n\n data = wf.readframes(CHUNK)\n while len(data):\n rms = audioop.rms(data, 2)\n\n if rms and (not last_rms):\n # if (len(w_seg) <= 7) and (not merge):\n # merge = True\n # # v_seg = []\n # w_seg = []\n # else:\n \n # print('%d: v(%d) w(%d)' % (i, len(v_seg), len(w_seg)))\n # i += 1\n\n # merge = False\n\n if len(v_seg) > 1000:\n pass\n else:\n if 0 < len(w_seg) < 30:\n for x in range(30-len(w_seg)):\n seg.append(w_seg[0])\n\n # for d in seg:\n # stream.write(d)\n frames.extend(seg)\n frames.extend(seg)\n\n seg = []\n v_seg = []\n w_seg = []\n\n if rms:\n v_seg.append(data)\n else:\n w_seg.append(data)\n seg.append(data)\n\n data = wf.readframes(CHUNK)\n last_rms = rms\n\n # stream.stop_stream()\n # stream.close()\n # p.terminate()\n\n wf2.writeframes(b''.join(frames))\n wf2.close()\n\n # break\n","sub_path":"_py/soundsplit/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"506151013","text":"# Python 3\n# Learning machine\nimport tensorflow as tf\nimport tensorflow.contrib.eager as tfe\nimport matplotlib.pyplot as plt\nimport csvparser as parser\n\ndef loss(model, x, y):\n\ty_ = model(x)\n\treturn tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)\n\t\ndef grad(model, inputs, targets):\n\t\twith tf.GradientTape() as tape:\n\t\t\tloss_value = loss(model, inputs, targets)\n\t\treturn tape.gradient(loss_value, model.variables)\n\t\t\ndef train(train_dataset):\n\ttrain_dataset = train_dataset.skip(1)\t\t\t\t\t# skip the first header row\n\ttrain_dataset = train_dataset.map(parser.parse_csv)\t\t# parse each row\n\ttrain_dataset = train_dataset.shuffle(buffer_size=1000)\t# randomize\n\ttrain_dataset = train_dataset.batch(32)\n\t\n\t# View a single example entry from a batch\n\tfeatures, label = iter(train_dataset).next()\n\tprint(\"example features:\", features[0])\n\tprint(\"example label:\", label[0])\n\t\n\t# Create a model\n\tmodel = tf.keras.Sequential([\n\t\ttf.keras.layers.Dense(10, activation=\"relu\", input_shape=(4,)),\t# input shape required\n\t\ttf.keras.layers.Dense(10, activation=\"relu\"),\n\t\ttf.keras.layers.Dense(3)\n\t])\n\n\t# Create an optimizer\n\toptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\n\n\t# training loop\n\t## Note : rerunning this cell uses the same model variables\n\n\t# keep results for plotting\n\ttrain_loss_results = []\n\ttrain_accuracy_results = []\n\n\tnum_epochs = 201\n\n\tfor epoch in range(num_epochs):\n\t\tepoch_loss_avg = tfe.metrics.Mean()\n\t\tepoch_accuracy = tfe.metrics.Accuracy()\n\n\t\t# Training loop - using batches of 32\n\t\tfor x, y, in train_dataset:\n\t\t\t# Optimize the model\n\t\t\tgrads = grad(model, x, y)\n\t\t\toptimizer.apply_gradients(zip(grads, model.variables),\n\t\t\t\t\t\tglobal_step=tf.train.get_or_create_global_step())\n\n\t\t\t# Track progress\n\t\t\tepoch_loss_avg(loss(model, x, y)) \t# add current batch loss\n\t\t\t# compare predicted label to actual label\n\t\t\tepoch_accuracy(tf.argmax(model(x), axis=1, output_type=tf.int32), y)\n\n\t\t#end epoch\n\t\ttrain_loss_results.append(epoch_loss_avg.result())\n\t\ttrain_accuracy_results.append(epoch_accuracy.result())\n\n\t\tif epoch % 50 == 0:\n\t\t\tprint(\"Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}\".format(epoch,\n\t\t\t\t\t\t\t\t\t\tepoch_loss_avg.result(),\n\t\t\t\t\t\t\t\t\t\tepoch_accuracy.result()))\n\t\t\n\t# Visualize the loss function over time\n\tfig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))\n\tfig.suptitle('Training Metrics')\n\n\taxes[0].set_ylabel(\"Loss\", fontsize=14)\n\taxes[0].plot(train_loss_results)\n\n\taxes[1].set_ylabel(\"Accuracy\", fontsize=14)\n\taxes[1].set_xlabel(\"Epoch\", fontsize=14)\n\taxes[1].plot(train_accuracy_results)\n\n\tplt.show()\t\n\t\t\t\t\t\t\t\n\treturn model\n","sub_path":"learningmachine.py","file_name":"learningmachine.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"578952040","text":"# -*- coding: utf-8 -*-\n\n'''\n 生成器\n'''\n\nimport random\n\n\ndef even_generator(n = 5):\n for i in range(n):\n print(\"Gen %d\"%i)\n yield(i*2)\n print(\"Gen %d done\"%(i))\n\n\ndef triangles():\n tri = [1]\n while True:\n yield(tri)\n tri = [x+tri[pos+1] for pos, x in enumerate(tri) if pos < len(tri) - 1]\n tri.insert(0, 1);\n tri.append(1);\n\n\ndef parent_generator():\n b1 = yield from sub_generator()\n print('Get result from sub_generator 1 = %s'%b1)\n b2 = yield from sub_generator()\n print('Get result from sub_generator 2 = %s'%b2)\n return 'parent'\n\n\ndef sub_generator():\n r1 = yield 1\n r2 = yield 2\n return random.randint(1, 100)\n\n\nif __name__ == \"__main__\":\n g = parent_generator()\n print(g.send(None))\n g.close()\n try:\n #g.throw(StopIteration)\n while True:\n print(g.send(None))\n except StopIteration as i:\n print('StopIteration caught and value is ', i)","sub_path":"src/study/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"568387187","text":"import cgitb; cgitb.enable()\nimport cgi\n\nfrom flask import Flask, render_template\napp = Flask(__name__)\n\n\n@app.route(\"/results\")\ndef results():\n inputs = cgi.FieldStorage()\n print(inputs)\n return render_template(\"results.html\")\n\n@app.route(\"/\")\ndef home():\n return render_template(\"home.html\")\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n \n\n\n\n \n","sub_path":"data_project/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"109886335","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.index1),\n path('ajax/validate_username/', views.validate_username, name='validate_username'),\n path('question/', views.index2, name='index2'),\n path('question/answer//', views.index3, name='index3'),\n path('question/activate/', views.endian_activated, name='endian'),\n path('question/lifeline//', views.endian_marking, name='indexx'),\n path('question/logout/', views.index4, name='login_logout'),\n]\n","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"129026959","text":"# coding=utf-8\n# 此文档是把RGG图像转化为灰度图\nimport numpy\nfrom PIL import Image\nfrom skimage import color\nimport cv2\nimport os\nfrom pylab import *\n\n# 方法一:利用公式计算\nimgpath = \"X:\\jet_python\\ipiut2\\\\1_1_cut/1_1.bmp\"\n# f, ext = os.path.splitext(imgpath)\nlena = cv2.imread(imgpath)\nimg = lena\nheight = img.shape[0]\nwidth = img.shape[1]\nchannels = img.shape[2]\nvalue = [0] * 3\ngray_img = numpy.zeros([height, width], numpy.uint8)\n\nfor row in range(height):\n for column in range(width):\n for chan in range(channels):\n value[chan] = img[row, column, chan]\n R = value[2]\n G = value[1]\n B = value[0]\n # new_value = 0.2989 * R + 0.5870 * G + 0.1140 * B\n new_value = 0.2989 * R + 0.5870 * G + 0.1140 * B # 转为灰度像素\n gray_img[row, column] = new_value\n\ngray_img = Image.fromarray(uint8(gray_img))\ngray_img.save(\"./data/1_22222.bmp\")\n\n\n# 方法二:利用python自带的方法。\n# imgpath = \"X:\\jet_python\\ipiut2\\\\1_1_cut/1_1.bmp\"\n# img = Image.open(imgpath)\n# img = img.convert(\"L\")\n# img.save(\"./data/1_11111.bmp\")\n","sub_path":"production/st_rgb_to_gray.py","file_name":"st_rgb_to_gray.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"547779484","text":"\"\"\"\nCreated on 2019-02-20\n@author: duytinvo\n\"\"\"\nimport argparse\nfrom mlmodels.inference.trans_language_serve import LM\n\n\ndef load_model(args):\n model_api = LM(args)\n return model_api\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--model_type\", default=None, type=str, help=\"Model type selected in the list \")\n parser.add_argument(\"--model_name_or_path\", type=str,\n default=\"/media/data/review_response/trained_model/checkpoint_by-step_175000/\",\n help=\"Path to pre-trained model or shortcut name selected in the list\")\n\n parser.add_argument(\"--prompt\", type=str,\n default=\" 1 \"\n \" the gates hotel south beach - a doubletree by hilton \"\n \" mrs.m \"\n \" nasty \"\n \" this has to be the nastiest hotel ever. \"\n \"\")\n parser.add_argument(\"--length\", type=int, default=200)\n parser.add_argument(\"--stop_token\", type=str, default=None, help=\"Token at which text generation is stopped\")\n parser.add_argument(\"--temperature\", type=float, default=1.0,\n help=\"temperature of 1.0 has no effect, lower tend toward greedy sampling\",)\n parser.add_argument(\"--repetition_penalty\", type=float, default=1.0,\n help=\"primarily useful for CTRL model; in that case, use 1.2\")\n parser.add_argument(\"--k\", type=int, default=0)\n parser.add_argument(\"--p\", type=float, default=0.9)\n\n parser.add_argument(\"--padding_text\", type=str, default=\"\", help=\"Padding text for Transfo-XL and XLNet.\")\n parser.add_argument(\"--xlm_language\", type=str, default=\"\", help=\"Optional language when used with the XLM model.\")\n\n parser.add_argument(\"--seed\", type=int, default=42, help=\"random seed for initialization\")\n parser.add_argument(\"--no_cuda\", action=\"store_false\", help=\"Avoid using CUDA when available\")\n parser.add_argument(\"--num_return_sequences\", type=int, default=1, help=\"The number of samples to generate.\")\n args = parser.parse_args()\n lm_api = LM(args)\n\n generated_sequences = lm_api.inference(\n rv_hotel=\"hyatt regency calgary\",\n rv_name=\"tin\",\n rv_rate=\"1\",\n rv_title=\"unworthy\",\n rv_text=\"Service was really good. Staff members were friendly and helpful. \"\n \"Was not the cleanest hotel. For this price I can find a much cleaner and better hotel. \"\n \"Paid parking for $30 sucks, paid breakfast for $40 sucks, rooms were too small. \"\n \"View was good from the rooms. Uneven beds, got neck pain next day when I realized it. \"\n \"Overall, will never go to them again.\")\n","sub_path":"mlmodels/demo/trans_language_inference.py","file_name":"trans_language_inference.py","file_ext":"py","file_size_in_byte":2951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"425246356","text":"from flask import Flask, abort, request, jsonify, render_template \nimport json\nimport uuid\napp = Flask(__name__, template_folder='.')\n\nfrom slurmpy import Slurm\n\n\n\n@app.route('/')\ndef main_handler():\n return render_template('index.html')\n\n@app.route('/submitjob', methods=[\"POST\"])\ndef submitJob():\n if not request.json:\n abort(400)\n body = request.json\n code = body[\"code\"]\n body.pop('code', None) # remove key\n account = body[\"account\"]\n if not account:\n abort(400)\n kargs= {\"partition\" : \"debug\"}\n for key, value in body.items():\n kargs[key] = value\n\n print(kargs)\n s = Slurm(str(uuid.uuid4()), kargs)\n code = \"MYDATA=/data/\"+account+\"\\n\"+code\n x = s.run(code);\n print(\"result\",x)\n return jsonify(x)\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8888, debug=False)\n\n\n\n\n\n\n\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"577551818","text":"# solutions.py\n\"\"\"Volume IB: Testing.\n\n\n\"\"\"\nimport math\n\n# Problem 1 Write unit tests for addition().\n# Be sure to install pytest-cov in order to see your code coverage change.\n\n\ndef addition(a, b):\n return a + b\n\n\ndef smallest_factor(n):\n \"\"\"Finds the smallest prime factor of a number.\n Assume n is a positive integer.\n \"\"\"\n if n == 1:\n return 1\n for i in range(2, int(math.sqrt(n)) + 1):\n if n % i == 0:\n return i\n return n\n\n\n# Problem 2 Write unit tests for operator().\ndef operator(a, b, oper):\n if type(oper) != str:\n raise ValueError(\"Oper should be a string\")\n if len(oper) != 1:\n raise ValueError(\"Oper should be one character\")\n if oper == \"+\":\n return a + b\n if oper == \"/\":\n if b == 0:\n raise ValueError(\"You can't divide by zero!\")\n return a/float(b)\n if oper == \"-\":\n return a-b\n if oper == \"*\":\n return a*b\n else:\n raise ValueError(\"Oper can only be: '+', '/', '-', or '*'\")\n\n# Problem 3 Write unit test for this class.\nclass ComplexNumber(object):\n def __init__(self, real=0, imag=0):\n self.real = real\n self.imag = imag\n\n def conjugate(self):\n return ComplexNumber(self.real, -self.imag)\n\n def norm(self):\n return math.sqrt(self.real**2 + self.imag**2)\n\n def __add__(self, other):\n real = self.real + other.real\n imag = self.imag + other.imag\n return ComplexNumber(real, imag)\n\n def __sub__(self, other):\n real = self.real - other.real\n imag = self.imag - other.imag\n return ComplexNumber(real, imag)\n\n def __mul__(self, other):\n real = self.real*other.real - self.imag*other.imag\n imag = self.imag*other.real + other.imag*self.real\n return ComplexNumber(real, imag)\n\n def __truediv__(self, other):\n if other.real == 0 and other.imag == 0:\n raise ValueError(\"Cannot divide by zero\")\n bottom = (other.conjugate()*other*1.).real\n top = self*other.conjugate()\n return ComplexNumber(top.real / bottom, top.imag / bottom)\n\n def __eq__(self, other):\n return self.imag == other.imag and self.real == other.real\n\n def __str__(self):\n return \"{}{}{}i\".format(self.real, '+' if self.imag >= 0 else '-',\n abs(self.imag))\n\n# Problem 5: Write code for the Set game here\n\nclass Hand(object):\n\n def __init__(self, filename):\n\n if filename[-4:] != \".txt\":\n raise ValueError(\"This is not a valid file name.\")\n self.name = filename\n file = open(filename, 'r')\n cards = []\n newlines = []\n lines = file.readlines()\n for line in lines:\n newlines.append(line.replace(\"\\n\",\"\"))\n for line in newlines:\n if line not in cards:\n cards.append(line)\n for card in cards:\n if len(card) != 4:\n raise ValueError(\"There is a 'card' with invalid number of attributes.\")\n for c in card:\n if int(c) < 0 or int(c)>2:\n raise ValueError(\"There is a 'card' with invalid attributes.\")\n if len(cards) != 12:\n raise ValueError(\"There are not exactly 12 cards.\")\n self.cards = cards\n file.close()\n\n def setcount(self):\n count = 0\n def validset(card1, card2, card3):\n checks = []\n for i in range(4):\n if (card1[i] == card2[i] and card1[i] == card3[i]) or (int(card1[i]) + int(card2[i]) + int(card3[i]) == 3):\n checks.append(True)\n if checks == [True, True, True, True]:\n return True\n else:\n return False\n\n for i in range(10):\n for j in range(i+1, 11):\n for k in range(j+1,12):\n if validset(self.cards[i], self.cards[j], self.cards[k]):\n count += 1\n return count\n","sub_path":"ProbSets/Comp/PSet 1/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":4037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"282148965","text":"import socket\nimport select\nimport sys\nimport msvcrt\n\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nIP_address = '127.0.0.1'\nPort = 8080\nserver.connect((IP_address, Port))\n\nwhile True:\n sockets_list = [server]\n read_sockets, write_socket, error_socket = select.select(sockets_list, [], [], 1)\n if msvcrt.kbhit:\n# print (\"Enter message:\")\n read_sockets.append(sys.stdin)\n for socks in read_sockets:\n if socks == server:\n message = socks.recv(2048)\n print (str(message, 'utf-8'))\n else:\n message = sys.stdin.readline()\n server.send(bytes(message, 'utf-8'))\n sys.stdout.write(\"\")\n sys.stdout.write(message)\n sys.stdout.flush()\nserver.close()","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"607571015","text":"import Netster\nimport time\nimport datetime\nimport sys\nimport threading\nimport processor\nimport GUI\nimport multiprocessing\n\nrun = True\nn = Netster.Netster()\n\ndef console():\n global run\n while True:\n userInput = input(\">:\")\n if (userInput == \"quit\"):\n run = False\n print(\"Bye!\")\n break\n elif (userInput == \"pr\"):\n multiprocessing.Process(target=processor.main).start()\n print(\"Processed log\")\n elif (userInput == \"gui\"):\n multiprocessing.Process(target=GUI.main).start()\n else:\n print(\"Unknown command!\")\n \n\ndef log(msg):\n f = open(\"log.txt\", \"a\")\n dt = datetime.datetime.now()\n f.write(str(dt.month) + \".\" + str(dt.day) + \".\" + str(dt.year) + \"_\" + str(dt.hour) + \":\" + str(dt.minute) + \":\" + str(dt.second) + \" - \" + msg + \"\\n\")\n f.close()\n\ndef main(args):\n del args[0]\n n._pingAddresses.extend(args)\n while ((datetime.datetime.now().second % 10) != 0):\n pass\n while (run):\n dt = datetime.datetime.now()\n if ((dt.hour == 3) and (dt.minute < 1)):\n log(str(n.speedtest()))\n else:\n past = time.time()\n log(str(n.ping()))\n time.sleep(10 - (time.time() - past) - 0.009)\n\nif (__name__ == \"__main__\"):\n threading.Thread(target=main, args=(sys.argv,)).start()\n console()\n quit()","sub_path":"PLTW_EDD_Data_Collection.py","file_name":"PLTW_EDD_Data_Collection.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"365686807","text":"import random\n\nprint('Ця програма згенерую с��исок чисел довжиною N')\nN = int(input(\"Введіть число N\\n \"))\narr = random.sample(range(1, 100), N)\nprint(\"Input list: {}\".format(arr))\n\n# bubble sort\nfor i in range(0, N):\n\tswapped = 0\n\tfor j in range(0, (N - i - 1)):\n\t\tif arr[j] >= arr[j+1]:\n\t\t\ttmp = arr[j]\n\t\t\tarr[j] = arr[j+1]\n\t\t\tarr[j+1] = tmp\n\t\t\tswapped = 1\n\tif swapped == 0:\n\t\tbreak\n\t\t\t\n\t\nprint(\"Output list: {}\".format(arr))","sub_path":"opt_bubble_sort.py","file_name":"opt_bubble_sort.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"349497117","text":"\"\"\"\r\n\r\nProgram : TrendIT\r\nDeveloper : Arjun Muraleedharan\r\nDate : 20-07-2019\r\n\r\nDescription:\r\n\r\nFunctions:\r\n\r\nPrerequisites:\r\n\r\n\r\nInitial Version V1.0\r\nPlot a sample graph\r\n\r\n\"\"\"\r\n\r\n# Libraries\r\nimport datetime\r\nimport getpass\r\nimport os\r\nimport linecache\r\nimport sys\r\nimport pandas as pd\r\nimport configparser\r\nimport shutil\r\nimport numpy as np\r\n\r\n# Initializing variables\r\nRunTime = datetime.datetime.now()\r\nconfig = configparser.ConfigParser()\r\nif config.read('trendconfig.ini') == 0:\r\n config.read('trendconfig.ini')\r\n FixedPath = \"D:/DS/EPOS/TREND/\"\r\n FixedName = \"incident.xlsx\"\r\n ResultFile = \"ResultLog.csv\"\r\n LogFile = \"ActivityLog.txt\"\r\n ReportFile = \"ReportLog.txt\"\r\nelse:\r\n # config.sections()\r\n FixedPath = config.get('inputfiles', 'FixedPath')\r\n FixedName = config.get('inputfiles', 'FixedName')\r\n ResultFile = config.get('outputfiles', 'ResultFile')\r\n LogFile = config.get('outputfiles', 'LogFile')\r\n ReportFile = config.get('outputfiles', 'ReportFile')\r\n\r\nToday = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)\r\ndata = []\r\nRep = ''\r\n\r\n\r\n# Error Handling Logs\r\ndef LogIt(typ, txt):\r\n if typ == \"a\":\r\n ActivityLog.write(str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) + \" : \" + txt + \"\\n\")\r\n # print(txt)\r\n elif typ == \"r\":\r\n ResultLog.write(txt + \"\\n\")\r\n # print(txt)\r\n elif typ == \"R\":\r\n ReportLog.write(txt + \"\\n\")\r\n elif typ == \"p\":\r\n print(txt + \"\\n\")\r\n elif typ == \"e\":\r\n # ActivityLog.write(str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")) + \" : \" + str(txt) + \"\\n\")\r\n print(txt)\r\n exc_type, exc_obj, tb = sys.exc_info()\r\n f = tb.tb_frame\r\n lineno = tb.tb_lineno\r\n filename = f.f_code.co_filename\r\n linecache.checkcache(filename)\r\n line = linecache.getline(filename, lineno, f.f_globals)\r\n err = (\"File : \" + filename\r\n + \"\\nLine No. : \" + str(lineno)\r\n + \"\\nLine : \" + str(line.strip())\r\n + \"\\nReason : \" + str(exc_obj)\r\n + \"\\n\")\r\n LogIt(\"a\", err)\r\n LogIt(\"a\", \"Program failed at \" + str(RunTime))\r\n os.system('pause')\r\n exit()\r\n else:\r\n print(\"INVALID LOG ERROR!\")\r\n LogIt(\"a\", \"Program failed at \" + str(RunTime))\r\n os.system('pause')\r\n exit()\r\n\r\n\r\n# Open Files\r\ndef FileOpen(file, mode):\r\n f = open(file, mode)\r\n return f\r\n\r\n\r\n# Close Files\r\ndef FileClose(file):\r\n file.close()\r\n\r\n\r\n# GET DATA\r\ndef GetData(f):\r\n df = pd.read_excel(f)\r\n # CleanData(df)\r\n\r\n\r\n# CLEAN DATA\r\ndef CleanData(df):\r\n df.columns = [column.replace(\" \", \"_\") for column in df.columns]\r\n df['Opened_Month'] = df['Opened'].dt.month\r\n MineData(df)\r\n\r\n\r\n# MINE DATA\r\ndef MineData(df):\r\n pl = pd.pivot_table(\r\n df[\r\n (df['Opened_Month'] >= Today.month - 2)\r\n & (df['Opened_Month'] <= Today.month - 1)\r\n ],\r\n index='Configuration_item',\r\n columns='Opened_Month',\r\n values='Priority',\r\n aggfunc=np.count_nonzero\r\n )\r\n pl = pl.fillna(0)\r\n pl.rename(columns=lambda x: calendar.month_name[x], inplace=True)\r\n pl['Total'] = pl.sum(axis=1)\r\n pl.sort_values(\"Total\", axis=0, ascending=False, inplace=True, na_position='last')\r\n pl.drop('Total', axis=1, inplace=True)\r\n pl.to_excel(FixedPath + 'Trend.xlsx')\r\n p = pl.plot.bar()\r\n p.get_figure().savefig(FixedPath + 'Trend.png', bbox_inches='tight', pad_inches=0)\r\n\r\n\r\n# Execution\r\n\r\n# Open files required\r\nActivityLog = FileOpen(FixedPath + LogFile, \"w+\")\r\nResultLog = FileOpen(FixedPath + ResultFile, \"w+\")\r\nReportLog = FileOpen(FixedPath + ReportFile, \"w+\")\r\nLogIt(\"a\", \"Initializing application by \" + getpass.getuser())\r\n\r\n# Log Header\r\nLogIt(\"R\", \"------------------------------------------------------------------------------------------------\")\r\nLogIt(\"R\", os.path.basename(sys.argv[0]) + \" by Arjun Muraeedharan\")\r\nLogIt(\"R\", \"Executed by \" + getpass.getuser() + \" at \" + str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")))\r\nLogIt(\"R\", \"------------------------------------------------------------------------------------------------\")\r\n\r\n\r\n# Mainline\r\nGetData(os.path.join(FixedPath, FixedName))\r\n\r\n\r\n# Log Footer\r\nLogIt(\"R\", \"------------------------------------------------------------------------------------------------\")\r\nLogIt(\"R\", \"Completed at \" + str(datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")))\r\nLogIt(\"R\", \"------------------------------------------------------------------------------------------------\")\r\n\r\n# Log program runtime\r\nRunTime = datetime.datetime.now() - RunTime\r\nLogIt(\"a\", \"Program completed successfully in \" + str(RunTime))\r\n\r\n# Close opened files\r\nFileClose(ActivityLog)\r\nFileClose(ReportLog)\r\n\r\nos.system('pause')\r\n","sub_path":"TrendIT_V2.0.py","file_name":"TrendIT_V2.0.py","file_ext":"py","file_size_in_byte":4869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"620158418","text":"from django.shortcuts import render\nfrom .models import User, Rating\nfrom .forms import MetricForm, VoteForm\nfrom django.http import HttpResponseRedirect\n\n# Create your views here.\ndef index(request):\n users = User.objects.all()\n form2 = MetricForm()\n form3 = VoteForm()\n context = { 'users': users, 'form2': form2, 'form3': form3 }\n\n return render(request, 'index.html', context)\n\ndef detail(request, user_id):\n user = User.objects.get(id = user_id)\n\n return render(request, 'user.html', {'user': user})\n\ndef profile(request, username):\n user = User.objects.get(username=username)\n ratings = Rating.objects.filter(user=user)\n return render(request, 'profile.html', { 'username': username, 'ratings': ratings })\n\ndef post_vote(request):\n form = VoteForm(request.POST)\n if form.is_valid():\n vote = form.save(commit = False)\n if request.user.email:\n vote.email = request.user.email\n vote.save()\n # vote.user = User.objects.first()\n # vote.metric = Metric.objects.first()\n return HttpResponseRedirect('/')\n\ndef post_metric(request):\n form = MetricForm(request.POST)\n if form.is_valid():\n form.save(commit = True)\n return HttpResponseRedirect('/')\n\n\n","sub_path":"crockerometer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"322565600","text":"import sys, os, binascii, json, sqlite3\nsys.path = [\"..\"]+sys.path\n\nbase_dir = os.environ[\"COPYCATBOWL_BASE_DIR\"] = os.path.join(os.getcwd(), \"server-data\")\nif not os.path.exists(base_dir):\n os.mkdir(base_dir)\n with open(os.path.join(base_dir, \"config.json\"), \"w\") as f:\n json.dump({\"SECRET_KEY\": binascii.hexlify(os.urandom(32)).decode(\"utf-8\")}, f)\n with open(\"schema.sql\") as f:\n db = sqlite3.connect(os.path.join(base_dir, \"copycatbowl.db\"))\n db.executescript(f.read())\n db.commit()\n db.close()\n\nfrom copycatbowl import app\napp.run(debug=True)\n","sub_path":"debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"468723182","text":"from os.path import splitext, join, exists, isdir,basename,abspath,dirname\nfrom rohan.global_imports import *\nimport trackpy as tp\ntp.ignore_logging()\n# import nd2reader\nimport pims\nimport logging\n# from htsimaging.lib.plot import *\nfrom htsimaging.lib.stat import *\n\n# %matplotlib inline\n\n@pims.pipeline\ndef average_z(image):\n return image.mean(axis=0) \n \ndef plot_msd(imsd,emsd,ax=None,scale=\"log\",plot_fh=None,\n params_msd={\"mpp\":0.0645,\n \"fps\":0.2,\n \"max_lagtime\":100\n }):\n if ax is None:\n plt.figure(figsize=(3, 3))\n ax=plt.subplot(111)\n\n head=params_msd[\"fps\"]*params_msd[\"max_lagtime\"]\n head=int(head)\n\n imsd=imsd.head(head)\n emsd=emsd.head(head)\n\n imsd.plot(x=imsd.index,legend=None,alpha=0.75,ax=ax)\n ax.set(ylabel=r'$\\langle \\Delta r^2 \\rangle$ [$\\mu$m$^2$]',\n xlabel='lag time $t$')\n if scale==\"log\":\n ax.set_xscale('log')\n ax.set_yscale('log')\n\n emsd.plot(x=emsd.index,style='o',legend=None,ax=ax)\n if scale==\"log\":\n ax.set_xscale('log')\n ax.set_yscale('log')\n ax.set(ylabel=r'$\\langle \\Delta r^2 \\rangle$ [$\\mu$m$^2$]',\n xlabel='lag time $t$')\n plt.tight_layout()\n if not plot_fh is None: \n ax.figure.savefig(plot_fh);\n# plt.clf();plt.close()\n return ax\n\ndef plot_emsd(expt_data,ax=None,color='k',scale=\"log\",plot_fh=None):\n if ax is None:\n plt.figure(figsize=(6, 3))\n ax=plt.subplot(121)\n expt_data.plot(x=expt_data.index,style='o',c=color,ax=ax,markeredgecolor = 'none')\n if scale==\"log\":\n ax.set_xscale('log')\n ax.set_yscale('log')\n ax.set(ylabel=r'$\\langle \\Delta r^2 \\rangle$ [$\\mu$m$^2$]',\n xlabel='lag time $t$')\n ax.legend(loc = 'center left', bbox_to_anchor = (1.0, 0.5)) #bbox_to_anchor=(2.2, 1.0)\n plt.tight_layout()\n if not plot_fh is None: \n ax.figure.savefig(plot_fh);\n# plt.clf();plt.close()\n return ax \n\ndef nd2frames(nd_fh):\n if nd_fh.endswith('nd2'):\n frames=pims.ND2_Reader(nd_fh)\n elif nd_fh.endswith('mp4'):\n frames=pims.Video(nd_fh)\n from pimsviewer.utils import wrap_frames_sequence\n frames=wrap_frames_sequence(frames)\n\n if nd_fh.endswith('nd2'):\n if len(np.shape(frames))==4:\n frames = average_z(frames)\n else:\n frames.default_coords['c'] = 1\n frames.bundle_axes='yx'\n frames.iter_axes = 't'\n return frames\n \ndef test_locate_particles(cellcfg,params_locate,frame=None,force=False,test=False):\n dlocate_testp=f\"{cellcfg['outp']}/dlocate_test.tsv\"\n if exists(dlocate_testp) and not force and not test:\n return True\n cellgfpmax=np.load(cellcfg['cellgfpmaxp'])\n frame=cellgfpmax if frame is None else frame\n df1 = tp.locate(frame, \n **params_locate)\n df1['particle']=df1.index\n if not test:\n to_table(df1,dlocate_testp)\n logging.info(f\"particles detected ={len(df1)}\") if not test else print(f\"particles detected ={len(df1)}\")\n if len(df1)==0:\n return False\n # plot dist signal of the detected particles\n fig=plt.figure()\n cellgfpmin=np.load(cellcfg['cellgfpminp'])\n from htsimaging.lib.plot import dist_signal\n ax=plt.subplot()\n# dist_signal(np.unique(cellgfpmin)[2:],\n# params_hist={'bins':20,'label':'gfp min',\n# 'density':True,'color':'k'},ax=ax)\n# dist_signal(np.unique(cellgfpmax)[2:],\n# params_hist={'bins':20,'label':'gfp max',\n# 'density':True,'color':'green'},ax=ax)\n dist_signal(np.unique(frame)[2:],\n params_hist={'bins':20,'label':'frame',\n 'density':True,'color':'lime'},ax=ax) \n dist_signal(df1['signal'],\n threshold=np.unique(frame)[1],label_threshold='signal_cytoplasm',\n params_hist={'bins':20,'label':f'particles\\n(total ={len(df1)})',\n 'density':True,'color':'r'},ax=ax)\n if not test:\n savefig(f\"{cellcfg['plotp']}/dist_signal_locate_particles.png\")\n # plot image of the detected particles\n from htsimaging.lib.plot import image_locate_particles\n ax=image_locate_particles(df1,\n frame=frame,\n img_region=np.load(cellcfg['cellbrightp']),\n annotate_particles=False)\n _=ax.text(0,1,'\\n'.join([f\"{k}:{params_locate[k]}\" for k in params_locate]),\n va='top',color='lime')\n if not test:\n savefig(f\"{cellcfg['plotp']}/image_locate_particles.png\") \n# if len(df1)>=5:\n# from htsimaging.lib.plot import plot_properties_cell\n# plot_properties_cell(cellcfg,df1,cols_colorby=df1.select_dtypes('float').columns.tolist()) \n# if not test:\n# savefig(f\"{cellcfg['plotp']}/plot_properties_cell_locate_particles.png\")\n return True\n \ndef trim_returns(df1):\n from htsimaging.lib.stat import get_inflection_point\n from htsimaging.lib.plot import plot_trajectories_stats\n # get inflection point if any\n df1=df1.groupby('particle').apply(lambda x: get_inflection_point(x))\n df2=df1.groupby('particle',as_index=False).apply(lambda df: df.set_index('frame').sort_index(axis=0).loc[df['inflection point'].unique()[0]:,:].reset_index())\n\n\n fig=plt.figure(figsize=[20,10])\n # plot before filtering\n ax=plt.subplot()\n df1.loc[df1['inflection point'].isnull(),:].groupby('particle').apply(lambda x: plot_trajectories_stats(x,\n coly='distance effective from centroid per frame',\n colx='frame',\n fig=fig,ax=ax,\n rescalex=False,\n params_plot={'color':'lime','alpha':0.5}))\n df1.loc[~df1['inflection point'].isnull(),:].groupby('particle').apply(lambda x: plot_trajectories_stats(x,\n coly='distance effective from centroid per frame',\n colx='frame',\n fig=fig,ax=ax,\n rescalex=False,\n axvlinex=x['inflection point'].unique()[0],\n params_plot={'color':'r','alpha':0.75}))\n\n df2.loc[~df2['inflection point'].isnull(),:].groupby('particle').apply(lambda x: plot_trajectories_stats(x,\n coly='distance effective from centroid per frame',\n colx='frame',\n fig=fig,ax=ax,\n rescalex=False,\n axvlinex=x['inflection point'].unique()[0],\n params_plot={'color':'g','alpha':1}))\n ax.get_legend().remove()\n ax.set_ylim(df1['distance effective from centroid per frame'].min(),df1['distance effective from centroid per frame'].max()) \n ax.set_xlim(df1['frame'].min(),df1['frame'].max())\n return df2\n \ndef fill_frame_jumps(df1,jump_length):\n df1=df1.sort_values(by=['particle','frame'])\n df1['frame delta']=df1['frame']-([df1['frame'].tolist()[0]-1]+df1['frame'].tolist()[:-1])\n df=df1.loc[(df1['frame delta']==jump_length),:]\n df.loc[df.index,'frame']=df['frame']-1\n df1=pd.concat({'not':df1,'fill':df},axis=0)\n df1.index.name='frame fill or not'\n df1=df1.reset_index()\n df1=df1.sort_values(by=['particle','frame'])\n df1['frame delta']=df1['frame']-([df1['frame'].tolist()[0]-1]+df1['frame'].tolist()[:-1])\n logging.warning(sum((df1['frame']-([df1['frame'].tolist()[0]-1]+df1['frame'].tolist()[:-1]))==jump_length)==0)\n df1.index=range(len(df1))\n return df1 \n \ndef cellcfg2distances(cellcfg,\n # for 150x150 images\n params={'locate':{'diameter':11, # round to odd number\n 'noise_size':1,\n 'separation':15,\n 'threshold':4000,\n 'preprocess':True,\n 'invert':False,\n 'max_iterations':50,\n 'percentile':0,\n 'engine':'numba',\n },\n 'link_df':{\n 'search_range':5,\n 'memory':1,\n 'link_strategy':'drop',},\n 'filter_stubs':{'threshold':4},\n 'get_distance_from_centroid':{'center':[75,75]},\n# 'msd':{'mpp':0.0645,'fps':0.2, 'max_lagtime':100},\n },\n test=False,force=False):\n params['locate']['separation']=params['locate']['diameter']*1\n params['locate']['threshold']=cellcfg['signal_cytoplasm']*0.5\n params['link_df']['search_range']=params['locate']['diameter']*0.33\n \n to_dict(params,f\"{cellcfg['outp']}/params.yml\")\n \n if not test_locate_particles(cellcfg,params['locate'],force=force,test=False):\n print(cellcfg['cfgp'])\n return \n # get trajectories\n steps=['locate','link_df','filter_stubs','filter_returns','subtract_drift','distance']\n dn2dp={s:f\"{cellcfg['outp']}/d{si}{s}.tsv\" for si,s in enumerate(steps)}\n dn2plotp_suffix={s:f\"{si}{s}.png\" for si,s in enumerate(steps)}\n steps_done=[k for k in dn2dp if exists(dn2dp[k])]\n \n if ('distance' in steps_done) and not force:\n print(cellcfg['cfgp'])\n return\n \n from htsimaging.lib.plot import image_trajectories\n from htsimaging.lib.stat import get_distance_from_centroid\n \n img_gfp=np.load(cellcfg['cellgfpmaxp'])\n img_bright=np.load(cellcfg['cellbrightp'])\n \n dn2df={}\n dn2df['locate']=tp.batch([np.load(p) for p in sorted(cellcfg['cellframes_masked_substracted'])],\n **params['locate'])\n if len(dn2df['locate'])==0:\n return\n dn2df['locate']['frame']=dn2df['locate']['frame'].astype(np.integer)\n dn2df['link_df']=tp.link_df(dn2df['locate'], **params['link_df'])\n# if params['link_df']['memory']!=0:\n dn2df['link_df']=fill_frame_jumps(dn2df['link_df'],\n jump_length=2 if params['link_df']['memory']==0 else params['link_df']['memory']+1)\n# to_table(dn2df['link_df'],'test.tsv')\n# to_table(dn2df['link_df'],dn2dp['link_df'])\n image_trajectories(dtraj=dn2df['link_df'], \n img_gfp=img_gfp, \n img_bright=img_bright, fig=None, ax=None)\n savefig(f\"{cellcfg['plotp']}/image_trajectories_{dn2plotp_suffix['link_df']}\")\n# to_table(dn2df['link_df'],dn2dp['link_df'])\n\n \n dn2df['filter_stubs']=tp.filter_stubs(dn2df['link_df'], threshold=params['filter_stubs']['threshold'])\n dn2df['filter_stubs'].index.name='index'\n dn2df['filter_stubs'].index=range(len(dn2df['filter_stubs']))\n if len(dn2df['filter_stubs'])==0:\n to_table(dn2df['filter_stubs'],dn2dp['distance'])\n print(cellcfg['cfgp'])\n return \n image_trajectories(dtraj=dn2df['filter_stubs'], \n img_gfp=img_gfp, \n img_bright=img_bright, fig=None, ax=None)\n savefig(f\"{cellcfg['plotp']}/image_trajectories_{dn2plotp_suffix['filter_stubs']}\")\n \n dn2df['filter_returns']=get_distance_from_centroid(dn2df['filter_stubs'],**params['get_distance_from_centroid'])\n dn2df['filter_returns']=trim_returns(dn2df['filter_returns'])\n savefig(f\"{cellcfg['plotp']}/image_trajectories_stats_trimming_{dn2plotp_suffix['filter_returns']}\")\n\n dn2df['filter_returns']=tp.filter_stubs(dn2df['filter_returns'], threshold=params['filter_stubs']['threshold'])\n dn2df['filter_returns'].index.name='index'\n dn2df['filter_returns'].index=range(len(dn2df['filter_returns']))\n if len(dn2df['filter_returns'])==0:\n to_table(dn2df['filter_returns'],dn2dp['distance'])\n print(cellcfg['cfgp'])\n return \n image_trajectories(dtraj=dn2df['filter_stubs'], \n img_gfp=img_gfp, \n img_bright=img_bright, fig=None, ax=None)\n savefig(f\"{cellcfg['plotp']}/image_trajectories_{dn2plotp_suffix['filter_returns']}\")\n\n d = tp.compute_drift(dn2df['filter_returns'])\n dn2df['subtract_drift'] = tp.subtract_drift(dn2df['filter_stubs'], d)\n image_trajectories(dtraj=dn2df['subtract_drift'], \n img_gfp=img_gfp, \n img_bright=img_bright, fig=None, ax=None)\n savefig(f\"{cellcfg['plotp']}/image_trajectories_{dn2plotp_suffix['subtract_drift']}\")\n\n dn2df['distance']=get_distance_from_centroid(dn2df['subtract_drift'],**params['get_distance_from_centroid'])\n from htsimaging.lib.stat import get_distance_travelled\n dn2df['distance']=get_distance_travelled(t_cor=dn2df['distance'])\n \n for k in dn2df:\n to_table(dn2df[k],dn2dp[k])\n# make_gif(cellcfg,\n# force=force) \n \ndef apply_cellcfgp2distances(cellcfgp):\n \"\"\"\n wrapper around cellcfg2distances for multiprocessing\n \"\"\"\n celli='/'.join(dirname(cellcfgp).split('/')[-3:])\n print(f\"processing {celli}: \");logging.info(celli)\n cellcfg=yaml.load(open(cellcfgp,'r'))\n cellcfg2distances(cellcfg,\n test=cellcfg['test'],\n force=cellcfg['force'])\n","sub_path":"htsimaging/lib/spt.py","file_name":"spt.py","file_ext":"py","file_size_in_byte":14051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"523706359","text":"# Copyright 2017 Great Software Laboratory Pvt. Ltd.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\nimport pynos.device\nfrom st2common.runners.base_action import Action\n\n\nclass VerifyVcs(Action):\n \"\"\"\n Implements the logic to verify VCS Fabric\n This action achieves the below functionality\n 1. Valdiates vcsId,rbridgeIDs and total nodes in VCS Fabric.\n \"\"\"\n def __init__(self, config=None):\n super(VerifyVcs, self).__init__(config=config)\n self.logger = logging.getLogger(__name__)\n\n def run(self, host=None, username=None, password=None, vcs_id=None,\n rbridge_ids=None, nodes=None):\n \"\"\"Run helper methods to implement the desired state.\n \"\"\"\n if host is None:\n host = self.config['mgmt_ip1']\n\n if username is None:\n username = self.config['username']\n\n if password is None:\n password = self.config['password']\n\n if vcs_id is None:\n vcs_id = self.config['vcs_id']\n\n if rbridge_ids is None:\n rbridge_ids = self.config['rbridge_id1']\n\n if nodes is None:\n nodes = 2\n\n conn = (host, '22')\n auth = (username, password)\n\n changes = {}\n\n with pynos.device.Device(conn=conn, auth=auth) as device:\n\n changes['pre_requisites'] = self._check_requirements(device, vcs_id, rbridge_ids, nodes)\n changes['verify_vcs'] = False\n if changes['pre_requisites']:\n changes['verify_vcs'] = self._verify_vcs(device, vcs_id, rbridge_ids, nodes)\n if changes['verify_vcs']:\n self.logger.info(\n 'closing connection to %s after verifying VCS Fabric successfully!',\n host)\n return changes\n else:\n self.logger.info(\n 'VCS Fabric Verification Failed')\n exit(1)\n\n def _check_requirements(self, device, vcs_id, rb_ids, nodes):\n rb_list = rb_ids.split(',')\n for rb_id in rb_list:\n if int(rb_id) > 239 or int(rb_id) < 1:\n raise ValueError(' Rbridge ID: %s is Invalid. Not in <1-239> range' % rb_id)\n\n if int(vcs_id) > 8192 or int(vcs_id) < 1:\n raise ValueError('VCS Id:%s is Invalid. Not in <1-8192> range' % vcs_id)\n\n return True\n\n def _verify_vcs(self, device, vcs_id, rbridge_ids, nodes):\n \"\"\"VCS Fabric Varification.\n \"\"\"\n try:\n output = device.vcs.vcs_nodes\n except RuntimeError as e:\n self.logger.error('VCS Fabric Verification Failed with Exception: %s', e)\n return False\n\n if not output:\n return False\n\n if not self._verify_vcsId(vcs_id, output):\n self.logger.info(\"VCSid verification failed\")\n return False\n rb_list = rbridge_ids.split(',')\n for rb_id in rb_list:\n if not self._verify_vcsRbrideId(rb_id, output):\n self.logger.info(\"Rbridge Id:%s verification failed\", rb_id)\n return False\n if not self._verify_vcsToalNoOfNodes(nodes, output):\n self.logger.info(\"Total Number of nodes in the VCS are not equal to desired nodes %r\",\n nodes)\n return False\n\n return True\n\n def _verify_vcsId(self, vcsId, output):\n result = False\n for node in output:\n if node['node-vcs-id'] == str(vcsId):\n result = True\n break\n return result\n\n def _verify_vcsRbrideId(self, rbridge_id, output):\n result = False\n\n for node in output:\n if node['node-rbridge-id'] == str(rbridge_id):\n result = True\n break\n return result\n\n def _verify_vcsToalNoOfNodes(self, nodes, output):\n result = False\n if len(output) == int(nodes):\n result = True\n return result\n","sub_path":"actions/verify_vcs_fabric.py","file_name":"verify_vcs_fabric.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"399199563","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem\n\ndatos = {\"Col1\":[1,2,3,4],\n \"Col2\":[1,3,5,7],\n \"Col3\":[1,2,4,6]}\n\nclass App(QTableWidget):\n def __init__(self, datos, *args):\n self.datos = datos\n self.asinarDatos()\n self.resizeColumnsToContents()\n self.resizeRowsToContents()\n\n def asinarDatos(self):\n cabeceirasHor = []\n for n, clave in enumerate(self.datos.keys()):\n cabeceirasHor.append(clave)\n for m, numero in enumerate(self.datos[clave]):\n novoElemento = QTableWidgetItem(numero)\n self.setItem(m, n, novoElemento)\n self.setHorizontalHeaderLabels(cabeceirasHor)\n\n","sub_path":"QTableWidget.py","file_name":"QTableWidget.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"260082578","text":"\nfrom adapterQuestionBankTest import *\nimport matplotlib.pyplot as plt\n\nadapter_question = AdapterQuestionBankTest()\n\nf = io.open(\"data_test/input.txt\", mode=\"r\")\nlist_query_question = [line for line in f]\n\ntotal = 0\ncount_yes = 0\ncount_no = 0\n\ny = []\nx = range(1, 7 + 1)\nfor i in range(1, 7 + 1):\n\tprint(i)\n\ttotal = 0\n\tcount_yes = 0\n\tcount_no = 0\n\tfor query_question in list_query_question:\n\n\t\tif(len(query_question.split(\"|\")) == 2):\n\t\t\ttotal += 1\n\t\t\tquery = query_question.split(\"|\")[0]\n\t\t\tcheck_id = query_question.split(\"|\")[1].replace(\"\\n\", \"\").strip()\n\t\t\tmy_list = adapter_question.find_answer(query, i)\n\n\t\t\tmy_check = False\n\t\t\tfor answer in my_list:\n\t\t\t\tif str(answer['id']) == check_id:\n\t\t\t\t\tmy_check = True\n\t\t\t\t\tbreak\n\n\t\t\tif(my_check):\n\t\t\t\tcount_yes += 1\n\t\t\t\t# print(\"Yesss\")\n\t\t\telse:\n\t\t\t\tcount_no += 1\n\t\t\t\t# print(\"NONNONO\")\n\n\tprint(\"Total: \" + str(total))\n\tprint(\"yes: \" + str(count_yes))\n\tprint(\"no: \" + str(count_no))\n\ty.append(100 * count_yes / total)\n\nplt.ylim([0, 100])\nplt.xlim([1, 7])\nplt.ylabel('Độ chính xác (%)')\nplt.xlabel('Số kết quả trả về')\nplt.plot(x, y)\nplt.show()\n# print(y)","sub_path":"question/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"288755712","text":"# pylint: disable=C0103\n# pylint: disable=W0703\n\n\"\"\"\ninventory.py\nCSV replacement\n\"\"\"\n\nimport datetime\nimport functools\nimport logging\nimport sys\n\nlog_format = \"%(asctime)s\\t%(message)s\"\nformatter = logging.Formatter(log_format)\n\nfile_handler = logging.FileHandler(\"inventory_{}.log\".format(datetime.datetime.now().strftime(\"%Y-%m-%d-%H:%M:%S\")))\nfile_handler.setFormatter(formatter)\n\nstream_handler = logging.StreamHandler(sys.stdout)\nstream_handler.setFormatter(formatter)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel('INFO')\nlogger.addHandler(stream_handler)\nlogger.addHandler(file_handler)\n\n\ndef add_furniture(invoice_file, customer_name, item_code, item_description, item_monthly_price):\n \"\"\" Creates invoice_file if it doesn't exist or append if it does. Adds item record to file.\"\"\"\n try:\n with open(file=invoice_file, mode='a') as file:\n record = \"{}, {}, {}, {}\\n\".format(customer_name, item_code, item_description, item_monthly_price)\n file.write(record)\n logger.debug(\"Wrote line %s to %s\", record, invoice_file)\n except OSError as er:\n logger.error(\"Failed to open %s. The error was: %s\", invoice_file, er)\n\n\ndef single_customer(customer_name, invoice_file):\n \"\"\"\n Uses closure to return a function that will iterate through rental_items and add each\n item to invoice_file\n\n :return: returns a function that takes one parameter, rental_items\n \"\"\"\n def return_function(rental_items):\n \"\"\" Creates invoice_file if it doesn't exist or append if it does. Adds item record to file.\"\"\"\n try:\n with open(file=invoice_file, mode='a') as file:\n for item in rental_items:\n item = item.strip('\\n')\n record = \"{},{}\\n\".format(customer_name, item)\n file.write(record)\n logger.debug(\"Wrote line %s to %s\", record, invoice_file)\n except OSError as er:\n logger.error(\"Failed to open %s. The error was: %s\", invoice_file, er)\n return return_function\n\n\nif __name__ == '__main__':\n add_furniture('invoices.csv', 'first last', 'LR04', 'Leather sofa', 25.00)\n add_furniture('invoices.csv', 'Edward Data', 'KT78', 'Kitchen Table', 10.00)\n\n with open('data/test_items.csv', 'r') as test_items:\n rentals = test_items.readlines()\n # single_customer works, but doesn't use functools.partial\n single_customer('A A', 'invoices.csv')(rentals)\n\n # Using functools.partial outside the function works too, but is less efficient.\n # I'm sure this isn't what the author had in mind.\n functools.partial(single_customer, customer_name='G G', invoice_file='invoices.csv')()(rentals)\n\n # I can see above that I've duplicated much of the code in add_furniture to create single_customer.\n # I assume I was supposed to use functools.partial to re-use the add_furniture function inside\n # single_customer, but I don't see a way to do that while still adhering to the input and output requirements\n # specified for each function in the assignment.\n","sub_path":"students/jsward/lesson08/assignment/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":3084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"653539275","text":"'''/** 114 Unique Paths\n * Easy'''\n\n\nclass Solution:\n # @return an integer\n def c(self, m, n):\n mp = {}\n for i in range(m):\n for j in range(n):\n if(i == 0 or j == 0):\n mp[(i, j)] = 1\n else:\n mp[(i, j)] = mp[(i - 1, j)] + mp[(i, j - 1)]\n return mp[(m - 1, n - 1)]\n\n def uniquePaths(self, m, n):\n return self.c(m, n)","sub_path":"J9Ch/src/J_9_DP/Required_10/python_cpp/_114_Unique_Paths_Easy.py","file_name":"_114_Unique_Paths_Easy.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"383461044","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom .models import Investor\nfrom .forms import InvestorForm\nfrom django.views.generic import UpdateView, DeleteView\nfrom django.urls import reverse_lazy\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import user_passes_test\nfrom user.models import StartupProfile\n\n# Create your views here.\ndef Investors(request):\n context = {\n 'investors': Investor.objects.all()\n }\n return render(request,'investors/investorshome.html', context)\n\ndef Startup(request):\n context = {\n 'startup': StartupProfile.objects.all()\n }\n return render(request,'investors/startup_home.html', context)\n\ndef InvestorCreateView(request):\n if request.user.is_authenticated and request.user.is_team:\n if(request.method == 'POST'):\n form = InvestorForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('investors')\n \n else:\n form = InvestorForm()\n \n context = {\n 'form': form\n }\n return render(request, 'investors/create_investor.html', context)\n\n else:\n return redirect('investors')\n\n@method_decorator(user_passes_test(lambda u: u.is_authenticated and u.is_team), name='dispatch')\nclass InvestorDeleteView(DeleteView):\n model = Investor\n success_url = reverse_lazy('investors')\n template_name = 'investors/confirm-delete-investors.html'\n\n\ndef InvestorUpdateView(request, pk):\n if request.user.is_authenticated and request.user.is_team:\n if request.method == 'POST':\n form = InvestorForm(request.POST, request.FILES,\n instance=Investor.objects.filter(id=pk).first())\n \n if form.is_valid():\n form.save()\n return redirect('investors')\n\n form = InvestorForm(instance=Investor.objects.filter(id=pk).first())\n context = {\n 'form': form\n }\n return render(request, 'investors/create_investor.html', context)\n\n else:\n return redirect('investors')\n","sub_path":"investors/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"304835312","text":"def convertWords(revers,a,b):\n a = revers[b::-1]\n return a\n\n\ndef spin_words(sentence):\n counter = 0\n xBeg = 0\n xEnd = 0\n inString = str(sentence)\n for i in inString[0::1]:\n counter += 1\n xBeg += 1\n if i == ' ':\n if counter > 5:\n counter = counter - 1\n #print(counter)\n # print(inString[counter::-1])\n print(convertWords(inString[:counter:], xBeg, counter))\n counter = 0\n else:\n print(inString[xBeg-counter:xBeg:1])\n counter = 0\n\n counter = 1\nspin_words('Alloha my name is Illyaa')","sub_path":"task_14.py","file_name":"task_14.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"312237906","text":"\"\"\"Unit tests for the cmsis_pack_manager module\"\"\"\n\nfrom os.path import join\nfrom string import ascii_lowercase, ascii_letters, hexdigits\nfrom mock import patch, MagicMock, call\nfrom hypothesis import given, settings, example\nfrom hypothesis.strategies import booleans, text, lists, just, integers, tuples\nfrom hypothesis.strategies import dictionaries, fixed_dictionaries\nfrom jinja2 import Template\nfrom bs4 import BeautifulSoup\n\nimport cmsis_pack_manager\n\n@given(lists(text(min_size=1), min_size=1), just(None))\n@example([\"1.0.0\", \"0.1.0\", \"0.0.1\"], \"1.0.0\")\n@example([\"1.0.0\", \"19.0.0\", \"2.0.0\"], \"19.0.0\")\ndef test_largest_version(version_strings, max_version):\n newest = cmsis_pack_manager.largest_version(version_strings)\n if max_version:\n assert(newest == max_version)\n\n@given(lists(integers()))\ndef test_do_queue(queue):\n to_run = MagicMock()\n cmsis_pack_manager.do_queue(cmsis_pack_manager.Reader, to_run, queue)\n for blah in queue:\n to_run.assert_any_call(blah)\n\n@given(text(alphabet=ascii_lowercase), text(alphabet=ascii_lowercase + \":/_.\"))\n@example(\"http\", \"google.com\")\n@example(\"http\", \"google.com://foo\")\ndef test_strip_protocol(protocol, url):\n uri = protocol + u'://' + url\n assert(cmsis_pack_manager.strip_protocol(uri) == url)\n\n@given(text(alphabet=ascii_lowercase), text(alphabet=ascii_lowercase + \":/_.\"))\n@example(\"http\", \"google.com\")\n@example(\"http\", \"google.com://foo\")\ndef test_cache_lookup(protocol, url):\n obj = cmsis_pack_manager.Cache(True, True)\n uri = protocol + u'://' + url\n assert(obj.data_path in obj._cache_lookup(uri))\n\n@given(text(alphabet=ascii_lowercase + \":/_.\"), text())\ndef test_cache_file(url, contents):\n @patch(\"cmsis_pack_manager.Cache._cache_lookup\")\n @patch(\"cmsis_pack_manager.Cache.display_counter\")\n @patch(\"cmsis_pack_manager.urlopen\")\n @patch(\"cmsis_pack_manager.makedirs\")\n @patch(\"cmsis_pack_manager.open\", create=True)\n def inner_test(_open, _, _urlopen, __, _cache_lookup):\n _open.return_value = MagicMock(spec=file)\n _urlopen.return_value.read.return_value = contents\n c = cmsis_pack_manager.Cache(True, True)\n c.cache_file(url)\n _urlopen.assert_called_with(url)\n _open.assert_called_with(_cache_lookup.return_value, \"wb+\")\n _open.return_value.__enter__.return_value.write.assert_called_with(contents)\n inner_test()\n\n\n@given(text(alphabet=ascii_lowercase + \"/\", min_size=1),\n text(alphabet=ascii_lowercase +\"/\", min_size=1))\ndef test_pdsc_from_cache(data_path, url):\n @patch(\"cmsis_pack_manager.BeautifulSoup\")\n @patch(\"cmsis_pack_manager.open\", create=True)\n def inner_test(_open, _bs):\n _open.return_value.__enter__.return_value = MagicMock\n c = cmsis_pack_manager.Cache(True, True, data_path=data_path)\n c.pdsc_from_cache(url)\n _open.called_with(join(data_path, url), \"r\")\n _bs.called_with(_open.return_value.__enter__.return_value, \"html.parser\")\n inner_test()\n\n@given(text(alphabet=ascii_lowercase + \"/\", min_size=1),\n text(alphabet=ascii_lowercase +\"/\", min_size=1))\ndef test_pack_from_cache(data_path, url):\n @patch(\"cmsis_pack_manager.ZipFile\")\n def inner_test(_zf):\n c = cmsis_pack_manager.Cache(True, True, data_path=data_path)\n device = {'pack_file': url}\n c.pack_from_cache(device)\n _zf.called_with(join(data_path, url))\n inner_test()\n\nVERSION_TEMPLATE = (\n \"\"\n \"{{vendor}}\"\n \"{{name}}\"\n \"{{url}}\"\n \"\"\n \"{% for version in versions %}\"\n \"\"\n \"{% endfor %}\"\n \"\"\n \"\")\n\n@given(text(alphabet=ascii_lowercase), text(alphabet=ascii_lowercase),\n text(alphabet=ascii_lowercase + \":/_.\"),\n lists(text(min_size=1), min_size=1))\ndef test_get_pack_url(name, vendor, url, versions):\n xml = Template(VERSION_TEMPLATE).render(name=name, vendor=vendor, url=url,\n versions=versions)\n @patch(\"cmsis_pack_manager.largest_version\")\n def inner_test(largest_version):\n pdsc_contents = BeautifulSoup(xml, \"html.parser\")\n largest_version.return_value = versions[0]\n c = cmsis_pack_manager.Cache(True, True)\n new_url = c.get_pack_url(pdsc_contents)\n assert new_url.startswith(url)\n assert new_url.endswith(\"%s.%s.%s.pack\" % (vendor, name, versions[0]))\n inner_test()\n\n@given(text(alphabet=ascii_lowercase), text(alphabet=ascii_lowercase),\n text(alphabet=ascii_lowercase + \":/_.\"),\n text(alphabet=ascii_lowercase + \".\"))\ndef test_get_pdsc_url(name, vendor, url, pdsc_filename):\n xml = Template(VERSION_TEMPLATE).render(name=name, vendor=vendor, url=url,\n versions=[])\n pdsc_contents = BeautifulSoup(xml, \"html.parser\")\n c = cmsis_pack_manager.Cache(True, True)\n new_url = c.get_pdsc_url(pdsc_contents, pdsc_filename)\n assert new_url.startswith(url)\n assert new_url.endswith(pdsc_filename)\n\n@given(text(alphabet=ascii_lowercase + \":/_.\"))\ndef test_pdsc_to_pack(url):\n @patch(\"cmsis_pack_manager.Cache.get_pack_url\")\n @patch(\"cmsis_pack_manager.Cache.pdsc_from_cache\")\n def inner_test(pdsc_from_cache, get_pack_url):\n c = cmsis_pack_manager.Cache(True, True)\n new_url = c.pdsc_to_pack(url)\n pdsc_from_cache.assert_called_with(url)\n get_pack_url.assert_called_with(pdsc_from_cache.return_value)\n inner_test()\n\n@given(text(alphabet=ascii_lowercase + \":/_.\"),\n text(alphabet=ascii_lowercase + \":/_.\"))\ndef test_cache_pdsc_and_pack(pack_url, pdsc_url):\n @patch(\"cmsis_pack_manager.Cache.cache_file\")\n @patch(\"cmsis_pack_manager.Cache.pdsc_to_pack\")\n def inner_test(pdsc_to_pack, cache_file):\n pdsc_to_pack.return_value = pack_url\n c = cmsis_pack_manager.Cache(True, True)\n c.cache_pdsc_and_pack(pdsc_url)\n cache_file.assert_has_calls([call(pdsc_url), call(pack_url)])\n inner_test()\n\nIDX_TEMPLATE = (\n \"{% for name, vendor, url in pdscs %}\"\n \"\"\n \"{% endfor %}\")\n\n@given(lists(tuples(text(alphabet=ascii_lowercase, min_size=1),\n text(alphabet=ascii_lowercase, min_size=1),\n text(alphabet=ascii_lowercase + \":/_.\", min_size=1)),\n min_size=1))\ndef test_get_urls(pdscs):\n xml = Template(IDX_TEMPLATE).render(pdscs=pdscs)\n @patch(\"cmsis_pack_manager.Cache.pdsc_from_cache\")\n def inner_test(pdsc_from_cache):\n pdsc_from_cache.return_value = BeautifulSoup(xml, \"html.parser\")\n c = cmsis_pack_manager.Cache(True, True)\n urls = c.get_urls()\n for uri in urls:\n assert any((name in uri and vendor in uri and url.rstrip(\"/\") in uri\n for name, vendor, url in pdscs))\n inner_test()\n\n\nSIMPLE_PDSC = (\n \"\"\n \" \"\n \" \"\n \" \"\n \"{% for memid, attrs in memory.items() %}\"\n \" \"\n \"{% endfor %}\"\n \" \"\n \" \"\n \" \"\n \" \"\n \"\"\n)\n\nSUBFAMILY_PDSC = (\n \"\"\n \" \"\n \" \"\n \" \"\n \" \"\n \" \"\n \"{% for memid, attrs in memory.items() %}\"\n \" \"\n \"{% endfor %}\"\n \" \"\n \" \"\n \" \"\n \"\"\n)\nFAMILY_PDSC = (\n \"\"\n \" \"\n \" \"\n \" \"\n \" \"\n \" \"\n \"{% for memid, attrs in memory.items() %}\"\n \" \"\n \"{% endfor %}\"\n \" \"\n \" \"\n \" \"\n \"\"\n)\n\n@given(text(alphabet=ascii_letters, min_size=1),\n fixed_dictionaries({\"core\": text(alphabet=ascii_letters + \"-\", min_size=1),\n \"memory\": dictionaries(text(alphabet=ascii_letters, min_size=1),\n fixed_dictionaries(\n {\"size\": text(alphabet=hexdigits),\n \"start\": text(alphabet=hexdigits)}))}),\n text(),\n text())\ndef test_simple_pdsc(name, expected_result, pdsc_url, pack_url):\n for tmpl in [SIMPLE_PDSC, SUBFAMILY_PDSC, FAMILY_PDSC]:\n xml = Template(tmpl).render(expected_result, name=name)\n input = BeautifulSoup(xml, \"html.parser\")\n c = cmsis_pack_manager.Cache(True, True)\n c._index = {}\n c._merge_targets(pdsc_url, pack_url, input)\n assert(name in c._index)\n device = c._index[name]\n assert(device[\"pdsc_file\"] == pdsc_url)\n assert(device[\"pack_file\"] == pack_url)\n for key, value in expected_result.items():\n assert(device[key] == value)\n\n","sub_path":"tests/unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":9825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"373831195","text":"'''\nShin Tran\nPython 210\nLesson 6 Assignment\n'''\n\nimport unittest\nimport mailroom4\nfrom io import StringIO\n\nclass Test_mailroom4(unittest.TestCase):\n\n # User types 'list' as the input, so the dictionary/list of names is unmodified\n def test_input0(self):\n list0 = ['Jennifer Miller','William Rodriguez','Patricia Brown']\n self.assertEqual(mailroom4.list_func(), list0)\n\n # User enters \"John Smith\" and a donation of $67,890, method outputs a string email\n def test_input1(self):\n list1 = ['John Smith', 67890]\n message_string = \"Dear {:s},\\n\\\n Thank you for the generous donation of ${:,.2f}.\\n\\\n Sincerely,\\n\\\n Your Local Charity\".format(*list1)\n self.assertEqual(mailroom4.print_email(list1), message_string)\n\n # Compares the report that gets generate based on the preloaded donor list\n def test_input2(self):\n s1 = \"Donor Name | Total Given | Num Gifts | Average Gift\\n\\\n-----------------------------------------------------------------\\n\\\nWilliam Rodriguez $ 161,585.16 3 $ 53,861.72\\n\\\nJennifer Miller $ 145,076.19 2 $ 72,538.10\\n\\\nPatricia Brown $ 100,863.96 2 $ 50,431.98\\n\\\n\"\n self.assertEqual(mailroom4.print_report(), s1)\n\n # Compares the thank you letter (txt file) output with the preloaded donor list\n def test_input3(self):\n donor_list = [[\"Jennifer Miller\",145076.19],[\"William Rodriguez\", 161585.16],[\"Patricia Brown\",100863.96]]\n message = \"Dear {:s},\\n\\\n Thank you for donating ${:,.2f}.\\n\\\n Sincerely,\\n\\\n Your Local Charity\"\n comp_list = []\n for item in donor_list:\n comp_list.append(message.format(*item))\n self.assertEqual(mailroom4.send_letters(), comp_list)\n\n# Main method so the program would run\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"students/ShinTran/lesson06/test_mailroom4.py","file_name":"test_mailroom4.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"653628901","text":"import json\nimport requests\n\nfrom collections import OrderedDict\nfrom flask import session\nfrom itertools import permutations\nfrom typing import Dict, List, Set, Union\n\nfrom app import concise_dictionary_collection, decomposition_collection, kanji_entries_collection, \\\n unabridged_dictionary_collection, words_pronunciation_collection\n\n\ndef get_terms_by_set_id(set_id: str = None) -> Set['str']:\n if not set_id:\n return set()\n headers = {\"Authorization\": \"Bearer \" + session['access_token']}\n response = requests.get('https://api.quizlet.com/2.0/sets/' + set_id + '/terms', headers=headers)\n response = json.loads(response.text)\n return set(entry['term'] for entry in response)\n\n\ndef decompose_kanji(text: str, exclude: str = None) -> List[str]:\n \"\"\"\n\n :param text: a text submitted by user\n :param exclude: an id of the set which terms will be excluded\n :return: a list of kanji found in the text and their components\n \"\"\"\n new_kanji_list = []\n\n for character in set(text):\n for entry in decomposition_collection.find({\"character\": character}):\n new_kanji_list.append(character)\n new_kanji_list.extend(entry['components'])\n\n kanji_to_exclude = get_terms_by_set_id(exclude)\n\n # now delete repeating Kanji and Kanji from the set of Kanji to be excluded\n result = []\n for kanji in new_kanji_list:\n if kanji not in result and kanji not in kanji_to_exclude:\n result.append(kanji)\n\n return result\n\n\ndef give_meaning_to_kanji(kanji_list: List['str']) -> Dict['str', 'str']:\n \"\"\"\n\n :param kanji_list: a list of Kanji\n :return: a dictionary where keys are Kanji and and values are entries\n \"\"\"\n result = {}\n for kanji in kanji_list:\n result[kanji] = kanji_entries_collection.find_one({\"character\": kanji})['entry']\n\n return result\n\n\ndef process_text_kanji(text: str, exclude: str = None) -> Dict['str', 'str']:\n \"\"\"\n\n :param text: text given by user\n :param exclude: an id of a set which terms will be excluded\n :return: a dictionary where keys are Kanji (strings) and and values are meanings (lists)\n \"\"\"\n decomposed_kanji = decompose_kanji(text, exclude)\n return give_meaning_to_kanji(decomposed_kanji)\n\n\ndef tokenize_text(text: str, exclude: str = None) -> List['str']:\n \"\"\"\n :param text: text given by user\n :param exclude: an id of a set which terms will be excluded\n :return: a list of unique words from the given text\n \"\"\"\n # Use lists instead of sets to preserve order\n words = text.split()\n terms_to_exclude = get_terms_by_set_id(exclude)\n unique_words = []\n for word in words:\n if word not in unique_words and word not in terms_to_exclude:\n unique_words.append(word)\n return unique_words\n\n\ndef give_meaning_to_words(words: List['str']) -> Dict['str', 'str']:\n result = {}\n for word in words:\n for entry in concise_dictionary_collection.find({\"word\": word}):\n result[word] = entry['entry']\n return result\n\n\ndef process_text_words(text: str, exclude: str = None) -> Dict['str', 'str']:\n words = tokenize_text(text, exclude)\n return give_meaning_to_words(words)\n\n\ndef process_text_kanji_words(text: str, exclude: str = None) -> Dict['str', 'str']:\n result = {}\n words = tokenize_text(text, exclude)\n for word in words:\n result.update(process_text_kanji(word, exclude))\n # If a word is only one character long, we do not overwrite Kanji entry but add \" (word)\" to word.\n if len(word) > 1:\n result.update(give_meaning_to_words([word]))\n else:\n word_result = give_meaning_to_words([word])\n if word_result:\n word_result[word + ' (word)'] = word_result.pop(word)\n result.update(word_result)\n return result\n\n\ndef get_user_set_titles() -> Union[bool, Dict['str', 'str']]:\n if 'access_token' not in session:\n return False\n headers = {\"Authorization\": \"Bearer \" + session['access_token'],\n 'User-Agent': 'Mozilla/5.0'}\n response = requests.get(\n 'https://api.quizlet.com/2.0/users/' + session['user_id'] + '/sets', headers=headers)\n response = json.loads(response.text)\n titles = {deck['id']: deck['title'] for deck in response}\n return titles\n\n\ndef create_terms_and_add_terms_to_it(title: str, terms: Dict['str', 'str']) -> bool:\n \"\"\"\n Creates a new set and adds terms to it.\n :param title: title of a new set\n :param terms: a dictionary. For example, {\"遠\": \"distant, far\", \"袁\": \"long kimono\"}\n \"\"\"\n\n headers = {\"Authorization\": \"Bearer \" + session['access_token']}\n terms_to_send = []\n definitions_to_send = []\n for term, definition in terms.items():\n terms_to_send.append(term)\n definitions_to_send.append(definition)\n data = {\n 'title': title,\n 'terms': terms_to_send,\n 'definitions': definitions_to_send,\n 'lang_terms': 'ja',\n 'lang_definitions': 'en'\n }\n requests.post('https://api.quizlet.com/2.0/sets', json=data, headers=headers)\n return True\n\n\ndef add_terms_to_set(set_id: str, new_terms: Dict['str', 'str']) -> bool:\n \"\"\"\n Adds terms to the set with id 'set_id'. Overwrite those that are already present.\n :param set_id: an id of the set to which terms will be added\n :param new_terms: a dictionary. For example, {\"遠\": \"distant, far\", \"袁\": \"long kimono\"}\n \"\"\"\n headers = {\"Authorization\": \"Bearer \" + session['access_token']}\n response = requests.get('https://api.quizlet.com/2.0/sets/' + set_id + '/terms', headers=headers)\n response = json.loads(response.text)\n title = json.loads(requests.get('https://api.quizlet.com/2.0/sets/' + set_id, headers=headers).text)['title']\n term_ids = []\n terms = []\n definitions = []\n for entry in response:\n terms.append(entry['term'])\n definitions.append(entry['definition'])\n term_ids.append(entry['id'])\n for term, definition in new_terms.items():\n if term not in terms:\n terms.append(term)\n definitions.append(definition)\n term_ids.append(0)\n else:\n # update definition\n term_index = terms.index(term)\n definitions[term_index] = definition\n\n data = {\n \"title\": title,\n \"term_ids\": [0] * len(terms),\n \"terms\": terms,\n \"definitions\": definitions\n }\n requests.put('https://api.quizlet.com/2.0/sets/' + set_id, json=data, headers=headers)\n return True\n\n\ndef process_lookup_text(text: str) -> List['str']:\n \"\"\"\n\n :param text: a text submitted by user. Normally, words separated by spaces.\n :return: a list of unique words from the text.\n \"\"\"\n # uses list to preserve order\n words = text.split(' ')\n result = []\n for word in words:\n if word not in result:\n result.append(word)\n return result\n\n\ndef get_dictionary_entries(terms: List['str']) -> Dict[str, str]:\n \"\"\"\n\n :param terms: a list of words\n :return: a dictionary where\n \"\"\"\n result = {}\n for term in terms:\n for entry in unabridged_dictionary_collection.find({\"word\": term}):\n result[term] = entry['entry']\n return result\n\n\ndef lookup_terms(text: str) -> Dict[str, str]:\n terms = process_lookup_text(text)\n return get_dictionary_entries(terms)\n\n\ndef build_part_query(set_of_elements, field_name):\n set_of_elements = permutations(set_of_elements)\n result = {'$or': []}\n for character_set in set_of_elements:\n query_part = {'$and': []}\n for character in character_set:\n query_part['$and'].append({field_name: {'$regex': character}})\n result['$or'].append(query_part)\n return result\n\n\ndef process_text_match(text: str, match: str = None) -> Dict[str, str]:\n\n text = text.strip('\\n').split(',')\n if len(text) == 1:\n kanji = text[0]\n pronunciations = None\n else:\n kanji, pronunciations = text[0], text[1]\n pronunciations = pronunciations.split(' ')\n kanji = kanji.split(' ')\n query_parts = []\n word_query_part = build_part_query(kanji, 'word')\n query_parts.append(word_query_part)\n if pronunciations:\n pronunciation_query_part = build_part_query(pronunciations, 'pronunciation')\n query_parts.append(pronunciation_query_part)\n\n words = []\n for element in words_pronunciation_collection.find({\"$and\": query_parts}):\n words.append(element[\"word\"])\n\n if match:\n available_kanji = get_terms_by_set_id(match)\n available_kanji = available_kanji.union(set(kanji))\n result = []\n for word in words:\n if len(set(word) - available_kanji) == 0:\n result.append(word)\n words = result\n\n words = give_meaning_to_words(words)\n\n return {key: words[key] for key in sorted(words)}\n\n\ndef change_theme(theme: str) -> bool:\n if theme not in ['day', 'night']:\n return False\n session['current_theme'] = theme\n return True\n","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"225736768","text":"# Definition for a binary tree node.\r\n# class TreeNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n\r\nfrom Utils import TreeNode\r\n\r\nclass Solution(object):\r\n def zigzagLevelOrder(self, root):\r\n \"\"\"\r\n :type root: TreeNode\r\n :rtype: List[List[int]]\r\n \"\"\"\r\n result = []\r\n que = [root]\r\n level = 1\r\n\r\n while que and que[0]: # root is none\r\n newque = []\r\n result_level = []\r\n for node in que:\r\n result_level.append(node.val)\r\n if node.left:\r\n newque.append(node.left)\r\n if node.right:\r\n newque.append(node.right)\r\n if level%2==0:\r\n result_level.reverse()\r\n level += 1\r\n result.append(result_level)\r\n que = newque\r\n \r\n return result\r\n\r\n\r\ns = Solution()\r\ntree = TreeNode.buildTree([3,9,20,None,None,15,7])\r\nprint(\r\n s.zigzagLevelOrder(tree)\r\n)","sub_path":"py3/sec2/Prob103.py","file_name":"Prob103.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"199880293","text":"class Solution(object):\n def getRow(self, rowIndex):\n \"\"\"\n :type rowIndex: int\n :rtype: List[int]\n \"\"\"\n res = [[] for i in range(rowIndex + 1)]\n res[0].append(1)\n \n for i in range(1,rowIndex + 1):\n for j in range(i + 1) :\n if(j == 0 or j == i ) :\n res[i].append(1)\n else:\n v = res[i-1][j - 1] + res[i-1][j]\n res[i].append(v)\n return res[-1]\n ","sub_path":"119.py","file_name":"119.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"203029966","text":"# -*- coding: utf-8 -*-\nfrom django.contrib.auth import get_user_model\n\nfrom rest_framework import viewsets\nfrom rest_framework.response import Response\n\nfrom .serializers import UserSerializer\nfrom .permissions import IsAdminOrIsMine\n\n\nUser = get_user_model()\n\n\nclass UserViewSet(viewsets.ModelViewSet):\n queryset = User.objects.all()\n serializer_class = UserSerializer\n permission_classes = (IsAdminOrIsMine, )\n\n def list(self, request, *args, **kwargs):\n if request.user.is_staff:\n queryset = self.filter_queryset(self.get_queryset())\n else:\n queryset = User.objects.filter(pk=request.user.pk)\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n","sub_path":"django/rest_frameworkd_source_and_fabric/prev_source/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"24485459","text":"import arrow\nfrom peewee import fn, JOIN\n\nfrom app.models import Publication, Asset, groups\nfrom app.models import PendingComment, RejectedComment, Comment\n\n\ndef create(name, domain):\n publication = Publication.create(name=name, domain=domain)\n return publication.id\n\n\ndef get(id):\n publication = Publication.select().where(Publication.id == id).first()\n return publication.to_dict() if publication else None\n\n\ndef get_by_domain(domain):\n publication = Publication.select().where(Publication.domain == domain).first()\n return publication.to_dict() if publication else None\n\n\ndef list_():\n publications = Publication.select().execute()\n return [publication.to_dict() for publication in publications]\nlist_.groups_required = [groups.moderator.value]\n\n\ndef update(id, mod_data):\n updatables = ('name', 'domain')\n update_dict = dict((k, v) for (k, v) in list(mod_data.items()) if k in updatables)\n\n Publication.update(**update_dict).where(Publication.id == id).execute()\nupdate.groups_required = [groups.community_manager.value]\n\n\ndef delete(id):\n Publication.delete().where(Publication.id == id).execute()\ndelete.groups_required = [groups.community_manager.value]\n\n\ndef get_assets(id, after=None, page: int=1, limit: int=20):\n assets = Asset.select().order_by(Asset.created.desc())\n where = [Asset.publication==id]\n if after:\n where.append(Asset.created > arrow.get(after).datetime)\n assets = assets.where(*where).paginate(page, limit)\n return [asset.to_dict() for asset in assets]\nget_assets.groups_required = [groups.moderator.value]\n\n\ndef get_assets_with_comment_stats(id, page: int=1, limit: int=20, after=None):\n assets = Asset.select(\n Asset,\n fn.COUNT(PendingComment.id).alias('total_pending_comments')\n ).where(\n Asset.publication == id\n ).join(\n PendingComment, JOIN.LEFT_OUTER\n ).order_by(\n fn.COUNT(PendingComment.id).desc(),\n Asset.created.desc()\n ).group_by(\n Asset.id\n ).paginate(page, limit)\n\n asset_ids = [asset.id for asset in assets]\n\n assets_with_rejected_comments_count = RejectedComment.select(\n RejectedComment.asset_id,\n fn.COUNT(RejectedComment.id).alias('total_rejected_comments')\n ).where(\n RejectedComment.asset_id << asset_ids\n ).group_by(RejectedComment.asset_id)\n rejected_comment_counts = {\n asset.asset_id: asset.total_rejected_comments for asset in assets_with_rejected_comments_count\n }\n\n assets_with_comments_count = Comment.select(\n Comment.asset_id,\n fn.COUNT(Comment.id).alias('total_comments')\n ).where(\n Comment.asset_id << asset_ids\n ).group_by(Comment.asset_id)\n comment_counts = {\n asset.id: asset.total_comments for asset in assets_with_comments_count\n }\n\n return [\n {\n 'comments_count': comment_counts.get(asset.id, 0),\n 'pending_comments_count': asset.total_pending_comments,\n 'rejected_comments_count': rejected_comment_counts.get(asset.id, 0),\n 'commenting_closed': asset.commenting_closed,\n **asset.to_dict()\n }\n for asset in assets\n ]\nget_assets_with_comment_stats.groups_required = [groups.moderator.value]\n","sub_path":"app/libs/publication.py","file_name":"publication.py","file_ext":"py","file_size_in_byte":3339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"308663527","text":"import urllib.request\nimport http.cookiejar\nimport urllib.parse\nimport random\nimport time\nimport pymysql\nimport json\nimport queue\nimport threading\nglobal l,r,sql\nclass MySQLDB:\n def __init__(self,hostname,user,pwd,db):\n self.__con=pymysql.connect(host=hostname,user=user,passwd=pwd,db=db)\n self.__cur=self.__con.cursor()\n def execute(self,order):\n try:\n print(order)\n self.__cur.execute(order)\n return self.__cur\n except:\n #print(order)\n print('order is incorrect')\n return None\n def commit(self):\n try:\n self.__con.commit()\n except:\n pass\n print('数据库已更新')\nclass users(threading.Thread):\n def __init__(self,id,pwd,startUnit,endUnit):\n threading.Thread.__init__(self)\n self.id=id\n self.pwd=pwd\n cj = http.cookiejar.LWPCookieJar()\n cookie_support = urllib.request.HTTPCookieProcessor(cj)\n self.opener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)\n posturl = 'http://202.198.110.38:82/Hepstudent/Ajax/ScoreAjax.ashx?Math=%s' % (str(random.uniform(0, 1))[0:17])\n fullurl=\"http://202.198.110.38:82/Hepstudent/Ajax/Login.ashx?random=%s&id=%s&pwd=%s&ut=1\" % (str(random.uniform(0, 1)),id, pwd)\n self.webheader= {'User-Agent': 'User-Agent: Mozilla/5.0 (Windows NT 7; WOW32; Trident/7.0; rv:7.0) like Gecko'}\n self.fullurl=urllib.request.Request(url=fullurl,headers=self.webheader)\n self.posturl=urllib.request.Request(url=posturl,headers=self.webheader)\n self.opener.open(fullurl=self.fullurl)\n self.startUnitId=startUnit\n self.endUnitId=endUnit\n class postThread(threading.Thread):\n def __init__(self,sec_q,opener,posturl,id):\n threading.Thread.__init__(self)\n self.sec_q=sec_q\n self.opener=opener\n self.posturl=posturl\n self.count=0\n self.id=id\n def run(self):\n postdata = self.sec_q.get()\n d=self.opener.open(fullurl=self.posturl, data=postdata)\n while(len(d.read().decode())<100):\n print('出现了失败的交易,正在重新交易')\n self.count+=1\n d = self.opener.open(fullurl=self.posturl, data=postdata)\n if self.count>=10:\n print(\"%s incorrect\"%self.id)\n break;\n self.sec_q.task_done()\n def getJson(self,chosedUnit):\n i=self.startUnitId\n sectionID=(\n 115,122,128,132,137,11,147,16,156,161,167,173,178,184,190,\n 196,202,206,210,216,223,228,232,238,241,246,250,255,260,264,\n 269,275,280,286,290,297,303,307,313,319,331,337,343,348,353,\n 360,367,373,379,386,396,403,409,416,422,466,441,446,453,460\n )\n jsonList=['http://202.198.110.38:82/HepStudent/Ajax/StudyAjax.ashx?Math=%s&levelID=%d&unitID=%d§ionID=%d' % (str (random.uniform(0, 1))[:17],x//15+4,x+1 if x<40 else x+2 if x<50 else x+3,sectionID[x]) for x in range(0,len(sectionID))]\n req=urllib.request.Request(url=jsonList[chosedUnit],headers=self.webheader)\n info=self.opener.open(req).read().decode()\n return info\n def run(self):\n nowUnitId=self.startUnitId\n postQueue=queue.Queue()\n for i in range(self.startUnitId,self.endUnitId):\n curentJson=self.getJson(i)\n try:\n currentModel = json.loads(curentJson)\n except:\n return;\n sectionArray = currentModel['Sections']\n for currentSecton in sectionArray:\n if (currentSecton['SectionName'].find('RWV') != -1 or \n currentSecton['SectionName']=='Listening Task' or \n currentSecton['SectionName'].find('Reading Task') != -1):\n postdata = urllib.parse.urlencode(dict(\n levelSequence=currentModel['Level']['LevelSequence'],\n unitSequence=currentModel['Unit']['UnitSequence'],\n sectionSequence=currentSecton['SectionSequence'],\n sectionName=currentSecton['SectionName'],\n topictype=currentSecton['TopicId'],\n score='%d'%(random.randint(100,100)) if currentSecton['SectionName'].find('RWV Role Play')==-1 else '%d'%(random.randint(50,53)),\n rolea='20.0',\n roleb='20.0',\n sectionID=currentSecton['SectionId'],\n unitid=currentModel['Unit']['UnitId'],\n passScore=\"10\",\n timeLimited=currentSecton['TimeLimited'],\n levelID=currentModel['Level']['LevelId'],\n duration='00:05:00',\n highWords='',\n lowWords='',\n pScore='良',\n rScore='差',\n fScore='良',\n sScore='差',\n tScore='良',\n )).encode()\n else:\n if currentSecton['SectionName'].find('Warm Up') != -1:\n score=random.randint(100,100)\n if currentSecton['SectionName'].find('Listening Task') != -1:\n score=random.randint(45,47)\n if currentSecton['SectionName'].find('Real World Listening') != -1:\n score=random.randint(45,48)\n postdata = urllib.parse.urlencode(\n dict(levelSequence=currentModel['Level']['LevelSequence'],\n unitSequence=currentModel['Unit']['UnitSequence'],\n sectionSequence=currentModel['Unit']['UnitSequence'],\n sectionName=currentSecton['SectionName'],\n topictype=currentSecton['TopicId'],\n score=str(score),\n rolea='0',\n roleb='0',\n sectionID=currentSecton['SectionId'],\n unitid=currentModel['Unit']['UnitId'],\n passScore=\"10\",\n timeLimited=currentSecton['TimeLimited'],\n levelID=currentModel['Level']['LevelId'],\n duration='00:05:00',\n highWords='',\n lowWords='',\n pScore='良',\n rScore='差',\n fScore='良',\n sScore='差',\n tScore='良',\n tips='',\n honor='',\n passinghonor=currentSecton['PassingHonor']\n )).encode()\n \n postQueue.put(postdata)\n while not postQueue.empty():\n time.sleep(random.randint(5,10))\n th=self.postThread(postQueue,self.opener,self.posturl,self.id)\n th.start()\n postQueue.join() \n nowUnitId+=1\n print('killed level %d unit %d'%(nowUnitId//15+3,nowUnitId%15+1))\n sql.execute('''update users set step=%d where id=\"%s\"'''%(nowUnitId,self.id))\n sql.commit()\n sql.execute('''update users set done=1 where id=\"%s\"'''%self.id)\n sql.commit()\nif __name__=='__main__':\n startTime=time.clock()\n log=open('log.csv','a')\n sql=MySQLDB(hostname='localhost',user='root',pwd='',db='pytrade')\n data=sql.execute('''select id,pwd,startunit,step,endunit from users where done=0''')\n data=[i for i in data]\n for user in data:\n print(user[0])\n th=users(user[0],user[1],max(int(user[2]),int(user[3])),user[4])\n th.start()\n while threading.active_count()>1:\n time.sleep(1)\n sql.commit()\n endtime=time.clock()\n print('交易完成,本次交易共花费了%.1f 秒!'%(endtime-startTime))","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"622402364","text":"from tortoise import fields\nfrom tortoise.backends.base.client import BaseDBAsyncClient\nfrom tortoise.exceptions import ConfigurationError\nfrom tortoise.models import get_backward_fk_filters, get_m2m_filters\n\n\nclass Tortoise:\n apps = {} # type: dict\n _inited = False\n _db_routing = None\n _global_connection = None\n\n @classmethod\n def register_model(cls, app, name, model):\n if app not in cls.apps:\n cls.apps[app] = {}\n if name in cls.apps[app]:\n raise ConfigurationError('{} duplicates in {}'.format(name, app))\n cls.apps[app][name] = model\n\n @classmethod\n def _set_connection_routing(cls, db_routing):\n if set(db_routing.keys()) != set(cls.apps.keys()):\n raise ConfigurationError('No db instanced for apps: {}'.format(\n \", \".join(set(db_routing.keys()) ^ set(cls.apps.keys()))))\n for app, client in db_routing.items():\n for model in cls.apps[app].values():\n model._meta.db = client\n\n @classmethod\n def _set_global_connection(cls, db_client):\n for app in cls.apps.values():\n for model in app.values():\n model._meta.db = db_client\n\n @classmethod\n def _client_routing(cls, global_client=None, db_routing=None):\n if global_client and db_routing:\n raise ConfigurationError('You must pass either global_client or db_routing')\n if global_client:\n if not isinstance(global_client, BaseDBAsyncClient):\n raise ConfigurationError('global_client must inherit from BaseDBAsyncClient')\n cls._set_global_connection(global_client)\n elif db_routing:\n if not all(isinstance(c, BaseDBAsyncClient) for c in db_routing.values()):\n raise ConfigurationError('All app values must inherit from BaseDBAsyncClient')\n cls._set_connection_routing(db_routing)\n else:\n raise ConfigurationError('You must pass either global_client or db_routing')\n\n @classmethod\n def _init_relations(cls):\n cls._inited = True\n for app_name, app in cls.apps.items():\n for model_name, model in app.items():\n if not model._meta.table:\n model._meta.table = model.__name__.lower()\n\n for field in model._meta.fk_fields:\n field_object = model._meta.fields_map[field]\n reference = field_object.model_name\n related_app_name, related_model_name = reference.split('.')\n related_model = cls.apps[related_app_name][related_model_name]\n field_object.type = related_model\n backward_relation_name = field_object.related_name\n if not backward_relation_name:\n backward_relation_name = '{}s'.format(model._meta.table)\n if backward_relation_name in related_model._meta.fields:\n raise ConfigurationError(\n 'backward relation \"{}\" duplicates in model {}'.format(\n backward_relation_name, related_model_name))\n fk_relation = fields.BackwardFKRelation(model, '{}_id'.format(field))\n setattr(related_model, backward_relation_name, fk_relation)\n related_model._meta.filters.update(\n get_backward_fk_filters(backward_relation_name, fk_relation)\n )\n\n related_model._meta.backward_fk_fields.add(backward_relation_name)\n related_model._meta.fetch_fields.add(backward_relation_name)\n related_model._meta.fields_map[backward_relation_name] = fk_relation\n related_model._meta.fields.add(backward_relation_name)\n\n for field in model._meta.m2m_fields:\n field_object = model._meta.fields_map[field]\n if field_object._generated:\n continue\n\n backward_key = field_object.backward_key\n if not backward_key:\n backward_key = '{}_id'.format(model._meta.table)\n field_object.backward_key = backward_key\n\n reference = field_object.model_name\n related_app_name, related_model_name = reference.split('.')\n related_model = cls.apps[related_app_name][related_model_name]\n\n field_object.type = related_model\n\n backward_relation_name = field_object.related_name\n if not backward_relation_name:\n backward_relation_name = '{}s'.format(model._meta.table)\n if backward_relation_name in related_model._meta.fields:\n raise ConfigurationError(\n 'backward relation \"{}\" duplicates in model {}'.format(\n backward_relation_name, related_model_name))\n\n if not field_object.through:\n related_model_table_name = (\n related_model._meta.table\n if related_model._meta.table else related_model.__name__.lower()\n )\n\n field_object.through = '{}_{}'.format(\n model._meta.table,\n related_model_table_name,\n )\n\n m2m_relation = fields.ManyToManyField(\n '{}.{}'.format(app_name, model_name),\n field_object.through,\n forward_key=field_object.backward_key,\n backward_key=field_object.forward_key,\n related_name=field,\n type=model\n )\n m2m_relation._generated = True\n setattr(\n related_model,\n backward_relation_name,\n m2m_relation,\n )\n model._meta.filters.update(get_m2m_filters(field, field_object))\n related_model._meta.filters.update(\n get_m2m_filters(backward_relation_name, m2m_relation)\n )\n related_model._meta.m2m_fields.add(backward_relation_name)\n related_model._meta.fetch_fields.add(backward_relation_name)\n related_model._meta.fields_map[backward_relation_name] = m2m_relation\n related_model._meta.fields.add(backward_relation_name)\n\n @classmethod\n def init(cls, global_client=None, db_routing=None):\n if cls._inited:\n raise ConfigurationError('Already initialised')\n cls._client_routing(global_client=global_client, db_routing=db_routing)\n cls._init_relations()\n\n\n__version__ = \"0.9.4\"\n","sub_path":"tortoise/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"157038744","text":"#!/usr/bin/env python3\nimport logging\nfrom pprint import pprint\nfrom plane_utils import config, \\\n get_html, \\\n open_file, \\\n get_details, \\\n make_header, \\\n make_data\nimport plane_logging \n\"\"\"\ndef row_magic(rows):\n logging.info(len(rows))\n logging.info(rows[0])\n logging.info(rows[5])\n logging.info(rows[6])\n for r in rows[4:]:\n out = {}\n h = make_header(rows[:1])\n #ogging.info(h)\n out[h[0]] = r[1]\n #out[h[1]] = r[2]\n #out[h[2]] = r[3]\n #out[h[3]] = r[4]\n\n pprint(out)\n\"\"\"\nif __name__ == '__main__':\n f = 'mock_data/1929.html'\n html = open_file(f)\n\n #rows = make_data(html)\n #pprint(rows[5:8])\n\n h = make_header(html)\n logging.info('h er: %s' % h)\n #row_magic(rows)\n\n\n #for i, r in enumerate(rows[5:]):\n # pprint(r)","sub_path":"dev.py","file_name":"dev.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"396395048","text":"import torch\r\nimport torchvision\r\nfrom PIL import Image, ImageDraw\r\nimport numpy as np\r\n\r\n###Convolutional Layers###\r\n\r\nimg_tensor = torch.zeros((1,3,800,800)).float()\r\nprint(img_tensor.shape)\r\n\r\n#梯度值\r\nimg_var = torch.autograd.Variable(img_tensor)\r\n#vgg16作为模型\r\nmodel = torchvision.models.vgg16(pretrained=False)\r\nfe = list(model.features)\r\nprint(fe)\r\n\r\n#生成一个列表\r\nreq_features = []\r\n\r\nk = img_var.clone()\r\n\r\n#这里的i(k)不太懂0.0\r\nfor i in fe:\r\n print(i)\r\n k = i(k)\r\n print(k.data.shape)\r\n if k.size()[2] < 800//16:\r\n break\r\n req_features.append(i)\r\n out_channels = k.size()[1]\r\nprint(len(req_features))\r\nprint(out_channels)\r\n\r\n#打印各层情况\r\nfor f in req_features:\r\n print(f)\r\n\r\n#\"*\"是像把名单(列表)传给这个函数一样\r\n#\"**\"则是字典\r\n#torch.nn.Sequential是按时序将你所给的层串成一个model(也就是文中的特征提取器)\r\nfaster_rcnn_fe_extractor = torch.nn.Sequential(*req_features)\r\nout_map = faster_rcnn_fe_extractor(img_var)\r\nprint(out_map.size())\r\n#输出特征图谱尺寸torch.Size([1, 512, 50, 50])\r\n#特征提取步骤中只有MaxPooling Layer将图片尺寸变为原来1/2,Conv和ReLu不改变图片大小\r\n\r\n#一个特征对应原图片中16*16个像素点区域\r\nfe_size = (800//16)\r\n# ctr_x , ctr_y 每个特征点对应原图片区域的右下方坐标\r\nctr_x = np.arange(16, (fe_size+1) * 16, 16)\r\nctr_y = np.arange(16, (fe_size+1) * 16, 16)\r\nprint(len(ctr_x)) #共50 * 50个特征点,将原图片分割成50*50=2500个区域\r\n\r\nindex = 0\r\n# ctr:每个特征点对应的原图片的中心点\r\nctr = dict()\r\nfor x in range(len(ctr_x)):\r\n for y in range(len(ctr_y)):\r\n ctr[index] = [-1, -1]\r\n ctr[index][1] = ctr_x[x] - 8\r\n ctr[index][0] = ctr_y[y] - 8\r\n index += 1\r\nprint(len(ctr))\r\n# 2500个对应原图的坐标点\r\n\r\n###生成anchor框###\r\n\r\n#用于生成anchor框的一些参数\r\nratios = [0.5, 1, 2]\r\nanchor_scales = [8, 16, 32]\r\nsub_sample = 16\r\n\r\n#初始化:每个区域有9个anchors候选框,每个候选框坐标(y1,x1,y2,x2)\r\nanchors = np.zeros(((fe_size * fe_size * 9), 4))\r\nprint(anchors.shape)\r\nindex = 0\r\n\r\n#将候选框的坐标赋值到anchors\r\nfor c in ctr:\r\n ctr_y, ctr_x = ctr[c]\r\n for i in range(len(ratios)):\r\n for j in range(len(anchor_scales)):\r\n #anchor scales是针对特征图的,所以需要乘以下采样\"sub_sample\"\r\n h = sub_sample * anchor_scales[j] * np.sqrt(ratios[i])\r\n w = sub_sample * anchor_scales[j] * np.sqrt(1. / ratios[i])\r\n anchors[index, 0] = ctr_y - h / 2.\r\n anchors[index, 1] = ctr_x - w / 2.\r\n anchors[index, 2] = ctr_y + h / 2.\r\n anchors[index, 3] = ctr_x + w / 2.\r\n index += 1\r\n#(22500 , 4)\r\nprint(anchors.shape)\r\n\r\n#有点懵\r\nimg_npy = img_tensor.numpy()\r\nimg_npy = np.transpose(img_npy[0], (1, 2, 0)).astype(np.float32)\r\nimg = Image.fromarray(np.uint8(img_npy))\r\ndraw = ImageDraw.Draw(img)\r\n\r\n#假设 图片中的两个目标框\"ground-truth\"\r\n#[y1, x1, y2, x2]format\r\n#asarray省内存\r\nbbox = np.asarray([[20, 30, 400, 500], [300, 400, 500, 600]], dtype=np.float32)\r\ndraw.rectangle([(30, 20), (500, 400)], outline=(100, 255, 0))\r\ndraw.rectangle([(400, 300), (600, 500)], outline=(100, 255, 0))\r\n\r\n#假设 图片中两个目标框分别对应的标签\r\n# 0 represents background\r\nlabels = np.asarray([6, 8], dtype=np.int8)\r\n\r\n# 去除坐标出界的边框,保留图片内的框——图片内框\r\n\r\nvalid_anchor_index = np.where(\r\n (anchors[:, 0] >= 0) &\r\n (anchors[:, 1] >= 0) &\r\n (anchors[:, 2] <= 800) &\r\n (anchors[:, 3] <= 800)\r\n )[0] # 该函数返回数组中满足条件的index\r\nprint(valid_anchor_index.shape) # (8940,),表明有8940个框满足条件\r\n\r\nvalid_anchor_boxes = anchors[valid_anchor_index]\r\nprint(valid_anchor_boxes.shape)\r\n\r\n#计算有效anchor框\"valid_anchor_boxes\"与目标框\"bbox\"\r\n#这里的2表示的是因为我们之前只是假设有两个目标框\r\nious = np.empty((len(valid_anchor_boxes), 2), dtype = np.float32)\r\nious.fill(0)\r\nprint(bbox)\r\n\r\nfor num1, i in enumerate(valid_anchor_boxes):\r\n ya1, xa1, ya2, xa2 = i\r\n anchor_area = (ya2 - ya1) * (xa2 - xa1)#anchor框面积\r\n for num2, j in enumerate(bbox):\r\n yb1, xb1, yb2, xb2 = j\r\n box_area = (yb2 - yb1) * (xb2 - xb1)#目标框面积\r\n inter_x1 = max([xb1, xa1])\r\n inter_y1 = max([yb1, ya1])\r\n # [x1, y1]左下点\r\n inter_x2 = min([xb2, xa2])\r\n inter_y2 = min([yb2, ya2])\r\n # [x2, y2]右上点\r\n if((inter_x1 < inter_x2) and (inter_y1 < inter_y2)):\r\n iter_area = (inter_y2 - inter_y1) * (inter_x2 - inter_x1)\r\n iou = iter_area / (anchor_area + box_area - iter_area)\r\n else:\r\n iou = 0.\r\n\r\n ious[num1, num2] = iou\r\n #两两之间的iou\r\n#所以此处的ious是8940个候选框和2个目标框的两两计算出的iou的矩阵\r\nprint(ious.shape)\r\n# 找出每个目标框最大IOU的anchor框的index,共2个\r\ngt_argmax_ious = ious.argmax(axis=0)\r\n# 获取每个目标框的最大IOU值\r\ngt_max_ious = ious[gt_argmax_ious, np.arange(ious.shape[1])]\r\n# 找出每个anchor框最大IOU的目标框index,共8940个\r\nargmax_ious = ious.argmax(axis=1)\r\n# 获取每个anchor框的最大IOU值,与argmax_ious对应\r\nmax_ious = ious[np.arange(len(valid_anchor_index)), argmax_ious]\r\n\r\ngt_argmax_ious = np.where(ious == gt_max_ious)[0]\r\nprint(gt_argmax_ious.shape)\r\n\r\npos_iou_threshold = 0.7\r\nneg_iou_threshold = 0.3\r\nlabel = np.empty((len(valid_anchor_index), ), dtype=np.int32)\r\nlabel.fill(-1)\r\nprint(label.shape)\r\n#某个点的9个框中的最大的iou都比负阙值小,则舍弃该点\r\nlabel[max_ious < neg_iou_threshold] = 0\r\n#全局极大必为1\r\nlabel[gt_argmax_ious] = 1\r\n#某个点的9个框的最大IOU比正阙值大,则保留\r\nlabel[max_ious >= pos_iou_threshold] = 1\r\n\r\n\r\n#先假设有一半正例,一半反例\r\npos_ratio = 0.5\r\nn_sample = 256\r\nn_pos = pos_ratio * n_sample\r\n\r\n#随机获取n_pos个正例\r\npos_index = np.where(label == 1)[0]\r\nif len(pos_index) > n_pos:\r\n disable_index = np.random.choice(pos_index, size=len(pos_index) - n_pos, replace=False)\r\n label[disable_index] = -1\r\n\r\nn_neg = n_sample - np.sum(label == 1)\r\nneg_index = np.where(label == 0)[0]\r\n\r\nif len(neg_index) > n_neg:\r\n disable_index = np.random.choice(neg_index, size=len(neg_index) - n_neg, replace=False)\r\n label[disable_index] = -1#这里是不是要改成+1呢?\r\nprint(np.sum(label == 1))\r\nprint(np.sum(label == 0))\r\n\r\n# 现在让我们用具有最大iou的ground truth对象为每个anchor box分配位置\r\n# 注意我们将为所有有效的anchor box分配anchor locs,而不考虑其标签,稍后计算损失时,我们可用简单的过滤器删除他们。\r\n\r\n# 为每个点都找到其9个框中iou最高的一个框\r\nmax_iou_bbox = bbox[argmax_ious]\r\nprint(max_iou_bbox)\r\nprint(max_iou_bbox.shape)\r\n# (8940, 4)\r\n\r\n# 有效的anchor的中心点和宽高\r\nheight = valid_anchor_boxes[:, 2] - valid_anchor_boxes[:, 0]\r\nwidth = valid_anchor_boxes[:, 3] - valid_anchor_boxes[:, 1]\r\nctr_y = valid_anchor_boxes[:, 0] + 0.5 * height\r\nctr_x = valid_anchor_boxes[:, 1] + 0.5 * width\r\n# 有效anchor对应目标框的中心点和宽高\r\nbase_height = max_iou_bbox[:, 2] - max_iou_bbox[:, 0]\r\nbase_width = max_iou_bbox[:, 3] - max_iou_bbox[:, 1]\r\nbase_ctr_y = max_iou_bbox[:, 0] + 0.5 * base_height\r\nbase_ctr_x = max_iou_bbox[:, 1] + 0.5 * base_width\r\n\r\n# 有效anchor转为目标框的系数(dy, dx为平移系数;dh, dw是放缩系数)\r\neps = np.finfo(height.dtype).eps\r\nheight = np.maximum(height, eps)\r\nwidth = np.maximum(width, eps)\r\ndy = (base_ctr_y - ctr_y) / height\r\ndx = (base_ctr_x - ctr_x) / width\r\ndh = np.log(base_height / height)\r\ndw = np.log(base_width / width)\r\nanchor_locs = np.vstack((dy, dx, dh, dw)).transpose()\r\nprint(anchor_locs.shape)\r\n\r\nanchor_labels = np.empty((len(anchors),), dtype=label.dtype)\r\nanchor_labels.fill(-1)\r\nanchor_labels[valid_anchor_index] = label\r\n\r\n# 懵逼\r\n# anchor_locations:每个有效anchor框转换为目标框的系数\r\nanchor_locations = np.empty((len(anchors),) + anchors.shape[1:], dtype=anchor_locs.dtype)\r\nanchor_locations.fill(0)\r\nanchor_locations[valid_anchor_index, :] = anchor_locs\r\n\r\n###Region Proposal Network###\r\n\r\nimport torch.nn as nn\r\nmid_channels = 512\r\nin_channels = 512\r\n# number of anchors at each location\r\nn_anchor = 9\r\nconv1 = nn.Conv2d(in_channels, mid_channels, 3, 1, 1)\r\nreg_layer = nn.Conv2d(mid_channels, n_anchor * 4, 1, 1, 0)\r\ncls_layer = nn.Conv2d(mid_channels, n_anchor * 2, 1, 1, 0)\r\n\r\n# conv sliding layer\r\nconv1.weight.data.normal_(0, 0.01)\r\nconv1.bias.data.zero_()\r\n\r\n# Regression layer\r\nreg_layer.weight.data.normal_(0, 0.01)\r\nreg_layer.bias.data.zero_()\r\n\r\n# classification layer\r\ncls_layer.weight.data.normal_(0, 0.01)\r\ncls_layer.bias.data.zero_()\r\n\r\n# out_map is 由CNN得到的特征图谱\r\nx = conv1(out_map)\r\n#回归层,计算有效anchor转为目标框的四个系数\r\npred_anchor_locs = reg_layer(x)\r\n#分类层,判断该anchor是否可以捕获目标\r\npred_cls_scores = cls_layer(x)\r\n# ((1L, 18L, 50L, 50L), (1L, 36L, 50L, 50L))\r\nprint(pred_cls_scores.shape, pred_anchor_locs.shape)\r\n\r\n# permute用来改变张量的维度顺序,简而言之,使张量变形\r\n# contiguous重新开辟一块空间来存储底层的一维数组,使用此函数后才可以调用view()否则报错\r\npred_anchor_locs = pred_anchor_locs.permute(0, 2, 3, 1).contiguous().view(1, -1, 4)\r\nprint(pred_anchor_locs.shape)\r\n# Out: torch.Size([1, 22500, 4])\r\n\r\npred_cls_scores = pred_cls_scores.permute(0, 2, 3, 1).contiguous()\r\nprint(pred_cls_scores.shape)\r\n# Out torch.Size([1, 50, 50, 18])\r\n\r\nobjectness_score = pred_cls_scores.view(1, 50, 50, 9, 2)[:, :, :, :, 1].contiguous().view(1, -1)\r\nprint(objectness_score.shape)\r\n# Out torch.Size([1, 22500])\r\n\r\npred_cls_scores = pred_cls_scores.view(1, -1, 2)\r\nprint(pred_cls_scores.shape)\r\n# Out torch.size([1, 22500, 2])\r\n\r\n# Generating proposals to feed Fast R-CNN network\r\nn_train_pre_nms = 12000\r\nn_train_post_nms = 2000\r\nn_test_pre_nms = 6000\r\nn_test_post_nms = 300\r\nmin_size = 16\r\n\r\n# 转换anchor格式从 y1, x1, y2, x2 到 ctr_x, ctr_y, h, w\r\nanc_height = anchors[:, 2] - anchors[:, 0]\r\nanc_width = anchors[:, 3] - anchors[:, 1]\r\nanc_ctr_y = anchors[:, 0] + 0.5 * anc_height\r\nanc_ctr_x = anchors[:, 1] + 0.5 * anc_width\r\n\r\n# 懵逼!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n# 懵逼!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n# 懵逼!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\r\n# 根据预测的四个系数,将anchor框通过平移和缩放转化为预测的目标框\r\npred_anchor_locs_numpy = pred_anchor_locs[0].data.numpy()\r\nobjectness_score_numpy = objectness_score[0].data.numpy()\r\n# python的双冒号和matlab很像,起始:终止:步长\r\n# 把预测的anchor矩阵中的存储的各个坐标抽出来\r\n# []\r\ndy = pred_anchor_locs_numpy[:, 0::4]\r\ndx = pred_anchor_locs_numpy[:, 1::4]\r\ndh = pred_anchor_locs_numpy[:, 2::4]\r\ndw = pred_anchor_locs_numpy[:, 3::4]\r\n\r\n# anc_height.shape (22500,)\r\n# ctr_y.shape (22500,)\r\n\r\n# np.newaxis在原来数据基础上增加一个维度\r\nctr_y = dy * anc_height[:, np.newaxis] + anc_ctr_y[:, np.newaxis]\r\nctr_x = dx * anc_width[:, np.newaxis] + anc_ctr_x[:, np.newaxis]\r\nh = np.exp(dh) * anc_height[:, np.newaxis]\r\nw = np.exp(dw) * anc_width[:, np.newaxis]\r\n\r\n\r\n\r\n# ROI : region of interest\r\n# 将预测目标框转换为[y1, x1, y2, x2]格式\r\n# roi是个大矩阵[22500, 4]\r\nroi = np.zeros(pred_anchor_locs_numpy.shape, dtype=pred_anchor_locs_numpy.dtype)\r\nroi[:, 0::4] = ctr_y - 0.5 * h\r\nroi[:, 1::4] = ctr_x - 0.5 * w\r\nroi[:, 2::4] = ctr_y + 0.5 * h\r\nroi[:, 3::4] = ctr_x + 0.5 * w\r\n\r\n# 剪辑预测框到图像上\r\nimg_size = (800, 800)\r\nroi[:, slice(0, 4, 2)] = np.clip(roi[:, slice(0, 4, 2)], 0, img_size[0])\r\nroi[:, slice(1, 4, 2)] = np.clip(roi[:, slice(1, 4, 2)], 0, img_size[1])\r\nprint(roi.shape)\r\n\r\n# 去除高度和宽度小于threshold的预测框\r\n# 为什么要去除这些预测框?\r\nhs = roi[:, 2] - roi[:, 0]\r\nws = roi[:, 3] - roi[:, 1]\r\nkeep = np.where((hs >= min_size) & (ws >= min_size))[0]\r\nroi = roi[keep, :]\r\nscore = objectness_score_numpy[keep]\r\n\r\norder = score.ravel().argsort()[::-1]\r\nprint(order.shape)\r\n# (22500, )\r\n\r\n# 取前几个预测框pre_nms_topN(如训练时12000,测试时300)\r\norder = order[:n_train_pre_nms]\r\nroi = roi[order, :]\r\nprint(roi.shape)\r\n# (12000, 4)\r\n\r\n# nms(非极大抑制)计算\r\n# 去除和极大值anchor框IOU大于70%的框\r\n# 去除相交的框,保留score大,且基本无相交的框\r\nnms_thresh = 0.7\r\ny1 = roi[:, 0]\r\nx1 = roi[:, 1]\r\ny2 = roi[:, 2]\r\nx2 = roi[:, 3]\r\n# y1, x1, y2, x2现在代表原图上ROI的左下和右上的坐标列向量\r\n\r\nareas = (x2 - x1 + 1) * (y2 - y1 + 1)\r\n# areas是ROI的面积列向量\r\nscore = score[order]\r\norder = score.argsort()[::-1]\r\nprint(order)\r\nkeep = []\r\n\r\nwhile order.size > 0:\r\n i = order[0]\r\n keep.append(i)\r\n xx1 = np.maximum(x1[i], x1[order[1:]])\r\n yy1 = np.maximum(y1[i], y1[order[1:]])\r\n xx2 = np.maximum(x2[i], x2[order[1:]])\r\n yy2 = np.maximum(y2[i], y2[order[1:]])\r\n\r\n w = np.maximum(0.0, xx2 - xx1 + 1)\r\n h = np.maximum(0.0, yy2 - yy1 + 1)\r\n inter = w * h\r\n\r\n ovr = inter / (areas[i] + areas[order[1:]] - inter)\r\n\r\n inds = np.where(ovr <= nms_thresh)[0]\r\n order = order[inds + 1]\r\n\r\nkeep = keep[:n_train_post_nms]\r\nroi = roi[keep]\r\nprint(roi.shape)\r\n\r\n\r\n###Proposal targets###\r\n\r\nn_sample = 128\r\npos_ratio = 0.25\r\npos_iou_thresh = 0.5\r\nneg_iou_thresh_hi = 0.5\r\nneg_iou_thresh_lo = 0.0\r\n\r\n# 找到每个ground-truth目标(真实目标框)与region proposal(预测目标框)的IOU\r\nious = np.empty((len(roi), 2), dtype=np.float32)\r\nious.fill(0)\r\nfor num1, i in enumerate(roi):\r\n ya1, xa1, ya2, xa2 = i\r\n anchor_area = (ya2 - ya1) * (xa2 - xa1)\r\n for num2, j in enumerate(bbox):\r\n yb1, xb1, yb2, xb2 = j\r\n box_area = (yb2 - yb1) * (xb2 - xb1)\r\n\r\n inter_x1 = max([xb1, xa1])\r\n inter_y1 = max([yb1, ya1])\r\n inter_x2 = min([xb2, xa2])\r\n inter_y2 = min([yb2, ya2])\r\n\r\n if (inter_x1 < inter_x2) and (inter_y1 < inter_y2):\r\n iter_area = (inter_y2 - inter_y1) * (inter_x2 - inter_x1)\r\n iou = iter_area / (anchor_area + box_area - iter_area)\r\n else:\r\n iou = 0.\r\n\r\n ious[num1, num2] = iou\r\nprint(ious.shape)\r\n\r\ngt_assignment = ious.argmax(axis=1)\r\nmax_iou = ious.max(axis=1)\r\nprint(gt_assignment)\r\nprint(max_iou)\r\n\r\n# 为每个proposal分配标签:\r\ngt_roi_label = labels[gt_assignment]\r\nprint(gt_roi_label)\r\n\r\n# 希望只保留n_sample*pos_ratio(128*0.25=32)个前景样本,因此如果只得到少于32个正样本,保持原状。\r\n# 如果得到多余32个前景目标,从中采样32个样本\r\n# 前景目标可理解成背景的反义词,是有清晰语义的目标\r\npos_roi_per_image = 32\r\npos_index = np.where(max_iou >= pos_iou_thresh)[0]\r\npos_roi_per_this_image = int(min(pos_roi_per_image, pos_index.size))\r\n# 这个if是干嘛用的\r\nif pos_index.size > 0:\r\n pos_index = np.random.choice(pos_index, size=pos_roi_per_this_image, replace=False)\r\nprint(pos_index)\r\n# 针对负[背景]region proposal进行相似处理\r\nneg_index = np.where((max_iou < neg_iou_thresh_hi) & (max_iou >= neg_iou_thresh_lo))[0]\r\nneg_roi_per_this_image = n_sample - pos_roi_per_this_image\r\nneg_roi_per_this_image = int(min(neg_roi_per_this_image, neg_index.size))\r\nif neg_index.size > 0:\r\n neg_index = np.random.choice(neg_index, size=neg_roi_per_this_image, replace=False)\r\n# print(neg_roi_per_this_image)\r\nprint(neg_index)\r\n\r\n#有点懵\r\nkeep_index = np.append(pos_index, neg_index)\r\ngt_roi_labels = gt_roi_label[keep_index]\r\n# 将negtive labels全部置为0\r\ngt_roi_labels[pos_roi_per_this_image:] = 0\r\nsample_roi = roi[keep_index]\r\nprint(sample_roi.shape)\r\n# 目标框\r\nbbox_for_sampled_roi = bbox[gt_assignment[keep_index]]\r\nprint(bbox_for_sampled_roi.shape)\r\n\r\nheight = sample_roi[:, 2] - sample_roi[:, 0]\r\nwidth = sample_roi[:, 3] - sample_roi[:, 1]\r\nctr_y = sample_roi[:, 0] + 0.5 * height\r\nctr_x = sample_roi[:, 1] + 0.5 * width\r\nbase_height = bbox_for_sampled_roi[:, 2] - bbox_for_sampled_roi[:, 0]\r\nbase_width = bbox_for_sampled_roi[:, 3] - bbox_for_sampled_roi[:, 1]\r\nbase_ctr_y = bbox_for_sampled_roi[:, 0] + 0.5 * base_height\r\nbase_ctr_x = bbox_for_sampled_roi[:, 1] + 0.5 * base_width\r\n\r\n\r\neps = np.finfo(height.dtype).eps\r\nheight = np.maximum(height, eps)\r\nwidth = np.maximum(width, eps)\r\n\r\n# 为���,不应该是训练的吗?咋还直接算出来了?\r\ndy = (base_ctr_y - ctr_y) / height\r\ndx = (base_ctr_x - ctr_x) / width\r\ndh = np.log(base_height / height)\r\ndw = np.log(base_width / width)\r\n\r\n# v-vertical vstack()把矩阵垂直摞起来.\r\ngt_roi_locs = np.vstack((dy, dx, dh, dw)).transpose()\r\nprint(gt_roi_locs.shape)\r\n\r\nrois = torch.from_numpy(sample_roi).float()\r\nroi_indices = 0 * np.ones((len(rois),), dtype=np.int32)\r\nroi_indices = torch.from_numpy(roi_indices).float()\r\nprint(rois.shape, roi_indices.shape)\r\n\r\nindices_and_rois = torch.cat([roi_indices[:, None], rois], dim=1)\r\nxy_indices_and_rois = indices_and_rois[:, [0, 2, 1, 4, 3]]\r\nindices_and_rois = xy_indices_and_rois.contiguous()\r\nprint(xy_indices_and_rois.shape)\r\n\r\n\r\n\r\n###ROI Pooling###\r\n\r\n\r\nsize = (7, 7)\r\nadaptive_max_pool = torch.nn.AdaptiveMaxPool2d(size[0], size[1])\r\noutput = []\r\nrois = indices_and_rois.float()\r\nrois[:, 1:].mul_(1/16.0)\r\nrois = rois.long()\r\nnum_rois = rois.size(0)\r\nfor i in range(num_rois):\r\n roi = rois[i]\r\n im_idx = roi[0]\r\n im = out_map.narrow(0, im_idx, 1)[..., roi[2]:(roi[4]+1), roi[1]:(roi[3]+1)]\r\n output.append(adaptive_max_pool(im)[0].data)\r\noutput = torch.stack(output)\r\nprint(output.size())\r\n\r\nk = output.view(output.size(0), -1)\r\nprint(k.shape)\r\n\r\n\r\n###分类层###\r\nroi_head_classifier = nn.Sequential(*[nn.Linear(25088, 4096),\r\n nn.Linear(4096, 4096)])\r\n# (VOC 20 classes + 1 background. Each will have 4 co-ordinates)\r\ncls_loc = nn.Linear(4096, 21 * 4)\r\ncls_loc.weight.data.normal_(0, 0.01)\r\n\r\ncls_loc.bias.data.zero_()\r\n# (VOC 20 classes + 1 background)\r\nscore = nn.Linear(4096, 21)\r\n\r\nk = torch.autograd.Variable(k)\r\nk = roi_head_classifier(k)\r\nroi_cls_loc = cls_loc(k)\r\nroi_cls_score = score(k)\r\nprint(roi_cls_loc.data.shape, roi_cls_score.data.shape)\r\n\r\n# Faster RCNN 损失函数\r\nprint(pred_anchor_locs.shape) # torch.Size([1, 22500, 4]) # RPN网络预测的坐标系数\r\nprint(pred_cls_scores.shape) # torch.Size([1, 22500, 2]) # RPN网络预测的类别\r\nprint(anchor_locations.shape) # (22500, 4) # anchor对应的实际坐标系数\r\nprint(anchor_labels.shape) # (22500,) # anchor的实际类别\r\n\r\n# 将输入输出排成一行\r\nrpn_loc = pred_anchor_locs[0]\r\nrpn_score = pred_cls_scores[0]\r\ngt_rpn_loc = torch.from_numpy(anchor_locations)\r\ngt_rpn_score = torch.from_numpy(anchor_labels)\r\nprint(rpn_loc.shape, rpn_score.shape, gt_rpn_loc.shape, gt_rpn_score.shape)\r\n\r\n# 对classification用交叉熵损失\r\ngt_rpn_score = torch.autograd.Variable(gt_rpn_score.long())\r\nrpn_cls_loss = torch.nn.functional.cross_entropy(rpn_score, gt_rpn_score, ignore_index=-1)\r\nprint(rpn_cls_loss)\r\n\r\n# 对于Regression 使用 smooth L1损失\r\npos = gt_rpn_score.data > 0\r\nmask = pos.unsqueeze(1).expand_as(rpn_loc)\r\nprint(mask.shape) # (22500L, 4L)\r\n\r\n# ?????????????????????????????????\r\n# 取有正数标签的边界区域\r\nmask_loc_preds = rpn_loc[mask].view(-1, 4)\r\nmask_loc_targets = gt_rpn_loc[mask].view(-1, 4)\r\nprint(mask_loc_preds.shape, mask_loc_targets.shape)\r\n\r\n# regression损失应用如下\r\nx = np.abs(mask_loc_targets.numpy() - mask_loc_preds.data.numpy())\r\nprint(x.shape)\r\n\r\nrpn_loc_loss = ((x < 1) * 0.5 * x**2) + ((x >= 1) * (x-0.5))\r\nrpn_loc_loss = rpn_loc_loss.sum()\r\nprint(rpn_loc_loss)\r\n\r\nN_reg = (gt_rpn_score > 0).float().sum()\r\nN_reg = np.squeeze(N_reg.data.numpy())\r\n\r\n# ??????????????????????????????\r\nprint(\"N_reg: {}, {}\".format(N_reg, N_reg.shape))\r\nrpn_loc_loss = rpn_loc_loss / N_reg\r\nrpn_loc_loss = np.float32(rpn_loc_loss)\r\n# rpn_loc_loss = torch.autograd.Variable(torch.from_numpy(rpn_loc_loss))\r\nrpn_lambda = 10.\r\nrpn_cls_loss = np.squeeze(rpn_cls_loss.data.numpy())\r\nprint(\"rpn_cls_loss: {}\".format(rpn_cls_loss)) # 0.693146109581\r\nprint('rpn_loc_loss: {}'.format(rpn_loc_loss)) # 0.0646051466465\r\nrpn_loss = rpn_cls_loss + (rpn_lambda * rpn_loc_loss)\r\nprint(\"rpn_loss: {}\".format(rpn_loss)) # 1.33919757605\r\n\r\n\r\n\r\n# Faster R-CNN 损失函数\r\n\r\n# 预测\r\nprint(roi_cls_loc.shape) # # torch.Size([128, 84])\r\nprint(roi_cls_score.shape) # torch.Size([128, 21])\r\n\r\n# 真实\r\nprint(gt_roi_locs.shape) # (128, 4)\r\nprint(gt_roi_labels.shape) # (128, )\r\n\r\ngt_roi_loc = torch.from_numpy(gt_roi_locs)\r\ngt_roi_label = torch.from_numpy(np.float32(gt_roi_labels)).long()\r\nprint(gt_roi_loc.shape, gt_roi_label.shape) # torch.Size([128, 4]) torch.Size([128])\r\n\r\n# 分类损失\r\ngt_roi_label = torch.autograd.Variable(gt_roi_label)\r\nroi_cls_loss = torch.nn.functional.cross_entropy(roi_cls_score, gt_roi_label, ignore_index=-1)\r\nprint(roi_cls_loss) # Variable containing: 3.0515\r\n\r\n\r\n# 回归损失\r\nn_sample = roi_cls_loc.shape[0]\r\nroi_loc = roi_cls_loc.view(n_sample, -1, 4)\r\nprint(roi_loc.shape) # (128L, 21L, 4L)\r\n\r\nroi_loc = roi_loc[torch.arange(0, n_sample).long(), gt_roi_label]\r\nprint(roi_loc.shape) # torch.Size([128, 4])\r\n\r\n\r\n# 用计算RPN网络回归损失的方法计算回归损失\r\n# roi_loc_loss = REGLoss(roi_loc, gt_roi_loc)\r\n\r\npos = gt_roi_label.data > 0 # Regression 损失也被应用在有正标签的边界区域中\r\nmask = pos.unsqueeze(1).expand_as(roi_loc)\r\nprint(mask.shape) # (128, 4L)\r\n\r\n# 现在取有正数标签的边界区域\r\nmask_loc_preds = roi_loc[mask].view(-1, 4)\r\nmask_loc_targets = gt_roi_loc[mask].view(-1, 4)\r\nprint(mask_loc_preds.shape, mask_loc_targets.shape) # ((19L, 4L), (19L, 4L))\r\n\r\n\r\nx = np.abs(mask_loc_targets.numpy() - mask_loc_preds.data.numpy())\r\nprint(x.shape) # (19, 4)\r\n\r\nroi_loc_loss = ((x < 1) * 0.5 * x**2) + ((x >= 1) * (x-0.5))\r\nprint(roi_loc_loss.sum()) # 1.4645805211187053\r\n\r\n\r\nN_reg = (gt_roi_label > 0).float().sum()\r\nN_reg = np.squeeze(N_reg.data.numpy())\r\nroi_loc_loss = roi_loc_loss.sum() / N_reg\r\nroi_loc_loss = np.float32(roi_loc_loss)\r\nprint(roi_loc_loss) # 0.077294916\r\n# roi_loc_loss = torch.autograd.Variable(torch.from_numpy(roi_loc_loss))\r\n\r\n\r\n# ROI损失总和\r\nroi_lambda = 10.\r\nroi_cls_loss = np.squeeze(roi_cls_loss.data.numpy())\r\nroi_loss = roi_cls_loss + (roi_lambda * roi_loc_loss)\r\nprint(roi_loss) # 3.810348778963089\r\n\r\n\r\ntotal_loss = rpn_loss + roi_loss\r\n\r\nprint(total_loss) # 5.149546355009079\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"12.22/simple_faster_RCNN.py","file_name":"simple_faster_RCNN.py","file_ext":"py","file_size_in_byte":22611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"546804676","text":"\"\"\"\nExamples using rosetta.modeling.eda\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pylab as pl\n\nfrom rosetta.modeling import eda\n\nN = 1000\n\n# Make a linear income vs. age relationship.\nage = pd.Series(100 * np.random.rand(N))\nage.name = 'age'\nincome = 10 * age + 10 * np.random.randn(N)\n\n# The relationship E[Y | X=x] is linear\npl.figure(1); pl.clf()\neda.plot_reducedY_vs_binnedX(age, income)\n\n\n# Make a sigmoidal P[cancer | X=x] relationship\ndef sigmoid(x):\n x_st = 5 * (x - x.mean()) / x.std()\n return np.exp(x_st) / (1 + np.exp(x_st))\n\nhas_cancer = (np.random.rand(N) < sigmoid(age)).astype('int')\npl.figure(2); pl.clf()\neda.plot_reducedY_vs_binnedX(age, has_cancer)\n","sub_path":"examples/eda_examples.py","file_name":"eda_examples.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"45547618","text":"from flask import render_template, Blueprint, make_response\n\nfrom ..model.drop_point import DropPoint\nfrom ..model.report import Report\nfrom ..model.visit import Visit\n\n\nstats = Blueprint(\"statistics\", __name__)\n\n\n@stats.route(\"/numbers\")\ndef html():\n return render_template(\n \"statistics.html\",\n stats=Statistics()\n )\n\n\n@stats.route(\"/numbers.js\")\ndef js():\n resp = make_response(render_template(\n \"js/statistics.js\",\n stats=Statistics()\n ))\n resp.mimetype = \"application/javascript\"\n return resp\n\n\nclass Statistics(object):\n\n @property\n def drop_point_count(self):\n return DropPoint.query.count()\n\n @property\n def report_count(self):\n return Report.query.count()\n\n @property\n def visit_count(self):\n return Visit.query.count()\n\n @property\n def drop_points_by_state(self):\n ret = {}\n for state in Report.states:\n ret[state] = 0\n for dp in DropPoint.query.all():\n if not dp.removed:\n s = dp.get_last_state()\n ret[s] = ret[s] + 1 if s in ret else 1\n return ret\n\n @property\n def reports_by_state(self):\n ret = {}\n for state in Report.states:\n ret[state] = Report.query.filter(Report.state == state).count()\n return ret\n\n @property\n def visits_by_action(self):\n ret = {}\n for action in Visit.actions:\n ret[action] = Visit.query.filter(Visit.action == action).count()\n return ret\n","sub_path":"c3bottles/views/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"483460518","text":"from parser import *\nfrom Search.solver import *\nimport sys\n\nif __name__ == \"__main__\":\n\n try:\n SRC_FILE = sys.argv[1]\n\n except IndexError:\n print(\"[ERROR]: Not Enough Arguments\")\n sys.exit(1)\n\n try:\n method = int(sys.argv[2])\n except Exception:\n method = None\n\n try:\n optimal = sys.argv[3]\n if optimal is 'o':\n optimal = True\n except Exception:\n optimal = False\n\n results = []\n\n # Open file and parse it from input\n with open(SRC_FILE, 'r') as file:\n\n # Number of iterations\n n_i = int(file.readline().split().pop(0))\n\n for i in range(0, n_i):\n\n if i is 5:\n break\n\n # Number of rectangles\n n_r = int(file.readline().split().pop(0))\n\n vertices = parse(file, n_r+1)\n\n print(\"###########################\")\n print(\"Iteration:\", i+1)\n if method is None:\n print(\"Simple\")\n elif method == 1:\n print(\"BFS Algorithm\")\n elif method == 2:\n if optimal is True:\n print(\"Optimized\", end=' ')\n print(\"DFS Algorithm\")\n elif method == 3:\n print(\"Iterative Deepening Search Algorithm\")\n elif method == 4:\n print(\"A* Algorithm\")\n elif method == 5:\n print(\"Branch-and-Bound\")\n else:\n print(\"Method does not exist\")\n break\n\n solution = Solver(vertices)\n solution.solve(n_r, method, optimal)\n\n results.append(len(solution.solution))\n\n # print(\"Probable guards: \", solution.solution)\n # print(\"Number of guards: \", len(solution.solution))\n\n\n\n # decision = input(\"Do you want to continue: [y/n]\")\n # if decision is \"n\":\n # break\n\n print(sum(results)/len(results))\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"84617277","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pulp\nimport glob\n\nfrom matplotlib import rcParams\nrcParams['font.family'] = 'sans-serif'\nrcParams['font.sans-serif'] = ['Hiragino Maru Gothic Pro', 'Yu Gothic', 'Meirio', 'Takao', 'IPAexGothic', 'IPAPGothic', 'VL PGothic', 'Noto Sans CJK JP']\n\n# MODE = 'all'\nMODE = 'normal'\n\n\n\nfilenames = glob.glob('data_severe/x_*')\nfilenames.sort()\nforecast_dates = [filename.split('_')[-1].split('.')[0] for filename in filenames]\n\n\n\n\ndef visualization(gamma,x_type,forecast_date): \n print(\"forcasted date ={0}\".format(f_date))\n \n # 重みの入力\n df_w = pd.read_csv('data_Kokudo/w_distance.csv',index_col=0)\n W= df_w.values\n w_pulp = W.T.reshape(-1)\n\n \n # x, x_q0025も計算\n df_x0975 = pd.read_csv('data_severe/x0975_{0}.csv'.format(forecast_date),index_col=0 )\n df_x0025 = pd.read_csv('data_severe/x0025_{0}.csv'.format(forecast_date),index_col=0 )\n df_xmean = pd.read_csv('data_severe/x_{0}.csv'.format(forecast_date),index_col=0 )\n gammas = np.load('data_transport/gammas_{0}_{1:03}_{2}.npy'.format(x_type,int(gamma*100),forecast_date))\n\n x_mean = df_xmean.values\n x_q0975 = df_x0975.values\n x_q0025 = df_x0025.values\n\n N = x_mean.shape[1]\n T = x_mean.shape[0]\n\n L = np.kron(np.ones((1,N)),np.eye(N)) - np.kron(np.eye(N),np.ones((1,N)))\n\n uv = np.load('data_transport/u_{0}_{1:03}_{2}.npy'.format(x_type,int(gamma*100),forecast_date))\n \n y_mean = np.zeros(x_mean.shape)\n y_q0975 = np.zeros(x_mean.shape)\n y_q0025 = np.zeros(x_mean.shape)\n\n y_mean[0] = x_mean[0]\n y_q0975[0] = x_q0975[0]\n y_q0025[0] = x_q0025[0]\n\n sum_u = np.zeros(T)\n sum_cost = np.zeros(T)\n\n for k in range(T-1):\n y_mean[k+1] = y_mean[k] + x_mean[k+1] - x_mean[k] + L.dot(uv[k])\n y_q0975[k+1] = y_q0975[k] + x_q0975[k+1] - x_q0975[k] + L.dot(uv[k])\n y_q0025[k+1] = y_q0025[k] + x_q0025[k+1] - x_q0025[k] + L.dot(uv[k])\n sum_u[k+1] = np.sum(uv[k])\n sum_cost[k+1] = np.sum(w_pulp*uv[k])\n\n # ベット数の入力 \n df_severe_beds = pd.read_csv('data_Koro/severe_beds.csv',index_col=0)\n dirnames = (df_severe_beds['japan_prefecture_code']+df_severe_beds['都道府県名']).values\n names = df_severe_beds['都道府県名'].values\n\n weeks = df_severe_beds.columns[2:].values\n new_week = max(weeks)\n M = df_severe_beds[new_week].values\n times = pd.to_datetime(df_xmean.index)\n\n date_s = min(times)\n date_e = max(times)\n\n # ## 全県の重症者数の表示\n\n plt.figure(figsize = (6,4)) \n\n\n plt.fill_between(times,x_q0025.sum(axis=1),x_q0975.sum(axis=1),facecolor = 'lime',alpha = 0.3,label = '95%信頼区間')\n plt.plot(times,x_mean.sum(axis=1),'*-',color = 'lime',label = '平均値')\n\n plt.plot([date_s,date_e],np.ones(2)*0.8*M.sum(),\"--\",label = '重症病床使用率 80%',color = 'red',linewidth = 2.0)\n plt.plot([date_s,date_e],np.ones(2)*M.sum(),\"--\",label = '重症病床使用率 100%',color = 'purple',linewidth = 2.0)\n\n plt.gca().tick_params(axis='x', rotation= -60)\n plt.title('全国の重症者数の予測値, 予測日={0}'.format(forecast_date),fontsize = 15)\n plt.xlim([date_s,date_e])\n plt.ylim([0, 1.5* M.sum(),])\n plt.ylabel('重症者数 [人]')\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)\n plt.grid()\n\n plt.savefig('resultB_google_prediction/all_severe_{0}.png'.format(forecast_date),bbox_inches='tight',dpi = 100)\n if MODE == 'normal':\n plt.savefig('resultB_google_prediction/all_severe.png',bbox_inches='tight',dpi = 100)\n\n\n plt.close()\n\n\n\n # 県ごとの感染者数の予測結果\n plt.figure(figsize = (50,25)) \n plt.subplots_adjust(wspace=0.1, hspace=0.5)\n\n for i in range(47):\n plt.subplot(10,5,i+1)\n\n plt.fill_between(times,x_q0025[:,i],x_q0975[:,i],facecolor = 'lime',alpha = 0.3,label = '95%信頼区間')\n plt.plot(times,x_mean[:,i],'*-',color = 'lime',label = '平均値')\n\n plt.plot([date_s,date_e],np.ones(2)*0.8*M[i],\"--\",label = '重症病床使用率 80%',color = 'red',linewidth = 2.0)\n plt.plot([date_s,date_e],np.ones(2)*M[i],\"--\",label = '重症病床使用率 100%',color = 'purple',linewidth = 2.0)\n\n\n plt.gca().tick_params(axis='x', rotation= -60)\n plt.title(names[i],fontsize = 20)\n plt.xlim([date_s,date_e])\n plt.ylim([0, 5.0* M[i]])\n plt.grid()\n\n if i < 42:\n plt.tick_params(labelbottom=False)\n if i == 0:\n plt.legend()\n\n plt.savefig('resultB_google_prediction/each_severe_{0}.png'.format(forecast_date),bbox_inches='tight',dpi = 100)\n if MODE == 'normal':\n plt.savefig('resultB_google_prediction/each_severe.png',bbox_inches='tight',dpi = 100)\n plt.close()\n\n \n # 県ごとの感染者数の予測結果\n plt.figure(figsize = (50,25)) \n plt.subplots_adjust(wspace=0.1, hspace=0.5)\n for i in range(47):\n plt.subplot(10,5,i+1)\n\n max_beds = M[i]\n # ベットの限界\n plt.plot([date_s,date_e],[0.8*max_beds,0.8*max_beds],'--',label = '重症者病床使用率80%',color = 'red',linewidth = 2.0)\n plt.plot([date_s,date_e],[max_beds,max_beds],'--',label = '重症者病床使用率100%',color = 'purple',linewidth = 2.0)\n # 輸送なし\n plt.fill_between(times,x_q0025[:,i],x_q0975[:,i],facecolor = 'lime',alpha = 0.5,label = '医療シェアリングなし',) \n plt.plot(times,x_mean[:,i],\"*-\",linewidth = 2,color= 'lime')\n\n # 輸送あり\n plt.fill_between(times,y_q0025[:,i],y_q0975[:,i],facecolor = 'orange',alpha = 0.5,label = '医療シェアリングあり',) \n plt.plot(times,y_mean[:,i],\"*-\",linewidth = 2,color = 'orange')\n\n\n plt.xlim([date_s,date_e])\n plt.ylim([0,5.0*max_beds])\n plt.grid()\n plt.gca().tick_params(axis='x', rotation= -60)\n plt.title(names[i],fontsize = 20)\n if i < 42:\n plt.tick_params(labelbottom=False)\n if i == 0:\n plt.legend()\n\n\n if MODE == 'normal':\n plt.savefig('resultC_transport_strategy/main/each_severe_{0}_{1:03}.png'.format(x_type,int(gamma*100)),bbox_inches='tight',dpi = 100)\n plt.savefig('resultC_transport_strategy/main/each_severe_{0}_{1:03}_{2}.png'.format(x_type,int(gamma*100),forecast_date),bbox_inches='tight',dpi = 100)\n plt.close()\n\n # コスト評価\n\n times = pd.to_datetime(df_xmean.index)[:-1]\n\n date_s = min(times)\n date_e = max(times)\n max_beds = M.sum()\n\n # 輸送人数\n plt.plot(times,sum_u[:-1],\"*-\",linewidth = 2,color= 'black',label = '重症者受け入れ依頼数')\n\n plt.xlim([date_s,date_e])\n\n plt.gca().tick_params(axis='x', rotation= -60)\n # plt.title('',fontsize = 20)\n plt.ylabel('毎日の重症者の受け入れ依頼数 [人]')\n\n plt.legend()\n if MODE == 'normal':\n plt.savefig('resultC_transport_strategy/cost/num_{0}_{1:03}.png'.format(x_type,int(gamma*100)),bbox_inches='tight',dpi = 100)\n plt.savefig('resultC_transport_strategy/cost/num_{0}_{1:03}_{2}.png'.format(x_type,int(gamma*100),forecast_date),bbox_inches='tight',dpi = 100)\n plt.close()\n\n\n times = pd.to_datetime(df_xmean.index)[:-1]\n\n date_s = min(times)\n date_e = max(times)\n max_beds = M.sum()\n\n # 輸送コスト\n plt.plot(times,sum_cost[:-1],\"*-\",linewidth = 2,color= 'black',label = '医療シェアリングの依頼コスト')\n\n\n\n\n plt.xlim([date_s,date_e])\n\n plt.gca().tick_params(axis='x', rotation= -60)\n\n plt.legend()\n\n plt.ylabel('毎日の依頼コスト [km]')\n if MODE == 'normal':\n plt.savefig('resultC_transport_strategy/cost/cost_{0}_{1:03}.png'.format(x_type,int(gamma*100)),bbox_inches='tight',dpi = 100)\n plt.savefig('resultC_transport_strategy/cost/cost_{0}_{1:03}_{2}.png'.format(x_type,int(gamma*100),forecast_date),bbox_inches='tight',dpi = 100)\n plt.close()\n\n\n times = pd.to_datetime(df_xmean.index)[:-1]\n\n date_s = min(times)\n date_e = max(times)\n max_beds = M.sum()\n\n # 輸送コスト\n plt.plot(times,sum_cost[:-1]/sum_u[:-1],\"*-\",linewidth = 2,color= 'black',label = '重症者患者ごとの依頼コスト')\n\n plt.xlim([date_s,date_e])\n\n plt.gca().tick_params(axis='x', rotation= -60)\n plt.legend()\n\n plt.ylabel('重症者患者ごとのコスト [km/人]')\n\n if MODE == 'normal':\n plt.savefig('resultC_transport_strategy/cost/performance_{0}_{1:03}.png'.format(x_type,int(gamma*100)),bbox_inches='tight',dpi = 100)\n plt.savefig('resultC_transport_strategy/cost/performance_{0}_{1:03}_{2}.png'.format(x_type,int(gamma*100),forecast_date),bbox_inches='tight',dpi = 100)\n plt.close()\n\n\n times = pd.to_datetime(df_xmean.index)\n\n plt.plot(times,gammas*100)\n plt.gca().tick_params(axis='x', rotation= -60)\n plt.ylabel('重症病床利用率の上限 [%]')\n\n if MODE == 'normal':\n plt.savefig('resultC_transport_strategy/cost/gammas_{0}_{1:03}.png'.format(x_type,int(gamma*100)),bbox_inches='tight',dpi = 300)\n plt.savefig('resultC_transport_strategy/cost/gammas_{0}_{1:03}_{2}.png'.format(x_type,int(gamma*100),forecast_date),bbox_inches='tight',dpi = 300)\n plt.close()\n\n\n # 各県の搬送数\n U = uv.reshape(T,N,N)\n\n U_sum = np.zeros(U.shape)\n U_sum[0] = U[0]\n for i in range(U_sum.shape[0]-1):\n U_sum[i+1] = U_sum[i] + U[i+1]\n\n times_U = np.sum(U_sum>0,axis=0)\n\n\n for target in range(N):\n# if sum(U[:,target,:].sum(0)>0) >0:\n plt.figure(figsize = (10,6)) \n\n times = pd.to_datetime(df_xmean.index)[:-1]\n num_U=np.sum(times_U[target] !=0)\n index_U = np.argsort(times_U[target,:])[::-1]\n tmp_names = names[index_U[:num_U]]\n\n for i in range(tmp_names.shape[0]):\n out_target = U_sum[:-1,target,index_U[i]]\n plt.plot(times,out_target,'-*',label = tmp_names[i])\n\n plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0)\n plt.grid()\n plt.gca().tick_params(axis='x', rotation= -60)\n\n plt.ylabel('重症者の医療シェア数 [人]')\n plt.title(names[target]+'から他地域へのシェアリング')\n if MODE == 'normal':\n plt.savefig('resultC_transport_strategy/' + dirnames[target]+'/transport_{0}_{1:03}.png'.format(x_type,int(gamma*100)),bbox_inches='tight',dpi = 300)\n plt.savefig('resultC_transport_strategy/' + dirnames[target]+'/transport_{0}_{1:03}_{2}.png'.format(x_type,int(gamma*100),forecast_date),bbox_inches='tight',dpi = 300)\n plt.close()\n\n\n\n# 重傷者病床上限率の設定\ngamma_list = [0.8,1.0]\n# 使う条件の設定\nx_type_list = ['upper','mean','bottom']\n\nif MODE == 'all':\n for f_date in forecast_dates:\n for gamma in gamma_list:\n for x_type in x_type_list:\n visualization(gamma,x_type,f_date)\nelif MODE == 'normal':\n f_date = max(forecast_dates)\n for gamma in gamma_list:\n for x_type in x_type_list:\n visualization(gamma,x_type,f_date)\n\n\n\n","sub_path":"Visualization_Severe.py","file_name":"Visualization_Severe.py","file_ext":"py","file_size_in_byte":11135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"46765933","text":"\nfrom __future__ import division\nimport argparse\nimport pandas as pd\nimport time\nimport json\nfrom tqdm import tqdm\n# useful stuff\nimport numpy as np\nfrom scipy.special import expit\nfrom sklearn.preprocessing import normalize\n\n\n__authors__ = ['author1','author2','author3']\n__emails__ = ['fatherchristmoas@northpole.dk','toothfairy@blackforest.no','easterbunny@greenfield.de']\n\ndef text2sentences(path):\n\t# feel free to make a better tokenization/pre-processing\n\n\t\"\"\"\n\t:param path: path to the text files\n\t:return: list of all sentences\n\t\"\"\"\n\n\n\tsentences = []\n\twith open(path) as f:\n\t\tfor l in f:\n\t\t\tsentences.append( l.lower().split() )\n\treturn sentences\n\ndef loadPairs(path):\n\n\t\"\"\"\n\n\t:param path: path to the csv of word pairs\n\t:return: zip object of word pairs\n\t\"\"\"\n\n\n\tdata = pd.read_csv(path, delimiter='\\t')\n\tpairs = zip(data['word1'],data['word2'],data['similarity'])\n\treturn pairs\n\n\nclass SkipGram():\n\tdef __init__(self, sentences = 1 , nEmbed=30, negativeRate=0.0001, winSize = 5, winNegSize = 5, minCount = 30):\n\t\tif sentences != 1:\n\t\t\tself.valid_vocab, self.vocab_occ, self.eliminated_words = self.initialize_vocab(sentences, minCount)\n\t\t# set of valid words over the whole dataset, dict of their occurences, and set of all eliminated words\n\t\t\tself.w2id, self.id2w = self.word_id() # word to ID mapping\n\t\t\tself.trainset = self.filter_train_set(self.eliminated_words, sentences) # set of sentences\n\t\t\tself.neg_vocab_set, self.n_neg = self.build_neg_vocab(self.valid_vocab, self.vocab_occ, negativeRate)\n\t\t\tself.neg_distrib = self.build_neg_distrib(self.neg_vocab_set)\n\t\t\tself.nEmbed = nEmbed\n\t\t\tself.n_words = len(self.valid_vocab)# number of words that appear at list five times\n\n\t\t\tself.winSize = winSize # Window size\n\t\t\tself.winNegSize = winNegSize # Number of negative words per target vector\n\n\t\t#Weighs of the model\n\t\t#self.W = np.random.random((self.n_words, nEmbed))\n\t\t#self.Wp = np.random.random((nEmbed, self.n_words))\n\n\n\tdef initialize_vocab(self, sentences, minCount):\n\t\tall_words = [word for sentence in sentences for word in sentence] # list of all the words of all sentences\n\t\tall_words_unique = set(all_words)\n\t\tvocab_occ = {word:0 for word in all_words_unique}\n\t\tfor word in all_words:\n\t\t\tvocab_occ[word] += 1\n\t\tvalid_words_set = set(filter(lambda x: vocab_occ[x] > minCount, all_words_unique))\n\t\tinvalid_words_set = all_words_unique - valid_words_set\n\t\treturn valid_words_set, vocab_occ, invalid_words_set\n\n\tdef word_id(self):\n\t\t\"\"\"\n\t\t:param setntences: set of all words in the vocab, occ > minCount\n\t\t:return: dictionaries {word:id} and {id:word}\n\t\t\"\"\"\n\t\treturn {word:q for q, word in enumerate(self.valid_vocab)}, \\\n\t\t\t {q:word for q, word in enumerate(self.valid_vocab)}\n\n\tdef filter_train_set(self, invalid_vocab, sentences):\n\t\t\"\"\"\n\n\t\t:param invalid_vocab: all words that must be extracted from the dataset\n\t\t:param sentences: list of sentences that constitute the dataset\n\t\t:return: sentences where all the invalid vocab has been deleted\n\t\t\"\"\"\n\t\tfor q, sentence in enumerate(sentences):\n\t\t\tto_del = []\n\t\t\tfor p, word in enumerate(sentence):\n\t\t\t\tif word in invalid_vocab:\n\t\t\t\t\tto_del.append(p)\n\t\t\tfor p in to_del[::-1]: # reverse index to be able to use del\n\t\t\t\tdel sentences[q][p]\n\n\t\treturn sentences\n\n\tdef build_neg_vocab(self, vocab, vocab_occ, neg_treshold):\n\t\t\"\"\"\n\n\t\t:param vocab: all the word that will be in the train set and occur at least minCount times\n\t\t:param vocab_occ: dict where {valid word : number of occurences}\n\t\t:param neg_treshold: maximum time a word can occur to be qualified for the negative words set\n\t\t:return:\n\t\t\"\"\"\n\n\t\tn = np.sum(vocab_occ[word] for word in vocab)\n\t\tvocab_freq = {word:vocab_occ[word]/n for word in vocab}\n\t\tneg_vocab = list(filter(lambda x:vocab_freq[x] < neg_treshold, vocab))\n\t\tneg_vocab_set = set(neg_vocab)\n\t\tn_neg = len(neg_vocab)\n\n\t\treturn neg_vocab_set, n_neg\n\n\tdef build_neg_distrib(self, neg_vocab, distrib=None):\n\n\t\tif distrib == None:\n\t\t\treturn self.build_neg_distrib_basic(neg_vocab)\n\n\t\telse:\n\t\t\treturn distrib(neg_vocab)\n\n\tdef build_neg_distrib_basic(self, neg_vocab):\n\n\t\t\"\"\"\n\t\tTODO : We might need to add a transformation to the distribution of the negative words\n\t\tsee http://mccormickml.com/2017/01/11/word2vec-tutorial-part-2-negative-sampling/ > SELECTING NEGATIVE SAMPLE\n\n\n\t\t:param neg_vocab: list of all the words that qualify for the negative vocabulary\n\t\t:return: a dictionary with the frequency of each word of the negative vocabulary\n\t\t\"\"\"\n\t\tn = np.sum(self.vocab_occ[word] for word in neg_vocab)\n\t\tdistr = {neg_w : self.vocab_occ[neg_w]/n for neg_w in neg_vocab}\n\n\t\treturn distr\n\n\n\tdef transform_34(self, neg_vocab):\n\n\t\tn = np.sum(self.vocab_occ[word] for word in neg_vocab)\n\t\tdistr = {neg_w: (self.vocab_occ[neg_w] / n) ** 0.75 for neg_w in neg_vocab}\n\t\tnormalisationFactor = np.sum(distr.values())\n\n\t\tdistrNormalised = {neg_w : distr[neg_w] / normalisationFactor for neg_w in neg_vocab}\n\n\t\treturn distrNormalised\n\n\n\tdef parse_sentence_for_context(self, sentence, K):\n\t\t\"\"\"\n\t\tthe windSize is defined at the initialisation of the class\n\n\t\t:param K: int, size of the context window\n\t\t:param sentence: str,\n\t\t:return: list of center words list(str), and a list with their corresponding context (list(list(str))\n\n\t\t\"\"\"\n\t\tcenter_words = []\n\t\tcontexts = []\n\t\tfor k, word in enumerate(sentence):\n\t\t\tkp = np.random.randint(1, K+1)\n\t\t\tcontext_before = sentence[k-kp:k]\n\t\t\tcontext_after = sentence[k+1:k+1+kp]\n\t\t\tcontexts.append(context_before + context_after)\n\t\t\tcenter_words.append(word)\n\t\treturn center_words, contexts\n\n\n\tdef select_negative_sampling(self, neg_distribution, K):\n\t\t\"\"\"\n\n\t\t:param neg_vocab: set of the negative vocab\n\t\t:param neg_distribution: {neg_word : sample rate}\n\t\t:return: returns K negative words\n\t\t\"\"\"\n\n\t\treturn [np.random.choice(list(neg_distribution.keys()), p = list(neg_distribution.values())) for x in range(K)]\n\n\tdef oneHot(self, dim, id):\n\t\toh = np.zeros(dim, int)\n\t\toh[id] = 1\n\t\treturn oh\n\n\n\tdef forward(self, center_word, target_context_word, neg_words):\n\n\t\t\"\"\"\n\n\t\t:param self:\n\t\t:param center_word: word of the center context to evaluate\n\t\t:param target_context_word: one word of the context\n\t\t:param neg_words: list of negative words\n\t\t:return: loss function and intermediate gradients\n\t\t\"\"\"\n\t\th = self.W[self.w2id[center_word], :] \t# output of the first layer for center_word\n\n\t\thc = self.Wp[:, self.w2id[target_context_word]]\n\n\t\th2_neg = []\n\n\t\tfor neg_word in neg_words:\n\t\t\th2_neg.append((self.Wp[:, self.w2id[neg_word]]))\n\n\t\tloss_pos = -np.log(expit(hc.T @ h))\n\t\tloss_neg = - np.sum(np.log(expit(-h2_n.T @ h)) for h2_n in h2_neg)\n\t\tloss = loss_pos + loss_neg\n\n\n\t\tgradsWp = np.zeros(self.Wp.shape)\n\n\t\tfor q, w in enumerate(neg_words):\n\t\t\tgradsWp[:, self.w2id[w]] = expit(h.T @ h2_neg[q]) * h\n\n\t\tgradsWp[:, self.w2id[target_context_word]] = (expit(h.T @ hc) - 1) * h\n\n\n\t\tgradW = np.zeros(self.W.shape)\n\n\t\tgradW[self.w2id[center_word], :] = (expit(h.T @ hc) - 1) * hc + np.sum(expit(h.T @ h2_n) * h2_n for h2_n in h2_neg)\n\n\n\t\treturn loss, gradW, gradsWp, loss_pos, loss_neg\n\n\tdef backward(self, lr, gradW, gradsWp):\n\n\t\tself.W -= lr* gradW\n\t\tself.Wp -= lr*gradsWp\n\n\n\tdef train(self, epochs, lr):\n\n\n\t\tself.W = np.random.uniform(-0.5, 0.5, size = self.n_words * self.nEmbed).reshape(self.n_words, self.nEmbed)\n\t\tself.Wp = np.random.uniform(-0.5, 0.5, size = self.nEmbed * self.n_words).reshape(self.nEmbed, self.n_words)\n\n\t\tprint(\"Similarity of Monday / Tuesday : {}\".format(self.similarity(\"monday\", \"tuesday\")))\n\t\tprint(\"Similarity of Monday / financial : {}\".format(self.similarity(\"monday\", \"financial\")))\n\n\t\tfor epoch in range(epochs):\n\n\t\t\tprint(\"epoch {}\".format(epoch))\n\n\t\t\tself.accloss = 0\n\t\t\tself.loss_pos = 0\n\t\t\tself.loss_neg = 0\n\n\t\t\tself.counter =0\n\n\t\t\tfor counter, sentence in tqdm(enumerate(self.trainset)):\n\n\n\t\t\t\t# sentence = filter(lambda word: word in self.vocab, sentence)\n\t\t\t\t# Already implemented during the initialisation of the class\n\n\t\t\t\tsentence_words, sentence_contexts = self.parse_sentence_for_context(sentence, self.winSize)\n\n\t\t\t\tfor q, context in enumerate(sentence_contexts):\n\n\t\t\t\t\tfor context_word in context:\n\t\t\t\t\t\tword = sentence_words[q] # Center word of the q-th sentence\n\t\t\t\t\t\trandomWinSize = len(context)\n\t\t\t\t\t\tneg_words = self.select_negative_sampling(self.neg_distrib, randomWinSize)\n\t\t\t\t\t\tif context_word == word: continue\n\n\t\t\t\t\t\tloss, gradW, gradsWp, loss_pos, loss_neg = self.forward(word, context_word, neg_words)\n\n\t\t\t\t\t\tself.accloss += loss\n\t\t\t\t\t\tself.loss_pos += loss_pos\n\t\t\t\t\t\tself.loss_neg += loss_neg\n\t\t\t\t\t\tself.counter += 1\n\n\t\t\t\t\t\tself.backward(lr, gradW, gradsWp)\n\n\n\t\t\tif counter % 1000 == 0:\n\t\t\t\tprint(\"Loss : {}\".format(self.accloss/self.counter))\n\t\t\t\tprint(\"Loss_pos : {}\".format(self.loss_pos / self.counter))\n\t\t\t\tprint(\"Loss_neg : {}\".format(self.loss_neg / self.counter))\n\t\t\t\tprint(\"Similarity of Monday / Tuesday : {}\".format(self.similarity(\"monday\", \"tuesday\")))\n\t\t\t\tprint(\"Similarity of Monday / financial : {}\".format(self.similarity(\"monday\", \"financial\")))\n\n\n\n\n\n\tdef save(self,path):\n\t\t\"\"\"\n\n\t\t:param self:\n\t\t:param path: path to which the model is to be saved\n\t\t:return: None, saves the model's weighs to path\n\t\t\"\"\"\n\n\n\n\t\twith open('w2id.json', 'w') as fp:\n\t\t\tjson.dump(self.w2id, fp)\n\n\t\t# Save\n\t\tnp.save(path + 'W.npy', self.W)\n\t\tnp.save(path + 'Wp.npy', self.Wp)\n\n\n\n\tdef load(self, path):\n\t\t\"\"\"\n\n\t\t:param self:\n\t\t:param path: path to the model\n\t\t:return: None, initiates the model with all the weighs saved previously\n\t\t\"\"\"\n\t\tself.W = np.load(path + 'W.npy')\n\t\tself.Wp = np.load(path + 'Wp.npy')\n\n\t\twith open('w2id.json', 'r') as fp:\n\t\t\tself.w2id = json.load(fp)\n\n\tdef similarity(self,word1,word2):\n\t\t\"\"\"\n\t\t\tcomputes similiarity between the two words. unknown words are mapped to one common vector\n\t\t:param word1:\n\t\t:param word2:\n\t\t:return: a float \\in [0,1] indicating the similarity (the higher the more similar)\n\t\t\"\"\"\n\t\ta, b = self.w2id[word1], self.w2id[word2]\n\t\te1, e2 = self.W[a,:], self.W[b,:]\n\n\t\treturn e1.T @ e2 / (np.linalg.norm(e1) * np.linalg.norm(e2))\n\n\n\nif __name__ == '__main__':\n\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('--text', help='path containing training data', required=True)\n\tparser.add_argument('--model', help='path to store/read model (when training/testing)', required=True)\n\tparser.add_argument('--test', help='enters test mode', action='store_true')\n\n\topts = parser.parse_args()\n\n\tif not opts.test:\n\t\tsentences = text2sentences(opts.text)\n\t\tsg = SkipGram(sentences)\n\t\tsg.train()\n\t\tsg.save(opts.model)\n\n\telse:\n\t\tpairs = loadPairs(opts.text)\n\n\t\tsg = SkipGram.load(opts.model)\n\t\tfor a,b,_ in pairs:\n\t\t\t# make sure this does not raise any exception, even if a or b are not in sg.vocab\n\t\t\tprint(sg.similarity(a,b))\n\n","sub_path":"skipGram.py","file_name":"skipGram.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"570953642","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# __author__:JasonLIN\r\n\r\nimport configparser\r\nfrom atm.bank.conf import settings\r\nconfig = configparser.ConfigParser()\r\nuser_path = settings.USER_PATH\r\nconfig.read(user_path)\r\ntrans_dic = settings.TRANSACTION_TYPE\r\n\r\n\r\ndef transaction(user, func, amount):\r\n \"\"\"交易处理函数\"\"\"\r\n amount = float(amount)\r\n trans_type = trans_dic[func][\"action\"]\r\n interest_rates = trans_dic[func][\"interest\"]\r\n interest = float(interest_rates) * amount\r\n balance = float(config.get(user, \"balance\"))\r\n try:\r\n if trans_type == \"+\":\r\n new_balance = balance + amount + interest\r\n elif trans_type == \"-\":\r\n if balance > amount:\r\n new_balance = balance - amount - interest\r\n else:\r\n print(\"\\033[31;1m余额不足,只剩[%d]\\033[0m\" % balance)\r\n return\r\n else:\r\n return\r\n config.set(user, \"balance\", str(new_balance))\r\n config.write(open(user_path, 'w'))\r\n return new_balance\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\n ","sub_path":"atm/bank/core/trans.py","file_name":"trans.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"540843553","text":"import numpy as np\nfrom plotClass import plotCLASS\nfrom plotParams import pltParams\n\nparams = pltParams()\n\nplc = plotCLASS()\n\nselectTimes = [1.8, 2.8, 4.5, 6]\n\ntimes = np.fromfile(\"../data/timeDelays[72].dat\", np.double)\n\ntimeInds = np.searchsorted(times, selectTimes)\ntimeInds[timeInds>=times.shape[0]-1] = -1\nprint(timeInds)\n\ndiffOpts = {\n \"labels\" : [str(tm) for tm in selectTimes],\n \"xLabel\" : r\"Q [$\\AA^{-1}$]\",\n \"ySlice\" : [-5, 5]\n }\n\npcorOpts = {\n \"labels\" : [str(tm) for tm in selectTimes],\n \"xLabel\" : r\"R [$\\AA$]\"\n }\nphnoxyOpts = {\n \"labels\" : [\"Phenoxy Simulation\", \"Data\"],\n \"ySlice\" : [-6,6],\n }\nphnylOpts = {\n \"labels\" : [\"Phenyl Simulation\", \"Data\"],\n \"ySlice\" : [-6,6],\n }\nfor std in [\"0.750000\"]: #smearSTD:\n\n files = [\"../data/sim_phenoxyRadicalDiffractionDiff[\" \n + params.NradBins + \"].dat\",\n \"../data/data_sMsFinalL0DiffSmear\"\n + std + \"[\" + params.NradBins + \"].dat\"]\n plc.print1d(files, \"../compare_phenoxysMsFinalDiff\",\n xRange=params.Qrange,\n normalize=True,\n options=phnoxyOpts)\n\n files = [\"../data/sim_phenylRadicalDiffractionDiff[\" \n + params.NradBins + \"].dat\",\n \"../data/data_sMsFinalL0DiffSmear\"\n + std + \"[\" + params.NradBins + \"].dat\"]\n plc.print1d(files, \"../compare_phenylsMsFinalDiff\",\n xRange=params.Qrange,\n normalize=True,\n options=phnylOpts)\n\n files = [\"../data/sim_phenoxyRadicalPairCorrDiff[\" \n + params.NpairCorrBins1 + \"].dat\",\n \"../data/data_pairCorrFinalDiffSmear\"\n + std + \"[\" + params.NpairCorrBins + \"].dat\"]\n plc.print1d(files, \"../compare_phenoxyPairCorrFinalDiff\",\n xRange=params.Rrange,\n normalize=True,\n options=phnoxyOpts)\n\n files = [\"../data/sim_phenylRadicalPairCorrDiff[\" \n + params.NpairCorrBins1 + \"].dat\",\n \"../data/data_pairCorrFinalDiffSmear\"\n + std + \"[\" + params.NpairCorrBins + \"].dat\"]\n plc.print1d(files, \"../compare_phenylPairCorrFinalDiff\",\n xRange=params.Rrange,\n normalize=True,\n options=phnylOpts)\n\n fileName = \"../data/data_sMsL0DiffSmear\" + std\\\n + \"[\" + params.NtimeSteps + \",\" + params.NradBins + \"].dat\"\n plc.printLineOut(fileName, 0, timeInds, \"../data_comparesMsLOSmear\" + std +\"\", \n xRange=params.Qrange, options=diffOpts)\n \n fileName = \"../data/data_pairCorrDiffSmear\" + std\\\n + \"[\" + params.NtimeSteps + \",\" + params.NpairCorrBins + \"].dat\" \n plc.printLineOut(fileName, 0, timeInds, \"../data_comparePairCorrLOSmear\" + std +\"\", \n xRange=params.Rrange, options=pcorOpts)\n","sub_path":"UED/timeDepStudies/plots/scripts/compareLO.py","file_name":"compareLO.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"52068478","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n# Author\n\nNelson Brochado (nelson.brochado@usi.ch)\n\n# Description\n\nThis module provides a function which estimates the hinge joint axis (i.e. hinge_axes),\nwhich we can also call directional vector of a hinge joint,\nwith respect to two inertial sensors attached to the links connected to the hinge joint.\n\n# References\n\n1. T. Seel, T. Schauer, J. Raisch.\nJoint Axis and Position Estimation from Inertial Measurement Data by Exploiting Kinematic Constraints.\nIn IEEE Multi-Conference on Systems and Control, pages 45–49, Dubrovnik, Croatia, 2012.\n\n2. T. Seel, T. Schauer, J. Raisch.\nIMU-Based Joint Angle Measurement for Gait Analysis.\nSensors, 14 (4):6891–6909, 2014.\n\n3. T. Seel\nLearning Control and Inertial Realtime Gait Analysis in Biomedical Applications:\nImproving Diagnosis and Treatment by Automatic Adaption and Feedback Control\nTechnischen Universität Berlin, 2016\n\n# Notes\n\n- For more details regarding this module, have a look at Nelson Brochado's bachelor project report and the references above.\n- No optimization to the algorithms below has been performed so far.\n\"\"\"\n\nimport numpy as np\nimport numpy.linalg as la\nfrom math import cos, sin, pi\nfrom random import uniform\n\nfrom coiwhri.util import not_parallel\n\n__all__ = [\"hinge_axes\", \"hinge_plane_axes\"]\n\n\ndef _x0():\n \"\"\"Returns a numpy array with shape (4,) of random angles in radians\n\n x := [ϕ₁, Θ₁, ϕ₂, Θ₂]\n\n where ϕ₁, ϕ₂ ∈ [-π/2, π/2] and Θ₁, Θ₂ ∈ [0, 2π).\n\n See Thomas Seel PhD thesis.\n\n Note: in the method uniform, the last value may or not be included:\n https://docs.python.org/2.7/library/random.html#random.uniform\"\"\"\n return np.array([uniform(-pi / 2, pi / 2), uniform(0, 2 * pi), uniform(-pi / 2, pi / 2), uniform(0, 2 * pi)])\n\n\ndef _spherical_coordinates(phi, theta):\n \"\"\"Returns a numpy array with shape (4,) representing the spherical coordinates\n of the hinge joint axis j, given the angles phi (inclination) and theta (azimuth).\n\n In a right-handed coordinate system where x, y and z are unit-length axis,\n and they are respectively the index, middle and thumb fingers,\n the inclination is the angle between j and its projection on the xy plane,\n whereas the azimuth is the angle between the x axis\n and the projection of j onto the xy plane.\n\n Assumes angles are given in radians.\"\"\"\n return np.array([cos(phi) * cos(theta), cos(phi) * sin(theta), sin(phi)])\n\n\ndef _j1_wrt_x(x):\n \"\"\"Given a numpy array with shape (4,), it calculates the Jacobian of\n\n j₁ = [cos(ϕ₁)cos(Θ₁), cos(ϕ₁)sin(Θ₁), sin(ϕ₁)]\n\n with respect to x := [ϕ₁, Θ₁, ϕ₂, Θ₂].\n\n Note that j₁ is only defined in terms of x[0] := ϕ₁ and x[1] := Θ₁.\"\"\"\n return np.array([[-sin(x[0]) * cos(x[1]), -cos(x[0]) * sin(x[1]), 0, 0],\n [-sin(x[0]) * sin(x[1]), cos(x[0]) * cos(x[1]), 0, 0],\n [cos(x[0]), 0, 0, 0]])\n\n\ndef _j2_wrt_x(x):\n \"\"\"Does a similar thing to _j1_wrt_x but for j2.\"\"\"\n return np.array([[0, 0, -sin(x[2]) * cos(x[3]), -cos(x[2]) * sin(x[3])],\n [0, 0, -sin(x[2]) * sin(x[3]), cos(x[2]) * cos(x[3])],\n [0, 0, cos(x[2]), 0]])\n\n\ndef _e_wrt_j(g, j):\n \"\"\"Returns the derivative (derived algebraically) of the constraint function\n\n e(t) := ||g₁(t) × j₁|| − ||g₂(t) × j₂||\n\n with respect to j, where j can be either j₁ or j₂,\n and consequently g must respectively be g₁(t) or g₂(t), for some point in time t.\n\n The previously mentioned algebraically derived gradient looks as follows:\n\n ∇e(t) := ((g × j) × g) / ||g × j||\n\n j and g must be numpy arrays with shape (3,).\"\"\"\n assert g.shape == j.shape == (3,)\n gxj = np.cross(g, j)\n return np.true_divide(np.cross(gxj, g), la.norm(gxj))\n\n\ndef _jacobian_row(x, g1, j1, g2, j2):\n \"\"\"Returns numpy array with shape (4,) representing the row of the Jacobian matrix of the function\n\n e(x) := ||g₁(t) × j₁|| − ||g₂(t) × j₂||, for t = 1..k and k >> 4\n\n where x := [ϕ₁, Θ₁, ϕ₂, Θ₂] and t is a point in time,\n corresponding to the numpy arrays g1, j1, g2 and j2 with shape (3,).\"\"\"\n assert x.shape == (4,)\n\n d1 = _e_wrt_j(g1, j1)\n d2 = _e_wrt_j(g2, j2)\n\n return np.dot(d1, _j1_wrt_x(x)) - np.dot(d2, _j2_wrt_x(x))\n\n\ndef _jacobian(x, g1s, j1, g2s, j2):\n \"\"\"Given numpy arrays g1s and g2s with shape (k,3) representing the k 3D angular velocities,\n obtained respectively from the first and second gyroscopes,\n and the numpy array with shape (3,) representing the current joint axis estimations j1 and j2,\n for respectively the first and second sensors,\n it returns the Jacobian matrix of the following function:\n\n e(x) := ||g₁(t) × j₁|| − ||g₂(t) × j₂||,\n\n for t = 1..k and k >> 4, with respect to the 1x4 matrix\n\n x := [ϕ₁, Θ₁, ϕ₂, Θ₂].\n\n The Jacobian matrix returned is a numpy array with shape (k,4).\"\"\"\n assert all(x.shape[0] > 4 and x.shape[1] == 3 for x in (g1s, g2s))\n assert g1s.shape[0] == g2s.shape[0]\n\n k = g1s.shape[0]\n j = np.empty((k, 4))\n for t in range(k):\n # Calculate the row t of the Jacobian matrix of the error function with respect to input x.\n j[t] = _jacobian_row(x, g1s[t], j1, g2s[t], j2)\n return j\n\n\ndef _hinge_constraint(g1, j1, g2, j2):\n \"\"\"Returns the following difference ||g₁(t) × j₁|| − ||g₂(t) × j₂||,\n which \"should\" be equal to 0, ∀t, where t is a point in time,\n in case that difference represents the hinge joint constraints.\n ||g₁(t) × j₁|| − ||g₂(t) × j₂|| represents the fact that,\n for each time t, the projections of g₁(t) and g₂(t)\n respectively on the first and second hinge joint planes,\n (i.e. the 2D joint planes which are perpendicular to respectively j₁ and j₂)\n have the same length.\n\n g1 and g2 are numpy arrays with shape (3,) representing the angular velocities\n provided respectively by the first and the second gyroscopes.\n\n j1 and j2 are the current estimates (as numpy arrays)\n of the spherical coordinates of the joint axis,\n seen from the local coordinate systems of respectively the first and second sensors.\"\"\"\n assert g1.shape == g2.shape == j1.shape == j2.shape == (3,)\n return la.norm(np.cross(g1, j1)) - la.norm(np.cross(g2, j2))\n\n\ndef _hinge_error(g1s, j1, g2s, j2):\n \"\"\"Returns a numpy array with shape (k,1) calculated from:\n\n e(x) := ||g₁(t) × j₁|| − ||g₂(t) × j₂||, for t = 1..k and k >> 4.\n\n g1s and g2s are numpy arrays with shape (k,3) representing k 3D angular velocities.\n j1 and j2 are numpy arrays with shape (3,) representing the current joint axis estimations.\n\n This is essentially the error vector (of the kinematic constraints).\"\"\"\n assert all(x.shape[0] > 4 and x.shape[1] == 3 for x in (g1s, g2s))\n assert g1s.shape[0] == g2s.shape[0]\n assert j1.shape == j2.shape == (3,)\n\n k = g1s.shape[0]\n r = np.empty((k, 1))\n for t in range(k):\n # Calculating the t row of the error vector r\n r[t] = _hinge_constraint(g1s[t], j1, g2s[t], j2)\n return r\n\n\ndef _correct_signs(j1, j2, axes_alignment=(0, 0, 0)):\n \"\"\"See Seel's PhD thesis (p. 61) for a way to correct the signs of the estimates.\n This is \"just\" a manual method to correct the signs of the estimates,\n and it depends on how the sensors are placed.\n Hence to call this procedure the client should roughly know how the sensors are oriented.\n\n In that document, it's explained that if the z-axis\n of both j1 and j2 point roughly in the same direction,\n then the z-coordinates of both j1 and j2 should have the same sign.\n If instead, to give another example, the local y-axis of the first sensor\n points roughly to the opposite direction of the z-axis of the second sensor,\n then the y-coordinate of j1 and the z-coordinate of j2 have different signs.\n\n Two axes can be both positive, both negative,\n the first can be negative and the second positive, or vice-versa.\"\"\"\n assert all(isinstance(x, int) for x in axes_alignment)\n\n def correct(alignment, i):\n if alignment == 0: # Both positive\n if j1[i] < 0:\n j1[i] *= -1\n if j2[i] < 0:\n j2[i] *= -1\n elif alignment > 0: # Both negative\n if j1[i] > 0:\n j1[i] *= -1\n if j2[i] > 0:\n j2[i] *= -1\n elif alignment == -1: # First is negative and second is positive\n if j1[i] > 0:\n j1[i] *= -1\n if j2[i] < 0:\n j2[i] *= -1\n else: # First is positive and second is negative\n if j1[i] < 0:\n j1[i] *= -1\n if j2[i] > 0:\n j2[i] *= -1\n\n for i, alignment in enumerate(axes_alignment):\n correct(alignment, i)\n\n\ndef hinge_axes(g1s, g2s, n=20, abs_tol=1e-4, rel_tol=1e-12, correct_signs=True, axes_alignment=(0, 0, 0)):\n \"\"\"Given numpy arrays g1s and g2s with shape (k,3),\n whose rows represent the 3D angular velocities,\n which should be given in coordinates of the local frames of the IMUs,\n it returns an estimation of the angles of the hinge joint axis,\n as a numpy array with shape (4,):\n\n x := [ϕ₁, Θ₁, ϕ₂, Θ₂]\n\n The numerical iterative algorithm (Guass-Newton) goes as follows:\n\n x = [ϕ₁, Θ₁, ϕ₂, Θ₂] # generate randomly the initial x\n for i from 1 to n\n j₁ = [cos(ϕ₁)cos(Θ₁), cos(ϕ₁)sin(Θ₁), sin(ϕ₁)]\n j₂ = [cos(ϕ₂)cos(Θ₂), cos(ϕ₂)sin(Θ₂), sin(ϕ₂)]\n calculate e(x) := ||g₁(t) × j₁|| − ||g₂(t) × j₂||, for t = 1..N\n calculate the Jacobian of e(x): J(e)\n calculate Moore-Penrose pseudoinverse of J(e) as: MP(J(e))\n update x as: x = x - MP(J(e)) * e(x)\n\n n is the maximum number of iterations to perform.\n According to the paper seel2012 about 20 iterations should be sufficient\n for the algorithm to converge to the right solution.\n\n abs_tol and rel_tol are also used to check if the algorithm has converged.\n If the following is true, where a and b are two successive iterates\n\n |a - b| <= (abs_tol + rel_tol * |b|)\n\n then the convergence condition is reached.\n\n If either the maximum number of iterations is reached\n or |a - b| <= (abs_tol + rel_tol * |b|) is true, the algorithm stops.\n\n Solving the least-squares problem defined above yield two estimates j1 and j2\n of the local joint axis coordinates that are approximately equal to the true coordinates,\n lets call them h1 and h2 (for hinge 1 and hinge 2),\n i.e. after having found the estimates j1 and j2 we either have that\n (j1, j2) ~ (h1, h2), (-j1, j2) ~ (h1, h2), (j1, -j2) ~ (h1, h2) or (-j1, -j2) ~ (h1, h2),\n that is one of the 4 combinations of signs of j1 and j2 is the correct estimation for h1 and h2.\n\n Weather the signs of the obtained estimates match\n is important for other calculations such as the hinge joint angle estimation.\n\n The elements of the tuple axes_alignment are used to correct the signs of the estimates.\n If axes_alignment[0] == 0, x1 and x2 are both positive.\n If axes_alignment[0] > 0, x1 and x2 are both negative.\n If axes_alignment[0] == -1, x1 is negative and x2 is positive.\n If axes_alignment[0] < -1, x1 is positive and x2 is negative.\n This works similarly for the other axes,\n where axes_alignment[1] is used to correct y1 and y2,\n and axes_alignment[2] is used to correct z1 and z2.\n This method assumes that the client of this function\n knows roughly how all axes are positioned and directed.\"\"\"\n assert all(x.shape[0] > 4 and x.shape[1] == 3 for x in (g1s, g2s))\n assert g1s.shape[0] == g2s.shape[0]\n\n x = _x0()\n\n for _ in range(n):\n j1 = _spherical_coordinates(x[0], x[1])\n j2 = _spherical_coordinates(x[2], x[3])\n\n j = _jacobian(x, g1s, j1, g2s, j2)\n p = la.pinv(j)\n e = _hinge_error(g1s, j1, g2s, j2)\n\n x_new = x - np.dot(p, e)[:, 0]\n\n if np.allclose(x, x_new, atol=abs_tol, rtol=rel_tol):\n x = x_new\n break\n\n x = x_new\n\n j1 = _spherical_coordinates(x[0], x[1])\n j2 = _spherical_coordinates(x[2], x[3])\n\n if correct_signs:\n _correct_signs(j1, j2, axes_alignment)\n\n return x, j1, j2\n\n\ndef hinge_plane_axes(j1, j2):\n \"\"\"Returns a tuple of size two containing tuples of size two.\n \n The first element of each sub-tuple is a vector \n representing the x-axis of the hinge joint plane,\n whereas the second element is a vector \n representing the y-axis of the same hinge joint plane.\n \n The first tuple represents the vectors of the hinge joint plane for j1,\n and the second tuple represents the vectors of the hinge joint plane for j2.\"\"\"\n c = not_parallel(j1, j2)\n\n # Coordinate axis of the hinge joint plane as seen from first sensor.\n # Note that x1 and y1 are perpendicular to j1,\n # that's why x1 and y1 form coordinate axes of the hinge joint plane.\n x1 = np.cross(j1, c)\n y1 = np.cross(j1, x1)\n\n # Coordinate axis of the hinge joint plane as seen from second sensor\n x2 = np.cross(j2, c)\n y2 = np.cross(j2, x2)\n\n return (x1, y1), (x2, y2)\n","sub_path":"src/coiwhri/joint_estimation.py","file_name":"joint_estimation.py","file_ext":"py","file_size_in_byte":13440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"487192175","text":"import os\n\nimport numpy as np\n\ndef load_embeddings(path, size, dimensions):\n\n embedding_matrix = np.zeros((size, dimensions), dtype=np.float32)\n\n # As embedding matrix could be quite big we 'stream' it into output file\n # chunk by chunk. One chunk shape could be [size // 10, dimensions].\n # So to load whole matrix we read the file until it's exhausted.\n size = os.stat(path).st_size\n with open(path, 'rb') as ifile:\n pos = 0\n idx = 0\n while pos < size:\n chunk = np.load(ifile)\n chunk_size = chunk.shape[0]\n embedding_matrix[idx:idx + chunk_size, :] = chunk\n idx += chunk_size\n pos = ifile.tell()\n return embedding_matrix[1:]\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"588355954","text":"# Copyright 2019, Hudson and Thames Quantitative Research\r\n# All rights reserved\r\n# Read more: https://github.com/hudson-and-thames/mlfinlab/blob/master/LICENSE.txt\r\n\r\n\"\"\"\r\nLabeling Raw Returns.\r\n\r\nMost basic form of labeling based on raw return of each observation relative to its previous value.\r\n\"\"\"\r\n\r\nimport numpy as np\r\n\r\nfrom mlfinlab.util import devadarsh\r\n\r\n\r\ndef raw_return(prices, binary=False, logarithmic=False, resample_by=None, lag=True):\r\n \"\"\"\r\n Raw returns labeling method.\r\n\r\n This is the most basic and ubiquitous labeling method used as a precursor to almost any kind of financial data\r\n analysis or machine learning. User can specify simple or logarithmic returns, numerical or binary labels, a\r\n resample period, and whether returns are lagged to be forward looking.\r\n\r\n :param prices: (pd.Series/pd.DataFrame) Time-indexed price data on stocks with which to calculate return.\r\n :param binary: (bool) If False, will return numerical returns. If True, will return the sign of the raw return.\r\n :param logarithmic: (bool) If False, will calculate simple returns. If True, will calculate logarithmic returns.\r\n :param resample_by: (str) If not None, the resampling period for price data prior to calculating returns. 'B' = per\r\n business day, 'W' = week, 'M' = month, etc. Will take the last observation for each period.\r\n For full details see `here.\r\n `_\r\n :param lag: (bool) If True, returns will be lagged to make them forward-looking.\r\n :return: (pd.Series/pd.DataFrame) Raw returns on market data. User can specify whether returns will be based on\r\n simple or logarithmic return, and whether the output will be numerical or categorical.\r\n \"\"\"\r\n\r\n devadarsh.track('labeling_raw_return')\r\n\r\n # Apply resample, if applicable\r\n if resample_by is not None:\r\n prices = prices.resample(resample_by).last()\r\n\r\n # Get return per period\r\n if logarithmic: # Log returns\r\n if lag:\r\n returns = np.log(prices).diff().shift(-1)\r\n else:\r\n returns = np.log(prices).diff()\r\n else: # Simple returns\r\n if lag:\r\n returns = prices.pct_change(periods=1).shift(-1)\r\n else:\r\n returns = prices.pct_change(periods=1)\r\n\r\n # Return sign only if categorical labels desired.\r\n if binary:\r\n returns = returns.apply(np.sign)\r\n\r\n return returns\r\n","sub_path":"src/collection/mlfinlab/labeling/raw_return.py","file_name":"raw_return.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"149622424","text":"# -*- coding: utf-8 -*-\n\nfrom gensim import corpora, models\nimport collections\nimport topics\nimport sys\nimport json\n\ndef compute_profiles(topic_ids, features, weights, preprocess_fn, stopwords,\n update, path, alpha=0.7, smartirs='atn'):\n\n '''\n Computes topic profiles\n Args:\n topic_ids: list of topic id's to compute keyword profiles for \n features: attributes to include in importance evaluation\n weights: weights associated with attributes in features\n preprocess_fn: function to preprocess original text \n stopwords: set of stopwords\n update: flag indicating whether this is an update operation\n path: file path for loading and saving\n alpha: contribution coefficient for the topic content \n smartirs: tf-idf weighting variants\n\n Returns:\n Topics profiles in the form of word weight dictionaries\n '''\n if update:\n print('Updating word weights for active topics...')\n with open(path, 'r') as f:\n profiles = json.load(f)\n else:\n print('Computing word weights for all topics...')\n profiles = {}\n\n for topic_id in topic_ids:\n # create a Topic object for each topic\n topic_id = str(topic_id)\n topic = topics.Topic(topic_id)\n topic.make_corpus_with_scores(preprocess_fn, stopwords, features, weights) \n if topic.valid:\n topic.get_dictionary()\n #print('scores for topic {}:'.format(topic.topic_id), topic.scores) \n topic.get_word_weight(alpha, smartirs)\n profiles[topic_id] = topic.word_weight\n '''\n if i+1 == int(n_topic_ids*percentage):\n print('{}% finished'.format(percentage))\n percentage += .01\n '''\n #print('word_weights for topic id {}: '.format(topic_id), profiles[topic_id])\n with open(path, 'w') as f:\n json.dump(profiles, f)\n\n print('二次过滤后剩余{}条有效主贴'.format(len(profiles)))\n return profiles\n\n'''\ndef update_scores(db, active_topics, path, features, weights, rid_to_index, \n reply_table_num):\n \n with open(path, 'r') as f:\n scores = json.load(f)\n\n for topic_id in active_topics:\n scores[topic_id] = get_scores(db, topic_id, features, weights, \n rid_to_index, reply_table_num)\n\n with open(path, 'w') as f:\n json.dump(scores, f)\n\n return scores\n'''\n\ndef get_profile_words(profiles, k, update, path):\n '''\n Get the top k most important words for a topic\n Args:\n profiles: word weights for each topic\n k: number of words to represent the topic\n update: flag indicating whether this is an update operation\n path: file path for loading and saving\n Returns:\n Top k most important words for topics specified by topic_ids\n '''\n if update:\n with open(path, 'r') as f:\n top_k = json.load(f)\n else:\n top_k = {}\n\n for topic_id in profiles:\n profile = [(w, weight) for w, weight in profiles[topic_id].items()]\n profile.sort(key=lambda x:x[1], reverse=True)\n top_num = min(k, len(profile))\n top_k[topic_id] = [tup[0] for tup in profile[:top_num]]\n \n with open(path, 'w') as f:\n json.dump(top_k, f)\n\n return top_k ","sub_path":"tmp/topic_profiling.py","file_name":"topic_profiling.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"83009401","text":"from future.moves import tkinter as tk\nfrom tkinter import filedialog\nfrom tkinter import simpledialog\nfrom tkinter import messagebox\nimport sqlModule\nimport face_recognition\nfrom PIL import ImageTk, Image\nimport cv2\nimport numpy as np\n\nknown_face_names = []\nknown_face_encodings = []\n\n\n# untuk merefresh variable known_face... dengan database\ndef refresh():\n # untuk mengakses variable global\n global known_face_names\n global known_face_encodings\n known_face_names = []\n known_face_encodings = []\n # get data nama dan face encoding dari database\n cursor = sqlModule.get_people_encoding()\n for row in cursor:\n known_face_names.append(row[0])\n known_face_encodings.append(list(map(float, (row[1].split(' ')))))\n\n\n# box refresh untuk merefresh box yang terdapat di window add dan delete\ndef box_refresh(listbox):\n # menghapus semua item dalam box\n listbox.delete(0, tk.END)\n # merefresh list known_face...\n refresh()\n # mengakses variable known_face...\n global known_face_names\n\n # menampilkan item yang ada di variable known_face ke listbox\n idx = 1\n for name in known_face_names:\n listbox.insert(idx, name)\n idx = idx + 1\n\n\n# function untuk command ketika menu add face ditekan\ndef add_face():\n # memunculkan window baru dan listbox (tambah wajah)\n addwindow = tk.Toplevel(mainWindow)\n listbox = tk.Listbox(addwindow)\n\n # refreshing listbox\n box_refresh(listbox)\n\n # function untuk command saat button add photo ditekan\n def add_photos():\n # menampilkan filedialog untuk mengambil file pada filesystem\n mainWindow.filename = filedialog.askopenfilename(initialdir='~',\n title='Select a Picture',\n filetypes=(('jpeg files', '*.jpg'),\n ('jpeg files', '*.jpeg'),\n ('all files', '*.*')))\n # jika terdapat file yang dipilih\n if mainWindow.filename != ():\n # menampilkan simple dialog untuk memasukkan nama\n name = simpledialog.askstring('Input', 'What\\'s your name?', parent=mainWindow)\n # jika form nama tidak kosong\n if name is not None:\n # load image file to variable\n image = face_recognition.load_image_file(mainWindow.filename)\n # encode image\n face_encode = face_recognition.face_encodings(image)\n # jika gambar valid (terdapat wajah)\n if face_encode != []:\n # menambahkan nama dan gambar ke database\n sqlModule.insert_people_encoding(name, face_encode)\n # merefresh listbox\n box_refresh(listbox)\n # jika tidak ada wajah yang terdeteksi\n else:\n print('face not detected')\n # jika form nama kosong\n else:\n print('name must be filled')\n # jika tidak ada file yang dipilih\n else:\n print('no file selected')\n\n # menambahkan button tambah photo\n add_btn = tk.Button(addwindow, text='Add photo', command=add_photos)\n add_btn.pack(side=tk.BOTTOM)\n\n listbox.pack()\n\n\n# function untuk command ketika menu delete face ditekan\ndef del_face():\n # memunculkan window baru dan listbox (hapus wajah)\n del_window = tk.Toplevel(mainWindow)\n listbox = tk.Listbox(del_window)\n\n # merefresh listbox\n box_refresh(listbox)\n\n # function untuk command ketika tombol delete ditekan\n def del_name():\n # jika terdapat nama yang dipilih dalam listbox\n if listbox.curselection() != ():\n # mengampil nama yang dipilih\n nama = listbox.get(listbox.curselection())\n # menampilkan messagebox question yes or no\n msg_box = messagebox.askyesno('Delete Face', 'Are you sure want to delete ' + nama\n + ' face?', icon='warning')\n # jika menekan tombol yes\n if msg_box:\n # menghapus data wajah berdasarkan nama\n sqlModule.delete_people_encoding(nama)\n # merefresh listbox\n box_refresh(listbox)\n\n # menambahkan button delete wajah\n del_btn = tk.Button(del_window, text='Delete', command=del_name)\n del_btn.pack(side=tk.BOTTOM)\n\n listbox.pack()\n\n\n# function untuk menampilkan camera pada window\ndef show_recog_cam():\n # menentukan lebar dan tinggi video yang ditampilkan\n width, height = 800, 600\n # make an instance\n cam = cv2.VideoCapture(0)\n cam.set(cv2.CAP_PROP_FRAME_WIDTH, width)\n cam.set(cv2.CAP_PROP_FRAME_HEIGHT, height)\n\n # mengambil per frame dari video\n _, frame = cam.read()\n # mengubah ukuran untuk mempercepat proses\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n # reversing image\n rgb_small_frame = small_frame[:, :, ::-1]\n\n # mengakses variable global\n global known_face_names\n global known_face_encodings\n\n # get face location and encodings\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n face_names = []\n # get all data from face_encodings\n for face_encoding in face_encodings:\n # digunakan jika wajah yang didapat tidak terdapat di database\n name = 'stranger'\n # jika known_face tidak kosong atau di database terdapat data wajah yang disimpan\n if known_face_names != []:\n # compare wajah yang tersimpan dengan wajah yang terdeteksi pada setiap frame video\n # compare_faces returning list nilai T atau F dari face yg match\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.4)\n # mendapatkan euclidean distance dari face yang dicompare\n face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)\n # np.argmin digunakan untuk mendapatkan index dari list of array yang memiliki nilai minimum\n best_match_index = np.argmin(face_distances)\n # jika index best_match_index pada list matches adalah True\n if matches[best_match_index]:\n # get nama dari list known_face_names\n name = known_face_names[best_match_index]\n # menambahkan nama kedalam list nama yang terdeteksi\n face_names.append(name)\n\n # create rectangle pada frame berdasar face yang terdeteksi\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n # diperbesar karena tadi frame diperkecil\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n # menggambar rectangle dan text pada wajah\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, name, (right+6, top+10), font, 0.8, (0, 255, 0), 1)\n\n # convert color from BGR to RGBA\n cv2img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n # get image from array\n img = Image.fromarray(cv2img)\n # create instance of ImageTk and add it into mainwindow\n imgtk = ImageTk.PhotoImage(image=img)\n main_window.imgtk = imgtk\n main_window.configure(image=imgtk)\n main_window.after(8, show_recog_cam)\n\n\nif __name__ == '__main__':\n mainWindow = tk.Tk()\n mainWindow.bind('', lambda e: mainWindow.quit())\n main_window = tk.Label(mainWindow)\n main_window.pack()\n\n # initiate connection to database\n sqlModule.init_connection()\n\n # refreshing known_face... list\n refresh()\n\n menuBar = tk.Menu(mainWindow)\n\n fileMenu = tk.Menu(menuBar, tearoff=0)\n fileMenu.add_command(label='Add New Face', command=add_face)\n fileMenu.add_command(label=\"Delete Face\", command=del_face)\n fileMenu.add_separator()\n fileMenu.add_command(label='Exit', command=mainWindow.quit)\n menuBar.add_cascade(label='File', menu=fileMenu)\n\n mainWindow.config(menu=menuBar)\n show_recog_cam()\n mainWindow.mainloop()\n","sub_path":"facerecognition.py","file_name":"facerecognition.py","file_ext":"py","file_size_in_byte":8217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"136028789","text":"# Fibonacci Recursion: We Meet Again\n# Given a user entered number\n# Use recursion function to return the nth value in the Fibonacci Sequence\n\n# Gameplan\n# =====================================\n# fibonacci function\n# 0-1, 1-2, 1-3, 2-4, 3-5, 5-6, 8-7\n\n\n\ndef fiboNum(x):\n global previous, current, next\n previous = 0\n current = 1\n if (x != 1):\n fiboNum(x - 1)\n next = previous + current\n previous = current\n current = next\n\n\nx = int(input('Enter a number: '))\nfiboNum(x)\nprint(previous)\n\n# get out of here! 15 minute or less solution!!\n","sub_path":"week2/W02E03S01.py","file_name":"W02E03S01.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"205350334","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2016 - Frank Lin\n\nfrom java_variable import VarType\nfrom skrutil.string_utils import indent\n\n_JAVA_BR = '\\n\\n'\n_JAVA_SPACE = ' '\n\n\nclass JavaClass:\n \"\"\"Java file generator, including package, class, fields, enums and manager.\n \"\"\"\n\n def __init__(self, group_name, class_name, java_variable_list, java_enum_list, java_manager_or_none):\n \"\"\"Init Java file generator.\n\n Args:\n group_name: A string which is package name, input name is C++ folder name, should be all lowercase. (eg: task)\n class_name: A string which is class name, input name is C++ class name, should be capitalized. (eg: Task)\n java_variable_list: A list of object which mean all fields in class.\n java_enum_list: A list of object which mean all enums in class.\n java_manager_or_none: A object means ObjectManager or none means the class has no ObjectManager.\n \"\"\"\n self.__group_name = group_name\n self.__class_name = class_name\n self.__java_var_list = java_variable_list\n self.__java_enum_list = java_enum_list\n self.__java_manager_or_none = java_manager_or_none\n\n if self.__java_manager_or_none is not None:\n self.__java_manager_or_none.set_object_name(class_name, class_name + 's')\n self.__java_manager_or_none.set_java_variable_list(java_variable_list)\n\n def generate_java_v2(self, config):\n \"\"\"Generates java object implementation.\n\n Args:\n config: A config that enables some user-defined name.\n \"\"\"\n file_name = self.__class_name + '.java'\n file_path = 'build/{0}/'.format(config.java_package_path) + self.__group_name + '/' + file_name\n output_java = open(file_path, 'w')\n\n java_package = 'package {0}.'.format(config.java_package_name) + self.__group_name + ';'\n\n output_java.write(java_package + _JAVA_BR)\n\n java_import = 'import android.support.annotation.IntDef;\\n'\n java_import += 'import java.lang.annotation.Retention;\\n'\n java_import += 'import java.lang.annotation.RetentionPolicy;' + _JAVA_BR\n\n java_import += 'import {0}.base.{1};\\n'.format(config.java_package_name, config.java_base_object)\n java_import += 'import {0}.jni.CoreObject;\\n'.format(config.java_package_name)\n java_import += 'import java.util.ArrayList;\\n'\n java_import += 'import java.util.Arrays;\\n'\n if self.__class_name != 'List':\n java_import += 'import java.util.List;'\n\n java_class_start = 'public final class ' + self.__class_name + ' extends {0} {{'.format(config.java_base_object)\n java_class_end = '}'\n\n output_java.write(java_import + _JAVA_BR)\n output_java.write(java_class_start + _JAVA_BR)\n\n # generates enum in class\n for java_enum in self.__java_enum_list:\n output_java.write(java_enum.generate_android_enum(_JAVA_SPACE) + '\\n')\n\n # generates fields in class\n for java_var in self.__java_var_list:\n output_java.write(_JAVA_SPACE + java_var.private_field_name() + '\\n')\n output_java.write('\\n')\n\n # generates constructor\n output_java.write(self.__constructors_v2())\n output_java.write(_JAVA_BR)\n\n # generate getters\n for java_var in self.__java_var_list:\n output_java.write(java_var.getter_v2() + _JAVA_BR)\n\n # end brace\n output_java.write(java_class_end + '\\n')\n\n def generate_java(self):\n \"\"\"Gets Java with JNI implementation. The class inherits from |CoreObject| which means invoker should release\n the object himself/herself by calling |CoreObject.dispose()|.\n\n New development should use instead.\n\n Returns:\n A string which is the class implementation.\n \"\"\"\n file_name = self.__class_name + '.java'\n file_path = 'build/com/lesschat/core/' + self.__group_name + '/' + file_name\n output_java = open(file_path, 'w')\n\n java_package = 'package com.lesschat.core.' + self.__group_name + ';'\n\n output_java.write(java_package + _JAVA_BR)\n\n java_import = 'import android.os.Parcel;\\n'\n java_import += 'import android.os.Parcelable;' + _JAVA_BR\n java_import += 'import com.lesschat.core.jni.CoreObject;' + _JAVA_BR\n java_import += 'import java.util.ArrayList;\\n'\n java_import += 'import java.util.Arrays;\\n'\n if self.__class_name != 'List':\n java_import += 'import java.util.List;'\n\n java_class_start = 'public class ' + self.__class_name + ' extends CoreObject implements Parcelable {'\n java_class_end = '}'\n\n output_java.write(java_import + _JAVA_BR)\n output_java.write(java_class_start + _JAVA_BR)\n\n output_java.write(self.__constructors())\n output_java.write(indent(4) + '@Override\\n')\n output_java.write(indent(4) + 'public void dispose() {\\n')\n output_java.write(indent(2) + 'nativeRelease{0}(mNativeHandler);\\n'.format(self.__class_name))\n output_java.write(indent(4) + '}' + _JAVA_BR)\n\n for java_enum in self.__java_enum_list:\n output_java.write(java_enum.generate_java_enum(_JAVA_SPACE) + '\\n')\n\n for java_var in self.__java_var_list:\n output_java.write(java_var.getter() + _JAVA_BR)\n\n output_java.write(_JAVA_BR)\n output_java.write(self.__native_constructors())\n output_java.write(indent(4) + 'private native void nativeRelease{0}(long handler);'.format(self.__class_name) + _JAVA_BR)\n\n for java_var in self.__java_var_list:\n output_java.write(java_var.native_getter() + _JAVA_BR)\n\n output_java.write(self.__parcelable())\n output_java.write(java_class_end)\n\n def generate_manager_v2(self, version, config):\n \"\"\"Generates Java manager implementation code.\n\n Args:\n version: A float for compact usage.\n config: A object describes some user-defined names.\n\n Returns:\n A string which is Java manager implementation code.\n \"\"\"\n if self.__java_manager_or_none is None:\n return\n manager_name = self.__java_manager_or_none.manager_name\n file_name = self.__java_manager_or_none.manager_name + '.java'\n file_path = 'build/{0}/'.format(config.java_package_path) + self.__group_name + '/' + file_name\n output_java = open(file_path, 'w')\n\n java_package = 'package {0}.'.format(config.java_package_name) + self.__group_name + ';'\n\n output_java.write(java_package + _JAVA_BR)\n\n java_import = ''\n if len(self.__java_manager_or_none.apis) != 0:\n java_import += 'import {0}.api.*;\\n'.format(config.java_package_name)\n\n java_import += 'import android.support.annotation.NonNull;' + '\\n'\n java_import += 'import android.support.annotation.Nullable;' + '\\n'\n java_import += 'import {0}.api.v3.OnFailureListener;'.format(config.java_package_name) + '\\n'\n java_import += 'import {0}.api.v3.OnResponseListener;'.format(config.java_package_name) + '\\n'\n java_import += 'import {2}.{0}.{1}.*;\\n'.format(self.__group_name, self.__class_name, config.java_package_name)\n java_import += 'import {0}.jni.CoreObject;\\n'.format(config.java_package_name)\n java_import += 'import {0}.director.Director;\\n'.format(config.java_package_name)\n java_import += 'import {0}.jni.JniHelper;\\n\\n'.format(config.java_package_name)\n java_import += 'import java.util.ArrayList;\\n'\n java_import += 'import java.util.List;' + _JAVA_BR\n\n java_class_start = 'public class ' + manager_name + ' extends CoreObject {' + _JAVA_BR\n java_class_end = '}'\n\n java_manager_constructor = 'public static {0} getInstance() {{ return Director.getInstance().get{0}(); }}'\n java_override = '@Override\\n'\n java_manager_dispose = 'public void dispose() { }' + _JAVA_BR\n\n output_java.write(java_import)\n output_java.write(java_class_start)\n\n if version < 6:\n output_java.write(self.__java_manager_or_none.generate_http_variables())\n output_java.write('\\n')\n\n output_java.write(indent(4) + java_manager_constructor.format(manager_name) + _JAVA_BR)\n output_java.write(indent(4) + java_override)\n output_java.write(indent(4) + java_manager_dispose)\n\n output_java.write(self.__java_manager_or_none.generate_fetch_v2())\n output_java.write(self.__java_manager_or_none.generate_http_function(version))\n output_java.write(self.__java_manager_or_none.generate_fetch_native_v2())\n output_java.write(self.__java_manager_or_none.generate_http_function_native())\n\n output_java.write(java_class_end)\n\n def __constructors(self):\n \"\"\"Java class constructor with native handler as parameter.\n\n Returns:\n A string which is the implementation of the constructor. For example:\n\n public Task(long nativeHandler) {\n mNativeHandler = nativeHandler;\n }\n \"\"\"\n constructor = indent(4) + 'public {0}() {{ \\n mNativeHandler = nativeCreate{0}(); \\n }}'\\\n .format(self.__class_name) + _JAVA_BR\n constructor += indent(4) + 'public {0}(long nativeHandler) {{\\n'.format(self.__class_name)\n constructor += indent(2) + 'mNativeHandler = nativeHandler;\\n'\n constructor += indent(4) + '}\\n\\n'\n return constructor\n\n def __constructors_v2(self):\n \"\"\"Java class constructor with all fields as parameters.\n\n Returns:\n A string which is the implementation of the constructor. For example:\n\n /*package*/ File(String fileId,\n @File.Type int type,\n @File.Visibility int visibility,\n @File.Belong int belong,\n @File.FolderPermissionSetting int folderPermissionSetting,\n String createdBy,\n long createdAt,\n String updatedBy,\n long updatedAt) {\n mFileId = fileId;\n ... Remainder omitted...\n }\n \"\"\"\n package_class = indent(4) + '/*package*/ {0}'.format(self.__class_name)\n num_line_indent = len(package_class) + 1\n\n if len(self.__java_var_list) > 1:\n first_var = self.__java_var_list[0].input_parameter_name()\n constructor = '{0}({1},\\n'.format(package_class, first_var)\n for var in self.__java_var_list:\n if first_var == var.input_parameter_name():\n continue\n constructor += indent(num_line_indent) + '{0},'.format(var.input_parameter_name()) + '\\n'\n constructor = constructor[:-2] # remove break line and last comma\n elif len(self.__java_var_list) == 1:\n first_var = self.__java_var_list[0].input_parameter_name()\n constructor = '{0}({1})'.format(package_class, first_var)\n else:\n constructor = '{0}()'.format(package_class)\n\n constructor += ') {\\n'\n\n for var in self.__java_var_list:\n constructor += indent(8) + var.assignment() + '\\n'\n constructor += indent(4) + '}'\n\n return constructor\n\n def __constructor_with_variable(self):\n constructor = indent(4) + 'public {0}('.format(self.__class_name)\n space = len(indent(4) + 'public {0}('.format(self.__class_name))\n space_str = ''\n for space_index in range(0, space):\n space_str += ' '\n for index in range(0, len(self.__java_var_list)):\n java_var = self.__java_var_list[index]\n java_var_type = java_var.var_type\n if index == 0:\n if java_var_type == VarType.cpp_enum:\n constructor += '{0} {1},\\n'.format(java_var.java_enum, java_var.name_str)\n elif java_var_type == VarType.cpp_string_array:\n constructor += 'String[] {0},\\n'.format(java_var.name_str)\n else:\n constructor += '{0} {1},\\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str)\n else:\n if java_var_type == VarType.cpp_enum:\n constructor += space_str + '{0} {1},\\n'.format(java_var.java_enum, java_var.name_str)\n elif java_var_type == VarType.cpp_string_array:\n constructor += space_str + 'String[] {0},\\n'.format(java_var.name_str)\n else:\n constructor += space_str + '{0} {1},\\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str)\n constructor = constructor[:-2]\n constructor += '){\\n'\n constructor += indent(2) + 'mNativeHandler = nativeCreate{0}('.format(self.__class_name)\n for java_var in self.__java_var_list:\n if java_var.var_type == VarType.cpp_enum:\n constructor += java_var.name_str + '.getValue(), '\n else:\n constructor += java_var.name_str + ', '\n constructor = constructor[:-2]\n constructor += ');\\n'\n constructor += indent(4) + '}' + _JAVA_BR\n return constructor\n\n def __native_constructors(self):\n native_constructor = indent(4) + 'private native long nativeCreate{0}();'.format(self.__class_name) + _JAVA_BR\n # native_constructor += self.__native_constructor_with_variable()\n return native_constructor\n\n def __native_constructor_with_variable(self):\n space_str = ''\n native_constructor = indent(4) + 'private native long nativeCreate{0}('.format(self.__class_name)\n for space_index in range(0, len(indent(4) + 'private native long nativeCreate{0}('.format(self.__class_name))):\n space_str += ' '\n for index in range(0, len(self.__java_var_list)):\n java_var = self.__java_var_list[index]\n java_var_type = java_var.var_type\n if index == 0:\n if java_var_type == VarType.cpp_enum:\n native_constructor += 'int {0},\\n'.format(java_var.name_str)\n elif java_var_type == VarType.cpp_string_array:\n native_constructor += 'String[] {0},\\n'.format(java_var.name_str)\n else:\n native_constructor += '{0} {1},\\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str)\n else:\n if java_var_type == VarType.cpp_enum:\n native_constructor += space_str + 'int {0},\\n'.format(java_var.name_str)\n elif java_var_type == VarType.cpp_string_array:\n native_constructor += space_str + 'String[] {0},\\n'.format(java_var.name_str)\n else:\n native_constructor += space_str + '{0} {1},\\n'.format(java_var.var_type.to_java_getter_setter_string(), java_var.name_str)\n native_constructor = native_constructor[:-2]\n native_constructor += ');' + _JAVA_BR\n return native_constructor\n\n def __initwith(self):\n initwith = indent(4) + 'public boolean initWithJson(String json) { return nativeInitWithJson(mNativeHandler, json); }'\n initwith += _JAVA_BR\n return initwith\n\n def __native_initwith(self):\n native_initwith = indent(4) + 'private native boolean nativeInitWithJson(long handler, String json);'\n native_initwith += _JAVA_BR\n return native_initwith\n\n def __parcelable(self):\n parcelable = indent(4) + 'public {0}(Parcel in) {{\\n'.format(self.__class_name)\n parcelable += indent(2) + 'mNativeHandler = in.readLong();\\n'\n parcelable += indent(4) + '}' + _JAVA_BR\n parcelable += indent(4) + 'public static final Parcelable.Creator<{0}> CREATOR = new Parcelable.Creator<{0}>() {{\\n\\n'\\\n .format(self.__class_name)\n parcelable += indent(2) + 'public {0} createFromParcel(Parcel in) {{ return new {0}(in); }}\\n\\n'\\\n .format(self.__class_name)\n parcelable += indent(2) + 'public {0}[] newArray(int size) {{ return new {0}[size]; }}\\n'\\\n .format(self.__class_name)\n parcelable += indent(4) + '};' + _JAVA_BR\n parcelable += indent(4) + '@Override\\n'\n parcelable += indent(4) + 'public int describeContents() { return 0; }' + _JAVA_BR\n parcelable += indent(4) + '@Override\\n'\n parcelable += indent(4) + 'public void writeToParcel(Parcel parcel, int i) { parcel.writeLong(mNativeHandler); }\\n'\n parcelable += '\\n'\n return parcelable\n\n def generate_manager(self):\n if self.java_manager_or_none is None:\n return\n manager_name = self.java_manager_or_none.manager_name\n file_name = self.java_manager_or_none.manager_name + '.java'\n file_path = 'build/com/lesschat/core/' + self.group_name + '/' + file_name\n output_java = open(file_path, 'w')\n\n java_package = 'package com.lesschat.core.' + self.group_name + ';'\n\n output_java.write(java_package + _JAVA_BR)\n\n java_import = ''\n if len(self.java_manager_or_none.apis) != 0:\n java_import += 'import com.lesschat.core.api.*;\\n'\n\n java_import += \"import android.support.annotation.NonNull;\"\n\n java_import += 'import com.lesschat.core.{0}.{1}.*;\\n'.format(self.group_name, self.class_name)\n java_import += 'import com.lesschat.core.jni.CoreObject;\\n'\n java_import += 'import com.lesschat.core.director.Director;\\n'\n java_import += 'import com.lesschat.core.jni.JniHelper;\\n\\n'\n java_import += 'import java.util.ArrayList;\\n'\n java_import += 'import java.util.List;' + _JAVA_BR\n\n java_class_start = 'public class ' + manager_name + ' extends CoreObject {' + _JAVA_BR\n java_class_end = '}'\n\n java_manager_constructor = 'public static @NonNull {0} getInstance() ' \\\n '{{ return Director.getInstance().get{0}();}}'\n java_override = '@Override\\n'\n java_manager_dispose = 'public void dispose() { }' + _JAVA_BR\n\n output_java.write(java_import)\n output_java.write(java_class_start)\n\n output_java.write(self.java_manager_or_none.generate_http_variable())\n output_java.write('\\n')\n\n output_java.write(indent(1) + java_manager_constructor.format(manager_name) + _JAVA_BR)\n output_java.write(indent(1) + java_override)\n output_java.write(indent(1) + java_manager_dispose)\n\n output_java.write(self.java_manager_or_none.generate_fetch())\n output_java.write(self.java_manager_or_none.generate_http_function())\n output_java.write(self.java_manager_or_none.generate_fetch_native())\n output_java.write(self.java_manager_or_none.generate_http_function_native())\n\n output_java.write(java_class_end)\n\n","sub_path":"skr_java_builder/java_class.py","file_name":"java_class.py","file_ext":"py","file_size_in_byte":19113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"558864410","text":"import math\nimport random\nfrom abc import ABC, abstractmethod\n\nfrom flukeprint import FP_RNG\n\nFP_RNG.random() # Change initial random state\n\n\nclass Sampler(ABC):\n\n def __init__(self, *args, **kwargs):\n self.rng = random.Random()\n self.rng.setstate(FP_RNG.getstate())\n\n @abstractmethod\n def sample(self):\n pass\n\n def seed(self, seed_val):\n self.rng.seed(seed_val)\n\n def get_state(self):\n return self.rng.getstate()\n\n def set_state(self, state):\n self.rng.setstate(state)\n\n\nclass Constant(Sampler):\n\n def __init__(self, value):\n super(Constant, self).__init__()\n self.value = value\n\n def sample(self):\n return self.value\n\n\nclass Uniform(Sampler):\n\n def __init__(self, low: float = 0.0, high: float = 1.0, dtype: str = 'float'):\n \"\"\" Generates a randomly sampled value from low to high with equal probability.\n\n :param low: Minimum value.\n :param high: Maximum value.\n :param dtype: Data type.\n \"\"\"\n super(Uniform, self).__init__()\n self.low = low\n self.high = high\n self.dtype = dtype\n\n def sample(self):\n res = self.rng.uniform(self.low, self.high)\n if 'fl' in self.dtype:\n return res\n return int(res)\n\n\nclass Choice(Sampler):\n\n def __init__(self, items: list, sampler: Sampler = Uniform(), *args, **kwargs):\n \"\"\" Samples a value from a given list according to the provided sampler.\n\n :param items: items to be sampled.\n :param sampler: Sampler used to select an item based on its index.\n \"\"\"\n super(Choice, self).__init__(*args, **kwargs)\n self.sampler = sampler\n self.items = items\n self.rng = self.sampler.rng\n\n def sample(self):\n i = self.sampler.sample() * len(self.items)\n i = int(math.floor(i))\n return self.items[i]\n\n\nclass Truncated(Sampler):\n\n def __init__(self, sampler: Sampler = Uniform(), low: float = None, high: float = None, *args, **kwargs):\n \"\"\" Given a sampler, clips the distribution between low and high.\n If None, not truncated.\n\n :param sampler: Sampler to be truncated.\n :param low: Minimum value to be sampled.\n :param high: Maximum value to be sampled.\n \"\"\"\n super(Truncated, self).__init__(*args, **kwargs)\n self.sampler = sampler\n self.rng = self.sampler.rng\n self.min = low\n self.max = high\n\n def sample(self):\n val = self.sampler.sample()\n if self.min is not None and val < self.min:\n val = self.min\n if self.max is not None and val > self.max:\n val = self.max\n return val\n\n\nclass Gaussian(Sampler):\n\n def __init__(self, mean: float = 0.0, std: float = 1.0, dtype: str = 'float'):\n \"\"\" Generates a randomly sampled value with specified mean and std based on a Gaussian distribution.\n\n :param mean: Mean of Gaussian.\n :param std: Standard deviation of Gaussian.\n :param dtype: Data type.\n \"\"\"\n super(Gaussian, self).__init__()\n self.mean = mean\n self.std = std\n self.dtype = dtype\n\n def sample(self):\n res = self.rng.gauss(self.mean, self.std)\n if 'fl' in self.dtype:\n return res\n return int(res)\n\n\nclass Normal(Gaussian):\n pass\n\n\nclass LognormVariate(Sampler):\n\n def __init__(self, mean: float = 0.0, std: float = 1.0, dtype: str = 'float'):\n \"\"\" Generates a randomly sampled value with specified mean and std based on a Log normal distribution.\n\n :param mean: Mean of Lognormal.\n :param std: Standard deviation of Lognormal.\n :param dtype: Data type.\n \"\"\"\n super(LognormVariate, self).__init__()\n self.mean = mean\n self.std = std\n self.dtype = dtype\n\n def sample(self):\n res = self.rng.lognormvariate(self.mean, self.std)\n if 'fl' in self.dtype:\n return res\n return int(res)\n\n\nclass BetaVariate(Sampler):\n\n def __init__(self, alpha: float, beta: float, dtype='float'):\n \"\"\" Generates a randomly sampled value with specified mean and std based on a Beta distribution.\n\n :param alpha: Alpha of beta distribution.\n :param beta: Beta of beta distribution.\n :param dtype: Data type.\n \"\"\"\n super(BetaVariate, self).__init__()\n self.alpha = alpha\n self.beta = beta\n self.dtype = dtype\n\n def sample(self):\n res = self.rng.betavariate(self.alpha, self.beta)\n if 'fl' in self.dtype:\n return res\n return int(res)\n\n\nclass ExpoVariate(Sampler):\n\n def __init__(self, lam: float, dtype='float'):\n \"\"\" Generates a randomly sampled value with lambda based on an exponential distribution.\n\n :param lam: Lambda of exponential distribution (one divided by desired mean).\n :param dtype: Data type.\n \"\"\"\n super(ExpoVariate, self).__init__()\n self.lam = lam\n self.dtype = dtype\n\n def sample(self):\n res = self.rng.expovariate(self.lam)\n if 'fl' in self.dtype:\n return res\n return int(res)\n\n\nclass WeibullVariate(Sampler):\n\n def __init__(self, alpha: float, beta: float, dtype: str = 'float'):\n \"\"\" Generates a randomly sampled value with specified mean and std based on a Weibull distribution.\n\n :param alpha: Alpha of Weibull distribution (scale parameter).\n :param beta: Beta of Weibull distribution (shape parameter).\n :param dtype: Data type.\n \"\"\"\n super(WeibullVariate, self).__init__()\n self.alpha = alpha\n self.beta = beta\n self.dtype = dtype\n\n def sample(self):\n res = self.rng.weibullvariate(self.alpha, self.beta)\n if 'fl' in self.dtype:\n return res\n return int(res)\n\n\nclass ParetoVariate(Sampler):\n\n def __init__(self, alpha: float, dtype: str = 'float'):\n \"\"\" Generates a randomly sampled value with alpha based on the Pareto distribution.\n\n :param alpha: Alpha of Pareto distribution (shape parameter).\n :param dtype: Data type.\n \"\"\"\n super(ParetoVariate, self).__init__()\n self.alpha = alpha\n self.dtype = dtype\n\n def sample(self):\n res = self.rng.paretovariate(self.alpha)\n if 'fl' in self.dtype:\n return res\n return int(res)\n","sub_path":"flukeprint/samplers.py","file_name":"samplers.py","file_ext":"py","file_size_in_byte":6435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"156835426","text":"# File: proj1.py\n# Author: Daniel Diseroad\n# Date: 11/3/16\n# Section: 28\n# E-mail: ddiser1@umbc.edu\n# Description:\n# This program allows two users to play the game Connect Four\n# Collaboration:\n# Collaboration was not allowed on this assignment.\n\nCOLUMN_ROW = 5\nCOLUMN_START = 1\nPLAYER_1 = \"x\"\nPLAYER_2 = \"o\"\nEMPTY = \"-\"\nRUN = \"y\"\nSTOP = \"n\"\nWIN = 4\n\n# aboveFive() prompts the user for the column and row length and validates that it is over 5\n# Input: none\n# Output: two ints; the row and column length\ndef aboveFive():\n promptRow = \"Please choose the number of rows. \\nPlease \" \\\n \"enter a number\" +\" greater than or equal to \"+ str(COLUMN_ROW)+ \": \" \n promptColumn = \"Please choose the number of columns.\\n\" \\\n \"Please enter a number\"+\" greater than or \" \\\n \"equal to \"+ str(COLUMN_ROW)+ \": \"\n row = int(input(promptRow))\n while rownumOfColumns):\n return False\n for i in range(len(board)):\n if board[i][columnNum-1] != EMPTY:\n counter+=1\n if (counter == len(board)):\n return False\n else:\n return True\n\n# winLoseDraw() checks to see if the game is over.\n# Input: a list with the board itself and an int representing the number of columns\n# Output: a boolean; representing whether the game is over or not\ndef winLoseDraw(board,numOfColumns,player):\n counter=0\n playerN = \"\"\n if(player == PLAYER_1):\n player = PLAYER_2\n playerN = \"Player 2\"\n else:\n player = PLAYER_1\n playerN = \"Player 1\"\n#tests to see if a player won horizontally\n for i in range(len(board)):\n counter=0\n for j in range(len(board[i])):\n if(board[i][j]==player):\n counter+=1\n if(counter==WIN):\n print(\"The horizontal winner is\",playerN)\n return True\n else:\n counter=0\n counter=0\n#tests to see if a player won vertically\n verticalMarks = []\n for i in range(len(board[0])):\n for j in range(len(board)):\n verticalMarks.append(board[j][i])\n for i in verticalMarks:\n if(i==player):\n counter+=1\n if(counter==WIN):\n print(\"The vertical winner is\",playerN)\n return True\n else:\n counter=0\n verticalMarks = []\n counter=0\n verticalMarks = []\n#diagonal check\n for i in range(len(board)):\n for j in range(len(board[i])):\n for w in range(WIN):\n if((i+w)<= len(board)-1) and ((j+w)<=len(board[i])-1):\n if board[i+w][j+w]==player:\n counter+=1\n if counter==WIN:\n print(\"The diagonal winner is\",playerN)\n return True\n else:\n counter=0\n else:\n counter=0\n counter = 0\n for w in range(WIN):\n if ((i+w)<= len(board)-1) and ((j-w)>=0):\n if board[i+w][j-w]==player:\n counter+=1\n if counter==WIN:\n print(\"The diagonal winner is\",playerN)\n return True\n else:\n counter=0\n else:\n counter = 0\n#draw check\n counter=0\n for i in range(numOfColumns):\n if(columnCheck((i+1),board,numOfColumns)==False):\n counter+=1\n if(counter==numOfColumns):\n print(\"There was a draw!\")\n return True\n return False\n \n# playerTurn() goes through a player's turn, validating their choices and calling functions\n# to update the board or save\n# Input: a string representing the current player, the board, an int representing the \n# total columns, and a list containing valid inputs for the column number\n# Output: a list representing the updated board\ndef playerTurn(player,board,numColumn,validNums):\n if(player==PLAYER_1):\n print(\"Player 1 what is your choice?\")\n else:\n print(\"Player 2 what is your choice?\")\n prompt = \"Please choose a column to place your \" \\\n \"piece in (\"+str(COLUMN_START)+\" - \"+str(numColumn)+\") \" \\\n \"or s to save: \"\n counter=0\n while True:\n userNum = input(prompt)\n if userNum==validNums[0]:\n #call save function\n openSave(1,board,player)\n else:\n #make sure the input is valid and use it, or reprompt.\n for i in range(len(validNums)):\n if validNums[i] == userNum:\n counter+=1\n if(columnCheck(int(userNum),board,numColumn)==True) and counter==1:\n board = boardUpdate(userNum,player,board)\n break\n else:\n if int(userNum)>0 and int(userNum)O) and uses shortest path only in a direct way\n el_relation = \"WIKIFIERED\" # default entity relation between token in sentence/topic and first entity found in KB\n wikifier_userkey = \"zlqsluqpacmwysgzyonpvqkmvmixiu\" \n\n # input args\n topic = json_post['topic']\n sent = json_post['sent']\n use_wikifier = json_post.get('use_wikifier', True)\n use_official_endpoint = json_post.get(\"use_official_endpoint\", True)\n use_pred_by_id = json_post.get(\"use_pred_by_id\", [\"P279\", \"P31\", \"P361\", \"P460\"]) # P279 (subclassof), P31 (instanceof), P361 (partof), P460 (saidtobethesameas)\n max_graph_depth = json_post.get(\"max_graph_depth\", 3)\n max_nodes = json_post.get(\"max_nodes\", 600) # max number of nodes visited before stop\n max_nodes_per_hop = json_post.get(\"max_nodes_per_hop\", 200) # max nodes to visit before stop\n if \"CONTENT_PROPERTIES\" in use_pred_by_id:\n use_pred_by_id = [el for el in use_pred_by_id if el != \"CONTENT_PROPERTIES\"]\n use_pred_by_id.extend(content_properties)\n if \"FREQUENT_PROPERTIES\" in use_pred_by_id:\n use_pred_by_id = [el for el in use_pred_by_id if el != \"FREQUENT_PROPERTIES\"]\n use_pred_by_id.extend(frequent_properties)\n\n # dic with preds, alias, desxriptions, freqs\n pred_infos = helper.get_property_infos(\"wikidata/resources/wikidata_30-11-18/\")\n\n # get db connections\n kb_name = \"wikidata_virtuoso\"\n if use_official_endpoint == True:\n kb_url = \"https://query.wikidata.org/sparql\"\n else:\n kb_url = \"http://knowledge-graph:8890/sparql\"\n nx_graph = nx.MultiDiGraph()\n\n results, avg_path_len = get_knowledge_for_sentence(sent, topic.replace(\"_\", \" \"), nx_graph, kb_name, kb_url,\n max_nodes=max_nodes,\n max_nodes_per_hop=max_nodes_per_hop,\n el_relation=el_relation,\n use_pred_by_name=use_pred_by_name,\n consider_relation_directions=consider_relation_directions,\n remove_mirrored_paths=False,\n use_wikifier=use_wikifier,\n printouts=True,\n exclude_pred_by_name=exclude_pred_by_name,\n use_pred_by_id=use_pred_by_id,\n exclude_pred_by_id=exclude_pred_by_id, pred_infos=pred_infos,\n apply_page_rank_sq_threshold=apply_page_rank_sq_threshold,\n max_graph_depth=max_graph_depth,\n userkey=wikifier_userkey,\n include_lda=include_lda,\n include_wordvec=include_wordvec,\n draw=draw,\n par_query=par_query,\n include_openie=include_openie)\n results[\"topic\"] = topic\n results[\"sent\"] = sent\n # print(json.dumps(results, sort_keys=True, indent=4))\n return(json.dumps(results, sort_keys=True, indent=4))\n\n except Exception as e:\n print(str(e))\n return json.dumps({\"error\": \"Execution error. Please contact an administrator.\"})\n\ndef get_cases(path, count=1, start=0):\n with open(path, 'r', encoding='utf8') as f:\n data = f.readlines()\n data = data[-len(data)+1:] # cut titles\n data = data[start:count+start] # only tkae first count from start on\n args = [(d.split('\\t')[0], d.split('\\t')[3], d.split('\\t')[4], d.split('\\t')[5]) for d in data] # collect arguments (topic + hash + sentence + label)\n return args\n\ndef run_and_save(topic, hashstr, sentence, label, max_depth, include_lda, include_wordvec, par_query, include_openie, output_path):\n f_json = extract_evidence({\"topic\": topic, \"sent\": sentence, \"max_graph_depth\": max_depth}, include_lda=include_lda, include_wordvec=include_wordvec, par_query=par_query, include_openie=include_openie)\n f = json.loads(f_json)\n f['label'] = 'Argument_for' if 'for' in label else 'Argument_against' if 'against' in label else 'NoArgument'\n f['hash'] = hashstr\n f_print_json = json.dumps(f)\n with open(output_path, 'a') as ff:\n ff.write(f_print_json)\n ff.write('\\n')\n\ndef create_classifier_data(topic, output_path, classifier_path):\n with open(output_path, 'r') as f:\n samples = f.read()\n\n samples = samples.split('}')\n ret_samples = []\n\n all_paths_exhausted = True\n avg_no_hops = 0\n avg_no_paths_between_entities = 0\n avg_no_paths_to_topic = 0\n avg_no_visited_nodes = 0\n avg_path_len = 0\n avg_processing_time_seconds = 0\n total_processing_time_seconds = 0\n total_samples = 0\n total_samples_with_paths = 0\n\n for s in samples:\n sample = s.replace('\\n', '')+'}'\n try:\n sample_dict = json.loads(sample)\n except:\n continue\n if 'error' not in sample_dict:\n avg_pathlen = 0\n for p in sample_dict['paths_within_sent']:\n avg_pathlen += p.count('[')\n for p in sample_dict['paths_to_topic']:\n avg_pathlen += p.count('[')\n try:\n avg_pathlen = avg_pathlen/(len(sample_dict['paths_within_sent'])+len(sample_dict['paths_to_topic']))\n except ZeroDivisionError:\n avg_pathlen = 0\n\n sample_dict['avg_path_len'] = avg_pathlen\n sample_dict['set'] = random.choice(['test', 'train', 'val'])\n sample_dict['no_hops'] = sample_dict.pop('total_hops')\n sample_dict['no_paths_between_entities'] = sample_dict.pop('total_paths_within_sent')\n sample_dict['no_paths_to_topic'] = sample_dict.pop('total_paths_to_topic')\n sample_dict['no_sent_annotations'] = sample_dict.pop('total_sent_annotations')\n sample_dict['no_topic_annotations'] = sample_dict.pop('total_topic_annotations')\n sample_dict['no_visited_nodes'] = sample_dict.pop('total_visited_nodes')\n sample_dict['paths_between_entities'] = sample_dict.pop('paths_within_sent')\n sample_dict['sentence'] = sample_dict.pop('sent')\n\n all_paths_exhausted = all_paths_exhausted and sample_dict['all_paths_exhausted']\n avg_no_hops += sample_dict['no_hops']\n avg_no_paths_between_entities += sample_dict['no_paths_between_entities']\n avg_no_paths_to_topic += sample_dict['no_paths_to_topic']\n avg_no_visited_nodes += sample_dict['no_visited_nodes']\n avg_path_len += sample_dict['avg_path_len']\n total_processing_time_seconds += float(sample_dict['total_processing_time_seconds'])\n total_samples += 1\n if sample_dict['no_paths_between_entities']+sample_dict['no_paths_to_topic'] > 0:\n total_samples_with_paths += 1\n\n ret_samples.append(sample_dict)\n\n out_dict = {\n 'metadata': {\n 'all_paths_exhausted' : all_paths_exhausted,\n 'avg_no_hops' : avg_no_hops/total_samples,\n 'avg_no_paths_between_entities' : avg_no_paths_between_entities/total_samples,\n 'avg_no_paths_to_topic' : avg_no_paths_to_topic/total_samples,\n 'avg_no_visited_nodes' : avg_no_visited_nodes/total_samples,\n 'avg_path_len' : avg_path_len/total_samples,\n 'avg_processing_time_seconds' : total_processing_time_seconds/total_samples,\n 'total_processing_time_seconds' : total_processing_time_seconds,\n 'total_samples' : total_samples,\n 'total_samples_with_paths' : total_samples_with_paths,\n 'creation_date': datetime.now().strftime('%Y-%m-%d_%H-%M-%S'),\n 'topic': topic\n },\n 'samples': ret_samples\n }\n\n\n with open(classifier_path, 'w') as f:\n f.write(json.dumps(out_dict, sort_keys=True, indent=4))\n\ndef main():\n\n # process arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', default='data', type=str, required=False, help='No data_dir found.')\n parser.add_argument('--topic', default=None, type=str, required=True, help='No topic found.')\n parser.add_argument('--num_cases', default=None, type=int, required=True, help='No num_cases found.')\n parser.add_argument('--depth', default=None, type=int, required=True, help='No depth found.')\n parser.add_argument('--include_lda', default=None, type=bool, required=True, help='No include_lda found.')\n parser.add_argument('--include_wordvec', default=None, type=bool, required=True, help='No include_wordvec found.')\n parser.add_argument('--par_query', default=None, type=bool, required=True, help='No par_query found.')\n parser.add_argument('--include_openie', default=None, type=bool, required=True, help='No include_openie found.')\n args = parser.parse_args()\n\n # create paths\n path_to_cases = 'testing//'+args.topic+'.tsv' # can change to any .tsv in /testing\n output_path = 'results//raw_result_'+args.topic+'_nx.json'\n classifier_path = output_path.replace('raw_', '')\n\n # load cases, run model and translate to json for classifier\n cases = get_cases(path_to_cases, args.num_cases)\n for t, h, s, l in cases:\n run_and_save(t, h, s, l, max_depth=args.depth, include_lda=args.include_lda, include_wordvec=args.include_wordvec, \n par_query=args.par_query, include_openie=args.include_openie, output_path=output_path)\n create_classifier_data(topic=args.topic, output_path=output_path, classifier_path=classifier_path)\n\nif __name__ == '__main__':\n main()","sub_path":"project/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":11024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"415141064","text":"#! /usr/bin/env python2.7\n\n\"\"\"\nClean up the mess that Mendeley leaves behind when it exports to BibTeX:\n\n* Delete entries with duplicate citekeys (keep the first one encountered)\n* Remove url and month fields (because apacite tries to include them and\n it's not necessary/is ugly)\n\nDave Kleinschmidt, 2015\n\"\"\"\n\nimport sys\nimport re\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-i',type=str)\nparser.add_argument('-o',type=str)\nargs = parser.parse_args()\n\ninput_path = args.i\noutput_path = args.o\n\nout = open(output_path,'a+')\ninp = open(input_path,'r')\n\ninclude_this_entry = True\nids_seen = set()\n\nstart_entry_re = re.compile('@\\w+{(?P\\w+),')\nexclude_line_re = re.compile('^(month|url|abstract|file|eprint|keywords|Automatically generated|Any changes|BibTeX export options)')\n# exclude_annote_re = re.compile(r\"annote = \\{\\s*.*\\}\")\n\nprint(\"Cleaned! Just like that!\\n\")\n\n\nfor line in inp:\n m = start_entry_re.match(line)\n if m:\n ## start of new entry. check for dupe\n if m.group('id') in ids_seen:\n include_this_entry = False\n out.write('Duplicate ID: ' + m.group('id') + '\\n')\n else:\n include_this_entry = True\n ids_seen.add(m.group('id'))\n if include_this_entry:\n if not exclude_line_re.match(line):\n out.write(line)\ninp.close()\nout.close()","sub_path":"clean_library.py","file_name":"clean_library.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"301118822","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\ndef Q1(x):\n while x-2!=0:\n a=0\n b=1\n c=0\n for i in range(x-2):\n c=a+b\n a=b\n b=c\n print(c,end=\" \")\n x-=1\n print('1 0')\n return\nQ1(int(input(\"enter number\")))\n\n\n# In[1]:\n\n\ndef Q2(n):\n a=[]\n s=0\n for i in range(n):\n a.append(int(input()))\n for i in range(n):\n c=0\n for j in range(n):\n if i!=j:\n if a[i]==a[j]:\n c+=1\n if c==0:\n s=s+a[i]\n return s\nQ2(int(input(\"no of values\")))\n\n\n# In[3]:\n\n\ndef Q3(a,b):\n if len(a)<=len(b):\n n=len(a)\n k=len(b)\n else:\n n=len(b)\n k=len(a)\n for i in range(n):\n print(a[i],b[i])\n for j in range(n,k):\n if(len(a)<=len(b)):\n print(b[j],'*')\n else:\n print(a[j],'*')\n return\nx=str(input(\"enter str:\"))\nx=x.split()\nQ3(x[0],x[1])\n\n\n# In[4]:\n\n\ndef Q4(a,b):\n if len(a)>=len(b):\n print(a.upper())\n else:\n print(b.upper())\n return\nx=str(input(\"enter str:\"))\nx=x.split()\nQ4(x[0],x[1])\n\n\n# In[1]:\n\n\ndef Q5_1(a):\n a=a.split()\n for i in range (len(a)):\n if a[i].istitle()==True:\n print(a[i].upper(),end= \" \")\n return\nx=str(input(\"enter str:\"))\nQ5_1(x)\n\n\n# In[2]:\n\n\ndef Q7(n):\n for i in range(len(n)):\n n[i]=int(n[i])\n for i in range(len(n)):\n for j in range(n[i]):\n print(\"*\",end=\"\")\n print(\"\")\n return\nx=input(\"enter num\")\nQ7(list(x))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"assignment file day9.py","file_name":"assignment file day9.py","file_ext":"py","file_size_in_byte":1565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"628778089","text":"# Copyright (c) 2015 Ultimaker B.V.\n# Uranium is released under the terms of the AGPLv3 or higher.\n\nfrom UM.WorkspaceReader import WorkspaceReader\nfrom UM.Scene.SceneNode import SceneNode\nfrom UM.Scene.PointCloudNode import PointCloudNode\nfrom UM.Logger import Logger\nimport xml.etree.ElementTree as ET\nfrom UM.Application import Application\nfrom UM.Mesh.MeshData import MeshType\nfrom UM.Math.Matrix import Matrix\n\nimport os\n\nclass MLPReader(WorkspaceReader):\n def __init__(self):\n super().__init__()\n self._supported_extension = \".mlp\"\n \n def read(self, file_name, storage_device): \n extension = os.path.splitext(file_name)[1]\n if extension.lower() == self._supported_extension:\n loaded_workspace = SceneNode()\n mesh_handler = Application.getInstance().getMeshFileHandler()\n f = storage_device.openFile(file_name, \"rt\")\n \n tree = ET.parse(f)\n root = tree.getroot()\n if root.tag == \"MeshLabProject\":\n for group in root.findall(\"MeshGroup\"):\n for mesh in group.findall(\"MLMesh\"): \n mesh_data = mesh_handler.read(mesh.get(\"filename\"),Application.getInstance().getStorageDevice(\"local\"))\n mesh_data.setName(mesh.get(\"label\"))\n if mesh_data.getType() is MeshType.pointcloud:\n mesh_node = PointCloudNode(loaded_workspace)\n else:\n mesh_node = SceneNode(loaded_workspace)\n mesh_lines = mesh.findall(\"MLMatrix44\")[0].text.splitlines()\n mesh_matrix = Matrix()\n mesh_matrix.setColumn(0,mesh_lines[1].split())\n mesh_matrix.setColumn(1,mesh_lines[2].split())\n mesh_matrix.setColumn(2,mesh_lines[3].split())\n mesh_matrix.setColumn(3,mesh_lines[4].split())\n mesh_node.setMeshData(mesh_data)\n return loaded_workspace\n else:\n Logger.log(\"e\", \"Unable to load file. It seems to be formated wrong.\")\n return None\n else:\n return None # Can't do anything with provided extention\n","sub_path":"plugins/FileHandlers/MLPReader/MLPReader.py","file_name":"MLPReader.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"408568480","text":"# -*- coding:utf-8 -*-\n# @Author: Niccolò Bonacchi\n# @Date: Thursday, September 27th 2018, 6:32:28 pm\n# @Last Modified by: Niccolò Bonacchi\n# @Last Modified time: 2018-09-28 15:26:50\n\nimport numpy as np\nimport subprocess\nimport os\nimport sys\n\n\ndef configure_sounddevice(sd=None, output='sysdefault', samplerate=44100):\n \"\"\"\n Will import, configure, and return sounddevice module to\n play sounds using onboard sound card.\n\n :param sd: sounddevice module to be configured,\n defaults to None, will import new module if absent.\n :type sd: module, optional\n :return: configured sounddevice module\n :rtype: sounddevice module\n \"\"\"\n if sd is None:\n import sounddevice as sd\n if sys.platform == 'linux':\n devices = sd.query_devices()\n sd.default.device = [(i, d) for i, d in enumerate(\n devices) if 'sysdefault' in d['name']][0][0]\n sd.default.latency = 'low'\n sd.default.channels = 2\n else:\n if output == 'xonar':\n devices = sd.query_devices()\n sd.default.device = [(i, d) for i, d in enumerate(\n devices) if 'Headphones' in d['name']][0][0]\n sd.default.latency = 'low'\n sd.default.channels = 2\n sd.default.samplerate = samplerate\n elif output == 'sysdefault':\n sd.default.latency = 'low'\n sd.default.channels = 2\n sd.default.samplerate = samplerate\n return sd\n\n\ndef make_sound(rate=44100, frequency=10000, duration=0.1, amplitude=1,\n fade=0.01, chans='L+TTL'):\n \"\"\"\n Build sounds and save bin file for upload to soundcard or play via\n sounddevice lib.\n\n :param rate: sample rate of the soundcard use 96000 for Bpod,\n defaults to 44100 for soundcard\n :type rate: int, optional\n :param frequency: (Hz) of the tone, if -1 will create uniform random white\n noise, defaults to 10000\n :type frequency: int, optional\n :param duration: (s) of sound, defaults to 0.1\n :type duration: float, optional\n :param amplitude: E[0, 1] of the sound 1=max 0=min, defaults to 1\n :type amplitude: intor float, optional\n :param fade: (s) time of fading window rise and decay, defaults to 0.01\n :type fade: float, optional\n :param chans: ['mono', 'L', 'R', 'stereo', 'L+TTL', 'TTL+R'] number of sound\n channels and type of output, defaults to 'L+TTL'\n :type chans: str, optional\n :return: streo sound from mono definitions\n :rtype: np.ndarray with shape (Nsamples, 2)\n \"\"\"\n sample_rate = rate # Sound card dependent,\n tone_duration = duration # sec\n fade_duration = fade # sec\n\n tvec = np.linspace(0, tone_duration, tone_duration * sample_rate)\n tone = amplitude * np.sin(2 * np.pi * frequency * tvec) # tone vec\n\n len_fade = int(fade_duration * sample_rate)\n fade_io = np.hanning(len_fade * 2)\n fadein = fade_io[:len_fade]\n fadeout = fade_io[len_fade:]\n win = np.ones(len(tvec))\n win[:len_fade] = fadein\n win[-len_fade:] = fadeout\n\n tone = tone * win\n ttl = np.ones(len(tone))\n null = np.zeros(len(tone))\n\n if frequency == -1:\n tone = amplitude * np.random.rand(tone.size)\n\n if chans == 'mono':\n sound = np.array(tone)\n elif chans == 'L':\n sound = np.array([tone, null]).T\n elif chans == 'R':\n sound = np.array([null, tone]).T\n elif chans == 'stereo':\n sound = np.array([tone, tone]).T\n elif chans == 'L+TTL':\n sound = np.array([tone, ttl]).T\n elif chans == 'TTL+R':\n sound = np.array([ttl, tone]).T\n\n return sound\n\n\ndef save_bin(sound, file_path):\n \"\"\"\n Save binary file for CFSoundcard upload.\n\n Binary files to be sent to the sound card need to be a single contiguous\n vector of int32 s. 4 Bytes left speaker, 4 Bytes right speaker, ..., etc.\n\n\n :param sound: Stereo sound\n :type sound: 2d numpy.array os shape (n_samples, 2)\n :param file_path: full path (w/ name) of location where to save the file\n :type file_path: str\n \"\"\"\n bin_sound = (sound * ((2**31) - 1)).astype(np.int32)\n\n if bin_sound.flags.f_contiguous:\n bin_sound = np.ascontiguousarray(bin_sound)\n\n bin_save = bin_sound.reshape(1, np.multiply(*bin_sound.shape))\n bin_save = np.ascontiguousarray(bin_save)\n\n with open(file_path, 'wb') as bf:\n bf.writelines(bin_save)\n\n\ndef uplopad(uploader_tool, file_path, index, type_=0, sample_rate=96):\n \"\"\"\n Uploads a bin file to an index of the non volatile memory of the sound card.\n\n :param uploader_tool: path of executable for transferring sounds\n :type uploader_tool: str\n :param file_path: path of file to be uploaded\n :type file_path: str\n :param index: E[2-31] memory bank to upload to\n :type index: int\n :param type_: {0: int32, 1: float32} datatype of binary file, defaults to 0\n :param type_: int, optional\n :param sample_rate: [96, 192] (KHz) playback sample rate, defaults to 96\n :param sample_rate: int, optional\n \"\"\"\n file_name = file_path.split(os.sep)[-1]\n file_folder = file_path.split(os.sep)[:-1]\n subprocess.call([uploader_tool, file_path, index, type_, sample_rate])\n\n log_file = os.path.join(file_folder, 'log')\n with open(log_file, 'a') as f:\n pass\n return\n\n\ndef get_uploaded_sounds():\n pass\n\n\nif __name__ == '__main__':\n sd = configure_sounddevice(output='xonar')\n sd.stop()\n L_TTL = make_sound(chans='L+TTL', amplitude=0.2)\n N_TTL = make_sound(chans='L+TTL', amplitude=-1)\n sd.play(L_TTL, 44100, mapping=[1, 2])\n\n print('i')\n","sub_path":"pybpod_projects/IBL/tasks/basicChoiceWorld/sound.py","file_name":"sound.py","file_ext":"py","file_size_in_byte":5628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"179393425","text":"#!/usr/bin/python3\n# FTP User Class\n# Bernardo Pla - 3885008\n# CNT 4713 - Project 1\n# User dictionary helper class\n\nclass userdict:\n isMatched = False\n\n def __init__(self):\n self.list = []\n\n#handle new user creation\n def newUser(self, user):\n if user not in self.list:\n self.list.append(user)\n\n # retrieve the list contents\n def currentlist(self):\n return self.list\n\n def matchedUsers(self, username):\n global isMatched\n isMatched = False\n try:\n for user in self.list:\n isMatched = True\n return user\n if(isMatched == False):\n print(\"ACCESS GRANTED\")\n except KeyError:\n print(\"GRANTED\")\n\n","sub_path":"ftp-server-client/ftp-server-client/userdict.py","file_name":"userdict.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"287396725","text":"\n\n#calss header\nclass _UNSATURATED():\n\tdef __init__(self,): \n\t\tself.name = \"UNSATURATED\"\n\t\tself.definitions = [u'Unsaturated fat or oil is either monounsaturated or polyunsaturated, found in plants, vegetable oil, and fish, and thought to be better for your health than saturated fat.', u'containing less of a substance than can be absorbed, and therefore not in a state of balance', u'used to describe a hydrocarbon in which the carbon atoms do not join as many hydrogen atoms as possible']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_unsaturated.py","file_name":"_unsaturated.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"33061722","text":"from django.views.generic. base import TemplateView\nfrom django.shortcuts import get_object_or_404, render, redirect\nfrom .forms import ThemeForm, CommentForm, HashtagForm\nfrom .models import Theme, Comment, Hashtag\nfrom django.utils import timezone \n\n\nclass MainpageView(TemplateView):\n template_name = 'theme/main.html'\n\n# Create your views here.\ndef detail(request, theme_id, comment=None):\n theme = get_object_or_404(Theme, id=theme_id)\n if request.method == \"POST\":\n form = CommentForm(request.POST, instance=comment)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.theme_id = theme\n comment.comment_text = form.cleaned_data[\"comment_text\"]\n comment.save()\n return redirect(\"detail\", theme_id)\n else:\n form = CommentForm(instance=comment) \n return render(request, \"theme/detail.html\", {\"theme\": theme, \"form\": form})\n\ndef commentedit(request, theme_id, pk):\n comment = get_object_or_404(Comment, pk=pk)\n return detail(request, theme_id, comment)\n\n\ndef commentremove(request, theme_id, pk):\n comment = get_object_or_404(Comment, pk=pk)\n comment.delete()\n return redirect('detail', theme_id)\n\n\ndef themeform(request, theme=None):\n if request.method == 'POST':\n form = ThemeForm(request.POST, request.FILES, instance=theme)\n if form.is_valid():\n theme = form.save(commit=False)\n theme.published_at = timezone.now()\n theme.save()\n form.save_m2m()\n return redirect('home')\n else:\n form = ThemeForm(instance=theme)\n return render(request,'theme/new.html' , {'form':form})\n\ndef hashtagform(request, hashtag=None):\n if request.method == 'POST':\n form = HashtagForm(request.POST, instance=hashtag)\n if form.is_valid():\n hashtag = form.save(commit=False)\n if Hashtag.objects.filter(name=form.cleaned_data['name']):\n form = HashtagForm()\n error_message = \"이미 존재하는 해시태그 입니다.\"\n return render(request, 'theme/hashtag.html', {'form':form, \"error_message\":error_message})\n else:\n hashtag.name = form.cleaned_data['name']\n hashtag.save()\n return redirect('home')\n else:\n form = HashtagForm(instance=hashtag)\n return render(request, 'theme/hashtag.html', {'form':form})\n\ndef search(request, hashtag_id):\n hashtag = get_object_or_404(Hashtag, id=hashtag_id)\n return render(request, 'theme/search.html', {'hashtag':hashtag}) \n\ndef edit(request, theme_id):\n theme = get_object_or_404(Theme, id=theme_id)\n return themeform(request,theme)\n\ndef remove(request, theme_id):\n theme = get_object_or_404(Theme, id=theme_id)\n theme.delete()\n return redirect('home')\n\ndef main(request):\n return render(request, 'theme/main.html')\n\ndef home(request):\n theme = Theme.objects\n hashtags = Hashtag.objects\n return render(request, 'theme/home.html', {'theme':theme, 'hashtags':hashtags})\n\ndef new(request):\n return render(request, 'theme/new.html')\n\ndef create(request):\n theme= Theme()\n theme.title = request.GET['title']\n theme.body = request.GET['body']\n theme.published_at = timezone.datetime.now()\n theme.save()\n return redirect('/theme/home/')","sub_path":"week5/theme/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"560673048","text":"from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponse, HttpResponseRedirect\nfrom chats.models import Chat, Message, Attachment\nfrom user_profile.models import User, Member\nimport json\nfrom chats.forms import ChatForm, MessageForm, AttachmentForm, AttachmentForm2\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.core.files.images import ImageFile\nfrom django.utils.timezone import now\n\n@login_required\ndef chat_list(request):\t\n\tif request.method == 'GET':\n\t\tchats = Chat.objects.all().filter(members__user__username=request.user.username)\n\t\tif chats.exists():\n\t\t\treturn JsonResponse({'data': list(chats.values('id', 'title'))})\n\t\telse:\n\t\t\treturn JsonResponse({'data': 'Nothing'}, status=404)\n\telse:\n\t\treturn HttpResponseNotAllowed(['GET'])\n\n@login_required\ndef create_chat(request):\n\tif request.method == 'POST':\n\t\tform = ChatForm(request.POST)\n\t\tif form.is_valid:\n\t\t\tchat = form.save()\n\t\t\tmember = Member(chat=chat, user=request.user)\n\t\t\tmember.save()\n\t\t\treturn JsonResponse({\n\t\t\t\t'msg': 'Save success',\n\t\t\t\t'id': chat.id\n\t\t\t})\n\t\treturn render(request, 'create.html', {'form': form})\n\telse:\n\t\tform = ChatForm()\n\treturn render(request, 'create.html', {'form': form})\n\n@login_required\ndef send_message(request):\n\tif request.method == \"POST\":\n\t\tform = MessageForm(request.POST, user=request.user)\n\t\tprint((request.user.members))\n\t\tif form.is_valid():\n\t\t\tpost = form.save()\n\t\t\tmembers = request.user.members\n\t\t\tmembers = members.all().filter(chat=form.cleaned_data['chat']).first()\n\t\t\tmembers.last_read_message = post\n\t\t\tmembers.save()\n\t\t\treturn JsonResponse({\n\t\t\t\t'msg': 'Save success',\n\t\t\t\t'id': post.id\n\t\t\t})\n\t\telse:\n\t\t\treturn render(request, 'create.html', {'form': form})\n\telse:\n\t\tform = MessageForm(user=request.user)\n\t\treturn render(request, 'create.html', {'form': form})\n\n@login_required\ndef read_message(request, title):\n\tif request.method == 'GET':\n\t\tusers = request.user.members.filter(chat__title=title) \n\t\tif users.exists():\n\t\t\tlast_message = Message.objects.last()\n\t\t\tmember = users.first() \n\t\t\tmember.last_read_message = last_message\n\t\t\tmember.save()\n\t\t\treturn HttpResponseRedirect('/chats/message_all/{}'.format(title))\n\t\telse:\n\t\t\treturn JsonResponse({'data': 'Nothing'}, status=404)\n\telse: \n\t\treturn HttpResponseNotAllowed(['GET'])\n\n@login_required\ndef all_message(request, id):\n\tif request.method == 'GET':\n\t\tmember = request.user.members.filter(chat__id=id)\n\t\tif not member.exists():\n\t\t\treturn JsonResponse({'data': 'Nothing'}, status=404)\n\t\tdate = member.first().last_read_message\n\t\tmessages_read = Message.objects.all().filter(chat__id=id).filter(id__lte=date.id)\n\t\tmessages_unread = Message.objects.all().filter(chat__id=id).filter(id__gt=date.id)\n\t\tif messages_read.exists() and messages_unread.exists():\n\t\t\treturn JsonResponse({'Read': list(messages_read.values('id', 'content')), 'Unread': list(messages_unread.values('id', 'content'))})\n\t\telif messages_read.exists():\n\t\t\treturn JsonResponse({'Read': list(messages_read.values('id', 'content'))})\n\t\telse:\n\t\t\treturn JsonResponse({'data': 'Nothing'}, status=404)\n\telse:\n\t\treturn HttpResponseNotAllowed(['GET'])\n\n@login_required\ndef upload_file(request):\n\tif request.method == \"POST\":\n\t\tform = AttachmentForm(request.POST, request.FILES, user=request.user)\n\t\tif form.is_valid():\n\t\t\tpost = form.save() \n\t\t\tmembers = request.user.members\n\t\t\tmembers = members.all().filter(chat=form.cleaned_data['chat']).first()\n\t\t\tmessage = Message(content=\"attach\", chat=form.cleaned_data['chat'], user=request.user)\n\t\t\tmessage.save()\n\t\t\tmembers.last_read_message = message\n\t\t\tmembers.save()\n\t\t\tpost.content_type = request.FILES['url'].content_type\n\t\t\tpost.message = message\n\t\t\tpost.user = request.user\n\t\t\tpost.save()\n\t\t\treturn JsonResponse({\n\t\t\t\t'msg': 'Save success',\n\t\t\t\t'id': post.id\n\t\t\t})\n\t\telse:\n\t\t\treturn render(request, 'create.html', {'form': form})\n\telif request.method == 'GET':\n\t\tform = AttachmentForm(user=request.user)\n\t\treturn render(request, 'create.html', {'form': form})\n\telse:\n\t\treturn HttpResponseNotAllowed(['GET', 'POST'])\n\n@login_required\ndef download_file(request, key):\n\tif request.method == 'GET':\n\t\tattachments = Attachment.objects.all().filter(url='uploads/{}'.format(key))\n\t\tlist_chat = []\n\t\tif attachments.exists():\n\t\t\tattachment = attachments.first()\n\t\t\turl = attachment.url.url\n\t\t\treturn HttpResponseRedirect(url)\n\t\telse:\n\t\t\tprint('Nothing')\n\t\t\tlist_chat.append('Nothing')\n\t\treturn JsonResponse({'data': str(list_chat)}, status=404)\n\telse:\n\t\treturn HttpResponseNotAllowed(['GET'])\n\ndef message_front(request):\n\tif request.method == 'GET':\n\t\tuser = User.objects.all().filter(username=request.GET['user'])\n\t\tmember = user.first().members.filter(chat__id=request.GET['id'])\n\t\tif not member.exists():\n\t\t\treturn JsonResponse({'data': []}, status=404)\n\t\tprint(request.GET['id'])\n\t\tmessages = Message.objects.all().filter(chat__id=request.GET['id'])\n\t\tif messages.exists():\n\t\t\treturn JsonResponse({'data': list(messages.values('id', 'content', 'date', 'user__username'))})\n\t\telse:\n\t\t\treturn JsonResponse({'data': []}, status=404)\n\telse:\n\t\treturn HttpResponseNotAllowed(['GET'])\n\n@csrf_exempt\ndef create_message_front(request):\n\tif request.method == 'POST':\n\t\tchat = Chat.objects.all().get(id=request.GET['id'])\n\t\tuser = User.objects.all().get(username=request.GET['user'])\n\t\tmessage = Message(content=request.GET['content'], chat=chat, user=user)\n\t\tchat.last_message_text = request.GET['content']\n\t\tchat.last_message_date = message.date\n\t\tmessage.save()\n\t\tchat.save()\n\t\treturn JsonResponse({'data' : request.GET})\n\telse:\n\t\treturn HttpResponseNotAllowed(['POST'])\n\ndef create_contact(request):\n\tif request.method == 'GET':\n\t\tcontact = User.objects.all().get(username=request.GET['contact'])\n\t\tuser = User.objects.all().get(username=request.GET['user'])\n\t\tfind_same_chats = Chat.objects.all().filter(is_group_chat=False)\n\t\tfind_same_chats = find_same_chats.filter(members__user=contact).filter(members__user=user)\n\t\tif find_same_chats.exists():\n\t\t\treturn JsonResponse({'data':find_same_chats.first().title})\n\t\tchat = Chat(title='{} {}'.format(contact.username, user.username))\n\t\tchat.save()\n\t\tmember_user = Member(user=user, chat=chat)\n\t\tmember_contact = Member(user=contact, chat=chat)\n\t\tmember_user.save()\n\t\tmember_contact.save()\t\n\t\treturn JsonResponse({'data':chat.title})\n\telse:\n\t\treturn HttpResponseNotAllowed(['GET'])\n\ndef chat_list_front(request):\t\n\tif request.method == 'GET':\n\t\tchats = Chat.objects.all().filter(members__user__username=request.GET['user'])\n\t\tif chats.exists():\n\t\t\treturn JsonResponse({'data': list(chats.values('id', 'title', 'is_group_chat', 'last_message_date', 'last_message_text'))})\n\t\telse:\n\t\t\treturn JsonResponse({'data': []}, status=404)\n\telse:\n\t\treturn HttpResponseNotAllowed(['GET'])\n\n@csrf_exempt\ndef create_chat_front(request):\n\tif request.method == 'POST':\n\t\tchat = Chat(title=request.GET['title'], is_group_chat=True)\n\t\tchat.save()\n\t\tuser = User.objects.get(username=request.GET['user'])\n\t\tmember = Member(chat=chat, user=user)\n\t\tmember.save()\n\t\treturn JsonResponse({\n\t\t\t'msg': 'Save success',\n\t\t\t'id': chat.id\n\t\t})\n\treturn render(request, 'create.html', {'form': form})\n\n@csrf_exempt\ndef add_user_to_chat(request):\n\tif request.method == 'POST':\n\t\tuser = User.objects.get(username=request.GET['user'])\n\t\tchat = Chat.objects.get(id=request.GET['id'])\n\t\tfind_same_member = Member.objects.all().filter(chat=chat, user=user)\n\t\tif find_same_member.exists():\n\t\t\treturn JsonResponse({'data': \"Пользователь уже добавлен в чат\"})\n\t\tmember = Member(user=user, chat=chat)\n\t\tmember.save()\n\t\treturn JsonResponse({\n\t\t\t'msg': 'Save success',\n\t\t\t'id': member.id\n\t\t})\n\telse:\n\t\treturn HttpResponseNotAllowed(['ПУЕ'])\n1234\n@csrf_exempt\ndef upload_front(request):\n\tif request.method == \"POST\":\n\t\tform = AttachmentForm2(request.POST, request.FILES)\n\t\tpost = form.save()\n\t\treturn JsonResponse({ 'msg':post.id })\n\telse:\n\t\tform = AttachmentForm2()\n\t\treturn render(request, 'create.html', {'form': form})\n\ndef chat_members(request):\n\tif request.method == \"GET\":\n\t\tusers = User.objects.all().filter(members__chat__id=request.GET['id'])\n\t\tif users.exists():\n\t\t\treturn JsonResponse({'data': list(users.values('id', 'username'))})\n\t\telse:\n\t\t\treturn JsonResponse({'data': []}, status=404)\n\ndef leave_chat(request):\n\tif request.method == \"GET\":\n\t\tmember = Member.objects.all().filter(chat__id=request.GET['id']).get(user__username=request.GET['user'])\n\t\tif member:\n\t\t\tmember.delete()\n\t\t\treturn JsonResponse({'data': 'success'})\n\telse: \n\t\treturn HttpResponseNotAllowed([\"GET\"])","sub_path":"messenger/chats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"631468118","text":"class Solution(object):\n def findRestaurant(self, list1, list2):\n \"\"\"\n :type list1: List[str]\n :type list2: List[str]\n :rtype: List[str]\n \"\"\"\n res = []\n dict1 = {}\n dict2 = {}\n sum = len(list1) + len(list2) - 2\n for k, v in enumerate(list1):\n dict1[v] = k\n for k, v in enumerate(list2):\n dict2[v] = k\n for i in range(len(list2)):\n if list2[i] in dict1:\n temp_sum = i + dict1[list2[i]]\n if temp_sum < sum:\n sum = temp_sum\n #print(set(list1).intersection(set(list2)))\n for element in set(list1).intersection(set(list2)):\n if dict1[element] + dict2[element] == sum:\n res.append(element)\n return res\n\nif __name__ == \"__main__\":\n solution = Solution()\n list1 = [\"Shogun\", \"Tapioca Express\", \"Burger King\", \"KFC\"]\n list2 = [\"Piatti\", \"The Grill at Torrey Pines\", \"Hungry Hunter Steakhouse\", \"Shogun\"]\n result = solution.findRestaurant(list1, list2)\n print(result)","sub_path":"500-600/599_mininum_index_sum_of_two_lists.py","file_name":"599_mininum_index_sum_of_two_lists.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"326518149","text":"import requests\nimport socket\nfrom datetime import datetime\nfrom bs4 import BeautifulSoup\n\n\n# The QR code id is the input paramenter of the function\ndef qr_validation_vienna(id):\n # issuing authority\n authority = \"City of Vienna\"\n\n # building the final url\n url = id\n\n # requesting the url\n qr_validation = requests.get(url)\n\n # url validation\n status_code = qr_validation.status_code\n\n # webserver check\n if status_code == 200:\n\n # parsing it in HTML\n QR_html = BeautifulSoup(qr_validation.text, \"html.parser\")\n\n # extraction of the required information based on the qr code url\n data = QR_html.find_all(\"p\")\n first_name = data[0].text\n last_name = data[1].text\n date_of_birth = data[2].text\n test_date = data[3].text\n\n # adding a validation time stamp\n current_date = datetime.now()\n test_validation = current_date.strftime(\"%d.%m.%Y %H:%M\")\n\n # validator identification\n validator = socket.gethostname()\n\n # return values\n return first_name, last_name, date_of_birth, test_date, test_validation, authority, id, validator\n\n # city vienna webserver is offline (does not mean that the result is not valid)\n else:\n offline = \"the city vienna webserver is offline\"\n return offline, offline, offline, offline, offline, offline, offline, offline","sub_path":"app/src/QR_vienna.py","file_name":"QR_vienna.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"575001095","text":"from django import forms\nfrom django.db.models import fields\nfrom .models import Portfolio\n\nfrom django_summernote.widgets import SummernoteWidget\n\nclass PortfolioForm(forms.ModelForm):\n class Meta:\n model = Portfolio\n fields = ['pf_title', 'pf_content', 'pf_attach']\n\n # pf_content의 위젯으로 summernote 사용\n widgets = {\n 'pf_content': SummernoteWidget(),\n }\n\n labels = {\n 'pf_title': '제목',\n 'pf_content': '내용',\n 'pf_attach': '첨부파일',\n }","sub_path":"pore/portfolio/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"226878379","text":"import pickle\nimport numpy as np\nimport sys\nimport os\nimport seaborn as sns\nimport matplotlib.pylab as plt\n\n\nos.makedirs(\"img_plots\",exist_ok=True)\n\nprint(\"loading file\")\nwith open(sys.argv[-1],\"rb\") as f:\n #img_np, preact_mean, preact_var, preact_grad = pickle.load(f)\n # img_np, preact_mean, preact_var = pickle.load(f)\n img_np, preact_mean, preact_var, entropy, mask = pickle.load(f)\nprint(\"done.\")\n\nfrom PIL import Image\nimport sys\ndef save_img(A,path,normalize=False):\n im = Image.fromarray(A.astype(np.uint8))\n im = im.resize((224,224))\n im.save(path)\n\nfrom matplotlib import cm\n# colormap = cm.gist_earth\ncolormap_name = 'coolwarm'\ncolormap = cm.get_cmap(colormap_name)\neps = 1e-7\nfns = {\n \"mean\": lambda j: preact_mean[j],\n # \"var\": lambda j: preact_var[j],\n # \"ratio\": lambda j: preact_var[j]/np.expand_dims(np.max(np.abs(preact_mean[j]),axis=-1),-1)\n # \"ratio\": lambda j: np.sqrt(preact_var[j])/np.mean(np.abs(preact_mean[j]),axis=-1, keepdims=True)\n # \"relerror\": lambda j: np.sqrt(np.max(preact_var[j],axis=-1,keepdims=True))/(np.max(preact_mean[j],axis=-1,keepdims=True)+eps)\n # \"relerror\": lambda j: np.mean(np.sqrt(preact_var[j])/(np.abs(preact_mean[j])+eps),axis=-1,keepdims=True)\n # \"relerror\": lambda j: np.sqrt(preact_var[j])/(np.abs(preact_mean[j])+eps)\n}\n\nHEATMAP=False\n\nLOCAL_NORMALIZE=True\nLOCAL_NORMALIZE_LAYERS=[0,27,35,48]\n# LOCAL_NORMALIZE_LAYERS=[0]\n\nfor name,fn in fns.items():\n\n print(\"Plotting \"+name)\n vals = [fn(j) for j in range(len(preact_mean))]\n\n # normalize with global maximum value\n # max_val = 0\n # for p in vals:\n # max_val = max(np.max(p),max_val)\n # print(name+\"_max\",max_val)\n\n global_max = 0.0\n global_min = np.Infinity\n if not LOCAL_NORMALIZE:\n for j,p in enumerate(vals):\n if j in LOCAL_NORMALIZE_LAYERS:\n global_max = np.maximum(np.max(p),global_max)\n global_min = np.minimum(np.min(p),global_min)\n\n for j,p in enumerate(vals):\n # continue\n # # p /= max_val\n if j != 48 and j != 0:\n continue\n # continue\n if len(LOCAL_NORMALIZE_LAYERS)!=0 and j not in LOCAL_NORMALIZE_LAYERS:\n continue\n\n # print(p.shape[0])\n if LOCAL_NORMALIZE:\n print(\"min:\",np.sqrt(np.min(p)), \"max:\", np.sqrt(np.max(p)), \"ratio\",np.sqrt(np.max(p))/np.sqrt(np.min(p)+eps),\"mean_std\",np.mean(np.sqrt(p)))\n else:\n print(\"global min:\",np.sqrt(global_min), \"max:\", global_max, \"ratio\",np.sqrt(global_max)/np.sqrt(global_max+eps),\"mean_std\",np.mean(np.sqrt(p)))\n for k in range(p.shape[0]):\n # for d in range(p.shape[-1]):\n # img = p[k,...,d]\n # # img = np.mean(p[k],axis=-1)\n\n # # normalize\n # img = img/np.max(img)\n\n # # colored\n # save_img(colormap(img*255), \"img_plots/i%i_l%i_d%i_%s.png\" % (k,j,d,name))\n\n img = np.max(p[k],axis=-1)\n # img = np.mean(np.abs(p[k]),axis=-1)\n # if k == 0:\n # print(\"min:\",np.sqrt(np.min(img)), \"max:\", np.sqrt(np.max(img)), \"ratio\",np.sqrt(np.max(img))/np.sqrt(np.min(img)),\"mean_std\",np.mean(np.sqrt(img)))\n if np.min(img) == np.max(img):\n print(\"Min = Max for k=\",k,\" j=\",j)\n continue\n # img = np.log(img+eps)\n if LOCAL_NORMALIZE:\n img = (img-np.min(img))/(np.max(img)-np.min(img)+eps)\n else:\n if j in LOCAL_NORMALIZE_LAYERS:\n img = (img-global_min)/(global_max-global_min)\n # img = np.log(img+eps)\n # img = (img-np.min(img))/(np.max(img)-np.min(img)+eps)\n # img = (img-np.min(img))/(0.5*np.max(img)-np.min(img))\n\n # img = img/np.max(img)\n # img = img/max_val\n if HEATMAP:\n # uniform_data = np.random.rand(10, 12)\n plt.tick_params( which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False)\n ax = sns.heatmap(img, linewidth=0, cmap=colormap_name, rasterized=True)\n plt.show()\n # plt.savefig(\"activation_%i.eps\"%(j),bbox_inches='tight', transparent=\"True\", pad_inches=0)\n else:\n try:\n save_img(colormap(img)*255, \"img_plots/i%i_l%i_mean_%s.png\" % (k,j,name))\n except:\n pass\n\n # greyscale\n # vals[j] *= 255\n # images = np.mean(preact_var[j],axis=-1)\n # images = np.stack([images]*3,axis=-1)\n # save_img(images[0],\"img_plots/preact_var_%i.png\" % j)\n\n# actual plotting\nfor i in range(img_np.shape[0]):\n save_img(img_np[i],\"img_plots/i%i.png\" % i)\n ent = entropy[i,...,0]\n # ent = np.maximum(entropy[i,...,0], 0)\n save_img((ent-np.min(ent))/(np.max(ent)-np.min(ent))*255,\"img_plots/i%i_entropy.png\" % i)\n save_img(mask[i,...,0]*255,\"img_plots/i%i_mask.png\" % i)\n","sub_path":"py/plot_img_activations.py","file_name":"plot_img_activations.py","file_ext":"py","file_size_in_byte":5037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"63"} +{"seq_id":"576753412","text":"\"\"\"\nextfslib is a library which contains Archive class to support writing extfs\nplugins for Midnight Commander.\n\nTested against python 2.7 and mc 4.8.7\n\nChangelog:\n 1.1 Added item pattern, and common git/uid attrs\n 1.0 Initial release\n\nAuthor: Roman 'gryf' Dobosz \nDate: 2013-05-12\nVersion: 1.1\nLicence: BSD\n\"\"\"\nimport os\nimport sys\nimport re\nfrom subprocess import check_output, CalledProcessError\n\n\nclass Archive(object):\n \"\"\"Archive handle. Provides interface to MC's extfs subsystem\"\"\"\n LINE_PAT = re.compile(\"^(?P)\\s\"\n \"(?P)\\s\"\n \"(?P)\\s\"\n \"(?P)\\s\"\n \"(?P)\\s+\"\n \"(?P