code
stringlengths
13
6.09M
order_type
stringclasses
2 values
original_example
dict
step_ids
listlengths
1
5
<|reserved_special_token_0|> <|reserved_special_token_1|> print('Pepito') print('Cumpleaños: 22 de enero') <|reserved_special_token_0|> print('Tengo', edad, 'años') <|reserved_special_token_0|> print('Me gusta la música de', cantante) print('Me gusta cenar', comida) print('Vivo en', ciudad) <|reserved_special_token_1|> print('Pepito') print('Cumpleaños: 22 de enero') edad = 42 print('Tengo', edad, 'años') cantante = 'Suzanne Vega' comida = 'rúcula' ciudad = 'Barcelona' print('Me gusta la música de', cantante) print('Me gusta cenar', comida) print('Vivo en', ciudad) <|reserved_special_token_1|> # Ejercicio 1 print('Pepito') print('Cumpleaños: 22 de enero') edad = 42 print('Tengo', edad, 'años') cantante = 'Suzanne Vega' comida = 'rúcula' ciudad = 'Barcelona' print('Me gusta la música de', cantante) print('Me gusta cenar', comida) print('Vivo en', ciudad)
flexible
{ "blob_id": "f26c624e8ae9711eb835e223407256e60dfc6d6e", "index": 8945, "step-1": "<mask token>\n", "step-2": "print('Pepito')\nprint('Cumpleaños: 22 de enero')\n<mask token>\nprint('Tengo', edad, 'años')\n<mask token>\nprint('Me gusta la música de', cantante)\nprint('Me gusta cenar', comida)\nprint('Vivo en', ciudad)\n", "step-3": "print('Pepito')\nprint('Cumpleaños: 22 de enero')\nedad = 42\nprint('Tengo', edad, 'años')\ncantante = 'Suzanne Vega'\ncomida = 'rúcula'\nciudad = 'Barcelona'\nprint('Me gusta la música de', cantante)\nprint('Me gusta cenar', comida)\nprint('Vivo en', ciudad)\n", "step-4": "# Ejercicio 1\nprint('Pepito')\nprint('Cumpleaños: 22 de enero')\nedad = 42\nprint('Tengo', edad, 'años')\ncantante = 'Suzanne Vega'\ncomida = 'rúcula'\nciudad = 'Barcelona'\nprint('Me gusta la música de', cantante)\nprint('Me gusta cenar', comida)\nprint('Vivo en', ciudad)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#/usr/bin/env python3 """Demonstrates how to do deterministic task generation using l2l""" import random def fixed_random(func): """Create the data""" def _func(self, i): state = random.getstate() if self.deterministic or self.seed is not None: random.seed(self.seed + i) results = func(self, i) random.setstate(state) else: results = func(self, i) return results return _func class RandomTest: def __init__(self, seed=42, deterministic=False): self.seed = seed self.deterministic = deterministic @fixed_random def test_function(self, i): return [random.randint(0, 10) for x in range(10)] rt = RandomTest(0) print(rt.test_function(0)) print(rt.test_function(0)) rt.seed = 1 print(rt.test_function(0)) print(rt.test_function(0))
normal
{ "blob_id": "7ee5779625d53ff1e18f73b20ba5849666f89b55", "index": 2111, "step-1": "<mask token>\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\nrt = RandomTest(0)\nprint(rt.test_function(0))\nprint(rt.test_function(0))\nrt.seed = 1\nprint(rt.test_function(0))\nprint(rt.test_function(0))\n", "step-4": "<mask token>\nimport random\n\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\nrt = RandomTest(0)\nprint(rt.test_function(0))\nprint(rt.test_function(0))\nrt.seed = 1\nprint(rt.test_function(0))\nprint(rt.test_function(0))\n", "step-5": "#/usr/bin/env python3\n\n\"\"\"Demonstrates how to do deterministic task generation using l2l\"\"\"\nimport random\n\ndef fixed_random(func):\n \"\"\"Create the data\"\"\"\n def _func(self, i):\n state = random.getstate()\n if self.deterministic or self.seed is not None:\n random.seed(self.seed + i)\n results = func(self, i)\n random.setstate(state)\n else:\n results = func(self, i)\n return results\n\n return _func\n\n\nclass RandomTest:\n\n def __init__(self, seed=42, deterministic=False):\n self.seed = seed\n self.deterministic = deterministic\n\n @fixed_random\n def test_function(self, i):\n return [random.randint(0, 10) for x in range(10)]\n\n\nrt = RandomTest(0)\nprint(rt.test_function(0))\nprint(rt.test_function(0))\nrt.seed = 1\nprint(rt.test_function(0))\nprint(rt.test_function(0))\n", "step-ids": [ 3, 4, 6, 7, 8 ] }
[ 3, 4, 6, 7, 8 ]
<|reserved_special_token_0|> def _build_url(**kargs): query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize': 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'} query.update(kargs) query_str = '&'.join([f'{key}={val}' for key, val in query.items()]) return f'{url_base}?{query_str}' <|reserved_special_token_0|> def _get_symbol(symbol, **kargs): kargs['symbol'] = symbol kargs['datatype'] = 'csv' req = _request(**kargs) text = req.text header, *text = text.split() text = '\n'.join([l for l in text[::-1]]) csv_str = f'{header}\n{text}' data = Data.load_csv(csv_str) return Security(symbol, data) def get(symbols, **kargs): if not isinstance(symbols, list): symbols = [symbols] result = Securities() for symbol in symbols: kargs['symbol'] = symbol result.add(id=symbol, security=_get_symbol(**kargs)) return result <|reserved_special_token_1|> <|reserved_special_token_0|> def _build_url(**kargs): query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize': 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'} query.update(kargs) query_str = '&'.join([f'{key}={val}' for key, val in query.items()]) return f'{url_base}?{query_str}' def _request(**kargs): url = _build_url(**kargs) return r.get(url) def _get_symbol(symbol, **kargs): kargs['symbol'] = symbol kargs['datatype'] = 'csv' req = _request(**kargs) text = req.text header, *text = text.split() text = '\n'.join([l for l in text[::-1]]) csv_str = f'{header}\n{text}' data = Data.load_csv(csv_str) return Security(symbol, data) def get(symbols, **kargs): if not isinstance(symbols, list): symbols = [symbols] result = Securities() for symbol in symbols: kargs['symbol'] = symbol result.add(id=symbol, security=_get_symbol(**kargs)) return result <|reserved_special_token_1|> <|reserved_special_token_0|> url_base = 'https://www.alphavantage.co/query' def _build_url(**kargs): query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize': 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'} query.update(kargs) query_str = '&'.join([f'{key}={val}' for key, val in query.items()]) return f'{url_base}?{query_str}' def _request(**kargs): url = _build_url(**kargs) return r.get(url) def _get_symbol(symbol, **kargs): kargs['symbol'] = symbol kargs['datatype'] = 'csv' req = _request(**kargs) text = req.text header, *text = text.split() text = '\n'.join([l for l in text[::-1]]) csv_str = f'{header}\n{text}' data = Data.load_csv(csv_str) return Security(symbol, data) def get(symbols, **kargs): if not isinstance(symbols, list): symbols = [symbols] result = Securities() for symbol in symbols: kargs['symbol'] = symbol result.add(id=symbol, security=_get_symbol(**kargs)) return result <|reserved_special_token_1|> import requests as r from .security import Security, Securities from .data import Data url_base = 'https://www.alphavantage.co/query' def _build_url(**kargs): query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize': 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'} query.update(kargs) query_str = '&'.join([f'{key}={val}' for key, val in query.items()]) return f'{url_base}?{query_str}' def _request(**kargs): url = _build_url(**kargs) return r.get(url) def _get_symbol(symbol, **kargs): kargs['symbol'] = symbol kargs['datatype'] = 'csv' req = _request(**kargs) text = req.text header, *text = text.split() text = '\n'.join([l for l in text[::-1]]) csv_str = f'{header}\n{text}' data = Data.load_csv(csv_str) return Security(symbol, data) def get(symbols, **kargs): if not isinstance(symbols, list): symbols = [symbols] result = Securities() for symbol in symbols: kargs['symbol'] = symbol result.add(id=symbol, security=_get_symbol(**kargs)) return result <|reserved_special_token_1|> import requests as r from .security import Security, Securities from .data import Data url_base = 'https://www.alphavantage.co/query' def _build_url(**kargs): query = { 'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize': 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN' } query.update(kargs) query_str = '&'.join([f'{key}={val}' for key, val in query.items()]) return f'{url_base}?{query_str}' def _request(**kargs): url = _build_url(**kargs) return r.get(url) def _get_symbol(symbol, **kargs): kargs['symbol'] = symbol kargs['datatype'] = 'csv' req = _request(**kargs) # Reverse dates to past to present text = req.text header, *text = text.split() text = '\n'.join( [l for l in text[::-1]] ) csv_str = f'{header}\n{text}' data = Data.load_csv(csv_str) return Security(symbol, data) def get(symbols, **kargs): if not isinstance(symbols, list): symbols = [symbols] result = Securities() for symbol in symbols: kargs['symbol'] = symbol result.add( id=symbol, security=_get_symbol(**kargs) ) return result
flexible
{ "blob_id": "e99d3ae82d8eea38d29d6c4f09fdb3858e36ca50", "index": 6518, "step-1": "<mask token>\n\n\ndef _build_url(**kargs):\n query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize':\n 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'}\n query.update(kargs)\n query_str = '&'.join([f'{key}={val}' for key, val in query.items()])\n return f'{url_base}?{query_str}'\n\n\n<mask token>\n\n\ndef _get_symbol(symbol, **kargs):\n kargs['symbol'] = symbol\n kargs['datatype'] = 'csv'\n req = _request(**kargs)\n text = req.text\n header, *text = text.split()\n text = '\\n'.join([l for l in text[::-1]])\n csv_str = f'{header}\\n{text}'\n data = Data.load_csv(csv_str)\n return Security(symbol, data)\n\n\ndef get(symbols, **kargs):\n if not isinstance(symbols, list):\n symbols = [symbols]\n result = Securities()\n for symbol in symbols:\n kargs['symbol'] = symbol\n result.add(id=symbol, security=_get_symbol(**kargs))\n return result\n", "step-2": "<mask token>\n\n\ndef _build_url(**kargs):\n query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize':\n 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'}\n query.update(kargs)\n query_str = '&'.join([f'{key}={val}' for key, val in query.items()])\n return f'{url_base}?{query_str}'\n\n\ndef _request(**kargs):\n url = _build_url(**kargs)\n return r.get(url)\n\n\ndef _get_symbol(symbol, **kargs):\n kargs['symbol'] = symbol\n kargs['datatype'] = 'csv'\n req = _request(**kargs)\n text = req.text\n header, *text = text.split()\n text = '\\n'.join([l for l in text[::-1]])\n csv_str = f'{header}\\n{text}'\n data = Data.load_csv(csv_str)\n return Security(symbol, data)\n\n\ndef get(symbols, **kargs):\n if not isinstance(symbols, list):\n symbols = [symbols]\n result = Securities()\n for symbol in symbols:\n kargs['symbol'] = symbol\n result.add(id=symbol, security=_get_symbol(**kargs))\n return result\n", "step-3": "<mask token>\nurl_base = 'https://www.alphavantage.co/query'\n\n\ndef _build_url(**kargs):\n query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize':\n 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'}\n query.update(kargs)\n query_str = '&'.join([f'{key}={val}' for key, val in query.items()])\n return f'{url_base}?{query_str}'\n\n\ndef _request(**kargs):\n url = _build_url(**kargs)\n return r.get(url)\n\n\ndef _get_symbol(symbol, **kargs):\n kargs['symbol'] = symbol\n kargs['datatype'] = 'csv'\n req = _request(**kargs)\n text = req.text\n header, *text = text.split()\n text = '\\n'.join([l for l in text[::-1]])\n csv_str = f'{header}\\n{text}'\n data = Data.load_csv(csv_str)\n return Security(symbol, data)\n\n\ndef get(symbols, **kargs):\n if not isinstance(symbols, list):\n symbols = [symbols]\n result = Securities()\n for symbol in symbols:\n kargs['symbol'] = symbol\n result.add(id=symbol, security=_get_symbol(**kargs))\n return result\n", "step-4": "import requests as r\nfrom .security import Security, Securities\nfrom .data import Data\nurl_base = 'https://www.alphavantage.co/query'\n\n\ndef _build_url(**kargs):\n query = {'function': 'TIME_SERIES_DAILY', 'symbol': 'SPY', 'outputsize':\n 'full', 'datatype': 'json', 'apikey': 'JPIO2GNGBMFRLGMN'}\n query.update(kargs)\n query_str = '&'.join([f'{key}={val}' for key, val in query.items()])\n return f'{url_base}?{query_str}'\n\n\ndef _request(**kargs):\n url = _build_url(**kargs)\n return r.get(url)\n\n\ndef _get_symbol(symbol, **kargs):\n kargs['symbol'] = symbol\n kargs['datatype'] = 'csv'\n req = _request(**kargs)\n text = req.text\n header, *text = text.split()\n text = '\\n'.join([l for l in text[::-1]])\n csv_str = f'{header}\\n{text}'\n data = Data.load_csv(csv_str)\n return Security(symbol, data)\n\n\ndef get(symbols, **kargs):\n if not isinstance(symbols, list):\n symbols = [symbols]\n result = Securities()\n for symbol in symbols:\n kargs['symbol'] = symbol\n result.add(id=symbol, security=_get_symbol(**kargs))\n return result\n", "step-5": "import requests as r\n\nfrom .security import Security, Securities\nfrom .data import Data\n\n\nurl_base = 'https://www.alphavantage.co/query'\n\ndef _build_url(**kargs):\n\tquery = {\n\t'function': 'TIME_SERIES_DAILY',\n\t'symbol': 'SPY',\n\t'outputsize': 'full',\n\t'datatype': 'json',\n\t'apikey': 'JPIO2GNGBMFRLGMN'\n\t}\n\tquery.update(kargs)\n\t\n\tquery_str = '&'.join([f'{key}={val}' for key, val in query.items()])\n\treturn f'{url_base}?{query_str}'\n\t\ndef _request(**kargs):\n\turl = _build_url(**kargs)\n\treturn r.get(url)\n\ndef _get_symbol(symbol, **kargs):\n\tkargs['symbol'] = symbol\n\tkargs['datatype'] = 'csv'\n\treq = _request(**kargs)\n\t# Reverse dates to past to present\n\ttext = req.text\n\theader, *text = text.split()\n\ttext = '\\n'.join(\n\t\t[l for l in text[::-1]]\n\t)\n\tcsv_str = f'{header}\\n{text}'\n\n\tdata = Data.load_csv(csv_str)\n\treturn Security(symbol, data) \n\t\ndef get(symbols, **kargs):\n\tif not isinstance(symbols, list):\n\t\tsymbols = [symbols]\n\t\t\n\tresult = Securities()\n\tfor symbol in symbols:\n\t\tkargs['symbol'] = symbol\n\t\tresult.add(\n\t\t\tid=symbol,\n\t\t\tsecurity=_get_symbol(**kargs)\n\t\t)\n\treturn result\n\t\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
# -*- coding: utf-8 -*- from __future__ import print_function """phy main CLI tool. Usage: phy --help """ #------------------------------------------------------------------------------ # Imports #------------------------------------------------------------------------------ import sys import os.path as op import argparse from textwrap import dedent import numpy as np from six import exec_, string_types #------------------------------------------------------------------------------ # Parser utilities #------------------------------------------------------------------------------ class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass class Parser(argparse.ArgumentParser): def error(self, message): sys.stderr.write(message + '\n\n') self.print_help() sys.exit(2) _examples = dedent(""" examples: phy -v display the version of phy phy download hybrid_120sec.dat -o data/ download a sample raw data file in `data/` phy describe my_file.kwik display information about a Kwik dataset phy spikesort my_params.prm run the whole suite (spike detection and clustering) phy detect my_params.prm run spike detection on a parameters file phy cluster-auto my_file.kwik run klustakwik on a dataset (after spike detection) phy cluster-manual my_file.kwik run the manual clustering GUI """) #------------------------------------------------------------------------------ # Parser creator #------------------------------------------------------------------------------ class ParserCreator(object): def __init__(self): self.create_main() self.create_download() self.create_traces() self.create_describe() self.create_spikesort() self.create_detect() self.create_auto() self.create_manual() self.create_notebook() @property def parser(self): return self._parser def _add_sub_parser(self, name, desc): p = self._subparsers.add_parser(name, help=desc, description=desc) self._add_options(p) return p def _add_options(self, parser): parser.add_argument('--debug', '-d', action='store_true', help='activate debug logging mode') parser.add_argument('--hide-traceback', action='store_true', help='hide the traceback for cleaner error ' 'messages') parser.add_argument('--profiler', '-p', action='store_true', help='activate the profiler') parser.add_argument('--line-profiler', '-lp', dest='line_profiler', action='store_true', help='activate the line-profiler -- you ' 'need to decorate the functions ' 'to profile with `@profile` ' 'in the code') parser.add_argument('--ipython', '-i', action='store_true', help='launch the script in an interactive ' 'IPython console') parser.add_argument('--pdb', action='store_true', help='activate the Python debugger') def create_main(self): import phy desc = sys.modules['phy'].__doc__ self._parser = Parser(description=desc, epilog=_examples, formatter_class=CustomFormatter, ) self._parser.set_defaults(func=None) self._parser.add_argument('--version', '-v', action='version', version=phy.__version_git__, help='print the version of phy') self._add_options(self._parser) self._subparsers = self._parser.add_subparsers(dest='command', title='subcommand', ) def create_download(self): desc = 'download a sample dataset' p = self._add_sub_parser('download', desc) p.add_argument('file', help='dataset filename') p.add_argument('--output-dir', '-o', help='output directory') p.add_argument('--base', default='cortexlab', choices=('cortexlab', 'github'), help='data repository name: `cortexlab` or `github`', ) p.set_defaults(func=download) def create_describe(self): desc = 'describe a `.kwik` file' p = self._add_sub_parser('describe', desc) p.add_argument('file', help='path to a `.kwik` file') p.add_argument('--clustering', default='main', help='name of the clustering to use') p.set_defaults(func=describe) def create_traces(self): desc = 'show the traces of a raw data file' p = self._add_sub_parser('traces', desc) p.add_argument('file', help='path to a `.kwd` or `.dat` file') p.add_argument('--interval', help='detection interval in seconds (e.g. `0,10`)') p.add_argument('--n-channels', '-n', help='number of channels in the recording ' '(only required when using a flat binary file)') p.add_argument('--dtype', help='NumPy data type ' '(only required when using a flat binary file)', default='int16', ) p.add_argument('--sample-rate', '-s', help='sample rate in Hz ' '(only required when using a flat binary file)') p.set_defaults(func=traces) def create_spikesort(self): desc = 'launch the whole spike sorting pipeline on a `.prm` file' p = self._add_sub_parser('spikesort', desc) p.add_argument('file', help='path to a `.prm` file') p.add_argument('--kwik-path', help='filename of the `.kwik` file ' 'to create (by default, `"experiment_name".kwik`)') p.add_argument('--overwrite', action='store_true', default=False, help='overwrite the `.kwik` file ') p.add_argument('--interval', help='detection interval in seconds (e.g. `0,10`)') p.set_defaults(func=spikesort) def create_detect(self): desc = 'launch the spike detection algorithm on a `.prm` file' p = self._add_sub_parser('detect', desc) p.add_argument('file', help='path to a `.prm` file') p.add_argument('--kwik-path', help='filename of the `.kwik` file ' 'to create (by default, `"experiment_name".kwik`)') p.add_argument('--overwrite', action='store_true', default=False, help='overwrite the `.kwik` file ') p.add_argument('--interval', help='detection interval in seconds (e.g. `0,10`)') p.set_defaults(func=detect) def create_auto(self): desc = 'launch the automatic clustering algorithm on a `.kwik` file' p = self._add_sub_parser('cluster-auto', desc) p.add_argument('file', help='path to a `.kwik` file') p.add_argument('--clustering', default='main', help='name of the clustering to use') p.set_defaults(func=cluster_auto) def create_manual(self): desc = 'launch the manual clustering GUI on a `.kwik` file' p = self._add_sub_parser('cluster-manual', desc) p.add_argument('file', help='path to a `.kwik` file') p.add_argument('--clustering', default='main', help='name of the clustering to use') p.add_argument('--cluster-ids', '-c', help='list of clusters to select initially') p.add_argument('--no-store', action='store_true', default=False, help='do not create the store (faster loading time, ' 'slower GUI)') p.set_defaults(func=cluster_manual) def create_notebook(self): # TODO pass def parse(self, args): try: return self._parser.parse_args(args) except SystemExit as e: if e.code != 0: raise e #------------------------------------------------------------------------------ # Subcommand functions #------------------------------------------------------------------------------ def _get_kwik_path(args): kwik_path = args.file if not op.exists(kwik_path): raise IOError("The file `{}` doesn't exist.".format(kwik_path)) return kwik_path def _create_session(args, **kwargs): from phy.session import Session kwik_path = _get_kwik_path(args) session = Session(kwik_path, **kwargs) return session def describe(args): from phy.io.kwik import KwikModel path = _get_kwik_path(args) model = KwikModel(path, clustering=args.clustering) return 'model.describe()', dict(model=model) def download(args): from phy import download_sample_data download_sample_data(args.file, output_dir=args.output_dir, base=args.base, ) def traces(args): from vispy.app import run from phy.plot.traces import TraceView from phy.io.h5 import open_h5 from phy.io.traces import read_kwd, read_dat path = args.file if path.endswith('.kwd'): f = open_h5(args.file) traces = read_kwd(f) elif path.endswith(('.dat', '.bin')): if not args.n_channels: raise ValueError("Please specify `--n-channels`.") if not args.dtype: raise ValueError("Please specify `--dtype`.") if not args.sample_rate: raise ValueError("Please specify `--sample-rate`.") n_channels = int(args.n_channels) dtype = np.dtype(args.dtype) traces = read_dat(path, dtype=dtype, n_channels=n_channels) start, end = map(int, args.interval.split(',')) sample_rate = float(args.sample_rate) start = int(sample_rate * start) end = int(sample_rate * end) c = TraceView(keys='interactive') c.visual.traces = .01 * traces[start:end, ...] c.show() run() return None, None def detect(args): from phy.io import create_kwik assert args.file.endswith('.prm') kwik_path = args.kwik_path kwik_path = create_kwik(args.file, overwrite=args.overwrite, kwik_path=kwik_path) interval = args.interval if interval is not None: interval = list(map(float, interval.split(','))) # Create the session with the newly-created .kwik file. args.file = kwik_path session = _create_session(args, use_store=False) return ('session.detect(interval=interval)', dict(session=session, interval=interval)) def cluster_auto(args): from phy.utils._misc import _read_python from phy.session import Session assert args.file.endswith('.prm') params = _read_python(args.file) kwik_path = params['experiment_name'] + '.kwik' session = Session(kwik_path) ns = dict(session=session, clustering=args.clustering, ) cmd = ('session.cluster(clustering=clustering)') return (cmd, ns) def spikesort(args): from phy.io import create_kwik assert args.file.endswith('.prm') kwik_path = args.kwik_path kwik_path = create_kwik(args.file, overwrite=args.overwrite, kwik_path=kwik_path, ) # Create the session with the newly-created .kwik file. args.file = kwik_path session = _create_session(args, use_store=False) interval = args.interval if interval is not None: interval = list(map(float, interval.split(','))) ns = dict(session=session, interval=interval, n_s_clusters=100, # TODO: better handling of KK parameters ) cmd = ('session.detect(interval=interval); session.cluster();') return (cmd, ns) def cluster_manual(args): session = _create_session(args, clustering=args.clustering, use_store=not(args.no_store), ) cluster_ids = (list(map(int, args.cluster_ids.split(','))) if args.cluster_ids else None) session.model.describe() from phy.gui import start_qt_app start_qt_app() gui = session.show_gui(cluster_ids=cluster_ids, show=False) print("\nPress `ctrl+h` to see the list of keyboard shortcuts.\n") return 'gui.show()', dict(session=session, gui=gui, requires_qt=True) #------------------------------------------------------------------------------ # Main functions #------------------------------------------------------------------------------ def main(args=None): p = ParserCreator() if args is None: args = sys.argv[1:] elif isinstance(args, string_types): args = args.split(' ') args = p.parse(args) if args is None: return if args.profiler or args.line_profiler: from phy.utils.testing import _enable_profiler, _profile prof = _enable_profiler(args.line_profiler) else: prof = None import phy if args.debug: phy.debug() # Hide the traceback. if args.hide_traceback: def exception_handler(exception_type, exception, traceback): print("{}: {}".format(exception_type.__name__, exception)) sys.excepthook = exception_handler # Activate IPython debugger. if args.pdb: from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1, ) func = args.func if func is None: p.parser.print_help() return out = func(args) if not out: return cmd, ns = out if not cmd: return requires_qt = ns.pop('requires_qt', False) requires_vispy = ns.pop('requires_vispy', False) # Default variables in namespace. ns.update(phy=phy, path=args.file) if 'session' in ns: ns['model'] = ns['session'].model # Interactive mode with IPython. if args.ipython: print("\nStarting IPython...") from IPython import start_ipython args_ipy = ["-i", "-c='{}'".format(cmd)] if requires_qt or requires_vispy: # Activate Qt event loop integration with Qt. args_ipy += ["--gui=qt"] start_ipython(args_ipy, user_ns=ns) else: if not prof: exec_(cmd, {}, ns) else: _profile(prof, cmd, {}, ns) if requires_qt: # Launch the Qt app. from phy.gui import run_qt_app run_qt_app() elif requires_vispy: # Launch the VisPy Qt app. from vispy.app import use_app, run use_app('pyqt4') run() #------------------------------------------------------------------------------ # Entry point #------------------------------------------------------------------------------ if __name__ == '__main__': main()
normal
{ "blob_id": "539523f177e2c3c0e1fb0226d1fcd65463b68a0e", "index": 6576, "step-1": "<mask token>\n\n\nclass Parser(argparse.ArgumentParser):\n\n def error(self, message):\n sys.stderr.write(message + '\\n\\n')\n self.print_help()\n sys.exit(2)\n\n\n<mask token>\n\n\nclass ParserCreator(object):\n\n def __init__(self):\n self.create_main()\n self.create_download()\n self.create_traces()\n self.create_describe()\n self.create_spikesort()\n self.create_detect()\n self.create_auto()\n self.create_manual()\n self.create_notebook()\n\n @property\n def parser(self):\n return self._parser\n\n def _add_sub_parser(self, name, desc):\n p = self._subparsers.add_parser(name, help=desc, description=desc)\n self._add_options(p)\n return p\n\n def _add_options(self, parser):\n parser.add_argument('--debug', '-d', action='store_true', help=\n 'activate debug logging mode')\n parser.add_argument('--hide-traceback', action='store_true', help=\n 'hide the traceback for cleaner error messages')\n parser.add_argument('--profiler', '-p', action='store_true', help=\n 'activate the profiler')\n parser.add_argument('--line-profiler', '-lp', dest='line_profiler',\n action='store_true', help=\n 'activate the line-profiler -- you need to decorate the functions to profile with `@profile` in the code'\n )\n parser.add_argument('--ipython', '-i', action='store_true', help=\n 'launch the script in an interactive IPython console')\n parser.add_argument('--pdb', action='store_true', help=\n 'activate the Python debugger')\n\n def create_main(self):\n import phy\n desc = sys.modules['phy'].__doc__\n self._parser = Parser(description=desc, epilog=_examples,\n formatter_class=CustomFormatter)\n self._parser.set_defaults(func=None)\n self._parser.add_argument('--version', '-v', action='version',\n version=phy.__version_git__, help='print the version of phy')\n self._add_options(self._parser)\n self._subparsers = self._parser.add_subparsers(dest='command',\n title='subcommand')\n\n def create_download(self):\n desc = 'download a sample dataset'\n p = self._add_sub_parser('download', desc)\n p.add_argument('file', help='dataset filename')\n p.add_argument('--output-dir', '-o', help='output directory')\n p.add_argument('--base', default='cortexlab', choices=('cortexlab',\n 'github'), help='data repository name: `cortexlab` or `github`')\n p.set_defaults(func=download)\n\n def create_describe(self):\n desc = 'describe a `.kwik` file'\n p = self._add_sub_parser('describe', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=describe)\n\n def create_traces(self):\n desc = 'show the traces of a raw data file'\n p = self._add_sub_parser('traces', desc)\n p.add_argument('file', help='path to a `.kwd` or `.dat` file')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.add_argument('--n-channels', '-n', help=\n 'number of channels in the recording (only required when using a flat binary file)'\n )\n p.add_argument('--dtype', help=\n 'NumPy data type (only required when using a flat binary file)',\n default='int16')\n p.add_argument('--sample-rate', '-s', help=\n 'sample rate in Hz (only required when using a flat binary file)')\n p.set_defaults(func=traces)\n\n def create_spikesort(self):\n desc = 'launch the whole spike sorting pipeline on a `.prm` file'\n p = self._add_sub_parser('spikesort', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=spikesort)\n\n def create_detect(self):\n desc = 'launch the spike detection algorithm on a `.prm` file'\n p = self._add_sub_parser('detect', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=detect)\n\n def create_auto(self):\n desc = 'launch the automatic clustering algorithm on a `.kwik` file'\n p = self._add_sub_parser('cluster-auto', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=cluster_auto)\n\n def create_manual(self):\n desc = 'launch the manual clustering GUI on a `.kwik` file'\n p = self._add_sub_parser('cluster-manual', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.add_argument('--cluster-ids', '-c', help=\n 'list of clusters to select initially')\n p.add_argument('--no-store', action='store_true', default=False,\n help='do not create the store (faster loading time, slower GUI)')\n p.set_defaults(func=cluster_manual)\n\n def create_notebook(self):\n pass\n\n def parse(self, args):\n try:\n return self._parser.parse_args(args)\n except SystemExit as e:\n if e.code != 0:\n raise e\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.\n RawDescriptionHelpFormatter):\n pass\n\n\nclass Parser(argparse.ArgumentParser):\n\n def error(self, message):\n sys.stderr.write(message + '\\n\\n')\n self.print_help()\n sys.exit(2)\n\n\n<mask token>\n\n\nclass ParserCreator(object):\n\n def __init__(self):\n self.create_main()\n self.create_download()\n self.create_traces()\n self.create_describe()\n self.create_spikesort()\n self.create_detect()\n self.create_auto()\n self.create_manual()\n self.create_notebook()\n\n @property\n def parser(self):\n return self._parser\n\n def _add_sub_parser(self, name, desc):\n p = self._subparsers.add_parser(name, help=desc, description=desc)\n self._add_options(p)\n return p\n\n def _add_options(self, parser):\n parser.add_argument('--debug', '-d', action='store_true', help=\n 'activate debug logging mode')\n parser.add_argument('--hide-traceback', action='store_true', help=\n 'hide the traceback for cleaner error messages')\n parser.add_argument('--profiler', '-p', action='store_true', help=\n 'activate the profiler')\n parser.add_argument('--line-profiler', '-lp', dest='line_profiler',\n action='store_true', help=\n 'activate the line-profiler -- you need to decorate the functions to profile with `@profile` in the code'\n )\n parser.add_argument('--ipython', '-i', action='store_true', help=\n 'launch the script in an interactive IPython console')\n parser.add_argument('--pdb', action='store_true', help=\n 'activate the Python debugger')\n\n def create_main(self):\n import phy\n desc = sys.modules['phy'].__doc__\n self._parser = Parser(description=desc, epilog=_examples,\n formatter_class=CustomFormatter)\n self._parser.set_defaults(func=None)\n self._parser.add_argument('--version', '-v', action='version',\n version=phy.__version_git__, help='print the version of phy')\n self._add_options(self._parser)\n self._subparsers = self._parser.add_subparsers(dest='command',\n title='subcommand')\n\n def create_download(self):\n desc = 'download a sample dataset'\n p = self._add_sub_parser('download', desc)\n p.add_argument('file', help='dataset filename')\n p.add_argument('--output-dir', '-o', help='output directory')\n p.add_argument('--base', default='cortexlab', choices=('cortexlab',\n 'github'), help='data repository name: `cortexlab` or `github`')\n p.set_defaults(func=download)\n\n def create_describe(self):\n desc = 'describe a `.kwik` file'\n p = self._add_sub_parser('describe', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=describe)\n\n def create_traces(self):\n desc = 'show the traces of a raw data file'\n p = self._add_sub_parser('traces', desc)\n p.add_argument('file', help='path to a `.kwd` or `.dat` file')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.add_argument('--n-channels', '-n', help=\n 'number of channels in the recording (only required when using a flat binary file)'\n )\n p.add_argument('--dtype', help=\n 'NumPy data type (only required when using a flat binary file)',\n default='int16')\n p.add_argument('--sample-rate', '-s', help=\n 'sample rate in Hz (only required when using a flat binary file)')\n p.set_defaults(func=traces)\n\n def create_spikesort(self):\n desc = 'launch the whole spike sorting pipeline on a `.prm` file'\n p = self._add_sub_parser('spikesort', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=spikesort)\n\n def create_detect(self):\n desc = 'launch the spike detection algorithm on a `.prm` file'\n p = self._add_sub_parser('detect', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=detect)\n\n def create_auto(self):\n desc = 'launch the automatic clustering algorithm on a `.kwik` file'\n p = self._add_sub_parser('cluster-auto', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=cluster_auto)\n\n def create_manual(self):\n desc = 'launch the manual clustering GUI on a `.kwik` file'\n p = self._add_sub_parser('cluster-manual', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.add_argument('--cluster-ids', '-c', help=\n 'list of clusters to select initially')\n p.add_argument('--no-store', action='store_true', default=False,\n help='do not create the store (faster loading time, slower GUI)')\n p.set_defaults(func=cluster_manual)\n\n def create_notebook(self):\n pass\n\n def parse(self, args):\n try:\n return self._parser.parse_args(args)\n except SystemExit as e:\n if e.code != 0:\n raise e\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.\n RawDescriptionHelpFormatter):\n pass\n\n\nclass Parser(argparse.ArgumentParser):\n\n def error(self, message):\n sys.stderr.write(message + '\\n\\n')\n self.print_help()\n sys.exit(2)\n\n\n<mask token>\n\n\nclass ParserCreator(object):\n\n def __init__(self):\n self.create_main()\n self.create_download()\n self.create_traces()\n self.create_describe()\n self.create_spikesort()\n self.create_detect()\n self.create_auto()\n self.create_manual()\n self.create_notebook()\n\n @property\n def parser(self):\n return self._parser\n\n def _add_sub_parser(self, name, desc):\n p = self._subparsers.add_parser(name, help=desc, description=desc)\n self._add_options(p)\n return p\n\n def _add_options(self, parser):\n parser.add_argument('--debug', '-d', action='store_true', help=\n 'activate debug logging mode')\n parser.add_argument('--hide-traceback', action='store_true', help=\n 'hide the traceback for cleaner error messages')\n parser.add_argument('--profiler', '-p', action='store_true', help=\n 'activate the profiler')\n parser.add_argument('--line-profiler', '-lp', dest='line_profiler',\n action='store_true', help=\n 'activate the line-profiler -- you need to decorate the functions to profile with `@profile` in the code'\n )\n parser.add_argument('--ipython', '-i', action='store_true', help=\n 'launch the script in an interactive IPython console')\n parser.add_argument('--pdb', action='store_true', help=\n 'activate the Python debugger')\n\n def create_main(self):\n import phy\n desc = sys.modules['phy'].__doc__\n self._parser = Parser(description=desc, epilog=_examples,\n formatter_class=CustomFormatter)\n self._parser.set_defaults(func=None)\n self._parser.add_argument('--version', '-v', action='version',\n version=phy.__version_git__, help='print the version of phy')\n self._add_options(self._parser)\n self._subparsers = self._parser.add_subparsers(dest='command',\n title='subcommand')\n\n def create_download(self):\n desc = 'download a sample dataset'\n p = self._add_sub_parser('download', desc)\n p.add_argument('file', help='dataset filename')\n p.add_argument('--output-dir', '-o', help='output directory')\n p.add_argument('--base', default='cortexlab', choices=('cortexlab',\n 'github'), help='data repository name: `cortexlab` or `github`')\n p.set_defaults(func=download)\n\n def create_describe(self):\n desc = 'describe a `.kwik` file'\n p = self._add_sub_parser('describe', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=describe)\n\n def create_traces(self):\n desc = 'show the traces of a raw data file'\n p = self._add_sub_parser('traces', desc)\n p.add_argument('file', help='path to a `.kwd` or `.dat` file')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.add_argument('--n-channels', '-n', help=\n 'number of channels in the recording (only required when using a flat binary file)'\n )\n p.add_argument('--dtype', help=\n 'NumPy data type (only required when using a flat binary file)',\n default='int16')\n p.add_argument('--sample-rate', '-s', help=\n 'sample rate in Hz (only required when using a flat binary file)')\n p.set_defaults(func=traces)\n\n def create_spikesort(self):\n desc = 'launch the whole spike sorting pipeline on a `.prm` file'\n p = self._add_sub_parser('spikesort', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=spikesort)\n\n def create_detect(self):\n desc = 'launch the spike detection algorithm on a `.prm` file'\n p = self._add_sub_parser('detect', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=detect)\n\n def create_auto(self):\n desc = 'launch the automatic clustering algorithm on a `.kwik` file'\n p = self._add_sub_parser('cluster-auto', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=cluster_auto)\n\n def create_manual(self):\n desc = 'launch the manual clustering GUI on a `.kwik` file'\n p = self._add_sub_parser('cluster-manual', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.add_argument('--cluster-ids', '-c', help=\n 'list of clusters to select initially')\n p.add_argument('--no-store', action='store_true', default=False,\n help='do not create the store (faster loading time, slower GUI)')\n p.set_defaults(func=cluster_manual)\n\n def create_notebook(self):\n pass\n\n def parse(self, args):\n try:\n return self._parser.parse_args(args)\n except SystemExit as e:\n if e.code != 0:\n raise e\n\n\ndef _get_kwik_path(args):\n kwik_path = args.file\n if not op.exists(kwik_path):\n raise IOError(\"The file `{}` doesn't exist.\".format(kwik_path))\n return kwik_path\n\n\ndef _create_session(args, **kwargs):\n from phy.session import Session\n kwik_path = _get_kwik_path(args)\n session = Session(kwik_path, **kwargs)\n return session\n\n\ndef describe(args):\n from phy.io.kwik import KwikModel\n path = _get_kwik_path(args)\n model = KwikModel(path, clustering=args.clustering)\n return 'model.describe()', dict(model=model)\n\n\ndef download(args):\n from phy import download_sample_data\n download_sample_data(args.file, output_dir=args.output_dir, base=args.base)\n\n\ndef traces(args):\n from vispy.app import run\n from phy.plot.traces import TraceView\n from phy.io.h5 import open_h5\n from phy.io.traces import read_kwd, read_dat\n path = args.file\n if path.endswith('.kwd'):\n f = open_h5(args.file)\n traces = read_kwd(f)\n elif path.endswith(('.dat', '.bin')):\n if not args.n_channels:\n raise ValueError('Please specify `--n-channels`.')\n if not args.dtype:\n raise ValueError('Please specify `--dtype`.')\n if not args.sample_rate:\n raise ValueError('Please specify `--sample-rate`.')\n n_channels = int(args.n_channels)\n dtype = np.dtype(args.dtype)\n traces = read_dat(path, dtype=dtype, n_channels=n_channels)\n start, end = map(int, args.interval.split(','))\n sample_rate = float(args.sample_rate)\n start = int(sample_rate * start)\n end = int(sample_rate * end)\n c = TraceView(keys='interactive')\n c.visual.traces = 0.01 * traces[start:end, ...]\n c.show()\n run()\n return None, None\n\n\ndef detect(args):\n from phy.io import create_kwik\n assert args.file.endswith('.prm')\n kwik_path = args.kwik_path\n kwik_path = create_kwik(args.file, overwrite=args.overwrite, kwik_path=\n kwik_path)\n interval = args.interval\n if interval is not None:\n interval = list(map(float, interval.split(',')))\n args.file = kwik_path\n session = _create_session(args, use_store=False)\n return 'session.detect(interval=interval)', dict(session=session,\n interval=interval)\n\n\ndef cluster_auto(args):\n from phy.utils._misc import _read_python\n from phy.session import Session\n assert args.file.endswith('.prm')\n params = _read_python(args.file)\n kwik_path = params['experiment_name'] + '.kwik'\n session = Session(kwik_path)\n ns = dict(session=session, clustering=args.clustering)\n cmd = 'session.cluster(clustering=clustering)'\n return cmd, ns\n\n\ndef spikesort(args):\n from phy.io import create_kwik\n assert args.file.endswith('.prm')\n kwik_path = args.kwik_path\n kwik_path = create_kwik(args.file, overwrite=args.overwrite, kwik_path=\n kwik_path)\n args.file = kwik_path\n session = _create_session(args, use_store=False)\n interval = args.interval\n if interval is not None:\n interval = list(map(float, interval.split(',')))\n ns = dict(session=session, interval=interval, n_s_clusters=100)\n cmd = 'session.detect(interval=interval); session.cluster();'\n return cmd, ns\n\n\ndef cluster_manual(args):\n session = _create_session(args, clustering=args.clustering, use_store=\n not args.no_store)\n cluster_ids = list(map(int, args.cluster_ids.split(','))\n ) if args.cluster_ids else None\n session.model.describe()\n from phy.gui import start_qt_app\n start_qt_app()\n gui = session.show_gui(cluster_ids=cluster_ids, show=False)\n print('\\nPress `ctrl+h` to see the list of keyboard shortcuts.\\n')\n return 'gui.show()', dict(session=session, gui=gui, requires_qt=True)\n\n\ndef main(args=None):\n p = ParserCreator()\n if args is None:\n args = sys.argv[1:]\n elif isinstance(args, string_types):\n args = args.split(' ')\n args = p.parse(args)\n if args is None:\n return\n if args.profiler or args.line_profiler:\n from phy.utils.testing import _enable_profiler, _profile\n prof = _enable_profiler(args.line_profiler)\n else:\n prof = None\n import phy\n if args.debug:\n phy.debug()\n if args.hide_traceback:\n\n def exception_handler(exception_type, exception, traceback):\n print('{}: {}'.format(exception_type.__name__, exception))\n sys.excepthook = exception_handler\n if args.pdb:\n from IPython.core import ultratb\n sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme=\n 'Linux', call_pdb=1)\n func = args.func\n if func is None:\n p.parser.print_help()\n return\n out = func(args)\n if not out:\n return\n cmd, ns = out\n if not cmd:\n return\n requires_qt = ns.pop('requires_qt', False)\n requires_vispy = ns.pop('requires_vispy', False)\n ns.update(phy=phy, path=args.file)\n if 'session' in ns:\n ns['model'] = ns['session'].model\n if args.ipython:\n print('\\nStarting IPython...')\n from IPython import start_ipython\n args_ipy = ['-i', \"-c='{}'\".format(cmd)]\n if requires_qt or requires_vispy:\n args_ipy += ['--gui=qt']\n start_ipython(args_ipy, user_ns=ns)\n else:\n if not prof:\n exec_(cmd, {}, ns)\n else:\n _profile(prof, cmd, {}, ns)\n if requires_qt:\n from phy.gui import run_qt_app\n run_qt_app()\n elif requires_vispy:\n from vispy.app import use_app, run\n use_app('pyqt4')\n run()\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "<mask token>\n\n\nclass CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.\n RawDescriptionHelpFormatter):\n pass\n\n\nclass Parser(argparse.ArgumentParser):\n\n def error(self, message):\n sys.stderr.write(message + '\\n\\n')\n self.print_help()\n sys.exit(2)\n\n\n_examples = dedent(\n \"\"\"\n\nexamples:\n phy -v display the version of phy\n phy download hybrid_120sec.dat -o data/\n download a sample raw data file in `data/`\n phy describe my_file.kwik\n display information about a Kwik dataset\n phy spikesort my_params.prm\n run the whole suite (spike detection and clustering)\n phy detect my_params.prm\n run spike detection on a parameters file\n phy cluster-auto my_file.kwik\n run klustakwik on a dataset (after spike detection)\n phy cluster-manual my_file.kwik\n run the manual clustering GUI\n\n\"\"\"\n )\n\n\nclass ParserCreator(object):\n\n def __init__(self):\n self.create_main()\n self.create_download()\n self.create_traces()\n self.create_describe()\n self.create_spikesort()\n self.create_detect()\n self.create_auto()\n self.create_manual()\n self.create_notebook()\n\n @property\n def parser(self):\n return self._parser\n\n def _add_sub_parser(self, name, desc):\n p = self._subparsers.add_parser(name, help=desc, description=desc)\n self._add_options(p)\n return p\n\n def _add_options(self, parser):\n parser.add_argument('--debug', '-d', action='store_true', help=\n 'activate debug logging mode')\n parser.add_argument('--hide-traceback', action='store_true', help=\n 'hide the traceback for cleaner error messages')\n parser.add_argument('--profiler', '-p', action='store_true', help=\n 'activate the profiler')\n parser.add_argument('--line-profiler', '-lp', dest='line_profiler',\n action='store_true', help=\n 'activate the line-profiler -- you need to decorate the functions to profile with `@profile` in the code'\n )\n parser.add_argument('--ipython', '-i', action='store_true', help=\n 'launch the script in an interactive IPython console')\n parser.add_argument('--pdb', action='store_true', help=\n 'activate the Python debugger')\n\n def create_main(self):\n import phy\n desc = sys.modules['phy'].__doc__\n self._parser = Parser(description=desc, epilog=_examples,\n formatter_class=CustomFormatter)\n self._parser.set_defaults(func=None)\n self._parser.add_argument('--version', '-v', action='version',\n version=phy.__version_git__, help='print the version of phy')\n self._add_options(self._parser)\n self._subparsers = self._parser.add_subparsers(dest='command',\n title='subcommand')\n\n def create_download(self):\n desc = 'download a sample dataset'\n p = self._add_sub_parser('download', desc)\n p.add_argument('file', help='dataset filename')\n p.add_argument('--output-dir', '-o', help='output directory')\n p.add_argument('--base', default='cortexlab', choices=('cortexlab',\n 'github'), help='data repository name: `cortexlab` or `github`')\n p.set_defaults(func=download)\n\n def create_describe(self):\n desc = 'describe a `.kwik` file'\n p = self._add_sub_parser('describe', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=describe)\n\n def create_traces(self):\n desc = 'show the traces of a raw data file'\n p = self._add_sub_parser('traces', desc)\n p.add_argument('file', help='path to a `.kwd` or `.dat` file')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.add_argument('--n-channels', '-n', help=\n 'number of channels in the recording (only required when using a flat binary file)'\n )\n p.add_argument('--dtype', help=\n 'NumPy data type (only required when using a flat binary file)',\n default='int16')\n p.add_argument('--sample-rate', '-s', help=\n 'sample rate in Hz (only required when using a flat binary file)')\n p.set_defaults(func=traces)\n\n def create_spikesort(self):\n desc = 'launch the whole spike sorting pipeline on a `.prm` file'\n p = self._add_sub_parser('spikesort', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=spikesort)\n\n def create_detect(self):\n desc = 'launch the spike detection algorithm on a `.prm` file'\n p = self._add_sub_parser('detect', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help=\n 'filename of the `.kwik` file to create (by default, `\"experiment_name\".kwik`)'\n )\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval', help=\n 'detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=detect)\n\n def create_auto(self):\n desc = 'launch the automatic clustering algorithm on a `.kwik` file'\n p = self._add_sub_parser('cluster-auto', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.set_defaults(func=cluster_auto)\n\n def create_manual(self):\n desc = 'launch the manual clustering GUI on a `.kwik` file'\n p = self._add_sub_parser('cluster-manual', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main', help=\n 'name of the clustering to use')\n p.add_argument('--cluster-ids', '-c', help=\n 'list of clusters to select initially')\n p.add_argument('--no-store', action='store_true', default=False,\n help='do not create the store (faster loading time, slower GUI)')\n p.set_defaults(func=cluster_manual)\n\n def create_notebook(self):\n pass\n\n def parse(self, args):\n try:\n return self._parser.parse_args(args)\n except SystemExit as e:\n if e.code != 0:\n raise e\n\n\ndef _get_kwik_path(args):\n kwik_path = args.file\n if not op.exists(kwik_path):\n raise IOError(\"The file `{}` doesn't exist.\".format(kwik_path))\n return kwik_path\n\n\ndef _create_session(args, **kwargs):\n from phy.session import Session\n kwik_path = _get_kwik_path(args)\n session = Session(kwik_path, **kwargs)\n return session\n\n\ndef describe(args):\n from phy.io.kwik import KwikModel\n path = _get_kwik_path(args)\n model = KwikModel(path, clustering=args.clustering)\n return 'model.describe()', dict(model=model)\n\n\ndef download(args):\n from phy import download_sample_data\n download_sample_data(args.file, output_dir=args.output_dir, base=args.base)\n\n\ndef traces(args):\n from vispy.app import run\n from phy.plot.traces import TraceView\n from phy.io.h5 import open_h5\n from phy.io.traces import read_kwd, read_dat\n path = args.file\n if path.endswith('.kwd'):\n f = open_h5(args.file)\n traces = read_kwd(f)\n elif path.endswith(('.dat', '.bin')):\n if not args.n_channels:\n raise ValueError('Please specify `--n-channels`.')\n if not args.dtype:\n raise ValueError('Please specify `--dtype`.')\n if not args.sample_rate:\n raise ValueError('Please specify `--sample-rate`.')\n n_channels = int(args.n_channels)\n dtype = np.dtype(args.dtype)\n traces = read_dat(path, dtype=dtype, n_channels=n_channels)\n start, end = map(int, args.interval.split(','))\n sample_rate = float(args.sample_rate)\n start = int(sample_rate * start)\n end = int(sample_rate * end)\n c = TraceView(keys='interactive')\n c.visual.traces = 0.01 * traces[start:end, ...]\n c.show()\n run()\n return None, None\n\n\ndef detect(args):\n from phy.io import create_kwik\n assert args.file.endswith('.prm')\n kwik_path = args.kwik_path\n kwik_path = create_kwik(args.file, overwrite=args.overwrite, kwik_path=\n kwik_path)\n interval = args.interval\n if interval is not None:\n interval = list(map(float, interval.split(',')))\n args.file = kwik_path\n session = _create_session(args, use_store=False)\n return 'session.detect(interval=interval)', dict(session=session,\n interval=interval)\n\n\ndef cluster_auto(args):\n from phy.utils._misc import _read_python\n from phy.session import Session\n assert args.file.endswith('.prm')\n params = _read_python(args.file)\n kwik_path = params['experiment_name'] + '.kwik'\n session = Session(kwik_path)\n ns = dict(session=session, clustering=args.clustering)\n cmd = 'session.cluster(clustering=clustering)'\n return cmd, ns\n\n\ndef spikesort(args):\n from phy.io import create_kwik\n assert args.file.endswith('.prm')\n kwik_path = args.kwik_path\n kwik_path = create_kwik(args.file, overwrite=args.overwrite, kwik_path=\n kwik_path)\n args.file = kwik_path\n session = _create_session(args, use_store=False)\n interval = args.interval\n if interval is not None:\n interval = list(map(float, interval.split(',')))\n ns = dict(session=session, interval=interval, n_s_clusters=100)\n cmd = 'session.detect(interval=interval); session.cluster();'\n return cmd, ns\n\n\ndef cluster_manual(args):\n session = _create_session(args, clustering=args.clustering, use_store=\n not args.no_store)\n cluster_ids = list(map(int, args.cluster_ids.split(','))\n ) if args.cluster_ids else None\n session.model.describe()\n from phy.gui import start_qt_app\n start_qt_app()\n gui = session.show_gui(cluster_ids=cluster_ids, show=False)\n print('\\nPress `ctrl+h` to see the list of keyboard shortcuts.\\n')\n return 'gui.show()', dict(session=session, gui=gui, requires_qt=True)\n\n\ndef main(args=None):\n p = ParserCreator()\n if args is None:\n args = sys.argv[1:]\n elif isinstance(args, string_types):\n args = args.split(' ')\n args = p.parse(args)\n if args is None:\n return\n if args.profiler or args.line_profiler:\n from phy.utils.testing import _enable_profiler, _profile\n prof = _enable_profiler(args.line_profiler)\n else:\n prof = None\n import phy\n if args.debug:\n phy.debug()\n if args.hide_traceback:\n\n def exception_handler(exception_type, exception, traceback):\n print('{}: {}'.format(exception_type.__name__, exception))\n sys.excepthook = exception_handler\n if args.pdb:\n from IPython.core import ultratb\n sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme=\n 'Linux', call_pdb=1)\n func = args.func\n if func is None:\n p.parser.print_help()\n return\n out = func(args)\n if not out:\n return\n cmd, ns = out\n if not cmd:\n return\n requires_qt = ns.pop('requires_qt', False)\n requires_vispy = ns.pop('requires_vispy', False)\n ns.update(phy=phy, path=args.file)\n if 'session' in ns:\n ns['model'] = ns['session'].model\n if args.ipython:\n print('\\nStarting IPython...')\n from IPython import start_ipython\n args_ipy = ['-i', \"-c='{}'\".format(cmd)]\n if requires_qt or requires_vispy:\n args_ipy += ['--gui=qt']\n start_ipython(args_ipy, user_ns=ns)\n else:\n if not prof:\n exec_(cmd, {}, ns)\n else:\n _profile(prof, cmd, {}, ns)\n if requires_qt:\n from phy.gui import run_qt_app\n run_qt_app()\n elif requires_vispy:\n from vispy.app import use_app, run\n use_app('pyqt4')\n run()\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\n\"\"\"phy main CLI tool.\n\nUsage:\n\n phy --help\n\n\"\"\"\n\n#------------------------------------------------------------------------------\n# Imports\n#------------------------------------------------------------------------------\n\nimport sys\nimport os.path as op\nimport argparse\nfrom textwrap import dedent\n\nimport numpy as np\nfrom six import exec_, string_types\n\n\n#------------------------------------------------------------------------------\n# Parser utilities\n#------------------------------------------------------------------------------\n\nclass CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,\n argparse.RawDescriptionHelpFormatter):\n pass\n\n\nclass Parser(argparse.ArgumentParser):\n def error(self, message):\n sys.stderr.write(message + '\\n\\n')\n self.print_help()\n sys.exit(2)\n\n\n_examples = dedent(\"\"\"\n\nexamples:\n phy -v display the version of phy\n phy download hybrid_120sec.dat -o data/\n download a sample raw data file in `data/`\n phy describe my_file.kwik\n display information about a Kwik dataset\n phy spikesort my_params.prm\n run the whole suite (spike detection and clustering)\n phy detect my_params.prm\n run spike detection on a parameters file\n phy cluster-auto my_file.kwik\n run klustakwik on a dataset (after spike detection)\n phy cluster-manual my_file.kwik\n run the manual clustering GUI\n\n\"\"\")\n\n\n#------------------------------------------------------------------------------\n# Parser creator\n#------------------------------------------------------------------------------\n\nclass ParserCreator(object):\n def __init__(self):\n self.create_main()\n self.create_download()\n self.create_traces()\n self.create_describe()\n self.create_spikesort()\n self.create_detect()\n self.create_auto()\n self.create_manual()\n self.create_notebook()\n\n @property\n def parser(self):\n return self._parser\n\n def _add_sub_parser(self, name, desc):\n p = self._subparsers.add_parser(name, help=desc, description=desc)\n self._add_options(p)\n return p\n\n def _add_options(self, parser):\n parser.add_argument('--debug', '-d',\n action='store_true',\n help='activate debug logging mode')\n\n parser.add_argument('--hide-traceback',\n action='store_true',\n help='hide the traceback for cleaner error '\n 'messages')\n\n parser.add_argument('--profiler', '-p',\n action='store_true',\n help='activate the profiler')\n\n parser.add_argument('--line-profiler', '-lp',\n dest='line_profiler',\n action='store_true',\n help='activate the line-profiler -- you '\n 'need to decorate the functions '\n 'to profile with `@profile` '\n 'in the code')\n\n parser.add_argument('--ipython', '-i', action='store_true',\n help='launch the script in an interactive '\n 'IPython console')\n\n parser.add_argument('--pdb', action='store_true',\n help='activate the Python debugger')\n\n def create_main(self):\n import phy\n\n desc = sys.modules['phy'].__doc__\n self._parser = Parser(description=desc,\n epilog=_examples,\n formatter_class=CustomFormatter,\n )\n self._parser.set_defaults(func=None)\n self._parser.add_argument('--version', '-v',\n action='version',\n version=phy.__version_git__,\n help='print the version of phy')\n self._add_options(self._parser)\n self._subparsers = self._parser.add_subparsers(dest='command',\n title='subcommand',\n )\n\n def create_download(self):\n desc = 'download a sample dataset'\n p = self._add_sub_parser('download', desc)\n p.add_argument('file', help='dataset filename')\n p.add_argument('--output-dir', '-o', help='output directory')\n p.add_argument('--base',\n default='cortexlab',\n choices=('cortexlab', 'github'),\n help='data repository name: `cortexlab` or `github`',\n )\n p.set_defaults(func=download)\n\n def create_describe(self):\n desc = 'describe a `.kwik` file'\n p = self._add_sub_parser('describe', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main',\n help='name of the clustering to use')\n p.set_defaults(func=describe)\n\n def create_traces(self):\n desc = 'show the traces of a raw data file'\n p = self._add_sub_parser('traces', desc)\n p.add_argument('file', help='path to a `.kwd` or `.dat` file')\n p.add_argument('--interval',\n help='detection interval in seconds (e.g. `0,10`)')\n p.add_argument('--n-channels', '-n',\n help='number of channels in the recording '\n '(only required when using a flat binary file)')\n p.add_argument('--dtype',\n help='NumPy data type '\n '(only required when using a flat binary file)',\n default='int16',\n )\n p.add_argument('--sample-rate', '-s',\n help='sample rate in Hz '\n '(only required when using a flat binary file)')\n p.set_defaults(func=traces)\n\n def create_spikesort(self):\n desc = 'launch the whole spike sorting pipeline on a `.prm` file'\n p = self._add_sub_parser('spikesort', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help='filename of the `.kwik` file '\n 'to create (by default, `\"experiment_name\".kwik`)')\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval',\n help='detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=spikesort)\n\n def create_detect(self):\n desc = 'launch the spike detection algorithm on a `.prm` file'\n p = self._add_sub_parser('detect', desc)\n p.add_argument('file', help='path to a `.prm` file')\n p.add_argument('--kwik-path', help='filename of the `.kwik` file '\n 'to create (by default, `\"experiment_name\".kwik`)')\n p.add_argument('--overwrite', action='store_true', default=False,\n help='overwrite the `.kwik` file ')\n p.add_argument('--interval',\n help='detection interval in seconds (e.g. `0,10`)')\n p.set_defaults(func=detect)\n\n def create_auto(self):\n desc = 'launch the automatic clustering algorithm on a `.kwik` file'\n p = self._add_sub_parser('cluster-auto', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main',\n help='name of the clustering to use')\n p.set_defaults(func=cluster_auto)\n\n def create_manual(self):\n desc = 'launch the manual clustering GUI on a `.kwik` file'\n p = self._add_sub_parser('cluster-manual', desc)\n p.add_argument('file', help='path to a `.kwik` file')\n p.add_argument('--clustering', default='main',\n help='name of the clustering to use')\n p.add_argument('--cluster-ids', '-c',\n help='list of clusters to select initially')\n p.add_argument('--no-store', action='store_true', default=False,\n help='do not create the store (faster loading time, '\n 'slower GUI)')\n p.set_defaults(func=cluster_manual)\n\n def create_notebook(self):\n # TODO\n pass\n\n def parse(self, args):\n try:\n return self._parser.parse_args(args)\n except SystemExit as e:\n if e.code != 0:\n raise e\n\n\n#------------------------------------------------------------------------------\n# Subcommand functions\n#------------------------------------------------------------------------------\n\ndef _get_kwik_path(args):\n kwik_path = args.file\n\n if not op.exists(kwik_path):\n raise IOError(\"The file `{}` doesn't exist.\".format(kwik_path))\n\n return kwik_path\n\n\ndef _create_session(args, **kwargs):\n from phy.session import Session\n kwik_path = _get_kwik_path(args)\n session = Session(kwik_path, **kwargs)\n return session\n\n\ndef describe(args):\n from phy.io.kwik import KwikModel\n path = _get_kwik_path(args)\n model = KwikModel(path, clustering=args.clustering)\n return 'model.describe()', dict(model=model)\n\n\ndef download(args):\n from phy import download_sample_data\n download_sample_data(args.file,\n output_dir=args.output_dir,\n base=args.base,\n )\n\n\ndef traces(args):\n from vispy.app import run\n from phy.plot.traces import TraceView\n from phy.io.h5 import open_h5\n from phy.io.traces import read_kwd, read_dat\n\n path = args.file\n if path.endswith('.kwd'):\n f = open_h5(args.file)\n traces = read_kwd(f)\n elif path.endswith(('.dat', '.bin')):\n if not args.n_channels:\n raise ValueError(\"Please specify `--n-channels`.\")\n if not args.dtype:\n raise ValueError(\"Please specify `--dtype`.\")\n if not args.sample_rate:\n raise ValueError(\"Please specify `--sample-rate`.\")\n n_channels = int(args.n_channels)\n dtype = np.dtype(args.dtype)\n traces = read_dat(path, dtype=dtype, n_channels=n_channels)\n\n start, end = map(int, args.interval.split(','))\n sample_rate = float(args.sample_rate)\n start = int(sample_rate * start)\n end = int(sample_rate * end)\n\n c = TraceView(keys='interactive')\n c.visual.traces = .01 * traces[start:end, ...]\n c.show()\n run()\n\n return None, None\n\n\ndef detect(args):\n from phy.io import create_kwik\n\n assert args.file.endswith('.prm')\n kwik_path = args.kwik_path\n kwik_path = create_kwik(args.file,\n overwrite=args.overwrite,\n kwik_path=kwik_path)\n\n interval = args.interval\n if interval is not None:\n interval = list(map(float, interval.split(',')))\n\n # Create the session with the newly-created .kwik file.\n args.file = kwik_path\n session = _create_session(args, use_store=False)\n return ('session.detect(interval=interval)',\n dict(session=session, interval=interval))\n\n\ndef cluster_auto(args):\n from phy.utils._misc import _read_python\n from phy.session import Session\n\n assert args.file.endswith('.prm')\n\n params = _read_python(args.file)\n kwik_path = params['experiment_name'] + '.kwik'\n session = Session(kwik_path)\n\n ns = dict(session=session,\n clustering=args.clustering,\n )\n cmd = ('session.cluster(clustering=clustering)')\n return (cmd, ns)\n\n\ndef spikesort(args):\n from phy.io import create_kwik\n\n assert args.file.endswith('.prm')\n kwik_path = args.kwik_path\n kwik_path = create_kwik(args.file,\n overwrite=args.overwrite,\n kwik_path=kwik_path,\n )\n # Create the session with the newly-created .kwik file.\n args.file = kwik_path\n session = _create_session(args, use_store=False)\n\n interval = args.interval\n if interval is not None:\n interval = list(map(float, interval.split(',')))\n\n ns = dict(session=session,\n interval=interval,\n n_s_clusters=100, # TODO: better handling of KK parameters\n )\n cmd = ('session.detect(interval=interval); session.cluster();')\n return (cmd, ns)\n\n\ndef cluster_manual(args):\n session = _create_session(args,\n clustering=args.clustering,\n use_store=not(args.no_store),\n )\n cluster_ids = (list(map(int, args.cluster_ids.split(',')))\n if args.cluster_ids else None)\n\n session.model.describe()\n\n from phy.gui import start_qt_app\n start_qt_app()\n\n gui = session.show_gui(cluster_ids=cluster_ids, show=False)\n print(\"\\nPress `ctrl+h` to see the list of keyboard shortcuts.\\n\")\n return 'gui.show()', dict(session=session, gui=gui, requires_qt=True)\n\n\n#------------------------------------------------------------------------------\n# Main functions\n#------------------------------------------------------------------------------\n\ndef main(args=None):\n p = ParserCreator()\n if args is None:\n args = sys.argv[1:]\n elif isinstance(args, string_types):\n args = args.split(' ')\n args = p.parse(args)\n if args is None:\n return\n\n if args.profiler or args.line_profiler:\n from phy.utils.testing import _enable_profiler, _profile\n prof = _enable_profiler(args.line_profiler)\n else:\n prof = None\n\n import phy\n if args.debug:\n phy.debug()\n\n # Hide the traceback.\n if args.hide_traceback:\n def exception_handler(exception_type, exception, traceback):\n print(\"{}: {}\".format(exception_type.__name__, exception))\n\n sys.excepthook = exception_handler\n\n # Activate IPython debugger.\n if args.pdb:\n from IPython.core import ultratb\n sys.excepthook = ultratb.FormattedTB(mode='Verbose',\n color_scheme='Linux',\n call_pdb=1,\n )\n\n func = args.func\n if func is None:\n p.parser.print_help()\n return\n\n out = func(args)\n if not out:\n return\n cmd, ns = out\n if not cmd:\n return\n requires_qt = ns.pop('requires_qt', False)\n requires_vispy = ns.pop('requires_vispy', False)\n\n # Default variables in namespace.\n ns.update(phy=phy, path=args.file)\n if 'session' in ns:\n ns['model'] = ns['session'].model\n\n # Interactive mode with IPython.\n if args.ipython:\n print(\"\\nStarting IPython...\")\n from IPython import start_ipython\n args_ipy = [\"-i\", \"-c='{}'\".format(cmd)]\n if requires_qt or requires_vispy:\n # Activate Qt event loop integration with Qt.\n args_ipy += [\"--gui=qt\"]\n start_ipython(args_ipy, user_ns=ns)\n else:\n if not prof:\n exec_(cmd, {}, ns)\n else:\n _profile(prof, cmd, {}, ns)\n\n if requires_qt:\n # Launch the Qt app.\n from phy.gui import run_qt_app\n run_qt_app()\n elif requires_vispy:\n # Launch the VisPy Qt app.\n from vispy.app import use_app, run\n use_app('pyqt4')\n run()\n\n\n#------------------------------------------------------------------------------\n# Entry point\n#------------------------------------------------------------------------------\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 17, 18, 29, 30, 32 ] }
[ 17, 18, 29, 30, 32 ]
import random import datetime import os import time import json # l_target_path = "E:/code/PYTHON_TRAINING/Training/Apr2020/BillingSystem/bills/" while True: l_store_id = random.randint(1, 4) now = datetime.datetime.now() l_bill_id = now.strftime("%Y%m%d%H%M%S") # Generate Random Date start_date = datetime.date(2000, 1, 1) end_date = datetime.date(2020, 1, 1) time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_number_of_days = random.randrange(days_between_dates) l_date = start_date + datetime.timedelta(days=random_number_of_days) l_bill_details = {} for i in range(random.randint(1, 25)): l_prod_id = random.randint(1,25) l_qty = random.randint(1,20) l_bill_details[l_prod_id] = l_qty l_data = { "bill_id":l_bill_id ,"store_id":l_store_id ,"bill_date":l_date ,"bill_details":l_bill_details} print(l_data) #json.dumps(l_data) new_file = open(l_target_path + l_bill_id + ".json", "w") new_file.write(str(l_data)) new_file.close() time.sleep(3)
normal
{ "blob_id": "fad2ad89e4d0f04fad61e27048397a5702870ca9", "index": 6177, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile True:\n l_store_id = random.randint(1, 4)\n now = datetime.datetime.now()\n l_bill_id = now.strftime('%Y%m%d%H%M%S')\n start_date = datetime.date(2000, 1, 1)\n end_date = datetime.date(2020, 1, 1)\n time_between_dates = end_date - start_date\n days_between_dates = time_between_dates.days\n random_number_of_days = random.randrange(days_between_dates)\n l_date = start_date + datetime.timedelta(days=random_number_of_days)\n l_bill_details = {}\n for i in range(random.randint(1, 25)):\n l_prod_id = random.randint(1, 25)\n l_qty = random.randint(1, 20)\n l_bill_details[l_prod_id] = l_qty\n l_data = {'bill_id': l_bill_id, 'store_id': l_store_id, 'bill_date':\n l_date, 'bill_details': l_bill_details}\n print(l_data)\n new_file = open(l_target_path + l_bill_id + '.json', 'w')\n new_file.write(str(l_data))\n new_file.close()\n time.sleep(3)\n", "step-3": "<mask token>\nl_target_path = 'E:/code/PYTHON_TRAINING/Training/Apr2020/BillingSystem/bills/'\nwhile True:\n l_store_id = random.randint(1, 4)\n now = datetime.datetime.now()\n l_bill_id = now.strftime('%Y%m%d%H%M%S')\n start_date = datetime.date(2000, 1, 1)\n end_date = datetime.date(2020, 1, 1)\n time_between_dates = end_date - start_date\n days_between_dates = time_between_dates.days\n random_number_of_days = random.randrange(days_between_dates)\n l_date = start_date + datetime.timedelta(days=random_number_of_days)\n l_bill_details = {}\n for i in range(random.randint(1, 25)):\n l_prod_id = random.randint(1, 25)\n l_qty = random.randint(1, 20)\n l_bill_details[l_prod_id] = l_qty\n l_data = {'bill_id': l_bill_id, 'store_id': l_store_id, 'bill_date':\n l_date, 'bill_details': l_bill_details}\n print(l_data)\n new_file = open(l_target_path + l_bill_id + '.json', 'w')\n new_file.write(str(l_data))\n new_file.close()\n time.sleep(3)\n", "step-4": "import random\nimport datetime\nimport os\nimport time\nimport json\nl_target_path = 'E:/code/PYTHON_TRAINING/Training/Apr2020/BillingSystem/bills/'\nwhile True:\n l_store_id = random.randint(1, 4)\n now = datetime.datetime.now()\n l_bill_id = now.strftime('%Y%m%d%H%M%S')\n start_date = datetime.date(2000, 1, 1)\n end_date = datetime.date(2020, 1, 1)\n time_between_dates = end_date - start_date\n days_between_dates = time_between_dates.days\n random_number_of_days = random.randrange(days_between_dates)\n l_date = start_date + datetime.timedelta(days=random_number_of_days)\n l_bill_details = {}\n for i in range(random.randint(1, 25)):\n l_prod_id = random.randint(1, 25)\n l_qty = random.randint(1, 20)\n l_bill_details[l_prod_id] = l_qty\n l_data = {'bill_id': l_bill_id, 'store_id': l_store_id, 'bill_date':\n l_date, 'bill_details': l_bill_details}\n print(l_data)\n new_file = open(l_target_path + l_bill_id + '.json', 'w')\n new_file.write(str(l_data))\n new_file.close()\n time.sleep(3)\n", "step-5": "import random\nimport datetime\nimport os\nimport time\nimport json\n\n#\nl_target_path = \"E:/code/PYTHON_TRAINING/Training/Apr2020/BillingSystem/bills/\"\n\n\nwhile True:\n\n l_store_id = random.randint(1, 4)\n now = datetime.datetime.now()\n l_bill_id = now.strftime(\"%Y%m%d%H%M%S\")\n\n\n # Generate Random Date\n start_date = datetime.date(2000, 1, 1)\n end_date = datetime.date(2020, 1, 1)\n time_between_dates = end_date - start_date\n days_between_dates = time_between_dates.days\n random_number_of_days = random.randrange(days_between_dates)\n\n l_date = start_date + datetime.timedelta(days=random_number_of_days)\n\n l_bill_details = {}\n\n for i in range(random.randint(1, 25)):\n\n l_prod_id = random.randint(1,25)\n l_qty = random.randint(1,20)\n l_bill_details[l_prod_id] = l_qty\n\n l_data = { \"bill_id\":l_bill_id\n ,\"store_id\":l_store_id\n ,\"bill_date\":l_date\n ,\"bill_details\":l_bill_details}\n \n print(l_data) #json.dumps(l_data)\n\n new_file = open(l_target_path + l_bill_id + \".json\", \"w\")\n new_file.write(str(l_data))\n new_file.close()\n\n\n time.sleep(3)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from __future__ import annotations from typing import TYPE_CHECKING import abc import tcod.event if TYPE_CHECKING: from tcodplus.canvas import Canvas from tcodplus.event import CanvasDispatcher class IDrawable(abc.ABC): @property @abc.abstractmethod def force_redraw(self) -> bool: pass @property @force_redraw.setter def force_redraw(self, value: bool) -> None: pass @abc.abstractmethod def draw(self, dest: Canvas) -> None: pass @abc.abstractmethod def base_drawing(self, console: tcod.console.Console) -> None: pass class IFocusable(abc.ABC): @property @abc.abstractmethod def focus_dispatcher(self) -> CanvasDispatcher: pass class IMouseFocusable(IFocusable): @abc.abstractmethod def mousefocus(self, event: tcod.event.MouseMotion) -> bool: pass class IKeyboardFocusable(IFocusable): @property @abc.abstractmethod def kbdfocus(self) -> bool: pass @kbdfocus.setter @abc.abstractmethod def kbdfocus(self, val: bool) -> None: pass @property @abc.abstractmethod def kbdfocus_requested(self) -> bool: pass @kbdfocus_requested.setter @abc.abstractmethod def kbdfocus_requested(self, val: bool) -> None: pass class IUpdatable(abc.ABC): @property @abc.abstractmethod def should_update(self) -> bool: pass @should_update.setter @abc.abstractmethod def should_update(self, value: bool) -> None: pass @abc.abstractmethod def update(self) -> None: pass
normal
{ "blob_id": "e37f958191c9481c6664e90c17f43419a0b5b606", "index": 8131, "step-1": "<mask token>\n\n\nclass IDrawable(abc.ABC):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass IFocusable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def focus_dispatcher(self) ->CanvasDispatcher:\n pass\n\n\nclass IMouseFocusable(IFocusable):\n\n @abc.abstractmethod\n def mousefocus(self, event: tcod.event.MouseMotion) ->bool:\n pass\n\n\nclass IKeyboardFocusable(IFocusable):\n\n @property\n @abc.abstractmethod\n def kbdfocus(self) ->bool:\n pass\n\n @kbdfocus.setter\n @abc.abstractmethod\n def kbdfocus(self, val: bool) ->None:\n pass\n\n @property\n @abc.abstractmethod\n def kbdfocus_requested(self) ->bool:\n pass\n\n @kbdfocus_requested.setter\n @abc.abstractmethod\n def kbdfocus_requested(self, val: bool) ->None:\n pass\n\n\nclass IUpdatable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def should_update(self) ->bool:\n pass\n\n @should_update.setter\n @abc.abstractmethod\n def should_update(self, value: bool) ->None:\n pass\n\n @abc.abstractmethod\n def update(self) ->None:\n pass\n", "step-2": "<mask token>\n\n\nclass IDrawable(abc.ABC):\n <mask token>\n <mask token>\n <mask token>\n\n @abc.abstractmethod\n def base_drawing(self, console: tcod.console.Console) ->None:\n pass\n\n\nclass IFocusable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def focus_dispatcher(self) ->CanvasDispatcher:\n pass\n\n\nclass IMouseFocusable(IFocusable):\n\n @abc.abstractmethod\n def mousefocus(self, event: tcod.event.MouseMotion) ->bool:\n pass\n\n\nclass IKeyboardFocusable(IFocusable):\n\n @property\n @abc.abstractmethod\n def kbdfocus(self) ->bool:\n pass\n\n @kbdfocus.setter\n @abc.abstractmethod\n def kbdfocus(self, val: bool) ->None:\n pass\n\n @property\n @abc.abstractmethod\n def kbdfocus_requested(self) ->bool:\n pass\n\n @kbdfocus_requested.setter\n @abc.abstractmethod\n def kbdfocus_requested(self, val: bool) ->None:\n pass\n\n\nclass IUpdatable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def should_update(self) ->bool:\n pass\n\n @should_update.setter\n @abc.abstractmethod\n def should_update(self, value: bool) ->None:\n pass\n\n @abc.abstractmethod\n def update(self) ->None:\n pass\n", "step-3": "<mask token>\n\n\nclass IDrawable(abc.ABC):\n <mask token>\n\n @property\n @force_redraw.setter\n def force_redraw(self, value: bool) ->None:\n pass\n\n @abc.abstractmethod\n def draw(self, dest: Canvas) ->None:\n pass\n\n @abc.abstractmethod\n def base_drawing(self, console: tcod.console.Console) ->None:\n pass\n\n\nclass IFocusable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def focus_dispatcher(self) ->CanvasDispatcher:\n pass\n\n\nclass IMouseFocusable(IFocusable):\n\n @abc.abstractmethod\n def mousefocus(self, event: tcod.event.MouseMotion) ->bool:\n pass\n\n\nclass IKeyboardFocusable(IFocusable):\n\n @property\n @abc.abstractmethod\n def kbdfocus(self) ->bool:\n pass\n\n @kbdfocus.setter\n @abc.abstractmethod\n def kbdfocus(self, val: bool) ->None:\n pass\n\n @property\n @abc.abstractmethod\n def kbdfocus_requested(self) ->bool:\n pass\n\n @kbdfocus_requested.setter\n @abc.abstractmethod\n def kbdfocus_requested(self, val: bool) ->None:\n pass\n\n\nclass IUpdatable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def should_update(self) ->bool:\n pass\n\n @should_update.setter\n @abc.abstractmethod\n def should_update(self, value: bool) ->None:\n pass\n\n @abc.abstractmethod\n def update(self) ->None:\n pass\n", "step-4": "<mask token>\n\n\nclass IDrawable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def force_redraw(self) ->bool:\n pass\n\n @property\n @force_redraw.setter\n def force_redraw(self, value: bool) ->None:\n pass\n\n @abc.abstractmethod\n def draw(self, dest: Canvas) ->None:\n pass\n\n @abc.abstractmethod\n def base_drawing(self, console: tcod.console.Console) ->None:\n pass\n\n\nclass IFocusable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def focus_dispatcher(self) ->CanvasDispatcher:\n pass\n\n\nclass IMouseFocusable(IFocusable):\n\n @abc.abstractmethod\n def mousefocus(self, event: tcod.event.MouseMotion) ->bool:\n pass\n\n\nclass IKeyboardFocusable(IFocusable):\n\n @property\n @abc.abstractmethod\n def kbdfocus(self) ->bool:\n pass\n\n @kbdfocus.setter\n @abc.abstractmethod\n def kbdfocus(self, val: bool) ->None:\n pass\n\n @property\n @abc.abstractmethod\n def kbdfocus_requested(self) ->bool:\n pass\n\n @kbdfocus_requested.setter\n @abc.abstractmethod\n def kbdfocus_requested(self, val: bool) ->None:\n pass\n\n\nclass IUpdatable(abc.ABC):\n\n @property\n @abc.abstractmethod\n def should_update(self) ->bool:\n pass\n\n @should_update.setter\n @abc.abstractmethod\n def should_update(self, value: bool) ->None:\n pass\n\n @abc.abstractmethod\n def update(self) ->None:\n pass\n", "step-5": "from __future__ import annotations\nfrom typing import TYPE_CHECKING\nimport abc\nimport tcod.event\n\nif TYPE_CHECKING:\n from tcodplus.canvas import Canvas\n from tcodplus.event import CanvasDispatcher\n\n\nclass IDrawable(abc.ABC):\n @property\n @abc.abstractmethod\n def force_redraw(self) -> bool:\n pass\n\n @property\n @force_redraw.setter\n def force_redraw(self, value: bool) -> None:\n pass\n\n @abc.abstractmethod\n def draw(self, dest: Canvas) -> None:\n pass\n\n @abc.abstractmethod\n def base_drawing(self, console: tcod.console.Console) -> None:\n pass\n\n\nclass IFocusable(abc.ABC):\n @property\n @abc.abstractmethod\n def focus_dispatcher(self) -> CanvasDispatcher:\n pass\n\n\nclass IMouseFocusable(IFocusable):\n @abc.abstractmethod\n def mousefocus(self, event: tcod.event.MouseMotion) -> bool:\n pass\n\n\nclass IKeyboardFocusable(IFocusable):\n @property\n @abc.abstractmethod\n def kbdfocus(self) -> bool:\n pass\n\n @kbdfocus.setter\n @abc.abstractmethod\n def kbdfocus(self, val: bool) -> None:\n pass\n\n @property\n @abc.abstractmethod\n def kbdfocus_requested(self) -> bool:\n pass\n\n @kbdfocus_requested.setter\n @abc.abstractmethod\n def kbdfocus_requested(self, val: bool) -> None:\n pass\n\n\nclass IUpdatable(abc.ABC):\n @property\n @abc.abstractmethod\n def should_update(self) -> bool:\n pass\n\n @should_update.setter\n @abc.abstractmethod\n def should_update(self, value: bool) -> None:\n pass\n\n @abc.abstractmethod\n def update(self) -> None:\n pass\n", "step-ids": [ 14, 15, 17, 18, 21 ] }
[ 14, 15, 17, 18, 21 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> bw2_schema = Schema(name=TEXT(stored=True, sortable=True), comment=TEXT( stored=True), product=TEXT(stored=True, sortable=True), categories=TEXT (stored=True), location=TEXT(stored=True, sortable=True), database=TEXT (stored=True), code=ID(unique=True, stored=True)) <|reserved_special_token_1|> from __future__ import print_function, unicode_literals from eight import * from whoosh.fields import TEXT, ID, Schema bw2_schema = Schema(name=TEXT(stored=True, sortable=True), comment=TEXT( stored=True), product=TEXT(stored=True, sortable=True), categories=TEXT (stored=True), location=TEXT(stored=True, sortable=True), database=TEXT (stored=True), code=ID(unique=True, stored=True)) <|reserved_special_token_1|> # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals from eight import * from whoosh.fields import TEXT, ID, Schema bw2_schema = Schema( name=TEXT(stored=True, sortable=True), comment=TEXT(stored=True), product=TEXT(stored=True, sortable=True), categories=TEXT(stored=True), location=TEXT(stored=True, sortable=True), database=TEXT(stored=True), code=ID(unique=True, stored=True), )
flexible
{ "blob_id": "07aafcb3db9c57ad09a29a827d72744ef0d22247", "index": 3319, "step-1": "<mask token>\n", "step-2": "<mask token>\nbw2_schema = Schema(name=TEXT(stored=True, sortable=True), comment=TEXT(\n stored=True), product=TEXT(stored=True, sortable=True), categories=TEXT\n (stored=True), location=TEXT(stored=True, sortable=True), database=TEXT\n (stored=True), code=ID(unique=True, stored=True))\n", "step-3": "from __future__ import print_function, unicode_literals\nfrom eight import *\nfrom whoosh.fields import TEXT, ID, Schema\nbw2_schema = Schema(name=TEXT(stored=True, sortable=True), comment=TEXT(\n stored=True), product=TEXT(stored=True, sortable=True), categories=TEXT\n (stored=True), location=TEXT(stored=True, sortable=True), database=TEXT\n (stored=True), code=ID(unique=True, stored=True))\n", "step-4": "# -*- coding: utf-8 -*-\nfrom __future__ import print_function, unicode_literals\nfrom eight import *\n\nfrom whoosh.fields import TEXT, ID, Schema\n\nbw2_schema = Schema(\n name=TEXT(stored=True, sortable=True),\n comment=TEXT(stored=True),\n product=TEXT(stored=True, sortable=True),\n categories=TEXT(stored=True),\n location=TEXT(stored=True, sortable=True),\n database=TEXT(stored=True),\n code=ID(unique=True, stored=True),\n)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#! /usr/bin/env python t = int(raw_input()) for i in xrange(1, t+1): N = raw_input() N1 = N track = set() if N == '0': print "Case #%s: " % i + "INSOMNIA" continue count = 2 while len(track) !=10: temp = set(x for x in N1) track = temp | track N1 = str(count*int(N)) count +=1 print "Case #%s: %d" % (i, int(N1) - int(N))
normal
{ "blob_id": "8c6b7032c85354740d59aa91108ad8b5279e1d45", "index": 2570, "step-1": "#! /usr/bin/env python\n\nt = int(raw_input())\nfor i in xrange(1, t+1):\n N = raw_input()\n N1 = N\n track = set()\n if N == '0':\n print \"Case #%s: \" % i + \"INSOMNIA\"\n continue\n count = 2\n while len(track) !=10:\n temp = set(x for x in N1)\n track = temp | track\n N1 = str(count*int(N))\n count +=1\n print \"Case #%s: %d\" % (i, int(N1) - int(N))\n\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if minutos > 800: total = minutos * 0.08 elif minutos > 400 and minutos <= 800: total = minutos * 0.15 elif minutos < 200: total = minutos * 0.2 else: total = minutos * 0.18 print('Valor da conta: R$ %.2f' % total) <|reserved_special_token_1|> <|reserved_special_token_0|> minutos = int(input('Minutos utilizados: ')) if minutos > 800: total = minutos * 0.08 elif minutos > 400 and minutos <= 800: total = minutos * 0.15 elif minutos < 200: total = minutos * 0.2 else: total = minutos * 0.18 print('Valor da conta: R$ %.2f' % total) <|reserved_special_token_1|> ''' A empresa Tchau de telefonia cobra: -Abaixo de 200 minutos, R$ 0,20 por minuto -Entre 200 e 400 minutos, R$ 0,18 por minuto -Acima de 400 minutos, R$ 0,15 por minuto - Bonus: - Acima de 800 minutos, R$ 0,08 Calcule a conta de telefone ''' minutos = int(input('Minutos utilizados: ')) if minutos > 800: total = minutos * 0.08 elif minutos > 400 and minutos <= 800: total = minutos * 0.15 elif minutos < 200: total = minutos * 0.2 else: total = minutos * 0.18 print('Valor da conta: R$ %.2f' %total)
flexible
{ "blob_id": "1b3e64be988495454535ca96c7a1b6c20aa27076", "index": 2648, "step-1": "<mask token>\n", "step-2": "<mask token>\nif minutos > 800:\n total = minutos * 0.08\nelif minutos > 400 and minutos <= 800:\n total = minutos * 0.15\nelif minutos < 200:\n total = minutos * 0.2\nelse:\n total = minutos * 0.18\nprint('Valor da conta: R$ %.2f' % total)\n", "step-3": "<mask token>\nminutos = int(input('Minutos utilizados: '))\nif minutos > 800:\n total = minutos * 0.08\nelif minutos > 400 and minutos <= 800:\n total = minutos * 0.15\nelif minutos < 200:\n total = minutos * 0.2\nelse:\n total = minutos * 0.18\nprint('Valor da conta: R$ %.2f' % total)\n", "step-4": "'''\nA empresa Tchau de telefonia cobra:\n-Abaixo de 200 minutos, R$ 0,20 por minuto\n-Entre 200 e 400 minutos, R$ 0,18 por minuto\n-Acima de 400 minutos, R$ 0,15 por minuto\n\n\n- Bonus: - Acima de 800 minutos, R$ 0,08\nCalcule a conta de telefone\n'''\n\nminutos = int(input('Minutos utilizados: '))\n\nif minutos > 800:\n total = minutos * 0.08\nelif minutos > 400 and minutos <= 800:\n total = minutos * 0.15\nelif minutos < 200:\n total = minutos * 0.2\nelse:\n total = minutos * 0.18\n\nprint('Valor da conta: R$ %.2f' %total)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def find_and_display_patter_in_series(*, series, pattern): """I used that function when i don't remeber full name of a given column""" res = series.loc[series.str.contains(pattern)] return res <|reserved_special_token_0|> def find_patter_in_series(*, s, pat, tolist=True): """ I used that function when i don't remeber full name of a given column """ res = s.loc[s.str.contains(pat)] if tolist == True: return res.values.tolist() else: return res def format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime= False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False): """ formats columns in df into datetime dtype, and set all times to UTC work with unix time units, ie. second number since 1970 columns in df, are find using full comlumn name or keywords in column name """ assert type(data ) == pd.DataFrame, 'please provide data in pandas dataframe format' if isinstance(pattern_list, str): pattern_list = [pattern_list] else: pass for pat in pattern_list: columns_with_potential_datetime_obj = list( find_and_display_patter_in_series(series=pd.Series(data.columns ), pattern=pat)) for i in columns_with_potential_datetime_obj: before_formatting = str(data.loc[0, i]) if unixtime == True: s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s' ).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone) else: pass else: s = pd.to_datetime(data.loc[:, i], errors='coerce', format= dt_format).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone) else: pass if verbose == True: print(f'date time formatted in: {i}') print( f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce' ) print( f' - Example: {before_formatting} -->> {str(data.loc[0, i])}' , end='\n') else: pass return data def replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True): """ searches string with a given pattern and replace it with a new patter (fillna), eg: nan, Parameters/Input _________________ _______________________________________________________________________________ * df Pandas Dataframe * searched_pattern "", str literal, used by pd.Series.str.contains() * colnames default, "all", or list with selected colnames in df * fillna default numpy.nan, or str literal - what do you want to place instead of searched pattern in df Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ searched_pattern = pat col_names = colnames if col_names == 'all': sel_col_names = list(df.columns) else: sel_col_names = col_names if verbose == True: print( f'\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\n' ) if verbose == False: pass for i, col_name in enumerate(sel_col_names): if is_string_dtype(df[col_name]): try: positions_to_replace = df[col_name].str.contains( searched_pattern, na=False).values examples_to_display = [str(x) for x in list(df.loc[list( positions_to_replace), col_name].str[0:20].values. tolist()[0:3])] df.loc[list(positions_to_replace), col_name] = [fillna ] * positions_to_replace.sum() examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace == False), col_name].str[0:20].values.tolist()[0:3])] if verbose == True: perc_of_replaced_pos_in_col = ''.join([str( positions_to_replace.sum() / df.shape[0] * 100), '%']) print( f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}' ) print( f" - three examples of replaced postions: {'; '.join(examples_to_display)}" , end='\n') print( f" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}" , end='\n\n') else: pass except: if verbose == True: print( f"""{i} - {col_name} - - probably only missing data datected, Values were not replaced! """ ) else: pass elif verbose == True: print( f'{i} - {col_name} - - is not of string type, Values were not replaced! \n' ) else: pass return df.copy() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def find_and_display_patter_in_series(*, series, pattern): """I used that function when i don't remeber full name of a given column""" res = series.loc[series.str.contains(pattern)] return res <|reserved_special_token_0|> def find_patter_in_series(*, s, pat, tolist=True): """ I used that function when i don't remeber full name of a given column """ res = s.loc[s.str.contains(pat)] if tolist == True: return res.values.tolist() else: return res def format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime= False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False): """ formats columns in df into datetime dtype, and set all times to UTC work with unix time units, ie. second number since 1970 columns in df, are find using full comlumn name or keywords in column name """ assert type(data ) == pd.DataFrame, 'please provide data in pandas dataframe format' if isinstance(pattern_list, str): pattern_list = [pattern_list] else: pass for pat in pattern_list: columns_with_potential_datetime_obj = list( find_and_display_patter_in_series(series=pd.Series(data.columns ), pattern=pat)) for i in columns_with_potential_datetime_obj: before_formatting = str(data.loc[0, i]) if unixtime == True: s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s' ).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone) else: pass else: s = pd.to_datetime(data.loc[:, i], errors='coerce', format= dt_format).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone) else: pass if verbose == True: print(f'date time formatted in: {i}') print( f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce' ) print( f' - Example: {before_formatting} -->> {str(data.loc[0, i])}' , end='\n') else: pass return data def replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True): """ searches string with a given pattern and replace it with a new patter (fillna), eg: nan, Parameters/Input _________________ _______________________________________________________________________________ * df Pandas Dataframe * searched_pattern "", str literal, used by pd.Series.str.contains() * colnames default, "all", or list with selected colnames in df * fillna default numpy.nan, or str literal - what do you want to place instead of searched pattern in df Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ searched_pattern = pat col_names = colnames if col_names == 'all': sel_col_names = list(df.columns) else: sel_col_names = col_names if verbose == True: print( f'\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\n' ) if verbose == False: pass for i, col_name in enumerate(sel_col_names): if is_string_dtype(df[col_name]): try: positions_to_replace = df[col_name].str.contains( searched_pattern, na=False).values examples_to_display = [str(x) for x in list(df.loc[list( positions_to_replace), col_name].str[0:20].values. tolist()[0:3])] df.loc[list(positions_to_replace), col_name] = [fillna ] * positions_to_replace.sum() examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace == False), col_name].str[0:20].values.tolist()[0:3])] if verbose == True: perc_of_replaced_pos_in_col = ''.join([str( positions_to_replace.sum() / df.shape[0] * 100), '%']) print( f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}' ) print( f" - three examples of replaced postions: {'; '.join(examples_to_display)}" , end='\n') print( f" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}" , end='\n\n') else: pass except: if verbose == True: print( f"""{i} - {col_name} - - probably only missing data datected, Values were not replaced! """ ) else: pass elif verbose == True: print( f'{i} - {col_name} - - is not of string type, Values were not replaced! \n' ) else: pass return df.copy() <|reserved_special_token_0|> def drop_nan(df, method='any', row=True, verbose=True): """ function to dropna with thresholds from rows and columns . method . any : row/column wiht any missing data are removed . all : row/column only wiht missing data are removed . int, >0 : keeps row/clumns wiht this or larger number of non missing data . float, >0 : as in the above, as fraction """ assert type(df) == pd.DataFrame, 'incorrect df dtype' df = df.copy() if verbose == True: print(df.shape) else: pass if row == True: shapeidx, dfaxis = 1, 0 else: shapeidx, dfaxis = 0, 1 if method == None: pass elif isinstance(method, str): df = df.dropna(how=method, axis=dfaxis) elif isinstance(method, int): tr = method if tr == 0: pass else: if tr >= df.shape[shapeidx]: tr = df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) elif isinstance(method, float): tr = int(np.ceil(df.shape[shapeidx] * method)) if tr == 0: pass else: if tr >= df.shape[shapeidx]: tr = df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) else: pass if verbose == True: print(df.shape) else: pass return df <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def find_and_display_patter_in_series(*, series, pattern): """I used that function when i don't remeber full name of a given column""" res = series.loc[series.str.contains(pattern)] return res <|reserved_special_token_0|> def find_patter_in_series(*, s, pat, tolist=True): """ I used that function when i don't remeber full name of a given column """ res = s.loc[s.str.contains(pat)] if tolist == True: return res.values.tolist() else: return res def format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime= False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False): """ formats columns in df into datetime dtype, and set all times to UTC work with unix time units, ie. second number since 1970 columns in df, are find using full comlumn name or keywords in column name """ assert type(data ) == pd.DataFrame, 'please provide data in pandas dataframe format' if isinstance(pattern_list, str): pattern_list = [pattern_list] else: pass for pat in pattern_list: columns_with_potential_datetime_obj = list( find_and_display_patter_in_series(series=pd.Series(data.columns ), pattern=pat)) for i in columns_with_potential_datetime_obj: before_formatting = str(data.loc[0, i]) if unixtime == True: s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s' ).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone) else: pass else: s = pd.to_datetime(data.loc[:, i], errors='coerce', format= dt_format).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone) else: pass if verbose == True: print(f'date time formatted in: {i}') print( f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce' ) print( f' - Example: {before_formatting} -->> {str(data.loc[0, i])}' , end='\n') else: pass return data def replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True): """ searches string with a given pattern and replace it with a new patter (fillna), eg: nan, Parameters/Input _________________ _______________________________________________________________________________ * df Pandas Dataframe * searched_pattern "", str literal, used by pd.Series.str.contains() * colnames default, "all", or list with selected colnames in df * fillna default numpy.nan, or str literal - what do you want to place instead of searched pattern in df Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ searched_pattern = pat col_names = colnames if col_names == 'all': sel_col_names = list(df.columns) else: sel_col_names = col_names if verbose == True: print( f'\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\n' ) if verbose == False: pass for i, col_name in enumerate(sel_col_names): if is_string_dtype(df[col_name]): try: positions_to_replace = df[col_name].str.contains( searched_pattern, na=False).values examples_to_display = [str(x) for x in list(df.loc[list( positions_to_replace), col_name].str[0:20].values. tolist()[0:3])] df.loc[list(positions_to_replace), col_name] = [fillna ] * positions_to_replace.sum() examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace == False), col_name].str[0:20].values.tolist()[0:3])] if verbose == True: perc_of_replaced_pos_in_col = ''.join([str( positions_to_replace.sum() / df.shape[0] * 100), '%']) print( f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}' ) print( f" - three examples of replaced postions: {'; '.join(examples_to_display)}" , end='\n') print( f" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}" , end='\n\n') else: pass except: if verbose == True: print( f"""{i} - {col_name} - - probably only missing data datected, Values were not replaced! """ ) else: pass elif verbose == True: print( f'{i} - {col_name} - - is not of string type, Values were not replaced! \n' ) else: pass return df.copy() def replace_numeric_values(*, df, colnames='all', lower_limit='none', upper_limit='none', equal=False, replace_with=np.nan, verbose=True): """ Replace numerical values that are outside of range of a values prediced with a theoretical limits of a given variable, eg less then 0 in weight of a product, Provide examples and numbers of replaced instances Parameters/Input _________________ _______________________________________________________________________________ * df : Pandas DataFrame * cols_in_df : list, exact colnames of selected or all columns in df * lower_limit : int,float,"none", if "none" no action is taken * upper_limit : int,float,"none", if "none" no action is taken * replace_with : str, np.nan, int, float * equal : bool, if True, >= and <= values then limits will be replaced, if False (default), > and < values then limits will be replaced, Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ cols_names = colnames if cols_names == 'all': cols = list(df.columns) else: cols = cols_names if verbose == True: print( f"\n{''.join(['-'] * 80)} \n Replacing Numerical Values in {len(cols)} columns" ) print( f' lower filter={lower_limit}, upper filter ={upper_limit}') if equal == True: print( f' Caution, equal=True, ie. values >= and <= then requested limits will be replaced' ) print(f"{''.join(['-'] * 80)}\n") if verbose == False: pass total_count = [] count = 0 for i, j in enumerate(cols): info_lower_filter = 0 info_upper_filter = 0 if is_numeric_dtype(df[j]): if lower_limit != 'none': if equal == True: lower_filter = df.loc[:, j] <= lower_limit if equal == False: lower_filter = df.loc[:, j] < lower_limit info_lower_filter = lower_filter.sum() df.loc[list(lower_filter), j] = replace_with if upper_limit != 'none': if equal == True: upper_filter = df.loc[:, j] >= upper_limit if equal == False: upper_filter = df.loc[:, j] > upper_limit info_upper_filter = upper_filter.sum() df.loc[list(upper_filter), j] = replace_with total_count.append(info_upper_filter + info_lower_filter) if verbose == True: if info_upper_filter + info_lower_filter > 0 and count < 4: print( f'eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}' ) else: pass count += 1 elif verbose == True: print(f'{i, j} is not of numeric type, values were not replaced !') else: pass if verbose == True: if len(total_count) > 3 and pd.Series(total_count).sum() > 0: print( f""". and {len(total_count) - 3} other columns had in total {pd.Series(total_count).sum()} replaced values """ ) if pd.Series(total_count).sum() == 0: print('No values were replaced in requested columns....') else: pass return df.copy() def drop_nan(df, method='any', row=True, verbose=True): """ function to dropna with thresholds from rows and columns . method . any : row/column wiht any missing data are removed . all : row/column only wiht missing data are removed . int, >0 : keeps row/clumns wiht this or larger number of non missing data . float, >0 : as in the above, as fraction """ assert type(df) == pd.DataFrame, 'incorrect df dtype' df = df.copy() if verbose == True: print(df.shape) else: pass if row == True: shapeidx, dfaxis = 1, 0 else: shapeidx, dfaxis = 0, 1 if method == None: pass elif isinstance(method, str): df = df.dropna(how=method, axis=dfaxis) elif isinstance(method, int): tr = method if tr == 0: pass else: if tr >= df.shape[shapeidx]: tr = df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) elif isinstance(method, float): tr = int(np.ceil(df.shape[shapeidx] * method)) if tr == 0: pass else: if tr >= df.shape[shapeidx]: tr = df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) else: pass if verbose == True: print(df.shape) else: pass return df def drop_columns(*, df, columns_to_drop, verbose=True): """ Small function to quickly remove columns from, by column names stored in the list - created to give info on removed columns and whether I am chnaging df in proper way, - the function allows for column name duplicates, """ assert type(df ) == pd.DataFrame, 'please provide df in pandas dataframe format' df = df.copy() columns_to_drop = list(pd.Series(columns_to_drop).unique()) if verbose == True: print(f'Removing {len(columns_to_drop)} columns from df') else: pass for i, j in enumerate(columns_to_drop): try: df.drop(columns=[j], axis=1, inplace=True) if verbose == True: print(f'{i} removing: {j}, ==> new df.shape: {df.shape}') else: pass except: if verbose == True: print( f'{i} .... column: {j}, was not found in df, check if name is correct....' ) else: pass return df <|reserved_special_token_1|> <|reserved_special_token_0|> def find_and_display_patter_in_series(*, series, pattern): """I used that function when i don't remeber full name of a given column""" res = series.loc[series.str.contains(pattern)] return res def load_csv(*, path, filename, sep='\t', verbose=True): """ Loads csv into pandas df, based on pandas.read_scv(), Returns error, if file or directoy not found Parameters/Input _________________ _______________________________________________________________________________ * path full path to directory * csv_name. full csv file name * separator " ", by default * display_head bool, True, by default, display df.head(), irrespectively when the futions was called. Returns _________________ _______________________________________________________________________________ * DataFrame by Pandas """ os.chdir(path) if len(glob.glob(filename)) == 1: df = pd.read_csv(filename, sep=sep, low_memory=False) if verbose == True: display(df.head(3)) print(df.shape) else: pass return df elif verbose == True: print(f'ERROR :csv file {filename}, was not found in: \n {path}') else: pass def find_patter_in_series(*, s, pat, tolist=True): """ I used that function when i don't remeber full name of a given column """ res = s.loc[s.str.contains(pat)] if tolist == True: return res.values.tolist() else: return res def format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime= False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False): """ formats columns in df into datetime dtype, and set all times to UTC work with unix time units, ie. second number since 1970 columns in df, are find using full comlumn name or keywords in column name """ assert type(data ) == pd.DataFrame, 'please provide data in pandas dataframe format' if isinstance(pattern_list, str): pattern_list = [pattern_list] else: pass for pat in pattern_list: columns_with_potential_datetime_obj = list( find_and_display_patter_in_series(series=pd.Series(data.columns ), pattern=pat)) for i in columns_with_potential_datetime_obj: before_formatting = str(data.loc[0, i]) if unixtime == True: s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s' ).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone) else: pass else: s = pd.to_datetime(data.loc[:, i], errors='coerce', format= dt_format).copy() data.loc[:, i] = s if timezone != None: data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone) else: pass if verbose == True: print(f'date time formatted in: {i}') print( f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce' ) print( f' - Example: {before_formatting} -->> {str(data.loc[0, i])}' , end='\n') else: pass return data def replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True): """ searches string with a given pattern and replace it with a new patter (fillna), eg: nan, Parameters/Input _________________ _______________________________________________________________________________ * df Pandas Dataframe * searched_pattern "", str literal, used by pd.Series.str.contains() * colnames default, "all", or list with selected colnames in df * fillna default numpy.nan, or str literal - what do you want to place instead of searched pattern in df Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ searched_pattern = pat col_names = colnames if col_names == 'all': sel_col_names = list(df.columns) else: sel_col_names = col_names if verbose == True: print( f'\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\n' ) if verbose == False: pass for i, col_name in enumerate(sel_col_names): if is_string_dtype(df[col_name]): try: positions_to_replace = df[col_name].str.contains( searched_pattern, na=False).values examples_to_display = [str(x) for x in list(df.loc[list( positions_to_replace), col_name].str[0:20].values. tolist()[0:3])] df.loc[list(positions_to_replace), col_name] = [fillna ] * positions_to_replace.sum() examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace == False), col_name].str[0:20].values.tolist()[0:3])] if verbose == True: perc_of_replaced_pos_in_col = ''.join([str( positions_to_replace.sum() / df.shape[0] * 100), '%']) print( f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}' ) print( f" - three examples of replaced postions: {'; '.join(examples_to_display)}" , end='\n') print( f" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}" , end='\n\n') else: pass except: if verbose == True: print( f"""{i} - {col_name} - - probably only missing data datected, Values were not replaced! """ ) else: pass elif verbose == True: print( f'{i} - {col_name} - - is not of string type, Values were not replaced! \n' ) else: pass return df.copy() def replace_numeric_values(*, df, colnames='all', lower_limit='none', upper_limit='none', equal=False, replace_with=np.nan, verbose=True): """ Replace numerical values that are outside of range of a values prediced with a theoretical limits of a given variable, eg less then 0 in weight of a product, Provide examples and numbers of replaced instances Parameters/Input _________________ _______________________________________________________________________________ * df : Pandas DataFrame * cols_in_df : list, exact colnames of selected or all columns in df * lower_limit : int,float,"none", if "none" no action is taken * upper_limit : int,float,"none", if "none" no action is taken * replace_with : str, np.nan, int, float * equal : bool, if True, >= and <= values then limits will be replaced, if False (default), > and < values then limits will be replaced, Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ cols_names = colnames if cols_names == 'all': cols = list(df.columns) else: cols = cols_names if verbose == True: print( f"\n{''.join(['-'] * 80)} \n Replacing Numerical Values in {len(cols)} columns" ) print( f' lower filter={lower_limit}, upper filter ={upper_limit}') if equal == True: print( f' Caution, equal=True, ie. values >= and <= then requested limits will be replaced' ) print(f"{''.join(['-'] * 80)}\n") if verbose == False: pass total_count = [] count = 0 for i, j in enumerate(cols): info_lower_filter = 0 info_upper_filter = 0 if is_numeric_dtype(df[j]): if lower_limit != 'none': if equal == True: lower_filter = df.loc[:, j] <= lower_limit if equal == False: lower_filter = df.loc[:, j] < lower_limit info_lower_filter = lower_filter.sum() df.loc[list(lower_filter), j] = replace_with if upper_limit != 'none': if equal == True: upper_filter = df.loc[:, j] >= upper_limit if equal == False: upper_filter = df.loc[:, j] > upper_limit info_upper_filter = upper_filter.sum() df.loc[list(upper_filter), j] = replace_with total_count.append(info_upper_filter + info_lower_filter) if verbose == True: if info_upper_filter + info_lower_filter > 0 and count < 4: print( f'eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}' ) else: pass count += 1 elif verbose == True: print(f'{i, j} is not of numeric type, values were not replaced !') else: pass if verbose == True: if len(total_count) > 3 and pd.Series(total_count).sum() > 0: print( f""". and {len(total_count) - 3} other columns had in total {pd.Series(total_count).sum()} replaced values """ ) if pd.Series(total_count).sum() == 0: print('No values were replaced in requested columns....') else: pass return df.copy() def drop_nan(df, method='any', row=True, verbose=True): """ function to dropna with thresholds from rows and columns . method . any : row/column wiht any missing data are removed . all : row/column only wiht missing data are removed . int, >0 : keeps row/clumns wiht this or larger number of non missing data . float, >0 : as in the above, as fraction """ assert type(df) == pd.DataFrame, 'incorrect df dtype' df = df.copy() if verbose == True: print(df.shape) else: pass if row == True: shapeidx, dfaxis = 1, 0 else: shapeidx, dfaxis = 0, 1 if method == None: pass elif isinstance(method, str): df = df.dropna(how=method, axis=dfaxis) elif isinstance(method, int): tr = method if tr == 0: pass else: if tr >= df.shape[shapeidx]: tr = df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) elif isinstance(method, float): tr = int(np.ceil(df.shape[shapeidx] * method)) if tr == 0: pass else: if tr >= df.shape[shapeidx]: tr = df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) else: pass if verbose == True: print(df.shape) else: pass return df def drop_columns(*, df, columns_to_drop, verbose=True): """ Small function to quickly remove columns from, by column names stored in the list - created to give info on removed columns and whether I am chnaging df in proper way, - the function allows for column name duplicates, """ assert type(df ) == pd.DataFrame, 'please provide df in pandas dataframe format' df = df.copy() columns_to_drop = list(pd.Series(columns_to_drop).unique()) if verbose == True: print(f'Removing {len(columns_to_drop)} columns from df') else: pass for i, j in enumerate(columns_to_drop): try: df.drop(columns=[j], axis=1, inplace=True) if verbose == True: print(f'{i} removing: {j}, ==> new df.shape: {df.shape}') else: pass except: if verbose == True: print( f'{i} .... column: {j}, was not found in df, check if name is correct....' ) else: pass return df <|reserved_special_token_1|> # ********************************************************************************** # # # # Project: Data Frame Explorer # # Author: Pawel Rosikiewicz # # Contact: prosikiewicz(a)gmail.com # # # # License: MIT License # # Copyright (C) 2021.01.30 Pawel Rosikiewicz # # # # Permission is hereby granted, free of charge, to any person obtaining a copy # # of this software and associated documentation files (the "Software"), to deal # # in the Software without restriction, including without limitation the rights # # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # # copies of the Software, and to permit persons to whom the Software is # # furnished to do so, subject to the following conditions: # # # # The above copyright notice and this permission notice shall be included in all # # copies or substantial portions of the Software. # # # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # # SOFTWARE. # # # # ********************************************************************************** # # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import pandas as pd import random import glob import re import os import seaborn as sns from IPython.display import display from pandas.api.types import is_numeric_dtype from pandas.api.types import is_string_dtype # Function, ............................................................................ def find_and_display_patter_in_series(*, series, pattern): "I used that function when i don't remeber full name of a given column" res = series.loc[series.str.contains(pattern)] return res # Function, ........................................................................................... def load_csv(*, path, filename, sep="\t", verbose=True): """ Loads csv into pandas df, based on pandas.read_scv(), Returns error, if file or directoy not found Parameters/Input _________________ _______________________________________________________________________________ * path full path to directory * csv_name. full csv file name * separator "\t", by default * display_head bool, True, by default, display df.head(), irrespectively when the futions was called. Returns _________________ _______________________________________________________________________________ * DataFrame by Pandas """ os.chdir(path) if len(glob.glob(filename))==1: df = pd.read_csv(filename, sep=sep, low_memory=False) # display example, if verbose==True: display(df.head(3)) print(df.shape) else: pass # return, return df else: if verbose==True: print(f"""ERROR :csv file {filename}, was not found in: \n {path}""") else: pass # Function, ............................................................................ def find_patter_in_series(*, s, pat, tolist=True): ''' I used that function when i don't remeber full name of a given column ''' res = s.loc[s.str.contains(pat)] if tolist==True: return res.values.tolist() else: return res # Function, ........................................................................................... def format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False): ''' formats columns in df into datetime dtype, and set all times to UTC work with unix time units, ie. second number since 1970 columns in df, are find using full comlumn name or keywords in column name ''' assert type(data)==pd.DataFrame, "please provide data in pandas dataframe format" if isinstance(pattern_list, str): pattern_list = [pattern_list] else: pass for pat in pattern_list: # find column names using provided patterns or their full names, columns_with_potential_datetime_obj = list(find_and_display_patter_in_series(series=pd.Series(data.columns), pattern=pat)) # replace for i in columns_with_potential_datetime_obj: # keep example of old cell before_formatting = str(data.loc[0, i]) # convert to one format if unixtime==True: s = pd.to_datetime(data.loc[:, i], errors="coerce", unit='s').copy()#,format cannot be used with unit="s", but it will be the same data.loc[:, i] = s if timezone!=None: data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone) else: pass else: s = pd.to_datetime(data.loc[:, i], errors="coerce",format=dt_format).copy() data.loc[:, i] = s if timezone!=None: data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone) else: pass # info if verbose==True: print(f"date time formatted in: {i}") print(f" - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce") print(f" - Example: {before_formatting} -->> {str(data.loc[0, i])}", end="\n") else: pass return data # Function, ........................................................................................... def replace_text(*,df ,pat="", colnames="all", fillna=np.nan, verbose=True): """ searches string with a given pattern and replace it with a new patter (fillna), eg: nan, Parameters/Input _________________ _______________________________________________________________________________ * df Pandas Dataframe * searched_pattern "", str literal, used by pd.Series.str.contains() * colnames default, "all", or list with selected colnames in df * fillna default numpy.nan, or str literal - what do you want to place instead of searched pattern in df Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ # for older version, searched_pattern = pat col_names = colnames # check col_names with values to replace, if col_names=="all": sel_col_names = list(df.columns) else: sel_col_names = col_names # display message header, if verbose==True: print(f"""\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\n""") if verbose==False: pass # exchnage searched pattern in each column separately, for i, col_name in enumerate(sel_col_names): # .. test if you really have string values in that column, otherwise it masy be float for all NaN in a column, and no action will be taken if is_string_dtype(df[col_name]): try: # .... find postions with a given pattern and select three examples to display for the user, positions_to_replace = df[col_name].str.contains(searched_pattern, na=False).values# arr examples_to_display = [str(x) for x in list(df.loc[list(positions_to_replace), col_name].str[0:20].values.tolist()[0:3])] # .... replace postions, and find examples of unchnaged postions, df.loc[list(positions_to_replace), col_name] = [fillna]*positions_to_replace.sum() examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace==False), col_name].str[0:20].values.tolist()[0:3])] # .... diplay info, if verbose==True: perc_of_replaced_pos_in_col = "".join([str(positions_to_replace.sum()/df.shape[0]*100),"%"]) print(f"{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}") print(f" - three examples of replaced postions: {'; '.join(examples_to_display)}", end="\n") print(f" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}", end="\n\n") # the second print returns three first examples of exchanged values, just to see what i did, else: pass except: if verbose==True: print(f"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n") else: pass else: if verbose==True: print(f"{i} - {col_name} - - is not of string type, Values were not replaced! \n") else: pass return df.copy() # Function, ........................................................................................... def replace_numeric_values(*, df, colnames="all", lower_limit="none", upper_limit="none", equal=False, replace_with=np.nan, verbose=True): """ Replace numerical values that are outside of range of a values prediced with a theoretical limits of a given variable, eg less then 0 in weight of a product, Provide examples and numbers of replaced instances Parameters/Input _________________ _______________________________________________________________________________ * df : Pandas DataFrame * cols_in_df : list, exact colnames of selected or all columns in df * lower_limit : int,float,"none", if "none" no action is taken * upper_limit : int,float,"none", if "none" no action is taken * replace_with : str, np.nan, int, float * equal : bool, if True, >= and <= values then limits will be replaced, if False (default), > and < values then limits will be replaced, Returns _________________ _______________________________________________________________________________ * DataFrame DataFramne.copy() with new values, * display messages. number of replaced straings in each column, and examples of replcaced values """ cols_names = colnames # .. check provided col_names, if cols_names=="all": cols = list(df.columns) else: cols = cols_names # .. info, header, if verbose==True: print(f"""\n{"".join(["-"]*80)} \n Replacing Numerical Values in {len(cols)} columns""") print(f" lower filter={lower_limit}, upper filter ={upper_limit}") if equal==True: print(f" Caution, equal=True, ie. values >= and <= then requested limits will be replaced") print(f'{"".join(["-"]*80)}\n') if verbose==False: pass # .. intelligent info, total_count=[] # .. count, to limit the number of displayed messages, count = 0 # .. replace values and collect examples, for i, j in enumerate(cols): # ..... assume no values were replaced, so the messages work later, info_lower_filter = 0 info_upper_filter = 0 # ..... test if the column is of the numeric type: # from pandas.api.types import is_numeric_dtype if is_numeric_dtype(df[j]): # * replace values < or <= lower limit, # - ---------------------------------- if lower_limit!="none": if equal == True: lower_filter = df.loc[:,j]<=lower_limit if equal == False: lower_filter = df.loc[:,j]<lower_limit # info, info_lower_filter=lower_filter.sum() df.loc[list(lower_filter),j]=replace_with # * replace values > or >= upper limit, # - ---------------------------------- if upper_limit!="none": if equal == True: upper_filter = df.loc[:,j]>=upper_limit if equal == False: upper_filter = df.loc[:,j]>upper_limit # info, info_upper_filter=upper_filter.sum() df.loc[list(upper_filter),j]=replace_with # * find how many values were replaced, and add that to the total_count list total_count.append(info_upper_filter+info_lower_filter) # * display examples for 3 first columns with replaced values, if verbose==True: if info_upper_filter+info_lower_filter>0 and count <4: print(f"eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}") else: pass # * add 1 to count, to limit the number of displayed examples, count += 1 else: if verbose==True: print(f"{i, j} is not of numeric type, values were not replaced !") else: pass # .. additional message, if more then 2 columns had replaced values, if verbose==True: if len(total_count)>3 and pd.Series(total_count).sum()>0: print(f". and {len(total_count)-3} other columns had in total {pd.Series(total_count).sum()} replaced values \n") # .. message in case no values vere replaced at all, if pd.Series(total_count).sum()==0: print("No values were replaced in requested columns....") else: pass # .. return, return df.copy() # function, ................................................... def drop_nan(df, method="any", row=True, verbose=True): ''' function to dropna with thresholds from rows and columns . method . any : row/column wiht any missing data are removed . all : row/column only wiht missing data are removed . int, >0 : keeps row/clumns wiht this or larger number of non missing data . float, >0 : as in the above, as fraction ''' assert type(df)==pd.DataFrame, "incorrect df dtype" df = df.copy() if verbose==True: print(df.shape) else: pass # set funtion for rows or columns, if row==True: shapeidx, dfaxis = 1, 0 else: shapeidx, dfaxis = 0, 1 # use threshold or "all", or None for do nothing, if method==None: pass elif isinstance(method, str): df = df.dropna(how=method, axis=dfaxis) # removes rows with NaN in all columns elif isinstance(method, int): tr = method if tr==0: pass else: if tr>=df.shape[shapeidx]: tr=df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value elif isinstance(method, float): tr = int(np.ceil(df.shape[shapeidx]*(method))) if tr==0: pass else: if tr>=df.shape[shapeidx]: tr=df.shape[shapeidx] else: pass df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value else: pass # info and return if verbose==True: print(df.shape) else: pass return df # Function, ........................................................................................... def drop_columns(*, df, columns_to_drop, verbose=True): """ Small function to quickly remove columns from, by column names stored in the list - created to give info on removed columns and whether I am chnaging df in proper way, - the function allows for column name duplicates, """ assert type(df)==pd.DataFrame, "please provide df in pandas dataframe format" df = df.copy() # find unique values in a list, just in case I made the mistake, columns_to_drop = list(pd.Series(columns_to_drop).unique()) # .. info, header, if verbose==True: print(f"""Removing {len(columns_to_drop)} columns from df""") else: pass # remove columns one by one, for i,j in enumerate(columns_to_drop): try: df.drop(columns=[j], axis=1, inplace=True) if verbose==True: print(f"{i} removing: {j}, ==> new df.shape: {df.shape}") else: pass except: if verbose==True: print(f"{i} .... column: {j}, was not found in df, check if name is correct....") else: pass return df
flexible
{ "blob_id": "5f50b20bd044471ebb8e1350d1a75a250b255d8f", "index": 8854, "step-1": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n<mask token>\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n<mask token>\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\n<mask token>\n\n\ndef drop_nan(df, method='any', row=True, verbose=True):\n \"\"\"\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n \"\"\"\n assert type(df) == pd.DataFrame, 'incorrect df dtype'\n df = df.copy()\n if verbose == True:\n print(df.shape)\n else:\n pass\n if row == True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n if method == None:\n pass\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis)\n elif isinstance(method, int):\n tr = method\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx] * method))\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n else:\n pass\n if verbose == True:\n print(df.shape)\n else:\n pass\n return df\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n<mask token>\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\ndef replace_numeric_values(*, df, colnames='all', lower_limit='none',\n upper_limit='none', equal=False, replace_with=np.nan, verbose=True):\n \"\"\" \n\n Replace numerical values that are outside of range of a values \n prediced with a theoretical limits of a given variable, \n eg less then 0 in weight of a product, \n Provide examples and numbers of replaced instances\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df : Pandas DataFrame\n * cols_in_df : list, exact colnames of selected or all columns in df\n * lower_limit : int,float,\"none\", if \"none\" no action is taken\n * upper_limit : int,float,\"none\", if \"none\" no action is taken\n * replace_with : str, np.nan, int, float\n * equal : bool, if True, >= and <= values then limits will be replaced,\n if False (default), > and < values then limits will be replaced,\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n cols_names = colnames\n if cols_names == 'all':\n cols = list(df.columns)\n else:\n cols = cols_names\n if verbose == True:\n print(\n f\"\\n{''.join(['-'] * 80)} \\n Replacing Numerical Values in {len(cols)} columns\"\n )\n print(\n f' lower filter={lower_limit}, upper filter ={upper_limit}')\n if equal == True:\n print(\n f' Caution, equal=True, ie. values >= and <= then requested limits will be replaced'\n )\n print(f\"{''.join(['-'] * 80)}\\n\")\n if verbose == False:\n pass\n total_count = []\n count = 0\n for i, j in enumerate(cols):\n info_lower_filter = 0\n info_upper_filter = 0\n if is_numeric_dtype(df[j]):\n if lower_limit != 'none':\n if equal == True:\n lower_filter = df.loc[:, j] <= lower_limit\n if equal == False:\n lower_filter = df.loc[:, j] < lower_limit\n info_lower_filter = lower_filter.sum()\n df.loc[list(lower_filter), j] = replace_with\n if upper_limit != 'none':\n if equal == True:\n upper_filter = df.loc[:, j] >= upper_limit\n if equal == False:\n upper_filter = df.loc[:, j] > upper_limit\n info_upper_filter = upper_filter.sum()\n df.loc[list(upper_filter), j] = replace_with\n total_count.append(info_upper_filter + info_lower_filter)\n if verbose == True:\n if info_upper_filter + info_lower_filter > 0 and count < 4:\n print(\n f'eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}'\n )\n else:\n pass\n count += 1\n elif verbose == True:\n print(f'{i, j} is not of numeric type, values were not replaced !')\n else:\n pass\n if verbose == True:\n if len(total_count) > 3 and pd.Series(total_count).sum() > 0:\n print(\n f\"\"\". and {len(total_count) - 3} other columns had in total {pd.Series(total_count).sum()} replaced values \n\"\"\"\n )\n if pd.Series(total_count).sum() == 0:\n print('No values were replaced in requested columns....')\n else:\n pass\n return df.copy()\n\n\ndef drop_nan(df, method='any', row=True, verbose=True):\n \"\"\"\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n \"\"\"\n assert type(df) == pd.DataFrame, 'incorrect df dtype'\n df = df.copy()\n if verbose == True:\n print(df.shape)\n else:\n pass\n if row == True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n if method == None:\n pass\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis)\n elif isinstance(method, int):\n tr = method\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx] * method))\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n else:\n pass\n if verbose == True:\n print(df.shape)\n else:\n pass\n return df\n\n\ndef drop_columns(*, df, columns_to_drop, verbose=True):\n \"\"\"\n Small function to quickly remove columns from, \n by column names stored in the list\n - created to give info on removed columns and whether I am chnaging df in proper way,\n - the function allows for column name duplicates, \n \"\"\"\n assert type(df\n ) == pd.DataFrame, 'please provide df in pandas dataframe format'\n df = df.copy()\n columns_to_drop = list(pd.Series(columns_to_drop).unique())\n if verbose == True:\n print(f'Removing {len(columns_to_drop)} columns from df')\n else:\n pass\n for i, j in enumerate(columns_to_drop):\n try:\n df.drop(columns=[j], axis=1, inplace=True)\n if verbose == True:\n print(f'{i} removing: {j}, ==> new df.shape: {df.shape}')\n else:\n pass\n except:\n if verbose == True:\n print(\n f'{i} .... column: {j}, was not found in df, check if name is correct....'\n )\n else:\n pass\n return df\n", "step-4": "<mask token>\n\n\ndef find_and_display_patter_in_series(*, series, pattern):\n \"\"\"I used that function when i don't remeber full name of a given column\"\"\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\ndef load_csv(*, path, filename, sep='\\t', verbose=True):\n \"\"\" \n Loads csv into pandas df, based on pandas.read_scv(), \n Returns error, if file or directoy not found\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * path full path to directory\n * csv_name. full csv file name\n * separator \"\t\", by default\n * display_head bool, True, by default, display df.head(), \n irrespectively when the futions was called. \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame by Pandas\n\n \"\"\"\n os.chdir(path)\n if len(glob.glob(filename)) == 1:\n df = pd.read_csv(filename, sep=sep, low_memory=False)\n if verbose == True:\n display(df.head(3))\n print(df.shape)\n else:\n pass\n return df\n elif verbose == True:\n print(f'ERROR :csv file {filename}, was not found in: \\n {path}')\n else:\n pass\n\n\ndef find_patter_in_series(*, s, pat, tolist=True):\n \"\"\"\n I used that function when i don't remeber full name of a given column\n \"\"\"\n res = s.loc[s.str.contains(pat)]\n if tolist == True:\n return res.values.tolist()\n else:\n return res\n\n\ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=\n False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n \"\"\"\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n \"\"\"\n assert type(data\n ) == pd.DataFrame, 'please provide data in pandas dataframe format'\n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else:\n pass\n for pat in pattern_list:\n columns_with_potential_datetime_obj = list(\n find_and_display_patter_in_series(series=pd.Series(data.columns\n ), pattern=pat))\n for i in columns_with_potential_datetime_obj:\n before_formatting = str(data.loc[0, i])\n if unixtime == True:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', unit='s'\n ).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n else:\n s = pd.to_datetime(data.loc[:, i], errors='coerce', format=\n dt_format).copy()\n data.loc[:, i] = s\n if timezone != None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n if verbose == True:\n print(f'date time formatted in: {i}')\n print(\n f' - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce'\n )\n print(\n f' - Example: {before_formatting} -->> {str(data.loc[0, i])}'\n , end='\\n')\n else:\n pass\n return data\n\n\ndef replace_text(*, df, pat='', colnames='all', fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n searched_pattern = pat\n col_names = colnames\n if col_names == 'all':\n sel_col_names = list(df.columns)\n else:\n sel_col_names = col_names\n if verbose == True:\n print(\n f'\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n'\n )\n if verbose == False:\n pass\n for i, col_name in enumerate(sel_col_names):\n if is_string_dtype(df[col_name]):\n try:\n positions_to_replace = df[col_name].str.contains(\n searched_pattern, na=False).values\n examples_to_display = [str(x) for x in list(df.loc[list(\n positions_to_replace), col_name].str[0:20].values.\n tolist()[0:3])]\n df.loc[list(positions_to_replace), col_name] = [fillna\n ] * positions_to_replace.sum()\n examples_of_positions_that_were_not_replaced = [str(x) for\n x in list(df.loc[list(positions_to_replace == False),\n col_name].str[0:20].values.tolist()[0:3])]\n if verbose == True:\n perc_of_replaced_pos_in_col = ''.join([str(\n positions_to_replace.sum() / df.shape[0] * 100), '%'])\n print(\n f'{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}'\n )\n print(\n f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\"\n , end='\\n')\n print(\n f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\"\n , end='\\n\\n')\n else:\n pass\n except:\n if verbose == True:\n print(\n f\"\"\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \n\"\"\"\n )\n else:\n pass\n elif verbose == True:\n print(\n f'{i} - {col_name} - - is not of string type, Values were not replaced! \\n'\n )\n else:\n pass\n return df.copy()\n\n\ndef replace_numeric_values(*, df, colnames='all', lower_limit='none',\n upper_limit='none', equal=False, replace_with=np.nan, verbose=True):\n \"\"\" \n\n Replace numerical values that are outside of range of a values \n prediced with a theoretical limits of a given variable, \n eg less then 0 in weight of a product, \n Provide examples and numbers of replaced instances\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df : Pandas DataFrame\n * cols_in_df : list, exact colnames of selected or all columns in df\n * lower_limit : int,float,\"none\", if \"none\" no action is taken\n * upper_limit : int,float,\"none\", if \"none\" no action is taken\n * replace_with : str, np.nan, int, float\n * equal : bool, if True, >= and <= values then limits will be replaced,\n if False (default), > and < values then limits will be replaced,\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n cols_names = colnames\n if cols_names == 'all':\n cols = list(df.columns)\n else:\n cols = cols_names\n if verbose == True:\n print(\n f\"\\n{''.join(['-'] * 80)} \\n Replacing Numerical Values in {len(cols)} columns\"\n )\n print(\n f' lower filter={lower_limit}, upper filter ={upper_limit}')\n if equal == True:\n print(\n f' Caution, equal=True, ie. values >= and <= then requested limits will be replaced'\n )\n print(f\"{''.join(['-'] * 80)}\\n\")\n if verbose == False:\n pass\n total_count = []\n count = 0\n for i, j in enumerate(cols):\n info_lower_filter = 0\n info_upper_filter = 0\n if is_numeric_dtype(df[j]):\n if lower_limit != 'none':\n if equal == True:\n lower_filter = df.loc[:, j] <= lower_limit\n if equal == False:\n lower_filter = df.loc[:, j] < lower_limit\n info_lower_filter = lower_filter.sum()\n df.loc[list(lower_filter), j] = replace_with\n if upper_limit != 'none':\n if equal == True:\n upper_filter = df.loc[:, j] >= upper_limit\n if equal == False:\n upper_filter = df.loc[:, j] > upper_limit\n info_upper_filter = upper_filter.sum()\n df.loc[list(upper_filter), j] = replace_with\n total_count.append(info_upper_filter + info_lower_filter)\n if verbose == True:\n if info_upper_filter + info_lower_filter > 0 and count < 4:\n print(\n f'eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}'\n )\n else:\n pass\n count += 1\n elif verbose == True:\n print(f'{i, j} is not of numeric type, values were not replaced !')\n else:\n pass\n if verbose == True:\n if len(total_count) > 3 and pd.Series(total_count).sum() > 0:\n print(\n f\"\"\". and {len(total_count) - 3} other columns had in total {pd.Series(total_count).sum()} replaced values \n\"\"\"\n )\n if pd.Series(total_count).sum() == 0:\n print('No values were replaced in requested columns....')\n else:\n pass\n return df.copy()\n\n\ndef drop_nan(df, method='any', row=True, verbose=True):\n \"\"\"\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n \"\"\"\n assert type(df) == pd.DataFrame, 'incorrect df dtype'\n df = df.copy()\n if verbose == True:\n print(df.shape)\n else:\n pass\n if row == True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n if method == None:\n pass\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis)\n elif isinstance(method, int):\n tr = method\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx] * method))\n if tr == 0:\n pass\n else:\n if tr >= df.shape[shapeidx]:\n tr = df.shape[shapeidx]\n else:\n pass\n df = df.dropna(thresh=tr, axis=dfaxis)\n else:\n pass\n if verbose == True:\n print(df.shape)\n else:\n pass\n return df\n\n\ndef drop_columns(*, df, columns_to_drop, verbose=True):\n \"\"\"\n Small function to quickly remove columns from, \n by column names stored in the list\n - created to give info on removed columns and whether I am chnaging df in proper way,\n - the function allows for column name duplicates, \n \"\"\"\n assert type(df\n ) == pd.DataFrame, 'please provide df in pandas dataframe format'\n df = df.copy()\n columns_to_drop = list(pd.Series(columns_to_drop).unique())\n if verbose == True:\n print(f'Removing {len(columns_to_drop)} columns from df')\n else:\n pass\n for i, j in enumerate(columns_to_drop):\n try:\n df.drop(columns=[j], axis=1, inplace=True)\n if verbose == True:\n print(f'{i} removing: {j}, ==> new df.shape: {df.shape}')\n else:\n pass\n except:\n if verbose == True:\n print(\n f'{i} .... column: {j}, was not found in df, check if name is correct....'\n )\n else:\n pass\n return df\n", "step-5": "# ********************************************************************************** #\n# #\n# Project: Data Frame Explorer # \n# Author: Pawel Rosikiewicz #\n# Contact: prosikiewicz(a)gmail.com #\n# #\n# License: MIT License #\n# Copyright (C) 2021.01.30 Pawel Rosikiewicz #\n# #\n# Permission is hereby granted, free of charge, to any person obtaining a copy #\n# of this software and associated documentation files (the \"Software\"), to deal #\n# in the Software without restriction, including without limitation the rights #\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #\n# copies of the Software, and to permit persons to whom the Software is #\n# furnished to do so, subject to the following conditions: #\n# # \n# The above copyright notice and this permission notice shall be included in all #\n# copies or substantial portions of the Software. #\n# #\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #\n# SOFTWARE. #\n# #\n# ********************************************************************************** #\n\n\n# -*- coding: utf-8 -*-\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport numpy as np\nimport pandas as pd\nimport random\nimport glob\nimport re\nimport os\nimport seaborn as sns\n\nfrom IPython.display import display\nfrom pandas.api.types import is_numeric_dtype\nfrom pandas.api.types import is_string_dtype\n\n\n\n\n\n\n# Function, ............................................................................\ndef find_and_display_patter_in_series(*, series, pattern):\n \"I used that function when i don't remeber full name of a given column\"\n res = series.loc[series.str.contains(pattern)]\n return res\n\n\n\n# Function, ...........................................................................................\ndef load_csv(*, path, filename, sep=\"\\t\", verbose=True):\n \"\"\" \n Loads csv into pandas df, based on pandas.read_scv(), \n Returns error, if file or directoy not found\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * path full path to directory\n * csv_name. full csv file name\n * separator \"\\t\", by default\n * display_head bool, True, by default, display df.head(), \n irrespectively when the futions was called. \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame by Pandas\n\n \"\"\"\n \n os.chdir(path)\n if len(glob.glob(filename))==1: \n df = pd.read_csv(filename, sep=sep, low_memory=False)\n \n # display example,\n if verbose==True:\n display(df.head(3))\n print(df.shape)\n else:\n pass\n \n # return,\n return df\n \n else:\n if verbose==True:\n print(f\"\"\"ERROR :csv file {filename}, was not found in: \\n {path}\"\"\")\n else:\n pass\n\n\n \n \n \n \n# Function, ............................................................................\ndef find_patter_in_series(*, s, pat, tolist=True):\n '''\n I used that function when i don't remeber full name of a given column\n '''\n res = s.loc[s.str.contains(pat)]\n \n if tolist==True:\n return res.values.tolist()\n else:\n return res \n \n \n \n \n\n \n# Function, ........................................................................................... \ndef format_to_datetime(*, data, pattern_list, timezone='UTC', unixtime=False, dt_format='%Y-%m-%d %H:%M:%S', verbose=False):\n '''\n formats columns in df into datetime dtype, and set all times to UTC\n work with unix time units, ie. second number since 1970\n columns in df, are find using full comlumn name or keywords in column name\n '''\n assert type(data)==pd.DataFrame, \"please provide data in pandas dataframe format\"\n \n if isinstance(pattern_list, str):\n pattern_list = [pattern_list]\n else: \n pass\n \n for pat in pattern_list: \n # find column names using provided patterns or their full names, \n columns_with_potential_datetime_obj = list(find_and_display_patter_in_series(series=pd.Series(data.columns), pattern=pat))\n \n # replace \n for i in columns_with_potential_datetime_obj:\n # keep example of old cell \n before_formatting = str(data.loc[0, i])\n \n # convert to one format\n if unixtime==True:\n s = pd.to_datetime(data.loc[:, i], errors=\"coerce\", unit='s').copy()#,format cannot be used with unit=\"s\", but it will be the same\n data.loc[:, i] = s\n if timezone!=None:\n data.loc[:, i] = data.loc[:, i].dt.tz_localize(timezone)\n else:\n pass\n \n else: \n s = pd.to_datetime(data.loc[:, i], errors=\"coerce\",format=dt_format).copy()\n data.loc[:, i] = s\n if timezone!=None:\n data.loc[:, i] = data.loc[:, i].dt.tz_convert(timezone)\n else:\n pass\n \n # info\n if verbose==True:\n print(f\"date time formatted in: {i}\") \n print(f\" - {data.loc[:, i].isnull().sum()} NaN were instroduced by coerce\")\n print(f\" - Example: {before_formatting} -->> {str(data.loc[0, i])}\", end=\"\\n\")\n else:\n pass\n\n return data \n \n \n \n \n \n \n \n# Function, ...........................................................................................\ndef replace_text(*,df ,pat=\"\", colnames=\"all\", fillna=np.nan, verbose=True):\n \"\"\" \n searches string with a given pattern and replace it with a new patter (fillna), eg: nan,\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df Pandas Dataframe\n * searched_pattern \"\", str literal, used by pd.Series.str.contains() \n * colnames default, \"all\", or list with selected colnames in df\n * fillna default numpy.nan, or str literal \n - what do you want to place instead of searched pattern in df\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\"\n \n # for older version, \n searched_pattern = pat\n col_names = colnames\n \n # check col_names with values to replace, \n if col_names==\"all\": \n sel_col_names = list(df.columns)\n else: \n sel_col_names = col_names \n\n # display message header, \n if verbose==True:\n print(f\"\"\"\\nReplacing Text in {len(sel_col_names)} columns: {sel_col_names}\\n\"\"\") \n \n if verbose==False:\n pass\n\n # exchnage searched pattern in each column separately, \n for i, col_name in enumerate(sel_col_names):\n \n # .. test if you really have string values in that column, otherwise it masy be float for all NaN in a column, and no action will be taken \n if is_string_dtype(df[col_name]):\n \n try:\n # .... find postions with a given pattern and select three examples to display for the user, \n positions_to_replace = df[col_name].str.contains(searched_pattern, na=False).values# arr\n examples_to_display = [str(x) for x in list(df.loc[list(positions_to_replace), col_name].str[0:20].values.tolist()[0:3])]\n\n # .... replace postions, and find examples of unchnaged postions,\n df.loc[list(positions_to_replace), col_name] = [fillna]*positions_to_replace.sum() \n examples_of_positions_that_were_not_replaced = [str(x) for x in list(df.loc[list(positions_to_replace==False), col_name].str[0:20].values.tolist()[0:3])]\n\n # .... diplay info,\n if verbose==True:\n perc_of_replaced_pos_in_col = \"\".join([str(positions_to_replace.sum()/df.shape[0]*100),\"%\"])\n print(f\"{i} - {col_name} - - {positions_to_replace.sum()} positions out of {df.shape[0]}, were replaced with {fillna}, ie. {perc_of_replaced_pos_in_col}\")\n print(f\" - three examples of replaced postions: {'; '.join(examples_to_display)}\", end=\"\\n\")\n print(f\" - three examples of unchanged postions: {'; '.join(examples_of_positions_that_were_not_replaced)}\", end=\"\\n\\n\")\n # the second print returns three first examples of exchanged values, just to see what i did,\n else:\n pass\n \n except:\n if verbose==True:\n print(f\"{i} - {col_name} - - probably only missing data datected, Values were not replaced! \\n\") \n else:\n pass\n \n else:\n if verbose==True:\n print(f\"{i} - {col_name} - - is not of string type, Values were not replaced! \\n\") \n else:\n pass\n \n return df.copy()\n\n\n \n \n \n\n\n\n# Function, ...........................................................................................\ndef replace_numeric_values(*, df, colnames=\"all\", lower_limit=\"none\", upper_limit=\"none\", equal=False, replace_with=np.nan, verbose=True):\n \"\"\" \n\n Replace numerical values that are outside of range of a values \n prediced with a theoretical limits of a given variable, \n eg less then 0 in weight of a product, \n Provide examples and numbers of replaced instances\n \n Parameters/Input \n _________________ _______________________________________________________________________________ \n\n * df : Pandas DataFrame\n * cols_in_df : list, exact colnames of selected or all columns in df\n * lower_limit : int,float,\"none\", if \"none\" no action is taken\n * upper_limit : int,float,\"none\", if \"none\" no action is taken\n * replace_with : str, np.nan, int, float\n * equal : bool, if True, >= and <= values then limits will be replaced,\n if False (default), > and < values then limits will be replaced,\n \n Returns \n _________________ _______________________________________________________________________________ \n\n * DataFrame DataFramne.copy() with new values,\n * display messages. number of replaced straings in each column, and examples of replcaced values\n \"\"\" \n\n \n cols_names = colnames\n \n # .. check provided col_names,\n if cols_names==\"all\": \n cols = list(df.columns)\n else: \n cols = cols_names \n\n # .. info, header, \n if verbose==True:\n print(f\"\"\"\\n{\"\".join([\"-\"]*80)} \\n Replacing Numerical Values in {len(cols)} columns\"\"\") \n print(f\" lower filter={lower_limit}, upper filter ={upper_limit}\")\n if equal==True:\n print(f\" Caution, equal=True, ie. values >= and <= then requested limits will be replaced\")\n print(f'{\"\".join([\"-\"]*80)}\\n') \n \n if verbose==False:\n pass\n \n \n # .. intelligent info,\n total_count=[]\n\n # .. count, to limit the number of displayed messages,\n count = 0\n\n # .. replace values and collect examples, \n for i, j in enumerate(cols):\n\n # ..... assume no values were replaced, so the messages work later, \n info_lower_filter = 0\n info_upper_filter = 0 \n \n # ..... test if the column is of the numeric type:\n # from pandas.api.types import is_numeric_dtype\n if is_numeric_dtype(df[j]):\n \n \n # * replace values < or <= lower limit,\n # - ----------------------------------\n if lower_limit!=\"none\": \n if equal == True:\n lower_filter = df.loc[:,j]<=lower_limit\n if equal == False:\n lower_filter = df.loc[:,j]<lower_limit\n \n # info,\n info_lower_filter=lower_filter.sum()\n df.loc[list(lower_filter),j]=replace_with\n \n \n # * replace values > or >= upper limit,\n # - ----------------------------------\n if upper_limit!=\"none\": \n if equal == True:\n upper_filter = df.loc[:,j]>=upper_limit\n if equal == False:\n upper_filter = df.loc[:,j]>upper_limit\n \n # info,\n info_upper_filter=upper_filter.sum()\n df.loc[list(upper_filter),j]=replace_with \n \n # * find how many values were replaced, and add that to the total_count list \n total_count.append(info_upper_filter+info_lower_filter)\n \n # * display examples for 3 first columns with replaced values,\n if verbose==True:\n if info_upper_filter+info_lower_filter>0 and count <4:\n print(f\"eg: {i}, {j} : {info_lower_filter} values <{lower_limit}, ...{info_upper_filter} values <{upper_limit}\")\n else:\n pass\n\n # * add 1 to count, to limit the number of displayed examples,\n count += 1 \n \n else:\n if verbose==True:\n print(f\"{i, j} is not of numeric type, values were not replaced !\")\n else:\n pass\n \n # .. additional message, if more then 2 columns had replaced values, \n if verbose==True:\n if len(total_count)>3 and pd.Series(total_count).sum()>0:\n print(f\". and {len(total_count)-3} other columns had in total {pd.Series(total_count).sum()} replaced values \\n\")\n\n # .. message in case no values vere replaced at all, \n if pd.Series(total_count).sum()==0:\n print(\"No values were replaced in requested columns....\")\n \n else:\n pass\n \n # .. return, \n return df.copy()\n \n \n \n \n\n \n \n# function, ...................................................\ndef drop_nan(df, method=\"any\", row=True, verbose=True): \n '''\n function to dropna with thresholds from rows and columns\n . method\n . any : row/column wiht any missing data are removed\n . all : row/column only wiht missing data are removed\n . int, >0 : keeps row/clumns wiht this or larger number of non missing data\n . float, >0 : as in the above, as fraction\n \n '''\n \n assert type(df)==pd.DataFrame, \"incorrect df dtype\"\n df = df.copy()\n \n if verbose==True:\n print(df.shape)\n else:\n pass\n \n # set funtion for rows or columns, \n if row==True:\n shapeidx, dfaxis = 1, 0\n else:\n shapeidx, dfaxis = 0, 1\n \n # use threshold or \"all\", or None for do nothing, \n if method==None:\n pass\n\n elif isinstance(method, str):\n df = df.dropna(how=method, axis=dfaxis) # removes rows with NaN in all columns \n\n elif isinstance(method, int):\n tr = method\n if tr==0:\n pass\n else:\n if tr>=df.shape[shapeidx]:\n tr=df.shape[shapeidx]\n else:\n pass \n df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value\n\n elif isinstance(method, float):\n tr = int(np.ceil(df.shape[shapeidx]*(method)))\n if tr==0:\n pass\n else:\n if tr>=df.shape[shapeidx]:\n tr=df.shape[shapeidx]\n else:\n pass \n df = df.dropna(thresh=tr, axis=dfaxis) # eg Keep only the rows with at least 2 non-NA value\n else:\n pass\n \n # info and return\n if verbose==True:\n print(df.shape)\n else:\n pass\n return df\n \n \n \n \n \n \n \n \n# Function, ...........................................................................................\ndef drop_columns(*, df, columns_to_drop, verbose=True):\n \"\"\"\n Small function to quickly remove columns from, \n by column names stored in the list\n - created to give info on removed columns and whether I am chnaging df in proper way,\n - the function allows for column name duplicates, \n \"\"\"\n \n assert type(df)==pd.DataFrame, \"please provide df in pandas dataframe format\"\n df = df.copy()\n \n # find unique values in a list, just in case I made the mistake, \n columns_to_drop = list(pd.Series(columns_to_drop).unique())\n\n # .. info, header, \n if verbose==True:\n print(f\"\"\"Removing {len(columns_to_drop)} columns from df\"\"\") \n else:\n pass\n\n \n # remove columns one by one, \n for i,j in enumerate(columns_to_drop):\n try:\n df.drop(columns=[j], axis=1, inplace=True)\n if verbose==True:\n print(f\"{i} removing: {j}, ==> new df.shape: {df.shape}\")\n else:\n pass\n \n except:\n if verbose==True:\n print(f\"{i} .... column: {j}, was not found in df, check if name is correct....\")\n else:\n pass\n \n return df\n\n", "step-ids": [ 4, 5, 7, 8, 10 ] }
[ 4, 5, 7, 8, 10 ]
botName = "firstBot" username = "mrthemafia" password = "oblivion" client_id = "Y3LQwponbEp07w" client_secret = "R4oyCEj6hSTJWHfWMwb-DGUOBm8"
normal
{ "blob_id": "3031f695d57492cf3b29694fecd0a41c469a3e00", "index": 7481, "step-1": "<mask token>\n", "step-2": "botName = 'firstBot'\nusername = 'mrthemafia'\npassword = 'oblivion'\nclient_id = 'Y3LQwponbEp07w'\nclient_secret = 'R4oyCEj6hSTJWHfWMwb-DGUOBm8'\n", "step-3": "botName = \"firstBot\"\nusername = \"mrthemafia\"\npassword = \"oblivion\"\nclient_id = \"Y3LQwponbEp07w\"\nclient_secret = \"R4oyCEj6hSTJWHfWMwb-DGUOBm8\"\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) y = self.predict(h1) return y <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) y = self.predict(h1) return y <|reserved_special_token_0|> net.load_state_dict(torch.load('net_data_multi.pkl')) <|reserved_special_token_0|> file_out.write('caseid,midprice\n') <|reserved_special_token_0|> while case < 143: line = file_test.readline().split(',') if len(line) < 9: case += 1 while case <= 153: x = torch.FloatTensor(40).zero_() y = torch.FloatTensor(20).zero_() for ct in range(10): line = file_test.readline() if line == '': break line = line.split(',') x[ct * 4] = float(line[6]) x[ct * 4 + 1] = float(line[7]) / 10000 x[ct * 4 + 2] = float(line[8]) x[ct * 4 + 3] = float(line[9]) / 10000 prediction = net(x) average = 0 for k in range(10): average += prediction.data.numpy()[k] average = 1.0 * average / 10 file_out.write(str(case) + ',' + str(average) + '\n') line = file_test.readline() case += 1 file_test.close() file_out.close() print('test complete') <|reserved_special_token_1|> <|reserved_special_token_0|> class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) y = self.predict(h1) return y net = Net(n_feature=40, n_hidden=10, n_output=20) net.load_state_dict(torch.load('net_data_multi.pkl')) file_test = open('dataset/test_data.csv', 'r') line = file_test.readline() file_out = open('result_multi.csv', 'w') file_out.write('caseid,midprice\n') case = 1 while case < 143: line = file_test.readline().split(',') if len(line) < 9: case += 1 while case <= 153: x = torch.FloatTensor(40).zero_() y = torch.FloatTensor(20).zero_() for ct in range(10): line = file_test.readline() if line == '': break line = line.split(',') x[ct * 4] = float(line[6]) x[ct * 4 + 1] = float(line[7]) / 10000 x[ct * 4 + 2] = float(line[8]) x[ct * 4 + 3] = float(line[9]) / 10000 prediction = net(x) average = 0 for k in range(10): average += prediction.data.numpy()[k] average = 1.0 * average / 10 file_out.write(str(case) + ',' + str(average) + '\n') line = file_test.readline() case += 1 file_test.close() file_out.close() print('test complete') <|reserved_special_token_1|> import torch import torch.nn.functional as F import csv class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) y = self.predict(h1) return y net = Net(n_feature=40, n_hidden=10, n_output=20) net.load_state_dict(torch.load('net_data_multi.pkl')) file_test = open('dataset/test_data.csv', 'r') line = file_test.readline() file_out = open('result_multi.csv', 'w') file_out.write('caseid,midprice\n') case = 1 while case < 143: line = file_test.readline().split(',') if len(line) < 9: case += 1 while case <= 153: x = torch.FloatTensor(40).zero_() y = torch.FloatTensor(20).zero_() for ct in range(10): line = file_test.readline() if line == '': break line = line.split(',') x[ct * 4] = float(line[6]) x[ct * 4 + 1] = float(line[7]) / 10000 x[ct * 4 + 2] = float(line[8]) x[ct * 4 + 3] = float(line[9]) / 10000 prediction = net(x) average = 0 for k in range(10): average += prediction.data.numpy()[k] average = 1.0 * average / 10 file_out.write(str(case) + ',' + str(average) + '\n') line = file_test.readline() case += 1 file_test.close() file_out.close() print('test complete') <|reserved_special_token_1|> import torch import torch.nn.functional as F import csv class Net(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output): super(Net, self).__init__() self.hidden = torch.nn.Linear(n_feature, n_hidden) self.predict = torch.nn.Linear(n_hidden, n_output) def forward(self, x): h1 = F.relu(self.hidden(x)) y = self.predict(h1) return y net = Net(n_feature=40, n_hidden=10, n_output=20) net.load_state_dict(torch.load('net_data_multi.pkl')) file_test = open('dataset/test_data.csv','r') line = file_test.readline() file_out = open('result_multi.csv','w') file_out.write('caseid,midprice\n') case = 1 while case < 143: line = file_test.readline().split(',') if len(line) < 9: case += 1 while case <= 153: x = torch.FloatTensor(40).zero_() y = torch.FloatTensor(20).zero_() for ct in range(10): line = file_test.readline() if line == '': break line = line.split(',') x[ct*4] = float(line[6]) x[ct*4+1] = float(line[7])/10000 x[ct*4+2] = float(line[8]) x[ct*4+3] = float(line[9])/10000 prediction = net(x) average = 0 for k in range(10): average += prediction.data.numpy()[k] average = 1.0*average/10 file_out.write(str(case)+','+str(average)+'\n') #print(str(case)+','+str(average)+'\n') line = file_test.readline() case += 1 file_test.close() file_out.close() print('test complete')
flexible
{ "blob_id": "e221553f866de8b3e175197a40982506bf8c1ef9", "index": 205, "step-1": "<mask token>\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n\n def forward(self, x):\n h1 = F.relu(self.hidden(x))\n y = self.predict(h1)\n return y\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n\n def forward(self, x):\n h1 = F.relu(self.hidden(x))\n y = self.predict(h1)\n return y\n\n\n<mask token>\nnet.load_state_dict(torch.load('net_data_multi.pkl'))\n<mask token>\nfile_out.write('caseid,midprice\\n')\n<mask token>\nwhile case < 143:\n line = file_test.readline().split(',')\n if len(line) < 9:\n case += 1\nwhile case <= 153:\n x = torch.FloatTensor(40).zero_()\n y = torch.FloatTensor(20).zero_()\n for ct in range(10):\n line = file_test.readline()\n if line == '':\n break\n line = line.split(',')\n x[ct * 4] = float(line[6])\n x[ct * 4 + 1] = float(line[7]) / 10000\n x[ct * 4 + 2] = float(line[8])\n x[ct * 4 + 3] = float(line[9]) / 10000\n prediction = net(x)\n average = 0\n for k in range(10):\n average += prediction.data.numpy()[k]\n average = 1.0 * average / 10\n file_out.write(str(case) + ',' + str(average) + '\\n')\n line = file_test.readline()\n case += 1\nfile_test.close()\nfile_out.close()\nprint('test complete')\n", "step-3": "<mask token>\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n\n def forward(self, x):\n h1 = F.relu(self.hidden(x))\n y = self.predict(h1)\n return y\n\n\nnet = Net(n_feature=40, n_hidden=10, n_output=20)\nnet.load_state_dict(torch.load('net_data_multi.pkl'))\nfile_test = open('dataset/test_data.csv', 'r')\nline = file_test.readline()\nfile_out = open('result_multi.csv', 'w')\nfile_out.write('caseid,midprice\\n')\ncase = 1\nwhile case < 143:\n line = file_test.readline().split(',')\n if len(line) < 9:\n case += 1\nwhile case <= 153:\n x = torch.FloatTensor(40).zero_()\n y = torch.FloatTensor(20).zero_()\n for ct in range(10):\n line = file_test.readline()\n if line == '':\n break\n line = line.split(',')\n x[ct * 4] = float(line[6])\n x[ct * 4 + 1] = float(line[7]) / 10000\n x[ct * 4 + 2] = float(line[8])\n x[ct * 4 + 3] = float(line[9]) / 10000\n prediction = net(x)\n average = 0\n for k in range(10):\n average += prediction.data.numpy()[k]\n average = 1.0 * average / 10\n file_out.write(str(case) + ',' + str(average) + '\\n')\n line = file_test.readline()\n case += 1\nfile_test.close()\nfile_out.close()\nprint('test complete')\n", "step-4": "import torch\nimport torch.nn.functional as F\nimport csv\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n\n def forward(self, x):\n h1 = F.relu(self.hidden(x))\n y = self.predict(h1)\n return y\n\n\nnet = Net(n_feature=40, n_hidden=10, n_output=20)\nnet.load_state_dict(torch.load('net_data_multi.pkl'))\nfile_test = open('dataset/test_data.csv', 'r')\nline = file_test.readline()\nfile_out = open('result_multi.csv', 'w')\nfile_out.write('caseid,midprice\\n')\ncase = 1\nwhile case < 143:\n line = file_test.readline().split(',')\n if len(line) < 9:\n case += 1\nwhile case <= 153:\n x = torch.FloatTensor(40).zero_()\n y = torch.FloatTensor(20).zero_()\n for ct in range(10):\n line = file_test.readline()\n if line == '':\n break\n line = line.split(',')\n x[ct * 4] = float(line[6])\n x[ct * 4 + 1] = float(line[7]) / 10000\n x[ct * 4 + 2] = float(line[8])\n x[ct * 4 + 3] = float(line[9]) / 10000\n prediction = net(x)\n average = 0\n for k in range(10):\n average += prediction.data.numpy()[k]\n average = 1.0 * average / 10\n file_out.write(str(case) + ',' + str(average) + '\\n')\n line = file_test.readline()\n case += 1\nfile_test.close()\nfile_out.close()\nprint('test complete')\n", "step-5": "import torch\nimport torch.nn.functional as F\nimport csv\n\n\nclass Net(torch.nn.Module):\n\n def __init__(self, n_feature, n_hidden, n_output):\n super(Net, self).__init__()\n self.hidden = torch.nn.Linear(n_feature, n_hidden)\n self.predict = torch.nn.Linear(n_hidden, n_output)\n\n def forward(self, x):\n h1 = F.relu(self.hidden(x))\n y = self.predict(h1) \n return y\n\n\nnet = Net(n_feature=40, n_hidden=10, n_output=20)\n\nnet.load_state_dict(torch.load('net_data_multi.pkl'))\n\nfile_test = open('dataset/test_data.csv','r')\nline = file_test.readline()\n\nfile_out = open('result_multi.csv','w')\nfile_out.write('caseid,midprice\\n')\n\ncase = 1\n\nwhile case < 143:\n line = file_test.readline().split(',')\n if len(line) < 9:\n case += 1\n \nwhile case <= 153:\n x = torch.FloatTensor(40).zero_()\n y = torch.FloatTensor(20).zero_()\n\n for ct in range(10):\n line = file_test.readline()\n if line == '':\n break\n line = line.split(',')\n\n x[ct*4] = float(line[6])\n x[ct*4+1] = float(line[7])/10000\n x[ct*4+2] = float(line[8])\n x[ct*4+3] = float(line[9])/10000\n\n prediction = net(x)\n\n average = 0\n for k in range(10):\n average += prediction.data.numpy()[k]\n average = 1.0*average/10\n\n file_out.write(str(case)+','+str(average)+'\\n')\n #print(str(case)+','+str(average)+'\\n')\n\n line = file_test.readline()\n case += 1\n\nfile_test.close()\nfile_out.close()\nprint('test complete')\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> class GameManager: def __init__(self): self.screen = pygame.display.set_mode((1280, 720), flags=pygame. FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) self.running = True self.delta_time = 1 self.active_scene = None self.load_scene(MainGame.MainGame, (self,)) self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14 ) self.pygame_clock = pygame.time.Clock() self.pygame_clock.tick() pygame.joystick.init() self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame. joystick.get_count())] for joystick in self.joystick: joystick.init() random.seed(time.time()) self.player_joy = -1 <|reserved_special_token_0|> def main_loop(self): while self.running: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.exit() self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3 fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self .delta_time)), False, (255, 255, 255)) self.active_scene.main_loop(events) self.screen.blit(fps_text, (self.screen.get_width() - fps_text. get_width(), 0)) pygame.display.flip() def load_scene(self, scene_object, scene_parameters): self.active_scene = scene_object(*scene_parameters) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class GameManager: def __init__(self): self.screen = pygame.display.set_mode((1280, 720), flags=pygame. FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) self.running = True self.delta_time = 1 self.active_scene = None self.load_scene(MainGame.MainGame, (self,)) self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14 ) self.pygame_clock = pygame.time.Clock() self.pygame_clock.tick() pygame.joystick.init() self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame. joystick.get_count())] for joystick in self.joystick: joystick.init() random.seed(time.time()) self.player_joy = -1 def __del__(self): self.exit() def main_loop(self): while self.running: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.exit() self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3 fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self .delta_time)), False, (255, 255, 255)) self.active_scene.main_loop(events) self.screen.blit(fps_text, (self.screen.get_width() - fps_text. get_width(), 0)) pygame.display.flip() def load_scene(self, scene_object, scene_parameters): self.active_scene = scene_object(*scene_parameters) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class GameManager: def __init__(self): self.screen = pygame.display.set_mode((1280, 720), flags=pygame. FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) self.running = True self.delta_time = 1 self.active_scene = None self.load_scene(MainGame.MainGame, (self,)) self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14 ) self.pygame_clock = pygame.time.Clock() self.pygame_clock.tick() pygame.joystick.init() self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame. joystick.get_count())] for joystick in self.joystick: joystick.init() random.seed(time.time()) self.player_joy = -1 def __del__(self): self.exit() def main_loop(self): while self.running: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.exit() self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3 fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self .delta_time)), False, (255, 255, 255)) self.active_scene.main_loop(events) self.screen.blit(fps_text, (self.screen.get_width() - fps_text. get_width(), 0)) pygame.display.flip() def load_scene(self, scene_object, scene_parameters): self.active_scene = scene_object(*scene_parameters) def exit(self): self.running = False <|reserved_special_token_1|> import pygame import time from menus import MainMenu from scenes import TestWorldGen from scenes import TestAnimation from scenes import TestLevel2 from scenes import MainGame import random class GameManager: def __init__(self): self.screen = pygame.display.set_mode((1280, 720), flags=pygame. FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) self.running = True self.delta_time = 1 self.active_scene = None self.load_scene(MainGame.MainGame, (self,)) self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14 ) self.pygame_clock = pygame.time.Clock() self.pygame_clock.tick() pygame.joystick.init() self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame. joystick.get_count())] for joystick in self.joystick: joystick.init() random.seed(time.time()) self.player_joy = -1 def __del__(self): self.exit() def main_loop(self): while self.running: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.exit() self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3 fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self .delta_time)), False, (255, 255, 255)) self.active_scene.main_loop(events) self.screen.blit(fps_text, (self.screen.get_width() - fps_text. get_width(), 0)) pygame.display.flip() def load_scene(self, scene_object, scene_parameters): self.active_scene = scene_object(*scene_parameters) def exit(self): self.running = False <|reserved_special_token_1|> import pygame import time from menus import MainMenu from scenes import TestWorldGen from scenes import TestAnimation from scenes import TestLevel2 from scenes import MainGame import random class GameManager: def __init__(self): self.screen = pygame.display.set_mode((1280, 720), flags=pygame.FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF) # type: pygame.Surface self.running = True self.delta_time = 1 self.active_scene = None # self.load_scene(MainMenu.MainMenu, (self,)) # self.load_scene(TestWorldGen.TestWorldGen, (self,)) # self.load_scene(TestAnimation.TestAnimation, (self,)) # self.load_scene(TestLevel2.TestLevel, (self, )) self.load_scene(MainGame.MainGame, (self,)) self.fps_font = pygame.font.Font("game_data/fonts/calling_code.ttf", 14) self.pygame_clock = pygame.time.Clock() # type: pygame self.pygame_clock.tick() pygame.joystick.init() self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())] for joystick in self.joystick: joystick.init() random.seed(time.time()) self.player_joy = -1 def __del__(self): self.exit() def main_loop(self): while self.running: events = pygame.event.get() for event in events: if event.type == pygame.QUIT: self.exit() self.delta_time = float(self.pygame_clock.tick(60)) / (10 ** 3) fps_text = self.fps_font.render("FPS: {}".format(round(1 / self.delta_time)), False, (255, 255, 255)) self.active_scene.main_loop(events) self.screen.blit(fps_text, (self.screen.get_width() - fps_text.get_width(), 0)) pygame.display.flip() def load_scene(self, scene_object, scene_parameters): self.active_scene = scene_object(*scene_parameters) def exit(self): self.running = False
flexible
{ "blob_id": "91806afea92587476ac743346b88098b197a033c", "index": 9706, "step-1": "<mask token>\n\n\nclass GameManager:\n\n def __init__(self):\n self.screen = pygame.display.set_mode((1280, 720), flags=pygame.\n FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF)\n self.running = True\n self.delta_time = 1\n self.active_scene = None\n self.load_scene(MainGame.MainGame, (self,))\n self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14\n )\n self.pygame_clock = pygame.time.Clock()\n self.pygame_clock.tick()\n pygame.joystick.init()\n self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame.\n joystick.get_count())]\n for joystick in self.joystick:\n joystick.init()\n random.seed(time.time())\n self.player_joy = -1\n <mask token>\n\n def main_loop(self):\n while self.running:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n self.exit()\n self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3\n fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self\n .delta_time)), False, (255, 255, 255))\n self.active_scene.main_loop(events)\n self.screen.blit(fps_text, (self.screen.get_width() - fps_text.\n get_width(), 0))\n pygame.display.flip()\n\n def load_scene(self, scene_object, scene_parameters):\n self.active_scene = scene_object(*scene_parameters)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass GameManager:\n\n def __init__(self):\n self.screen = pygame.display.set_mode((1280, 720), flags=pygame.\n FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF)\n self.running = True\n self.delta_time = 1\n self.active_scene = None\n self.load_scene(MainGame.MainGame, (self,))\n self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14\n )\n self.pygame_clock = pygame.time.Clock()\n self.pygame_clock.tick()\n pygame.joystick.init()\n self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame.\n joystick.get_count())]\n for joystick in self.joystick:\n joystick.init()\n random.seed(time.time())\n self.player_joy = -1\n\n def __del__(self):\n self.exit()\n\n def main_loop(self):\n while self.running:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n self.exit()\n self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3\n fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self\n .delta_time)), False, (255, 255, 255))\n self.active_scene.main_loop(events)\n self.screen.blit(fps_text, (self.screen.get_width() - fps_text.\n get_width(), 0))\n pygame.display.flip()\n\n def load_scene(self, scene_object, scene_parameters):\n self.active_scene = scene_object(*scene_parameters)\n <mask token>\n", "step-3": "<mask token>\n\n\nclass GameManager:\n\n def __init__(self):\n self.screen = pygame.display.set_mode((1280, 720), flags=pygame.\n FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF)\n self.running = True\n self.delta_time = 1\n self.active_scene = None\n self.load_scene(MainGame.MainGame, (self,))\n self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14\n )\n self.pygame_clock = pygame.time.Clock()\n self.pygame_clock.tick()\n pygame.joystick.init()\n self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame.\n joystick.get_count())]\n for joystick in self.joystick:\n joystick.init()\n random.seed(time.time())\n self.player_joy = -1\n\n def __del__(self):\n self.exit()\n\n def main_loop(self):\n while self.running:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n self.exit()\n self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3\n fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self\n .delta_time)), False, (255, 255, 255))\n self.active_scene.main_loop(events)\n self.screen.blit(fps_text, (self.screen.get_width() - fps_text.\n get_width(), 0))\n pygame.display.flip()\n\n def load_scene(self, scene_object, scene_parameters):\n self.active_scene = scene_object(*scene_parameters)\n\n def exit(self):\n self.running = False\n", "step-4": "import pygame\nimport time\nfrom menus import MainMenu\nfrom scenes import TestWorldGen\nfrom scenes import TestAnimation\nfrom scenes import TestLevel2\nfrom scenes import MainGame\nimport random\n\n\nclass GameManager:\n\n def __init__(self):\n self.screen = pygame.display.set_mode((1280, 720), flags=pygame.\n FULLSCREEN | pygame.HWSURFACE | pygame.DOUBLEBUF)\n self.running = True\n self.delta_time = 1\n self.active_scene = None\n self.load_scene(MainGame.MainGame, (self,))\n self.fps_font = pygame.font.Font('game_data/fonts/calling_code.ttf', 14\n )\n self.pygame_clock = pygame.time.Clock()\n self.pygame_clock.tick()\n pygame.joystick.init()\n self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame.\n joystick.get_count())]\n for joystick in self.joystick:\n joystick.init()\n random.seed(time.time())\n self.player_joy = -1\n\n def __del__(self):\n self.exit()\n\n def main_loop(self):\n while self.running:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n self.exit()\n self.delta_time = float(self.pygame_clock.tick(60)) / 10 ** 3\n fps_text = self.fps_font.render('FPS: {}'.format(round(1 / self\n .delta_time)), False, (255, 255, 255))\n self.active_scene.main_loop(events)\n self.screen.blit(fps_text, (self.screen.get_width() - fps_text.\n get_width(), 0))\n pygame.display.flip()\n\n def load_scene(self, scene_object, scene_parameters):\n self.active_scene = scene_object(*scene_parameters)\n\n def exit(self):\n self.running = False\n", "step-5": "import pygame\nimport time\nfrom menus import MainMenu\nfrom scenes import TestWorldGen\nfrom scenes import TestAnimation\nfrom scenes import TestLevel2\nfrom scenes import MainGame\nimport random\n\n\nclass GameManager:\n def __init__(self):\n self.screen = pygame.display.set_mode((1280, 720),\n flags=pygame.FULLSCREEN |\n pygame.HWSURFACE |\n pygame.DOUBLEBUF) # type: pygame.Surface\n\n self.running = True\n\n self.delta_time = 1\n\n self.active_scene = None\n # self.load_scene(MainMenu.MainMenu, (self,))\n # self.load_scene(TestWorldGen.TestWorldGen, (self,))\n # self.load_scene(TestAnimation.TestAnimation, (self,))\n # self.load_scene(TestLevel2.TestLevel, (self, ))\n self.load_scene(MainGame.MainGame, (self,))\n\n self.fps_font = pygame.font.Font(\"game_data/fonts/calling_code.ttf\", 14)\n\n self.pygame_clock = pygame.time.Clock() # type: pygame\n self.pygame_clock.tick()\n pygame.joystick.init()\n self.joystick = [pygame.joystick.Joystick(i) for i in range(pygame.joystick.get_count())]\n for joystick in self.joystick:\n joystick.init()\n\n random.seed(time.time())\n\n self.player_joy = -1\n\n def __del__(self):\n self.exit()\n\n def main_loop(self):\n while self.running:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n self.exit()\n\n self.delta_time = float(self.pygame_clock.tick(60)) / (10 ** 3)\n\n fps_text = self.fps_font.render(\"FPS: {}\".format(round(1 / self.delta_time)), False, (255, 255, 255))\n\n self.active_scene.main_loop(events)\n\n self.screen.blit(fps_text, (self.screen.get_width() - fps_text.get_width(), 0))\n\n pygame.display.flip()\n\n def load_scene(self, scene_object, scene_parameters):\n self.active_scene = scene_object(*scene_parameters)\n\n def exit(self):\n self.running = False\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> class Autorization: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class AutorizationClient(Autorization): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() token = request.session['token'] title_page = _('User - User Affiliation').title() filters = {} form_filters = AuthorizationClientFilter(request.GET) if form_filters.is_valid(): filters = form_filters.cleaned_data tools = Tools() filters['from_date'] = tools.date_format_to_db(date=filters[ 'from_date']) filters['until_date'] = tools.date_format_to_db(date=filters[ 'until_date']) filters = form_filters.cleaned_data if request.method == 'GET': if 'approve' in request.GET and request.GET['approve']: pk = request.GET['approve'] data = {'status': 1} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) if 'rejected' in request.GET and request.GET['rejected']: pk = request.GET['rejected'] data = {'status': 2} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) data = obj_api.get(slug='authorizations/clients/', arg=filters, token=token) header_table = [('', 'code_seller'), ('', 'name'), ('', 'document_type_name'), ('', 'document'), ('', ''), ('', ''), ( '', 'document'), ('', 'approve'), ('', 'rejected'), ('', 'date_join')] multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'), {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan': '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2', 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan': '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_( 'name or Social reason'), {}), (_('type document'), {}), (_( 'document number'), {}), (_('description'), {}), (_( 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]] approve_column = {'type': 'submit', 'data': {'name': 'approve', 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}} rejected_column = {'type': 'submit', 'data': {'name': 'rejected', 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}} custom_column = {'date_join': {'type': 'date', 'data': ('date_join' ,)}, 'approve': {'type': 'if_eval', 'data': ('r["status"]=="0"' ,), 'next': approve_column}, 'rejected': {'type': 'if_eval', 'data': ('r["status"]=="0"',), 'next': rejected_column}} table = convert(data, header=header_table, multi_header= multi_header, custom_column=custom_column) vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/authorization/clients.html', {'table': table, 'vars_page': vars_page, 'form_filters': form_filters}) <|reserved_special_token_1|> <|reserved_special_token_0|> class Autorization: <|reserved_special_token_0|> <|reserved_special_token_0|> def generate_header(self, custom_title=None): if custom_title: title = '{} - '.format(_('authorizations')).title() + custom_title else: title = self.title_content_header header = {'icon': self.logo_content_header, 'title': title} return {**header, **self.vars_page} class AutorizationClient(Autorization): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() token = request.session['token'] title_page = _('User - User Affiliation').title() filters = {} form_filters = AuthorizationClientFilter(request.GET) if form_filters.is_valid(): filters = form_filters.cleaned_data tools = Tools() filters['from_date'] = tools.date_format_to_db(date=filters[ 'from_date']) filters['until_date'] = tools.date_format_to_db(date=filters[ 'until_date']) filters = form_filters.cleaned_data if request.method == 'GET': if 'approve' in request.GET and request.GET['approve']: pk = request.GET['approve'] data = {'status': 1} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) if 'rejected' in request.GET and request.GET['rejected']: pk = request.GET['rejected'] data = {'status': 2} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) data = obj_api.get(slug='authorizations/clients/', arg=filters, token=token) header_table = [('', 'code_seller'), ('', 'name'), ('', 'document_type_name'), ('', 'document'), ('', ''), ('', ''), ( '', 'document'), ('', 'approve'), ('', 'rejected'), ('', 'date_join')] multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'), {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan': '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2', 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan': '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_( 'name or Social reason'), {}), (_('type document'), {}), (_( 'document number'), {}), (_('description'), {}), (_( 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]] approve_column = {'type': 'submit', 'data': {'name': 'approve', 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}} rejected_column = {'type': 'submit', 'data': {'name': 'rejected', 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}} custom_column = {'date_join': {'type': 'date', 'data': ('date_join' ,)}, 'approve': {'type': 'if_eval', 'data': ('r["status"]=="0"' ,), 'next': approve_column}, 'rejected': {'type': 'if_eval', 'data': ('r["status"]=="0"',), 'next': rejected_column}} table = convert(data, header=header_table, multi_header= multi_header, custom_column=custom_column) vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/authorization/clients.html', {'table': table, 'vars_page': vars_page, 'form_filters': form_filters}) <|reserved_special_token_1|> <|reserved_special_token_0|> class Autorization: logo_content_header = 'fa fa-key' vars_page = {} def generate_header(self, custom_title=None): if custom_title: title = '{} - '.format(_('authorizations')).title() + custom_title else: title = self.title_content_header header = {'icon': self.logo_content_header, 'title': title} return {**header, **self.vars_page} class AutorizationClient(Autorization): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() token = request.session['token'] title_page = _('User - User Affiliation').title() filters = {} form_filters = AuthorizationClientFilter(request.GET) if form_filters.is_valid(): filters = form_filters.cleaned_data tools = Tools() filters['from_date'] = tools.date_format_to_db(date=filters[ 'from_date']) filters['until_date'] = tools.date_format_to_db(date=filters[ 'until_date']) filters = form_filters.cleaned_data if request.method == 'GET': if 'approve' in request.GET and request.GET['approve']: pk = request.GET['approve'] data = {'status': 1} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) if 'rejected' in request.GET and request.GET['rejected']: pk = request.GET['rejected'] data = {'status': 2} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) data = obj_api.get(slug='authorizations/clients/', arg=filters, token=token) header_table = [('', 'code_seller'), ('', 'name'), ('', 'document_type_name'), ('', 'document'), ('', ''), ('', ''), ( '', 'document'), ('', 'approve'), ('', 'rejected'), ('', 'date_join')] multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'), {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan': '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2', 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan': '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_( 'name or Social reason'), {}), (_('type document'), {}), (_( 'document number'), {}), (_('description'), {}), (_( 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]] approve_column = {'type': 'submit', 'data': {'name': 'approve', 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}} rejected_column = {'type': 'submit', 'data': {'name': 'rejected', 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}} custom_column = {'date_join': {'type': 'date', 'data': ('date_join' ,)}, 'approve': {'type': 'if_eval', 'data': ('r["status"]=="0"' ,), 'next': approve_column}, 'rejected': {'type': 'if_eval', 'data': ('r["status"]=="0"',), 'next': rejected_column}} table = convert(data, header=header_table, multi_header= multi_header, custom_column=custom_column) vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/authorization/clients.html', {'table': table, 'vars_page': vars_page, 'form_filters': form_filters}) <|reserved_special_token_1|> <|reserved_special_token_0|> from django.shortcuts import render from dashboard.json2table import convert from django.utils.translation import ugettext_lazy as _ from api.connection import api from login.utils.tools import role_admin_check from django.utils.decorators import method_decorator from django.contrib.auth.decorators import user_passes_test from dashboard.tools import capitalize as cap, ToolsBackend as Tools from dashboard.forms import AuthorizationClientFilter class Autorization: logo_content_header = 'fa fa-key' vars_page = {} def generate_header(self, custom_title=None): if custom_title: title = '{} - '.format(_('authorizations')).title() + custom_title else: title = self.title_content_header header = {'icon': self.logo_content_header, 'title': title} return {**header, **self.vars_page} class AutorizationClient(Autorization): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() token = request.session['token'] title_page = _('User - User Affiliation').title() filters = {} form_filters = AuthorizationClientFilter(request.GET) if form_filters.is_valid(): filters = form_filters.cleaned_data tools = Tools() filters['from_date'] = tools.date_format_to_db(date=filters[ 'from_date']) filters['until_date'] = tools.date_format_to_db(date=filters[ 'until_date']) filters = form_filters.cleaned_data if request.method == 'GET': if 'approve' in request.GET and request.GET['approve']: pk = request.GET['approve'] data = {'status': 1} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) if 'rejected' in request.GET and request.GET['rejected']: pk = request.GET['rejected'] data = {'status': 2} obj_api.put(slug='authorizations/clients/' + pk, token= token, arg=data) data = obj_api.get(slug='authorizations/clients/', arg=filters, token=token) header_table = [('', 'code_seller'), ('', 'name'), ('', 'document_type_name'), ('', 'document'), ('', ''), ('', ''), ( '', 'document'), ('', 'approve'), ('', 'rejected'), ('', 'date_join')] multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'), {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan': '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2', 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan': '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_( 'name or Social reason'), {}), (_('type document'), {}), (_( 'document number'), {}), (_('description'), {}), (_( 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]] approve_column = {'type': 'submit', 'data': {'name': 'approve', 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}} rejected_column = {'type': 'submit', 'data': {'name': 'rejected', 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}} custom_column = {'date_join': {'type': 'date', 'data': ('date_join' ,)}, 'approve': {'type': 'if_eval', 'data': ('r["status"]=="0"' ,), 'next': approve_column}, 'rejected': {'type': 'if_eval', 'data': ('r["status"]=="0"',), 'next': rejected_column}} table = convert(data, header=header_table, multi_header= multi_header, custom_column=custom_column) vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/authorization/clients.html', {'table': table, 'vars_page': vars_page, 'form_filters': form_filters}) <|reserved_special_token_1|> """Vista de Autorizaciones (Clientes/Especialistas/Vendedores).""" from django.shortcuts import render from dashboard.json2table import convert from django.utils.translation import ugettext_lazy as _ from api.connection import api from login.utils.tools import role_admin_check from django.utils.decorators import method_decorator from django.contrib.auth.decorators import user_passes_test from dashboard.tools import capitalize as cap, ToolsBackend as Tools from dashboard.forms import AuthorizationClientFilter class Autorization: logo_content_header = "fa fa-key" vars_page = {} def generate_header(self, custom_title=None): if custom_title: title = "{} - ".format(_("authorizations")).title() + custom_title else: title = self.title_content_header header = {'icon': self.logo_content_header, 'title': title} return {**header, **self.vars_page} class AutorizationClient(Autorization): """ Manejo de autorizaciones de clientes, se listan los clientes, en orden de pendiente, aprobado y rechazado, segun fecha Para posterior aprovacion o rechazo """ @method_decorator(user_passes_test(role_admin_check())) def list(self, request): """ Listado de clientes por autorizar, se incluyen tambien clientes aprovados y rechazados """ obj_api = api() # actual_page = get_actual_page(request) token = request.session['token'] title_page = _('User - User Affiliation').title() filters = {} form_filters = AuthorizationClientFilter(request.GET) if form_filters.is_valid(): # Agregamos filtros de encontrarse alguno filters = form_filters.cleaned_data tools = Tools() filters['from_date'] = tools.date_format_to_db(date=filters['from_date']) filters['until_date'] = tools.date_format_to_db(date=filters['until_date']) filters = form_filters.cleaned_data if request.method == 'GET': if 'approve' in request.GET and request.GET['approve']: pk = request.GET['approve'] data = {"status":1} obj_api.put(slug='authorizations/clients/' + pk, token=token, arg=data) if 'rejected' in request.GET and request.GET['rejected']: pk = request.GET['rejected'] data = {"status":2} obj_api.put(slug='authorizations/clients/' + pk, token=token, arg=data) # Traer data para el listado data = obj_api.get(slug='authorizations/clients/', arg=filters, token=token) header_table = [("", "code_seller"), ("", "name"),( "", "document_type_name"), ( "", "document"),( "", ""), ("", ""), ( "", "document"), ( "", "approve"), ("", "rejected"), ( "", "date_join")] # Multiples header, una lista por cada nivel de la cabecera multi_header = [ [ (_("seller code"), {'rowspan': '2'}), (_('user'), {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan': '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2', 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan': '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'}), ], [ (_('name or Social reason'), {}), (_('type document'), {}), (_('document number'), {}), (_('description'), {}), (_('Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {}), ], ] approve_column = {'type': 'submit', 'data': {'name':'approve','key':'id', 'cls':'btn btn-success','text':cap(_('approve'))}} rejected_column = {'type': 'submit', 'data': {'name':'rejected','key':'id', 'cls':'btn btn-danger','text':cap(_('rejected'))}} custom_column = { "date_join": {'type': 'date', 'data': ('date_join',)}, "approve": {'type': 'if_eval', 'data': ('r["status"]=="0"',), 'next': approve_column}, "rejected": { 'type': 'if_eval', 'data': ('r["status"]=="0"',), 'next': rejected_column }, } table = convert(data, header=header_table, multi_header=multi_header, custom_column=custom_column) # Titulo de la vista y variables de la Clase vars_page = self.generate_header(custom_title=title_page) return render(request, 'admin/authorization/clients.html', {'table': table, 'vars_page': vars_page, 'form_filters':form_filters})
flexible
{ "blob_id": "b78ad3a55eb27fd91f89c22db07fadca297640ab", "index": 2892, "step-1": "<mask token>\n\n\nclass Autorization:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass AutorizationClient(Autorization):\n \"\"\"\n Manejo de autorizaciones de clientes,\n se listan los clientes, en orden de pendiente,\n aprobado y rechazado, segun fecha\n Para posterior aprovacion o rechazo\n \"\"\"\n\n @method_decorator(user_passes_test(role_admin_check()))\n def list(self, request):\n \"\"\"\n Listado de clientes por autorizar,\n se incluyen tambien clientes aprovados y rechazados\n \"\"\"\n obj_api = api()\n token = request.session['token']\n title_page = _('User - User Affiliation').title()\n filters = {}\n form_filters = AuthorizationClientFilter(request.GET)\n if form_filters.is_valid():\n filters = form_filters.cleaned_data\n tools = Tools()\n filters['from_date'] = tools.date_format_to_db(date=filters[\n 'from_date'])\n filters['until_date'] = tools.date_format_to_db(date=filters[\n 'until_date'])\n filters = form_filters.cleaned_data\n if request.method == 'GET':\n if 'approve' in request.GET and request.GET['approve']:\n pk = request.GET['approve']\n data = {'status': 1}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n if 'rejected' in request.GET and request.GET['rejected']:\n pk = request.GET['rejected']\n data = {'status': 2}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n data = obj_api.get(slug='authorizations/clients/', arg=filters,\n token=token)\n header_table = [('', 'code_seller'), ('', 'name'), ('',\n 'document_type_name'), ('', 'document'), ('', ''), ('', ''), (\n '', 'document'), ('', 'approve'), ('', 'rejected'), ('',\n 'date_join')]\n multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'),\n {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan':\n '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2',\n 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan':\n '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_(\n 'name or Social reason'), {}), (_('type document'), {}), (_(\n 'document number'), {}), (_('description'), {}), (_(\n 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]]\n approve_column = {'type': 'submit', 'data': {'name': 'approve',\n 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}}\n rejected_column = {'type': 'submit', 'data': {'name': 'rejected',\n 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}}\n custom_column = {'date_join': {'type': 'date', 'data': ('date_join'\n ,)}, 'approve': {'type': 'if_eval', 'data': ('r[\"status\"]==\"0\"'\n ,), 'next': approve_column}, 'rejected': {'type': 'if_eval',\n 'data': ('r[\"status\"]==\"0\"',), 'next': rejected_column}}\n table = convert(data, header=header_table, multi_header=\n multi_header, custom_column=custom_column)\n vars_page = self.generate_header(custom_title=title_page)\n return render(request, 'admin/authorization/clients.html', {'table':\n table, 'vars_page': vars_page, 'form_filters': form_filters})\n", "step-2": "<mask token>\n\n\nclass Autorization:\n <mask token>\n <mask token>\n\n def generate_header(self, custom_title=None):\n if custom_title:\n title = '{} - '.format(_('authorizations')).title() + custom_title\n else:\n title = self.title_content_header\n header = {'icon': self.logo_content_header, 'title': title}\n return {**header, **self.vars_page}\n\n\nclass AutorizationClient(Autorization):\n \"\"\"\n Manejo de autorizaciones de clientes,\n se listan los clientes, en orden de pendiente,\n aprobado y rechazado, segun fecha\n Para posterior aprovacion o rechazo\n \"\"\"\n\n @method_decorator(user_passes_test(role_admin_check()))\n def list(self, request):\n \"\"\"\n Listado de clientes por autorizar,\n se incluyen tambien clientes aprovados y rechazados\n \"\"\"\n obj_api = api()\n token = request.session['token']\n title_page = _('User - User Affiliation').title()\n filters = {}\n form_filters = AuthorizationClientFilter(request.GET)\n if form_filters.is_valid():\n filters = form_filters.cleaned_data\n tools = Tools()\n filters['from_date'] = tools.date_format_to_db(date=filters[\n 'from_date'])\n filters['until_date'] = tools.date_format_to_db(date=filters[\n 'until_date'])\n filters = form_filters.cleaned_data\n if request.method == 'GET':\n if 'approve' in request.GET and request.GET['approve']:\n pk = request.GET['approve']\n data = {'status': 1}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n if 'rejected' in request.GET and request.GET['rejected']:\n pk = request.GET['rejected']\n data = {'status': 2}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n data = obj_api.get(slug='authorizations/clients/', arg=filters,\n token=token)\n header_table = [('', 'code_seller'), ('', 'name'), ('',\n 'document_type_name'), ('', 'document'), ('', ''), ('', ''), (\n '', 'document'), ('', 'approve'), ('', 'rejected'), ('',\n 'date_join')]\n multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'),\n {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan':\n '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2',\n 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan':\n '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_(\n 'name or Social reason'), {}), (_('type document'), {}), (_(\n 'document number'), {}), (_('description'), {}), (_(\n 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]]\n approve_column = {'type': 'submit', 'data': {'name': 'approve',\n 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}}\n rejected_column = {'type': 'submit', 'data': {'name': 'rejected',\n 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}}\n custom_column = {'date_join': {'type': 'date', 'data': ('date_join'\n ,)}, 'approve': {'type': 'if_eval', 'data': ('r[\"status\"]==\"0\"'\n ,), 'next': approve_column}, 'rejected': {'type': 'if_eval',\n 'data': ('r[\"status\"]==\"0\"',), 'next': rejected_column}}\n table = convert(data, header=header_table, multi_header=\n multi_header, custom_column=custom_column)\n vars_page = self.generate_header(custom_title=title_page)\n return render(request, 'admin/authorization/clients.html', {'table':\n table, 'vars_page': vars_page, 'form_filters': form_filters})\n", "step-3": "<mask token>\n\n\nclass Autorization:\n logo_content_header = 'fa fa-key'\n vars_page = {}\n\n def generate_header(self, custom_title=None):\n if custom_title:\n title = '{} - '.format(_('authorizations')).title() + custom_title\n else:\n title = self.title_content_header\n header = {'icon': self.logo_content_header, 'title': title}\n return {**header, **self.vars_page}\n\n\nclass AutorizationClient(Autorization):\n \"\"\"\n Manejo de autorizaciones de clientes,\n se listan los clientes, en orden de pendiente,\n aprobado y rechazado, segun fecha\n Para posterior aprovacion o rechazo\n \"\"\"\n\n @method_decorator(user_passes_test(role_admin_check()))\n def list(self, request):\n \"\"\"\n Listado de clientes por autorizar,\n se incluyen tambien clientes aprovados y rechazados\n \"\"\"\n obj_api = api()\n token = request.session['token']\n title_page = _('User - User Affiliation').title()\n filters = {}\n form_filters = AuthorizationClientFilter(request.GET)\n if form_filters.is_valid():\n filters = form_filters.cleaned_data\n tools = Tools()\n filters['from_date'] = tools.date_format_to_db(date=filters[\n 'from_date'])\n filters['until_date'] = tools.date_format_to_db(date=filters[\n 'until_date'])\n filters = form_filters.cleaned_data\n if request.method == 'GET':\n if 'approve' in request.GET and request.GET['approve']:\n pk = request.GET['approve']\n data = {'status': 1}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n if 'rejected' in request.GET and request.GET['rejected']:\n pk = request.GET['rejected']\n data = {'status': 2}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n data = obj_api.get(slug='authorizations/clients/', arg=filters,\n token=token)\n header_table = [('', 'code_seller'), ('', 'name'), ('',\n 'document_type_name'), ('', 'document'), ('', ''), ('', ''), (\n '', 'document'), ('', 'approve'), ('', 'rejected'), ('',\n 'date_join')]\n multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'),\n {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan':\n '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2',\n 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan':\n '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_(\n 'name or Social reason'), {}), (_('type document'), {}), (_(\n 'document number'), {}), (_('description'), {}), (_(\n 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]]\n approve_column = {'type': 'submit', 'data': {'name': 'approve',\n 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}}\n rejected_column = {'type': 'submit', 'data': {'name': 'rejected',\n 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}}\n custom_column = {'date_join': {'type': 'date', 'data': ('date_join'\n ,)}, 'approve': {'type': 'if_eval', 'data': ('r[\"status\"]==\"0\"'\n ,), 'next': approve_column}, 'rejected': {'type': 'if_eval',\n 'data': ('r[\"status\"]==\"0\"',), 'next': rejected_column}}\n table = convert(data, header=header_table, multi_header=\n multi_header, custom_column=custom_column)\n vars_page = self.generate_header(custom_title=title_page)\n return render(request, 'admin/authorization/clients.html', {'table':\n table, 'vars_page': vars_page, 'form_filters': form_filters})\n", "step-4": "<mask token>\nfrom django.shortcuts import render\nfrom dashboard.json2table import convert\nfrom django.utils.translation import ugettext_lazy as _\nfrom api.connection import api\nfrom login.utils.tools import role_admin_check\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import user_passes_test\nfrom dashboard.tools import capitalize as cap, ToolsBackend as Tools\nfrom dashboard.forms import AuthorizationClientFilter\n\n\nclass Autorization:\n logo_content_header = 'fa fa-key'\n vars_page = {}\n\n def generate_header(self, custom_title=None):\n if custom_title:\n title = '{} - '.format(_('authorizations')).title() + custom_title\n else:\n title = self.title_content_header\n header = {'icon': self.logo_content_header, 'title': title}\n return {**header, **self.vars_page}\n\n\nclass AutorizationClient(Autorization):\n \"\"\"\n Manejo de autorizaciones de clientes,\n se listan los clientes, en orden de pendiente,\n aprobado y rechazado, segun fecha\n Para posterior aprovacion o rechazo\n \"\"\"\n\n @method_decorator(user_passes_test(role_admin_check()))\n def list(self, request):\n \"\"\"\n Listado de clientes por autorizar,\n se incluyen tambien clientes aprovados y rechazados\n \"\"\"\n obj_api = api()\n token = request.session['token']\n title_page = _('User - User Affiliation').title()\n filters = {}\n form_filters = AuthorizationClientFilter(request.GET)\n if form_filters.is_valid():\n filters = form_filters.cleaned_data\n tools = Tools()\n filters['from_date'] = tools.date_format_to_db(date=filters[\n 'from_date'])\n filters['until_date'] = tools.date_format_to_db(date=filters[\n 'until_date'])\n filters = form_filters.cleaned_data\n if request.method == 'GET':\n if 'approve' in request.GET and request.GET['approve']:\n pk = request.GET['approve']\n data = {'status': 1}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n if 'rejected' in request.GET and request.GET['rejected']:\n pk = request.GET['rejected']\n data = {'status': 2}\n obj_api.put(slug='authorizations/clients/' + pk, token=\n token, arg=data)\n data = obj_api.get(slug='authorizations/clients/', arg=filters,\n token=token)\n header_table = [('', 'code_seller'), ('', 'name'), ('',\n 'document_type_name'), ('', 'document'), ('', ''), ('', ''), (\n '', 'document'), ('', 'approve'), ('', 'rejected'), ('',\n 'date_join')]\n multi_header = [[(_('seller code'), {'rowspan': '2'}), (_('user'),\n {'rowspan': '1', 'colspan': '3'}), (_('product'), {'rowspan':\n '1', 'colspan': '2'}), (_('user code'), {'rowspan': '2',\n 'colspan': '1'}), (_('validation'), {'rowspan': '1', 'colspan':\n '2'}), (_('date'), {'rowspan': '2', 'colspan': '1'})], [(_(\n 'name or Social reason'), {}), (_('type document'), {}), (_(\n 'document number'), {}), (_('description'), {}), (_(\n 'Query Numbers'), {}), (_('approve'), {}), (_('deneis'), {})]]\n approve_column = {'type': 'submit', 'data': {'name': 'approve',\n 'key': 'id', 'cls': 'btn btn-success', 'text': cap(_('approve'))}}\n rejected_column = {'type': 'submit', 'data': {'name': 'rejected',\n 'key': 'id', 'cls': 'btn btn-danger', 'text': cap(_('rejected'))}}\n custom_column = {'date_join': {'type': 'date', 'data': ('date_join'\n ,)}, 'approve': {'type': 'if_eval', 'data': ('r[\"status\"]==\"0\"'\n ,), 'next': approve_column}, 'rejected': {'type': 'if_eval',\n 'data': ('r[\"status\"]==\"0\"',), 'next': rejected_column}}\n table = convert(data, header=header_table, multi_header=\n multi_header, custom_column=custom_column)\n vars_page = self.generate_header(custom_title=title_page)\n return render(request, 'admin/authorization/clients.html', {'table':\n table, 'vars_page': vars_page, 'form_filters': form_filters})\n", "step-5": "\"\"\"Vista de Autorizaciones (Clientes/Especialistas/Vendedores).\"\"\"\nfrom django.shortcuts import render\nfrom dashboard.json2table import convert\nfrom django.utils.translation import ugettext_lazy as _\nfrom api.connection import api\nfrom login.utils.tools import role_admin_check\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.decorators import user_passes_test\nfrom dashboard.tools import capitalize as cap, ToolsBackend as Tools\nfrom dashboard.forms import AuthorizationClientFilter\nclass Autorization:\n logo_content_header = \"fa fa-key\"\n vars_page = {}\n def generate_header(self, custom_title=None):\n if custom_title:\n title = \"{} - \".format(_(\"authorizations\")).title() + custom_title\n else:\n title = self.title_content_header\n\n header = {'icon': self.logo_content_header, 'title': title}\n return {**header, **self.vars_page}\n\n\nclass AutorizationClient(Autorization):\n \"\"\"\n Manejo de autorizaciones de clientes,\n se listan los clientes, en orden de pendiente,\n aprobado y rechazado, segun fecha\n Para posterior aprovacion o rechazo\n \"\"\"\n\n @method_decorator(user_passes_test(role_admin_check()))\n def list(self, request):\n \"\"\"\n Listado de clientes por autorizar,\n se incluyen tambien clientes aprovados y rechazados\n \"\"\"\n\n obj_api = api()\n # actual_page = get_actual_page(request)\n token = request.session['token']\n title_page = _('User - User Affiliation').title()\n filters = {}\n\n form_filters = AuthorizationClientFilter(request.GET)\n\n if form_filters.is_valid(): # Agregamos filtros de encontrarse alguno\n filters = form_filters.cleaned_data\n tools = Tools()\n filters['from_date'] = tools.date_format_to_db(date=filters['from_date'])\n filters['until_date'] = tools.date_format_to_db(date=filters['until_date'])\n filters = form_filters.cleaned_data\n \n if request.method == 'GET':\n if 'approve' in request.GET and request.GET['approve']:\n pk = request.GET['approve']\n data = {\"status\":1}\n obj_api.put(slug='authorizations/clients/' + pk, token=token, arg=data)\n\n if 'rejected' in request.GET and request.GET['rejected']:\n pk = request.GET['rejected']\n data = {\"status\":2}\n obj_api.put(slug='authorizations/clients/' + pk, token=token, arg=data)\n\n # Traer data para el listado\n data = obj_api.get(slug='authorizations/clients/', arg=filters, token=token)\n\n\n header_table = [(\"\", \"code_seller\"), (\"\", \"name\"),(\n \"\", \"document_type_name\"), ( \"\", \"document\"),(\n \"\", \"\"), (\"\", \"\"), (\n \"\", \"document\"), (\n \"\", \"approve\"), (\"\", \"rejected\"), (\n \"\", \"date_join\")]\n\n # Multiples header, una lista por cada nivel de la cabecera\n multi_header = [\n [\n (_(\"seller code\"), {'rowspan': '2'}),\n (_('user'), {'rowspan': '1', 'colspan': '3'}),\n (_('product'), {'rowspan': '1', 'colspan': '2'}),\n (_('user code'), {'rowspan': '2', 'colspan': '1'}),\n (_('validation'), {'rowspan': '1', 'colspan': '2'}),\n (_('date'), {'rowspan': '2', 'colspan': '1'}),\n ],\n [\n (_('name or Social reason'), {}),\n (_('type document'), {}),\n (_('document number'), {}),\n (_('description'), {}),\n (_('Query Numbers'), {}),\n (_('approve'), {}),\n (_('deneis'), {}),\n ],\n ]\n\n approve_column = {'type': 'submit', 'data': {'name':'approve','key':'id',\n 'cls':'btn btn-success','text':cap(_('approve'))}}\n rejected_column = {'type': 'submit', 'data': {'name':'rejected','key':'id',\n 'cls':'btn btn-danger','text':cap(_('rejected'))}}\n custom_column = {\n \"date_join\": {'type': 'date', 'data': ('date_join',)},\n \"approve\": {'type': 'if_eval', 'data': ('r[\"status\"]==\"0\"',),\n 'next': approve_column},\n \"rejected\": {\n 'type': 'if_eval',\n 'data': ('r[\"status\"]==\"0\"',),\n 'next': rejected_column\n },\n }\n\n table = convert(data, header=header_table, multi_header=multi_header, custom_column=custom_column)\n\n # Titulo de la vista y variables de la Clase\n vars_page = self.generate_header(custom_title=title_page)\n\n return render(request, 'admin/authorization/clients.html',\n {'table': table, 'vars_page': vars_page, 'form_filters':form_filters})", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def is_even(a): check_integer(a) if a % 2 == 0: print('true') return True else: print('false') return False <|reserved_special_token_0|> <|reserved_special_token_1|> def check_integer(a): if type(a) != int: print('please input an integer') exit() def is_even(a): check_integer(a) if a % 2 == 0: print('true') return True else: print('false') return False <|reserved_special_token_0|> <|reserved_special_token_1|> def check_integer(a): if type(a) != int: print('please input an integer') exit() def is_even(a): check_integer(a) if a % 2 == 0: print('true') return True else: print('false') return False is_even(2) is_even(3) is_even('cat') <|reserved_special_token_1|> def check_integer(a): if type(a) != int: print("please input an integer") exit() def is_even(a): check_integer(a) if a % 2 == 0: print("true") return True else: print("false") return False is_even(2) is_even(3) is_even("cat")
flexible
{ "blob_id": "92391f17380b2e09cc9b3913f15ce35189d9893d", "index": 8241, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef is_even(a):\n check_integer(a)\n if a % 2 == 0:\n print('true')\n return True\n else:\n print('false')\n return False\n\n\n<mask token>\n", "step-3": "def check_integer(a):\n if type(a) != int:\n print('please input an integer')\n exit()\n\n\ndef is_even(a):\n check_integer(a)\n if a % 2 == 0:\n print('true')\n return True\n else:\n print('false')\n return False\n\n\n<mask token>\n", "step-4": "def check_integer(a):\n if type(a) != int:\n print('please input an integer')\n exit()\n\n\ndef is_even(a):\n check_integer(a)\n if a % 2 == 0:\n print('true')\n return True\n else:\n print('false')\n return False\n\n\nis_even(2)\nis_even(3)\nis_even('cat')\n", "step-5": "\n\ndef check_integer(a):\n if type(a) != int:\n print(\"please input an integer\")\n exit()\n\n\ndef is_even(a):\n check_integer(a)\n if a % 2 == 0:\n print(\"true\")\n return True\n else:\n print(\"false\")\n return False\n\n\nis_even(2)\nis_even(3)\nis_even(\"cat\")\n\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> for i in range(100): numero = int(input('Digite um valor:')) if numero % 2 == 0: contador_pares += 1 else: contador_impares += 1 print('A quantidade de números pares é igual a:', contador_pares) print('A quantidade de números ímpares é igual a:', contador_impares) <|reserved_special_token_1|> contador_pares = 0 contador_impares = 0 for i in range(100): numero = int(input('Digite um valor:')) if numero % 2 == 0: contador_pares += 1 else: contador_impares += 1 print('A quantidade de números pares é igual a:', contador_pares) print('A quantidade de números ímpares é igual a:', contador_impares)
flexible
{ "blob_id": "03aa33861def30a46de85c5b309878a1180a760f", "index": 5211, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(100):\n numero = int(input('Digite um valor:'))\n if numero % 2 == 0:\n contador_pares += 1\n else:\n contador_impares += 1\nprint('A quantidade de números pares é igual a:', contador_pares)\nprint('A quantidade de números ímpares é igual a:', contador_impares)\n", "step-3": "contador_pares = 0\ncontador_impares = 0\nfor i in range(100):\n numero = int(input('Digite um valor:'))\n if numero % 2 == 0:\n contador_pares += 1\n else:\n contador_impares += 1\nprint('A quantidade de números pares é igual a:', contador_pares)\nprint('A quantidade de números ímpares é igual a:', contador_impares)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import torch import numpy as np # source: https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb def kernel(X1, X2, l=1.0, sigma_f=1.0): ''' Isotropic squared exponential kernel. Computes a covariance matrix from points in X1 and X2. Args: X1: Array of m points (m x d). X2: Array of n points (n x d). Returns: Covariance matrix (m x n). ''' sqdist = np.sum(X1**2, 1).reshape(-1, 1) + np.sum(X2**2, 1) - 2 * np.dot(X1, X2.T) return sigma_f**2 * np.exp(-0.5 / l**2 * sqdist) # source: # https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb def posterior_predictive(X_s, X_train, Y_train, l=1.0, sigma_f=1.0, sigma_y=1e-8): ''' Computes the sufficient statistics of the GP posterior predictive distribution from m training data X_train and Y_train and n new inputs X_s. Args: X_s: New input locations (n x d). X_train: Training locations (m x d). Y_train: Training targets (m x 1). l: Kernel length parameter. sigma_f: Kernel vertical variation parameter. sigma_y: Noise parameter. Returns: Posterior mean vector (n x d) and covariance matrix (n x n). ''' K = kernel(X_train, X_train, l, sigma_f) + sigma_y**2 * np.eye(len(X_train)) K_s = kernel(X_s, X_train, l, sigma_f) K_ss = kernel(X_s, X_s, l, sigma_f) + sigma_y**2 * np.eye(len(X_s)) mu_s = np.matmul(K_s, np.linalg.solve(K, Y_train)) cov_s = K_ss - np.matmul(K_s, np.linalg.solve(K, K_s.T)) return mu_s, cov_s class CNP(torch.nn.Module): def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer, dec_layer): super(CNP, self).__init__() if en_layer == 1: self.encoder = torch.nn.Linear(in_dim, hidden_dim) else: self.encoder = [ torch.nn.Linear(in_dim, hidden_dim), torch.nn.ReLU() ] for i in range(en_layer-2): self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.encoder.append(torch.nn.ReLU()) self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.encoder = torch.nn.Sequential(*self.encoder) if dec_layer == 1: self.decoder = torch.nn.Linear(hidden_dim+query_dim, out_dim) else: self.decoder = [ torch.nn.Linear(hidden_dim+query_dim, hidden_dim), torch.nn.ReLU() ] for i in range(dec_layer-2): self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.decoder.append(torch.nn.ReLU()) self.decoder.append(torch.nn.Linear(hidden_dim, out_dim)) self.decoder = torch.nn.Sequential(*self.decoder) def forward(self, context, query, key=None): query = query.view(query.shape[0], -1) # encode h = self.encoder(context) # aggregate h = h.mean(dim=0) h = torch.stack([h]*(query.shape[0]), dim=0) r = torch.cat([h, query], dim=1) # predict out = self.decoder(r) return out class ANP(torch.nn.Module): def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer, dec_layer, nhead): super(ANP, self).__init__() if en_layer == 1: self.encoder = torch.nn.Linear(in_dim, hidden_dim) else: self.encoder = [ torch.nn.Linear(in_dim, hidden_dim), torch.nn.ReLU() ] for i in range(en_layer-2): self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.encoder.append(torch.nn.ReLU()) self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.encoder = torch.nn.Sequential(*self.encoder) if dec_layer == 1: self.decoder = torch.nn.Linear(hidden_dim, out_dim) else: self.decoder = [ torch.nn.Linear(hidden_dim, hidden_dim), torch.nn.ReLU() ] for i in range(dec_layer-2): self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.decoder.append(torch.nn.ReLU()) self.decoder.append(torch.nn.Linear(hidden_dim, out_dim)) self.decoder = torch.nn.Sequential(*self.decoder) self.projector = torch.nn.Linear(query_dim, hidden_dim) self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=nhead) def forward(self, context, key, query): query = query.view(query.shape[0], -1) key = key.view(key.shape[0], -1) # encode h = self.encoder(context) h.unsqueeze_(1) # aggregate q_t = self.projector(query) k_t = self.projector(key) q_t.unsqueeze_(1) k_t.unsqueeze_(1) h, _ = self.attention(query=q_t, key=k_t, value=h) h.squeeze_(1) # predict pred = self.decoder(h) return pred class ANPv2(torch.nn.Module): def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer, dec_layer, nhead): super(ANPv2, self).__init__() if en_layer == 1: self.encoder = torch.nn.Linear(in_dim, hidden_dim) else: self.encoder = [ torch.nn.Linear(in_dim, hidden_dim), torch.nn.ReLU() ] for i in range(en_layer-2): self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.encoder.append(torch.nn.ReLU()) self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.encoder = torch.nn.Sequential(*self.encoder) if dec_layer == 1: self.decoder = torch.nn.Linear(hidden_dim, out_dim) else: self.decoder = [ torch.nn.Linear(hidden_dim, hidden_dim), torch.nn.ReLU() ] for i in range(dec_layer-2): self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim)) self.decoder.append(torch.nn.ReLU()) self.decoder.append(torch.nn.Linear(hidden_dim, out_dim)) self.decoder = torch.nn.Sequential(*self.decoder) self.key_mlp = torch.nn.Sequential( torch.nn.Linear(query_dim, hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim, hidden_dim) ) self.query_mlp = torch.nn.Sequential( torch.nn.Linear(query_dim, hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim, hidden_dim) ) self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=nhead) def forward(self, context, key, query): query = query.view(query.shape[0], -1) key = key.view(key.shape[0], -1) # encode h = self.encoder(context) h.unsqueeze_(1) # aggregate q_t = self.query_mlp(query) k_t = self.key_mlp(key) q_t.unsqueeze_(1) k_t.unsqueeze_(1) h, _ = self.attention(query=q_t, key=k_t, value=h) h.squeeze_(1) # predict pred = self.decoder(h) return pred
normal
{ "blob_id": "82c3bde5746d04c126a93851844f775e7ce65f4b", "index": 9442, "step-1": "<mask token>\n\n\nclass CNP(torch.nn.Module):\n <mask token>\n <mask token>\n\n\nclass ANP(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.projector = torch.nn.Linear(query_dim, hidden_dim)\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.projector(query)\n k_t = self.projector(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n\n\nclass ANPv2(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANPv2, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.key_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.query_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.query_mlp(query)\n k_t = self.key_mlp(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n", "step-2": "<mask token>\n\n\nclass CNP(torch.nn.Module):\n <mask token>\n\n def forward(self, context, query, key=None):\n query = query.view(query.shape[0], -1)\n h = self.encoder(context)\n h = h.mean(dim=0)\n h = torch.stack([h] * query.shape[0], dim=0)\n r = torch.cat([h, query], dim=1)\n out = self.decoder(r)\n return out\n\n\nclass ANP(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.projector = torch.nn.Linear(query_dim, hidden_dim)\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.projector(query)\n k_t = self.projector(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n\n\nclass ANPv2(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANPv2, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.key_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.query_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.query_mlp(query)\n k_t = self.key_mlp(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n", "step-3": "<mask token>\n\n\nclass CNP(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer):\n super(CNP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim + query_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim + query_dim,\n hidden_dim), torch.nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n\n def forward(self, context, query, key=None):\n query = query.view(query.shape[0], -1)\n h = self.encoder(context)\n h = h.mean(dim=0)\n h = torch.stack([h] * query.shape[0], dim=0)\n r = torch.cat([h, query], dim=1)\n out = self.decoder(r)\n return out\n\n\nclass ANP(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.projector = torch.nn.Linear(query_dim, hidden_dim)\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.projector(query)\n k_t = self.projector(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n\n\nclass ANPv2(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANPv2, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.key_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.query_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.query_mlp(query)\n k_t = self.key_mlp(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n", "step-4": "<mask token>\n\n\ndef posterior_predictive(X_s, X_train, Y_train, l=1.0, sigma_f=1.0, sigma_y\n =1e-08):\n \"\"\" Computes the sufficient statistics of the GP posterior predictive distribution from m training data X_train and Y_train and n new inputs X_s. Args: X_s: New input locations (n x d). X_train: Training locations (m x d). Y_train: Training targets (m x 1). l: Kernel length parameter. sigma_f: Kernel vertical variation parameter. sigma_y: Noise parameter. Returns: Posterior mean vector (n x d) and covariance matrix (n x n). \"\"\"\n K = kernel(X_train, X_train, l, sigma_f) + sigma_y ** 2 * np.eye(len(\n X_train))\n K_s = kernel(X_s, X_train, l, sigma_f)\n K_ss = kernel(X_s, X_s, l, sigma_f) + sigma_y ** 2 * np.eye(len(X_s))\n mu_s = np.matmul(K_s, np.linalg.solve(K, Y_train))\n cov_s = K_ss - np.matmul(K_s, np.linalg.solve(K, K_s.T))\n return mu_s, cov_s\n\n\nclass CNP(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer):\n super(CNP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim + query_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim + query_dim,\n hidden_dim), torch.nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n\n def forward(self, context, query, key=None):\n query = query.view(query.shape[0], -1)\n h = self.encoder(context)\n h = h.mean(dim=0)\n h = torch.stack([h] * query.shape[0], dim=0)\n r = torch.cat([h, query], dim=1)\n out = self.decoder(r)\n return out\n\n\nclass ANP(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.projector = torch.nn.Linear(query_dim, hidden_dim)\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.projector(query)\n k_t = self.projector(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n\n\nclass ANPv2(torch.nn.Module):\n\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer,\n dec_layer, nhead):\n super(ANPv2, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [torch.nn.Linear(in_dim, hidden_dim), torch.nn.\n ReLU()]\n for i in range(en_layer - 2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [torch.nn.Linear(hidden_dim, hidden_dim), torch.\n nn.ReLU()]\n for i in range(dec_layer - 2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.key_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.query_mlp = torch.nn.Sequential(torch.nn.Linear(query_dim,\n hidden_dim), torch.nn.ReLU(), torch.nn.Linear(hidden_dim,\n hidden_dim))\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim,\n num_heads=nhead)\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n h = self.encoder(context)\n h.unsqueeze_(1)\n q_t = self.query_mlp(query)\n k_t = self.key_mlp(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n pred = self.decoder(h)\n return pred\n", "step-5": "import torch\nimport numpy as np\n\n\n# source: https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb\ndef kernel(X1, X2, l=1.0, sigma_f=1.0):\n ''' Isotropic squared exponential kernel. Computes a covariance matrix from points in X1 and X2. Args: X1: Array of m points (m x d). X2: Array of n points (n x d). Returns: Covariance matrix (m x n). '''\n sqdist = np.sum(X1**2, 1).reshape(-1, 1) + np.sum(X2**2, 1) - 2 * np.dot(X1, X2.T)\n return sigma_f**2 * np.exp(-0.5 / l**2 * sqdist)\n \n# source: # https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb\ndef posterior_predictive(X_s, X_train, Y_train, l=1.0, sigma_f=1.0, sigma_y=1e-8):\n ''' Computes the sufficient statistics of the GP posterior predictive distribution from m training data X_train and Y_train and n new inputs X_s. Args: X_s: New input locations (n x d). X_train: Training locations (m x d). Y_train: Training targets (m x 1). l: Kernel length parameter. sigma_f: Kernel vertical variation parameter. sigma_y: Noise parameter. Returns: Posterior mean vector (n x d) and covariance matrix (n x n). '''\n K = kernel(X_train, X_train, l, sigma_f) + sigma_y**2 * np.eye(len(X_train))\n K_s = kernel(X_s, X_train, l, sigma_f)\n K_ss = kernel(X_s, X_s, l, sigma_f) + sigma_y**2 * np.eye(len(X_s))\n \n mu_s = np.matmul(K_s, np.linalg.solve(K, Y_train))\n cov_s = K_ss - np.matmul(K_s, np.linalg.solve(K, K_s.T))\n \n return mu_s, cov_s\n\nclass CNP(torch.nn.Module):\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer, dec_layer):\n super(CNP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [\n torch.nn.Linear(in_dim, hidden_dim),\n torch.nn.ReLU()\n ]\n for i in range(en_layer-2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n \n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim+query_dim, out_dim)\n else:\n self.decoder = [\n torch.nn.Linear(hidden_dim+query_dim, hidden_dim),\n torch.nn.ReLU()\n ]\n for i in range(dec_layer-2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n \n def forward(self, context, query, key=None):\n query = query.view(query.shape[0], -1)\n # encode\n h = self.encoder(context)\n # aggregate\n h = h.mean(dim=0)\n h = torch.stack([h]*(query.shape[0]), dim=0)\n r = torch.cat([h, query], dim=1)\n # predict\n out = self.decoder(r)\n return out\n\n\nclass ANP(torch.nn.Module):\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer, dec_layer, nhead):\n super(ANP, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [\n torch.nn.Linear(in_dim, hidden_dim),\n torch.nn.ReLU()\n ]\n for i in range(en_layer-2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n \n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [\n torch.nn.Linear(hidden_dim, hidden_dim),\n torch.nn.ReLU()\n ]\n for i in range(dec_layer-2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n self.projector = torch.nn.Linear(query_dim, hidden_dim)\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=nhead)\n\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n # encode\n h = self.encoder(context)\n h.unsqueeze_(1)\n # aggregate\n q_t = self.projector(query)\n k_t = self.projector(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n # predict\n pred = self.decoder(h)\n return pred\n\nclass ANPv2(torch.nn.Module):\n def __init__(self, in_dim, hidden_dim, query_dim, out_dim, en_layer, dec_layer, nhead):\n super(ANPv2, self).__init__()\n if en_layer == 1:\n self.encoder = torch.nn.Linear(in_dim, hidden_dim)\n else:\n self.encoder = [\n torch.nn.Linear(in_dim, hidden_dim),\n torch.nn.ReLU()\n ]\n for i in range(en_layer-2):\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder.append(torch.nn.ReLU())\n self.encoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.encoder = torch.nn.Sequential(*self.encoder)\n \n if dec_layer == 1:\n self.decoder = torch.nn.Linear(hidden_dim, out_dim)\n else:\n self.decoder = [\n torch.nn.Linear(hidden_dim, hidden_dim),\n torch.nn.ReLU()\n ]\n for i in range(dec_layer-2):\n self.decoder.append(torch.nn.Linear(hidden_dim, hidden_dim))\n self.decoder.append(torch.nn.ReLU())\n self.decoder.append(torch.nn.Linear(hidden_dim, out_dim))\n self.decoder = torch.nn.Sequential(*self.decoder)\n \n self.key_mlp = torch.nn.Sequential(\n torch.nn.Linear(query_dim, hidden_dim),\n torch.nn.ReLU(),\n torch.nn.Linear(hidden_dim, hidden_dim)\n )\n\n self.query_mlp = torch.nn.Sequential(\n torch.nn.Linear(query_dim, hidden_dim),\n torch.nn.ReLU(),\n torch.nn.Linear(hidden_dim, hidden_dim)\n )\n\n self.attention = torch.nn.MultiheadAttention(embed_dim=hidden_dim, num_heads=nhead)\n\n\n def forward(self, context, key, query):\n query = query.view(query.shape[0], -1)\n key = key.view(key.shape[0], -1)\n # encode\n h = self.encoder(context)\n h.unsqueeze_(1)\n # aggregate\n q_t = self.query_mlp(query)\n k_t = self.key_mlp(key)\n q_t.unsqueeze_(1)\n k_t.unsqueeze_(1)\n h, _ = self.attention(query=q_t, key=k_t, value=h)\n h.squeeze_(1)\n # predict\n pred = self.decoder(h)\n return pred\n", "step-ids": [ 7, 8, 9, 10, 13 ] }
[ 7, 8, 9, 10, 13 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class GetInTouchForm(forms.ModelForm): class Meta: model = GetInTouch fields = '__all__' <|reserved_special_token_1|> from django import forms from .models import GetInTouch class GetInTouchForm(forms.ModelForm): class Meta: model = GetInTouch fields = '__all__'
flexible
{ "blob_id": "c8dc143c09aa7f677167a4942ae1c4a0fbf75128", "index": 3219, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass GetInTouchForm(forms.ModelForm):\n\n\n class Meta:\n model = GetInTouch\n fields = '__all__'\n", "step-3": "from django import forms\nfrom .models import GetInTouch\n\n\nclass GetInTouchForm(forms.ModelForm):\n\n\n class Meta:\n model = GetInTouch\n fields = '__all__'\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> def md5_hexdigest(data): return hashlib.md5(data.encode('utf-8')).hexdigest() def sha1_hexdigest(data): return hashlib.sha1(data.encode('utf-8')).hexdigest() def sha224_hexdigest(data): return hashlib.sha224(data.encode('utf-8')).hexdigest() <|reserved_special_token_0|> def sha384_hexdigest(data): return hashlib.sha384(data.encode('utf-8')).hexdigest() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def md5_hexdigest(data): return hashlib.md5(data.encode('utf-8')).hexdigest() def sha1_hexdigest(data): return hashlib.sha1(data.encode('utf-8')).hexdigest() def sha224_hexdigest(data): return hashlib.sha224(data.encode('utf-8')).hexdigest() def sha256_hexdigest(data): return hashlib.sha256(data.encode('utf-8')).hexdigest() def sha384_hexdigest(data): return hashlib.sha384(data.encode('utf-8')).hexdigest() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def md5_hexdigest(data): return hashlib.md5(data.encode('utf-8')).hexdigest() def sha1_hexdigest(data): return hashlib.sha1(data.encode('utf-8')).hexdigest() def sha224_hexdigest(data): return hashlib.sha224(data.encode('utf-8')).hexdigest() def sha256_hexdigest(data): return hashlib.sha256(data.encode('utf-8')).hexdigest() def sha384_hexdigest(data): return hashlib.sha384(data.encode('utf-8')).hexdigest() def sha512_hexdigest(data): return hashlib.sha512(data.encode('utf-8')).hexdigest() <|reserved_special_token_1|> import hashlib def md5_hexdigest(data): return hashlib.md5(data.encode('utf-8')).hexdigest() def sha1_hexdigest(data): return hashlib.sha1(data.encode('utf-8')).hexdigest() def sha224_hexdigest(data): return hashlib.sha224(data.encode('utf-8')).hexdigest() def sha256_hexdigest(data): return hashlib.sha256(data.encode('utf-8')).hexdigest() def sha384_hexdigest(data): return hashlib.sha384(data.encode('utf-8')).hexdigest() def sha512_hexdigest(data): return hashlib.sha512(data.encode('utf-8')).hexdigest()
flexible
{ "blob_id": "35a95c49c2dc09b528329433a157cf313cf59667", "index": 8955, "step-1": "<mask token>\n\n\ndef md5_hexdigest(data):\n return hashlib.md5(data.encode('utf-8')).hexdigest()\n\n\ndef sha1_hexdigest(data):\n return hashlib.sha1(data.encode('utf-8')).hexdigest()\n\n\ndef sha224_hexdigest(data):\n return hashlib.sha224(data.encode('utf-8')).hexdigest()\n\n\n<mask token>\n\n\ndef sha384_hexdigest(data):\n return hashlib.sha384(data.encode('utf-8')).hexdigest()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef md5_hexdigest(data):\n return hashlib.md5(data.encode('utf-8')).hexdigest()\n\n\ndef sha1_hexdigest(data):\n return hashlib.sha1(data.encode('utf-8')).hexdigest()\n\n\ndef sha224_hexdigest(data):\n return hashlib.sha224(data.encode('utf-8')).hexdigest()\n\n\ndef sha256_hexdigest(data):\n return hashlib.sha256(data.encode('utf-8')).hexdigest()\n\n\ndef sha384_hexdigest(data):\n return hashlib.sha384(data.encode('utf-8')).hexdigest()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef md5_hexdigest(data):\n return hashlib.md5(data.encode('utf-8')).hexdigest()\n\n\ndef sha1_hexdigest(data):\n return hashlib.sha1(data.encode('utf-8')).hexdigest()\n\n\ndef sha224_hexdigest(data):\n return hashlib.sha224(data.encode('utf-8')).hexdigest()\n\n\ndef sha256_hexdigest(data):\n return hashlib.sha256(data.encode('utf-8')).hexdigest()\n\n\ndef sha384_hexdigest(data):\n return hashlib.sha384(data.encode('utf-8')).hexdigest()\n\n\ndef sha512_hexdigest(data):\n return hashlib.sha512(data.encode('utf-8')).hexdigest()\n", "step-4": "import hashlib\n\n\ndef md5_hexdigest(data):\n return hashlib.md5(data.encode('utf-8')).hexdigest()\n\n\ndef sha1_hexdigest(data):\n return hashlib.sha1(data.encode('utf-8')).hexdigest()\n\n\ndef sha224_hexdigest(data):\n return hashlib.sha224(data.encode('utf-8')).hexdigest()\n\n\ndef sha256_hexdigest(data):\n return hashlib.sha256(data.encode('utf-8')).hexdigest()\n\n\ndef sha384_hexdigest(data):\n return hashlib.sha384(data.encode('utf-8')).hexdigest()\n\n\ndef sha512_hexdigest(data):\n return hashlib.sha512(data.encode('utf-8')).hexdigest()\n", "step-5": null, "step-ids": [ 4, 5, 6, 7 ] }
[ 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True): node = hou.pwd() def getNaskCasting(): path = 'E:/WIP/Work/casting-nask.csv' file = open(path, 'r') fileText = file.readlines() file.close() fileText.pop(0) assetDic = {} for line in fileText: assetType = line.split(',') assetName = assetType[2] assetType = assetType[1].split('/')[0] assetDic[assetName] = assetType.lower() return assetDic assetList = getNaskCasting() colorList = {'sets': (0, 0.4, 1), 'chars': (0.4, 1, 0.4), 'props': (0.6, 0.4, 1)} assetTypeList = {'sets': [], 'props': [], 'chars': []} nodeChildren = hou.node(nodePath).children() for child in list(nodeChildren): if str(child) in assetList.keys(): type = assetList[str(child)] if colorNode == True: child.setColor(hou.Color(colorList[type])) assetTypeList[type].append(child) if alignNode == True: u = 0 v = 0 for type in sorted(assetTypeList.keys()): v = 0 for asset in sorted(assetTypeList[type]): pos = hou.Vector2(u, v) asset.setPosition(pos) v -= 1 u -= 3 <|reserved_special_token_0|> <|reserved_special_token_1|> def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True): node = hou.pwd() def getNaskCasting(): path = 'E:/WIP/Work/casting-nask.csv' file = open(path, 'r') fileText = file.readlines() file.close() fileText.pop(0) assetDic = {} for line in fileText: assetType = line.split(',') assetName = assetType[2] assetType = assetType[1].split('/')[0] assetDic[assetName] = assetType.lower() return assetDic assetList = getNaskCasting() colorList = {'sets': (0, 0.4, 1), 'chars': (0.4, 1, 0.4), 'props': (0.6, 0.4, 1)} assetTypeList = {'sets': [], 'props': [], 'chars': []} nodeChildren = hou.node(nodePath).children() for child in list(nodeChildren): if str(child) in assetList.keys(): type = assetList[str(child)] if colorNode == True: child.setColor(hou.Color(colorList[type])) assetTypeList[type].append(child) if alignNode == True: u = 0 v = 0 for type in sorted(assetTypeList.keys()): v = 0 for asset in sorted(assetTypeList[type]): pos = hou.Vector2(u, v) asset.setPosition(pos) v -= 1 u -= 3 reorderAssetsByTypes('/obj/geo1') <|reserved_special_token_1|> def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True): node = hou.pwd() def getNaskCasting(): path = "E:/WIP/Work/casting-nask.csv" file = open(path, "r") fileText = file.readlines() file.close() fileText.pop(0) assetDic = {} for line in fileText: assetType = line.split(",") assetName = assetType[2] assetType = assetType[1].split("/")[0] assetDic[assetName] = assetType.lower() return assetDic assetList = getNaskCasting() colorList = {"sets":(0, 0.4, 1), "chars":(0.4, 1, 0.4), "props":(0.6, 0.4, 1)} assetTypeList = {"sets":[], "props":[], "chars":[]} nodeChildren = hou.node(nodePath).children() #colorize nodes by asset type for child in list(nodeChildren): if str(child) in assetList.keys(): type = assetList[str(child)] if colorNode == True: child.setColor(hou.Color(colorList[type])) assetTypeList[type].append(child) #reorder nodes layout by asset type if alignNode == True: u = 0 v = 0 for type in sorted(assetTypeList.keys()): v = 0 for asset in sorted(assetTypeList[type]): pos = hou.Vector2 (u,v) asset.setPosition(pos) v -= 1 u -= 3 reorderAssetsByTypes("/obj/geo1")
flexible
{ "blob_id": "3073850890eb7a61fb5200c5ab87c802cafe50bb", "index": 7229, "step-1": "<mask token>\n", "step-2": "def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True):\n node = hou.pwd()\n\n def getNaskCasting():\n path = 'E:/WIP/Work/casting-nask.csv'\n file = open(path, 'r')\n fileText = file.readlines()\n file.close()\n fileText.pop(0)\n assetDic = {}\n for line in fileText:\n assetType = line.split(',')\n assetName = assetType[2]\n assetType = assetType[1].split('/')[0]\n assetDic[assetName] = assetType.lower()\n return assetDic\n assetList = getNaskCasting()\n colorList = {'sets': (0, 0.4, 1), 'chars': (0.4, 1, 0.4), 'props': (0.6,\n 0.4, 1)}\n assetTypeList = {'sets': [], 'props': [], 'chars': []}\n nodeChildren = hou.node(nodePath).children()\n for child in list(nodeChildren):\n if str(child) in assetList.keys():\n type = assetList[str(child)]\n if colorNode == True:\n child.setColor(hou.Color(colorList[type]))\n assetTypeList[type].append(child)\n if alignNode == True:\n u = 0\n v = 0\n for type in sorted(assetTypeList.keys()):\n v = 0\n for asset in sorted(assetTypeList[type]):\n pos = hou.Vector2(u, v)\n asset.setPosition(pos)\n v -= 1\n u -= 3\n\n\n<mask token>\n", "step-3": "def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True):\n node = hou.pwd()\n\n def getNaskCasting():\n path = 'E:/WIP/Work/casting-nask.csv'\n file = open(path, 'r')\n fileText = file.readlines()\n file.close()\n fileText.pop(0)\n assetDic = {}\n for line in fileText:\n assetType = line.split(',')\n assetName = assetType[2]\n assetType = assetType[1].split('/')[0]\n assetDic[assetName] = assetType.lower()\n return assetDic\n assetList = getNaskCasting()\n colorList = {'sets': (0, 0.4, 1), 'chars': (0.4, 1, 0.4), 'props': (0.6,\n 0.4, 1)}\n assetTypeList = {'sets': [], 'props': [], 'chars': []}\n nodeChildren = hou.node(nodePath).children()\n for child in list(nodeChildren):\n if str(child) in assetList.keys():\n type = assetList[str(child)]\n if colorNode == True:\n child.setColor(hou.Color(colorList[type]))\n assetTypeList[type].append(child)\n if alignNode == True:\n u = 0\n v = 0\n for type in sorted(assetTypeList.keys()):\n v = 0\n for asset in sorted(assetTypeList[type]):\n pos = hou.Vector2(u, v)\n asset.setPosition(pos)\n v -= 1\n u -= 3\n\n\nreorderAssetsByTypes('/obj/geo1')\n", "step-4": "def reorderAssetsByTypes(nodePath, colorNode=True, alignNode=True):\n node = hou.pwd()\n \n def getNaskCasting():\n path = \"E:/WIP/Work/casting-nask.csv\"\n\n file = open(path, \"r\")\n fileText = file.readlines()\n file.close()\n fileText.pop(0)\n\n assetDic = {}\n\n for line in fileText:\n assetType = line.split(\",\")\n assetName = assetType[2]\n assetType = assetType[1].split(\"/\")[0]\n assetDic[assetName] = assetType.lower()\n\n return assetDic\n \n assetList = getNaskCasting()\n colorList = {\"sets\":(0, 0.4, 1), \"chars\":(0.4, 1, 0.4), \"props\":(0.6, 0.4, 1)}\n assetTypeList = {\"sets\":[], \"props\":[], \"chars\":[]}\n \n nodeChildren = hou.node(nodePath).children()\n \n #colorize nodes by asset type\n for child in list(nodeChildren):\n if str(child) in assetList.keys():\n type = assetList[str(child)]\n if colorNode == True:\n child.setColor(hou.Color(colorList[type]))\n assetTypeList[type].append(child)\n \n #reorder nodes layout by asset type\n if alignNode == True:\n u = 0\n v = 0\n for type in sorted(assetTypeList.keys()):\n v = 0\n for asset in sorted(assetTypeList[type]):\n pos = hou.Vector2 (u,v)\n asset.setPosition(pos)\n v -= 1\n u -= 3\n\nreorderAssetsByTypes(\"/obj/geo1\")\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#! /usr/bin/python from bs4 import BeautifulSoup import requests import sys def exit(err): print err sys.exit(0) def get_text(node, lower = True): if lower: return (''.join(node.findAll(text = True))).strip().lower() return (''.join(node.findAll(text = True))).strip() def get_method_signature(tag): gold = 'Method signature:'.lower() return tag.name == "td" and get_text(tag) == gold def get_returns(tag): gold = 'Returns:'.lower() return tag.name == "pre" and gold in get_text(tag) def main(): if len(sys.argv) != 3: exit("Usage: %s <srm_number> <class_name>" % sys.argv[0]) srm = sys.argv[1].strip().lower() class_name = sys.argv[2].strip().lower() domain = "http://community.topcoder.com" search_url = "%(domain)s/tc?module=ProblemArchive&class=%(class_name)s" data = requests.get(search_url % locals()).text # f = open('/tmp/data.html', 'w') # f.write(data) # f.close() # data = open('/tmp/data.html', 'r') soup = BeautifulSoup(data) result_table = None result_table_string = 'Challenge' tables = soup.findAll('table') tables.reverse() for table in tables: if result_table_string.lower() in get_text(table): result_table = table break else: exit("no problem found, please check class name") result_row = None actual_class_name = None for row in result_table.findAll('tr'): cells = row.findAll('td') if len(cells) < 3: continue if get_text(cells[1]) == class_name and srm in get_text(cells[2]): actual_class_name = get_text(cells[1], lower = False) result_row = row break else: exit("no problem found, please check class name and SRM number") problem_url = "%s%s" % (domain, cells[1].find('a').get('href')) data = requests.get(problem_url).text # f = open('/tmp/problem.html', 'w') # f.write(data) # f.close() #data = open('/tmp/problem.html', 'r') soup = BeautifulSoup(data) try: method_signature_text = soup.findAll(get_method_signature)[-1] method_signature = method_signature_text.nextSibling.string returns_tr = method_signature_text.parent.previousSibling return_type = returns_tr.findAll('td')[1].string.strip() parameters_tr = returns_tr.previousSibling parameters = parameters_tr.findAll('td')[1].string.split(",") method_tr = parameters_tr.previousSibling method_name = method_tr.findAll('td')[1].string.strip() test_cases = soup.findAll(get_returns) expected_return_values = [] inputs = [] for i in range(len(test_cases)): inputs.append([]) for i, test_case in enumerate(test_cases): expected_return_values.append(test_case.string.strip().split(": ")[1]) input_values = test_case.parent.parent.previousSibling.findAll('pre') for input_value in input_values: inputs[i].append(input_value.string.strip()) except: raise exit("error getting method signature, no luck") # inject test cases into template spaces = " " input_test_case = "%(parameter)s var_%(index_1)d_%(index_2)d = %(value)s;\n" invoke_method = "%(return_type)s expected_%(index_1)d = %(lower_actual_class_name)s.%(method_name)s(%(method_params)s);\n" if return_type == "String": compare_outputs = "System.out.println((expected_%(index_1)d.equals(%(expected_value)s) ? \"Passed\" : \"Failed\") + \" for case %(index_1)d\");" else: compare_outputs = "System.out.println(((expected_%(index_1)d == %(expected_value)s) ? \"Passed\" : \"Failed\") + \" for case %(index_1)d\");" compare_outputs += "\n" lower_actual_class_name = actual_class_name.lower() test_case_str = "" for index_1, input_case in enumerate(inputs): # declare the inputs method_params_list = [] for index_2, parameter in enumerate(parameters): value = input_case[index_2] test_case_str += spaces test_case_str += input_test_case % locals() method_params_list.append("var_%(index_1)d_%(index_2)d" % locals()) # invoke the function method_params = ','.join(method_params_list) test_case_str += spaces test_case_str += invoke_method % locals() # compare the output expected_value = expected_return_values[index_1] test_case_str += spaces test_case_str += compare_outputs % locals() # inject everything else into final template template = open('template.java', 'r').read() fp = open('%(actual_class_name)s.java' % locals(), 'w') fp.write(template % locals()) fp.close() print "done :) generated %(actual_class_name)s.java" % locals() if __name__ == "__main__": main()
normal
{ "blob_id": "e3119979028d3dd4e1061563db4ec20607e744d1", "index": 3749, "step-1": "#! /usr/bin/python\n\nfrom bs4 import BeautifulSoup\n\nimport requests\nimport sys\n\ndef exit(err):\n print err\n sys.exit(0)\n\ndef get_text(node, lower = True):\n if lower:\n return (''.join(node.findAll(text = True))).strip().lower()\n return (''.join(node.findAll(text = True))).strip()\n\ndef get_method_signature(tag):\n gold = 'Method signature:'.lower()\n return tag.name == \"td\" and get_text(tag) == gold\n\ndef get_returns(tag):\n gold = 'Returns:'.lower()\n return tag.name == \"pre\" and gold in get_text(tag)\n\ndef main():\n\n if len(sys.argv) != 3:\n exit(\"Usage: %s <srm_number> <class_name>\" % sys.argv[0])\n\n srm = sys.argv[1].strip().lower()\n class_name = sys.argv[2].strip().lower()\n\n domain = \"http://community.topcoder.com\"\n search_url = \"%(domain)s/tc?module=ProblemArchive&class=%(class_name)s\"\n\n data = requests.get(search_url % locals()).text\n # f = open('/tmp/data.html', 'w')\n # f.write(data)\n # f.close()\n # data = open('/tmp/data.html', 'r')\n\n soup = BeautifulSoup(data)\n result_table = None\n result_table_string = 'Challenge'\n tables = soup.findAll('table')\n tables.reverse()\n for table in tables:\n if result_table_string.lower() in get_text(table):\n result_table = table\n break\n else:\n exit(\"no problem found, please check class name\")\n\n result_row = None\n actual_class_name = None\n for row in result_table.findAll('tr'):\n cells = row.findAll('td')\n if len(cells) < 3:\n continue\n if get_text(cells[1]) == class_name and srm in get_text(cells[2]):\n actual_class_name = get_text(cells[1], lower = False)\n result_row = row\n break\n else:\n exit(\"no problem found, please check class name and SRM number\")\n\n problem_url = \"%s%s\" % (domain, cells[1].find('a').get('href'))\n\n data = requests.get(problem_url).text\n # f = open('/tmp/problem.html', 'w')\n # f.write(data)\n # f.close()\n #data = open('/tmp/problem.html', 'r')\n\n soup = BeautifulSoup(data)\n try:\n method_signature_text = soup.findAll(get_method_signature)[-1]\n method_signature = method_signature_text.nextSibling.string\n returns_tr = method_signature_text.parent.previousSibling\n return_type = returns_tr.findAll('td')[1].string.strip()\n parameters_tr = returns_tr.previousSibling\n parameters = parameters_tr.findAll('td')[1].string.split(\",\")\n method_tr = parameters_tr.previousSibling\n method_name = method_tr.findAll('td')[1].string.strip()\n test_cases = soup.findAll(get_returns)\n expected_return_values = []\n inputs = []\n for i in range(len(test_cases)):\n inputs.append([])\n for i, test_case in enumerate(test_cases):\n expected_return_values.append(test_case.string.strip().split(\": \")[1])\n input_values = test_case.parent.parent.previousSibling.findAll('pre')\n for input_value in input_values:\n inputs[i].append(input_value.string.strip())\n except:\n raise\n exit(\"error getting method signature, no luck\")\n\n # inject test cases into template\n spaces = \" \"\n input_test_case = \"%(parameter)s var_%(index_1)d_%(index_2)d = %(value)s;\\n\"\n invoke_method = \"%(return_type)s expected_%(index_1)d = %(lower_actual_class_name)s.%(method_name)s(%(method_params)s);\\n\"\n if return_type == \"String\":\n compare_outputs = \"System.out.println((expected_%(index_1)d.equals(%(expected_value)s) ? \\\"Passed\\\" : \\\"Failed\\\") + \\\" for case %(index_1)d\\\");\"\n else:\n compare_outputs = \"System.out.println(((expected_%(index_1)d == %(expected_value)s) ? \\\"Passed\\\" : \\\"Failed\\\") + \\\" for case %(index_1)d\\\");\"\n compare_outputs += \"\\n\"\n lower_actual_class_name = actual_class_name.lower()\n test_case_str = \"\"\n for index_1, input_case in enumerate(inputs):\n # declare the inputs\n method_params_list = []\n for index_2, parameter in enumerate(parameters):\n value = input_case[index_2]\n test_case_str += spaces\n test_case_str += input_test_case % locals()\n method_params_list.append(\"var_%(index_1)d_%(index_2)d\" % locals())\n # invoke the function\n method_params = ','.join(method_params_list)\n test_case_str += spaces\n test_case_str += invoke_method % locals()\n # compare the output\n expected_value = expected_return_values[index_1]\n test_case_str += spaces\n test_case_str += compare_outputs % locals()\n\n # inject everything else into final template\n template = open('template.java', 'r').read()\n fp = open('%(actual_class_name)s.java' % locals(), 'w')\n fp.write(template % locals())\n fp.close()\n print \"done :) generated %(actual_class_name)s.java\" % locals()\n\nif __name__ == \"__main__\":\n main()", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Config(object): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Config(object): from_train_file = 'data/dev.en' to_train_file = 'data/dev.vi' _PAD = b'_PAD' _GO = b'_GO' _EOS = b'_EOS' _UNK = b'_UNK' _START_VOCAB = [_PAD, _GO, _EOS, _UNK] PAD_ID = 0 GO_ID = 1 EOS_ID = 2 UNK_ID = 3 batch_size = 64 max_epochs = 1 early_stopping = 2 dropout = 0.9 lr = 0.5 l2 = 0.001 learning_rate_decay = 0.99 batch_size = 32 size = 1024 num_layers = 3 from_vocab_size = 10000 to_vocab_size = 10000 data_dir = 'data/' dev_dir = 'data/' max_train_data_size = 200 steps_per_checkpoint = 5 forward_only = False buckets = [(10, 50)] num_samples = 512 encode_layers = 3 encode_num_steps = 10 encode_hidden_size = 50 decode_layers = 3 encode_num_steps = 10 decode_hidden_size = 50 dtype = tf.float32 <|reserved_special_token_1|> import tensorflow as tf class Config(object): from_train_file = 'data/dev.en' to_train_file = 'data/dev.vi' _PAD = b'_PAD' _GO = b'_GO' _EOS = b'_EOS' _UNK = b'_UNK' _START_VOCAB = [_PAD, _GO, _EOS, _UNK] PAD_ID = 0 GO_ID = 1 EOS_ID = 2 UNK_ID = 3 batch_size = 64 max_epochs = 1 early_stopping = 2 dropout = 0.9 lr = 0.5 l2 = 0.001 learning_rate_decay = 0.99 batch_size = 32 size = 1024 num_layers = 3 from_vocab_size = 10000 to_vocab_size = 10000 data_dir = 'data/' dev_dir = 'data/' max_train_data_size = 200 steps_per_checkpoint = 5 forward_only = False buckets = [(10, 50)] num_samples = 512 encode_layers = 3 encode_num_steps = 10 encode_hidden_size = 50 decode_layers = 3 encode_num_steps = 10 decode_hidden_size = 50 dtype = tf.float32 <|reserved_special_token_1|> import tensorflow as tf class Config(object): # Source and Target files from_train_file='data/dev.en' to_train_file='data/dev.vi' # Special characters and ID's _PAD = b"_PAD" _GO = b"_GO" _EOS = b"_EOS" _UNK = b"_UNK" _START_VOCAB = [_PAD, _GO, _EOS, _UNK] PAD_ID = 0 GO_ID = 1 EOS_ID = 2 UNK_ID = 3 # NMT hyperparameters batch_size = 64 max_epochs = 1 early_stopping = 2 dropout = 0.9 lr = 0.5 l2 = 0.001 learning_rate_decay = 0.99 batch_size = 32 size = 1024 num_layers = 3 from_vocab_size = 10000 to_vocab_size = 10000 data_dir = "data/" dev_dir = "data/" max_train_data_size = 200 steps_per_checkpoint = 5 forward_only = False # Buckets buckets = [(10,50)] # Other config variables num_samples = 512 # Encoding parameters encode_layers = 3 encode_num_steps = 10 encode_hidden_size = 50 # Encoding parameters decode_layers = 3 encode_num_steps = 10 decode_hidden_size = 50 dtype = tf.float32
flexible
{ "blob_id": "c27c2df1830f066ca4f973c46967722869090d05", "index": 1373, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Config(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Config(object):\n from_train_file = 'data/dev.en'\n to_train_file = 'data/dev.vi'\n _PAD = b'_PAD'\n _GO = b'_GO'\n _EOS = b'_EOS'\n _UNK = b'_UNK'\n _START_VOCAB = [_PAD, _GO, _EOS, _UNK]\n PAD_ID = 0\n GO_ID = 1\n EOS_ID = 2\n UNK_ID = 3\n batch_size = 64\n max_epochs = 1\n early_stopping = 2\n dropout = 0.9\n lr = 0.5\n l2 = 0.001\n learning_rate_decay = 0.99\n batch_size = 32\n size = 1024\n num_layers = 3\n from_vocab_size = 10000\n to_vocab_size = 10000\n data_dir = 'data/'\n dev_dir = 'data/'\n max_train_data_size = 200\n steps_per_checkpoint = 5\n forward_only = False\n buckets = [(10, 50)]\n num_samples = 512\n encode_layers = 3\n encode_num_steps = 10\n encode_hidden_size = 50\n decode_layers = 3\n encode_num_steps = 10\n decode_hidden_size = 50\n dtype = tf.float32\n", "step-4": "import tensorflow as tf\n\n\nclass Config(object):\n from_train_file = 'data/dev.en'\n to_train_file = 'data/dev.vi'\n _PAD = b'_PAD'\n _GO = b'_GO'\n _EOS = b'_EOS'\n _UNK = b'_UNK'\n _START_VOCAB = [_PAD, _GO, _EOS, _UNK]\n PAD_ID = 0\n GO_ID = 1\n EOS_ID = 2\n UNK_ID = 3\n batch_size = 64\n max_epochs = 1\n early_stopping = 2\n dropout = 0.9\n lr = 0.5\n l2 = 0.001\n learning_rate_decay = 0.99\n batch_size = 32\n size = 1024\n num_layers = 3\n from_vocab_size = 10000\n to_vocab_size = 10000\n data_dir = 'data/'\n dev_dir = 'data/'\n max_train_data_size = 200\n steps_per_checkpoint = 5\n forward_only = False\n buckets = [(10, 50)]\n num_samples = 512\n encode_layers = 3\n encode_num_steps = 10\n encode_hidden_size = 50\n decode_layers = 3\n encode_num_steps = 10\n decode_hidden_size = 50\n dtype = tf.float32\n", "step-5": "import tensorflow as tf\n\nclass Config(object):\n\n # Source and Target files\n from_train_file='data/dev.en'\n to_train_file='data/dev.vi'\n\n # Special characters and ID's\n _PAD = b\"_PAD\"\n _GO = b\"_GO\"\n _EOS = b\"_EOS\"\n _UNK = b\"_UNK\"\n _START_VOCAB = [_PAD, _GO, _EOS, _UNK]\n\n PAD_ID = 0\n GO_ID = 1\n EOS_ID = 2\n UNK_ID = 3\n\n # NMT hyperparameters\n batch_size = 64\n max_epochs = 1\n early_stopping = 2\n dropout = 0.9\n lr = 0.5\n l2 = 0.001\n learning_rate_decay = 0.99\n batch_size = 32\n size = 1024\n num_layers = 3\n from_vocab_size = 10000\n to_vocab_size = 10000\n data_dir = \"data/\"\n dev_dir = \"data/\"\n max_train_data_size = 200\n steps_per_checkpoint = 5\n forward_only = False\n\n # Buckets\n buckets = [(10,50)]\n\n # Other config variables\n num_samples = 512\n\n # Encoding parameters\n encode_layers = 3\n encode_num_steps = 10\n encode_hidden_size = 50\n\n # Encoding parameters\n decode_layers = 3\n encode_num_steps = 10\n decode_hidden_size = 50\n\n dtype = tf.float32\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) ->int: horizontalCuts.sort() verticalCuts.sort() horizontalCuts.append(h) verticalCuts.append(w) hbreadth = 0 prev = 0 for h in horizontalCuts: height = h - prev hbreadth = max(height, hbreadth) prev = h prev = 0 vlength = 0 for v in verticalCuts: height = v - prev vlength = max(vlength, height) prev = v maxarea = hbreadth * vlength % (10 ** 9 + 7) return maxarea <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) ->int: horizontalCuts.sort() verticalCuts.sort() horizontalCuts.append(h) verticalCuts.append(w) hbreadth = 0 prev = 0 for h in horizontalCuts: height = h - prev hbreadth = max(height, hbreadth) prev = h prev = 0 vlength = 0 for v in verticalCuts: height = v - prev vlength = max(vlength, height) prev = v maxarea = hbreadth * vlength % (10 ** 9 + 7) return maxarea <|reserved_special_token_0|> print(obj.maxArea(h, w, horizontalCuts, verticalCuts)) <|reserved_special_token_1|> <|reserved_special_token_0|> h = 5 w = 4 horizontalCuts = [3] verticalCuts = [3] class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) ->int: horizontalCuts.sort() verticalCuts.sort() horizontalCuts.append(h) verticalCuts.append(w) hbreadth = 0 prev = 0 for h in horizontalCuts: height = h - prev hbreadth = max(height, hbreadth) prev = h prev = 0 vlength = 0 for v in verticalCuts: height = v - prev vlength = max(vlength, height) prev = v maxarea = hbreadth * vlength % (10 ** 9 + 7) return maxarea obj = Solution() print(obj.maxArea(h, w, horizontalCuts, verticalCuts)) <|reserved_special_token_1|> from typing import List h = 5 w = 4 horizontalCuts = [3] verticalCuts = [3] class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) ->int: horizontalCuts.sort() verticalCuts.sort() horizontalCuts.append(h) verticalCuts.append(w) hbreadth = 0 prev = 0 for h in horizontalCuts: height = h - prev hbreadth = max(height, hbreadth) prev = h prev = 0 vlength = 0 for v in verticalCuts: height = v - prev vlength = max(vlength, height) prev = v maxarea = hbreadth * vlength % (10 ** 9 + 7) return maxarea obj = Solution() print(obj.maxArea(h, w, horizontalCuts, verticalCuts)) <|reserved_special_token_1|> from typing import List h = 5 w = 4 horizontalCuts = [3] verticalCuts = [3] class Solution: def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int: horizontalCuts.sort() verticalCuts.sort() horizontalCuts.append(h) verticalCuts.append(w) hbreadth= 0 prev=0 for h in horizontalCuts: height= h-prev hbreadth= max(height, hbreadth) prev= h prev=0 vlength=0 for v in verticalCuts: height= v-prev vlength= max(vlength, height) prev=v maxarea= (hbreadth * vlength) % ((10**9) + 7) return maxarea obj=Solution() print(obj.maxArea(h, w, horizontalCuts, verticalCuts))
flexible
{ "blob_id": "8fb559810fbf79f0849ed98e51d3f2ad1ccc4b8b", "index": 8296, "step-1": "<mask token>\n\n\nclass Solution:\n\n def maxArea(self, h: int, w: int, horizontalCuts: List[int],\n verticalCuts: List[int]) ->int:\n horizontalCuts.sort()\n verticalCuts.sort()\n horizontalCuts.append(h)\n verticalCuts.append(w)\n hbreadth = 0\n prev = 0\n for h in horizontalCuts:\n height = h - prev\n hbreadth = max(height, hbreadth)\n prev = h\n prev = 0\n vlength = 0\n for v in verticalCuts:\n height = v - prev\n vlength = max(vlength, height)\n prev = v\n maxarea = hbreadth * vlength % (10 ** 9 + 7)\n return maxarea\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n\n def maxArea(self, h: int, w: int, horizontalCuts: List[int],\n verticalCuts: List[int]) ->int:\n horizontalCuts.sort()\n verticalCuts.sort()\n horizontalCuts.append(h)\n verticalCuts.append(w)\n hbreadth = 0\n prev = 0\n for h in horizontalCuts:\n height = h - prev\n hbreadth = max(height, hbreadth)\n prev = h\n prev = 0\n vlength = 0\n for v in verticalCuts:\n height = v - prev\n vlength = max(vlength, height)\n prev = v\n maxarea = hbreadth * vlength % (10 ** 9 + 7)\n return maxarea\n\n\n<mask token>\nprint(obj.maxArea(h, w, horizontalCuts, verticalCuts))\n", "step-3": "<mask token>\nh = 5\nw = 4\nhorizontalCuts = [3]\nverticalCuts = [3]\n\n\nclass Solution:\n\n def maxArea(self, h: int, w: int, horizontalCuts: List[int],\n verticalCuts: List[int]) ->int:\n horizontalCuts.sort()\n verticalCuts.sort()\n horizontalCuts.append(h)\n verticalCuts.append(w)\n hbreadth = 0\n prev = 0\n for h in horizontalCuts:\n height = h - prev\n hbreadth = max(height, hbreadth)\n prev = h\n prev = 0\n vlength = 0\n for v in verticalCuts:\n height = v - prev\n vlength = max(vlength, height)\n prev = v\n maxarea = hbreadth * vlength % (10 ** 9 + 7)\n return maxarea\n\n\nobj = Solution()\nprint(obj.maxArea(h, w, horizontalCuts, verticalCuts))\n", "step-4": "from typing import List\nh = 5\nw = 4\nhorizontalCuts = [3]\nverticalCuts = [3]\n\n\nclass Solution:\n\n def maxArea(self, h: int, w: int, horizontalCuts: List[int],\n verticalCuts: List[int]) ->int:\n horizontalCuts.sort()\n verticalCuts.sort()\n horizontalCuts.append(h)\n verticalCuts.append(w)\n hbreadth = 0\n prev = 0\n for h in horizontalCuts:\n height = h - prev\n hbreadth = max(height, hbreadth)\n prev = h\n prev = 0\n vlength = 0\n for v in verticalCuts:\n height = v - prev\n vlength = max(vlength, height)\n prev = v\n maxarea = hbreadth * vlength % (10 ** 9 + 7)\n return maxarea\n\n\nobj = Solution()\nprint(obj.maxArea(h, w, horizontalCuts, verticalCuts))\n", "step-5": "from typing import List\nh = 5\nw = 4\nhorizontalCuts = [3]\nverticalCuts = [3]\nclass Solution:\n def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:\n horizontalCuts.sort()\n verticalCuts.sort()\n horizontalCuts.append(h)\n verticalCuts.append(w)\n hbreadth= 0\n prev=0\n for h in horizontalCuts:\n height= h-prev\n hbreadth= max(height, hbreadth)\n prev= h\n\n prev=0\n vlength=0\n for v in verticalCuts:\n height= v-prev\n vlength= max(vlength, height)\n prev=v\n\n maxarea= (hbreadth * vlength) % ((10**9) + 7)\n return maxarea\n\nobj=Solution()\nprint(obj.maxArea(h, w, horizontalCuts, verticalCuts))\n", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
from web3 import Web3, HTTPProvider, IPCProvider from tcmb.tcmb_parser import TCMB_Processor from ecb.ecb_parser import ECB_Processor from web3.contract import ConciseContract from web3.middleware import geth_poa_middleware import json import time tcmb_currencies = ["TRY", "USD", "AUD", "DKK", "EUR", "GBP", "CHF", "SEK", "CAD", "KWD", "NOK", "SAR", "JPY", "BGN", "RON", "RUB", "IRR", "CNY", "PKR"] ecb_currencies = ["EUR", "USD", "JPY", "BGN", "CZK", "DKK", "GBP", "HUF", "PLN", "RON", "SEK", "CHF", "ISK", "NOK", "HRK", "RUB", "TRY", "AUD", "BRL", "CAD", "CNY", "HKD", "IDR", "ILS", "INR", "KRW", "MXN", "MYR", "NZD", "PHP", "SGD", "THB", "ZAR"] def epoch_day(epoch_time): epoch_time = int(epoch_time) return(epoch_time - (epoch_time % 86400)) with open('config_ebloc.json') as json_data_file: config_data = json.load(json_data_file) owner_address = config_data["owner"]["address"] owner_password = config_data["owner"]["password"] contract_address = config_data["contract"]["address"] contract_abi = config_data["contract"]["abi"] gas = int(config_data["price"]["gas"]) gas_price = Web3.toWei( int(config_data["price"]["gas_price"]), 'gwei') ecb_daily_log_path = config_data["log"]["ecb_daily"] tcmb_daily_log_path = config_data["log"]["tcmb_daily"] geth_ipc_path = config_data["geth"]["geth_ipc_path"] contract_address = Web3.toChecksumAddress(contract_address) web3 = Web3(IPCProvider(geth_ipc_path)) web3.middleware_stack.inject(geth_poa_middleware, layer=0) web3.eth.defaultAccount = web3.eth.accounts[0] web3.personal.unlockAccount(web3.eth.accounts[0], owner_password) contract_instance = web3.eth.contract(abi=contract_abi, address=contract_address, ContractFactoryClass=ConciseContract) unix_time = Web3.toInt(epoch_day(time.time())) def add_ecb(): unix_time = Web3.toInt(epoch_day(time.time())) ECB = ECB_Processor() f = open(ecb_daily_log_path, "a") if(time.strftime("%Y-%m-%d") == ECB.Currency_Dict["time"]): for curr in ecb_currencies: curr_code = bytes(curr, encoding='utf-8') curr_value = web3.toInt(int(float(ECB.Currency_Dict[curr])*(10**9))) tx_hash = contract_instance.add_ecb(unix_time, curr_code, curr_value, transact={'from': web3.eth.accounts[0]}) tx_hash = tx_hash.hex() print(time.strftime("%Y-%m-%d %H:%M"), unix_time, tx_hash, curr_code, file=f) else: print(time.strftime("%Y-%m-%d %H:%M"), unix_time, "Weekend", file=f) f.close() def add_tcmb(): unix_time = Web3.toInt(epoch_day(time.time())) TCMB = TCMB_Processor() f = open(tcmb_daily_log_path, "a") if(time.strftime("%m/%d/%Y") == TCMB.CURRENCY_DICT["Date"]): for curr in tcmb_currencies: curr_code = bytes(curr, encoding='utf-8') curr_value_fb = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr]["ForexBuying"])*(10**9))) curr_value_fs = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr]["ForexSelling"])*(10**9))) # forex buying tx_hash_fb = contract_instance.add_tcmb_forexbuying(unix_time, curr_code, curr_value_fb, transact={'from': web3.eth.accounts[0]}) tx_hash_fb = tx_hash_fb.hex() print(time.strftime("%Y-%m-%d %H:%M"), unix_time, tx_hash_fb, curr_code, file=f) # forex selling tx_hash_fs = contract_instance.add_tcmb_forexselling(unix_time, curr_code, curr_value_fs, transact={'from': web3.eth.accounts[0]}) tx_hash_fs = tx_hash_fs.hex() print(time.strftime("%Y-%m-%d %H:%M"), unix_time, tx_hash_fs, curr_code, file=f) else: print(time.strftime("%Y-%m-%d %H:%M"), unix_time, "Weekend", file=f) f.close() if __name__ == "__main__": add_ecb() add_tcmb() print(time.strftime("%Y-%m-%d %H:%M"), " DONE EBLOC add_ecb & add_tcmb")
normal
{ "blob_id": "ecd5097d9d497b62b89217ee3c46506f21fc15d2", "index": 5065, "step-1": "<mask token>\n\n\ndef epoch_day(epoch_time):\n epoch_time = int(epoch_time)\n return epoch_time - epoch_time % 86400\n\n\n<mask token>\n\n\ndef add_ecb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n ECB = ECB_Processor()\n f = open(ecb_daily_log_path, 'a')\n if time.strftime('%Y-%m-%d') == ECB.Currency_Dict['time']:\n for curr in ecb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value = web3.toInt(int(float(ECB.Currency_Dict[curr]) * 10 **\n 9))\n tx_hash = contract_instance.add_ecb(unix_time, curr_code,\n curr_value, transact={'from': web3.eth.accounts[0]})\n tx_hash = tx_hash.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\ndef add_tcmb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n TCMB = TCMB_Processor()\n f = open(tcmb_daily_log_path, 'a')\n if time.strftime('%m/%d/%Y') == TCMB.CURRENCY_DICT['Date']:\n for curr in tcmb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value_fb = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexBuying']) * 10 ** 9))\n curr_value_fs = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexSelling']) * 10 ** 9))\n tx_hash_fb = contract_instance.add_tcmb_forexbuying(unix_time,\n curr_code, curr_value_fb, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fb = tx_hash_fb.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fb,\n curr_code, file=f)\n tx_hash_fs = contract_instance.add_tcmb_forexselling(unix_time,\n curr_code, curr_value_fs, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fs = tx_hash_fs.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fs,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef epoch_day(epoch_time):\n epoch_time = int(epoch_time)\n return epoch_time - epoch_time % 86400\n\n\nwith open('config_ebloc.json') as json_data_file:\n config_data = json.load(json_data_file)\n<mask token>\nweb3.middleware_stack.inject(geth_poa_middleware, layer=0)\n<mask token>\nweb3.personal.unlockAccount(web3.eth.accounts[0], owner_password)\n<mask token>\n\n\ndef add_ecb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n ECB = ECB_Processor()\n f = open(ecb_daily_log_path, 'a')\n if time.strftime('%Y-%m-%d') == ECB.Currency_Dict['time']:\n for curr in ecb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value = web3.toInt(int(float(ECB.Currency_Dict[curr]) * 10 **\n 9))\n tx_hash = contract_instance.add_ecb(unix_time, curr_code,\n curr_value, transact={'from': web3.eth.accounts[0]})\n tx_hash = tx_hash.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\ndef add_tcmb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n TCMB = TCMB_Processor()\n f = open(tcmb_daily_log_path, 'a')\n if time.strftime('%m/%d/%Y') == TCMB.CURRENCY_DICT['Date']:\n for curr in tcmb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value_fb = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexBuying']) * 10 ** 9))\n curr_value_fs = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexSelling']) * 10 ** 9))\n tx_hash_fb = contract_instance.add_tcmb_forexbuying(unix_time,\n curr_code, curr_value_fb, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fb = tx_hash_fb.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fb,\n curr_code, file=f)\n tx_hash_fs = contract_instance.add_tcmb_forexselling(unix_time,\n curr_code, curr_value_fs, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fs = tx_hash_fs.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fs,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\nif __name__ == '__main__':\n add_ecb()\n add_tcmb()\n print(time.strftime('%Y-%m-%d %H:%M'), ' DONE EBLOC add_ecb & add_tcmb')\n", "step-3": "<mask token>\ntcmb_currencies = ['TRY', 'USD', 'AUD', 'DKK', 'EUR', 'GBP', 'CHF', 'SEK',\n 'CAD', 'KWD', 'NOK', 'SAR', 'JPY', 'BGN', 'RON', 'RUB', 'IRR', 'CNY', 'PKR'\n ]\necb_currencies = ['EUR', 'USD', 'JPY', 'BGN', 'CZK', 'DKK', 'GBP', 'HUF',\n 'PLN', 'RON', 'SEK', 'CHF', 'ISK', 'NOK', 'HRK', 'RUB', 'TRY', 'AUD',\n 'BRL', 'CAD', 'CNY', 'HKD', 'IDR', 'ILS', 'INR', 'KRW', 'MXN', 'MYR',\n 'NZD', 'PHP', 'SGD', 'THB', 'ZAR']\n\n\ndef epoch_day(epoch_time):\n epoch_time = int(epoch_time)\n return epoch_time - epoch_time % 86400\n\n\nwith open('config_ebloc.json') as json_data_file:\n config_data = json.load(json_data_file)\nowner_address = config_data['owner']['address']\nowner_password = config_data['owner']['password']\ncontract_address = config_data['contract']['address']\ncontract_abi = config_data['contract']['abi']\ngas = int(config_data['price']['gas'])\ngas_price = Web3.toWei(int(config_data['price']['gas_price']), 'gwei')\necb_daily_log_path = config_data['log']['ecb_daily']\ntcmb_daily_log_path = config_data['log']['tcmb_daily']\ngeth_ipc_path = config_data['geth']['geth_ipc_path']\ncontract_address = Web3.toChecksumAddress(contract_address)\nweb3 = Web3(IPCProvider(geth_ipc_path))\nweb3.middleware_stack.inject(geth_poa_middleware, layer=0)\nweb3.eth.defaultAccount = web3.eth.accounts[0]\nweb3.personal.unlockAccount(web3.eth.accounts[0], owner_password)\ncontract_instance = web3.eth.contract(abi=contract_abi, address=\n contract_address, ContractFactoryClass=ConciseContract)\nunix_time = Web3.toInt(epoch_day(time.time()))\n\n\ndef add_ecb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n ECB = ECB_Processor()\n f = open(ecb_daily_log_path, 'a')\n if time.strftime('%Y-%m-%d') == ECB.Currency_Dict['time']:\n for curr in ecb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value = web3.toInt(int(float(ECB.Currency_Dict[curr]) * 10 **\n 9))\n tx_hash = contract_instance.add_ecb(unix_time, curr_code,\n curr_value, transact={'from': web3.eth.accounts[0]})\n tx_hash = tx_hash.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\ndef add_tcmb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n TCMB = TCMB_Processor()\n f = open(tcmb_daily_log_path, 'a')\n if time.strftime('%m/%d/%Y') == TCMB.CURRENCY_DICT['Date']:\n for curr in tcmb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value_fb = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexBuying']) * 10 ** 9))\n curr_value_fs = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexSelling']) * 10 ** 9))\n tx_hash_fb = contract_instance.add_tcmb_forexbuying(unix_time,\n curr_code, curr_value_fb, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fb = tx_hash_fb.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fb,\n curr_code, file=f)\n tx_hash_fs = contract_instance.add_tcmb_forexselling(unix_time,\n curr_code, curr_value_fs, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fs = tx_hash_fs.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fs,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\nif __name__ == '__main__':\n add_ecb()\n add_tcmb()\n print(time.strftime('%Y-%m-%d %H:%M'), ' DONE EBLOC add_ecb & add_tcmb')\n", "step-4": "from web3 import Web3, HTTPProvider, IPCProvider\nfrom tcmb.tcmb_parser import TCMB_Processor\nfrom ecb.ecb_parser import ECB_Processor\nfrom web3.contract import ConciseContract\nfrom web3.middleware import geth_poa_middleware\nimport json\nimport time\ntcmb_currencies = ['TRY', 'USD', 'AUD', 'DKK', 'EUR', 'GBP', 'CHF', 'SEK',\n 'CAD', 'KWD', 'NOK', 'SAR', 'JPY', 'BGN', 'RON', 'RUB', 'IRR', 'CNY', 'PKR'\n ]\necb_currencies = ['EUR', 'USD', 'JPY', 'BGN', 'CZK', 'DKK', 'GBP', 'HUF',\n 'PLN', 'RON', 'SEK', 'CHF', 'ISK', 'NOK', 'HRK', 'RUB', 'TRY', 'AUD',\n 'BRL', 'CAD', 'CNY', 'HKD', 'IDR', 'ILS', 'INR', 'KRW', 'MXN', 'MYR',\n 'NZD', 'PHP', 'SGD', 'THB', 'ZAR']\n\n\ndef epoch_day(epoch_time):\n epoch_time = int(epoch_time)\n return epoch_time - epoch_time % 86400\n\n\nwith open('config_ebloc.json') as json_data_file:\n config_data = json.load(json_data_file)\nowner_address = config_data['owner']['address']\nowner_password = config_data['owner']['password']\ncontract_address = config_data['contract']['address']\ncontract_abi = config_data['contract']['abi']\ngas = int(config_data['price']['gas'])\ngas_price = Web3.toWei(int(config_data['price']['gas_price']), 'gwei')\necb_daily_log_path = config_data['log']['ecb_daily']\ntcmb_daily_log_path = config_data['log']['tcmb_daily']\ngeth_ipc_path = config_data['geth']['geth_ipc_path']\ncontract_address = Web3.toChecksumAddress(contract_address)\nweb3 = Web3(IPCProvider(geth_ipc_path))\nweb3.middleware_stack.inject(geth_poa_middleware, layer=0)\nweb3.eth.defaultAccount = web3.eth.accounts[0]\nweb3.personal.unlockAccount(web3.eth.accounts[0], owner_password)\ncontract_instance = web3.eth.contract(abi=contract_abi, address=\n contract_address, ContractFactoryClass=ConciseContract)\nunix_time = Web3.toInt(epoch_day(time.time()))\n\n\ndef add_ecb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n ECB = ECB_Processor()\n f = open(ecb_daily_log_path, 'a')\n if time.strftime('%Y-%m-%d') == ECB.Currency_Dict['time']:\n for curr in ecb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value = web3.toInt(int(float(ECB.Currency_Dict[curr]) * 10 **\n 9))\n tx_hash = contract_instance.add_ecb(unix_time, curr_code,\n curr_value, transact={'from': web3.eth.accounts[0]})\n tx_hash = tx_hash.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\ndef add_tcmb():\n unix_time = Web3.toInt(epoch_day(time.time()))\n TCMB = TCMB_Processor()\n f = open(tcmb_daily_log_path, 'a')\n if time.strftime('%m/%d/%Y') == TCMB.CURRENCY_DICT['Date']:\n for curr in tcmb_currencies:\n curr_code = bytes(curr, encoding='utf-8')\n curr_value_fb = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexBuying']) * 10 ** 9))\n curr_value_fs = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\n 'ForexSelling']) * 10 ** 9))\n tx_hash_fb = contract_instance.add_tcmb_forexbuying(unix_time,\n curr_code, curr_value_fb, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fb = tx_hash_fb.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fb,\n curr_code, file=f)\n tx_hash_fs = contract_instance.add_tcmb_forexselling(unix_time,\n curr_code, curr_value_fs, transact={'from': web3.eth.\n accounts[0]})\n tx_hash_fs = tx_hash_fs.hex()\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, tx_hash_fs,\n curr_code, file=f)\n else:\n print(time.strftime('%Y-%m-%d %H:%M'), unix_time, 'Weekend', file=f)\n f.close()\n\n\nif __name__ == '__main__':\n add_ecb()\n add_tcmb()\n print(time.strftime('%Y-%m-%d %H:%M'), ' DONE EBLOC add_ecb & add_tcmb')\n", "step-5": "from web3 import Web3, HTTPProvider, IPCProvider\nfrom tcmb.tcmb_parser import TCMB_Processor\nfrom ecb.ecb_parser import ECB_Processor\nfrom web3.contract import ConciseContract\nfrom web3.middleware import geth_poa_middleware\nimport json\nimport time\n\ntcmb_currencies = [\"TRY\", \"USD\", \"AUD\", \"DKK\", \"EUR\", \"GBP\", \"CHF\", \"SEK\", \"CAD\", \n\t\t\"KWD\", \"NOK\", \"SAR\", \"JPY\", \"BGN\", \"RON\", \"RUB\", \"IRR\", \"CNY\", \"PKR\"]\n\necb_currencies = [\"EUR\", \"USD\", \"JPY\", \"BGN\", \"CZK\", \"DKK\", \"GBP\", \"HUF\", \"PLN\", \n\t\t\"RON\", \"SEK\", \"CHF\", \"ISK\", \"NOK\", \"HRK\", \"RUB\", \"TRY\", \"AUD\", \"BRL\", \n\t\t\"CAD\", \"CNY\", \"HKD\", \"IDR\", \"ILS\", \"INR\", \"KRW\", \"MXN\", \"MYR\", \"NZD\", \n\t\t\"PHP\", \"SGD\", \"THB\", \"ZAR\"]\n\ndef epoch_day(epoch_time):\n\tepoch_time = int(epoch_time)\n\treturn(epoch_time - (epoch_time % 86400))\n\nwith open('config_ebloc.json') as json_data_file:\n\tconfig_data = json.load(json_data_file)\n\nowner_address = config_data[\"owner\"][\"address\"]\nowner_password = config_data[\"owner\"][\"password\"]\ncontract_address = config_data[\"contract\"][\"address\"]\ncontract_abi = config_data[\"contract\"][\"abi\"]\ngas = int(config_data[\"price\"][\"gas\"])\ngas_price = Web3.toWei( int(config_data[\"price\"][\"gas_price\"]), 'gwei')\necb_daily_log_path = config_data[\"log\"][\"ecb_daily\"]\ntcmb_daily_log_path = config_data[\"log\"][\"tcmb_daily\"]\ngeth_ipc_path = config_data[\"geth\"][\"geth_ipc_path\"]\n\ncontract_address = Web3.toChecksumAddress(contract_address)\n\nweb3 = Web3(IPCProvider(geth_ipc_path))\nweb3.middleware_stack.inject(geth_poa_middleware, layer=0)\n\nweb3.eth.defaultAccount = web3.eth.accounts[0]\nweb3.personal.unlockAccount(web3.eth.accounts[0], owner_password)\n\ncontract_instance = web3.eth.contract(abi=contract_abi, address=contract_address, ContractFactoryClass=ConciseContract)\n\nunix_time = Web3.toInt(epoch_day(time.time()))\n\ndef add_ecb():\n\tunix_time = Web3.toInt(epoch_day(time.time()))\n\tECB = ECB_Processor()\n\tf = open(ecb_daily_log_path, \"a\")\n\tif(time.strftime(\"%Y-%m-%d\") == ECB.Currency_Dict[\"time\"]):\n\t\tfor curr in ecb_currencies:\n\t\t\tcurr_code = bytes(curr, encoding='utf-8')\n\t\t\tcurr_value = web3.toInt(int(float(ECB.Currency_Dict[curr])*(10**9)))\n\t\t\ttx_hash = contract_instance.add_ecb(unix_time, curr_code, curr_value, transact={'from': web3.eth.accounts[0]})\n\t\t\ttx_hash = tx_hash.hex()\n\t\t\tprint(time.strftime(\"%Y-%m-%d %H:%M\"), unix_time, tx_hash, curr_code, file=f)\n\telse:\n\t\tprint(time.strftime(\"%Y-%m-%d %H:%M\"), unix_time, \"Weekend\", file=f)\n\tf.close()\n\ndef add_tcmb():\n\tunix_time = Web3.toInt(epoch_day(time.time()))\n\tTCMB = TCMB_Processor()\n\tf = open(tcmb_daily_log_path, \"a\")\n\tif(time.strftime(\"%m/%d/%Y\") == TCMB.CURRENCY_DICT[\"Date\"]):\n\t\tfor curr in tcmb_currencies:\n\t\t\tcurr_code = bytes(curr, encoding='utf-8')\n\t\t\tcurr_value_fb = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\"ForexBuying\"])*(10**9)))\n\t\t\tcurr_value_fs = web3.toInt(int(float(TCMB.CURRENCY_DICT[curr][\"ForexSelling\"])*(10**9)))\n\t\t\t# forex buying\n\t\t\ttx_hash_fb = contract_instance.add_tcmb_forexbuying(unix_time, curr_code, curr_value_fb, transact={'from': web3.eth.accounts[0]})\n\t\t\ttx_hash_fb = tx_hash_fb.hex()\n\t\t\tprint(time.strftime(\"%Y-%m-%d %H:%M\"), unix_time, tx_hash_fb, curr_code, file=f)\n\t\t\t# forex selling\n\t\t\ttx_hash_fs = contract_instance.add_tcmb_forexselling(unix_time, curr_code, curr_value_fs, transact={'from': web3.eth.accounts[0]})\n\t\t\ttx_hash_fs = tx_hash_fs.hex()\n\t\t\tprint(time.strftime(\"%Y-%m-%d %H:%M\"), unix_time, tx_hash_fs, curr_code, file=f)\n\telse:\n\t\tprint(time.strftime(\"%Y-%m-%d %H:%M\"), unix_time, \"Weekend\", file=f)\n\tf.close()\n\n\nif __name__ == \"__main__\":\n\tadd_ecb()\n\tadd_tcmb()\n\tprint(time.strftime(\"%Y-%m-%d %H:%M\"), \" DONE EBLOC add_ecb & add_tcmb\")", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> def countVowels(string): count = 0 vowels = ['a', 'e', 'i', 'o', 'u', 'y'] for vowel in vowels: count += string.count(vowel) return count <|reserved_special_token_0|> def isPalindrome(string): return reverse(string) == string def main(): count = 5 while count > 0: string = input('Enter a string: ') print('The middle character(s) is/are: ' + middle(string)) print('The string reversed is: ' + reverse(string)) print('The string contains ' + str(countVowels(string)) + ' vowels.') if isPalindrome(string): print('That is a palindrome.\n') else: print('That is not palindrome.\n') count -= 1 <|reserved_special_token_0|> <|reserved_special_token_1|> def middle(string): characters = list(string) length = len(characters) middleNum = round((length + 0.5) / 2) if length % 2 == 0: return characters[middleNum - 1] + characters[middleNum] else: return characters[middleNum - 1] def countVowels(string): count = 0 vowels = ['a', 'e', 'i', 'o', 'u', 'y'] for vowel in vowels: count += string.count(vowel) return count <|reserved_special_token_0|> def isPalindrome(string): return reverse(string) == string def main(): count = 5 while count > 0: string = input('Enter a string: ') print('The middle character(s) is/are: ' + middle(string)) print('The string reversed is: ' + reverse(string)) print('The string contains ' + str(countVowels(string)) + ' vowels.') if isPalindrome(string): print('That is a palindrome.\n') else: print('That is not palindrome.\n') count -= 1 <|reserved_special_token_0|> <|reserved_special_token_1|> def middle(string): characters = list(string) length = len(characters) middleNum = round((length + 0.5) / 2) if length % 2 == 0: return characters[middleNum - 1] + characters[middleNum] else: return characters[middleNum - 1] def countVowels(string): count = 0 vowels = ['a', 'e', 'i', 'o', 'u', 'y'] for vowel in vowels: count += string.count(vowel) return count def reverse(string): return string[::-1] def isPalindrome(string): return reverse(string) == string def main(): count = 5 while count > 0: string = input('Enter a string: ') print('The middle character(s) is/are: ' + middle(string)) print('The string reversed is: ' + reverse(string)) print('The string contains ' + str(countVowels(string)) + ' vowels.') if isPalindrome(string): print('That is a palindrome.\n') else: print('That is not palindrome.\n') count -= 1 <|reserved_special_token_0|> <|reserved_special_token_1|> def middle(string): characters = list(string) length = len(characters) middleNum = round((length + 0.5) / 2) if length % 2 == 0: return characters[middleNum - 1] + characters[middleNum] else: return characters[middleNum - 1] def countVowels(string): count = 0 vowels = ['a', 'e', 'i', 'o', 'u', 'y'] for vowel in vowels: count += string.count(vowel) return count def reverse(string): return string[::-1] def isPalindrome(string): return reverse(string) == string def main(): count = 5 while count > 0: string = input('Enter a string: ') print('The middle character(s) is/are: ' + middle(string)) print('The string reversed is: ' + reverse(string)) print('The string contains ' + str(countVowels(string)) + ' vowels.') if isPalindrome(string): print('That is a palindrome.\n') else: print('That is not palindrome.\n') count -= 1 main() <|reserved_special_token_0|> <|reserved_special_token_1|> # CIS 117 Python Programming - Lab 10 # Bryce DesBrisay def middle(string): characters = list(string) length = len(characters) middleNum = round((length + .5) / 2) if length % 2 == 0: return characters[middleNum - 1] + characters[middleNum] else: return characters[middleNum - 1] def countVowels(string): count = 0 vowels = ['a','e','i','o','u','y'] for vowel in vowels: count += string.count(vowel) return count def reverse(string): return string[::-1] def isPalindrome(string): return reverse(string) == string def main(): count = 5 while count > 0: string = input('Enter a string: ') print('The middle character(s) is/are: ' + middle(string)) print('The string reversed is: ' + reverse(string)) print('The string contains ' + str(countVowels(string)) + ' vowels.') if isPalindrome(string): print('That is a palindrome.\n') else: print('That is not palindrome.\n') count -= 1 main() ''' Enter a string: racecar The middle character(s) is/are: e The string reversed is: racecar The string contains 3 vowels. That is a palindrome. Enter a string: apple The middle character(s) is/are: p The string reversed is: elppa The string contains 2 vowels. That is not palindrome. Enter a string: civic The middle character(s) is/are: v The string reversed is: civic The string contains 2 vowels. That is a palindrome. Enter a string: bottle The middle character(s) is/are: tt The string reversed is: elttob The string contains 2 vowels. That is not palindrome. Enter a string: noon The middle character(s) is/are: oo The string reversed is: noon The string contains 2 vowels. That is a palindrome. '''
flexible
{ "blob_id": "d60690892eddda656c11470aacd1fdc9d07a721a", "index": 3563, "step-1": "<mask token>\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\n<mask token>\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\n<mask token>\n", "step-2": "def middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + 0.5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\n<mask token>\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\n<mask token>\n", "step-3": "def middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + 0.5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\ndef reverse(string):\n return string[::-1]\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\n<mask token>\n", "step-4": "def middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + 0.5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\n\ndef countVowels(string):\n count = 0\n vowels = ['a', 'e', 'i', 'o', 'u', 'y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\n\ndef reverse(string):\n return string[::-1]\n\n\ndef isPalindrome(string):\n return reverse(string) == string\n\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\n\nmain()\n<mask token>\n", "step-5": "# CIS 117 Python Programming - Lab 10\n# Bryce DesBrisay\n\ndef middle(string):\n characters = list(string)\n length = len(characters)\n middleNum = round((length + .5) / 2)\n if length % 2 == 0:\n return characters[middleNum - 1] + characters[middleNum]\n else:\n return characters[middleNum - 1]\n\ndef countVowels(string):\n count = 0\n vowels = ['a','e','i','o','u','y']\n for vowel in vowels:\n count += string.count(vowel)\n return count\n\ndef reverse(string):\n return string[::-1]\n\ndef isPalindrome(string):\n return reverse(string) == string\n\ndef main():\n count = 5\n while count > 0:\n string = input('Enter a string: ')\n print('The middle character(s) is/are: ' + middle(string))\n print('The string reversed is: ' + reverse(string))\n print('The string contains ' + str(countVowels(string)) + ' vowels.')\n if isPalindrome(string):\n print('That is a palindrome.\\n')\n else:\n print('That is not palindrome.\\n')\n count -= 1\n\nmain()\n\n'''\nEnter a string: racecar\nThe middle character(s) is/are: e\nThe string reversed is: racecar\nThe string contains 3 vowels.\nThat is a palindrome.\n\nEnter a string: apple\nThe middle character(s) is/are: p\nThe string reversed is: elppa\nThe string contains 2 vowels.\nThat is not palindrome.\n\nEnter a string: civic\nThe middle character(s) is/are: v\nThe string reversed is: civic\nThe string contains 2 vowels.\nThat is a palindrome.\n\nEnter a string: bottle\nThe middle character(s) is/are: tt\nThe string reversed is: elttob\nThe string contains 2 vowels.\nThat is not palindrome.\n\nEnter a string: noon\nThe middle character(s) is/are: oo\nThe string reversed is: noon\nThe string contains 2 vowels.\nThat is a palindrome.\n'''\n\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../tools')) import files import genetics def main(argv): S = files.read_lines(argv[0]) S_rc = [genetics.dna_complement(s) for s in S] S_u = set(S + S_rc) B_k = [] for s in S_u: B_k.append((s[:-1], s[1:])) print '\n'.join('(%s, %s)' % b for b in sorted(B_k)) if __name__ == "__main__": main(sys.argv[1:])
normal
{ "blob_id": "b616b907eb67fff97d57ee2b0d3ab8e01d154956", "index": 2038, "step-1": "import os\nimport sys\nsys.path.append(os.path.join(os.path.dirname(__file__), '../tools'))\n\nimport files\nimport genetics\n\n\ndef main(argv):\n S = files.read_lines(argv[0])\n S_rc = [genetics.dna_complement(s) for s in S]\n S_u = set(S + S_rc)\n\n B_k = []\n\n for s in S_u:\n B_k.append((s[:-1], s[1:]))\n\n print '\\n'.join('(%s, %s)' % b for b in sorted(B_k))\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
# -*- coding: utf-8 -*- # # File: PatrimonyCertificate.py # # Copyright (c) 2015 by CommunesPlone # Generator: ArchGenXML Version 2.7 # http://plone.org/products/archgenxml # # GNU General Public License (GPL) # __author__ = """Gauthier BASTIEN <gbastien@commune.sambreville.be>, Stephan GEULETTE <stephan.geulette@uvcw.be>, Jean-Michel Abe <jm.abe@la-bruyere.be>""" __docformat__ = 'plaintext' from AccessControl import ClassSecurityInfo from Products.Archetypes.atapi import * from zope.interface import implements from Products.urban import interfaces from Products.urban.content.licence.GenericLicence import GenericLicence from Products.urban.content.Inquiry import Inquiry from Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin from Products.urban import UrbanMessage as _ from Products.urban.config import * ##code-section module-header #fill in your manual code here from Products.urban.utils import setOptionalAttributes from Products.urban.utils import setSchemataForInquiry from Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget optional_fields = ['architects'] ##/code-section module-header schema = Schema(( ReferenceField( name='architects', widget=ReferenceBrowserWidget( allow_search=True, only_for_review_states='enabled', allow_browse=True, force_close_on_insert=True, startup_directory='urban/architects', restrict_browsing_to_startup_directory=True, wild_card_search=True, show_index_selector=True, label=_('urban_label_architects', default='Architect(s)'), popup_name='contact_reference_popup', ), required=False, schemata='urban_description', multiValued=True, relationship="miscdemandarchitects", allowed_types='Architect', ), ), ) ##code-section after-local-schema #fill in your manual code here setOptionalAttributes(schema, optional_fields) ##/code-section after-local-schema PatrimonyCertificate_schema = BaseFolderSchema.copy() + \ getattr(GenericLicence, 'schema', Schema(())).copy() + \ getattr(Inquiry, 'schema', Schema(())).copy() + \ schema.copy() ##code-section after-schema #fill in your manual code here #put the the fields coming from Inquiry in a specific schemata setSchemataForInquiry(PatrimonyCertificate_schema) ##/code-section after-schema class PatrimonyCertificate(BaseFolder, GenericLicence, Inquiry, BrowserDefaultMixin): """ """ security = ClassSecurityInfo() implements(interfaces.IPatrimonyCertificate) meta_type = 'PatrimonyCertificate' _at_rename_after_creation = True schema = PatrimonyCertificate_schema ##code-section class-header #fill in your manual code here schemata_order = ['urban_description', 'urban_road', 'urban_location'] ##/code-section class-header # Methods # Manually created methods security.declarePublic('getRepresentatives') def getRepresentatives(self): """ """ return self.getArchitects() def getLastDeposit(self): return self.getLastEvent(interfaces.IDepositEvent) def getLastCollegeReport(self): return self.getLastEvent(interfaces.ICollegeReportEvent) def getLastTheLicence(self): return self.getLastEvent(interfaces.ITheLicenceEvent) registerType(PatrimonyCertificate, PROJECTNAME) # end of class PatrimonyCertificate ##code-section module-footer #fill in your manual code here def finalizeSchema(schema, folderish=False, moveDiscussion=True): """ Finalizes the type schema to alter some fields """ schema.moveField('description', after='architects') return schema finalizeSchema(PatrimonyCertificate_schema) ##/code-section module-footer
normal
{ "blob_id": "6c0b2fa8166bb21a514dc188858e1de285ad9b0a", "index": 166, "step-1": "<mask token>\n\n\nclass PatrimonyCertificate(BaseFolder, GenericLicence, Inquiry,\n BrowserDefaultMixin):\n <mask token>\n security = ClassSecurityInfo()\n implements(interfaces.IPatrimonyCertificate)\n meta_type = 'PatrimonyCertificate'\n _at_rename_after_creation = True\n schema = PatrimonyCertificate_schema\n schemata_order = ['urban_description', 'urban_road', 'urban_location']\n security.declarePublic('getRepresentatives')\n\n def getRepresentatives(self):\n \"\"\"\n \"\"\"\n return self.getArchitects()\n\n def getLastDeposit(self):\n return self.getLastEvent(interfaces.IDepositEvent)\n\n def getLastCollegeReport(self):\n return self.getLastEvent(interfaces.ICollegeReportEvent)\n\n def getLastTheLicence(self):\n return self.getLastEvent(interfaces.ITheLicenceEvent)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass PatrimonyCertificate(BaseFolder, GenericLicence, Inquiry,\n BrowserDefaultMixin):\n \"\"\"\n \"\"\"\n security = ClassSecurityInfo()\n implements(interfaces.IPatrimonyCertificate)\n meta_type = 'PatrimonyCertificate'\n _at_rename_after_creation = True\n schema = PatrimonyCertificate_schema\n schemata_order = ['urban_description', 'urban_road', 'urban_location']\n security.declarePublic('getRepresentatives')\n\n def getRepresentatives(self):\n \"\"\"\n \"\"\"\n return self.getArchitects()\n\n def getLastDeposit(self):\n return self.getLastEvent(interfaces.IDepositEvent)\n\n def getLastCollegeReport(self):\n return self.getLastEvent(interfaces.ICollegeReportEvent)\n\n def getLastTheLicence(self):\n return self.getLastEvent(interfaces.ITheLicenceEvent)\n\n\n<mask token>\n\n\ndef finalizeSchema(schema, folderish=False, moveDiscussion=True):\n \"\"\"\n Finalizes the type schema to alter some fields\n \"\"\"\n schema.moveField('description', after='architects')\n return schema\n\n\n<mask token>\n", "step-3": "<mask token>\nsetOptionalAttributes(schema, optional_fields)\n<mask token>\nsetSchemataForInquiry(PatrimonyCertificate_schema)\n\n\nclass PatrimonyCertificate(BaseFolder, GenericLicence, Inquiry,\n BrowserDefaultMixin):\n \"\"\"\n \"\"\"\n security = ClassSecurityInfo()\n implements(interfaces.IPatrimonyCertificate)\n meta_type = 'PatrimonyCertificate'\n _at_rename_after_creation = True\n schema = PatrimonyCertificate_schema\n schemata_order = ['urban_description', 'urban_road', 'urban_location']\n security.declarePublic('getRepresentatives')\n\n def getRepresentatives(self):\n \"\"\"\n \"\"\"\n return self.getArchitects()\n\n def getLastDeposit(self):\n return self.getLastEvent(interfaces.IDepositEvent)\n\n def getLastCollegeReport(self):\n return self.getLastEvent(interfaces.ICollegeReportEvent)\n\n def getLastTheLicence(self):\n return self.getLastEvent(interfaces.ITheLicenceEvent)\n\n\nregisterType(PatrimonyCertificate, PROJECTNAME)\n\n\ndef finalizeSchema(schema, folderish=False, moveDiscussion=True):\n \"\"\"\n Finalizes the type schema to alter some fields\n \"\"\"\n schema.moveField('description', after='architects')\n return schema\n\n\nfinalizeSchema(PatrimonyCertificate_schema)\n", "step-4": "__author__ = \"\"\"Gauthier BASTIEN <gbastien@commune.sambreville.be>, Stephan GEULETTE\n<stephan.geulette@uvcw.be>, Jean-Michel Abe <jm.abe@la-bruyere.be>\"\"\"\n__docformat__ = 'plaintext'\n<mask token>\noptional_fields = ['architects']\nschema = Schema((ReferenceField(name='architects', widget=\n ReferenceBrowserWidget(allow_search=True, only_for_review_states=\n 'enabled', allow_browse=True, force_close_on_insert=True,\n startup_directory='urban/architects',\n restrict_browsing_to_startup_directory=True, wild_card_search=True,\n show_index_selector=True, label=_('urban_label_architects', default=\n 'Architect(s)'), popup_name='contact_reference_popup'), required=False,\n schemata='urban_description', multiValued=True, relationship=\n 'miscdemandarchitects', allowed_types='Architect'),))\nsetOptionalAttributes(schema, optional_fields)\nPatrimonyCertificate_schema = BaseFolderSchema.copy() + getattr(GenericLicence,\n 'schema', Schema(())).copy() + getattr(Inquiry, 'schema', Schema(())).copy(\n ) + schema.copy()\nsetSchemataForInquiry(PatrimonyCertificate_schema)\n\n\nclass PatrimonyCertificate(BaseFolder, GenericLicence, Inquiry,\n BrowserDefaultMixin):\n \"\"\"\n \"\"\"\n security = ClassSecurityInfo()\n implements(interfaces.IPatrimonyCertificate)\n meta_type = 'PatrimonyCertificate'\n _at_rename_after_creation = True\n schema = PatrimonyCertificate_schema\n schemata_order = ['urban_description', 'urban_road', 'urban_location']\n security.declarePublic('getRepresentatives')\n\n def getRepresentatives(self):\n \"\"\"\n \"\"\"\n return self.getArchitects()\n\n def getLastDeposit(self):\n return self.getLastEvent(interfaces.IDepositEvent)\n\n def getLastCollegeReport(self):\n return self.getLastEvent(interfaces.ICollegeReportEvent)\n\n def getLastTheLicence(self):\n return self.getLastEvent(interfaces.ITheLicenceEvent)\n\n\nregisterType(PatrimonyCertificate, PROJECTNAME)\n\n\ndef finalizeSchema(schema, folderish=False, moveDiscussion=True):\n \"\"\"\n Finalizes the type schema to alter some fields\n \"\"\"\n schema.moveField('description', after='architects')\n return schema\n\n\nfinalizeSchema(PatrimonyCertificate_schema)\n", "step-5": "# -*- coding: utf-8 -*-\n#\n# File: PatrimonyCertificate.py\n#\n# Copyright (c) 2015 by CommunesPlone\n# Generator: ArchGenXML Version 2.7\n# http://plone.org/products/archgenxml\n#\n# GNU General Public License (GPL)\n#\n\n__author__ = \"\"\"Gauthier BASTIEN <gbastien@commune.sambreville.be>, Stephan GEULETTE\n<stephan.geulette@uvcw.be>, Jean-Michel Abe <jm.abe@la-bruyere.be>\"\"\"\n__docformat__ = 'plaintext'\n\nfrom AccessControl import ClassSecurityInfo\nfrom Products.Archetypes.atapi import *\nfrom zope.interface import implements\nfrom Products.urban import interfaces\nfrom Products.urban.content.licence.GenericLicence import GenericLicence\nfrom Products.urban.content.Inquiry import Inquiry\nfrom Products.CMFDynamicViewFTI.browserdefault import BrowserDefaultMixin\n\nfrom Products.urban import UrbanMessage as _\nfrom Products.urban.config import *\n\n##code-section module-header #fill in your manual code here\nfrom Products.urban.utils import setOptionalAttributes\nfrom Products.urban.utils import setSchemataForInquiry\nfrom Products.ATReferenceBrowserWidget.ATReferenceBrowserWidget import ReferenceBrowserWidget\noptional_fields = ['architects']\n##/code-section module-header\n\nschema = Schema((\n\n ReferenceField(\n name='architects',\n widget=ReferenceBrowserWidget(\n allow_search=True,\n only_for_review_states='enabled',\n allow_browse=True,\n force_close_on_insert=True,\n startup_directory='urban/architects',\n restrict_browsing_to_startup_directory=True,\n wild_card_search=True,\n show_index_selector=True,\n label=_('urban_label_architects', default='Architect(s)'),\n popup_name='contact_reference_popup',\n ),\n required=False,\n schemata='urban_description',\n multiValued=True,\n relationship=\"miscdemandarchitects\",\n allowed_types='Architect',\n ),\n\n),\n)\n\n##code-section after-local-schema #fill in your manual code here\nsetOptionalAttributes(schema, optional_fields)\n##/code-section after-local-schema\n\nPatrimonyCertificate_schema = BaseFolderSchema.copy() + \\\n getattr(GenericLicence, 'schema', Schema(())).copy() + \\\n getattr(Inquiry, 'schema', Schema(())).copy() + \\\n schema.copy()\n\n##code-section after-schema #fill in your manual code here\n#put the the fields coming from Inquiry in a specific schemata\nsetSchemataForInquiry(PatrimonyCertificate_schema)\n##/code-section after-schema\n\nclass PatrimonyCertificate(BaseFolder, GenericLicence, Inquiry, BrowserDefaultMixin):\n \"\"\"\n \"\"\"\n security = ClassSecurityInfo()\n implements(interfaces.IPatrimonyCertificate)\n\n meta_type = 'PatrimonyCertificate'\n _at_rename_after_creation = True\n\n schema = PatrimonyCertificate_schema\n\n ##code-section class-header #fill in your manual code here\n schemata_order = ['urban_description', 'urban_road', 'urban_location']\n ##/code-section class-header\n\n # Methods\n\n # Manually created methods\n\n security.declarePublic('getRepresentatives')\n def getRepresentatives(self):\n \"\"\"\n \"\"\"\n return self.getArchitects()\n\n def getLastDeposit(self):\n return self.getLastEvent(interfaces.IDepositEvent)\n\n def getLastCollegeReport(self):\n return self.getLastEvent(interfaces.ICollegeReportEvent)\n\n def getLastTheLicence(self):\n return self.getLastEvent(interfaces.ITheLicenceEvent)\n\n\n\nregisterType(PatrimonyCertificate, PROJECTNAME)\n# end of class PatrimonyCertificate\n\n##code-section module-footer #fill in your manual code here\ndef finalizeSchema(schema, folderish=False, moveDiscussion=True):\n \"\"\"\n Finalizes the type schema to alter some fields\n \"\"\"\n schema.moveField('description', after='architects')\n return schema\n\nfinalizeSchema(PatrimonyCertificate_schema)\n##/code-section module-footer\n\n", "step-ids": [ 6, 8, 9, 10, 12 ] }
[ 6, 8, 9, 10, 12 ]
#!/usr/bin/python # -*- coding: utf-8 -*- import base64 import json import os import re import subprocess import time import traceback import zipfile from datetime import datetime import requests from flask import request, current_app from library.oss import oss_upload_monkey_package_picture from public_config import TCLOUD_FILE_TEMP_PATH class ToolBusiness(object): @classmethod def get_tool_ip(cls): ip = request.args.get('ip') url = 'http://api.map.baidu.com/location/ip' params = {"ip": ip, "ak": 'kqCYLKt8Uz9VnvHBXA7uOI51FIrei0OM'} ret = requests.get(url=url, params=params) ret = json.loads(ret.content) if ret and 'status' in ret and ret['status'] == 0 and 'content' in ret and 'address' in ret: return ret['status'], ret['content'], ret['address'], 'ok' return 101, '', '', '获取失败' @classmethod def apk_analysis(cls, apk_download_url, type=1): try: # type 1 : not save , 2: save to db target_path = "/tmp/packages/" if not os.path.exists(target_path): os.mkdir(target_path) date_time_now = datetime.now().strftime('%Y%m%d-%H.%M.%S') target_name = '{}.apk'.format(date_time_now) download_apk_name = os.path.join(target_path, target_name) current_app.logger.info('开始从 {} 下载到 {}'.format(apk_download_url, download_apk_name)) response = requests.get(url=apk_download_url, verify=False) with open(download_apk_name, 'wb') as f: f.write(response.content) time.sleep(0.5) # 下载失败 if not os.path.exists(download_apk_name): current_app.logger.error('{} 下载失败!'.format(apk_download_url)) return 102, "下载失败" current_app.logger.info('下载成功,保存地址 {}'.format(download_apk_name)) current_app.logger.info('开始分析') package_info_re = re.compile(r"package: name='(.*)' versionCode='(.*)' versionName='(.*?)'.*", re.I) label_icon_re = re.compile(r"application: label='(.+)'.*icon='(.+)'", re.I) launchable_activity_re = re.compile(r"launchable-activity: name='(.+)'.*label.*", re.I) apk_info = {} cmd = '/usr/local/bin/aapt dump badging {}'.format(download_apk_name) command_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) infos = command_process.stdout.readlines() for info in infos: info = info.decode('utf-8') if info.startswith('package:'): temp = package_info_re.search(info) apk_info['package_name'] = temp.group(1) apk_info['version_code'] = temp.group(2) or 0 apk_info['version_name'] = temp.group(3) elif info.startswith('application:'): temp = label_icon_re.search(info) apk_info['label'] = temp.group(1) apk_info['icon'] = temp.group(2) elif info.startswith('launchable-activity:'): temp = launchable_activity_re.search(info) apk_info['default_activity'] = temp.group(1) try: size = round(os.path.getsize(download_apk_name) / float(1024 * 1024), 2) apk_info['size'] = str(size) zip = zipfile.ZipFile(download_apk_name) icon_binary = zip.read(apk_info['icon']) time_now = datetime.now().strftime('%Y%m%d.%H%M%S') picture = f'monkey-{time_now}.png' dir_path = f'{TCLOUD_FILE_TEMP_PATH}/monkey' if not os.path.exists(TCLOUD_FILE_TEMP_PATH): os.mkdir(TCLOUD_FILE_TEMP_PATH) if not os.path.exists(dir_path): os.mkdir(dir_path) with open(f'{dir_path}/{picture}', 'wb') as f: f.write(icon_binary) apk_info['icon'] = oss_upload_monkey_package_picture(dir_path, picture) except Exception as e: current_app.logger.warning(e) current_app.logger.warning(traceback.format_exc()) current_app.logger.info(apk_info) if type == 1: pass elif type == 2: pass return apk_info except Exception as e: current_app.logger.error(e) current_app.logger.error(traceback.format_exc()) return {}
normal
{ "blob_id": "bf45349a9fdfcef7392c477e089c5e3916cb4c8e", "index": 8502, "step-1": "<mask token>\n\n\nclass ToolBusiness(object):\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass ToolBusiness(object):\n\n @classmethod\n def get_tool_ip(cls):\n ip = request.args.get('ip')\n url = 'http://api.map.baidu.com/location/ip'\n params = {'ip': ip, 'ak': 'kqCYLKt8Uz9VnvHBXA7uOI51FIrei0OM'}\n ret = requests.get(url=url, params=params)\n ret = json.loads(ret.content)\n if ret and 'status' in ret and ret['status'\n ] == 0 and 'content' in ret and 'address' in ret:\n return ret['status'], ret['content'], ret['address'], 'ok'\n return 101, '', '', '获取失败'\n <mask token>\n", "step-3": "<mask token>\n\n\nclass ToolBusiness(object):\n\n @classmethod\n def get_tool_ip(cls):\n ip = request.args.get('ip')\n url = 'http://api.map.baidu.com/location/ip'\n params = {'ip': ip, 'ak': 'kqCYLKt8Uz9VnvHBXA7uOI51FIrei0OM'}\n ret = requests.get(url=url, params=params)\n ret = json.loads(ret.content)\n if ret and 'status' in ret and ret['status'\n ] == 0 and 'content' in ret and 'address' in ret:\n return ret['status'], ret['content'], ret['address'], 'ok'\n return 101, '', '', '获取失败'\n\n @classmethod\n def apk_analysis(cls, apk_download_url, type=1):\n try:\n target_path = '/tmp/packages/'\n if not os.path.exists(target_path):\n os.mkdir(target_path)\n date_time_now = datetime.now().strftime('%Y%m%d-%H.%M.%S')\n target_name = '{}.apk'.format(date_time_now)\n download_apk_name = os.path.join(target_path, target_name)\n current_app.logger.info('开始从 {} 下载到 {}'.format(apk_download_url,\n download_apk_name))\n response = requests.get(url=apk_download_url, verify=False)\n with open(download_apk_name, 'wb') as f:\n f.write(response.content)\n time.sleep(0.5)\n if not os.path.exists(download_apk_name):\n current_app.logger.error('{} 下载失败!'.format(apk_download_url))\n return 102, '下载失败'\n current_app.logger.info('下载成功,保存地址 {}'.format(download_apk_name))\n current_app.logger.info('开始分析')\n package_info_re = re.compile(\n \"package: name='(.*)' versionCode='(.*)' versionName='(.*?)'.*\"\n , re.I)\n label_icon_re = re.compile(\"application: label='(.+)'.*icon='(.+)'\"\n , re.I)\n launchable_activity_re = re.compile(\n \"launchable-activity: name='(.+)'.*label.*\", re.I)\n apk_info = {}\n cmd = '/usr/local/bin/aapt dump badging {}'.format(\n download_apk_name)\n command_process = subprocess.Popen(cmd, shell=True, stdout=\n subprocess.PIPE, stderr=subprocess.STDOUT)\n infos = command_process.stdout.readlines()\n for info in infos:\n info = info.decode('utf-8')\n if info.startswith('package:'):\n temp = package_info_re.search(info)\n apk_info['package_name'] = temp.group(1)\n apk_info['version_code'] = temp.group(2) or 0\n apk_info['version_name'] = temp.group(3)\n elif info.startswith('application:'):\n temp = label_icon_re.search(info)\n apk_info['label'] = temp.group(1)\n apk_info['icon'] = temp.group(2)\n elif info.startswith('launchable-activity:'):\n temp = launchable_activity_re.search(info)\n apk_info['default_activity'] = temp.group(1)\n try:\n size = round(os.path.getsize(download_apk_name) / float(\n 1024 * 1024), 2)\n apk_info['size'] = str(size)\n zip = zipfile.ZipFile(download_apk_name)\n icon_binary = zip.read(apk_info['icon'])\n time_now = datetime.now().strftime('%Y%m%d.%H%M%S')\n picture = f'monkey-{time_now}.png'\n dir_path = f'{TCLOUD_FILE_TEMP_PATH}/monkey'\n if not os.path.exists(TCLOUD_FILE_TEMP_PATH):\n os.mkdir(TCLOUD_FILE_TEMP_PATH)\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n with open(f'{dir_path}/{picture}', 'wb') as f:\n f.write(icon_binary)\n apk_info['icon'] = oss_upload_monkey_package_picture(dir_path,\n picture)\n except Exception as e:\n current_app.logger.warning(e)\n current_app.logger.warning(traceback.format_exc())\n current_app.logger.info(apk_info)\n if type == 1:\n pass\n elif type == 2:\n pass\n return apk_info\n except Exception as e:\n current_app.logger.error(e)\n current_app.logger.error(traceback.format_exc())\n return {}\n", "step-4": "import base64\nimport json\nimport os\nimport re\nimport subprocess\nimport time\nimport traceback\nimport zipfile\nfrom datetime import datetime\nimport requests\nfrom flask import request, current_app\nfrom library.oss import oss_upload_monkey_package_picture\nfrom public_config import TCLOUD_FILE_TEMP_PATH\n\n\nclass ToolBusiness(object):\n\n @classmethod\n def get_tool_ip(cls):\n ip = request.args.get('ip')\n url = 'http://api.map.baidu.com/location/ip'\n params = {'ip': ip, 'ak': 'kqCYLKt8Uz9VnvHBXA7uOI51FIrei0OM'}\n ret = requests.get(url=url, params=params)\n ret = json.loads(ret.content)\n if ret and 'status' in ret and ret['status'\n ] == 0 and 'content' in ret and 'address' in ret:\n return ret['status'], ret['content'], ret['address'], 'ok'\n return 101, '', '', '获取失败'\n\n @classmethod\n def apk_analysis(cls, apk_download_url, type=1):\n try:\n target_path = '/tmp/packages/'\n if not os.path.exists(target_path):\n os.mkdir(target_path)\n date_time_now = datetime.now().strftime('%Y%m%d-%H.%M.%S')\n target_name = '{}.apk'.format(date_time_now)\n download_apk_name = os.path.join(target_path, target_name)\n current_app.logger.info('开始从 {} 下载到 {}'.format(apk_download_url,\n download_apk_name))\n response = requests.get(url=apk_download_url, verify=False)\n with open(download_apk_name, 'wb') as f:\n f.write(response.content)\n time.sleep(0.5)\n if not os.path.exists(download_apk_name):\n current_app.logger.error('{} 下载失败!'.format(apk_download_url))\n return 102, '下载失败'\n current_app.logger.info('下载成功,保存地址 {}'.format(download_apk_name))\n current_app.logger.info('开始分析')\n package_info_re = re.compile(\n \"package: name='(.*)' versionCode='(.*)' versionName='(.*?)'.*\"\n , re.I)\n label_icon_re = re.compile(\"application: label='(.+)'.*icon='(.+)'\"\n , re.I)\n launchable_activity_re = re.compile(\n \"launchable-activity: name='(.+)'.*label.*\", re.I)\n apk_info = {}\n cmd = '/usr/local/bin/aapt dump badging {}'.format(\n download_apk_name)\n command_process = subprocess.Popen(cmd, shell=True, stdout=\n subprocess.PIPE, stderr=subprocess.STDOUT)\n infos = command_process.stdout.readlines()\n for info in infos:\n info = info.decode('utf-8')\n if info.startswith('package:'):\n temp = package_info_re.search(info)\n apk_info['package_name'] = temp.group(1)\n apk_info['version_code'] = temp.group(2) or 0\n apk_info['version_name'] = temp.group(3)\n elif info.startswith('application:'):\n temp = label_icon_re.search(info)\n apk_info['label'] = temp.group(1)\n apk_info['icon'] = temp.group(2)\n elif info.startswith('launchable-activity:'):\n temp = launchable_activity_re.search(info)\n apk_info['default_activity'] = temp.group(1)\n try:\n size = round(os.path.getsize(download_apk_name) / float(\n 1024 * 1024), 2)\n apk_info['size'] = str(size)\n zip = zipfile.ZipFile(download_apk_name)\n icon_binary = zip.read(apk_info['icon'])\n time_now = datetime.now().strftime('%Y%m%d.%H%M%S')\n picture = f'monkey-{time_now}.png'\n dir_path = f'{TCLOUD_FILE_TEMP_PATH}/monkey'\n if not os.path.exists(TCLOUD_FILE_TEMP_PATH):\n os.mkdir(TCLOUD_FILE_TEMP_PATH)\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n with open(f'{dir_path}/{picture}', 'wb') as f:\n f.write(icon_binary)\n apk_info['icon'] = oss_upload_monkey_package_picture(dir_path,\n picture)\n except Exception as e:\n current_app.logger.warning(e)\n current_app.logger.warning(traceback.format_exc())\n current_app.logger.info(apk_info)\n if type == 1:\n pass\n elif type == 2:\n pass\n return apk_info\n except Exception as e:\n current_app.logger.error(e)\n current_app.logger.error(traceback.format_exc())\n return {}\n", "step-5": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport base64\nimport json\nimport os\nimport re\nimport subprocess\nimport time\nimport traceback\nimport zipfile\nfrom datetime import datetime\n\nimport requests\nfrom flask import request, current_app\n\nfrom library.oss import oss_upload_monkey_package_picture\nfrom public_config import TCLOUD_FILE_TEMP_PATH\n\n\nclass ToolBusiness(object):\n\n @classmethod\n def get_tool_ip(cls):\n ip = request.args.get('ip')\n\n url = 'http://api.map.baidu.com/location/ip'\n params = {\"ip\": ip, \"ak\": 'kqCYLKt8Uz9VnvHBXA7uOI51FIrei0OM'}\n ret = requests.get(url=url, params=params)\n ret = json.loads(ret.content)\n\n if ret and 'status' in ret and ret['status'] == 0 and 'content' in ret and 'address' in ret:\n return ret['status'], ret['content'], ret['address'], 'ok'\n\n return 101, '', '', '获取失败'\n\n @classmethod\n def apk_analysis(cls, apk_download_url, type=1):\n try:\n # type 1 : not save , 2: save to db\n target_path = \"/tmp/packages/\"\n if not os.path.exists(target_path):\n os.mkdir(target_path)\n\n date_time_now = datetime.now().strftime('%Y%m%d-%H.%M.%S')\n target_name = '{}.apk'.format(date_time_now)\n\n download_apk_name = os.path.join(target_path, target_name)\n\n current_app.logger.info('开始从 {} 下载到 {}'.format(apk_download_url, download_apk_name))\n\n response = requests.get(url=apk_download_url, verify=False)\n\n with open(download_apk_name, 'wb') as f:\n f.write(response.content)\n\n time.sleep(0.5)\n # 下载失败\n if not os.path.exists(download_apk_name):\n current_app.logger.error('{} 下载失败!'.format(apk_download_url))\n return 102, \"下载失败\"\n\n current_app.logger.info('下载成功,保存地址 {}'.format(download_apk_name))\n current_app.logger.info('开始分析')\n\n package_info_re = re.compile(r\"package: name='(.*)' versionCode='(.*)' versionName='(.*?)'.*\", re.I)\n label_icon_re = re.compile(r\"application: label='(.+)'.*icon='(.+)'\", re.I)\n launchable_activity_re = re.compile(r\"launchable-activity: name='(.+)'.*label.*\", re.I)\n\n apk_info = {}\n\n cmd = '/usr/local/bin/aapt dump badging {}'.format(download_apk_name)\n\n command_process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n\n infos = command_process.stdout.readlines()\n\n for info in infos:\n info = info.decode('utf-8')\n if info.startswith('package:'):\n temp = package_info_re.search(info)\n apk_info['package_name'] = temp.group(1)\n apk_info['version_code'] = temp.group(2) or 0\n apk_info['version_name'] = temp.group(3)\n elif info.startswith('application:'):\n temp = label_icon_re.search(info)\n apk_info['label'] = temp.group(1)\n apk_info['icon'] = temp.group(2)\n elif info.startswith('launchable-activity:'):\n temp = launchable_activity_re.search(info)\n apk_info['default_activity'] = temp.group(1)\n\n try:\n size = round(os.path.getsize(download_apk_name) / float(1024 * 1024), 2)\n apk_info['size'] = str(size)\n zip = zipfile.ZipFile(download_apk_name)\n icon_binary = zip.read(apk_info['icon'])\n time_now = datetime.now().strftime('%Y%m%d.%H%M%S')\n picture = f'monkey-{time_now}.png'\n dir_path = f'{TCLOUD_FILE_TEMP_PATH}/monkey'\n\n if not os.path.exists(TCLOUD_FILE_TEMP_PATH):\n os.mkdir(TCLOUD_FILE_TEMP_PATH)\n\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n with open(f'{dir_path}/{picture}', 'wb') as f:\n f.write(icon_binary)\n\n apk_info['icon'] = oss_upload_monkey_package_picture(dir_path, picture)\n except Exception as e:\n current_app.logger.warning(e)\n current_app.logger.warning(traceback.format_exc())\n\n current_app.logger.info(apk_info)\n\n if type == 1:\n pass\n elif type == 2:\n pass\n\n return apk_info\n except Exception as e:\n current_app.logger.error(e)\n current_app.logger.error(traceback.format_exc())\n return {}\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
import inspect import re import openquake.hazardlib.source as oqsrc # List of valid attributes for an area source AREAS_ATTRIBUTES = set(['source_id', 'name', 'tectonic_region_type', 'mfd', 'rupture_mesh_spacing', 'magnitude_scaling_relationship', 'rupture_aspect_ratio', 'temporal_occurrence_model', 'upper_seismogenic_depth', 'lower_seismogenic_depth', 'nodal_plane_distribution', 'hypocenter_distribution', 'polygon', 'area_discretization']) AREAS_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'source_type']) # List of valid attributes for a simple source SIMPLE_FAULT_ATTRIBUTES = set(['source_id', 'name', 'tectonic_region_type', 'mfd', 'rupture_mesh_spacing', 'magnitude_scaling_relationship', 'rupture_aspect_ratio', 'temporal_occurrence_model', 'upper_seismogenic_depth', 'lower_seismogenic_depth', 'fault_trace', 'dip', 'rake', 'hypo_list', 'sliprate']) SIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'dip', 'rake', 'hypo_list', 'slip_list']) SIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'source_type']) # This adds support for shapefiles created by the OpenQuake-engine SIMPLE_FAULT_ATTRIBUTES |= set(['']) # Create the set of valid source types SOURCE_TYPES = set() for name, obj in inspect.getmembers(oqsrc): if inspect.isclass(obj): if not re.search('Rupture', name): SOURCE_TYPES.add(name) class OQtSource(object): """ A container for information necessary to build and/or characterise an earthquake source :parameter str source_id: The ID of the source :parameter str source_type: Source type i.e. Object name amongst the ones admitted in the OpenQuake Hazardlib. """ def __init__(self, *args, **kwargs): # Checks if len(args): self.source_id = args[0] if len(args) > 1: self.source_type = args[1] if len(kwargs): self.__dict__.update(kwargs) # Check mandatory attributes: ID if 'source_id' not in self.__dict__: raise ValueError('Source must have an ID') elif not isinstance(self.source_id, str): raise ValueError('ID must be a string') # Check mandatory fields: SOURCE TYPE if 'source_type' not in self.__dict__: raise ValueError('Source must have a type') if self.source_type not in SOURCE_TYPES: raise ValueError('Unrecognized source type: %s' % self.source_type) if 'source_type' in self.__dict__: attribute_set = AREAS_ATTRIBUTES elif 'source_type' in self.__dict__: attribute_set = SIMPLE_FAULT_ATTRIBUTES else: raise ValueError('Unsupported source type') # Check attributes for key in self.__dict__: if key not in attribute_set: print ('Attribute set', attribute_set) msg = 'Parameter %s not compatible with this source' % (key) raise ValueError(msg) def get_info(self): for key in self.__dict__: print ('%30s:' % (key), getattr(self, key))
normal
{ "blob_id": "8adf8cfc72d5af955bf7509d3573a9bcc7c0845e", "index": 7537, "step-1": "<mask token>\n\n\nclass OQtSource(object):\n <mask token>\n\n def __init__(self, *args, **kwargs):\n if len(args):\n self.source_id = args[0]\n if len(args) > 1:\n self.source_type = args[1]\n if len(kwargs):\n self.__dict__.update(kwargs)\n if 'source_id' not in self.__dict__:\n raise ValueError('Source must have an ID')\n elif not isinstance(self.source_id, str):\n raise ValueError('ID must be a string')\n if 'source_type' not in self.__dict__:\n raise ValueError('Source must have a type')\n if self.source_type not in SOURCE_TYPES:\n raise ValueError('Unrecognized source type: %s' % self.source_type)\n if 'source_type' in self.__dict__:\n attribute_set = AREAS_ATTRIBUTES\n elif 'source_type' in self.__dict__:\n attribute_set = SIMPLE_FAULT_ATTRIBUTES\n else:\n raise ValueError('Unsupported source type')\n for key in self.__dict__:\n if key not in attribute_set:\n print('Attribute set', attribute_set)\n msg = 'Parameter %s not compatible with this source' % key\n raise ValueError(msg)\n <mask token>\n", "step-2": "<mask token>\n\n\nclass OQtSource(object):\n \"\"\"\n A container for information necessary to build and/or characterise an\n earthquake source\n\n :parameter str source_id:\n The ID of the source\n :parameter str source_type:\n Source type i.e. Object name amongst the ones admitted in the\n OpenQuake Hazardlib.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if len(args):\n self.source_id = args[0]\n if len(args) > 1:\n self.source_type = args[1]\n if len(kwargs):\n self.__dict__.update(kwargs)\n if 'source_id' not in self.__dict__:\n raise ValueError('Source must have an ID')\n elif not isinstance(self.source_id, str):\n raise ValueError('ID must be a string')\n if 'source_type' not in self.__dict__:\n raise ValueError('Source must have a type')\n if self.source_type not in SOURCE_TYPES:\n raise ValueError('Unrecognized source type: %s' % self.source_type)\n if 'source_type' in self.__dict__:\n attribute_set = AREAS_ATTRIBUTES\n elif 'source_type' in self.__dict__:\n attribute_set = SIMPLE_FAULT_ATTRIBUTES\n else:\n raise ValueError('Unsupported source type')\n for key in self.__dict__:\n if key not in attribute_set:\n print('Attribute set', attribute_set)\n msg = 'Parameter %s not compatible with this source' % key\n raise ValueError(msg)\n\n def get_info(self):\n for key in self.__dict__:\n print('%30s:' % key, getattr(self, key))\n", "step-3": "<mask token>\nAREAS_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'source_type'])\n<mask token>\nSIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'dip', 'rake',\n 'hypo_list', 'slip_list'])\nSIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'source_type'])\nSIMPLE_FAULT_ATTRIBUTES |= set([''])\n<mask token>\nfor name, obj in inspect.getmembers(oqsrc):\n if inspect.isclass(obj):\n if not re.search('Rupture', name):\n SOURCE_TYPES.add(name)\n\n\nclass OQtSource(object):\n \"\"\"\n A container for information necessary to build and/or characterise an\n earthquake source\n\n :parameter str source_id:\n The ID of the source\n :parameter str source_type:\n Source type i.e. Object name amongst the ones admitted in the\n OpenQuake Hazardlib.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if len(args):\n self.source_id = args[0]\n if len(args) > 1:\n self.source_type = args[1]\n if len(kwargs):\n self.__dict__.update(kwargs)\n if 'source_id' not in self.__dict__:\n raise ValueError('Source must have an ID')\n elif not isinstance(self.source_id, str):\n raise ValueError('ID must be a string')\n if 'source_type' not in self.__dict__:\n raise ValueError('Source must have a type')\n if self.source_type not in SOURCE_TYPES:\n raise ValueError('Unrecognized source type: %s' % self.source_type)\n if 'source_type' in self.__dict__:\n attribute_set = AREAS_ATTRIBUTES\n elif 'source_type' in self.__dict__:\n attribute_set = SIMPLE_FAULT_ATTRIBUTES\n else:\n raise ValueError('Unsupported source type')\n for key in self.__dict__:\n if key not in attribute_set:\n print('Attribute set', attribute_set)\n msg = 'Parameter %s not compatible with this source' % key\n raise ValueError(msg)\n\n def get_info(self):\n for key in self.__dict__:\n print('%30s:' % key, getattr(self, key))\n", "step-4": "import inspect\nimport re\nimport openquake.hazardlib.source as oqsrc\nAREAS_ATTRIBUTES = set(['source_id', 'name', 'tectonic_region_type', 'mfd',\n 'rupture_mesh_spacing', 'magnitude_scaling_relationship',\n 'rupture_aspect_ratio', 'temporal_occurrence_model',\n 'upper_seismogenic_depth', 'lower_seismogenic_depth',\n 'nodal_plane_distribution', 'hypocenter_distribution', 'polygon',\n 'area_discretization'])\nAREAS_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'source_type'])\nSIMPLE_FAULT_ATTRIBUTES = set(['source_id', 'name', 'tectonic_region_type',\n 'mfd', 'rupture_mesh_spacing', 'magnitude_scaling_relationship',\n 'rupture_aspect_ratio', 'temporal_occurrence_model',\n 'upper_seismogenic_depth', 'lower_seismogenic_depth', 'fault_trace',\n 'dip', 'rake', 'hypo_list', 'sliprate'])\nSIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'dip', 'rake',\n 'hypo_list', 'slip_list'])\nSIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval', 'gr_bval', 'source_type'])\nSIMPLE_FAULT_ATTRIBUTES |= set([''])\nSOURCE_TYPES = set()\nfor name, obj in inspect.getmembers(oqsrc):\n if inspect.isclass(obj):\n if not re.search('Rupture', name):\n SOURCE_TYPES.add(name)\n\n\nclass OQtSource(object):\n \"\"\"\n A container for information necessary to build and/or characterise an\n earthquake source\n\n :parameter str source_id:\n The ID of the source\n :parameter str source_type:\n Source type i.e. Object name amongst the ones admitted in the\n OpenQuake Hazardlib.\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if len(args):\n self.source_id = args[0]\n if len(args) > 1:\n self.source_type = args[1]\n if len(kwargs):\n self.__dict__.update(kwargs)\n if 'source_id' not in self.__dict__:\n raise ValueError('Source must have an ID')\n elif not isinstance(self.source_id, str):\n raise ValueError('ID must be a string')\n if 'source_type' not in self.__dict__:\n raise ValueError('Source must have a type')\n if self.source_type not in SOURCE_TYPES:\n raise ValueError('Unrecognized source type: %s' % self.source_type)\n if 'source_type' in self.__dict__:\n attribute_set = AREAS_ATTRIBUTES\n elif 'source_type' in self.__dict__:\n attribute_set = SIMPLE_FAULT_ATTRIBUTES\n else:\n raise ValueError('Unsupported source type')\n for key in self.__dict__:\n if key not in attribute_set:\n print('Attribute set', attribute_set)\n msg = 'Parameter %s not compatible with this source' % key\n raise ValueError(msg)\n\n def get_info(self):\n for key in self.__dict__:\n print('%30s:' % key, getattr(self, key))\n", "step-5": "import inspect\nimport re\nimport openquake.hazardlib.source as oqsrc\n\n# List of valid attributes for an area source\nAREAS_ATTRIBUTES = set(['source_id', \n\t\t\t'name', \n\t\t\t'tectonic_region_type', \n\t\t\t'mfd',\n 'rupture_mesh_spacing',\n 'magnitude_scaling_relationship',\n 'rupture_aspect_ratio',\n 'temporal_occurrence_model',\n 'upper_seismogenic_depth',\n 'lower_seismogenic_depth',\n 'nodal_plane_distribution',\n 'hypocenter_distribution',\n 'polygon',\n 'area_discretization'])\n \nAREAS_ATTRIBUTES |= set(['gr_aval', \n\t\t\t 'gr_bval', \n\t\t\t 'source_type'])\n\n# List of valid attributes for a simple source\nSIMPLE_FAULT_ATTRIBUTES = set(['source_id',\n 'name',\n 'tectonic_region_type',\n 'mfd',\n 'rupture_mesh_spacing',\n 'magnitude_scaling_relationship',\n 'rupture_aspect_ratio',\n 'temporal_occurrence_model',\n 'upper_seismogenic_depth',\n 'lower_seismogenic_depth',\n 'fault_trace',\n 'dip', \n 'rake', \n 'hypo_list', \n 'sliprate'])\n \nSIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval', \n 'gr_bval', \n 'dip',\n 'rake',\n 'hypo_list',\n 'slip_list'])\n\nSIMPLE_FAULT_ATTRIBUTES |= set(['gr_aval',\n 'gr_bval',\n 'source_type'])\n\n# This adds support for shapefiles created by the OpenQuake-engine\nSIMPLE_FAULT_ATTRIBUTES |= set([''])\n\n# Create the set of valid source types\nSOURCE_TYPES = set()\nfor name, obj in inspect.getmembers(oqsrc):\n if inspect.isclass(obj):\n if not re.search('Rupture', name):\n SOURCE_TYPES.add(name)\n\nclass OQtSource(object):\n \"\"\"\n A container for information necessary to build and/or characterise an\n earthquake source\n\n :parameter str source_id:\n The ID of the source\n :parameter str source_type:\n Source type i.e. Object name amongst the ones admitted in the\n OpenQuake Hazardlib.\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n # Checks\n if len(args):\n self.source_id = args[0]\n if len(args) > 1:\n self.source_type = args[1]\n if len(kwargs):\n self.__dict__.update(kwargs)\n # Check mandatory attributes: ID\n if 'source_id' not in self.__dict__:\n raise ValueError('Source must have an ID')\n elif not isinstance(self.source_id, str):\n raise ValueError('ID must be a string')\n # Check mandatory fields: SOURCE TYPE\n if 'source_type' not in self.__dict__:\n raise ValueError('Source must have a type')\n if self.source_type not in SOURCE_TYPES:\n raise ValueError('Unrecognized source type: %s' % self.source_type)\n if 'source_type' in self.__dict__:\n attribute_set = AREAS_ATTRIBUTES\n elif 'source_type' in self.__dict__:\n attribute_set = SIMPLE_FAULT_ATTRIBUTES\n else:\n raise ValueError('Unsupported source type')\n # Check attributes\n for key in self.__dict__:\n if key not in attribute_set:\n print ('Attribute set', attribute_set)\n msg = 'Parameter %s not compatible with this source' % (key)\n raise ValueError(msg)\n\n def get_info(self):\n for key in self.__dict__:\n print ('%30s:' % (key), getattr(self, key))\n", "step-ids": [ 2, 4, 5, 7, 8 ] }
[ 2, 4, 5, 7, 8 ]
from collections import Counter, defaultdict from random import randrange from copy import deepcopy import sys def election(votes, message=True, force_forward=False): votes = deepcopy(votes) N = len(votes) for i in range(N): obtained = Counter([v[-1] for v in votes if len(v)]).most_common() M = len(obtained) top = obtained[0] if M == 1: return top[0] accum = [0] for ob in obtained[::-1]: accum.append(accum[-1] + ob[1]) accum = accum[:0:-1] candidates = {top[0]} for m in range(1,M): if accum[m] < obtained[m-1][1]: break else: candidates.add(obtained[m][0]) else: m += 1 if message: print('The {}-th vote: {}'.format(i+1, obtained)) if m == 1: return top[0] elif m >= M: l = M-2 while l >= 0 and obtained[l][1] == obtained[-1][1]: l -= 1 candidates = {obtained[i][0] for i in range(l+1)} fighting = {obtained[i][0] for i in range(l+1,M)} losers = set() for f in fighting: tmp_votes = deepcopy(votes) tmp_candidates = candidates | {f} for n in range(N): while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1] in tmp_candidates: tmp_votes[n].pop() tmp_result = election(tmp_votes, message=False) if tmp_result != f and not (isinstance(tmp_result,list) and f in dict(tmp_result)): losers.add(f) candidates |= fighting candidates -= losers if losers: if message: print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m) if obtained[j][0] in candidates])) else: if message: print(' All the candidates survived.') if force_forward: drop = obtained[randrange(l+1,M)][0] candidates.discard(drop) if message: print(' Drop the candidate \'{}\'.'.format(drop)) elif message: print(' Final winner was not determined.') return obtained elif message: print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m)])) for n in range(N): while len(votes[n]) > 0 and not votes[n][-1] in candidates: votes[n].pop() if __name__ == '__main__': args = sys.argv if len(args) <= 1: K = 0 else: K = int(args[1]) votes = [] while True: try: votes.append(list(input().strip().upper()[::-1])) except EOFError: break if K == 0: winner = election(votes) print('---') if isinstance(winner, list): print('The candidates \'{}\' are still surviving.'.format(winner)) else: print('The candidate \'{}\' is the Final Winner !!!'.format(winner)) else: win_times = defaultdict(int) for _ in range(K): win_times[election(votes, message=False, force_forward=True)] += 1 result = list(win_times.items()) if len(result) == 1: winner = result[0][0] print('The candidate \'{}\' is the Final Winner !!'.format(winner)) else: print('Final winner was not determined.') print('The winner distribution is: {}'.format(dict(win_times)))
normal
{ "blob_id": "05764d1cfd9573616fcd6b125280fddf2e5ce7ad", "index": 3712, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1, M):\n if accum[m] < obtained[m - 1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n if message:\n print('The {}-th vote: {}'.format(i + 1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M - 2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l + 1)}\n fighting = {obtained[i][0] for i in range(l + 1, M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1\n ] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result, list) and\n f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([obtained[j][0\n ] for j in range(m) if obtained[j][0] in candidates]))\n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l + 1, M)][0]\n candidates.discard(drop)\n if message:\n print(\" Drop the candidate '{}'.\".format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([obtained[j][0] for j in\n range(m)]))\n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1, M):\n if accum[m] < obtained[m - 1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n if message:\n print('The {}-th vote: {}'.format(i + 1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M - 2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l + 1)}\n fighting = {obtained[i][0] for i in range(l + 1, M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1\n ] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result, list) and\n f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([obtained[j][0\n ] for j in range(m) if obtained[j][0] in candidates]))\n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l + 1, M)][0]\n candidates.discard(drop)\n if message:\n print(\" Drop the candidate '{}'.\".format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([obtained[j][0] for j in\n range(m)]))\n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) <= 1:\n K = 0\n else:\n K = int(args[1])\n votes = []\n while True:\n try:\n votes.append(list(input().strip().upper()[::-1]))\n except EOFError:\n break\n if K == 0:\n winner = election(votes)\n print('---')\n if isinstance(winner, list):\n print(\"The candidates '{}' are still surviving.\".format(winner))\n else:\n print(\"The candidate '{}' is the Final Winner !!!\".format(winner))\n else:\n win_times = defaultdict(int)\n for _ in range(K):\n win_times[election(votes, message=False, force_forward=True)] += 1\n result = list(win_times.items())\n if len(result) == 1:\n winner = result[0][0]\n print(\"The candidate '{}' is the Final Winner !!\".format(winner))\n else:\n print('Final winner was not determined.')\n print('The winner distribution is: {}'.format(dict(win_times)))\n", "step-4": "from collections import Counter, defaultdict\nfrom random import randrange\nfrom copy import deepcopy\nimport sys\n\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1, M):\n if accum[m] < obtained[m - 1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n if message:\n print('The {}-th vote: {}'.format(i + 1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M - 2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l + 1)}\n fighting = {obtained[i][0] for i in range(l + 1, M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1\n ] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result, list) and\n f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([obtained[j][0\n ] for j in range(m) if obtained[j][0] in candidates]))\n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l + 1, M)][0]\n candidates.discard(drop)\n if message:\n print(\" Drop the candidate '{}'.\".format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([obtained[j][0] for j in\n range(m)]))\n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) <= 1:\n K = 0\n else:\n K = int(args[1])\n votes = []\n while True:\n try:\n votes.append(list(input().strip().upper()[::-1]))\n except EOFError:\n break\n if K == 0:\n winner = election(votes)\n print('---')\n if isinstance(winner, list):\n print(\"The candidates '{}' are still surviving.\".format(winner))\n else:\n print(\"The candidate '{}' is the Final Winner !!!\".format(winner))\n else:\n win_times = defaultdict(int)\n for _ in range(K):\n win_times[election(votes, message=False, force_forward=True)] += 1\n result = list(win_times.items())\n if len(result) == 1:\n winner = result[0][0]\n print(\"The candidate '{}' is the Final Winner !!\".format(winner))\n else:\n print('Final winner was not determined.')\n print('The winner distribution is: {}'.format(dict(win_times)))\n", "step-5": "from collections import Counter, defaultdict\nfrom random import randrange\nfrom copy import deepcopy\nimport sys\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1,M):\n if accum[m] < obtained[m-1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n\n if message:\n print('The {}-th vote: {}'.format(i+1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M-2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l+1)}\n fighting = {obtained[i][0] for i in range(l+1,M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result,list) and f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m) if obtained[j][0] in candidates])) \n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l+1,M)][0]\n candidates.discard(drop)\n if message:\n print(' Drop the candidate \\'{}\\'.'.format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m)]))\n \n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) <= 1:\n K = 0\n else:\n K = int(args[1])\n\n votes = []\n while True:\n try:\n votes.append(list(input().strip().upper()[::-1]))\n except EOFError:\n break\n\n if K == 0:\n winner = election(votes)\n print('---')\n if isinstance(winner, list):\n print('The candidates \\'{}\\' are still surviving.'.format(winner))\n else:\n print('The candidate \\'{}\\' is the Final Winner !!!'.format(winner))\n else:\n win_times = defaultdict(int)\n for _ in range(K):\n win_times[election(votes, message=False, force_forward=True)] += 1\n result = list(win_times.items())\n if len(result) == 1:\n winner = result[0][0]\n print('The candidate \\'{}\\' is the Final Winner !!'.format(winner)) \n else:\n print('Final winner was not determined.')\n print('The winner distribution is: {}'.format(dict(win_times)))\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import flask import flask_sqlalchemy app = flask.Flask(__name__) app.config.from_pyfile('settings.py') db = flask_sqlalchemy.SQLAlchemy(app)
normal
{ "blob_id": "2ed0ae48e8fec2c92effcbb3e495a1a9f4636c27", "index": 6777, "step-1": "<mask token>\n", "step-2": "<mask token>\napp.config.from_pyfile('settings.py')\n<mask token>\n", "step-3": "<mask token>\napp = flask.Flask(__name__)\napp.config.from_pyfile('settings.py')\ndb = flask_sqlalchemy.SQLAlchemy(app)\n", "step-4": "import flask\nimport flask_sqlalchemy\napp = flask.Flask(__name__)\napp.config.from_pyfile('settings.py')\ndb = flask_sqlalchemy.SQLAlchemy(app)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
{ 'variables': { 'node_shared_openssl%': 'true' }, 'targets': [ { 'target_name': 'keypair', 'sources': [ 'secp256k1/keypair.cc' ], 'conditions': [ # For Windows, require either a 32-bit or 64-bit # separately-compiled OpenSSL library. # Currently set up to use with the following OpenSSL distro: # # http://slproweb.com/products/Win32OpenSSL.html [ 'OS=="win"', { 'conditions': [ [ 'target_arch=="x64"', { 'variables': { 'openssl_root%': 'C:/OpenSSL-Win64' }, }, { 'variables': { 'openssl_root%': 'C:/OpenSSL-Win32' } } ] ], 'libraries': [ '-l<(openssl_root)/lib/libeay32.lib', ], 'include_dirs': [ '<(openssl_root)/include', ], }, # Otherwise, if not Windows, link against the exposed OpenSSL # in Node. { "conditions": [ ['node_shared_openssl=="false"', { # so when "node_shared_openssl" is "false", then OpenSSL has been # bundled into the node executable. So we need to include the same # header files that were used when building node. 'include_dirs': [ '<(node_root_dir)/deps/openssl/openssl/include' ], "conditions" : [ ["target_arch=='ia32'", { "include_dirs": [ "<(node_root_dir)/deps/openssl/config/piii" ] }], ["target_arch=='x64'", { "include_dirs": [ "<(node_root_dir)/deps/openssl/config/k8" ] }], ["target_arch=='arm'", { "include_dirs": [ "<(node_root_dir)/deps/openssl/config/arm" ] }] ] }] ]} ]] } ] }
normal
{ "blob_id": "e7b30353fd25beb9d5cdeee688e4ffa6955d4221", "index": 8437, "step-1": "<mask token>\n", "step-2": "{'variables': {'node_shared_openssl%': 'true'}, 'targets': [{'target_name':\n 'keypair', 'sources': ['secp256k1/keypair.cc'], 'conditions': [[\n 'OS==\"win\"', {'conditions': [['target_arch==\"x64\"', {'variables': {\n 'openssl_root%': 'C:/OpenSSL-Win64'}}, {'variables': {'openssl_root%':\n 'C:/OpenSSL-Win32'}}]], 'libraries': [\n '-l<(openssl_root)/lib/libeay32.lib'], 'include_dirs': [\n '<(openssl_root)/include']}, {'conditions': [[\n 'node_shared_openssl==\"false\"', {'include_dirs': [\n '<(node_root_dir)/deps/openssl/openssl/include'], 'conditions': [[\n \"target_arch=='ia32'\", {'include_dirs': [\n '<(node_root_dir)/deps/openssl/config/piii']}], [\"target_arch=='x64'\",\n {'include_dirs': ['<(node_root_dir)/deps/openssl/config/k8']}], [\n \"target_arch=='arm'\", {'include_dirs': [\n '<(node_root_dir)/deps/openssl/config/arm']}]]}]]}]]}]}\n", "step-3": "{\n 'variables': {\n 'node_shared_openssl%': 'true'\n },\n 'targets': [\n {\n 'target_name': 'keypair',\n 'sources': [\n 'secp256k1/keypair.cc'\n ],\n 'conditions': [\n # For Windows, require either a 32-bit or 64-bit\n # separately-compiled OpenSSL library.\n\t# Currently set up to use with the following OpenSSL distro:\n\t#\n\t# http://slproweb.com/products/Win32OpenSSL.html\n [\n\t 'OS==\"win\"', \n\t {\n 'conditions':\n\t [\n [\n\t 'target_arch==\"x64\"',\n\t {\n\t 'variables': {\n 'openssl_root%': 'C:/OpenSSL-Win64'\n },\n }, {\n 'variables': {\n 'openssl_root%': 'C:/OpenSSL-Win32'\n }\n\t\t}\n\t ]\n ],\n 'libraries': [ \n '-l<(openssl_root)/lib/libeay32.lib',\n ],\n 'include_dirs': [\n '<(openssl_root)/include',\n ],\n },\n\n\n # Otherwise, if not Windows, link against the exposed OpenSSL\n\t # in Node.\n {\n \"conditions\": [\n ['node_shared_openssl==\"false\"', {\n # so when \"node_shared_openssl\" is \"false\", then OpenSSL has been\n # bundled into the node executable. So we need to include the same\n # header files that were used when building node.\n 'include_dirs': [\n '<(node_root_dir)/deps/openssl/openssl/include'\n ],\n \"conditions\" : [\n [\"target_arch=='ia32'\", {\n \"include_dirs\": [ \"<(node_root_dir)/deps/openssl/config/piii\" ]\n }],\n [\"target_arch=='x64'\", {\n \"include_dirs\": [ \"<(node_root_dir)/deps/openssl/config/k8\" ]\n }],\n [\"target_arch=='arm'\", {\n \"include_dirs\": [ \"<(node_root_dir)/deps/openssl/config/arm\" ]\n }]\n ]\n }]\n ]}\n ]]\n }\n ]\n}\n\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
#case1 print("My name is Jia-Chi. \nI have an older sister. \nI prefer Coke.\nMy favorite song is \"Amazing Grace\"") #case2 print('''Liang, Jia-Chi 1 Coke Amazing Grace''')
normal
{ "blob_id": "55986f6c2dafe650704660142cf85640e763b26d", "index": 3291, "step-1": "<mask token>\n", "step-2": "print(\n \"\"\"My name is Jia-Chi. \nI have an older sister. \nI prefer Coke.\nMy favorite song is \"Amazing Grace\\\"\"\"\"\n )\nprint(\"\"\"Liang, Jia-Chi\n1\nCoke\nAmazing Grace\"\"\")\n", "step-3": "#case1\nprint(\"My name is Jia-Chi. \\nI have an older sister. \\nI prefer Coke.\\nMy favorite song is \\\"Amazing Grace\\\"\")\n#case2\nprint('''Liang, Jia-Chi\n1\nCoke\nAmazing Grace''')\n\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> def write(output_filename, content): with open(output_filename, 'w') as outfile: outfile.write(content) def main(argv): """ WebPerf Core Carbon Percentiles Usage: * run webperf-core test on all websites you want to use for your percentiles (with json as output file) * run this file against your output file, for example like this: carbon-rating.py -i data\\carbon-references-2022.json -o tests\\energy_efficiency_carbon_percentiles.py Options and arguments: -h/--help : Help information on how to use script -i/--input <file path> : input file path (.json) -o/--output <file path> : output file path (.py) """ output_filename = '' input_filename = '' langCode = 'en' language = False language = gettext.translation('webperf-core', localedir='locales', languages=[langCode]) language.install() _ = language.gettext try: opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output='] ) except getopt.GetoptError: print(main.__doc__) sys.exit(2) if opts.__len__() == 0: print(main.__doc__) sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print(main.__doc__) sys.exit(2) elif opt in ('-i', '--input'): input_filename = arg file_ending = '' file_long_ending = '' if len(input_filename) > 4: file_ending = input_filename[-4:].lower() if len(input_filename) > 7: file_long_ending = input_filename[-7:].lower() if file_long_ending == '.sqlite': from engines.sqlite import read_sites, add_site, delete_site elif file_ending == '.csv': from engines.csv import read_sites, add_site, delete_site elif file_ending == '.xml': from engines.sitemap import read_sites, add_site, delete_site else: from engines.json import read_tests, read_sites, add_site, delete_site pass elif opt in ('-o', '--output'): output_filename = arg pass tests = read_tests(input_filename, 0, -1) generated_date = False co2s = list() for test in tests: if not generated_date: generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE] ).strftime('%Y-%m-%d') str_data = test[FIELD_INDEX_DATA].replace("'", '"') data = json.loads(str_data) print(str_data) co2s.append(data['co2']) if not generated_date: generated_date = datetime.today().strftime('%Y-%m-%d') output_content = ( '# This array was last generated with carbon-rating.py on {0}\n'. format(generated_date)) output_content += 'def get_generated_date():\n' output_content += "\treturn '{0}'\n".format(generated_date) output_content += '\n' output_content += 'def get_percentiles():\n' output_content += '\treturn [\n' co2s_sorted = sorted(co2s) intervals = list() index = 1 while index <= 100: percentile = getPercentile(co2s_sorted, index) intervals.append(percentile) position = index - 1 if index < 100: if position % 10 == 0 and position != 0: output_content += '\t\t# {0} percentile\n'.format(position) output_content += '\t\t{0},\n'.format(percentile) else: output_content += '\t\t{0}\n'.format(percentile) index += 1 output_content += '\t]' print(output_content) if len(output_filename) > 0: write(output_filename, output_content) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def getPercentile(arr, percentile): percentile = min(100, max(0, percentile)) index = percentile / 100 * (len(arr) - 1) fractionPart = index - math.floor(index) intPart = math.floor(index) percentile = float(arr[intPart]) if fractionPart > 0: percentile += fractionPart * (float(arr[intPart + 1]) - float(arr[ intPart])) else: percentile += 0 return percentile def write(output_filename, content): with open(output_filename, 'w') as outfile: outfile.write(content) def main(argv): """ WebPerf Core Carbon Percentiles Usage: * run webperf-core test on all websites you want to use for your percentiles (with json as output file) * run this file against your output file, for example like this: carbon-rating.py -i data\\carbon-references-2022.json -o tests\\energy_efficiency_carbon_percentiles.py Options and arguments: -h/--help : Help information on how to use script -i/--input <file path> : input file path (.json) -o/--output <file path> : output file path (.py) """ output_filename = '' input_filename = '' langCode = 'en' language = False language = gettext.translation('webperf-core', localedir='locales', languages=[langCode]) language.install() _ = language.gettext try: opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output='] ) except getopt.GetoptError: print(main.__doc__) sys.exit(2) if opts.__len__() == 0: print(main.__doc__) sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print(main.__doc__) sys.exit(2) elif opt in ('-i', '--input'): input_filename = arg file_ending = '' file_long_ending = '' if len(input_filename) > 4: file_ending = input_filename[-4:].lower() if len(input_filename) > 7: file_long_ending = input_filename[-7:].lower() if file_long_ending == '.sqlite': from engines.sqlite import read_sites, add_site, delete_site elif file_ending == '.csv': from engines.csv import read_sites, add_site, delete_site elif file_ending == '.xml': from engines.sitemap import read_sites, add_site, delete_site else: from engines.json import read_tests, read_sites, add_site, delete_site pass elif opt in ('-o', '--output'): output_filename = arg pass tests = read_tests(input_filename, 0, -1) generated_date = False co2s = list() for test in tests: if not generated_date: generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE] ).strftime('%Y-%m-%d') str_data = test[FIELD_INDEX_DATA].replace("'", '"') data = json.loads(str_data) print(str_data) co2s.append(data['co2']) if not generated_date: generated_date = datetime.today().strftime('%Y-%m-%d') output_content = ( '# This array was last generated with carbon-rating.py on {0}\n'. format(generated_date)) output_content += 'def get_generated_date():\n' output_content += "\treturn '{0}'\n".format(generated_date) output_content += '\n' output_content += 'def get_percentiles():\n' output_content += '\treturn [\n' co2s_sorted = sorted(co2s) intervals = list() index = 1 while index <= 100: percentile = getPercentile(co2s_sorted, index) intervals.append(percentile) position = index - 1 if index < 100: if position % 10 == 0 and position != 0: output_content += '\t\t# {0} percentile\n'.format(position) output_content += '\t\t{0},\n'.format(percentile) else: output_content += '\t\t{0}\n'.format(percentile) index += 1 output_content += '\t]' print(output_content) if len(output_filename) > 0: write(output_filename, output_content) <|reserved_special_token_0|> if __name__ == '__main__': main(sys.argv[1:]) <|reserved_special_token_1|> <|reserved_special_token_0|> FIELD_INDEX_DATE = 0 FIELD_INDEX_DATA = 1 def getPercentile(arr, percentile): percentile = min(100, max(0, percentile)) index = percentile / 100 * (len(arr) - 1) fractionPart = index - math.floor(index) intPart = math.floor(index) percentile = float(arr[intPart]) if fractionPart > 0: percentile += fractionPart * (float(arr[intPart + 1]) - float(arr[ intPart])) else: percentile += 0 return percentile def write(output_filename, content): with open(output_filename, 'w') as outfile: outfile.write(content) def main(argv): """ WebPerf Core Carbon Percentiles Usage: * run webperf-core test on all websites you want to use for your percentiles (with json as output file) * run this file against your output file, for example like this: carbon-rating.py -i data\\carbon-references-2022.json -o tests\\energy_efficiency_carbon_percentiles.py Options and arguments: -h/--help : Help information on how to use script -i/--input <file path> : input file path (.json) -o/--output <file path> : output file path (.py) """ output_filename = '' input_filename = '' langCode = 'en' language = False language = gettext.translation('webperf-core', localedir='locales', languages=[langCode]) language.install() _ = language.gettext try: opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output='] ) except getopt.GetoptError: print(main.__doc__) sys.exit(2) if opts.__len__() == 0: print(main.__doc__) sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print(main.__doc__) sys.exit(2) elif opt in ('-i', '--input'): input_filename = arg file_ending = '' file_long_ending = '' if len(input_filename) > 4: file_ending = input_filename[-4:].lower() if len(input_filename) > 7: file_long_ending = input_filename[-7:].lower() if file_long_ending == '.sqlite': from engines.sqlite import read_sites, add_site, delete_site elif file_ending == '.csv': from engines.csv import read_sites, add_site, delete_site elif file_ending == '.xml': from engines.sitemap import read_sites, add_site, delete_site else: from engines.json import read_tests, read_sites, add_site, delete_site pass elif opt in ('-o', '--output'): output_filename = arg pass tests = read_tests(input_filename, 0, -1) generated_date = False co2s = list() for test in tests: if not generated_date: generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE] ).strftime('%Y-%m-%d') str_data = test[FIELD_INDEX_DATA].replace("'", '"') data = json.loads(str_data) print(str_data) co2s.append(data['co2']) if not generated_date: generated_date = datetime.today().strftime('%Y-%m-%d') output_content = ( '# This array was last generated with carbon-rating.py on {0}\n'. format(generated_date)) output_content += 'def get_generated_date():\n' output_content += "\treturn '{0}'\n".format(generated_date) output_content += '\n' output_content += 'def get_percentiles():\n' output_content += '\treturn [\n' co2s_sorted = sorted(co2s) intervals = list() index = 1 while index <= 100: percentile = getPercentile(co2s_sorted, index) intervals.append(percentile) position = index - 1 if index < 100: if position % 10 == 0 and position != 0: output_content += '\t\t# {0} percentile\n'.format(position) output_content += '\t\t{0},\n'.format(percentile) else: output_content += '\t\t{0}\n'.format(percentile) index += 1 output_content += '\t]' print(output_content) if len(output_filename) > 0: write(output_filename, output_content) <|reserved_special_token_0|> if __name__ == '__main__': main(sys.argv[1:]) <|reserved_special_token_1|> import sys import getopt import datetime import gettext import math import datetime import json import gettext from datetime import datetime FIELD_INDEX_DATE = 0 FIELD_INDEX_DATA = 1 def getPercentile(arr, percentile): percentile = min(100, max(0, percentile)) index = percentile / 100 * (len(arr) - 1) fractionPart = index - math.floor(index) intPart = math.floor(index) percentile = float(arr[intPart]) if fractionPart > 0: percentile += fractionPart * (float(arr[intPart + 1]) - float(arr[ intPart])) else: percentile += 0 return percentile def write(output_filename, content): with open(output_filename, 'w') as outfile: outfile.write(content) def main(argv): """ WebPerf Core Carbon Percentiles Usage: * run webperf-core test on all websites you want to use for your percentiles (with json as output file) * run this file against your output file, for example like this: carbon-rating.py -i data\\carbon-references-2022.json -o tests\\energy_efficiency_carbon_percentiles.py Options and arguments: -h/--help : Help information on how to use script -i/--input <file path> : input file path (.json) -o/--output <file path> : output file path (.py) """ output_filename = '' input_filename = '' langCode = 'en' language = False language = gettext.translation('webperf-core', localedir='locales', languages=[langCode]) language.install() _ = language.gettext try: opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output='] ) except getopt.GetoptError: print(main.__doc__) sys.exit(2) if opts.__len__() == 0: print(main.__doc__) sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): print(main.__doc__) sys.exit(2) elif opt in ('-i', '--input'): input_filename = arg file_ending = '' file_long_ending = '' if len(input_filename) > 4: file_ending = input_filename[-4:].lower() if len(input_filename) > 7: file_long_ending = input_filename[-7:].lower() if file_long_ending == '.sqlite': from engines.sqlite import read_sites, add_site, delete_site elif file_ending == '.csv': from engines.csv import read_sites, add_site, delete_site elif file_ending == '.xml': from engines.sitemap import read_sites, add_site, delete_site else: from engines.json import read_tests, read_sites, add_site, delete_site pass elif opt in ('-o', '--output'): output_filename = arg pass tests = read_tests(input_filename, 0, -1) generated_date = False co2s = list() for test in tests: if not generated_date: generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE] ).strftime('%Y-%m-%d') str_data = test[FIELD_INDEX_DATA].replace("'", '"') data = json.loads(str_data) print(str_data) co2s.append(data['co2']) if not generated_date: generated_date = datetime.today().strftime('%Y-%m-%d') output_content = ( '# This array was last generated with carbon-rating.py on {0}\n'. format(generated_date)) output_content += 'def get_generated_date():\n' output_content += "\treturn '{0}'\n".format(generated_date) output_content += '\n' output_content += 'def get_percentiles():\n' output_content += '\treturn [\n' co2s_sorted = sorted(co2s) intervals = list() index = 1 while index <= 100: percentile = getPercentile(co2s_sorted, index) intervals.append(percentile) position = index - 1 if index < 100: if position % 10 == 0 and position != 0: output_content += '\t\t# {0} percentile\n'.format(position) output_content += '\t\t{0},\n'.format(percentile) else: output_content += '\t\t{0}\n'.format(percentile) index += 1 output_content += '\t]' print(output_content) if len(output_filename) > 0: write(output_filename, output_content) <|reserved_special_token_0|> if __name__ == '__main__': main(sys.argv[1:]) <|reserved_special_token_1|> # -*- coding: utf-8 -*- import sys import getopt import datetime import gettext import math import datetime import json import gettext from datetime import datetime FIELD_INDEX_DATE = 0 FIELD_INDEX_DATA = 1 def getPercentile(arr, percentile): percentile = min(100, max(0, percentile)) index = (percentile / 100) * (len(arr) - 1) fractionPart = index - math.floor(index) intPart = math.floor(index) percentile = float(arr[intPart]) if fractionPart > 0: percentile += fractionPart * \ (float(arr[intPart + 1]) - float(arr[intPart])) else: percentile += 0 return percentile def write(output_filename, content): with open(output_filename, 'w') as outfile: outfile.write(content) def main(argv): """ WebPerf Core Carbon Percentiles Usage: * run webperf-core test on all websites you want to use for your percentiles (with json as output file) * run this file against your output file, for example like this: carbon-rating.py -i data\carbon-references-2022.json -o tests\energy_efficiency_carbon_percentiles.py Options and arguments: -h/--help\t\t\t: Help information on how to use script -i/--input <file path>\t: input file path (.json) -o/--output <file path>\t: output file path (.py) """ output_filename = '' input_filename = '' langCode = 'en' language = False # add support for default (en) language language = gettext.translation( 'webperf-core', localedir='locales', languages=[langCode]) language.install() _ = language.gettext try: opts, args = getopt.getopt( argv, "hi:o:", ["help", "input=", "output="]) except getopt.GetoptError: print(main.__doc__) sys.exit(2) if (opts.__len__() == 0): print(main.__doc__) sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): # help print(main.__doc__) sys.exit(2) elif opt in ("-i", "--input"): # input file path input_filename = arg file_ending = "" file_long_ending = "" if (len(input_filename) > 4): file_ending = input_filename[-4:].lower() if (len(input_filename) > 7): file_long_ending = input_filename[-7:].lower() if file_long_ending == ".sqlite": from engines.sqlite import read_sites, add_site, delete_site elif (file_ending == ".csv"): from engines.csv import read_sites, add_site, delete_site elif (file_ending == ".xml"): # https://example.com/sitemap.xml from engines.sitemap import read_sites, add_site, delete_site else: from engines.json import read_tests, read_sites, add_site, delete_site pass elif opt in ("-o", "--output"): # output file path output_filename = arg pass tests = read_tests(input_filename, 0, -1) generated_date = False co2s = list() for test in tests: if not generated_date: generated_date = datetime.fromisoformat( test[FIELD_INDEX_DATE]).strftime('%Y-%m-%d') str_data = test[FIELD_INDEX_DATA].replace('\'', '"') data = json.loads(str_data) print(str_data) co2s.append(data['co2']) if not generated_date: generated_date = datetime.today().strftime('%Y-%m-%d') output_content = "# This array was last generated with carbon-rating.py on {0}\n".format( generated_date) output_content += "def get_generated_date():\n" output_content += "\treturn '{0}'\n".format( generated_date) output_content += "\n" output_content += "def get_percentiles():\n" output_content += "\treturn [\n" co2s_sorted = sorted(co2s) intervals = list() index = 1 while (index <= 100): percentile = getPercentile(co2s_sorted, index) intervals.append(percentile) position = index - 1 if index < 100: if position % 10 == 0 and position != 0: output_content += "\t\t# {0} percentile\n".format(position) output_content += "\t\t{0},\n".format(percentile) else: output_content += "\t\t{0}\n".format(percentile) index += 1 output_content += "\t]" print(output_content) if (len(output_filename) > 0): write(output_filename, output_content) """ If file is executed on itself then call a definition, mostly for testing purposes """ if __name__ == '__main__': main(sys.argv[1:])
flexible
{ "blob_id": "a801ca6ae90556d41fd278032af4e58a63709cec", "index": 7977, "step-1": "<mask token>\n\n\ndef write(output_filename, content):\n with open(output_filename, 'w') as outfile:\n outfile.write(content)\n\n\ndef main(argv):\n \"\"\"\n WebPerf Core Carbon Percentiles\n\n\n Usage:\n * run webperf-core test on all websites you want to use for your percentiles (with json as output file)\n * run this file against your output file, for example like this: carbon-rating.py -i data\\\\carbon-references-2022.json -o tests\\\\energy_efficiency_carbon_percentiles.py\n\n Options and arguments:\n -h/--help\t\t\t: Help information on how to use script\n -i/--input <file path>\t: input file path (.json)\n -o/--output <file path>\t: output file path (.py)\n \"\"\"\n output_filename = ''\n input_filename = ''\n langCode = 'en'\n language = False\n language = gettext.translation('webperf-core', localedir='locales',\n languages=[langCode])\n language.install()\n _ = language.gettext\n try:\n opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output=']\n )\n except getopt.GetoptError:\n print(main.__doc__)\n sys.exit(2)\n if opts.__len__() == 0:\n print(main.__doc__)\n sys.exit(2)\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n print(main.__doc__)\n sys.exit(2)\n elif opt in ('-i', '--input'):\n input_filename = arg\n file_ending = ''\n file_long_ending = ''\n if len(input_filename) > 4:\n file_ending = input_filename[-4:].lower()\n if len(input_filename) > 7:\n file_long_ending = input_filename[-7:].lower()\n if file_long_ending == '.sqlite':\n from engines.sqlite import read_sites, add_site, delete_site\n elif file_ending == '.csv':\n from engines.csv import read_sites, add_site, delete_site\n elif file_ending == '.xml':\n from engines.sitemap import read_sites, add_site, delete_site\n else:\n from engines.json import read_tests, read_sites, add_site, delete_site\n pass\n elif opt in ('-o', '--output'):\n output_filename = arg\n pass\n tests = read_tests(input_filename, 0, -1)\n generated_date = False\n co2s = list()\n for test in tests:\n if not generated_date:\n generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE]\n ).strftime('%Y-%m-%d')\n str_data = test[FIELD_INDEX_DATA].replace(\"'\", '\"')\n data = json.loads(str_data)\n print(str_data)\n co2s.append(data['co2'])\n if not generated_date:\n generated_date = datetime.today().strftime('%Y-%m-%d')\n output_content = (\n '# This array was last generated with carbon-rating.py on {0}\\n'.\n format(generated_date))\n output_content += 'def get_generated_date():\\n'\n output_content += \"\\treturn '{0}'\\n\".format(generated_date)\n output_content += '\\n'\n output_content += 'def get_percentiles():\\n'\n output_content += '\\treturn [\\n'\n co2s_sorted = sorted(co2s)\n intervals = list()\n index = 1\n while index <= 100:\n percentile = getPercentile(co2s_sorted, index)\n intervals.append(percentile)\n position = index - 1\n if index < 100:\n if position % 10 == 0 and position != 0:\n output_content += '\\t\\t# {0} percentile\\n'.format(position)\n output_content += '\\t\\t{0},\\n'.format(percentile)\n else:\n output_content += '\\t\\t{0}\\n'.format(percentile)\n index += 1\n output_content += '\\t]'\n print(output_content)\n if len(output_filename) > 0:\n write(output_filename, output_content)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef getPercentile(arr, percentile):\n percentile = min(100, max(0, percentile))\n index = percentile / 100 * (len(arr) - 1)\n fractionPart = index - math.floor(index)\n intPart = math.floor(index)\n percentile = float(arr[intPart])\n if fractionPart > 0:\n percentile += fractionPart * (float(arr[intPart + 1]) - float(arr[\n intPart]))\n else:\n percentile += 0\n return percentile\n\n\ndef write(output_filename, content):\n with open(output_filename, 'w') as outfile:\n outfile.write(content)\n\n\ndef main(argv):\n \"\"\"\n WebPerf Core Carbon Percentiles\n\n\n Usage:\n * run webperf-core test on all websites you want to use for your percentiles (with json as output file)\n * run this file against your output file, for example like this: carbon-rating.py -i data\\\\carbon-references-2022.json -o tests\\\\energy_efficiency_carbon_percentiles.py\n\n Options and arguments:\n -h/--help\t\t\t: Help information on how to use script\n -i/--input <file path>\t: input file path (.json)\n -o/--output <file path>\t: output file path (.py)\n \"\"\"\n output_filename = ''\n input_filename = ''\n langCode = 'en'\n language = False\n language = gettext.translation('webperf-core', localedir='locales',\n languages=[langCode])\n language.install()\n _ = language.gettext\n try:\n opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output=']\n )\n except getopt.GetoptError:\n print(main.__doc__)\n sys.exit(2)\n if opts.__len__() == 0:\n print(main.__doc__)\n sys.exit(2)\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n print(main.__doc__)\n sys.exit(2)\n elif opt in ('-i', '--input'):\n input_filename = arg\n file_ending = ''\n file_long_ending = ''\n if len(input_filename) > 4:\n file_ending = input_filename[-4:].lower()\n if len(input_filename) > 7:\n file_long_ending = input_filename[-7:].lower()\n if file_long_ending == '.sqlite':\n from engines.sqlite import read_sites, add_site, delete_site\n elif file_ending == '.csv':\n from engines.csv import read_sites, add_site, delete_site\n elif file_ending == '.xml':\n from engines.sitemap import read_sites, add_site, delete_site\n else:\n from engines.json import read_tests, read_sites, add_site, delete_site\n pass\n elif opt in ('-o', '--output'):\n output_filename = arg\n pass\n tests = read_tests(input_filename, 0, -1)\n generated_date = False\n co2s = list()\n for test in tests:\n if not generated_date:\n generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE]\n ).strftime('%Y-%m-%d')\n str_data = test[FIELD_INDEX_DATA].replace(\"'\", '\"')\n data = json.loads(str_data)\n print(str_data)\n co2s.append(data['co2'])\n if not generated_date:\n generated_date = datetime.today().strftime('%Y-%m-%d')\n output_content = (\n '# This array was last generated with carbon-rating.py on {0}\\n'.\n format(generated_date))\n output_content += 'def get_generated_date():\\n'\n output_content += \"\\treturn '{0}'\\n\".format(generated_date)\n output_content += '\\n'\n output_content += 'def get_percentiles():\\n'\n output_content += '\\treturn [\\n'\n co2s_sorted = sorted(co2s)\n intervals = list()\n index = 1\n while index <= 100:\n percentile = getPercentile(co2s_sorted, index)\n intervals.append(percentile)\n position = index - 1\n if index < 100:\n if position % 10 == 0 and position != 0:\n output_content += '\\t\\t# {0} percentile\\n'.format(position)\n output_content += '\\t\\t{0},\\n'.format(percentile)\n else:\n output_content += '\\t\\t{0}\\n'.format(percentile)\n index += 1\n output_content += '\\t]'\n print(output_content)\n if len(output_filename) > 0:\n write(output_filename, output_content)\n\n\n<mask token>\nif __name__ == '__main__':\n main(sys.argv[1:])\n", "step-3": "<mask token>\nFIELD_INDEX_DATE = 0\nFIELD_INDEX_DATA = 1\n\n\ndef getPercentile(arr, percentile):\n percentile = min(100, max(0, percentile))\n index = percentile / 100 * (len(arr) - 1)\n fractionPart = index - math.floor(index)\n intPart = math.floor(index)\n percentile = float(arr[intPart])\n if fractionPart > 0:\n percentile += fractionPart * (float(arr[intPart + 1]) - float(arr[\n intPart]))\n else:\n percentile += 0\n return percentile\n\n\ndef write(output_filename, content):\n with open(output_filename, 'w') as outfile:\n outfile.write(content)\n\n\ndef main(argv):\n \"\"\"\n WebPerf Core Carbon Percentiles\n\n\n Usage:\n * run webperf-core test on all websites you want to use for your percentiles (with json as output file)\n * run this file against your output file, for example like this: carbon-rating.py -i data\\\\carbon-references-2022.json -o tests\\\\energy_efficiency_carbon_percentiles.py\n\n Options and arguments:\n -h/--help\t\t\t: Help information on how to use script\n -i/--input <file path>\t: input file path (.json)\n -o/--output <file path>\t: output file path (.py)\n \"\"\"\n output_filename = ''\n input_filename = ''\n langCode = 'en'\n language = False\n language = gettext.translation('webperf-core', localedir='locales',\n languages=[langCode])\n language.install()\n _ = language.gettext\n try:\n opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output=']\n )\n except getopt.GetoptError:\n print(main.__doc__)\n sys.exit(2)\n if opts.__len__() == 0:\n print(main.__doc__)\n sys.exit(2)\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n print(main.__doc__)\n sys.exit(2)\n elif opt in ('-i', '--input'):\n input_filename = arg\n file_ending = ''\n file_long_ending = ''\n if len(input_filename) > 4:\n file_ending = input_filename[-4:].lower()\n if len(input_filename) > 7:\n file_long_ending = input_filename[-7:].lower()\n if file_long_ending == '.sqlite':\n from engines.sqlite import read_sites, add_site, delete_site\n elif file_ending == '.csv':\n from engines.csv import read_sites, add_site, delete_site\n elif file_ending == '.xml':\n from engines.sitemap import read_sites, add_site, delete_site\n else:\n from engines.json import read_tests, read_sites, add_site, delete_site\n pass\n elif opt in ('-o', '--output'):\n output_filename = arg\n pass\n tests = read_tests(input_filename, 0, -1)\n generated_date = False\n co2s = list()\n for test in tests:\n if not generated_date:\n generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE]\n ).strftime('%Y-%m-%d')\n str_data = test[FIELD_INDEX_DATA].replace(\"'\", '\"')\n data = json.loads(str_data)\n print(str_data)\n co2s.append(data['co2'])\n if not generated_date:\n generated_date = datetime.today().strftime('%Y-%m-%d')\n output_content = (\n '# This array was last generated with carbon-rating.py on {0}\\n'.\n format(generated_date))\n output_content += 'def get_generated_date():\\n'\n output_content += \"\\treturn '{0}'\\n\".format(generated_date)\n output_content += '\\n'\n output_content += 'def get_percentiles():\\n'\n output_content += '\\treturn [\\n'\n co2s_sorted = sorted(co2s)\n intervals = list()\n index = 1\n while index <= 100:\n percentile = getPercentile(co2s_sorted, index)\n intervals.append(percentile)\n position = index - 1\n if index < 100:\n if position % 10 == 0 and position != 0:\n output_content += '\\t\\t# {0} percentile\\n'.format(position)\n output_content += '\\t\\t{0},\\n'.format(percentile)\n else:\n output_content += '\\t\\t{0}\\n'.format(percentile)\n index += 1\n output_content += '\\t]'\n print(output_content)\n if len(output_filename) > 0:\n write(output_filename, output_content)\n\n\n<mask token>\nif __name__ == '__main__':\n main(sys.argv[1:])\n", "step-4": "import sys\nimport getopt\nimport datetime\nimport gettext\nimport math\nimport datetime\nimport json\nimport gettext\nfrom datetime import datetime\nFIELD_INDEX_DATE = 0\nFIELD_INDEX_DATA = 1\n\n\ndef getPercentile(arr, percentile):\n percentile = min(100, max(0, percentile))\n index = percentile / 100 * (len(arr) - 1)\n fractionPart = index - math.floor(index)\n intPart = math.floor(index)\n percentile = float(arr[intPart])\n if fractionPart > 0:\n percentile += fractionPart * (float(arr[intPart + 1]) - float(arr[\n intPart]))\n else:\n percentile += 0\n return percentile\n\n\ndef write(output_filename, content):\n with open(output_filename, 'w') as outfile:\n outfile.write(content)\n\n\ndef main(argv):\n \"\"\"\n WebPerf Core Carbon Percentiles\n\n\n Usage:\n * run webperf-core test on all websites you want to use for your percentiles (with json as output file)\n * run this file against your output file, for example like this: carbon-rating.py -i data\\\\carbon-references-2022.json -o tests\\\\energy_efficiency_carbon_percentiles.py\n\n Options and arguments:\n -h/--help\t\t\t: Help information on how to use script\n -i/--input <file path>\t: input file path (.json)\n -o/--output <file path>\t: output file path (.py)\n \"\"\"\n output_filename = ''\n input_filename = ''\n langCode = 'en'\n language = False\n language = gettext.translation('webperf-core', localedir='locales',\n languages=[langCode])\n language.install()\n _ = language.gettext\n try:\n opts, args = getopt.getopt(argv, 'hi:o:', ['help', 'input=', 'output=']\n )\n except getopt.GetoptError:\n print(main.__doc__)\n sys.exit(2)\n if opts.__len__() == 0:\n print(main.__doc__)\n sys.exit(2)\n for opt, arg in opts:\n if opt in ('-h', '--help'):\n print(main.__doc__)\n sys.exit(2)\n elif opt in ('-i', '--input'):\n input_filename = arg\n file_ending = ''\n file_long_ending = ''\n if len(input_filename) > 4:\n file_ending = input_filename[-4:].lower()\n if len(input_filename) > 7:\n file_long_ending = input_filename[-7:].lower()\n if file_long_ending == '.sqlite':\n from engines.sqlite import read_sites, add_site, delete_site\n elif file_ending == '.csv':\n from engines.csv import read_sites, add_site, delete_site\n elif file_ending == '.xml':\n from engines.sitemap import read_sites, add_site, delete_site\n else:\n from engines.json import read_tests, read_sites, add_site, delete_site\n pass\n elif opt in ('-o', '--output'):\n output_filename = arg\n pass\n tests = read_tests(input_filename, 0, -1)\n generated_date = False\n co2s = list()\n for test in tests:\n if not generated_date:\n generated_date = datetime.fromisoformat(test[FIELD_INDEX_DATE]\n ).strftime('%Y-%m-%d')\n str_data = test[FIELD_INDEX_DATA].replace(\"'\", '\"')\n data = json.loads(str_data)\n print(str_data)\n co2s.append(data['co2'])\n if not generated_date:\n generated_date = datetime.today().strftime('%Y-%m-%d')\n output_content = (\n '# This array was last generated with carbon-rating.py on {0}\\n'.\n format(generated_date))\n output_content += 'def get_generated_date():\\n'\n output_content += \"\\treturn '{0}'\\n\".format(generated_date)\n output_content += '\\n'\n output_content += 'def get_percentiles():\\n'\n output_content += '\\treturn [\\n'\n co2s_sorted = sorted(co2s)\n intervals = list()\n index = 1\n while index <= 100:\n percentile = getPercentile(co2s_sorted, index)\n intervals.append(percentile)\n position = index - 1\n if index < 100:\n if position % 10 == 0 and position != 0:\n output_content += '\\t\\t# {0} percentile\\n'.format(position)\n output_content += '\\t\\t{0},\\n'.format(percentile)\n else:\n output_content += '\\t\\t{0}\\n'.format(percentile)\n index += 1\n output_content += '\\t]'\n print(output_content)\n if len(output_filename) > 0:\n write(output_filename, output_content)\n\n\n<mask token>\nif __name__ == '__main__':\n main(sys.argv[1:])\n", "step-5": "# -*- coding: utf-8 -*-\nimport sys\nimport getopt\nimport datetime\nimport gettext\nimport math\nimport datetime\nimport json\nimport gettext\nfrom datetime import datetime\n\nFIELD_INDEX_DATE = 0\nFIELD_INDEX_DATA = 1\n\n\ndef getPercentile(arr, percentile):\n percentile = min(100, max(0, percentile))\n index = (percentile / 100) * (len(arr) - 1)\n fractionPart = index - math.floor(index)\n intPart = math.floor(index)\n percentile = float(arr[intPart])\n\n if fractionPart > 0:\n percentile += fractionPart * \\\n (float(arr[intPart + 1]) - float(arr[intPart]))\n else:\n percentile += 0\n\n return percentile\n\n\ndef write(output_filename, content):\n with open(output_filename, 'w') as outfile:\n outfile.write(content)\n\n\ndef main(argv):\n \"\"\"\n WebPerf Core Carbon Percentiles\n\n\n Usage:\n * run webperf-core test on all websites you want to use for your percentiles (with json as output file)\n * run this file against your output file, for example like this: carbon-rating.py -i data\\carbon-references-2022.json -o tests\\energy_efficiency_carbon_percentiles.py\n\n Options and arguments:\n -h/--help\\t\\t\\t: Help information on how to use script\n -i/--input <file path>\\t: input file path (.json)\n -o/--output <file path>\\t: output file path (.py)\n \"\"\"\n\n output_filename = ''\n input_filename = ''\n langCode = 'en'\n language = False\n\n # add support for default (en) language\n language = gettext.translation(\n 'webperf-core', localedir='locales', languages=[langCode])\n language.install()\n _ = language.gettext\n\n try:\n opts, args = getopt.getopt(\n argv, \"hi:o:\", [\"help\", \"input=\", \"output=\"])\n except getopt.GetoptError:\n print(main.__doc__)\n sys.exit(2)\n\n if (opts.__len__() == 0):\n print(main.__doc__)\n sys.exit(2)\n\n for opt, arg in opts:\n if opt in ('-h', '--help'): # help\n print(main.__doc__)\n sys.exit(2)\n elif opt in (\"-i\", \"--input\"): # input file path\n input_filename = arg\n\n file_ending = \"\"\n file_long_ending = \"\"\n if (len(input_filename) > 4):\n file_ending = input_filename[-4:].lower()\n if (len(input_filename) > 7):\n file_long_ending = input_filename[-7:].lower()\n\n if file_long_ending == \".sqlite\":\n from engines.sqlite import read_sites, add_site, delete_site\n elif (file_ending == \".csv\"):\n from engines.csv import read_sites, add_site, delete_site\n elif (file_ending == \".xml\"): # https://example.com/sitemap.xml\n from engines.sitemap import read_sites, add_site, delete_site\n else:\n from engines.json import read_tests, read_sites, add_site, delete_site\n pass\n elif opt in (\"-o\", \"--output\"): # output file path\n output_filename = arg\n pass\n\n tests = read_tests(input_filename, 0, -1)\n generated_date = False\n co2s = list()\n\n for test in tests:\n if not generated_date:\n generated_date = datetime.fromisoformat(\n test[FIELD_INDEX_DATE]).strftime('%Y-%m-%d')\n\n str_data = test[FIELD_INDEX_DATA].replace('\\'', '\"')\n data = json.loads(str_data)\n print(str_data)\n co2s.append(data['co2'])\n\n if not generated_date:\n generated_date = datetime.today().strftime('%Y-%m-%d')\n\n output_content = \"# This array was last generated with carbon-rating.py on {0}\\n\".format(\n generated_date)\n output_content += \"def get_generated_date():\\n\"\n output_content += \"\\treturn '{0}'\\n\".format(\n generated_date)\n output_content += \"\\n\"\n output_content += \"def get_percentiles():\\n\"\n output_content += \"\\treturn [\\n\"\n\n co2s_sorted = sorted(co2s)\n\n intervals = list()\n\n index = 1\n while (index <= 100):\n percentile = getPercentile(co2s_sorted, index)\n intervals.append(percentile)\n position = index - 1\n if index < 100:\n if position % 10 == 0 and position != 0:\n output_content += \"\\t\\t# {0} percentile\\n\".format(position)\n\n output_content += \"\\t\\t{0},\\n\".format(percentile)\n else:\n output_content += \"\\t\\t{0}\\n\".format(percentile)\n index += 1\n\n output_content += \"\\t]\"\n\n print(output_content)\n if (len(output_filename) > 0):\n write(output_filename, output_content)\n\n\n\"\"\"\nIf file is executed on itself then call a definition, mostly for testing purposes\n\"\"\"\nif __name__ == '__main__':\n main(sys.argv[1:])\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o) ) <|reserved_special_token_1|> n = int(input('Digite um número')) m = n - 1 o = n + 1 print('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o) ) <|reserved_special_token_1|> n=int(input("Digite um número")) m=n-1 o=n+1 print("Seu número é {} seu antecessor é {} e seu sucessor é {}".format(n,m,o))
flexible
{ "blob_id": "47d72379b894826dad335f098649702ade195f78", "index": 7337, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o)\n )\n", "step-3": "n = int(input('Digite um número'))\nm = n - 1\no = n + 1\nprint('Seu número é {} seu antecessor é {} e seu sucessor é {}'.format(n, m, o)\n )\n", "step-4": "n=int(input(\"Digite um número\"))\nm=n-1\no=n+1\nprint(\"Seu número é {} seu antecessor é {} e seu sucessor é {}\".format(n,m,o))", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# vim: expandtab # -*- coding: utf-8 -*- from poleno.utils.template import Library from chcemvediet.apps.obligees.models import Obligee register = Library() @register.simple_tag def gender(gender, masculine, feminine, neuter, plurale): if gender == Obligee.GENDERS.MASCULINE: return masculine elif gender == Obligee.GENDERS.FEMININE: return feminine elif gender == Obligee.GENDERS.NEUTER: return neuter elif gender == Obligee.GENDERS.PLURALE: return plurale else: return u''
normal
{ "blob_id": "c9d12f14fa0e46e4590746d45862fe255b415a1d", "index": 396, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@register.simple_tag\ndef gender(gender, masculine, feminine, neuter, plurale):\n if gender == Obligee.GENDERS.MASCULINE:\n return masculine\n elif gender == Obligee.GENDERS.FEMININE:\n return feminine\n elif gender == Obligee.GENDERS.NEUTER:\n return neuter\n elif gender == Obligee.GENDERS.PLURALE:\n return plurale\n else:\n return u''\n", "step-3": "<mask token>\nregister = Library()\n\n\n@register.simple_tag\ndef gender(gender, masculine, feminine, neuter, plurale):\n if gender == Obligee.GENDERS.MASCULINE:\n return masculine\n elif gender == Obligee.GENDERS.FEMININE:\n return feminine\n elif gender == Obligee.GENDERS.NEUTER:\n return neuter\n elif gender == Obligee.GENDERS.PLURALE:\n return plurale\n else:\n return u''\n", "step-4": "from poleno.utils.template import Library\nfrom chcemvediet.apps.obligees.models import Obligee\nregister = Library()\n\n\n@register.simple_tag\ndef gender(gender, masculine, feminine, neuter, plurale):\n if gender == Obligee.GENDERS.MASCULINE:\n return masculine\n elif gender == Obligee.GENDERS.FEMININE:\n return feminine\n elif gender == Obligee.GENDERS.NEUTER:\n return neuter\n elif gender == Obligee.GENDERS.PLURALE:\n return plurale\n else:\n return u''\n", "step-5": "# vim: expandtab\n# -*- coding: utf-8 -*-\nfrom poleno.utils.template import Library\nfrom chcemvediet.apps.obligees.models import Obligee\n\n\nregister = Library()\n\n@register.simple_tag\ndef gender(gender, masculine, feminine, neuter, plurale):\n if gender == Obligee.GENDERS.MASCULINE:\n return masculine\n elif gender == Obligee.GENDERS.FEMININE:\n return feminine\n elif gender == Obligee.GENDERS.NEUTER:\n return neuter\n elif gender == Obligee.GENDERS.PLURALE:\n return plurale\n else:\n return u''\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import asyncio import logging from datetime import datetime from discord.ext import commands from discord.ext.commands import Bot, Context from humanize import precisedelta from sqlalchemy.exc import SQLAlchemyError from sqlalchemy_utils import ScalarListException from config import CONFIG from models import Reminder, db_session from utils import ( DateTimeConverter, get_database_user, get_database_user_from_id, get_name_string, user_is_irc_bot, ) LONG_HELP_TEXT = """ Add reminders for yourself or remove the last one you added. """ SHORT_HELP_TEXT = """Add or remove reminders.""" async def reminder_check(bot): await bot.wait_until_ready() while not bot.is_closed(): now = datetime.now() reminders = ( db_session.query(Reminder) .filter(Reminder.trigger_at <= now, Reminder.triggered == False) # noqa 712 .all() ) for r in reminders: if r.irc_name: display_name = r.irc_name else: author_uid = r.user.user_uid display_name = f"<@{author_uid}>" channel = bot.get_channel(r.playback_channel_id) message = f"Reminding {display_name}: " + r.reminder_content await channel.send(message) r.triggered = True db_session.commit() await asyncio.sleep(CONFIG.REMINDER_SEARCH_INTERVAL) class Reminders(commands.Cog): def __init__(self, bot: Bot): self.bot = bot self.bot.loop.create_task(reminder_check(self.bot)) @commands.group(help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT) async def reminder(self, ctx: Context): if not ctx.invoked_subcommand: await ctx.send("Subcommand not found.") @reminder.command( help='Add a reminder, format "yyyy-mm-dd hh:mm" or "mm-dd hh:mm" or hh:mm:ss or hh:mm or xdxhxmxs or any ordered combination of the last format, then finally your reminder (rest of discord message).' ) async def add( self, ctx: Context, trigger_time: DateTimeConverter, *, reminder_content: str ): now = datetime.now() if not trigger_time: await ctx.send("Incorrect time format, please see help text.") elif trigger_time < now: await ctx.send("That time is in the past.") else: # HURRAY the time is valid and not in the past, add the reminder display_name = get_name_string(ctx.message) # set the id to a random value if the author was the bridge bot, since we wont be using it anyways # if ctx.message.clean_content.startswith("**<"): <---- FOR TESTING if user_is_irc_bot(ctx): author_id = 1 irc_n = display_name else: author_id = get_database_user(ctx.author).id irc_n = None trig_at = trigger_time trig = False playback_ch_id = ctx.message.channel.id new_reminder = Reminder( user_id=author_id, reminder_content=reminder_content, trigger_at=trig_at, triggered=trig, playback_channel_id=playback_ch_id, irc_name=irc_n, ) db_session.add(new_reminder) try: db_session.commit() await ctx.send( f"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {precisedelta(CONFIG.REMINDER_SEARCH_INTERVAL, minimum_unit='seconds')})." ) except (ScalarListException, SQLAlchemyError) as e: db_session.rollback() logging.exception(e) await ctx.send(f"Something went wrong") def setup(bot: Bot): bot.add_cog(Reminders(bot))
normal
{ "blob_id": "0f54853901a26b66fe35106593ded6c92785b8db", "index": 2682, "step-1": "<mask token>\n\n\nclass Reminders(commands.Cog):\n\n def __init__(self, bot: Bot):\n self.bot = bot\n self.bot.loop.create_task(reminder_check(self.bot))\n\n @commands.group(help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT)\n async def reminder(self, ctx: Context):\n if not ctx.invoked_subcommand:\n await ctx.send('Subcommand not found.')\n\n @reminder.command(help=\n 'Add a reminder, format \"yyyy-mm-dd hh:mm\" or \"mm-dd hh:mm\" or hh:mm:ss or hh:mm or xdxhxmxs or any ordered combination of the last format, then finally your reminder (rest of discord message).'\n )\n async def add(self, ctx: Context, trigger_time: DateTimeConverter, *,\n reminder_content: str):\n now = datetime.now()\n if not trigger_time:\n await ctx.send('Incorrect time format, please see help text.')\n elif trigger_time < now:\n await ctx.send('That time is in the past.')\n else:\n display_name = get_name_string(ctx.message)\n if user_is_irc_bot(ctx):\n author_id = 1\n irc_n = display_name\n else:\n author_id = get_database_user(ctx.author).id\n irc_n = None\n trig_at = trigger_time\n trig = False\n playback_ch_id = ctx.message.channel.id\n new_reminder = Reminder(user_id=author_id, reminder_content=\n reminder_content, trigger_at=trig_at, triggered=trig,\n playback_channel_id=playback_ch_id, irc_name=irc_n)\n db_session.add(new_reminder)\n try:\n db_session.commit()\n await ctx.send(\n f\"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {precisedelta(CONFIG.REMINDER_SEARCH_INTERVAL, minimum_unit='seconds')}).\"\n )\n except (ScalarListException, SQLAlchemyError) as e:\n db_session.rollback()\n logging.exception(e)\n await ctx.send(f'Something went wrong')\n\n\ndef setup(bot: Bot):\n bot.add_cog(Reminders(bot))\n", "step-2": "<mask token>\n\n\nasync def reminder_check(bot):\n await bot.wait_until_ready()\n while not bot.is_closed():\n now = datetime.now()\n reminders = db_session.query(Reminder).filter(Reminder.trigger_at <=\n now, Reminder.triggered == False).all()\n for r in reminders:\n if r.irc_name:\n display_name = r.irc_name\n else:\n author_uid = r.user.user_uid\n display_name = f'<@{author_uid}>'\n channel = bot.get_channel(r.playback_channel_id)\n message = f'Reminding {display_name}: ' + r.reminder_content\n await channel.send(message)\n r.triggered = True\n db_session.commit()\n await asyncio.sleep(CONFIG.REMINDER_SEARCH_INTERVAL)\n\n\nclass Reminders(commands.Cog):\n\n def __init__(self, bot: Bot):\n self.bot = bot\n self.bot.loop.create_task(reminder_check(self.bot))\n\n @commands.group(help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT)\n async def reminder(self, ctx: Context):\n if not ctx.invoked_subcommand:\n await ctx.send('Subcommand not found.')\n\n @reminder.command(help=\n 'Add a reminder, format \"yyyy-mm-dd hh:mm\" or \"mm-dd hh:mm\" or hh:mm:ss or hh:mm or xdxhxmxs or any ordered combination of the last format, then finally your reminder (rest of discord message).'\n )\n async def add(self, ctx: Context, trigger_time: DateTimeConverter, *,\n reminder_content: str):\n now = datetime.now()\n if not trigger_time:\n await ctx.send('Incorrect time format, please see help text.')\n elif trigger_time < now:\n await ctx.send('That time is in the past.')\n else:\n display_name = get_name_string(ctx.message)\n if user_is_irc_bot(ctx):\n author_id = 1\n irc_n = display_name\n else:\n author_id = get_database_user(ctx.author).id\n irc_n = None\n trig_at = trigger_time\n trig = False\n playback_ch_id = ctx.message.channel.id\n new_reminder = Reminder(user_id=author_id, reminder_content=\n reminder_content, trigger_at=trig_at, triggered=trig,\n playback_channel_id=playback_ch_id, irc_name=irc_n)\n db_session.add(new_reminder)\n try:\n db_session.commit()\n await ctx.send(\n f\"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {precisedelta(CONFIG.REMINDER_SEARCH_INTERVAL, minimum_unit='seconds')}).\"\n )\n except (ScalarListException, SQLAlchemyError) as e:\n db_session.rollback()\n logging.exception(e)\n await ctx.send(f'Something went wrong')\n\n\ndef setup(bot: Bot):\n bot.add_cog(Reminders(bot))\n", "step-3": "<mask token>\nLONG_HELP_TEXT = \"\"\"\nAdd reminders for yourself or remove the last one you added.\n\"\"\"\nSHORT_HELP_TEXT = 'Add or remove reminders.'\n\n\nasync def reminder_check(bot):\n await bot.wait_until_ready()\n while not bot.is_closed():\n now = datetime.now()\n reminders = db_session.query(Reminder).filter(Reminder.trigger_at <=\n now, Reminder.triggered == False).all()\n for r in reminders:\n if r.irc_name:\n display_name = r.irc_name\n else:\n author_uid = r.user.user_uid\n display_name = f'<@{author_uid}>'\n channel = bot.get_channel(r.playback_channel_id)\n message = f'Reminding {display_name}: ' + r.reminder_content\n await channel.send(message)\n r.triggered = True\n db_session.commit()\n await asyncio.sleep(CONFIG.REMINDER_SEARCH_INTERVAL)\n\n\nclass Reminders(commands.Cog):\n\n def __init__(self, bot: Bot):\n self.bot = bot\n self.bot.loop.create_task(reminder_check(self.bot))\n\n @commands.group(help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT)\n async def reminder(self, ctx: Context):\n if not ctx.invoked_subcommand:\n await ctx.send('Subcommand not found.')\n\n @reminder.command(help=\n 'Add a reminder, format \"yyyy-mm-dd hh:mm\" or \"mm-dd hh:mm\" or hh:mm:ss or hh:mm or xdxhxmxs or any ordered combination of the last format, then finally your reminder (rest of discord message).'\n )\n async def add(self, ctx: Context, trigger_time: DateTimeConverter, *,\n reminder_content: str):\n now = datetime.now()\n if not trigger_time:\n await ctx.send('Incorrect time format, please see help text.')\n elif trigger_time < now:\n await ctx.send('That time is in the past.')\n else:\n display_name = get_name_string(ctx.message)\n if user_is_irc_bot(ctx):\n author_id = 1\n irc_n = display_name\n else:\n author_id = get_database_user(ctx.author).id\n irc_n = None\n trig_at = trigger_time\n trig = False\n playback_ch_id = ctx.message.channel.id\n new_reminder = Reminder(user_id=author_id, reminder_content=\n reminder_content, trigger_at=trig_at, triggered=trig,\n playback_channel_id=playback_ch_id, irc_name=irc_n)\n db_session.add(new_reminder)\n try:\n db_session.commit()\n await ctx.send(\n f\"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {precisedelta(CONFIG.REMINDER_SEARCH_INTERVAL, minimum_unit='seconds')}).\"\n )\n except (ScalarListException, SQLAlchemyError) as e:\n db_session.rollback()\n logging.exception(e)\n await ctx.send(f'Something went wrong')\n\n\ndef setup(bot: Bot):\n bot.add_cog(Reminders(bot))\n", "step-4": "import asyncio\nimport logging\nfrom datetime import datetime\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot, Context\nfrom humanize import precisedelta\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom sqlalchemy_utils import ScalarListException\nfrom config import CONFIG\nfrom models import Reminder, db_session\nfrom utils import DateTimeConverter, get_database_user, get_database_user_from_id, get_name_string, user_is_irc_bot\nLONG_HELP_TEXT = \"\"\"\nAdd reminders for yourself or remove the last one you added.\n\"\"\"\nSHORT_HELP_TEXT = 'Add or remove reminders.'\n\n\nasync def reminder_check(bot):\n await bot.wait_until_ready()\n while not bot.is_closed():\n now = datetime.now()\n reminders = db_session.query(Reminder).filter(Reminder.trigger_at <=\n now, Reminder.triggered == False).all()\n for r in reminders:\n if r.irc_name:\n display_name = r.irc_name\n else:\n author_uid = r.user.user_uid\n display_name = f'<@{author_uid}>'\n channel = bot.get_channel(r.playback_channel_id)\n message = f'Reminding {display_name}: ' + r.reminder_content\n await channel.send(message)\n r.triggered = True\n db_session.commit()\n await asyncio.sleep(CONFIG.REMINDER_SEARCH_INTERVAL)\n\n\nclass Reminders(commands.Cog):\n\n def __init__(self, bot: Bot):\n self.bot = bot\n self.bot.loop.create_task(reminder_check(self.bot))\n\n @commands.group(help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT)\n async def reminder(self, ctx: Context):\n if not ctx.invoked_subcommand:\n await ctx.send('Subcommand not found.')\n\n @reminder.command(help=\n 'Add a reminder, format \"yyyy-mm-dd hh:mm\" or \"mm-dd hh:mm\" or hh:mm:ss or hh:mm or xdxhxmxs or any ordered combination of the last format, then finally your reminder (rest of discord message).'\n )\n async def add(self, ctx: Context, trigger_time: DateTimeConverter, *,\n reminder_content: str):\n now = datetime.now()\n if not trigger_time:\n await ctx.send('Incorrect time format, please see help text.')\n elif trigger_time < now:\n await ctx.send('That time is in the past.')\n else:\n display_name = get_name_string(ctx.message)\n if user_is_irc_bot(ctx):\n author_id = 1\n irc_n = display_name\n else:\n author_id = get_database_user(ctx.author).id\n irc_n = None\n trig_at = trigger_time\n trig = False\n playback_ch_id = ctx.message.channel.id\n new_reminder = Reminder(user_id=author_id, reminder_content=\n reminder_content, trigger_at=trig_at, triggered=trig,\n playback_channel_id=playback_ch_id, irc_name=irc_n)\n db_session.add(new_reminder)\n try:\n db_session.commit()\n await ctx.send(\n f\"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {precisedelta(CONFIG.REMINDER_SEARCH_INTERVAL, minimum_unit='seconds')}).\"\n )\n except (ScalarListException, SQLAlchemyError) as e:\n db_session.rollback()\n logging.exception(e)\n await ctx.send(f'Something went wrong')\n\n\ndef setup(bot: Bot):\n bot.add_cog(Reminders(bot))\n", "step-5": "import asyncio\nimport logging\nfrom datetime import datetime\n\nfrom discord.ext import commands\nfrom discord.ext.commands import Bot, Context\nfrom humanize import precisedelta\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom sqlalchemy_utils import ScalarListException\n\nfrom config import CONFIG\nfrom models import Reminder, db_session\nfrom utils import (\n DateTimeConverter,\n get_database_user,\n get_database_user_from_id,\n get_name_string,\n user_is_irc_bot,\n)\n\nLONG_HELP_TEXT = \"\"\"\nAdd reminders for yourself or remove the last one you added.\n\"\"\"\nSHORT_HELP_TEXT = \"\"\"Add or remove reminders.\"\"\"\n\n\nasync def reminder_check(bot):\n await bot.wait_until_ready()\n while not bot.is_closed():\n now = datetime.now()\n reminders = (\n db_session.query(Reminder)\n .filter(Reminder.trigger_at <= now, Reminder.triggered == False) # noqa 712\n .all()\n )\n for r in reminders:\n if r.irc_name:\n display_name = r.irc_name\n else:\n author_uid = r.user.user_uid\n display_name = f\"<@{author_uid}>\"\n channel = bot.get_channel(r.playback_channel_id)\n message = f\"Reminding {display_name}: \" + r.reminder_content\n await channel.send(message)\n r.triggered = True\n db_session.commit()\n\n await asyncio.sleep(CONFIG.REMINDER_SEARCH_INTERVAL)\n\n\nclass Reminders(commands.Cog):\n def __init__(self, bot: Bot):\n self.bot = bot\n self.bot.loop.create_task(reminder_check(self.bot))\n\n @commands.group(help=LONG_HELP_TEXT, brief=SHORT_HELP_TEXT)\n async def reminder(self, ctx: Context):\n if not ctx.invoked_subcommand:\n await ctx.send(\"Subcommand not found.\")\n\n @reminder.command(\n help='Add a reminder, format \"yyyy-mm-dd hh:mm\" or \"mm-dd hh:mm\" or hh:mm:ss or hh:mm or xdxhxmxs or any ordered combination of the last format, then finally your reminder (rest of discord message).'\n )\n async def add(\n self, ctx: Context, trigger_time: DateTimeConverter, *, reminder_content: str\n ):\n now = datetime.now()\n if not trigger_time:\n await ctx.send(\"Incorrect time format, please see help text.\")\n elif trigger_time < now:\n await ctx.send(\"That time is in the past.\")\n else:\n # HURRAY the time is valid and not in the past, add the reminder\n display_name = get_name_string(ctx.message)\n\n # set the id to a random value if the author was the bridge bot, since we wont be using it anyways\n # if ctx.message.clean_content.startswith(\"**<\"): <---- FOR TESTING\n if user_is_irc_bot(ctx):\n author_id = 1\n irc_n = display_name\n else:\n author_id = get_database_user(ctx.author).id\n irc_n = None\n\n trig_at = trigger_time\n trig = False\n playback_ch_id = ctx.message.channel.id\n new_reminder = Reminder(\n user_id=author_id,\n reminder_content=reminder_content,\n trigger_at=trig_at,\n triggered=trig,\n playback_channel_id=playback_ch_id,\n irc_name=irc_n,\n )\n db_session.add(new_reminder)\n try:\n db_session.commit()\n await ctx.send(\n f\"Thanks {display_name}, I have saved your reminder (but please note that my granularity is set at {precisedelta(CONFIG.REMINDER_SEARCH_INTERVAL, minimum_unit='seconds')}).\"\n )\n except (ScalarListException, SQLAlchemyError) as e:\n db_session.rollback()\n logging.exception(e)\n await ctx.send(f\"Something went wrong\")\n\n\ndef setup(bot: Bot):\n bot.add_cog(Reminders(bot))\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
""" Main CLI endpoint for GeoCube """ import importlib.metadata import click from click import group import geocube.cli.commands as cmd_modules from geocube import show_versions CONTEXT_SETTINGS = { "help_option_names": ["-h", "--help"], "token_normalize_func": lambda x: x.replace("-", "_"), } def check_version(ctx, _, value): """ Print current version, and check for latest version. Called via 'geocube --version' :param ctx: Application context object (click.Context) :param value: Passed in by Click :return None """ if not value or ctx.resilient_parsing: return click.echo(f"geocube v{importlib.metadata.version('geocube')}") ctx.exit() def cli_show_version(ctx, _, value): """ Print debugging version information. :param ctx: Application context object (click.Context) :param value: Passed in by Click :return None """ if not value or ctx.resilient_parsing: return show_versions() ctx.exit() @group(context_settings=CONTEXT_SETTINGS) @click.option( "-v", "--version", is_flag=True, is_eager=True, expose_value=False, callback=check_version, help="Show the current version", ) @click.option( "--show-versions", is_flag=True, is_eager=True, expose_value=False, callback=cli_show_version, help="Show debugging version information", ) def geocube(): """Top-level command and entry point into the GeoCube CLI""" def _add_subcommands(): """ Individual commands (and sub-commands) are encapsulated in separate files under /commands. Collect these command groups, and add them underneath the top-level command (geocube). """ geocube.add_command(cmd_modules.make_geocube.make_geocube) _add_subcommands()
normal
{ "blob_id": "0964121d88fad2906311de7532eac52ff784fff6", "index": 8306, "step-1": "<mask token>\n\n\ndef check_version(ctx, _, value):\n \"\"\"\n Print current version, and check for latest version.\n\n Called via 'geocube --version'\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n click.echo(f\"geocube v{importlib.metadata.version('geocube')}\")\n ctx.exit()\n\n\ndef cli_show_version(ctx, _, value):\n \"\"\"\n Print debugging version information.\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n show_versions()\n ctx.exit()\n\n\n@group(context_settings=CONTEXT_SETTINGS)\n@click.option('-v', '--version', is_flag=True, is_eager=True, expose_value=\n False, callback=check_version, help='Show the current version')\n@click.option('--show-versions', is_flag=True, is_eager=True, expose_value=\n False, callback=cli_show_version, help='Show debugging version information'\n )\ndef geocube():\n \"\"\"Top-level command and entry point into the GeoCube CLI\"\"\"\n\n\ndef _add_subcommands():\n \"\"\"\n Individual commands (and sub-commands) are encapsulated in separate files\n under /commands. Collect these command groups, and add them underneath the\n top-level command (geocube).\n \"\"\"\n geocube.add_command(cmd_modules.make_geocube.make_geocube)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef check_version(ctx, _, value):\n \"\"\"\n Print current version, and check for latest version.\n\n Called via 'geocube --version'\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n click.echo(f\"geocube v{importlib.metadata.version('geocube')}\")\n ctx.exit()\n\n\ndef cli_show_version(ctx, _, value):\n \"\"\"\n Print debugging version information.\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n show_versions()\n ctx.exit()\n\n\n@group(context_settings=CONTEXT_SETTINGS)\n@click.option('-v', '--version', is_flag=True, is_eager=True, expose_value=\n False, callback=check_version, help='Show the current version')\n@click.option('--show-versions', is_flag=True, is_eager=True, expose_value=\n False, callback=cli_show_version, help='Show debugging version information'\n )\ndef geocube():\n \"\"\"Top-level command and entry point into the GeoCube CLI\"\"\"\n\n\ndef _add_subcommands():\n \"\"\"\n Individual commands (and sub-commands) are encapsulated in separate files\n under /commands. Collect these command groups, and add them underneath the\n top-level command (geocube).\n \"\"\"\n geocube.add_command(cmd_modules.make_geocube.make_geocube)\n\n\n_add_subcommands()\n", "step-3": "<mask token>\nCONTEXT_SETTINGS = {'help_option_names': ['-h', '--help'],\n 'token_normalize_func': lambda x: x.replace('-', '_')}\n\n\ndef check_version(ctx, _, value):\n \"\"\"\n Print current version, and check for latest version.\n\n Called via 'geocube --version'\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n click.echo(f\"geocube v{importlib.metadata.version('geocube')}\")\n ctx.exit()\n\n\ndef cli_show_version(ctx, _, value):\n \"\"\"\n Print debugging version information.\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n show_versions()\n ctx.exit()\n\n\n@group(context_settings=CONTEXT_SETTINGS)\n@click.option('-v', '--version', is_flag=True, is_eager=True, expose_value=\n False, callback=check_version, help='Show the current version')\n@click.option('--show-versions', is_flag=True, is_eager=True, expose_value=\n False, callback=cli_show_version, help='Show debugging version information'\n )\ndef geocube():\n \"\"\"Top-level command and entry point into the GeoCube CLI\"\"\"\n\n\ndef _add_subcommands():\n \"\"\"\n Individual commands (and sub-commands) are encapsulated in separate files\n under /commands. Collect these command groups, and add them underneath the\n top-level command (geocube).\n \"\"\"\n geocube.add_command(cmd_modules.make_geocube.make_geocube)\n\n\n_add_subcommands()\n", "step-4": "<mask token>\nimport importlib.metadata\nimport click\nfrom click import group\nimport geocube.cli.commands as cmd_modules\nfrom geocube import show_versions\nCONTEXT_SETTINGS = {'help_option_names': ['-h', '--help'],\n 'token_normalize_func': lambda x: x.replace('-', '_')}\n\n\ndef check_version(ctx, _, value):\n \"\"\"\n Print current version, and check for latest version.\n\n Called via 'geocube --version'\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n click.echo(f\"geocube v{importlib.metadata.version('geocube')}\")\n ctx.exit()\n\n\ndef cli_show_version(ctx, _, value):\n \"\"\"\n Print debugging version information.\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n show_versions()\n ctx.exit()\n\n\n@group(context_settings=CONTEXT_SETTINGS)\n@click.option('-v', '--version', is_flag=True, is_eager=True, expose_value=\n False, callback=check_version, help='Show the current version')\n@click.option('--show-versions', is_flag=True, is_eager=True, expose_value=\n False, callback=cli_show_version, help='Show debugging version information'\n )\ndef geocube():\n \"\"\"Top-level command and entry point into the GeoCube CLI\"\"\"\n\n\ndef _add_subcommands():\n \"\"\"\n Individual commands (and sub-commands) are encapsulated in separate files\n under /commands. Collect these command groups, and add them underneath the\n top-level command (geocube).\n \"\"\"\n geocube.add_command(cmd_modules.make_geocube.make_geocube)\n\n\n_add_subcommands()\n", "step-5": "\"\"\"\nMain CLI endpoint for GeoCube\n\"\"\"\nimport importlib.metadata\n\nimport click\nfrom click import group\n\nimport geocube.cli.commands as cmd_modules\nfrom geocube import show_versions\n\nCONTEXT_SETTINGS = {\n \"help_option_names\": [\"-h\", \"--help\"],\n \"token_normalize_func\": lambda x: x.replace(\"-\", \"_\"),\n}\n\n\ndef check_version(ctx, _, value):\n \"\"\"\n Print current version, and check for latest version.\n\n Called via 'geocube --version'\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n\n click.echo(f\"geocube v{importlib.metadata.version('geocube')}\")\n\n ctx.exit()\n\n\ndef cli_show_version(ctx, _, value):\n \"\"\"\n Print debugging version information.\n\n :param ctx: Application context object (click.Context)\n :param value: Passed in by Click\n :return None\n \"\"\"\n if not value or ctx.resilient_parsing:\n return\n\n show_versions()\n\n ctx.exit()\n\n\n@group(context_settings=CONTEXT_SETTINGS)\n@click.option(\n \"-v\",\n \"--version\",\n is_flag=True,\n is_eager=True,\n expose_value=False,\n callback=check_version,\n help=\"Show the current version\",\n)\n@click.option(\n \"--show-versions\",\n is_flag=True,\n is_eager=True,\n expose_value=False,\n callback=cli_show_version,\n help=\"Show debugging version information\",\n)\ndef geocube():\n \"\"\"Top-level command and entry point into the GeoCube CLI\"\"\"\n\n\ndef _add_subcommands():\n \"\"\"\n Individual commands (and sub-commands) are encapsulated in separate files\n under /commands. Collect these command groups, and add them underneath the\n top-level command (geocube).\n \"\"\"\n geocube.add_command(cmd_modules.make_geocube.make_geocube)\n\n\n_add_subcommands()\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
# -*- coding: utf-8 -*- """Digital Forensics Virtual File System (dfVFS). dfVFS, or Digital Forensics Virtual File System, is a Python module that provides read-only access to file-system objects from various storage media types and file formats. """
normal
{ "blob_id": "f7d3096d669946e13186a893ffc53067e0fd0a0a", "index": 1065, "step-1": "<mask token>\n", "step-2": "# -*- coding: utf-8 -*-\n\"\"\"Digital Forensics Virtual File System (dfVFS).\n\ndfVFS, or Digital Forensics Virtual File System, is a Python module\nthat provides read-only access to file-system objects from various\nstorage media types and file formats.\n\"\"\"\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
import sys minus = "-" plus = "+" divis = "/" multi = "*" power = "^" unary = "-" br_op = "(" br_cl = ")" operations = [power, divis, multi, minus, plus] digits = ['1','2','3','4','5','6','7','8','9','0','.'] def find_close_pos(the_string): open_count = 0 close_count = 0 for i in range(len(the_string)): if the_string[i] == br_op : open_count = open_count + 1 if the_string[i] == br_cl : close_count = close_count + 1 if close_count == open_count: return i def parse(the_string): parsed_string = [] number = "" for i in range(len(the_string)): if the_string[i] == "-" and i == 0: ### string = "-2 + blablabla" number += the_string[i] elif the_string[i] in operations and the_string[i-1] not in operations: ### ^ parsed_string.append(float(number)) parsed_string.append(the_string[i]) number = "" elif the_string[i] == "-" and the_string[i-1] in operations: ### ^- number += the_string[i] elif the_string[i] in digits: ### 2 number += the_string[i] parsed_string.append(float(number)) return parsed_string def single_operation(parsed_string): if parsed_string[1] == "+": return parsed_string[0] + parsed_string[2] if parsed_string[1] == "-": return parsed_string[0] - parsed_string[2] if parsed_string[1] == "/": return parsed_string[0] / parsed_string[2] if parsed_string[1] == "*": return parsed_string[0] * parsed_string[2] if parsed_string[1] == "^": return parsed_string[0] ** parsed_string[2] def compute(the_string): try: the_string = the_string.replace(" ", "") ### delete space chars while br_op in the_string : open_pos = the_string.index(br_op) close_pos = find_close_pos(the_string) old = the_string[open_pos:close_pos+1] new = compute(the_string[open_pos+1:close_pos]) the_string = the_string.replace(old, str(new)) parsed_string = parse(the_string) for operation in operations: while operation in parsed_string: pos = len(parsed_string) - parsed_string[::-1].index(operation) res = single_operation(parsed_string[pos-2:pos+1]) parsed_string[pos-2:pos+1] = [res] return parsed_string[0] except: pass def read_file(path): lines = [ line for line in open (path,'r') if line.strip() != "" ] return lines def main(path): try: for line in read_file(path): print str(round(float(compute(line)),5)).rstrip('0').rstrip('.') except: print line print "Unexpected error:", sys.exc_info()[0] if __name__ == '__main__': path = sys.argv[1] main(path)
normal
{ "blob_id": "c0c8f40e43f1c27f8efa47cfc366c6076b77b9c9", "index": 9337, "step-1": "import sys\n\nminus = \"-\"\nplus = \"+\"\ndivis = \"/\"\nmulti = \"*\"\npower = \"^\"\nunary = \"-\"\nbr_op = \"(\"\nbr_cl = \")\"\n\noperations = [power, divis, multi, minus, plus]\ndigits = ['1','2','3','4','5','6','7','8','9','0','.']\n\ndef find_close_pos(the_string):\n\topen_count = 0\n\tclose_count = 0\n\tfor i in range(len(the_string)):\n\t\tif the_string[i] == br_op :\n\t\t\topen_count = open_count + 1\n\t\tif the_string[i] == br_cl :\n\t\t\tclose_count = close_count + 1\n\t\t\tif close_count == open_count:\n\t\t\t\treturn i\n\ndef parse(the_string):\n\tparsed_string = []\n\tnumber = \"\"\n\tfor i in range(len(the_string)):\n\t\tif the_string[i] == \"-\" and i == 0: ### string = \"-2 + blablabla\"\n\t\t\tnumber += the_string[i]\n\t\telif the_string[i] in operations and the_string[i-1] not in operations: ### ^\n\t\t\tparsed_string.append(float(number))\n\t\t\tparsed_string.append(the_string[i])\n\t\t\tnumber = \"\"\n\t\telif the_string[i] == \"-\" and the_string[i-1] in operations: ### ^-\n\t\t\tnumber += the_string[i]\n\t\telif the_string[i] in digits: ### 2\n\t\t\tnumber += the_string[i]\n\tparsed_string.append(float(number))\n\treturn parsed_string\n\ndef single_operation(parsed_string):\n\tif parsed_string[1] == \"+\":\n\t\treturn parsed_string[0] + parsed_string[2]\n\tif parsed_string[1] == \"-\":\n\t\treturn parsed_string[0] - parsed_string[2]\n\tif parsed_string[1] == \"/\":\n\t\treturn parsed_string[0] / parsed_string[2]\n\tif parsed_string[1] == \"*\":\n\t\treturn parsed_string[0] * parsed_string[2]\n\tif parsed_string[1] == \"^\":\n\t\treturn parsed_string[0] ** parsed_string[2]\n\ndef compute(the_string):\n\ttry:\n\t\tthe_string = the_string.replace(\" \", \"\") ### delete space chars\n\t\twhile br_op in the_string : \n\t\t\topen_pos = the_string.index(br_op)\n\t\t\tclose_pos = find_close_pos(the_string)\n\t\t\told = the_string[open_pos:close_pos+1]\n\t\t\tnew = compute(the_string[open_pos+1:close_pos])\n\t\t\tthe_string = the_string.replace(old, str(new))\n\t\tparsed_string = parse(the_string)\n\t\tfor operation in operations:\n\t\t\twhile operation in parsed_string:\n\t\t\t\tpos = len(parsed_string) - parsed_string[::-1].index(operation)\n\t\t\t\tres = single_operation(parsed_string[pos-2:pos+1])\n\t\t\t\tparsed_string[pos-2:pos+1] = [res]\n\t\treturn parsed_string[0]\n\texcept:\n\t\tpass\n\ndef read_file(path):\n\tlines = [ line for line in open (path,'r') if line.strip() != \"\" ]\n\treturn lines\n\ndef main(path):\n\ttry:\n\t\tfor line in read_file(path):\n\t\t\tprint str(round(float(compute(line)),5)).rstrip('0').rstrip('.')\n\texcept:\n\t\tprint line\n\t\tprint \"Unexpected error:\", sys.exc_info()[0]\n\nif __name__ == '__main__':\n\tpath = sys.argv[1]\n\tmain(path)\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
class Node: <|reserved_special_token_0|> class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return [] if not root.children: return [root.val] result = [] for child in root.children: result += self.postorder(child) result += [root.val] return result <|reserved_special_token_0|> <|reserved_special_token_1|> class Node: def __init__(self, val, children): self.val = val self.children = children class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return [] if not root.children: return [root.val] result = [] for child in root.children: result += self.postorder(child) result += [root.val] return result <|reserved_special_token_0|> <|reserved_special_token_1|> class Node: def __init__(self, val, children): self.val = val self.children = children class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return [] if not root.children: return [root.val] result = [] for child in root.children: result += self.postorder(child) result += [root.val] return result <|reserved_special_token_0|> print(result) <|reserved_special_token_1|> class Node: def __init__(self, val, children): self.val = val self.children = children class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return [] if not root.children: return [root.val] result = [] for child in root.children: result += self.postorder(child) result += [root.val] return result n5 = Node(5, None) n6 = Node(6, None) n3 = Node(2, None) n4 = Node(4, None) n2 = Node(3, [n5, n6]) n1 = Node(1, [n2, n3, n4]) s = Solution() result = s.postorder(n1) print(result) <|reserved_special_token_1|> # Definition for a Node. class Node: def __init__(self, val, children): self.val = val self.children = children class Solution(object): def postorder(self, root): """ :type root: Node :rtype: List[int] """ if not root: return([]) if not root.children: return([root.val]) result = [] for child in root.children: result += self.postorder(child) result += [root.val] return(result) n5 = Node(5,None) n6 = Node(6,None) n3 = Node(2,None) n4 = Node(4,None) n2 = Node(3,[n5,n6]) n1 = Node(1,[n2,n3,n4]) s = Solution() result = s.postorder(n1) print(result)
flexible
{ "blob_id": "93ec15a37bd5f022e8f6e226e3bf0e91cc0457c6", "index": 2178, "step-1": "class Node:\n <mask token>\n\n\nclass Solution(object):\n\n def postorder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n if not root.children:\n return [root.val]\n result = []\n for child in root.children:\n result += self.postorder(child)\n result += [root.val]\n return result\n\n\n<mask token>\n", "step-2": "class Node:\n\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\n\nclass Solution(object):\n\n def postorder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n if not root.children:\n return [root.val]\n result = []\n for child in root.children:\n result += self.postorder(child)\n result += [root.val]\n return result\n\n\n<mask token>\n", "step-3": "class Node:\n\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\n\nclass Solution(object):\n\n def postorder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n if not root.children:\n return [root.val]\n result = []\n for child in root.children:\n result += self.postorder(child)\n result += [root.val]\n return result\n\n\n<mask token>\nprint(result)\n", "step-4": "class Node:\n\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\n\nclass Solution(object):\n\n def postorder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[int]\n \"\"\"\n if not root:\n return []\n if not root.children:\n return [root.val]\n result = []\n for child in root.children:\n result += self.postorder(child)\n result += [root.val]\n return result\n\n\nn5 = Node(5, None)\nn6 = Node(6, None)\nn3 = Node(2, None)\nn4 = Node(4, None)\nn2 = Node(3, [n5, n6])\nn1 = Node(1, [n2, n3, n4])\ns = Solution()\nresult = s.postorder(n1)\nprint(result)\n", "step-5": "# Definition for a Node.\nclass Node:\n def __init__(self, val, children):\n self.val = val\n self.children = children\n\nclass Solution(object):\n def postorder(self, root):\n \"\"\"\n :type root: Node\n :rtype: List[int]\n \"\"\"\n if not root:\n return([])\n if not root.children:\n return([root.val])\n result = []\n for child in root.children:\n result += self.postorder(child)\n result += [root.val]\n return(result)\n\n \nn5 = Node(5,None)\nn6 = Node(6,None)\nn3 = Node(2,None)\nn4 = Node(4,None)\nn2 = Node(3,[n5,n6])\nn1 = Node(1,[n2,n3,n4])\n\ns = Solution()\nresult = s.postorder(n1)\nprint(result)\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> def get_paths(debug, dataset): if debug and dataset == 'OASIS': project_wd = os.getcwd() project_data = os.path.join(project_wd, 'data') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BANC': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BOSTON': project_wd = os.getcwd() project_data = None project_sink = None elif debug and dataset == 'BANC_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif debug and dataset == 'UKBIO_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif not debug and dataset == 'OASIS': project_wd = '/code' project_data = os.path.join(os.sep, 'NaN', 'data') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BANC': project_wd = '/code' project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BOSTON': project_wd = '/code' project_data = None project_sink = None elif not debug and (dataset == 'BANC_freesurf' or dataset == 'UKBIO_freesurf' or dataset == 'freesurf_combined'): project_wd = '/code' project_data = os.path.join(os.sep, 'code', 'BayOptPy', 'freesurfer_preprocess') project_sink = None else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Code Path: %s' % project_wd) print('Data Path: %s' % project_data) print('Data Out: %s' % project_sink) return project_wd, project_data, project_sink def get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute) output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute): if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis == 'feat_combi' or analysis == 'vanilla_combi' or analysis == 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or analysis == 'uniform_dist'): if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) elif analysis == 'population': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) elif analysis == 'mutation': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover)) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % ( mutation, crossover)) else: raise IOError('Analysis path not defined. Passed analysis was %s' % analysis) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis): """ This function gets the original dataset and transforms it into a uniformly distributed dataset. """ project_wd, project_data, project_sink = get_paths(debug, dataset) demographics, imgs, dataframe = get_data(project_data, dataset, debug, project_wd, resamplefactor, raw=raw, analysis=analysis) demographics['age_int'] = demographics['age'].astype('int32', copy=False) age_range = np.arange(demographics['age'].min(), demographics['age'].max()) max_n = 14 age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89] age_range = np.setdiff1d(age_range, age_to_remove) ids_to_use = [] for age in age_range: ids_to_use.append(demographics.index[demographics['age_int'] == age ].tolist()[:max_n]) ids_to_use = [item for sublist in ids_to_use for item in sublist] demographics = demographics[demographics.index.isin(ids_to_use)] dataframe = dataframe.loc[demographics['id']] print('Shape of the new demographics:') print(demographics.shape) print('Oldest %d and youngest %d subject' % (demographics['age_int']. max(), demographics['age_int'].min())) print('Number of age bins %d' % len(demographics['age_int'].unique())) return demographics, dataframe def get_best_pipeline_paths(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): output_path = get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute) checkpoint_path = os.path.join(output_path, 'checkpoint_folder') if os.path.exists(checkpoint_path): shutil.rmtree(checkpoint_path) print('Deleted pre-exiting checkpoint folder') if not os.path.exists(checkpoint_path): os.makedirs(checkpoint_path) print('Creating checkpoint folder') return checkpoint_path def drop_missing_features(dataframe): """ This function takes a dataframe and removes the already defined missing columns from the dataframe. """ missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1', 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles', 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf', 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities', 'Left-non-WM-hypointensities', 'non-WM-hypointensities', 'Right-WM-hypointensities', 'Left-WM-hypointensities', 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus', 'Left-choroid-plexus', 'Left-Lateral-Ventricle', 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent'] cleaned_df = dataframe.drop(missing_features, axis=1) return cleaned_df def get_data_covariates(dataPath, rawsubjectsId, dataset): if dataset == 'OASIS': demographics = pd.read_csv(os.path.join(dataPath, 'oasis_cross-sectional.csv')) demographics = demographics.sort_values('ID') missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = demographics.loc[(demographics['CDR'] == 0) | demographics['CDR'].isnull(), 'ID'] demographics = demographics.loc[demographics['ID'].isin(selectedSubId)] elif dataset == 'BANC': column_names = ['ID', 'original_dataset', 'sex', 'Age'] demographics = pd.read_csv(os.path.join(dataPath, 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names) missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = rawsubjectsId else: raise ValueError('Analysis for this dataset is not yet implemented!') assert len(selectedSubId) == len(demographics) return demographics, selectedSubId <|reserved_special_token_0|> def _load_nibabel(filePath): img = nib.load(os.path.join(filePath)) return img def get_config_dictionary(): regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': { 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': { 'max_depth': range(1, 11), 'min_samples_split': range(2, 21), 'min_samples_leaf': range(1, 21)}, 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]}, 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]}, 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive', 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [ 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {}, 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05, 0.001), 'score_func': {'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile': range(1, 100), 'score_func': { 'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.VarianceThreshold': {'threshold': [ 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}} return regressor_config_dic def get_mean_age(df): mean_age = df['Age'].mean() std_age = df['Age'].std() print('Mean Age %.2f +- %.2f' % (mean_age, std_age)) <|reserved_special_token_0|> def get_mae_for_all_generations(dataset, random_seed, generations, config_dict, tpot_path): """ Get the MAE values for both the training and test dataset :return: """ saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict, generations)) logbook = joblib.load(saved_path) gen = list(logbook['log'].keys()) print('There are %d optminal pipelines' % len(gen)) print('These are the best pipelines') for generation in gen: print(logbook['log'][generation]['pipeline_name']) all_mae_test = [] all_mae_train = [] pipeline_complexity = [] curr_gen_idx = 0 for generation in range(generations): if generation == gen[curr_gen_idx]: all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_test_mae'])) all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_score'])) pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx] ]['pipeline_sklearn_obj'].named_steps.keys())) if len(gen) > 1 and len(gen) > curr_gen_idx + 1: curr_gen_idx += 1 else: all_mae_test.append(all_mae_test[-1]) all_mae_train.append(all_mae_train[-1]) pipeline_complexity.append(pipeline_complexity[-1]) pipeline_complexity = np.array(pipeline_complexity) return all_mae_test, all_mae_train, pipeline_complexity <|reserved_special_token_0|> def create_age_histogram(df, dataset): """ Get an age array and plot and save the age histogram for the analysed sample """ set_publication_style() plt.figure() path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset min_age = df['age'].min() max_age = df['age'].max() plt.hist(df['age'], bins=65, range=(min_age, max_age)) plt.xlabel('Age') plt.ylabel('# of Subjects') plt.legend() plt.savefig(path_to_save) plt.close() def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title= None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' cm = confusion_matrix(y_true, y_pred) labels = [int(x) for x in unique_labels(y_true, y_pred)] classes = classes[labels] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print('Normalized confusion matrix') else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel= 'True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2.0 for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center', color='white' if cm[i, j] > thresh else 'black') fig.tight_layout() return ax, cm def plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ fig, ax = plt.subplots() im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean. shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '{0:.2f} ± {1:.2f}' thresh = cm_mean.max() / 2.0 for i in range(cm_mean.shape[0]): for j in range(cm_mean.shape[1]): ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha= 'center', va='center', color='white' if cm_mean[i, j] > thresh else 'black') fig.tight_layout() return ax def plot_predicted_vs_true(true_y, predicted_y, save_path, metric): fig = plt.figure() plt.scatter(true_y, predicted_y, alpha=0.5) plt.ylabel('Predicted %s' % metric) plt.xlabel('True %s' % metric) plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y), max(true_y)), alpha=0.3, linestyle='--', color='b') if metric == 'Age': plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.savefig(save_path) plt.close() <|reserved_special_token_0|> def ttest_ind_corrected(performance_a, performance_b, k=10, r=10): """Corrected repeated k-fold cv test. The test assumes that the classifiers were evaluated using cross validation. Ref: Bouckaert, Remco R., and Eibe Frank. "Evaluating the replicability of significance tests for comparing learning algorithms." Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004 Args: performance_a: performances from classifier A performance_b: performances from classifier B k: number of folds r: number of repetitions Returns: t: t-statistic of the corrected test. prob: p-value of the corrected test. """ df = k * r - 1 x = performance_a - performance_b m = np.mean(x) sigma_2 = np.var(x, ddof=1) denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2) with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(m, denom) prob = stats.t.sf(np.abs(t), df) * 2 return t, prob <|reserved_special_token_1|> <|reserved_special_token_0|> def get_paths(debug, dataset): if debug and dataset == 'OASIS': project_wd = os.getcwd() project_data = os.path.join(project_wd, 'data') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BANC': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BOSTON': project_wd = os.getcwd() project_data = None project_sink = None elif debug and dataset == 'BANC_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif debug and dataset == 'UKBIO_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif not debug and dataset == 'OASIS': project_wd = '/code' project_data = os.path.join(os.sep, 'NaN', 'data') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BANC': project_wd = '/code' project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BOSTON': project_wd = '/code' project_data = None project_sink = None elif not debug and (dataset == 'BANC_freesurf' or dataset == 'UKBIO_freesurf' or dataset == 'freesurf_combined'): project_wd = '/code' project_data = os.path.join(os.sep, 'code', 'BayOptPy', 'freesurfer_preprocess') project_sink = None else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Code Path: %s' % project_wd) print('Data Path: %s' % project_data) print('Data Out: %s' % project_sink) return project_wd, project_data, project_sink def get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute) output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute): if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis == 'feat_combi' or analysis == 'vanilla_combi' or analysis == 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or analysis == 'uniform_dist'): if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) elif analysis == 'population': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) elif analysis == 'mutation': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover)) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % ( mutation, crossover)) else: raise IOError('Analysis path not defined. Passed analysis was %s' % analysis) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis): """ This function gets the original dataset and transforms it into a uniformly distributed dataset. """ project_wd, project_data, project_sink = get_paths(debug, dataset) demographics, imgs, dataframe = get_data(project_data, dataset, debug, project_wd, resamplefactor, raw=raw, analysis=analysis) demographics['age_int'] = demographics['age'].astype('int32', copy=False) age_range = np.arange(demographics['age'].min(), demographics['age'].max()) max_n = 14 age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89] age_range = np.setdiff1d(age_range, age_to_remove) ids_to_use = [] for age in age_range: ids_to_use.append(demographics.index[demographics['age_int'] == age ].tolist()[:max_n]) ids_to_use = [item for sublist in ids_to_use for item in sublist] demographics = demographics[demographics.index.isin(ids_to_use)] dataframe = dataframe.loc[demographics['id']] print('Shape of the new demographics:') print(demographics.shape) print('Oldest %d and youngest %d subject' % (demographics['age_int']. max(), demographics['age_int'].min())) print('Number of age bins %d' % len(demographics['age_int'].unique())) return demographics, dataframe def get_best_pipeline_paths(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): output_path = get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute) checkpoint_path = os.path.join(output_path, 'checkpoint_folder') if os.path.exists(checkpoint_path): shutil.rmtree(checkpoint_path) print('Deleted pre-exiting checkpoint folder') if not os.path.exists(checkpoint_path): os.makedirs(checkpoint_path) print('Creating checkpoint folder') return checkpoint_path def drop_missing_features(dataframe): """ This function takes a dataframe and removes the already defined missing columns from the dataframe. """ missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1', 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles', 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf', 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities', 'Left-non-WM-hypointensities', 'non-WM-hypointensities', 'Right-WM-hypointensities', 'Left-WM-hypointensities', 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus', 'Left-choroid-plexus', 'Left-Lateral-Ventricle', 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent'] cleaned_df = dataframe.drop(missing_features, axis=1) return cleaned_df def get_data_covariates(dataPath, rawsubjectsId, dataset): if dataset == 'OASIS': demographics = pd.read_csv(os.path.join(dataPath, 'oasis_cross-sectional.csv')) demographics = demographics.sort_values('ID') missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = demographics.loc[(demographics['CDR'] == 0) | demographics['CDR'].isnull(), 'ID'] demographics = demographics.loc[demographics['ID'].isin(selectedSubId)] elif dataset == 'BANC': column_names = ['ID', 'original_dataset', 'sex', 'Age'] demographics = pd.read_csv(os.path.join(dataPath, 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names) missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = rawsubjectsId else: raise ValueError('Analysis for this dataset is not yet implemented!') assert len(selectedSubId) == len(demographics) return demographics, selectedSubId def _multiprocessing_resample(img, target_affine): resampled_img = image.resample_img(img, target_affine=target_affine, interpolation='nearest') return resampled_img def _load_nibabel(filePath): img = nib.load(os.path.join(filePath)) return img def get_config_dictionary(): regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': { 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': { 'max_depth': range(1, 11), 'min_samples_split': range(2, 21), 'min_samples_leaf': range(1, 21)}, 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]}, 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]}, 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive', 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [ 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {}, 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05, 0.001), 'score_func': {'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile': range(1, 100), 'score_func': { 'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.VarianceThreshold': {'threshold': [ 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}} return regressor_config_dic def get_mean_age(df): mean_age = df['Age'].mean() std_age = df['Age'].std() print('Mean Age %.2f +- %.2f' % (mean_age, std_age)) <|reserved_special_token_0|> def get_mae_for_all_generations(dataset, random_seed, generations, config_dict, tpot_path): """ Get the MAE values for both the training and test dataset :return: """ saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict, generations)) logbook = joblib.load(saved_path) gen = list(logbook['log'].keys()) print('There are %d optminal pipelines' % len(gen)) print('These are the best pipelines') for generation in gen: print(logbook['log'][generation]['pipeline_name']) all_mae_test = [] all_mae_train = [] pipeline_complexity = [] curr_gen_idx = 0 for generation in range(generations): if generation == gen[curr_gen_idx]: all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_test_mae'])) all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_score'])) pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx] ]['pipeline_sklearn_obj'].named_steps.keys())) if len(gen) > 1 and len(gen) > curr_gen_idx + 1: curr_gen_idx += 1 else: all_mae_test.append(all_mae_test[-1]) all_mae_train.append(all_mae_train[-1]) pipeline_complexity.append(pipeline_complexity[-1]) pipeline_complexity = np.array(pipeline_complexity) return all_mae_test, all_mae_train, pipeline_complexity <|reserved_special_token_0|> def create_age_histogram(df, dataset): """ Get an age array and plot and save the age histogram for the analysed sample """ set_publication_style() plt.figure() path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset min_age = df['age'].min() max_age = df['age'].max() plt.hist(df['age'], bins=65, range=(min_age, max_age)) plt.xlabel('Age') plt.ylabel('# of Subjects') plt.legend() plt.savefig(path_to_save) plt.close() def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title= None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' cm = confusion_matrix(y_true, y_pred) labels = [int(x) for x in unique_labels(y_true, y_pred)] classes = classes[labels] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print('Normalized confusion matrix') else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel= 'True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2.0 for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center', color='white' if cm[i, j] > thresh else 'black') fig.tight_layout() return ax, cm def plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ fig, ax = plt.subplots() im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean. shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '{0:.2f} ± {1:.2f}' thresh = cm_mean.max() / 2.0 for i in range(cm_mean.shape[0]): for j in range(cm_mean.shape[1]): ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha= 'center', va='center', color='white' if cm_mean[i, j] > thresh else 'black') fig.tight_layout() return ax def plot_predicted_vs_true(true_y, predicted_y, save_path, metric): fig = plt.figure() plt.scatter(true_y, predicted_y, alpha=0.5) plt.ylabel('Predicted %s' % metric) plt.xlabel('True %s' % metric) plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y), max(true_y)), alpha=0.3, linestyle='--', color='b') if metric == 'Age': plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.savefig(save_path) plt.close() <|reserved_special_token_0|> def ttest_ind_corrected(performance_a, performance_b, k=10, r=10): """Corrected repeated k-fold cv test. The test assumes that the classifiers were evaluated using cross validation. Ref: Bouckaert, Remco R., and Eibe Frank. "Evaluating the replicability of significance tests for comparing learning algorithms." Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004 Args: performance_a: performances from classifier A performance_b: performances from classifier B k: number of folds r: number of repetitions Returns: t: t-statistic of the corrected test. prob: p-value of the corrected test. """ df = k * r - 1 x = performance_a - performance_b m = np.mean(x) sigma_2 = np.var(x, ddof=1) denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2) with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(m, denom) prob = stats.t.sf(np.abs(t), df) * 2 return t, prob <|reserved_special_token_1|> <|reserved_special_token_0|> def get_paths(debug, dataset): if debug and dataset == 'OASIS': project_wd = os.getcwd() project_data = os.path.join(project_wd, 'data') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BANC': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BOSTON': project_wd = os.getcwd() project_data = None project_sink = None elif debug and dataset == 'BANC_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif debug and dataset == 'UKBIO_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif not debug and dataset == 'OASIS': project_wd = '/code' project_data = os.path.join(os.sep, 'NaN', 'data') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BANC': project_wd = '/code' project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BOSTON': project_wd = '/code' project_data = None project_sink = None elif not debug and (dataset == 'BANC_freesurf' or dataset == 'UKBIO_freesurf' or dataset == 'freesurf_combined'): project_wd = '/code' project_data = os.path.join(os.sep, 'code', 'BayOptPy', 'freesurfer_preprocess') project_sink = None else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Code Path: %s' % project_wd) print('Data Path: %s' % project_data) print('Data Out: %s' % project_sink) return project_wd, project_data, project_sink def get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute) output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute): if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis == 'feat_combi' or analysis == 'vanilla_combi' or analysis == 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or analysis == 'uniform_dist'): if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) elif analysis == 'population': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) elif analysis == 'mutation': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover)) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % ( mutation, crossover)) else: raise IOError('Analysis path not defined. Passed analysis was %s' % analysis) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis): """ This function gets the original dataset and transforms it into a uniformly distributed dataset. """ project_wd, project_data, project_sink = get_paths(debug, dataset) demographics, imgs, dataframe = get_data(project_data, dataset, debug, project_wd, resamplefactor, raw=raw, analysis=analysis) demographics['age_int'] = demographics['age'].astype('int32', copy=False) age_range = np.arange(demographics['age'].min(), demographics['age'].max()) max_n = 14 age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89] age_range = np.setdiff1d(age_range, age_to_remove) ids_to_use = [] for age in age_range: ids_to_use.append(demographics.index[demographics['age_int'] == age ].tolist()[:max_n]) ids_to_use = [item for sublist in ids_to_use for item in sublist] demographics = demographics[demographics.index.isin(ids_to_use)] dataframe = dataframe.loc[demographics['id']] print('Shape of the new demographics:') print(demographics.shape) print('Oldest %d and youngest %d subject' % (demographics['age_int']. max(), demographics['age_int'].min())) print('Number of age bins %d' % len(demographics['age_int'].unique())) return demographics, dataframe def get_best_pipeline_paths(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): output_path = get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute) checkpoint_path = os.path.join(output_path, 'checkpoint_folder') if os.path.exists(checkpoint_path): shutil.rmtree(checkpoint_path) print('Deleted pre-exiting checkpoint folder') if not os.path.exists(checkpoint_path): os.makedirs(checkpoint_path) print('Creating checkpoint folder') return checkpoint_path def drop_missing_features(dataframe): """ This function takes a dataframe and removes the already defined missing columns from the dataframe. """ missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1', 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles', 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf', 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities', 'Left-non-WM-hypointensities', 'non-WM-hypointensities', 'Right-WM-hypointensities', 'Left-WM-hypointensities', 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus', 'Left-choroid-plexus', 'Left-Lateral-Ventricle', 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent'] cleaned_df = dataframe.drop(missing_features, axis=1) return cleaned_df def get_data_covariates(dataPath, rawsubjectsId, dataset): if dataset == 'OASIS': demographics = pd.read_csv(os.path.join(dataPath, 'oasis_cross-sectional.csv')) demographics = demographics.sort_values('ID') missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = demographics.loc[(demographics['CDR'] == 0) | demographics['CDR'].isnull(), 'ID'] demographics = demographics.loc[demographics['ID'].isin(selectedSubId)] elif dataset == 'BANC': column_names = ['ID', 'original_dataset', 'sex', 'Age'] demographics = pd.read_csv(os.path.join(dataPath, 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names) missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = rawsubjectsId else: raise ValueError('Analysis for this dataset is not yet implemented!') assert len(selectedSubId) == len(demographics) return demographics, selectedSubId def _multiprocessing_resample(img, target_affine): resampled_img = image.resample_img(img, target_affine=target_affine, interpolation='nearest') return resampled_img def _load_nibabel(filePath): img = nib.load(os.path.join(filePath)) return img def get_config_dictionary(): regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': { 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': { 'max_depth': range(1, 11), 'min_samples_split': range(2, 21), 'min_samples_leaf': range(1, 21)}, 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]}, 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]}, 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive', 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [ 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {}, 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05, 0.001), 'score_func': {'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile': range(1, 100), 'score_func': { 'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.VarianceThreshold': {'threshold': [ 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}} return regressor_config_dic def get_mean_age(df): mean_age = df['Age'].mean() std_age = df['Age'].std() print('Mean Age %.2f +- %.2f' % (mean_age, std_age)) def get_data(project_data, dataset, debug, project_wd, resamplefactor, raw, analysis): """ Load the csv files and return :param project_data: :param dataset: :param debug: :param project_wd: :param resamplefactor: :raw: Which type of fressesfurfer should we analyse (the raw, where both datasets have not been matched or the not raw where the number of columns between dataset is the same) :return: demographics: :return: demographics: :return: dataframe.values: Just the numeric values of the dataframe """ if dataset == 'freesurf_combined' and raw == True: raise ValueError('The combined analysis cannot use the raw dataset') print('Loading Brain image data') elif dataset == 'OASIS': fileList = os.listdir(project_data) rawsubjectsId = [re.sub('^smwc1(.*?)\\_mpr-1_anon.nii$', '\\1', file) for file in fileList if file.endswith('.nii')] demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset) get_mean_age(demographics) imgs = [nib.load(os.path.join(project_data, 'smwc1%s_mpr-1_anon.nii' % subject)) for subject in tqdm( selectedSubId)] elif dataset == 'BANC': project_data_path = os.path.join(project_data, 'wm_data') fileList = os.listdir(project_data_path) rawsubjectsId = [file[5:12] for file in fileList if file.endswith( '.nii.gz')] demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset) get_mean_age(demographics) subjectsFile = [os.path.join(project_data_path, file) for file in fileList if file[5:12] in selectedSubId] with Pool() as p: imgs = list(tqdm(p.imap(_load_nibabel, subjectsFile), total=len (selectedSubId))) elif dataset == 'BANC_freesurf' and raw == True: freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'BANC', 'aparc_aseg_stats_BANC.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif dataset == 'UKBIO_freesurf' and raw == False and not analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO.csv'), delimiter=',') ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',', index_col=False) demographics = ukbio_full_df[['age', 'sex', 'id']].copy() freesurf_df = freesurf_df.set_index('id') return demographics, None, freesurf_df elif dataset == 'BANC_freesurf' and raw == False and not analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif dataset == 'UKBIO_freesurf' and raw == True and not analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') freesurf_df = freesurf_df.drop(columns='id.4844') demographics = freesurf_df[['age', 'sex', 'id']].copy() freesurf_df = freesurf_df.set_index('id') return demographics, None, freesurf_df elif dataset == 'UKBIO_freesurf' and raw == False and analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO_summary.csv'), delimiter=',') ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') demographics = ukbio_full_df[['age', 'sex', 'id']].copy() return demographics, None, freesurf_df elif dataset == 'BANC_freesurf' and raw == False and analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC_summary.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif dataset == 'freesurf_combined': ukbio_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO.csv'), delimiter=',', index_col=0) banc_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0) ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') rawsubjectsId = banc_df.index banc_demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') ukbio_demographics = ukbio_full_df[['age', 'sex', 'id']].copy() freesurfer_df = pd.concat([ukbio_df, banc_df]) tmp = banc_demographics.drop('original_dataset', axis=1) tmp.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) tmp['sex'] = tmp['sex'].map({'F': 'female', 'M': 'male'}) tmp['dataset'] = 'banc' ukbio_demographics['dataset'] = 'ukbio' demographics = pd.concat([ukbio_demographics, tmp], sort=False) bins = 17, 30, 40, 50, 60, 70, 80, 90 group_labels = range(1, len(bins)) demographics['age_band'] = pd.cut(demographics['age'], bins, labels =group_labels) sex_age_group = demographics.groupby(['sex', 'age_band']) demographics['stratify'] = sex_age_group.grouper.group_info[0] + 1 return demographics, None, freesurfer_df else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Resample the dataset by a factor of %d' % resamplefactor) print('Original image size: %s' % (imgs[0].shape,)) resampleby2affine = np.array([[resamplefactor, 1, 1, 1], [1, resamplefactor, 1, 1], [1, 1, resamplefactor, 1], [1, 1, 1, 1]]) target_affine = np.multiply(imgs[0].affine, resampleby2affine) print('Resampling Images') with Pool() as p: args = partial(_multiprocessing_resample, target_affine=target_affine) resampledimgs = list(tqdm(p.imap(args, imgs), total=len(imgs))) print('Resampled image size: %s' % (resampledimgs[0].shape,)) print('Compute brain mask') MeanImgMask = masking.compute_multi_epi_mask(resampledimgs, lower_cutoff=0.001, upper_cutoff=0.85, opening=False) maskedData = [masking.apply_mask(img, MeanImgMask) for img in resampledimgs ] if debug: mask_path = os.path.join(project_wd, 'BayOptPy', 'tpot') print('Saving brain mask: %s' % mask_path) nib.save(MeanImgMask, os.path.join(mask_path, 'mask_%s.nii.gz' % dataset)) print('Applied mask to the dataset') maskedData = np.array(maskedData) return demographics, imgs, maskedData def get_mae_for_all_generations(dataset, random_seed, generations, config_dict, tpot_path): """ Get the MAE values for both the training and test dataset :return: """ saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict, generations)) logbook = joblib.load(saved_path) gen = list(logbook['log'].keys()) print('There are %d optminal pipelines' % len(gen)) print('These are the best pipelines') for generation in gen: print(logbook['log'][generation]['pipeline_name']) all_mae_test = [] all_mae_train = [] pipeline_complexity = [] curr_gen_idx = 0 for generation in range(generations): if generation == gen[curr_gen_idx]: all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_test_mae'])) all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_score'])) pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx] ]['pipeline_sklearn_obj'].named_steps.keys())) if len(gen) > 1 and len(gen) > curr_gen_idx + 1: curr_gen_idx += 1 else: all_mae_test.append(all_mae_test[-1]) all_mae_train.append(all_mae_train[-1]) pipeline_complexity.append(pipeline_complexity[-1]) pipeline_complexity = np.array(pipeline_complexity) return all_mae_test, all_mae_train, pipeline_complexity <|reserved_special_token_0|> def create_age_histogram(df, dataset): """ Get an age array and plot and save the age histogram for the analysed sample """ set_publication_style() plt.figure() path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset min_age = df['age'].min() max_age = df['age'].max() plt.hist(df['age'], bins=65, range=(min_age, max_age)) plt.xlabel('Age') plt.ylabel('# of Subjects') plt.legend() plt.savefig(path_to_save) plt.close() def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title= None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' cm = confusion_matrix(y_true, y_pred) labels = [int(x) for x in unique_labels(y_true, y_pred)] classes = classes[labels] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print('Normalized confusion matrix') else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel= 'True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2.0 for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center', color='white' if cm[i, j] > thresh else 'black') fig.tight_layout() return ax, cm def plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ fig, ax = plt.subplots() im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean. shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '{0:.2f} ± {1:.2f}' thresh = cm_mean.max() / 2.0 for i in range(cm_mean.shape[0]): for j in range(cm_mean.shape[1]): ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha= 'center', va='center', color='white' if cm_mean[i, j] > thresh else 'black') fig.tight_layout() return ax def plot_predicted_vs_true(true_y, predicted_y, save_path, metric): fig = plt.figure() plt.scatter(true_y, predicted_y, alpha=0.5) plt.ylabel('Predicted %s' % metric) plt.xlabel('True %s' % metric) plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y), max(true_y)), alpha=0.3, linestyle='--', color='b') if metric == 'Age': plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.savefig(save_path) plt.close() <|reserved_special_token_0|> def ttest_ind_corrected(performance_a, performance_b, k=10, r=10): """Corrected repeated k-fold cv test. The test assumes that the classifiers were evaluated using cross validation. Ref: Bouckaert, Remco R., and Eibe Frank. "Evaluating the replicability of significance tests for comparing learning algorithms." Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004 Args: performance_a: performances from classifier A performance_b: performances from classifier B k: number of folds r: number of repetitions Returns: t: t-statistic of the corrected test. prob: p-value of the corrected test. """ df = k * r - 1 x = performance_a - performance_b m = np.mean(x) sigma_2 = np.var(x, ddof=1) denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2) with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(m, denom) prob = stats.t.sf(np.abs(t), df) * 2 return t, prob <|reserved_special_token_1|> <|reserved_special_token_0|> matplotlib.use('Agg') <|reserved_special_token_0|> sns.set() def get_paths(debug, dataset): if debug and dataset == 'OASIS': project_wd = os.getcwd() project_data = os.path.join(project_wd, 'data') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BANC': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BOSTON': project_wd = os.getcwd() project_data = None project_sink = None elif debug and dataset == 'BANC_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif debug and dataset == 'UKBIO_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif not debug and dataset == 'OASIS': project_wd = '/code' project_data = os.path.join(os.sep, 'NaN', 'data') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BANC': project_wd = '/code' project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BOSTON': project_wd = '/code' project_data = None project_sink = None elif not debug and (dataset == 'BANC_freesurf' or dataset == 'UKBIO_freesurf' or dataset == 'freesurf_combined'): project_wd = '/code' project_data = os.path.join(os.sep, 'code', 'BayOptPy', 'freesurfer_preprocess') project_sink = None else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Code Path: %s' % project_wd) print('Data Path: %s' % project_data) print('Data Out: %s' % project_sink) return project_wd, project_data, project_sink def get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute) output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute): if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis == 'feat_combi' or analysis == 'vanilla_combi' or analysis == 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or analysis == 'uniform_dist'): if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen) elif analysis == 'population': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%05d_population_size' % population_size, '%03d_generations' % ngen) elif analysis == 'mutation': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover)) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' % model, 'Output', analysis, predicted_attribute, '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % ( mutation, crossover)) else: raise IOError('Analysis path not defined. Passed analysis was %s' % analysis) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis): """ This function gets the original dataset and transforms it into a uniformly distributed dataset. """ project_wd, project_data, project_sink = get_paths(debug, dataset) demographics, imgs, dataframe = get_data(project_data, dataset, debug, project_wd, resamplefactor, raw=raw, analysis=analysis) demographics['age_int'] = demographics['age'].astype('int32', copy=False) age_range = np.arange(demographics['age'].min(), demographics['age'].max()) max_n = 14 age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89] age_range = np.setdiff1d(age_range, age_to_remove) ids_to_use = [] for age in age_range: ids_to_use.append(demographics.index[demographics['age_int'] == age ].tolist()[:max_n]) ids_to_use = [item for sublist in ids_to_use for item in sublist] demographics = demographics[demographics.index.isin(ids_to_use)] dataframe = dataframe.loc[demographics['id']] print('Shape of the new demographics:') print(demographics.shape) print('Oldest %d and youngest %d subject' % (demographics['age_int']. max(), demographics['age_int'].min())) print('Number of age bins %d' % len(demographics['age_int'].unique())) return demographics, dataframe def get_best_pipeline_paths(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): output_path = get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute) checkpoint_path = os.path.join(output_path, 'checkpoint_folder') if os.path.exists(checkpoint_path): shutil.rmtree(checkpoint_path) print('Deleted pre-exiting checkpoint folder') if not os.path.exists(checkpoint_path): os.makedirs(checkpoint_path) print('Creating checkpoint folder') return checkpoint_path def drop_missing_features(dataframe): """ This function takes a dataframe and removes the already defined missing columns from the dataframe. """ missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1', 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles', 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf', 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities', 'Left-non-WM-hypointensities', 'non-WM-hypointensities', 'Right-WM-hypointensities', 'Left-WM-hypointensities', 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus', 'Left-choroid-plexus', 'Left-Lateral-Ventricle', 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent'] cleaned_df = dataframe.drop(missing_features, axis=1) return cleaned_df def get_data_covariates(dataPath, rawsubjectsId, dataset): if dataset == 'OASIS': demographics = pd.read_csv(os.path.join(dataPath, 'oasis_cross-sectional.csv')) demographics = demographics.sort_values('ID') missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = demographics.loc[(demographics['CDR'] == 0) | demographics['CDR'].isnull(), 'ID'] demographics = demographics.loc[demographics['ID'].isin(selectedSubId)] elif dataset == 'BANC': column_names = ['ID', 'original_dataset', 'sex', 'Age'] demographics = pd.read_csv(os.path.join(dataPath, 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names) missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) demographics = demographics.loc[~demographics['ID'].isin( missingsubjectsId)] selectedSubId = rawsubjectsId else: raise ValueError('Analysis for this dataset is not yet implemented!') assert len(selectedSubId) == len(demographics) return demographics, selectedSubId def _multiprocessing_resample(img, target_affine): resampled_img = image.resample_img(img, target_affine=target_affine, interpolation='nearest') return resampled_img def _load_nibabel(filePath): img = nib.load(os.path.join(filePath)) return img def get_config_dictionary(): regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': { 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': { 'max_depth': range(1, 11), 'min_samples_split': range(2, 21), 'min_samples_leaf': range(1, 21)}, 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]}, 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]}, 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive', 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [ 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {}, 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05, 0.001), 'score_func': {'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile': range(1, 100), 'score_func': { 'sklearn.feature_selection.f_regression': None}}, 'sklearn.feature_selection.VarianceThreshold': {'threshold': [ 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}} return regressor_config_dic def get_mean_age(df): mean_age = df['Age'].mean() std_age = df['Age'].std() print('Mean Age %.2f +- %.2f' % (mean_age, std_age)) def get_data(project_data, dataset, debug, project_wd, resamplefactor, raw, analysis): """ Load the csv files and return :param project_data: :param dataset: :param debug: :param project_wd: :param resamplefactor: :raw: Which type of fressesfurfer should we analyse (the raw, where both datasets have not been matched or the not raw where the number of columns between dataset is the same) :return: demographics: :return: demographics: :return: dataframe.values: Just the numeric values of the dataframe """ if dataset == 'freesurf_combined' and raw == True: raise ValueError('The combined analysis cannot use the raw dataset') print('Loading Brain image data') elif dataset == 'OASIS': fileList = os.listdir(project_data) rawsubjectsId = [re.sub('^smwc1(.*?)\\_mpr-1_anon.nii$', '\\1', file) for file in fileList if file.endswith('.nii')] demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset) get_mean_age(demographics) imgs = [nib.load(os.path.join(project_data, 'smwc1%s_mpr-1_anon.nii' % subject)) for subject in tqdm( selectedSubId)] elif dataset == 'BANC': project_data_path = os.path.join(project_data, 'wm_data') fileList = os.listdir(project_data_path) rawsubjectsId = [file[5:12] for file in fileList if file.endswith( '.nii.gz')] demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset) get_mean_age(demographics) subjectsFile = [os.path.join(project_data_path, file) for file in fileList if file[5:12] in selectedSubId] with Pool() as p: imgs = list(tqdm(p.imap(_load_nibabel, subjectsFile), total=len (selectedSubId))) elif dataset == 'BANC_freesurf' and raw == True: freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'BANC', 'aparc_aseg_stats_BANC.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif dataset == 'UKBIO_freesurf' and raw == False and not analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO.csv'), delimiter=',') ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',', index_col=False) demographics = ukbio_full_df[['age', 'sex', 'id']].copy() freesurf_df = freesurf_df.set_index('id') return demographics, None, freesurf_df elif dataset == 'BANC_freesurf' and raw == False and not analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif dataset == 'UKBIO_freesurf' and raw == True and not analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') freesurf_df = freesurf_df.drop(columns='id.4844') demographics = freesurf_df[['age', 'sex', 'id']].copy() freesurf_df = freesurf_df.set_index('id') return demographics, None, freesurf_df elif dataset == 'UKBIO_freesurf' and raw == False and analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO_summary.csv'), delimiter=',') ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') demographics = ukbio_full_df[['age', 'sex', 'id']].copy() return demographics, None, freesurf_df elif dataset == 'BANC_freesurf' and raw == False and analysis == 'summary_data': freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC_summary.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif dataset == 'freesurf_combined': ukbio_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO.csv'), delimiter=',', index_col=0) banc_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0) ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') rawsubjectsId = banc_df.index banc_demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') ukbio_demographics = ukbio_full_df[['age', 'sex', 'id']].copy() freesurfer_df = pd.concat([ukbio_df, banc_df]) tmp = banc_demographics.drop('original_dataset', axis=1) tmp.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True) tmp['sex'] = tmp['sex'].map({'F': 'female', 'M': 'male'}) tmp['dataset'] = 'banc' ukbio_demographics['dataset'] = 'ukbio' demographics = pd.concat([ukbio_demographics, tmp], sort=False) bins = 17, 30, 40, 50, 60, 70, 80, 90 group_labels = range(1, len(bins)) demographics['age_band'] = pd.cut(demographics['age'], bins, labels =group_labels) sex_age_group = demographics.groupby(['sex', 'age_band']) demographics['stratify'] = sex_age_group.grouper.group_info[0] + 1 return demographics, None, freesurfer_df else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Resample the dataset by a factor of %d' % resamplefactor) print('Original image size: %s' % (imgs[0].shape,)) resampleby2affine = np.array([[resamplefactor, 1, 1, 1], [1, resamplefactor, 1, 1], [1, 1, resamplefactor, 1], [1, 1, 1, 1]]) target_affine = np.multiply(imgs[0].affine, resampleby2affine) print('Resampling Images') with Pool() as p: args = partial(_multiprocessing_resample, target_affine=target_affine) resampledimgs = list(tqdm(p.imap(args, imgs), total=len(imgs))) print('Resampled image size: %s' % (resampledimgs[0].shape,)) print('Compute brain mask') MeanImgMask = masking.compute_multi_epi_mask(resampledimgs, lower_cutoff=0.001, upper_cutoff=0.85, opening=False) maskedData = [masking.apply_mask(img, MeanImgMask) for img in resampledimgs ] if debug: mask_path = os.path.join(project_wd, 'BayOptPy', 'tpot') print('Saving brain mask: %s' % mask_path) nib.save(MeanImgMask, os.path.join(mask_path, 'mask_%s.nii.gz' % dataset)) print('Applied mask to the dataset') maskedData = np.array(maskedData) return demographics, imgs, maskedData def get_mae_for_all_generations(dataset, random_seed, generations, config_dict, tpot_path): """ Get the MAE values for both the training and test dataset :return: """ saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict, generations)) logbook = joblib.load(saved_path) gen = list(logbook['log'].keys()) print('There are %d optminal pipelines' % len(gen)) print('These are the best pipelines') for generation in gen: print(logbook['log'][generation]['pipeline_name']) all_mae_test = [] all_mae_train = [] pipeline_complexity = [] curr_gen_idx = 0 for generation in range(generations): if generation == gen[curr_gen_idx]: all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_test_mae'])) all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][ 'pipeline_score'])) pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx] ]['pipeline_sklearn_obj'].named_steps.keys())) if len(gen) > 1 and len(gen) > curr_gen_idx + 1: curr_gen_idx += 1 else: all_mae_test.append(all_mae_test[-1]) all_mae_train.append(all_mae_train[-1]) pipeline_complexity.append(pipeline_complexity[-1]) pipeline_complexity = np.array(pipeline_complexity) return all_mae_test, all_mae_train, pipeline_complexity def set_publication_style(): plt.style.use(['seaborn-white', 'seaborn-talk']) matplotlib.rc('font', family='Times New Roman') sns.set_style('white', {'axes.spines.top': False, 'axes.spines.right': False, 'axes.labelsize': 'large'}) def create_age_histogram(df, dataset): """ Get an age array and plot and save the age histogram for the analysed sample """ set_publication_style() plt.figure() path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset min_age = df['age'].min() max_age = df['age'].max() plt.hist(df['age'], bins=65, range=(min_age, max_age)) plt.xlabel('Age') plt.ylabel('# of Subjects') plt.legend() plt.savefig(path_to_save) plt.close() def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title= None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' cm = confusion_matrix(y_true, y_pred) labels = [int(x) for x in unique_labels(y_true, y_pred)] classes = classes[labels] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print('Normalized confusion matrix') else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel= 'True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2.0 for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center', color='white' if cm[i, j] > thresh else 'black') fig.tight_layout() return ax, cm def plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ fig, ax = plt.subplots() im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean. shape[0]), xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode= 'anchor') fmt = '{0:.2f} ± {1:.2f}' thresh = cm_mean.max() / 2.0 for i in range(cm_mean.shape[0]): for j in range(cm_mean.shape[1]): ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha= 'center', va='center', color='white' if cm_mean[i, j] > thresh else 'black') fig.tight_layout() return ax def plot_predicted_vs_true(true_y, predicted_y, save_path, metric): fig = plt.figure() plt.scatter(true_y, predicted_y, alpha=0.5) plt.ylabel('Predicted %s' % metric) plt.xlabel('True %s' % metric) plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y), max(true_y)), alpha=0.3, linestyle='--', color='b') if metric == 'Age': plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max( true_y), max(predicted_y)), step=10)) plt.savefig(save_path) plt.close() def load_cognitive_data(project_data): cog_path = os.path.join(project_data, 'cog_ukbio') cog_df = pd.read_csv(os.path.join(cog_path, 'UKB_10k_cog_bmi.csv')) cog_df = cog_df.set_index('ID') return cog_df def ttest_ind_corrected(performance_a, performance_b, k=10, r=10): """Corrected repeated k-fold cv test. The test assumes that the classifiers were evaluated using cross validation. Ref: Bouckaert, Remco R., and Eibe Frank. "Evaluating the replicability of significance tests for comparing learning algorithms." Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004 Args: performance_a: performances from classifier A performance_b: performances from classifier B k: number of folds r: number of repetitions Returns: t: t-statistic of the corrected test. prob: p-value of the corrected test. """ df = k * r - 1 x = performance_a - performance_b m = np.mean(x) sigma_2 = np.var(x, ddof=1) denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2) with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(m, denom) prob = stats.t.sf(np.abs(t), df) * 2 return t, prob <|reserved_special_token_1|> import joblib import os import shutil import re from scipy import stats from functools import partial import pandas as pd from multiprocessing import Process, Pool from nilearn import masking, image import nibabel as nib import numpy as np from tqdm import tqdm import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from sklearn.utils.multiclass import unique_labels import seaborn as sns sns.set() def get_paths(debug, dataset): if debug and dataset == 'OASIS': project_wd = os.getcwd() project_data = os.path.join(project_wd, 'data') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BANC': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif debug and dataset == 'BOSTON': project_wd = os.getcwd() project_data = None project_sink = None elif debug and dataset == 'BANC_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif debug and dataset == 'UKBIO_freesurf': project_wd = os.getcwd() project_data = os.path.join(os.getenv('HOME'), 'BayOptPy', 'freesurfer_preprocess') project_sink = None elif not debug and dataset == 'OASIS': project_wd = '/code' project_data = os.path.join(os.sep, 'NaN', 'data') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BANC': project_wd = '/code' project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016') project_sink = os.path.join(project_data, 'output') elif not debug and dataset == 'BOSTON': project_wd = '/code' project_data = None project_sink = None elif not debug and (dataset == 'BANC_freesurf' or dataset == 'UKBIO_freesurf' or dataset == 'freesurf_combined' ): project_wd = '/code' project_data = os.path.join(os.sep, 'code', 'BayOptPy', 'freesurfer_preprocess') project_sink = None else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Code Path: %s' %project_wd) print('Data Path: %s' %project_data) print('Data Out: %s' %project_sink ) return project_wd, project_data, project_sink def get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): # Check if output path exists, otherwise create it rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute) output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' %random_seed) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation, crossover, predicted_attribute): # As they should have been created by the get_output_path, do not create # path but just find its location if analysis == 'vanilla' or analysis == 'feat_selec' or \ analysis == 'feat_combi' or analysis == 'vanilla_combi' or \ analysis == 'random_seed' or analysis == 'ukbio' or \ analysis == 'summary_data' or analysis == 'uniform_dist': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' %model, 'Output', analysis, predicted_attribute, '%03d_generations' %ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' %model, 'Output', analysis, predicted_attribute, '%03d_generations' %ngen) elif analysis == 'population': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' %model, 'Output', analysis, predicted_attribute, '%05d_population_size' %population_size, '%03d_generations' %ngen) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' %model, 'Output', analysis, predicted_attribute, '%05d_population_size' %population_size, '%03d_generations' %ngen) elif analysis == 'mutation': if debug: output_path = os.path.join('BayOptPy', 'tpot_%s' %model, 'Output', analysis, predicted_attribute, '%03d_generations' %ngen, '%.01f_mut_%.01f_cross' %(mutation, crossover)) else: output_path = os.path.join(os.sep, 'code', 'BayOptPy', 'tpot_%s' %model, 'Output', analysis, predicted_attribute, '%03d_generations' %ngen, '%.01f_mut_%.01f_cross' %(mutation, crossover)) else: raise IOError('Analysis path not defined. Passed analysis was %s' %analysis) if not os.path.exists(output_path): os.makedirs(output_path) return output_path def get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis): """ This function gets the original dataset and transforms it into a uniformly distributed dataset. """ project_wd, project_data, project_sink = get_paths(debug, dataset) demographics, imgs, dataframe = get_data(project_data, dataset, debug, project_wd, resamplefactor, raw=raw, analysis=analysis) # transform age into ints demographics['age_int'] = demographics['age'].astype('int32', copy=False) # Select 14 subjects for all ages that have 14 representatives. age_range = np.arange(demographics['age'].min(), demographics['age'].max()) # remove entry where you don't have 14 subjects max_n = 14 age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89] age_range = np.setdiff1d(age_range, age_to_remove) # iterate over the dataframe and select 14 subjects for each age range ids_to_use = [] for age in age_range: ids_to_use.append(demographics.index[demographics['age_int'] == age].tolist()[:max_n]) # flatten ids_to_use ids_to_use = [item for sublist in ids_to_use for item in sublist] # Filter the demographics dataframe demographics = demographics[demographics.index.isin(ids_to_use)] # set subject's id as index # filter dataset using index of the subjects dataframe = dataframe.loc[demographics['id']] # Print some diagnosis print('Shape of the new demographics:') print(demographics.shape) print('Oldest %d and youngest %d subject' %(demographics['age_int'].max(), demographics['age_int'].min())) print('Number of age bins %d' %len(demographics['age_int'].unique())) return demographics, dataframe def get_best_pipeline_paths(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute): # check if folder exists and in case yes, remove it as new runs will save # new files without overwritting output_path = get_output_path(model, analysis, ngen, random_seed, population_size, debug, mutation, crossover, predicted_attribute) checkpoint_path = os.path.join(output_path, 'checkpoint_folder') # Delete folder if it already exists and create a new one if os.path.exists(checkpoint_path): shutil.rmtree(checkpoint_path) print('Deleted pre-exiting checkpoint folder') if not os.path.exists(checkpoint_path): os.makedirs(checkpoint_path) print('Creating checkpoint folder') return checkpoint_path def drop_missing_features(dataframe): ''' This function takes a dataframe and removes the already defined missing columns from the dataframe. ''' missing_features = [# This features are repeated or missing on the BIOBANK # dataset 'BrainSegVolNotVent', 'BrainSegVolNotVent.1', 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', # Drop additional features that are 0 or have no # biological meaning 'SurfaceHoles', 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf', 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities', 'Left-non-WM-hypointensities', 'non-WM-hypointensities', 'Right-WM-hypointensities', 'Left-WM-hypointensities', 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus', 'Left-choroid-plexus', 'Left-Lateral-Ventricle', 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent', ] cleaned_df = dataframe.drop(missing_features, axis=1) return cleaned_df def get_data_covariates(dataPath, rawsubjectsId, dataset): if dataset == 'OASIS': # Load the demographic details from the dataset demographics = pd.read_csv(os.path.join(dataPath, 'oasis_cross-sectional.csv')) # sort demographics by ascending id demographics = demographics.sort_values('ID') # Check if there is any subject for which we have the fmri data but no demographics missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) # remove the demographic data from the missing subjects demographics = demographics.loc[~demographics['ID'].isin(missingsubjectsId)] # list of subjects that do not have dementia (CDR > 0) selectedSubId = demographics.loc[(demographics['CDR'] == 0) | (demographics['CDR'].isnull()), 'ID'] # filter demographics to exclude those with CDR > 0 demographics = demographics.loc[demographics['ID'].isin(selectedSubId)] elif dataset == 'BANC': # Load the demographic details from the dataset column_names = ['ID', 'original_dataset', 'sex', 'Age'] demographics = pd.read_csv(os.path.join(dataPath,'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names) # Check if there is any subject for which we have the fmri data but no demographics missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId)) # remove the demographic data from the missing subjects demographics = demographics.loc[~demographics['ID'].isin(missingsubjectsId)] selectedSubId = rawsubjectsId else: raise ValueError('Analysis for this dataset is not yet implemented!') # do some sanity checks # Check if you have the same number of selectedsubjectsid as the demographic information assert(len(selectedSubId) == len(demographics)) return demographics, selectedSubId def _multiprocessing_resample(img, target_affine): resampled_img = image.resample_img(img, target_affine=target_affine, interpolation='nearest') return resampled_img def _load_nibabel(filePath): img = nib.load(os.path.join(filePath)) return img def get_config_dictionary(): # Define the same default pipeline as TPOT light but without the preprocessing operators regressor_config_dic = { 'sklearn.linear_model.ElasticNetCV': { 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-5, 1e-4, 1e-3, 1e-2, 1e-1] }, 'sklearn.tree.DecisionTreeRegressor': { 'max_depth': range(1, 11), 'min_samples_split': range(2, 21), 'min_samples_leaf': range(1, 21) }, 'sklearn.neighbors.KNeighborsRegressor': { 'n_neighbors': range(1, 101), 'weights': ["uniform", "distance"], 'p': [1, 2] }, 'sklearn.linear_model.LassoLarsCV': { 'normalize': [True, False] }, 'sklearn.svm.LinearSVR': { 'loss': ["epsilon_insensitive", "squared_epsilon_insensitive"], 'dual': [True, False], 'tol': [1e-5, 1e-4, 1e-3, 1e-2, 1e-1], 'C': [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.], 'epsilon': [1e-4, 1e-3, 1e-2, 1e-1, 1.] }, 'sklearn.linear_model.RidgeCV': { }, # Selectors 'sklearn.feature_selection.SelectFwe': { 'alpha': np.arange(0, 0.05, 0.001), 'score_func': { 'sklearn.feature_selection.f_regression': None } }, 'sklearn.feature_selection.SelectPercentile': { 'percentile': range(1, 100), 'score_func': { 'sklearn.feature_selection.f_regression': None } }, 'sklearn.feature_selection.VarianceThreshold': { 'threshold': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2] } } return regressor_config_dic def get_mean_age(df): mean_age = df['Age'].mean() std_age = df['Age'].std() print('Mean Age %.2f +- %.2f' %(mean_age, std_age)) def get_data(project_data, dataset, debug, project_wd, resamplefactor, raw, analysis): ''' Load the csv files and return :param project_data: :param dataset: :param debug: :param project_wd: :param resamplefactor: :raw: Which type of fressesfurfer should we analyse (the raw, where both datasets have not been matched or the not raw where the number of columns between dataset is the same) :return: demographics: :return: demographics: :return: dataframe.values: Just the numeric values of the dataframe ''' if dataset == 'freesurf_combined' and raw == True: raise ValueError('The combined analysis cannot use the raw dataset') print('Loading Brain image data') elif dataset == 'OASIS': # remove the file end and get list of all used subjects fileList = os.listdir(project_data) rawsubjectsId = [re.sub(r'^smwc1(.*?)\_mpr-1_anon.nii$', '\\1', file) for file in fileList if file.endswith('.nii')] # TODO: Change this. For testing purpose select just the first 5 subjects #rawsubjectsId = rawsubjectsId[:25] # Load the demographics for each subject demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset) # print subjects mean age get_mean_age(demographics) # Load image proxies imgs = [nib.load(os.path.join(project_data, 'smwc1%s_mpr-1_anon.nii' %subject)) for subject in tqdm(selectedSubId)] elif dataset == 'BANC': # For now, performing analysis on White Matter. project_data_path = os.path.join(project_data, 'wm_data') # remove the file end and get list of all used subjects fileList = os.listdir(project_data_path) rawsubjectsId = [file[5:12] for file in fileList if file.endswith('.nii.gz')] # TODO: select only a set of 5 subjects # rawsubjectsId = rawsubjectsId[:5] # Load the demographics for each subject demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset) # print subjects mean age get_mean_age(demographics) # Get the file path of the selected subjects subjectsFile = [os.path.join(project_data_path, file) for file in fileList if file[5:12] in selectedSubId] # Load image proxies with Pool() as p: imgs = list(tqdm(p.imap(_load_nibabel, subjectsFile), total=len(selectedSubId))) elif (dataset == 'BANC_freesurf' and raw==True): freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'BANC', 'aparc_aseg_stats_BANC.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index # Load the demographics for each subject demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') # return numpy array of the dataframe # Rename columns to maintain consistency withe ukbio demographics.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif (dataset == 'UKBIO_freesurf' and raw==False and not analysis=='summary_data'): freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO.csv'), delimiter=',') # Read the full matrix to get the demographics information ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',', index_col=False) demographics = ukbio_full_df[['age', 'sex', 'id']].copy() freesurf_df = freesurf_df.set_index('id') return demographics, None, freesurf_df elif (dataset == 'BANC_freesurf' and raw==False and not analysis=='summary_data'): freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index # Load the demographics for each subject demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') # return numpy array of the dataframe # Rename columns to maintain consistency withe ukbio demographics.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif (dataset == 'UKBIO_freesurf' and raw==True and not analysis=='summary_data'): freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') freesurf_df = freesurf_df.drop(columns='id.4844') demographics = freesurf_df[['age', 'sex', 'id']].copy() freesurf_df = freesurf_df.set_index('id') return demographics, None, freesurf_df elif (dataset == 'UKBIO_freesurf' and raw==False and analysis=='summary_data'): # This dataset contains only 21 feature that represent summary metrics freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO_summary.csv'), delimiter=',') # Read the full matrix to get the demographics information ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') demographics = ukbio_full_df[['age', 'sex', 'id']].copy() return demographics, None, freesurf_df elif (dataset == 'BANC_freesurf' and raw==False and analysis=='summary_data'): # This dataset contains only 21 feature that represent summary metrics freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC_summary.csv'), delimiter=',', index_col=0) rawsubjectsId = freesurf_df.index # Load the demographics for each subject demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') # Rename columns to maintain consistency withe ukbio demographics.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True) return demographics, None, freesurf_df elif (dataset == 'freesurf_combined'): ukbio_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_UKBIO.csv'), delimiter=',', index_col=0) banc_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'matched_dataset', 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0) ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy', 'freesurfer_preprocess', 'original_dataset', 'UKBIO', 'UKB_10k_FS_4844_combined.csv'), delimiter=',') rawsubjectsId = banc_df.index # Load the demographics for each subject banc_demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC') ukbio_demographics = ukbio_full_df[['age', 'sex', 'id']].copy() # Concatenate both freesurfeer datasets freesurfer_df = pd.concat([ukbio_df, banc_df]) # Concatenate demographics information (Age and Sex) tmp = banc_demographics.drop('original_dataset', axis=1) tmp.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True) # transform M/F into male/female tmp['sex'] = tmp['sex'].map({'F': 'female', 'M': 'male'}) # Add column to specify dataset tmp['dataset'] = 'banc' ukbio_demographics['dataset'] = 'ukbio' demographics = pd.concat([ukbio_demographics, tmp], sort=False) # TODO: For now assume that the index in the BIOBANK correspond to th # Stratify subjects. Divide them into classes <30, 30<40, 40<50, 50<60, # 60<70, 70<80, 80<90, 90<100. Each age will be then further stratified # into F/M. bins = (17, 30, 40, 50, 60, 70, 80, 90) group_labels = range(1,len(bins)) demographics['age_band'] = pd.cut(demographics['age'], bins, labels=group_labels) sex_age_group = demographics.groupby(['sex', 'age_band']) # Note that the following groups are created: # ('female', 1), ('female', 2), ('female', 3), ('female', 4), ('female', 5), # ('female', 6), ('female', 7), ('male', 1), ('male', 2), ('male', 3), # ('male', 4), ('male', 5), ('male', 6), ('male', 7)] # This will label the groups cited above in a crescent order. In total # you will have 1-14 groups, grouped according to their age and sex demographics['stratify'] = sex_age_group.grouper.group_info[0] + 1 #same order between both fines return demographics, None, freesurfer_df else: raise ValueError('Analysis for this dataset is not yet implemented!') print('Resample the dataset by a factor of %d' %resamplefactor) print('Original image size: %s' %(imgs[0].shape,)) # resample dataset to a lower quality. Increase the voxel size by two resampleby2affine = np.array([[resamplefactor, 1, 1, 1], [1, resamplefactor, 1, 1], [1, 1, resamplefactor, 1], [1, 1, 1, 1]]) target_affine = np.multiply(imgs[0].affine, resampleby2affine) print('Resampling Images') with Pool() as p: args = partial(_multiprocessing_resample, target_affine=target_affine) resampledimgs = list(tqdm(p.imap(args, imgs), total=len(imgs))) print('Resampled image size: %s' %(resampledimgs[0].shape,)) # Use nilearn to mask only the brain voxels across subjects print('Compute brain mask') #The lower and the upper_cutoff represent the lower and the upper fraction of the histogram to be discarded MeanImgMask = masking.compute_multi_epi_mask(resampledimgs, lower_cutoff=0.001, upper_cutoff=.85, opening=False) # Apply the group mask on all subjects. # Note: The apply_mask function returns the flattened data as a numpy array maskedData = [masking.apply_mask(img, MeanImgMask) for img in resampledimgs] # If debug option is set, save an nifti image of the image. # Note: if you resampled the image you will not be able to overlay it on the original brain if debug: mask_path = os.path.join(project_wd, 'BayOptPy', 'tpot') print('Saving brain mask: %s' %mask_path) nib.save(MeanImgMask, os.path.join(mask_path, 'mask_%s.nii.gz' %dataset)) print('Applied mask to the dataset') # Transform the imaging data into a np array (subjects x voxels) maskedData = np.array(maskedData) return demographics, imgs, maskedData def get_mae_for_all_generations(dataset, random_seed, generations, config_dict, tpot_path): ''' Get the MAE values for both the training and test dataset :return: ''' # Load the scores for the best models saved_path = os.path.join(tpot_path, 'random_seed_%03d' %random_seed, 'tpot_%s_%s_%03dgen_pipelines.dump' %(dataset, config_dict, generations)) # Note that if a value is not present for a generation, that means that the # score did not change from the previous generation # sort the array in ascending order logbook = joblib.load(saved_path) gen = list(logbook['log'].keys()) print('There are %d optminal pipelines' %len(gen)) print('These are the best pipelines') for generation in gen: print(logbook['log'][generation]['pipeline_name']) # Iterate over the the list of saved MAEs and repeat the values where one # generation is missed all_mae_test = [] all_mae_train = [] pipeline_complexity = [] curr_gen_idx = 0 # all generations for generation in range(generations): if generation == gen[curr_gen_idx]: all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]]['pipeline_test_mae'])) all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]]['pipeline_score'])) pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx]]['pipeline_sklearn_obj'].named_steps.keys())) if len(gen) > 1 and (len(gen) > curr_gen_idx + 1): curr_gen_idx += 1 else: # repeat the same last value all_mae_test.append(all_mae_test[-1]) all_mae_train.append(all_mae_train[-1]) pipeline_complexity.append(pipeline_complexity[-1]) # transform the pipeline_complexity into a numpy array, in order to perform # fancy indexing pipeline_complexity = np.array(pipeline_complexity) return all_mae_test, all_mae_train, pipeline_complexity def set_publication_style(): # Se font size to paper size plt.style.use(['seaborn-white', 'seaborn-talk']) matplotlib.rc("font", family="Times New Roman") # Remove the spines sns.set_style('white', {"axes.spines.top": False, "axes.spines.right": False, "axes.labelsize": 'large'}) def create_age_histogram(df, dataset): ''' Get an age array and plot and save the age histogram for the analysed sample ''' # Define plot styple set_publication_style() plt.figure() path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' %dataset min_age = df['age'].min() max_age = df['age'].max() plt.hist(df['age'], bins=65, range=(min_age,max_age)) plt.xlabel('Age') plt.ylabel('# of Subjects') plt.legend() plt.savefig(path_to_save) plt.close() def plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if not title: if normalize: title = 'Normalized confusion matrix' else: title = 'Confusion matrix, without normalization' # Compute confusion matrix cm = confusion_matrix(y_true, y_pred) # Only use the labels that appear in the data labels = [int(x) for x in unique_labels(y_true, y_pred)] classes = classes[labels] if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) fig, ax = plt.subplots() im = ax.imshow(cm, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i in range(cm.shape[0]): for j in range(cm.shape[1]): ax.text(j, i, format(cm[i, j], fmt), ha="center", va="center", color="white" if cm[i, j] > thresh else "black") fig.tight_layout() return ax, cm def plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None, cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ fig, ax = plt.subplots() im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap) ax.figure.colorbar(im, ax=ax) # We want to show all ticks... ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean.shape[0]), # ... and label them with the respective list entries xticklabels=classes, yticklabels=classes, title=title, ylabel='True label', xlabel='Predicted label') # Rotate the tick labels and set their alignment. plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor") # Loop over data dimensions and create text annotations. fmt = '{0:.2f} ± {1:.2f}' thresh = cm_mean.max() / 2. for i in range(cm_mean.shape[0]): for j in range(cm_mean.shape[1]): ax.text(j, i, fmt.format(cm_mean[i, j],cm_std[i, j]), ha="center", va="center", color="white" if cm_mean[i, j] > thresh else "black") fig.tight_layout() return ax def plot_predicted_vs_true(true_y, predicted_y, save_path, metric): fig = plt.figure() plt.scatter(true_y, predicted_y, alpha=.5) plt.ylabel('Predicted %s' %metric) plt.xlabel('True %s'%metric) plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y), max(true_y)), alpha=.3, linestyle='--', color='b') if metric == 'Age': plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max(true_y), max(predicted_y)), step=10)) plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max(true_y), max(predicted_y)), step=10)) plt.savefig(save_path) plt.close() def load_cognitive_data(project_data): cog_path = os.path.join(project_data, 'cog_ukbio') cog_df = pd.read_csv(os.path.join(cog_path, 'UKB_10k_cog_bmi.csv')) cog_df = cog_df.set_index('ID') return cog_df def ttest_ind_corrected(performance_a, performance_b, k=10, r=10): """Corrected repeated k-fold cv test. The test assumes that the classifiers were evaluated using cross validation. Ref: Bouckaert, Remco R., and Eibe Frank. "Evaluating the replicability of significance tests for comparing learning algorithms." Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004 Args: performance_a: performances from classifier A performance_b: performances from classifier B k: number of folds r: number of repetitions Returns: t: t-statistic of the corrected test. prob: p-value of the corrected test. """ df = k * r - 1 x = performance_a - performance_b m = np.mean(x) sigma_2 = np.var(x, ddof=1) denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2) with np.errstate(divide='ignore', invalid='ignore'): t = np.divide(m, denom) prob = stats.t.sf(np.abs(t), df) * 2 return t, prob
flexible
{ "blob_id": "2e9d71b8055e1bab107cedae69ca3bc4219e7d38", "index": 7460, "step-1": "<mask token>\n\n\ndef get_paths(debug, dataset):\n if debug and dataset == 'OASIS':\n project_wd = os.getcwd()\n project_data = os.path.join(project_wd, 'data')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BANC':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BOSTON':\n project_wd = os.getcwd()\n project_data = None\n project_sink = None\n elif debug and dataset == 'BANC_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif debug and dataset == 'UKBIO_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif not debug and dataset == 'OASIS':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'NaN', 'data')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BANC':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BOSTON':\n project_wd = '/code'\n project_data = None\n project_sink = None\n elif not debug and (dataset == 'BANC_freesurf' or dataset ==\n 'UKBIO_freesurf' or dataset == 'freesurf_combined'):\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'code', 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n print('Code Path: %s' % project_wd)\n print('Data Path: %s' % project_data)\n print('Data Out: %s' % project_sink)\n return project_wd, project_data, project_sink\n\n\ndef get_output_path(model, analysis, ngen, random_seed, population_size,\n debug, mutation, crossover, predicted_attribute):\n rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen,\n population_size, debug, mutation, crossover, predicted_attribute)\n output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_all_random_seed_paths(model, analysis, ngen, population_size, debug,\n mutation, crossover, predicted_attribute):\n if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis ==\n 'feat_combi' or analysis == 'vanilla_combi' or analysis ==\n 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or\n analysis == 'uniform_dist'):\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen)\n elif analysis == 'population':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, \n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n elif analysis == 'mutation':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover))\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (\n mutation, crossover))\n else:\n raise IOError('Analysis path not defined. Passed analysis was %s' %\n analysis)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis):\n \"\"\"\n This function gets the original dataset and transforms it into a uniformly\n distributed dataset.\n \"\"\"\n project_wd, project_data, project_sink = get_paths(debug, dataset)\n demographics, imgs, dataframe = get_data(project_data, dataset, debug,\n project_wd, resamplefactor, raw=raw, analysis=analysis)\n demographics['age_int'] = demographics['age'].astype('int32', copy=False)\n age_range = np.arange(demographics['age'].min(), demographics['age'].max())\n max_n = 14\n age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89]\n age_range = np.setdiff1d(age_range, age_to_remove)\n ids_to_use = []\n for age in age_range:\n ids_to_use.append(demographics.index[demographics['age_int'] == age\n ].tolist()[:max_n])\n ids_to_use = [item for sublist in ids_to_use for item in sublist]\n demographics = demographics[demographics.index.isin(ids_to_use)]\n dataframe = dataframe.loc[demographics['id']]\n print('Shape of the new demographics:')\n print(demographics.shape)\n print('Oldest %d and youngest %d subject' % (demographics['age_int'].\n max(), demographics['age_int'].min()))\n print('Number of age bins %d' % len(demographics['age_int'].unique()))\n return demographics, dataframe\n\n\ndef get_best_pipeline_paths(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute):\n output_path = get_output_path(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute)\n checkpoint_path = os.path.join(output_path, 'checkpoint_folder')\n if os.path.exists(checkpoint_path):\n shutil.rmtree(checkpoint_path)\n print('Deleted pre-exiting checkpoint folder')\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n print('Creating checkpoint folder')\n return checkpoint_path\n\n\ndef drop_missing_features(dataframe):\n \"\"\"\n This function takes a dataframe and removes the already defined missing\n columns from the dataframe.\n \"\"\"\n missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1',\n 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles',\n 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf',\n 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities',\n 'Left-non-WM-hypointensities', 'non-WM-hypointensities',\n 'Right-WM-hypointensities', 'Left-WM-hypointensities',\n 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus',\n 'Left-choroid-plexus', 'Left-Lateral-Ventricle',\n 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent']\n cleaned_df = dataframe.drop(missing_features, axis=1)\n return cleaned_df\n\n\ndef get_data_covariates(dataPath, rawsubjectsId, dataset):\n if dataset == 'OASIS':\n demographics = pd.read_csv(os.path.join(dataPath,\n 'oasis_cross-sectional.csv'))\n demographics = demographics.sort_values('ID')\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = demographics.loc[(demographics['CDR'] == 0) |\n demographics['CDR'].isnull(), 'ID']\n demographics = demographics.loc[demographics['ID'].isin(selectedSubId)]\n elif dataset == 'BANC':\n column_names = ['ID', 'original_dataset', 'sex', 'Age']\n demographics = pd.read_csv(os.path.join(dataPath,\n 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names)\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = rawsubjectsId\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n assert len(selectedSubId) == len(demographics)\n return demographics, selectedSubId\n\n\n<mask token>\n\n\ndef _load_nibabel(filePath):\n img = nib.load(os.path.join(filePath))\n return img\n\n\ndef get_config_dictionary():\n regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': {\n 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, \n 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': {\n 'max_depth': range(1, 11), 'min_samples_split': range(2, 21),\n 'min_samples_leaf': range(1, 21)},\n 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, \n 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]},\n 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]},\n 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive',\n 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [\n 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, \n 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, \n 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {},\n 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05,\n 0.001), 'score_func': {'sklearn.feature_selection.f_regression':\n None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile':\n range(1, 100), 'score_func': {\n 'sklearn.feature_selection.f_regression': None}},\n 'sklearn.feature_selection.VarianceThreshold': {'threshold': [\n 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}}\n return regressor_config_dic\n\n\ndef get_mean_age(df):\n mean_age = df['Age'].mean()\n std_age = df['Age'].std()\n print('Mean Age %.2f +- %.2f' % (mean_age, std_age))\n\n\n<mask token>\n\n\ndef get_mae_for_all_generations(dataset, random_seed, generations,\n config_dict, tpot_path):\n \"\"\"\n Get the MAE values for both the training and test dataset\n :return:\n \"\"\"\n saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, \n 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict,\n generations))\n logbook = joblib.load(saved_path)\n gen = list(logbook['log'].keys())\n print('There are %d optminal pipelines' % len(gen))\n print('These are the best pipelines')\n for generation in gen:\n print(logbook['log'][generation]['pipeline_name'])\n all_mae_test = []\n all_mae_train = []\n pipeline_complexity = []\n curr_gen_idx = 0\n for generation in range(generations):\n if generation == gen[curr_gen_idx]:\n all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_test_mae']))\n all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_score']))\n pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx]\n ]['pipeline_sklearn_obj'].named_steps.keys()))\n if len(gen) > 1 and len(gen) > curr_gen_idx + 1:\n curr_gen_idx += 1\n else:\n all_mae_test.append(all_mae_test[-1])\n all_mae_train.append(all_mae_train[-1])\n pipeline_complexity.append(pipeline_complexity[-1])\n pipeline_complexity = np.array(pipeline_complexity)\n return all_mae_test, all_mae_train, pipeline_complexity\n\n\n<mask token>\n\n\ndef create_age_histogram(df, dataset):\n \"\"\"\n Get an age array and plot and save the age histogram for the analysed sample\n \"\"\"\n set_publication_style()\n plt.figure()\n path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset\n min_age = df['age'].min()\n max_age = df['age'].max()\n plt.hist(df['age'], bins=65, range=(min_age, max_age))\n plt.xlabel('Age')\n plt.ylabel('# of Subjects')\n plt.legend()\n plt.savefig(path_to_save)\n plt.close()\n\n\ndef plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=\n None, cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n cm = confusion_matrix(y_true, y_pred)\n labels = [int(x) for x in unique_labels(y_true, y_pred)]\n classes = classes[labels]\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print('Normalized confusion matrix')\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]),\n xticklabels=classes, yticklabels=classes, title=title, ylabel=\n 'True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.0\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center',\n color='white' if cm[i, j] > thresh else 'black')\n fig.tight_layout()\n return ax, cm\n\n\ndef plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n fig, ax = plt.subplots()\n im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean.\n shape[0]), xticklabels=classes, yticklabels=classes, title=title,\n ylabel='True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '{0:.2f} ± {1:.2f}'\n thresh = cm_mean.max() / 2.0\n for i in range(cm_mean.shape[0]):\n for j in range(cm_mean.shape[1]):\n ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha=\n 'center', va='center', color='white' if cm_mean[i, j] >\n thresh else 'black')\n fig.tight_layout()\n return ax\n\n\ndef plot_predicted_vs_true(true_y, predicted_y, save_path, metric):\n fig = plt.figure()\n plt.scatter(true_y, predicted_y, alpha=0.5)\n plt.ylabel('Predicted %s' % metric)\n plt.xlabel('True %s' % metric)\n plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y),\n max(true_y)), alpha=0.3, linestyle='--', color='b')\n if metric == 'Age':\n plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.savefig(save_path)\n plt.close()\n\n\n<mask token>\n\n\ndef ttest_ind_corrected(performance_a, performance_b, k=10, r=10):\n \"\"\"Corrected repeated k-fold cv test.\n The test assumes that the classifiers were evaluated using cross validation.\n\n Ref:\n Bouckaert, Remco R., and Eibe Frank. \"Evaluating the replicability of significance tests for comparing learning\n algorithms.\" Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004\n\n Args:\n performance_a: performances from classifier A\n performance_b: performances from classifier B\n k: number of folds\n r: number of repetitions\n\n Returns:\n t: t-statistic of the corrected test.\n prob: p-value of the corrected test.\n \"\"\"\n df = k * r - 1\n x = performance_a - performance_b\n m = np.mean(x)\n sigma_2 = np.var(x, ddof=1)\n denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2)\n with np.errstate(divide='ignore', invalid='ignore'):\n t = np.divide(m, denom)\n prob = stats.t.sf(np.abs(t), df) * 2\n return t, prob\n", "step-2": "<mask token>\n\n\ndef get_paths(debug, dataset):\n if debug and dataset == 'OASIS':\n project_wd = os.getcwd()\n project_data = os.path.join(project_wd, 'data')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BANC':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BOSTON':\n project_wd = os.getcwd()\n project_data = None\n project_sink = None\n elif debug and dataset == 'BANC_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif debug and dataset == 'UKBIO_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif not debug and dataset == 'OASIS':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'NaN', 'data')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BANC':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BOSTON':\n project_wd = '/code'\n project_data = None\n project_sink = None\n elif not debug and (dataset == 'BANC_freesurf' or dataset ==\n 'UKBIO_freesurf' or dataset == 'freesurf_combined'):\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'code', 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n print('Code Path: %s' % project_wd)\n print('Data Path: %s' % project_data)\n print('Data Out: %s' % project_sink)\n return project_wd, project_data, project_sink\n\n\ndef get_output_path(model, analysis, ngen, random_seed, population_size,\n debug, mutation, crossover, predicted_attribute):\n rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen,\n population_size, debug, mutation, crossover, predicted_attribute)\n output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_all_random_seed_paths(model, analysis, ngen, population_size, debug,\n mutation, crossover, predicted_attribute):\n if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis ==\n 'feat_combi' or analysis == 'vanilla_combi' or analysis ==\n 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or\n analysis == 'uniform_dist'):\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen)\n elif analysis == 'population':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, \n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n elif analysis == 'mutation':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover))\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (\n mutation, crossover))\n else:\n raise IOError('Analysis path not defined. Passed analysis was %s' %\n analysis)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis):\n \"\"\"\n This function gets the original dataset and transforms it into a uniformly\n distributed dataset.\n \"\"\"\n project_wd, project_data, project_sink = get_paths(debug, dataset)\n demographics, imgs, dataframe = get_data(project_data, dataset, debug,\n project_wd, resamplefactor, raw=raw, analysis=analysis)\n demographics['age_int'] = demographics['age'].astype('int32', copy=False)\n age_range = np.arange(demographics['age'].min(), demographics['age'].max())\n max_n = 14\n age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89]\n age_range = np.setdiff1d(age_range, age_to_remove)\n ids_to_use = []\n for age in age_range:\n ids_to_use.append(demographics.index[demographics['age_int'] == age\n ].tolist()[:max_n])\n ids_to_use = [item for sublist in ids_to_use for item in sublist]\n demographics = demographics[demographics.index.isin(ids_to_use)]\n dataframe = dataframe.loc[demographics['id']]\n print('Shape of the new demographics:')\n print(demographics.shape)\n print('Oldest %d and youngest %d subject' % (demographics['age_int'].\n max(), demographics['age_int'].min()))\n print('Number of age bins %d' % len(demographics['age_int'].unique()))\n return demographics, dataframe\n\n\ndef get_best_pipeline_paths(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute):\n output_path = get_output_path(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute)\n checkpoint_path = os.path.join(output_path, 'checkpoint_folder')\n if os.path.exists(checkpoint_path):\n shutil.rmtree(checkpoint_path)\n print('Deleted pre-exiting checkpoint folder')\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n print('Creating checkpoint folder')\n return checkpoint_path\n\n\ndef drop_missing_features(dataframe):\n \"\"\"\n This function takes a dataframe and removes the already defined missing\n columns from the dataframe.\n \"\"\"\n missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1',\n 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles',\n 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf',\n 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities',\n 'Left-non-WM-hypointensities', 'non-WM-hypointensities',\n 'Right-WM-hypointensities', 'Left-WM-hypointensities',\n 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus',\n 'Left-choroid-plexus', 'Left-Lateral-Ventricle',\n 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent']\n cleaned_df = dataframe.drop(missing_features, axis=1)\n return cleaned_df\n\n\ndef get_data_covariates(dataPath, rawsubjectsId, dataset):\n if dataset == 'OASIS':\n demographics = pd.read_csv(os.path.join(dataPath,\n 'oasis_cross-sectional.csv'))\n demographics = demographics.sort_values('ID')\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = demographics.loc[(demographics['CDR'] == 0) |\n demographics['CDR'].isnull(), 'ID']\n demographics = demographics.loc[demographics['ID'].isin(selectedSubId)]\n elif dataset == 'BANC':\n column_names = ['ID', 'original_dataset', 'sex', 'Age']\n demographics = pd.read_csv(os.path.join(dataPath,\n 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names)\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = rawsubjectsId\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n assert len(selectedSubId) == len(demographics)\n return demographics, selectedSubId\n\n\ndef _multiprocessing_resample(img, target_affine):\n resampled_img = image.resample_img(img, target_affine=target_affine,\n interpolation='nearest')\n return resampled_img\n\n\ndef _load_nibabel(filePath):\n img = nib.load(os.path.join(filePath))\n return img\n\n\ndef get_config_dictionary():\n regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': {\n 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, \n 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': {\n 'max_depth': range(1, 11), 'min_samples_split': range(2, 21),\n 'min_samples_leaf': range(1, 21)},\n 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, \n 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]},\n 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]},\n 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive',\n 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [\n 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, \n 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, \n 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {},\n 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05,\n 0.001), 'score_func': {'sklearn.feature_selection.f_regression':\n None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile':\n range(1, 100), 'score_func': {\n 'sklearn.feature_selection.f_regression': None}},\n 'sklearn.feature_selection.VarianceThreshold': {'threshold': [\n 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}}\n return regressor_config_dic\n\n\ndef get_mean_age(df):\n mean_age = df['Age'].mean()\n std_age = df['Age'].std()\n print('Mean Age %.2f +- %.2f' % (mean_age, std_age))\n\n\n<mask token>\n\n\ndef get_mae_for_all_generations(dataset, random_seed, generations,\n config_dict, tpot_path):\n \"\"\"\n Get the MAE values for both the training and test dataset\n :return:\n \"\"\"\n saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, \n 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict,\n generations))\n logbook = joblib.load(saved_path)\n gen = list(logbook['log'].keys())\n print('There are %d optminal pipelines' % len(gen))\n print('These are the best pipelines')\n for generation in gen:\n print(logbook['log'][generation]['pipeline_name'])\n all_mae_test = []\n all_mae_train = []\n pipeline_complexity = []\n curr_gen_idx = 0\n for generation in range(generations):\n if generation == gen[curr_gen_idx]:\n all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_test_mae']))\n all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_score']))\n pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx]\n ]['pipeline_sklearn_obj'].named_steps.keys()))\n if len(gen) > 1 and len(gen) > curr_gen_idx + 1:\n curr_gen_idx += 1\n else:\n all_mae_test.append(all_mae_test[-1])\n all_mae_train.append(all_mae_train[-1])\n pipeline_complexity.append(pipeline_complexity[-1])\n pipeline_complexity = np.array(pipeline_complexity)\n return all_mae_test, all_mae_train, pipeline_complexity\n\n\n<mask token>\n\n\ndef create_age_histogram(df, dataset):\n \"\"\"\n Get an age array and plot and save the age histogram for the analysed sample\n \"\"\"\n set_publication_style()\n plt.figure()\n path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset\n min_age = df['age'].min()\n max_age = df['age'].max()\n plt.hist(df['age'], bins=65, range=(min_age, max_age))\n plt.xlabel('Age')\n plt.ylabel('# of Subjects')\n plt.legend()\n plt.savefig(path_to_save)\n plt.close()\n\n\ndef plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=\n None, cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n cm = confusion_matrix(y_true, y_pred)\n labels = [int(x) for x in unique_labels(y_true, y_pred)]\n classes = classes[labels]\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print('Normalized confusion matrix')\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]),\n xticklabels=classes, yticklabels=classes, title=title, ylabel=\n 'True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.0\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center',\n color='white' if cm[i, j] > thresh else 'black')\n fig.tight_layout()\n return ax, cm\n\n\ndef plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n fig, ax = plt.subplots()\n im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean.\n shape[0]), xticklabels=classes, yticklabels=classes, title=title,\n ylabel='True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '{0:.2f} ± {1:.2f}'\n thresh = cm_mean.max() / 2.0\n for i in range(cm_mean.shape[0]):\n for j in range(cm_mean.shape[1]):\n ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha=\n 'center', va='center', color='white' if cm_mean[i, j] >\n thresh else 'black')\n fig.tight_layout()\n return ax\n\n\ndef plot_predicted_vs_true(true_y, predicted_y, save_path, metric):\n fig = plt.figure()\n plt.scatter(true_y, predicted_y, alpha=0.5)\n plt.ylabel('Predicted %s' % metric)\n plt.xlabel('True %s' % metric)\n plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y),\n max(true_y)), alpha=0.3, linestyle='--', color='b')\n if metric == 'Age':\n plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.savefig(save_path)\n plt.close()\n\n\n<mask token>\n\n\ndef ttest_ind_corrected(performance_a, performance_b, k=10, r=10):\n \"\"\"Corrected repeated k-fold cv test.\n The test assumes that the classifiers were evaluated using cross validation.\n\n Ref:\n Bouckaert, Remco R., and Eibe Frank. \"Evaluating the replicability of significance tests for comparing learning\n algorithms.\" Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004\n\n Args:\n performance_a: performances from classifier A\n performance_b: performances from classifier B\n k: number of folds\n r: number of repetitions\n\n Returns:\n t: t-statistic of the corrected test.\n prob: p-value of the corrected test.\n \"\"\"\n df = k * r - 1\n x = performance_a - performance_b\n m = np.mean(x)\n sigma_2 = np.var(x, ddof=1)\n denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2)\n with np.errstate(divide='ignore', invalid='ignore'):\n t = np.divide(m, denom)\n prob = stats.t.sf(np.abs(t), df) * 2\n return t, prob\n", "step-3": "<mask token>\n\n\ndef get_paths(debug, dataset):\n if debug and dataset == 'OASIS':\n project_wd = os.getcwd()\n project_data = os.path.join(project_wd, 'data')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BANC':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BOSTON':\n project_wd = os.getcwd()\n project_data = None\n project_sink = None\n elif debug and dataset == 'BANC_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif debug and dataset == 'UKBIO_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif not debug and dataset == 'OASIS':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'NaN', 'data')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BANC':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BOSTON':\n project_wd = '/code'\n project_data = None\n project_sink = None\n elif not debug and (dataset == 'BANC_freesurf' or dataset ==\n 'UKBIO_freesurf' or dataset == 'freesurf_combined'):\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'code', 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n print('Code Path: %s' % project_wd)\n print('Data Path: %s' % project_data)\n print('Data Out: %s' % project_sink)\n return project_wd, project_data, project_sink\n\n\ndef get_output_path(model, analysis, ngen, random_seed, population_size,\n debug, mutation, crossover, predicted_attribute):\n rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen,\n population_size, debug, mutation, crossover, predicted_attribute)\n output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_all_random_seed_paths(model, analysis, ngen, population_size, debug,\n mutation, crossover, predicted_attribute):\n if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis ==\n 'feat_combi' or analysis == 'vanilla_combi' or analysis ==\n 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or\n analysis == 'uniform_dist'):\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen)\n elif analysis == 'population':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, \n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n elif analysis == 'mutation':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover))\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (\n mutation, crossover))\n else:\n raise IOError('Analysis path not defined. Passed analysis was %s' %\n analysis)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis):\n \"\"\"\n This function gets the original dataset and transforms it into a uniformly\n distributed dataset.\n \"\"\"\n project_wd, project_data, project_sink = get_paths(debug, dataset)\n demographics, imgs, dataframe = get_data(project_data, dataset, debug,\n project_wd, resamplefactor, raw=raw, analysis=analysis)\n demographics['age_int'] = demographics['age'].astype('int32', copy=False)\n age_range = np.arange(demographics['age'].min(), demographics['age'].max())\n max_n = 14\n age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89]\n age_range = np.setdiff1d(age_range, age_to_remove)\n ids_to_use = []\n for age in age_range:\n ids_to_use.append(demographics.index[demographics['age_int'] == age\n ].tolist()[:max_n])\n ids_to_use = [item for sublist in ids_to_use for item in sublist]\n demographics = demographics[demographics.index.isin(ids_to_use)]\n dataframe = dataframe.loc[demographics['id']]\n print('Shape of the new demographics:')\n print(demographics.shape)\n print('Oldest %d and youngest %d subject' % (demographics['age_int'].\n max(), demographics['age_int'].min()))\n print('Number of age bins %d' % len(demographics['age_int'].unique()))\n return demographics, dataframe\n\n\ndef get_best_pipeline_paths(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute):\n output_path = get_output_path(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute)\n checkpoint_path = os.path.join(output_path, 'checkpoint_folder')\n if os.path.exists(checkpoint_path):\n shutil.rmtree(checkpoint_path)\n print('Deleted pre-exiting checkpoint folder')\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n print('Creating checkpoint folder')\n return checkpoint_path\n\n\ndef drop_missing_features(dataframe):\n \"\"\"\n This function takes a dataframe and removes the already defined missing\n columns from the dataframe.\n \"\"\"\n missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1',\n 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles',\n 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf',\n 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities',\n 'Left-non-WM-hypointensities', 'non-WM-hypointensities',\n 'Right-WM-hypointensities', 'Left-WM-hypointensities',\n 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus',\n 'Left-choroid-plexus', 'Left-Lateral-Ventricle',\n 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent']\n cleaned_df = dataframe.drop(missing_features, axis=1)\n return cleaned_df\n\n\ndef get_data_covariates(dataPath, rawsubjectsId, dataset):\n if dataset == 'OASIS':\n demographics = pd.read_csv(os.path.join(dataPath,\n 'oasis_cross-sectional.csv'))\n demographics = demographics.sort_values('ID')\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = demographics.loc[(demographics['CDR'] == 0) |\n demographics['CDR'].isnull(), 'ID']\n demographics = demographics.loc[demographics['ID'].isin(selectedSubId)]\n elif dataset == 'BANC':\n column_names = ['ID', 'original_dataset', 'sex', 'Age']\n demographics = pd.read_csv(os.path.join(dataPath,\n 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names)\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = rawsubjectsId\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n assert len(selectedSubId) == len(demographics)\n return demographics, selectedSubId\n\n\ndef _multiprocessing_resample(img, target_affine):\n resampled_img = image.resample_img(img, target_affine=target_affine,\n interpolation='nearest')\n return resampled_img\n\n\ndef _load_nibabel(filePath):\n img = nib.load(os.path.join(filePath))\n return img\n\n\ndef get_config_dictionary():\n regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': {\n 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, \n 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': {\n 'max_depth': range(1, 11), 'min_samples_split': range(2, 21),\n 'min_samples_leaf': range(1, 21)},\n 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, \n 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]},\n 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]},\n 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive',\n 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [\n 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, \n 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, \n 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {},\n 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05,\n 0.001), 'score_func': {'sklearn.feature_selection.f_regression':\n None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile':\n range(1, 100), 'score_func': {\n 'sklearn.feature_selection.f_regression': None}},\n 'sklearn.feature_selection.VarianceThreshold': {'threshold': [\n 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}}\n return regressor_config_dic\n\n\ndef get_mean_age(df):\n mean_age = df['Age'].mean()\n std_age = df['Age'].std()\n print('Mean Age %.2f +- %.2f' % (mean_age, std_age))\n\n\ndef get_data(project_data, dataset, debug, project_wd, resamplefactor, raw,\n analysis):\n \"\"\" Load the csv files and return\n :param project_data:\n :param dataset:\n :param debug:\n :param project_wd:\n :param resamplefactor:\n :raw: Which type of fressesfurfer should we analyse (the raw, where both\n datasets have not been matched or the not raw where the number of columns\n between dataset is the same)\n :return: demographics:\n :return: demographics:\n :return: dataframe.values: Just the numeric values of the dataframe\n \"\"\"\n if dataset == 'freesurf_combined' and raw == True:\n raise ValueError('The combined analysis cannot use the raw dataset')\n print('Loading Brain image data')\n elif dataset == 'OASIS':\n fileList = os.listdir(project_data)\n rawsubjectsId = [re.sub('^smwc1(.*?)\\\\_mpr-1_anon.nii$', '\\\\1',\n file) for file in fileList if file.endswith('.nii')]\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, dataset)\n get_mean_age(demographics)\n imgs = [nib.load(os.path.join(project_data, \n 'smwc1%s_mpr-1_anon.nii' % subject)) for subject in tqdm(\n selectedSubId)]\n elif dataset == 'BANC':\n project_data_path = os.path.join(project_data, 'wm_data')\n fileList = os.listdir(project_data_path)\n rawsubjectsId = [file[5:12] for file in fileList if file.endswith(\n '.nii.gz')]\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, dataset)\n get_mean_age(demographics)\n subjectsFile = [os.path.join(project_data_path, file) for file in\n fileList if file[5:12] in selectedSubId]\n with Pool() as p:\n imgs = list(tqdm(p.imap(_load_nibabel, subjectsFile), total=len\n (selectedSubId)))\n elif dataset == 'BANC_freesurf' and raw == True:\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'BANC',\n 'aparc_aseg_stats_BANC.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'},\n inplace=True)\n return demographics, None, freesurf_df\n elif dataset == 'UKBIO_freesurf' and raw == False and not analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_UKBIO.csv'), delimiter=',')\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',', index_col=False)\n demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n freesurf_df = freesurf_df.set_index('id')\n return demographics, None, freesurf_df\n elif dataset == 'BANC_freesurf' and raw == False and not analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'},\n inplace=True)\n return demographics, None, freesurf_df\n elif dataset == 'UKBIO_freesurf' and raw == True and not analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n freesurf_df = freesurf_df.drop(columns='id.4844')\n demographics = freesurf_df[['age', 'sex', 'id']].copy()\n freesurf_df = freesurf_df.set_index('id')\n return demographics, None, freesurf_df\n elif dataset == 'UKBIO_freesurf' and raw == False and analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_UKBIO_summary.csv'), delimiter=',')\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n return demographics, None, freesurf_df\n elif dataset == 'BANC_freesurf' and raw == False and analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_BANC_summary.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'},\n inplace=True)\n return demographics, None, freesurf_df\n elif dataset == 'freesurf_combined':\n ukbio_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_UKBIO.csv'), delimiter=',', index_col=0)\n banc_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0)\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n rawsubjectsId = banc_df.index\n banc_demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n ukbio_demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n freesurfer_df = pd.concat([ukbio_df, banc_df])\n tmp = banc_demographics.drop('original_dataset', axis=1)\n tmp.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True)\n tmp['sex'] = tmp['sex'].map({'F': 'female', 'M': 'male'})\n tmp['dataset'] = 'banc'\n ukbio_demographics['dataset'] = 'ukbio'\n demographics = pd.concat([ukbio_demographics, tmp], sort=False)\n bins = 17, 30, 40, 50, 60, 70, 80, 90\n group_labels = range(1, len(bins))\n demographics['age_band'] = pd.cut(demographics['age'], bins, labels\n =group_labels)\n sex_age_group = demographics.groupby(['sex', 'age_band'])\n demographics['stratify'] = sex_age_group.grouper.group_info[0] + 1\n return demographics, None, freesurfer_df\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n print('Resample the dataset by a factor of %d' % resamplefactor)\n print('Original image size: %s' % (imgs[0].shape,))\n resampleby2affine = np.array([[resamplefactor, 1, 1, 1], [1,\n resamplefactor, 1, 1], [1, 1, resamplefactor, 1], [1, 1, 1, 1]])\n target_affine = np.multiply(imgs[0].affine, resampleby2affine)\n print('Resampling Images')\n with Pool() as p:\n args = partial(_multiprocessing_resample, target_affine=target_affine)\n resampledimgs = list(tqdm(p.imap(args, imgs), total=len(imgs)))\n print('Resampled image size: %s' % (resampledimgs[0].shape,))\n print('Compute brain mask')\n MeanImgMask = masking.compute_multi_epi_mask(resampledimgs,\n lower_cutoff=0.001, upper_cutoff=0.85, opening=False)\n maskedData = [masking.apply_mask(img, MeanImgMask) for img in resampledimgs\n ]\n if debug:\n mask_path = os.path.join(project_wd, 'BayOptPy', 'tpot')\n print('Saving brain mask: %s' % mask_path)\n nib.save(MeanImgMask, os.path.join(mask_path, 'mask_%s.nii.gz' %\n dataset))\n print('Applied mask to the dataset')\n maskedData = np.array(maskedData)\n return demographics, imgs, maskedData\n\n\ndef get_mae_for_all_generations(dataset, random_seed, generations,\n config_dict, tpot_path):\n \"\"\"\n Get the MAE values for both the training and test dataset\n :return:\n \"\"\"\n saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, \n 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict,\n generations))\n logbook = joblib.load(saved_path)\n gen = list(logbook['log'].keys())\n print('There are %d optminal pipelines' % len(gen))\n print('These are the best pipelines')\n for generation in gen:\n print(logbook['log'][generation]['pipeline_name'])\n all_mae_test = []\n all_mae_train = []\n pipeline_complexity = []\n curr_gen_idx = 0\n for generation in range(generations):\n if generation == gen[curr_gen_idx]:\n all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_test_mae']))\n all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_score']))\n pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx]\n ]['pipeline_sklearn_obj'].named_steps.keys()))\n if len(gen) > 1 and len(gen) > curr_gen_idx + 1:\n curr_gen_idx += 1\n else:\n all_mae_test.append(all_mae_test[-1])\n all_mae_train.append(all_mae_train[-1])\n pipeline_complexity.append(pipeline_complexity[-1])\n pipeline_complexity = np.array(pipeline_complexity)\n return all_mae_test, all_mae_train, pipeline_complexity\n\n\n<mask token>\n\n\ndef create_age_histogram(df, dataset):\n \"\"\"\n Get an age array and plot and save the age histogram for the analysed sample\n \"\"\"\n set_publication_style()\n plt.figure()\n path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset\n min_age = df['age'].min()\n max_age = df['age'].max()\n plt.hist(df['age'], bins=65, range=(min_age, max_age))\n plt.xlabel('Age')\n plt.ylabel('# of Subjects')\n plt.legend()\n plt.savefig(path_to_save)\n plt.close()\n\n\ndef plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=\n None, cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n cm = confusion_matrix(y_true, y_pred)\n labels = [int(x) for x in unique_labels(y_true, y_pred)]\n classes = classes[labels]\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print('Normalized confusion matrix')\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]),\n xticklabels=classes, yticklabels=classes, title=title, ylabel=\n 'True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.0\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center',\n color='white' if cm[i, j] > thresh else 'black')\n fig.tight_layout()\n return ax, cm\n\n\ndef plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n fig, ax = plt.subplots()\n im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean.\n shape[0]), xticklabels=classes, yticklabels=classes, title=title,\n ylabel='True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '{0:.2f} ± {1:.2f}'\n thresh = cm_mean.max() / 2.0\n for i in range(cm_mean.shape[0]):\n for j in range(cm_mean.shape[1]):\n ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha=\n 'center', va='center', color='white' if cm_mean[i, j] >\n thresh else 'black')\n fig.tight_layout()\n return ax\n\n\ndef plot_predicted_vs_true(true_y, predicted_y, save_path, metric):\n fig = plt.figure()\n plt.scatter(true_y, predicted_y, alpha=0.5)\n plt.ylabel('Predicted %s' % metric)\n plt.xlabel('True %s' % metric)\n plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y),\n max(true_y)), alpha=0.3, linestyle='--', color='b')\n if metric == 'Age':\n plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.savefig(save_path)\n plt.close()\n\n\n<mask token>\n\n\ndef ttest_ind_corrected(performance_a, performance_b, k=10, r=10):\n \"\"\"Corrected repeated k-fold cv test.\n The test assumes that the classifiers were evaluated using cross validation.\n\n Ref:\n Bouckaert, Remco R., and Eibe Frank. \"Evaluating the replicability of significance tests for comparing learning\n algorithms.\" Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004\n\n Args:\n performance_a: performances from classifier A\n performance_b: performances from classifier B\n k: number of folds\n r: number of repetitions\n\n Returns:\n t: t-statistic of the corrected test.\n prob: p-value of the corrected test.\n \"\"\"\n df = k * r - 1\n x = performance_a - performance_b\n m = np.mean(x)\n sigma_2 = np.var(x, ddof=1)\n denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2)\n with np.errstate(divide='ignore', invalid='ignore'):\n t = np.divide(m, denom)\n prob = stats.t.sf(np.abs(t), df) * 2\n return t, prob\n", "step-4": "<mask token>\nmatplotlib.use('Agg')\n<mask token>\nsns.set()\n\n\ndef get_paths(debug, dataset):\n if debug and dataset == 'OASIS':\n project_wd = os.getcwd()\n project_data = os.path.join(project_wd, 'data')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BANC':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BOSTON':\n project_wd = os.getcwd()\n project_data = None\n project_sink = None\n elif debug and dataset == 'BANC_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif debug and dataset == 'UKBIO_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif not debug and dataset == 'OASIS':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'NaN', 'data')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BANC':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BOSTON':\n project_wd = '/code'\n project_data = None\n project_sink = None\n elif not debug and (dataset == 'BANC_freesurf' or dataset ==\n 'UKBIO_freesurf' or dataset == 'freesurf_combined'):\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'code', 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n print('Code Path: %s' % project_wd)\n print('Data Path: %s' % project_data)\n print('Data Out: %s' % project_sink)\n return project_wd, project_data, project_sink\n\n\ndef get_output_path(model, analysis, ngen, random_seed, population_size,\n debug, mutation, crossover, predicted_attribute):\n rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen,\n population_size, debug, mutation, crossover, predicted_attribute)\n output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' % random_seed)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_all_random_seed_paths(model, analysis, ngen, population_size, debug,\n mutation, crossover, predicted_attribute):\n if (analysis == 'vanilla' or analysis == 'feat_selec' or analysis ==\n 'feat_combi' or analysis == 'vanilla_combi' or analysis ==\n 'random_seed' or analysis == 'ukbio' or analysis == 'summary_data' or\n analysis == 'uniform_dist'):\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen)\n elif analysis == 'population':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, \n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%05d_population_size' % population_size, \n '%03d_generations' % ngen)\n elif analysis == 'mutation':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' % model,\n 'Output', analysis, predicted_attribute, '%03d_generations' %\n ngen, '%.01f_mut_%.01f_cross' % (mutation, crossover))\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy', \n 'tpot_%s' % model, 'Output', analysis, predicted_attribute,\n '%03d_generations' % ngen, '%.01f_mut_%.01f_cross' % (\n mutation, crossover))\n else:\n raise IOError('Analysis path not defined. Passed analysis was %s' %\n analysis)\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n return output_path\n\n\ndef get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis):\n \"\"\"\n This function gets the original dataset and transforms it into a uniformly\n distributed dataset.\n \"\"\"\n project_wd, project_data, project_sink = get_paths(debug, dataset)\n demographics, imgs, dataframe = get_data(project_data, dataset, debug,\n project_wd, resamplefactor, raw=raw, analysis=analysis)\n demographics['age_int'] = demographics['age'].astype('int32', copy=False)\n age_range = np.arange(demographics['age'].min(), demographics['age'].max())\n max_n = 14\n age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89]\n age_range = np.setdiff1d(age_range, age_to_remove)\n ids_to_use = []\n for age in age_range:\n ids_to_use.append(demographics.index[demographics['age_int'] == age\n ].tolist()[:max_n])\n ids_to_use = [item for sublist in ids_to_use for item in sublist]\n demographics = demographics[demographics.index.isin(ids_to_use)]\n dataframe = dataframe.loc[demographics['id']]\n print('Shape of the new demographics:')\n print(demographics.shape)\n print('Oldest %d and youngest %d subject' % (demographics['age_int'].\n max(), demographics['age_int'].min()))\n print('Number of age bins %d' % len(demographics['age_int'].unique()))\n return demographics, dataframe\n\n\ndef get_best_pipeline_paths(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute):\n output_path = get_output_path(model, analysis, ngen, random_seed,\n population_size, debug, mutation, crossover, predicted_attribute)\n checkpoint_path = os.path.join(output_path, 'checkpoint_folder')\n if os.path.exists(checkpoint_path):\n shutil.rmtree(checkpoint_path)\n print('Deleted pre-exiting checkpoint folder')\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n print('Creating checkpoint folder')\n return checkpoint_path\n\n\ndef drop_missing_features(dataframe):\n \"\"\"\n This function takes a dataframe and removes the already defined missing\n columns from the dataframe.\n \"\"\"\n missing_features = ['BrainSegVolNotVent', 'BrainSegVolNotVent.1',\n 'BrainSegVolNotVent.2', 'eTIV', 'eTIV.1', 'SurfaceHoles',\n 'rhSurfaceHoles', 'lhSurfaceHoles', 'BrainSegVolNotVentSurf',\n 'BrainSegVol', 'Optic-Chiasm', 'Right-non-WM-hypointensities',\n 'Left-non-WM-hypointensities', 'non-WM-hypointensities',\n 'Right-WM-hypointensities', 'Left-WM-hypointensities',\n 'WM-hypointensities', '5th-Ventricle', 'Right-choroid-plexus',\n 'Left-choroid-plexus', 'Left-Lateral-Ventricle',\n 'Right-Lateral-Ventricle', 'Left-Inf-Lat-Vent', 'Right-Inf-Lat-Vent']\n cleaned_df = dataframe.drop(missing_features, axis=1)\n return cleaned_df\n\n\ndef get_data_covariates(dataPath, rawsubjectsId, dataset):\n if dataset == 'OASIS':\n demographics = pd.read_csv(os.path.join(dataPath,\n 'oasis_cross-sectional.csv'))\n demographics = demographics.sort_values('ID')\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = demographics.loc[(demographics['CDR'] == 0) |\n demographics['CDR'].isnull(), 'ID']\n demographics = demographics.loc[demographics['ID'].isin(selectedSubId)]\n elif dataset == 'BANC':\n column_names = ['ID', 'original_dataset', 'sex', 'Age']\n demographics = pd.read_csv(os.path.join(dataPath,\n 'original_dataset', 'BANC', 'BANC_2016.csv'), names=column_names)\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n demographics = demographics.loc[~demographics['ID'].isin(\n missingsubjectsId)]\n selectedSubId = rawsubjectsId\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n assert len(selectedSubId) == len(demographics)\n return demographics, selectedSubId\n\n\ndef _multiprocessing_resample(img, target_affine):\n resampled_img = image.resample_img(img, target_affine=target_affine,\n interpolation='nearest')\n return resampled_img\n\n\ndef _load_nibabel(filePath):\n img = nib.load(os.path.join(filePath))\n return img\n\n\ndef get_config_dictionary():\n regressor_config_dic = {'sklearn.linear_model.ElasticNetCV': {\n 'l1_ratio': np.arange(0.0, 1.01, 0.05), 'tol': [1e-05, 0.0001, \n 0.001, 0.01, 0.1]}, 'sklearn.tree.DecisionTreeRegressor': {\n 'max_depth': range(1, 11), 'min_samples_split': range(2, 21),\n 'min_samples_leaf': range(1, 21)},\n 'sklearn.neighbors.KNeighborsRegressor': {'n_neighbors': range(1, \n 101), 'weights': ['uniform', 'distance'], 'p': [1, 2]},\n 'sklearn.linear_model.LassoLarsCV': {'normalize': [True, False]},\n 'sklearn.svm.LinearSVR': {'loss': ['epsilon_insensitive',\n 'squared_epsilon_insensitive'], 'dual': [True, False], 'tol': [\n 1e-05, 0.0001, 0.001, 0.01, 0.1], 'C': [0.0001, 0.001, 0.01, 0.1, \n 0.5, 1.0, 5.0, 10.0, 15.0, 20.0, 25.0], 'epsilon': [0.0001, 0.001, \n 0.01, 0.1, 1.0]}, 'sklearn.linear_model.RidgeCV': {},\n 'sklearn.feature_selection.SelectFwe': {'alpha': np.arange(0, 0.05,\n 0.001), 'score_func': {'sklearn.feature_selection.f_regression':\n None}}, 'sklearn.feature_selection.SelectPercentile': {'percentile':\n range(1, 100), 'score_func': {\n 'sklearn.feature_selection.f_regression': None}},\n 'sklearn.feature_selection.VarianceThreshold': {'threshold': [\n 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]}}\n return regressor_config_dic\n\n\ndef get_mean_age(df):\n mean_age = df['Age'].mean()\n std_age = df['Age'].std()\n print('Mean Age %.2f +- %.2f' % (mean_age, std_age))\n\n\ndef get_data(project_data, dataset, debug, project_wd, resamplefactor, raw,\n analysis):\n \"\"\" Load the csv files and return\n :param project_data:\n :param dataset:\n :param debug:\n :param project_wd:\n :param resamplefactor:\n :raw: Which type of fressesfurfer should we analyse (the raw, where both\n datasets have not been matched or the not raw where the number of columns\n between dataset is the same)\n :return: demographics:\n :return: demographics:\n :return: dataframe.values: Just the numeric values of the dataframe\n \"\"\"\n if dataset == 'freesurf_combined' and raw == True:\n raise ValueError('The combined analysis cannot use the raw dataset')\n print('Loading Brain image data')\n elif dataset == 'OASIS':\n fileList = os.listdir(project_data)\n rawsubjectsId = [re.sub('^smwc1(.*?)\\\\_mpr-1_anon.nii$', '\\\\1',\n file) for file in fileList if file.endswith('.nii')]\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, dataset)\n get_mean_age(demographics)\n imgs = [nib.load(os.path.join(project_data, \n 'smwc1%s_mpr-1_anon.nii' % subject)) for subject in tqdm(\n selectedSubId)]\n elif dataset == 'BANC':\n project_data_path = os.path.join(project_data, 'wm_data')\n fileList = os.listdir(project_data_path)\n rawsubjectsId = [file[5:12] for file in fileList if file.endswith(\n '.nii.gz')]\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, dataset)\n get_mean_age(demographics)\n subjectsFile = [os.path.join(project_data_path, file) for file in\n fileList if file[5:12] in selectedSubId]\n with Pool() as p:\n imgs = list(tqdm(p.imap(_load_nibabel, subjectsFile), total=len\n (selectedSubId)))\n elif dataset == 'BANC_freesurf' and raw == True:\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'BANC',\n 'aparc_aseg_stats_BANC.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'},\n inplace=True)\n return demographics, None, freesurf_df\n elif dataset == 'UKBIO_freesurf' and raw == False and not analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_UKBIO.csv'), delimiter=',')\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',', index_col=False)\n demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n freesurf_df = freesurf_df.set_index('id')\n return demographics, None, freesurf_df\n elif dataset == 'BANC_freesurf' and raw == False and not analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'},\n inplace=True)\n return demographics, None, freesurf_df\n elif dataset == 'UKBIO_freesurf' and raw == True and not analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n freesurf_df = freesurf_df.drop(columns='id.4844')\n demographics = freesurf_df[['age', 'sex', 'id']].copy()\n freesurf_df = freesurf_df.set_index('id')\n return demographics, None, freesurf_df\n elif dataset == 'UKBIO_freesurf' and raw == False and analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_UKBIO_summary.csv'), delimiter=',')\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n return demographics, None, freesurf_df\n elif dataset == 'BANC_freesurf' and raw == False and analysis == 'summary_data':\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_BANC_summary.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n demographics.rename(index=str, columns={'ID': 'id', 'Age': 'age'},\n inplace=True)\n return demographics, None, freesurf_df\n elif dataset == 'freesurf_combined':\n ukbio_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_UKBIO.csv'), delimiter=',', index_col=0)\n banc_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'matched_dataset',\n 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0)\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess', 'original_dataset', 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n rawsubjectsId = banc_df.index\n banc_demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId, 'BANC')\n ukbio_demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n freesurfer_df = pd.concat([ukbio_df, banc_df])\n tmp = banc_demographics.drop('original_dataset', axis=1)\n tmp.rename(index=str, columns={'ID': 'id', 'Age': 'age'}, inplace=True)\n tmp['sex'] = tmp['sex'].map({'F': 'female', 'M': 'male'})\n tmp['dataset'] = 'banc'\n ukbio_demographics['dataset'] = 'ukbio'\n demographics = pd.concat([ukbio_demographics, tmp], sort=False)\n bins = 17, 30, 40, 50, 60, 70, 80, 90\n group_labels = range(1, len(bins))\n demographics['age_band'] = pd.cut(demographics['age'], bins, labels\n =group_labels)\n sex_age_group = demographics.groupby(['sex', 'age_band'])\n demographics['stratify'] = sex_age_group.grouper.group_info[0] + 1\n return demographics, None, freesurfer_df\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n print('Resample the dataset by a factor of %d' % resamplefactor)\n print('Original image size: %s' % (imgs[0].shape,))\n resampleby2affine = np.array([[resamplefactor, 1, 1, 1], [1,\n resamplefactor, 1, 1], [1, 1, resamplefactor, 1], [1, 1, 1, 1]])\n target_affine = np.multiply(imgs[0].affine, resampleby2affine)\n print('Resampling Images')\n with Pool() as p:\n args = partial(_multiprocessing_resample, target_affine=target_affine)\n resampledimgs = list(tqdm(p.imap(args, imgs), total=len(imgs)))\n print('Resampled image size: %s' % (resampledimgs[0].shape,))\n print('Compute brain mask')\n MeanImgMask = masking.compute_multi_epi_mask(resampledimgs,\n lower_cutoff=0.001, upper_cutoff=0.85, opening=False)\n maskedData = [masking.apply_mask(img, MeanImgMask) for img in resampledimgs\n ]\n if debug:\n mask_path = os.path.join(project_wd, 'BayOptPy', 'tpot')\n print('Saving brain mask: %s' % mask_path)\n nib.save(MeanImgMask, os.path.join(mask_path, 'mask_%s.nii.gz' %\n dataset))\n print('Applied mask to the dataset')\n maskedData = np.array(maskedData)\n return demographics, imgs, maskedData\n\n\ndef get_mae_for_all_generations(dataset, random_seed, generations,\n config_dict, tpot_path):\n \"\"\"\n Get the MAE values for both the training and test dataset\n :return:\n \"\"\"\n saved_path = os.path.join(tpot_path, 'random_seed_%03d' % random_seed, \n 'tpot_%s_%s_%03dgen_pipelines.dump' % (dataset, config_dict,\n generations))\n logbook = joblib.load(saved_path)\n gen = list(logbook['log'].keys())\n print('There are %d optminal pipelines' % len(gen))\n print('These are the best pipelines')\n for generation in gen:\n print(logbook['log'][generation]['pipeline_name'])\n all_mae_test = []\n all_mae_train = []\n pipeline_complexity = []\n curr_gen_idx = 0\n for generation in range(generations):\n if generation == gen[curr_gen_idx]:\n all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_test_mae']))\n all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]][\n 'pipeline_score']))\n pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx]\n ]['pipeline_sklearn_obj'].named_steps.keys()))\n if len(gen) > 1 and len(gen) > curr_gen_idx + 1:\n curr_gen_idx += 1\n else:\n all_mae_test.append(all_mae_test[-1])\n all_mae_train.append(all_mae_train[-1])\n pipeline_complexity.append(pipeline_complexity[-1])\n pipeline_complexity = np.array(pipeline_complexity)\n return all_mae_test, all_mae_train, pipeline_complexity\n\n\ndef set_publication_style():\n plt.style.use(['seaborn-white', 'seaborn-talk'])\n matplotlib.rc('font', family='Times New Roman')\n sns.set_style('white', {'axes.spines.top': False, 'axes.spines.right': \n False, 'axes.labelsize': 'large'})\n\n\ndef create_age_histogram(df, dataset):\n \"\"\"\n Get an age array and plot and save the age histogram for the analysed sample\n \"\"\"\n set_publication_style()\n plt.figure()\n path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' % dataset\n min_age = df['age'].min()\n max_age = df['age'].max()\n plt.hist(df['age'], bins=65, range=(min_age, max_age))\n plt.xlabel('Age')\n plt.ylabel('# of Subjects')\n plt.legend()\n plt.savefig(path_to_save)\n plt.close()\n\n\ndef plot_confusion_matrix(y_true, y_pred, classes, normalize=False, title=\n None, cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n cm = confusion_matrix(y_true, y_pred)\n labels = [int(x) for x in unique_labels(y_true, y_pred)]\n classes = classes[labels]\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print('Normalized confusion matrix')\n else:\n print('Confusion matrix, without normalization')\n print(cm)\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm.shape[1]), yticks=np.arange(cm.shape[0]),\n xticklabels=classes, yticklabels=classes, title=title, ylabel=\n 'True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.0\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt), ha='center', va='center',\n color='white' if cm[i, j] > thresh else 'black')\n fig.tight_layout()\n return ax, cm\n\n\ndef plot_confusion_matrix_boosting(cm_mean, cm_std, classes, title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n fig, ax = plt.subplots()\n im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n ax.set(xticks=np.arange(cm_mean.shape[1]), yticks=np.arange(cm_mean.\n shape[0]), xticklabels=classes, yticklabels=classes, title=title,\n ylabel='True label', xlabel='Predicted label')\n plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode=\n 'anchor')\n fmt = '{0:.2f} ± {1:.2f}'\n thresh = cm_mean.max() / 2.0\n for i in range(cm_mean.shape[0]):\n for j in range(cm_mean.shape[1]):\n ax.text(j, i, fmt.format(cm_mean[i, j], cm_std[i, j]), ha=\n 'center', va='center', color='white' if cm_mean[i, j] >\n thresh else 'black')\n fig.tight_layout()\n return ax\n\n\ndef plot_predicted_vs_true(true_y, predicted_y, save_path, metric):\n fig = plt.figure()\n plt.scatter(true_y, predicted_y, alpha=0.5)\n plt.ylabel('Predicted %s' % metric)\n plt.xlabel('True %s' % metric)\n plt.plot(np.arange(min(true_y), max(true_y)), np.arange(min(true_y),\n max(true_y)), alpha=0.3, linestyle='--', color='b')\n if metric == 'Age':\n plt.xticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.yticks(np.arange(min(min(true_y), min(predicted_y)), max(max(\n true_y), max(predicted_y)), step=10))\n plt.savefig(save_path)\n plt.close()\n\n\ndef load_cognitive_data(project_data):\n cog_path = os.path.join(project_data, 'cog_ukbio')\n cog_df = pd.read_csv(os.path.join(cog_path, 'UKB_10k_cog_bmi.csv'))\n cog_df = cog_df.set_index('ID')\n return cog_df\n\n\ndef ttest_ind_corrected(performance_a, performance_b, k=10, r=10):\n \"\"\"Corrected repeated k-fold cv test.\n The test assumes that the classifiers were evaluated using cross validation.\n\n Ref:\n Bouckaert, Remco R., and Eibe Frank. \"Evaluating the replicability of significance tests for comparing learning\n algorithms.\" Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004\n\n Args:\n performance_a: performances from classifier A\n performance_b: performances from classifier B\n k: number of folds\n r: number of repetitions\n\n Returns:\n t: t-statistic of the corrected test.\n prob: p-value of the corrected test.\n \"\"\"\n df = k * r - 1\n x = performance_a - performance_b\n m = np.mean(x)\n sigma_2 = np.var(x, ddof=1)\n denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2)\n with np.errstate(divide='ignore', invalid='ignore'):\n t = np.divide(m, denom)\n prob = stats.t.sf(np.abs(t), df) * 2\n return t, prob\n", "step-5": "import joblib\nimport os\nimport shutil\nimport re\nfrom scipy import stats\nfrom functools import partial\n\nimport pandas as pd\nfrom multiprocessing import Process, Pool\nfrom nilearn import masking, image\nimport nibabel as nib\nimport numpy as np\nfrom tqdm import tqdm\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.utils.multiclass import unique_labels\nimport seaborn as sns\nsns.set()\n\ndef get_paths(debug, dataset):\n\n if debug and dataset == 'OASIS':\n project_wd = os.getcwd()\n project_data = os.path.join(project_wd, 'data')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BANC':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif debug and dataset == 'BOSTON':\n project_wd = os.getcwd()\n project_data = None\n project_sink = None\n elif debug and dataset == 'BANC_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif debug and dataset == 'UKBIO_freesurf':\n project_wd = os.getcwd()\n project_data = os.path.join(os.getenv('HOME'), 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n elif not debug and dataset == 'OASIS':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'NaN', 'data')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BANC':\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'data', 'NaN', 'BANC_2016')\n project_sink = os.path.join(project_data, 'output')\n elif not debug and dataset == 'BOSTON':\n project_wd = '/code'\n project_data = None\n project_sink = None\n elif not debug and (dataset == 'BANC_freesurf' or\n dataset == 'UKBIO_freesurf' or\n dataset == 'freesurf_combined'\n ):\n project_wd = '/code'\n project_data = os.path.join(os.sep, 'code', 'BayOptPy',\n 'freesurfer_preprocess')\n project_sink = None\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n\n print('Code Path: %s' %project_wd)\n print('Data Path: %s' %project_data)\n print('Data Out: %s' %project_sink )\n return project_wd, project_data, project_sink\n\ndef get_output_path(model, analysis, ngen, random_seed, population_size, debug,\n mutation, crossover, predicted_attribute):\n # Check if output path exists, otherwise create it\n rnd_seed_path = get_all_random_seed_paths(model, analysis, ngen, population_size,\n debug, mutation, crossover,\n predicted_attribute)\n output_path = os.path.join(rnd_seed_path, 'random_seed_%03d' %random_seed)\n\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n return output_path\n\ndef get_all_random_seed_paths(model, analysis, ngen, population_size, debug, mutation,\n crossover, predicted_attribute):\n # As they should have been created by the get_output_path, do not create\n # path but just find its location\n if analysis == 'vanilla' or analysis == 'feat_selec' or \\\n analysis == 'feat_combi' or analysis == 'vanilla_combi' or \\\n analysis == 'random_seed' or analysis == 'ukbio' or \\\n analysis == 'summary_data' or analysis == 'uniform_dist':\n if debug:\n output_path = os.path.join('BayOptPy', 'tpot_%s' %model, 'Output',\n analysis, predicted_attribute,\n '%03d_generations' %ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy',\n 'tpot_%s' %model,\n 'Output', analysis,\n predicted_attribute,\n '%03d_generations' %ngen)\n elif analysis == 'population':\n if debug:\n output_path = os.path.join('BayOptPy',\n 'tpot_%s' %model,\n 'Output', analysis, predicted_attribute,\n '%05d_population_size' %population_size,\n '%03d_generations' %ngen)\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy',\n 'tpot_%s' %model,\n 'Output', analysis,\n predicted_attribute,\n '%05d_population_size' %population_size,\n '%03d_generations' %ngen)\n elif analysis == 'mutation':\n if debug:\n output_path = os.path.join('BayOptPy',\n 'tpot_%s' %model,\n 'Output', analysis,\n predicted_attribute,\n '%03d_generations' %ngen,\n '%.01f_mut_%.01f_cross' %(mutation, crossover))\n else:\n output_path = os.path.join(os.sep, 'code', 'BayOptPy',\n 'tpot_%s' %model,\n 'Output', analysis,\n predicted_attribute,\n '%03d_generations' %ngen,\n '%.01f_mut_%.01f_cross' %(mutation, crossover))\n\n else:\n raise IOError('Analysis path not defined. Passed analysis was %s'\n %analysis)\n\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n\n return output_path\n\ndef get_uniform_dist_data(debug, dataset, resamplefactor, raw, analysis):\n \"\"\"\n This function gets the original dataset and transforms it into a uniformly\n distributed dataset.\n \"\"\"\n\n project_wd, project_data, project_sink = get_paths(debug, dataset)\n\n demographics, imgs, dataframe = get_data(project_data, dataset,\n debug, project_wd,\n resamplefactor,\n raw=raw,\n analysis=analysis)\n\n # transform age into ints\n demographics['age_int'] = demographics['age'].astype('int32', copy=False)\n\n # Select 14 subjects for all ages that have 14 representatives.\n age_range = np.arange(demographics['age'].min(), demographics['age'].max())\n # remove entry where you don't have 14 subjects\n max_n = 14\n age_to_remove = [35, 36, 39, 42, 78, 79, 80, 81, 82, 83, 85, 89]\n age_range = np.setdiff1d(age_range, age_to_remove)\n # iterate over the dataframe and select 14 subjects for each age range\n ids_to_use = []\n for age in age_range:\n ids_to_use.append(demographics.index[demographics['age_int'] ==\n age].tolist()[:max_n])\n\n # flatten ids_to_use\n ids_to_use = [item for sublist in ids_to_use for item in sublist]\n # Filter the demographics dataframe\n demographics = demographics[demographics.index.isin(ids_to_use)]\n # set subject's id as index\n # filter dataset using index of the subjects\n dataframe = dataframe.loc[demographics['id']]\n\n # Print some diagnosis\n print('Shape of the new demographics:')\n print(demographics.shape)\n print('Oldest %d and youngest %d subject' %(demographics['age_int'].max(),\n demographics['age_int'].min()))\n print('Number of age bins %d' %len(demographics['age_int'].unique()))\n return demographics, dataframe\n\n\ndef get_best_pipeline_paths(model, analysis, ngen, random_seed, population_size, debug,\n mutation, crossover, predicted_attribute):\n # check if folder exists and in case yes, remove it as new runs will save\n # new files without overwritting\n output_path = get_output_path(model, analysis, ngen, random_seed, population_size,\n debug, mutation, crossover,\n predicted_attribute)\n checkpoint_path = os.path.join(output_path, 'checkpoint_folder')\n\n # Delete folder if it already exists and create a new one\n if os.path.exists(checkpoint_path):\n shutil.rmtree(checkpoint_path)\n print('Deleted pre-exiting checkpoint folder')\n\n if not os.path.exists(checkpoint_path):\n os.makedirs(checkpoint_path)\n print('Creating checkpoint folder')\n\n return checkpoint_path\n\ndef drop_missing_features(dataframe):\n '''\n This function takes a dataframe and removes the already defined missing\n columns from the dataframe.\n '''\n missing_features = [# This features are repeated or missing on the BIOBANK\n # dataset\n 'BrainSegVolNotVent',\n 'BrainSegVolNotVent.1',\n 'BrainSegVolNotVent.2',\n 'eTIV',\n 'eTIV.1',\n # Drop additional features that are 0 or have no\n # biological meaning\n 'SurfaceHoles',\n 'rhSurfaceHoles',\n 'lhSurfaceHoles',\n 'BrainSegVolNotVentSurf',\n 'BrainSegVol',\n 'Optic-Chiasm',\n 'Right-non-WM-hypointensities',\n 'Left-non-WM-hypointensities',\n 'non-WM-hypointensities',\n 'Right-WM-hypointensities',\n 'Left-WM-hypointensities',\n 'WM-hypointensities',\n '5th-Ventricle',\n 'Right-choroid-plexus',\n 'Left-choroid-plexus',\n 'Left-Lateral-Ventricle',\n 'Right-Lateral-Ventricle',\n 'Left-Inf-Lat-Vent',\n 'Right-Inf-Lat-Vent',\n\n ]\n\n\n cleaned_df = dataframe.drop(missing_features, axis=1)\n return cleaned_df\n\ndef get_data_covariates(dataPath, rawsubjectsId, dataset):\n if dataset == 'OASIS':\n # Load the demographic details from the dataset\n demographics = pd.read_csv(os.path.join(dataPath, 'oasis_cross-sectional.csv'))\n # sort demographics by ascending id\n demographics = demographics.sort_values('ID')\n\n # Check if there is any subject for which we have the fmri data but no demographics\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n # remove the demographic data from the missing subjects\n demographics = demographics.loc[~demographics['ID'].isin(missingsubjectsId)]\n\n # list of subjects that do not have dementia (CDR > 0)\n selectedSubId = demographics.loc[(demographics['CDR'] == 0) | (demographics['CDR'].isnull()), 'ID']\n # filter demographics to exclude those with CDR > 0\n demographics = demographics.loc[demographics['ID'].isin(selectedSubId)]\n\n elif dataset == 'BANC':\n # Load the demographic details from the dataset\n column_names = ['ID', 'original_dataset', 'sex', 'Age']\n demographics = pd.read_csv(os.path.join(dataPath,'original_dataset',\n 'BANC',\n 'BANC_2016.csv'), names=column_names)\n # Check if there is any subject for which we have the fmri data but no demographics\n missingsubjectsId = list(set(demographics['ID']) ^ set(rawsubjectsId))\n # remove the demographic data from the missing subjects\n demographics = demographics.loc[~demographics['ID'].isin(missingsubjectsId)]\n selectedSubId = rawsubjectsId\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n\n # do some sanity checks\n # Check if you have the same number of selectedsubjectsid as the demographic information\n assert(len(selectedSubId) == len(demographics))\n\n return demographics, selectedSubId\n\n\ndef _multiprocessing_resample(img, target_affine):\n resampled_img = image.resample_img(img, target_affine=target_affine,\n interpolation='nearest')\n return resampled_img\n\n\ndef _load_nibabel(filePath):\n img = nib.load(os.path.join(filePath))\n return img\n\ndef get_config_dictionary():\n # Define the same default pipeline as TPOT light but without the preprocessing operators\n regressor_config_dic = {\n\n 'sklearn.linear_model.ElasticNetCV': {\n 'l1_ratio': np.arange(0.0, 1.01, 0.05),\n 'tol': [1e-5, 1e-4, 1e-3, 1e-2, 1e-1]\n },\n\n 'sklearn.tree.DecisionTreeRegressor': {\n 'max_depth': range(1, 11),\n 'min_samples_split': range(2, 21),\n 'min_samples_leaf': range(1, 21)\n },\n\n 'sklearn.neighbors.KNeighborsRegressor': {\n 'n_neighbors': range(1, 101),\n 'weights': [\"uniform\", \"distance\"],\n 'p': [1, 2]\n },\n\n 'sklearn.linear_model.LassoLarsCV': {\n 'normalize': [True, False]\n },\n\n 'sklearn.svm.LinearSVR': {\n 'loss': [\"epsilon_insensitive\", \"squared_epsilon_insensitive\"],\n 'dual': [True, False],\n 'tol': [1e-5, 1e-4, 1e-3, 1e-2, 1e-1],\n 'C': [1e-4, 1e-3, 1e-2, 1e-1, 0.5, 1., 5., 10., 15., 20., 25.],\n 'epsilon': [1e-4, 1e-3, 1e-2, 1e-1, 1.]\n },\n\n 'sklearn.linear_model.RidgeCV': {\n },\n\n # Selectors\n 'sklearn.feature_selection.SelectFwe': {\n 'alpha': np.arange(0, 0.05, 0.001),\n 'score_func': {\n 'sklearn.feature_selection.f_regression': None\n }\n },\n\n 'sklearn.feature_selection.SelectPercentile': {\n 'percentile': range(1, 100),\n 'score_func': {\n 'sklearn.feature_selection.f_regression': None\n }\n },\n\n 'sklearn.feature_selection.VarianceThreshold': {\n 'threshold': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.2]\n }\n\n }\n return regressor_config_dic\n\ndef get_mean_age(df):\n mean_age = df['Age'].mean()\n std_age = df['Age'].std()\n print('Mean Age %.2f +- %.2f' %(mean_age, std_age))\n\ndef get_data(project_data, dataset, debug, project_wd, resamplefactor, raw,\n analysis):\n ''' Load the csv files and return\n :param project_data:\n :param dataset:\n :param debug:\n :param project_wd:\n :param resamplefactor:\n :raw: Which type of fressesfurfer should we analyse (the raw, where both\n datasets have not been matched or the not raw where the number of columns\n between dataset is the same)\n :return: demographics:\n :return: demographics:\n :return: dataframe.values: Just the numeric values of the dataframe\n '''\n\n if dataset == 'freesurf_combined' and raw == True:\n raise ValueError('The combined analysis cannot use the raw dataset')\n print('Loading Brain image data')\n elif dataset == 'OASIS':\n # remove the file end and get list of all used subjects\n fileList = os.listdir(project_data)\n rawsubjectsId = [re.sub(r'^smwc1(.*?)\\_mpr-1_anon.nii$', '\\\\1', file) for file in fileList if file.endswith('.nii')]\n # TODO: Change this. For testing purpose select just the first 5 subjects\n #rawsubjectsId = rawsubjectsId[:25]\n\n # Load the demographics for each subject\n demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset)\n # print subjects mean age\n get_mean_age(demographics)\n # Load image proxies\n imgs = [nib.load(os.path.join(project_data, 'smwc1%s_mpr-1_anon.nii' %subject)) for subject in tqdm(selectedSubId)]\n\n elif dataset == 'BANC':\n # For now, performing analysis on White Matter.\n project_data_path = os.path.join(project_data, 'wm_data')\n # remove the file end and get list of all used subjects\n fileList = os.listdir(project_data_path)\n rawsubjectsId = [file[5:12] for file in fileList if file.endswith('.nii.gz')]\n # TODO: select only a set of 5 subjects\n # rawsubjectsId = rawsubjectsId[:5]\n\n # Load the demographics for each subject\n demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, dataset)\n # print subjects mean age\n get_mean_age(demographics)\n # Get the file path of the selected subjects\n subjectsFile = [os.path.join(project_data_path, file) for file in fileList if file[5:12] in selectedSubId]\n\n # Load image proxies\n with Pool() as p:\n imgs = list(tqdm(p.imap(_load_nibabel, subjectsFile), total=len(selectedSubId)))\n\n elif (dataset == 'BANC_freesurf' and raw==True):\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'original_dataset',\n 'BANC',\n 'aparc_aseg_stats_BANC.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n\n # Load the demographics for each subject\n demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC')\n # return numpy array of the dataframe\n # Rename columns to maintain consistency withe ukbio\n demographics.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True)\n return demographics, None, freesurf_df\n\n elif (dataset == 'UKBIO_freesurf' and raw==False and not\n analysis=='summary_data'):\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'matched_dataset',\n 'aparc_aseg_UKBIO.csv'), delimiter=',')\n # Read the full matrix to get the demographics information\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'original_dataset',\n 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'),\n delimiter=',',\n index_col=False)\n demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n freesurf_df = freesurf_df.set_index('id')\n return demographics, None, freesurf_df\n elif (dataset == 'BANC_freesurf' and raw==False and not\n analysis=='summary_data'):\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'matched_dataset',\n 'aparc_aseg_BANC.csv'), delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n\n # Load the demographics for each subject\n demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC')\n # return numpy array of the dataframe\n # Rename columns to maintain consistency withe ukbio\n demographics.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True)\n return demographics, None, freesurf_df\n\n elif (dataset == 'UKBIO_freesurf' and raw==True and not\n analysis=='summary_data'):\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'original_dataset',\n 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n freesurf_df = freesurf_df.drop(columns='id.4844')\n demographics = freesurf_df[['age', 'sex', 'id']].copy()\n freesurf_df = freesurf_df.set_index('id')\n return demographics, None, freesurf_df\n elif (dataset == 'UKBIO_freesurf' and raw==False and\n analysis=='summary_data'):\n # This dataset contains only 21 feature that represent summary metrics\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'matched_dataset',\n 'aparc_aseg_UKBIO_summary.csv'), delimiter=',')\n # Read the full matrix to get the demographics information\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'original_dataset',\n 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n return demographics, None, freesurf_df\n elif (dataset == 'BANC_freesurf' and raw==False and\n analysis=='summary_data'):\n # This dataset contains only 21 feature that represent summary metrics\n freesurf_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'matched_dataset',\n 'aparc_aseg_BANC_summary.csv'),\n delimiter=',', index_col=0)\n rawsubjectsId = freesurf_df.index\n\n # Load the demographics for each subject\n demographics, selectedSubId = get_data_covariates(project_data, rawsubjectsId, 'BANC')\n # Rename columns to maintain consistency withe ukbio\n demographics.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True)\n return demographics, None, freesurf_df\n\n elif (dataset == 'freesurf_combined'):\n ukbio_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'matched_dataset',\n 'aparc_aseg_UKBIO.csv'),\n delimiter=',', index_col=0)\n\n banc_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'matched_dataset',\n 'aparc_aseg_BANC.csv'),\n delimiter=',', index_col=0)\n ukbio_full_df = pd.read_csv(os.path.join(project_wd, 'BayOptPy',\n 'freesurfer_preprocess',\n 'original_dataset',\n 'UKBIO',\n 'UKB_10k_FS_4844_combined.csv'), delimiter=',')\n rawsubjectsId = banc_df.index\n # Load the demographics for each subject\n banc_demographics, selectedSubId = get_data_covariates(project_data,\n rawsubjectsId,\n 'BANC')\n ukbio_demographics = ukbio_full_df[['age', 'sex', 'id']].copy()\n # Concatenate both freesurfeer datasets\n freesurfer_df = pd.concat([ukbio_df, banc_df])\n\n # Concatenate demographics information (Age and Sex)\n tmp = banc_demographics.drop('original_dataset', axis=1)\n tmp.rename(index=str, columns={'ID':'id', 'Age': 'age'}, inplace=True)\n # transform M/F into male/female\n tmp['sex'] = tmp['sex'].map({'F': 'female', 'M': 'male'})\n # Add column to specify dataset\n tmp['dataset'] = 'banc'\n ukbio_demographics['dataset'] = 'ukbio'\n demographics = pd.concat([ukbio_demographics, tmp], sort=False)\n # TODO: For now assume that the index in the BIOBANK correspond to th\n # Stratify subjects. Divide them into classes <30, 30<40, 40<50, 50<60,\n # 60<70, 70<80, 80<90, 90<100. Each age will be then further stratified\n # into F/M.\n bins = (17, 30, 40, 50, 60, 70, 80, 90)\n group_labels = range(1,len(bins))\n demographics['age_band'] = pd.cut(demographics['age'], bins,\n labels=group_labels)\n sex_age_group = demographics.groupby(['sex', 'age_band'])\n # Note that the following groups are created:\n # ('female', 1), ('female', 2), ('female', 3), ('female', 4), ('female', 5),\n # ('female', 6), ('female', 7), ('male', 1), ('male', 2), ('male', 3),\n # ('male', 4), ('male', 5), ('male', 6), ('male', 7)]\n # This will label the groups cited above in a crescent order. In total\n # you will have 1-14 groups, grouped according to their age and sex\n demographics['stratify'] = sex_age_group.grouper.group_info[0] + 1\n #same order between both fines\n return demographics, None, freesurfer_df\n\n else:\n raise ValueError('Analysis for this dataset is not yet implemented!')\n\n print('Resample the dataset by a factor of %d' %resamplefactor)\n print('Original image size: %s' %(imgs[0].shape,))\n # resample dataset to a lower quality. Increase the voxel size by two\n resampleby2affine = np.array([[resamplefactor, 1, 1, 1],\n [1, resamplefactor, 1, 1],\n [1, 1, resamplefactor, 1],\n [1, 1, 1, 1]])\n target_affine = np.multiply(imgs[0].affine, resampleby2affine)\n print('Resampling Images')\n with Pool() as p:\n args = partial(_multiprocessing_resample, target_affine=target_affine)\n resampledimgs = list(tqdm(p.imap(args, imgs), total=len(imgs)))\n print('Resampled image size: %s' %(resampledimgs[0].shape,))\n\n # Use nilearn to mask only the brain voxels across subjects\n print('Compute brain mask')\n #The lower and the upper_cutoff represent the lower and the upper fraction of the histogram to be discarded\n MeanImgMask = masking.compute_multi_epi_mask(resampledimgs, lower_cutoff=0.001, upper_cutoff=.85, opening=False)\n # Apply the group mask on all subjects.\n # Note: The apply_mask function returns the flattened data as a numpy array\n maskedData = [masking.apply_mask(img, MeanImgMask) for img in resampledimgs]\n # If debug option is set, save an nifti image of the image.\n # Note: if you resampled the image you will not be able to overlay it on the original brain\n if debug:\n mask_path = os.path.join(project_wd, 'BayOptPy', 'tpot')\n print('Saving brain mask: %s' %mask_path)\n nib.save(MeanImgMask, os.path.join(mask_path, 'mask_%s.nii.gz' %dataset))\n print('Applied mask to the dataset')\n\n # Transform the imaging data into a np array (subjects x voxels)\n maskedData = np.array(maskedData)\n\n return demographics, imgs, maskedData\n\ndef get_mae_for_all_generations(dataset, random_seed, generations, config_dict,\n tpot_path):\n '''\n Get the MAE values for both the training and test dataset\n :return:\n '''\n # Load the scores for the best models\n saved_path = os.path.join(tpot_path, 'random_seed_%03d' %random_seed,\n 'tpot_%s_%s_%03dgen_pipelines.dump'\n %(dataset, config_dict, generations))\n # Note that if a value is not present for a generation, that means that the\n # score did not change from the previous generation\n # sort the array in ascending order\n logbook = joblib.load(saved_path)\n gen = list(logbook['log'].keys())\n\n print('There are %d optminal pipelines' %len(gen))\n print('These are the best pipelines')\n for generation in gen:\n print(logbook['log'][generation]['pipeline_name'])\n\n # Iterate over the the list of saved MAEs and repeat the values where one\n # generation is missed\n all_mae_test = []\n all_mae_train = []\n pipeline_complexity = []\n curr_gen_idx = 0\n # all generations\n for generation in range(generations):\n if generation == gen[curr_gen_idx]:\n all_mae_test.append(abs(logbook['log'][gen[curr_gen_idx]]['pipeline_test_mae']))\n all_mae_train.append(abs(logbook['log'][gen[curr_gen_idx]]['pipeline_score']))\n pipeline_complexity.append(len(logbook['log'][gen[curr_gen_idx]]['pipeline_sklearn_obj'].named_steps.keys()))\n if len(gen) > 1 and (len(gen) > curr_gen_idx + 1):\n curr_gen_idx += 1\n else:\n # repeat the same last value\n all_mae_test.append(all_mae_test[-1])\n all_mae_train.append(all_mae_train[-1])\n pipeline_complexity.append(pipeline_complexity[-1])\n\n # transform the pipeline_complexity into a numpy array, in order to perform\n # fancy indexing\n pipeline_complexity = np.array(pipeline_complexity)\n return all_mae_test, all_mae_train, pipeline_complexity\n\ndef set_publication_style():\n # Se font size to paper size\n plt.style.use(['seaborn-white', 'seaborn-talk'])\n matplotlib.rc(\"font\", family=\"Times New Roman\")\n # Remove the spines\n sns.set_style('white', {\"axes.spines.top\": False,\n \"axes.spines.right\": False,\n \"axes.labelsize\": 'large'})\n\ndef create_age_histogram(df, dataset):\n '''\n Get an age array and plot and save the age histogram for the analysed sample\n '''\n # Define plot styple\n set_publication_style()\n plt.figure()\n path_to_save = '/code/BayOptPy/tpot/age_histogram_%s.eps' %dataset\n min_age = df['age'].min()\n max_age = df['age'].max()\n plt.hist(df['age'], bins=65, range=(min_age,max_age))\n plt.xlabel('Age')\n plt.ylabel('# of Subjects')\n plt.legend()\n plt.savefig(path_to_save)\n plt.close()\n\n\n\ndef plot_confusion_matrix(y_true, y_pred, classes,\n normalize=False,\n title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if not title:\n if normalize:\n title = 'Normalized confusion matrix'\n else:\n title = 'Confusion matrix, without normalization'\n\n # Compute confusion matrix\n cm = confusion_matrix(y_true, y_pred)\n # Only use the labels that appear in the data\n labels = [int(x) for x in unique_labels(y_true, y_pred)]\n classes = classes[labels]\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n fig, ax = plt.subplots()\n im = ax.imshow(cm, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n # We want to show all ticks...\n ax.set(xticks=np.arange(cm.shape[1]),\n yticks=np.arange(cm.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=classes, yticklabels=classes,\n title=title,\n ylabel='True label',\n xlabel='Predicted label')\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i in range(cm.shape[0]):\n for j in range(cm.shape[1]):\n ax.text(j, i, format(cm[i, j], fmt),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n fig.tight_layout()\n return ax, cm\n\ndef plot_confusion_matrix_boosting(cm_mean, cm_std,\n classes,\n title=None,\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n\n fig, ax = plt.subplots()\n im = ax.imshow(cm_mean, interpolation='nearest', cmap=cmap)\n ax.figure.colorbar(im, ax=ax)\n # We want to show all ticks...\n ax.set(xticks=np.arange(cm_mean.shape[1]),\n yticks=np.arange(cm_mean.shape[0]),\n # ... and label them with the respective list entries\n xticklabels=classes, yticklabels=classes,\n title=title,\n ylabel='True label',\n xlabel='Predicted label')\n\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n\n # Loop over data dimensions and create text annotations.\n fmt = '{0:.2f} ± {1:.2f}'\n thresh = cm_mean.max() / 2.\n for i in range(cm_mean.shape[0]):\n for j in range(cm_mean.shape[1]):\n ax.text(j, i, fmt.format(cm_mean[i, j],cm_std[i, j]),\n ha=\"center\", va=\"center\",\n color=\"white\" if cm_mean[i, j] > thresh else \"black\")\n fig.tight_layout()\n return ax\n\ndef plot_predicted_vs_true(true_y, predicted_y, save_path, metric):\n fig = plt.figure()\n plt.scatter(true_y, predicted_y, alpha=.5)\n plt.ylabel('Predicted %s' %metric)\n plt.xlabel('True %s'%metric)\n plt.plot(np.arange(min(true_y),\n max(true_y)),\n np.arange(min(true_y),\n max(true_y)), alpha=.3, linestyle='--',\n color='b')\n if metric == 'Age':\n plt.xticks(np.arange(min(min(true_y), min(predicted_y)),\n max(max(true_y), max(predicted_y)), step=10))\n plt.yticks(np.arange(min(min(true_y), min(predicted_y)),\n max(max(true_y), max(predicted_y)), step=10))\n plt.savefig(save_path)\n plt.close()\n\ndef load_cognitive_data(project_data):\n cog_path = os.path.join(project_data, 'cog_ukbio')\n cog_df = pd.read_csv(os.path.join(cog_path, 'UKB_10k_cog_bmi.csv'))\n cog_df = cog_df.set_index('ID')\n return cog_df\n\ndef ttest_ind_corrected(performance_a, performance_b, k=10, r=10):\n \"\"\"Corrected repeated k-fold cv test.\n The test assumes that the classifiers were evaluated using cross validation.\n\n Ref:\n Bouckaert, Remco R., and Eibe Frank. \"Evaluating the replicability of significance tests for comparing learning\n algorithms.\" Pacific-Asia Conference on Knowledge Discovery and Data Mining. Springer, Berlin, Heidelberg, 2004\n\n Args:\n performance_a: performances from classifier A\n performance_b: performances from classifier B\n k: number of folds\n r: number of repetitions\n\n Returns:\n t: t-statistic of the corrected test.\n prob: p-value of the corrected test.\n \"\"\"\n df = k * r - 1\n\n x = performance_a - performance_b\n m = np.mean(x)\n\n sigma_2 = np.var(x, ddof=1)\n denom = np.sqrt((1 / k * r + 1 / (k - 1)) * sigma_2)\n\n with np.errstate(divide='ignore', invalid='ignore'):\n t = np.divide(m, denom)\n\n prob = stats.t.sf(np.abs(t), df) * 2\n\n return t, prob\n\n", "step-ids": [ 16, 17, 18, 21, 23 ] }
[ 16, 17, 18, 21, 23 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('api', '0001_initial')] operations = [migrations.RemoveField(model_name='replays', name='id'), migrations.AddField(model_name='replays', name='oponent', field= models.CharField(default='', max_length=200), preserve_default= False), migrations.AddField(model_name='replays', name='player', field=models.CharField(default='', max_length=200), preserve_default=False), migrations.AddField(model_name='replays', name='processed', field=models.BooleanField(default=False)), migrations.AlterField(model_name='replays', name='title', field= models.CharField(max_length=200, primary_key=True, serialize=False))] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('api', '0001_initial')] operations = [migrations.RemoveField(model_name='replays', name='id'), migrations.AddField(model_name='replays', name='oponent', field= models.CharField(default='', max_length=200), preserve_default= False), migrations.AddField(model_name='replays', name='player', field=models.CharField(default='', max_length=200), preserve_default=False), migrations.AddField(model_name='replays', name='processed', field=models.BooleanField(default=False)), migrations.AlterField(model_name='replays', name='title', field= models.CharField(max_length=200, primary_key=True, serialize=False))] <|reserved_special_token_1|> # Generated by Django 2.1 on 2018-12-09 21:53 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='replays', name='id', ), migrations.AddField( model_name='replays', name='oponent', field=models.CharField(default='', max_length=200), preserve_default=False, ), migrations.AddField( model_name='replays', name='player', field=models.CharField(default='', max_length=200), preserve_default=False, ), migrations.AddField( model_name='replays', name='processed', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='replays', name='title', field=models.CharField(max_length=200, primary_key=True, serialize=False), ), ]
flexible
{ "blob_id": "2c1ea45d3c7ee822ec58c2fadaf7fc182acc4422", "index": 9264, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('api', '0001_initial')]\n operations = [migrations.RemoveField(model_name='replays', name='id'),\n migrations.AddField(model_name='replays', name='oponent', field=\n models.CharField(default='', max_length=200), preserve_default=\n False), migrations.AddField(model_name='replays', name='player',\n field=models.CharField(default='', max_length=200),\n preserve_default=False), migrations.AddField(model_name='replays',\n name='processed', field=models.BooleanField(default=False)),\n migrations.AlterField(model_name='replays', name='title', field=\n models.CharField(max_length=200, primary_key=True, serialize=False))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('api', '0001_initial')]\n operations = [migrations.RemoveField(model_name='replays', name='id'),\n migrations.AddField(model_name='replays', name='oponent', field=\n models.CharField(default='', max_length=200), preserve_default=\n False), migrations.AddField(model_name='replays', name='player',\n field=models.CharField(default='', max_length=200),\n preserve_default=False), migrations.AddField(model_name='replays',\n name='processed', field=models.BooleanField(default=False)),\n migrations.AlterField(model_name='replays', name='title', field=\n models.CharField(max_length=200, primary_key=True, serialize=False))]\n", "step-5": "# Generated by Django 2.1 on 2018-12-09 21:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('api', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='replays',\n name='id',\n ),\n migrations.AddField(\n model_name='replays',\n name='oponent',\n field=models.CharField(default='', max_length=200),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='replays',\n name='player',\n field=models.CharField(default='', max_length=200),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='replays',\n name='processed',\n field=models.BooleanField(default=False),\n ),\n migrations.AlterField(\n model_name='replays',\n name='title',\n field=models.CharField(max_length=200, primary_key=True, serialize=False),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> ROUTE_LIST = [webapp2.Route('/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryApi, name='historyApi'), webapp2.Route( '/api<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.PageApi, name= 'pageApi'), webapp2.Route('/signup', handler=handlers.SignupPage, name= 'signup'), webapp2.Route('/login', handler=handlers.LoginPage, name= 'login'), webapp2.Route('/logout', handler=handlers.LogoutPage, name= 'logout'), webapp2.Route('/search', handler=handlers.SearchPage, name= 'search'), webapp2.Route('/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler =handlers.EditPage, name='edit'), webapp2.Route( '/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryPage, name='history'), webapp2.Route('<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler =handlers.WikiPage, name='wiki')] <|reserved_special_token_1|> import webapp2 import handlers ROUTE_LIST = [webapp2.Route('/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryApi, name='historyApi'), webapp2.Route( '/api<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.PageApi, name= 'pageApi'), webapp2.Route('/signup', handler=handlers.SignupPage, name= 'signup'), webapp2.Route('/login', handler=handlers.LoginPage, name= 'login'), webapp2.Route('/logout', handler=handlers.LogoutPage, name= 'logout'), webapp2.Route('/search', handler=handlers.SearchPage, name= 'search'), webapp2.Route('/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler =handlers.EditPage, name='edit'), webapp2.Route( '/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryPage, name='history'), webapp2.Route('<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler =handlers.WikiPage, name='wiki')] <|reserved_special_token_1|> #!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014 Vincent Celis # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import webapp2 import handlers # A list containing webapp2.Route instances to define the routing tables ROUTE_LIST = [ webapp2.Route(r'/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryApi, name='historyApi'), webapp2.Route(r'/api<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.PageApi, name='pageApi'), webapp2.Route(r'/signup', handler=handlers.SignupPage, name='signup'), webapp2.Route(r'/login', handler=handlers.LoginPage, name='login'), webapp2.Route(r'/logout', handler=handlers.LogoutPage, name='logout'), webapp2.Route(r'/search', handler=handlers.SearchPage, name='search'), webapp2.Route(r'/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.EditPage, name='edit'), webapp2.Route(r'/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryPage, name='history'), webapp2.Route(r'<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.WikiPage, name='wiki') ]
flexible
{ "blob_id": "a61bc654eecb4e44dce3e62df752f80559a2d055", "index": 9184, "step-1": "<mask token>\n", "step-2": "<mask token>\nROUTE_LIST = [webapp2.Route('/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryApi, name='historyApi'), webapp2.Route(\n '/api<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.PageApi, name=\n 'pageApi'), webapp2.Route('/signup', handler=handlers.SignupPage, name=\n 'signup'), webapp2.Route('/login', handler=handlers.LoginPage, name=\n 'login'), webapp2.Route('/logout', handler=handlers.LogoutPage, name=\n 'logout'), webapp2.Route('/search', handler=handlers.SearchPage, name=\n 'search'), webapp2.Route('/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.EditPage, name='edit'), webapp2.Route(\n '/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryPage,\n name='history'), webapp2.Route('<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.WikiPage, name='wiki')]\n", "step-3": "import webapp2\nimport handlers\nROUTE_LIST = [webapp2.Route('/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryApi, name='historyApi'), webapp2.Route(\n '/api<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.PageApi, name=\n 'pageApi'), webapp2.Route('/signup', handler=handlers.SignupPage, name=\n 'signup'), webapp2.Route('/login', handler=handlers.LoginPage, name=\n 'login'), webapp2.Route('/logout', handler=handlers.LogoutPage, name=\n 'logout'), webapp2.Route('/search', handler=handlers.SearchPage, name=\n 'search'), webapp2.Route('/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.EditPage, name='edit'), webapp2.Route(\n '/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryPage,\n name='history'), webapp2.Route('<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.WikiPage, name='wiki')]\n", "step-4": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2014 Vincent Celis\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport webapp2\nimport handlers\n\n# A list containing webapp2.Route instances to define the routing tables\nROUTE_LIST = [\n webapp2.Route(r'/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryApi, name='historyApi'),\n webapp2.Route(r'/api<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.PageApi, name='pageApi'),\n webapp2.Route(r'/signup', handler=handlers.SignupPage, name='signup'),\n webapp2.Route(r'/login', handler=handlers.LoginPage, name='login'),\n webapp2.Route(r'/logout', handler=handlers.LogoutPage, name='logout'),\n webapp2.Route(r'/search', handler=handlers.SearchPage, name='search'),\n webapp2.Route(r'/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.EditPage, name='edit'),\n webapp2.Route(r'/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryPage, name='history'),\n webapp2.Route(r'<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.WikiPage, name='wiki')\n ]", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def cameras_get_info(): """ cameras_get_info - reads the camera info from the XML file and puts it into a python data structure and returns it. """ status = 0 xmldoc = minidom.parse(CAMERA_XML_FILE) itemlist = xmldoc.getElementsByTagName('camera') cameras_info = [] for i in xrange(len(itemlist)): cameras_info.append({'id': itemlist[i].attributes['id'].value}) a = itemlist[i].getElementsByTagName('user') cameras_info[i].update({'user': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('model') cameras_info[i].update({'model': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('passwd') cameras_info[i].update({'passwd': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('port') cameras_info[i].update({'port': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('ip_address') cameras_info[i].update({'ip_address': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('disk_location') cameras_info[i].update({'disk_location': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('mfgr') cameras_info[i].update({'mfgr': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('ftp_loc') cameras_info[i].update({'ftp_loc': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('status') cameras_info[i].update({'status': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('location') cameras_info[i].update({'location': a[0].firstChild.data}) return status, cameras_info <|reserved_special_token_1|> <|reserved_special_token_0|> CAMERA_XML_FILE = '/tmp/cameras.xml' def cameras_get_info(): """ cameras_get_info - reads the camera info from the XML file and puts it into a python data structure and returns it. """ status = 0 xmldoc = minidom.parse(CAMERA_XML_FILE) itemlist = xmldoc.getElementsByTagName('camera') cameras_info = [] for i in xrange(len(itemlist)): cameras_info.append({'id': itemlist[i].attributes['id'].value}) a = itemlist[i].getElementsByTagName('user') cameras_info[i].update({'user': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('model') cameras_info[i].update({'model': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('passwd') cameras_info[i].update({'passwd': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('port') cameras_info[i].update({'port': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('ip_address') cameras_info[i].update({'ip_address': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('disk_location') cameras_info[i].update({'disk_location': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('mfgr') cameras_info[i].update({'mfgr': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('ftp_loc') cameras_info[i].update({'ftp_loc': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('status') cameras_info[i].update({'status': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('location') cameras_info[i].update({'location': a[0].firstChild.data}) return status, cameras_info <|reserved_special_token_1|> <|reserved_special_token_0|> from xml.dom import minidom, Node CAMERA_XML_FILE = '/tmp/cameras.xml' def cameras_get_info(): """ cameras_get_info - reads the camera info from the XML file and puts it into a python data structure and returns it. """ status = 0 xmldoc = minidom.parse(CAMERA_XML_FILE) itemlist = xmldoc.getElementsByTagName('camera') cameras_info = [] for i in xrange(len(itemlist)): cameras_info.append({'id': itemlist[i].attributes['id'].value}) a = itemlist[i].getElementsByTagName('user') cameras_info[i].update({'user': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('model') cameras_info[i].update({'model': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('passwd') cameras_info[i].update({'passwd': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('port') cameras_info[i].update({'port': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('ip_address') cameras_info[i].update({'ip_address': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('disk_location') cameras_info[i].update({'disk_location': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('mfgr') cameras_info[i].update({'mfgr': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('ftp_loc') cameras_info[i].update({'ftp_loc': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('status') cameras_info[i].update({'status': a[0].firstChild.data}) a = itemlist[i].getElementsByTagName('location') cameras_info[i].update({'location': a[0].firstChild.data}) return status, cameras_info <|reserved_special_token_1|> #!/usr/bin/env python2.7 ''' lib script to encapsulate the camera info ''' from xml.dom import minidom, Node # what % of the file system remains before deleting files # amount that we will cleanup relative to the filesystem total CAMERA_XML_FILE = "/tmp/cameras.xml" def cameras_get_info(): ''' cameras_get_info - reads the camera info from the XML file and puts it into a python data structure and returns it. ''' status = 0 xmldoc = minidom.parse(CAMERA_XML_FILE) itemlist = xmldoc.getElementsByTagName('camera') # camera info to return cameras_info = [] for i in xrange(len(itemlist)): cameras_info.append({'id':itemlist[i].attributes['id'].value}) a=itemlist[i].getElementsByTagName('user') cameras_info[i].update({'user':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('model') cameras_info[i].update({'model':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('passwd') cameras_info[i].update({'passwd':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('port') cameras_info[i].update({'port':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('ip_address') cameras_info[i].update({'ip_address':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('disk_location') cameras_info[i].update({'disk_location':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('mfgr') cameras_info[i].update({'mfgr':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('ftp_loc') cameras_info[i].update({'ftp_loc':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('status') cameras_info[i].update({'status':a[0].firstChild.data}) a=itemlist[i].getElementsByTagName('location') cameras_info[i].update({'location':a[0].firstChild.data}) return status, cameras_info
flexible
{ "blob_id": "510d411d79d5df8658703241f161b3e2a9ec5932", "index": 4110, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef cameras_get_info():\n \"\"\"\n cameras_get_info - reads the camera info from the XML file and\n puts it into a python data structure and returns it.\n \"\"\"\n status = 0\n xmldoc = minidom.parse(CAMERA_XML_FILE)\n itemlist = xmldoc.getElementsByTagName('camera')\n cameras_info = []\n for i in xrange(len(itemlist)):\n cameras_info.append({'id': itemlist[i].attributes['id'].value})\n a = itemlist[i].getElementsByTagName('user')\n cameras_info[i].update({'user': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('model')\n cameras_info[i].update({'model': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('passwd')\n cameras_info[i].update({'passwd': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('port')\n cameras_info[i].update({'port': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('ip_address')\n cameras_info[i].update({'ip_address': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('disk_location')\n cameras_info[i].update({'disk_location': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('mfgr')\n cameras_info[i].update({'mfgr': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('ftp_loc')\n cameras_info[i].update({'ftp_loc': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('status')\n cameras_info[i].update({'status': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('location')\n cameras_info[i].update({'location': a[0].firstChild.data})\n return status, cameras_info\n", "step-3": "<mask token>\nCAMERA_XML_FILE = '/tmp/cameras.xml'\n\n\ndef cameras_get_info():\n \"\"\"\n cameras_get_info - reads the camera info from the XML file and\n puts it into a python data structure and returns it.\n \"\"\"\n status = 0\n xmldoc = minidom.parse(CAMERA_XML_FILE)\n itemlist = xmldoc.getElementsByTagName('camera')\n cameras_info = []\n for i in xrange(len(itemlist)):\n cameras_info.append({'id': itemlist[i].attributes['id'].value})\n a = itemlist[i].getElementsByTagName('user')\n cameras_info[i].update({'user': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('model')\n cameras_info[i].update({'model': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('passwd')\n cameras_info[i].update({'passwd': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('port')\n cameras_info[i].update({'port': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('ip_address')\n cameras_info[i].update({'ip_address': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('disk_location')\n cameras_info[i].update({'disk_location': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('mfgr')\n cameras_info[i].update({'mfgr': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('ftp_loc')\n cameras_info[i].update({'ftp_loc': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('status')\n cameras_info[i].update({'status': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('location')\n cameras_info[i].update({'location': a[0].firstChild.data})\n return status, cameras_info\n", "step-4": "<mask token>\nfrom xml.dom import minidom, Node\nCAMERA_XML_FILE = '/tmp/cameras.xml'\n\n\ndef cameras_get_info():\n \"\"\"\n cameras_get_info - reads the camera info from the XML file and\n puts it into a python data structure and returns it.\n \"\"\"\n status = 0\n xmldoc = minidom.parse(CAMERA_XML_FILE)\n itemlist = xmldoc.getElementsByTagName('camera')\n cameras_info = []\n for i in xrange(len(itemlist)):\n cameras_info.append({'id': itemlist[i].attributes['id'].value})\n a = itemlist[i].getElementsByTagName('user')\n cameras_info[i].update({'user': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('model')\n cameras_info[i].update({'model': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('passwd')\n cameras_info[i].update({'passwd': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('port')\n cameras_info[i].update({'port': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('ip_address')\n cameras_info[i].update({'ip_address': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('disk_location')\n cameras_info[i].update({'disk_location': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('mfgr')\n cameras_info[i].update({'mfgr': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('ftp_loc')\n cameras_info[i].update({'ftp_loc': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('status')\n cameras_info[i].update({'status': a[0].firstChild.data})\n a = itemlist[i].getElementsByTagName('location')\n cameras_info[i].update({'location': a[0].firstChild.data})\n return status, cameras_info\n", "step-5": "#!/usr/bin/env python2.7\n'''\n lib script to encapsulate the camera info\n'''\nfrom xml.dom import minidom, Node\n\n# what % of the file system remains before deleting files\n# amount that we will cleanup relative to the filesystem total\nCAMERA_XML_FILE = \"/tmp/cameras.xml\"\n\n\ndef cameras_get_info():\n '''\n cameras_get_info - reads the camera info from the XML file and\n puts it into a python data structure and returns it.\n '''\n status = 0\n xmldoc = minidom.parse(CAMERA_XML_FILE)\n itemlist = xmldoc.getElementsByTagName('camera')\n # camera info to return\n cameras_info = []\n for i in xrange(len(itemlist)):\n cameras_info.append({'id':itemlist[i].attributes['id'].value})\n a=itemlist[i].getElementsByTagName('user')\n cameras_info[i].update({'user':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('model')\n cameras_info[i].update({'model':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('passwd')\n cameras_info[i].update({'passwd':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('port')\n cameras_info[i].update({'port':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('ip_address')\n cameras_info[i].update({'ip_address':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('disk_location')\n cameras_info[i].update({'disk_location':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('mfgr')\n cameras_info[i].update({'mfgr':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('ftp_loc')\n cameras_info[i].update({'ftp_loc':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('status')\n cameras_info[i].update({'status':a[0].firstChild.data})\n a=itemlist[i].getElementsByTagName('location')\n cameras_info[i].update({'location':a[0].firstChild.data})\n return status, cameras_info\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring. class Solution(object): def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s) == 0: return "" if len(s) == 1: return s start = -1 end = -2 for i in range(len(s)): side = 1 while i - side >= 0 and i + side < len(s) and s[i - side] == s[i + side]: side += 1 if (side - 1) * 2 + 1 > end - start + 1: start = i - (side - 1) end = i + side out_string = s[start:end] start = -1 end = -2 for i in range(len(s) - 1): side = 0 while i - side >= 0 and i + 1 + side < len(s) and s[i - side] == s[i + 1 + side]: side += 1 if side * 2 > end - start + 1: start = i - side + 1 end = i + 1 + side return out_string if len(out_string) > end - start else s[start:end]
normal
{ "blob_id": "7c39b3927bc0702818c54875785b4657c20c441e", "index": 2272, "step-1": "<mask token>\n", "step-2": "class Solution(object):\n <mask token>\n", "step-3": "class Solution(object):\n\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if len(s) == 0:\n return ''\n if len(s) == 1:\n return s\n start = -1\n end = -2\n for i in range(len(s)):\n side = 1\n while i - side >= 0 and i + side < len(s) and s[i - side] == s[\n i + side]:\n side += 1\n if (side - 1) * 2 + 1 > end - start + 1:\n start = i - (side - 1)\n end = i + side\n out_string = s[start:end]\n start = -1\n end = -2\n for i in range(len(s) - 1):\n side = 0\n while i - side >= 0 and i + 1 + side < len(s) and s[i - side] == s[\n i + 1 + side]:\n side += 1\n if side * 2 > end - start + 1:\n start = i - side + 1\n end = i + 1 + side\n return out_string if len(out_string) > end - start else s[start:end]\n", "step-4": "# Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.\n\nclass Solution(object):\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if len(s) == 0:\n return \"\"\n if len(s) == 1:\n return s\n \n start = -1\n end = -2\n for i in range(len(s)):\n side = 1\n while i - side >= 0 and i + side < len(s) and s[i - side] == s[i + side]:\n side += 1\n if (side - 1) * 2 + 1 > end - start + 1:\n start = i - (side - 1)\n end = i + side\n out_string = s[start:end]\n start = -1\n end = -2\n for i in range(len(s) - 1):\n side = 0\n while i - side >= 0 and i + 1 + side < len(s) and s[i - side] == s[i + 1 + side]:\n side += 1\n if side * 2 > end - start + 1:\n start = i - side + 1\n end = i + 1 + side\n return out_string if len(out_string) > end - start else s[start:end]\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def ConfigObject(config_path): """read a configuration file to retrieve access token""" configDict = {} with open(config_path, 'r') as config: for line in config.readlines(): try: configDict[line.split('=')[0]] = line.split('=')[1].rstrip() except: pass return configDict def uploadZippedToBox(zippedFolder, boxfolder=None): if boxfolder is None: boxfolder = accessUploadFolder() try: items = boxfolder.get_items() for item in items: if item.name == os.path.basename(zippedFolder): try: item.delete() except Exception as e: print(e) return False boxfolder.upload(zippedFolder) uploaded = True except Exception as e: print(e) uploaded = False pass finally: return uploaded <|reserved_special_token_0|> def uploadAllZippedToBox(zipFolder): """uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed""" zipFiles = listZipFiles(zipFolder) tfolder = accessUploadFolder() items = tfolder.get_items() for item in items: if item.name in zipFiles: try: item.delete() except Exception as e: print(e) zipFiles.remove(item.name) uploadedFiles = [] badUploads = [] for zipped in zipFiles: try: uploadZippedToBox(zipped, tfolder) uploadedFiles.append((zipped, True)) except Exception as e: print(e) badUploads.append((zipped, False)) pass return uploadedFiles, badUploads <|reserved_special_token_1|> <|reserved_special_token_0|> def ConfigObject(config_path): """read a configuration file to retrieve access token""" configDict = {} with open(config_path, 'r') as config: for line in config.readlines(): try: configDict[line.split('=')[0]] = line.split('=')[1].rstrip() except: pass return configDict def uploadZippedToBox(zippedFolder, boxfolder=None): if boxfolder is None: boxfolder = accessUploadFolder() try: items = boxfolder.get_items() for item in items: if item.name == os.path.basename(zippedFolder): try: item.delete() except Exception as e: print(e) return False boxfolder.upload(zippedFolder) uploaded = True except Exception as e: print(e) uploaded = False pass finally: return uploaded def accessUploadFolder(year=2020): config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath( __file__)), 'instance', 'Boxapp.cfg'])) CLIENT_ID = config['client_id'] CLIENT_FOLDER = config['client_folder' + str(year)] ACCESS_TOKEN = config['access_token'] auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token= ACCESS_TOKEN) client = Client(auth) try: my = client.user(user_id='me').get() print(my.name) except: sys.exit( 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.' ) tfolder = client.folder(CLIENT_FOLDER) return tfolder <|reserved_special_token_0|> def uploadAllZippedToBox(zipFolder): """uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed""" zipFiles = listZipFiles(zipFolder) tfolder = accessUploadFolder() items = tfolder.get_items() for item in items: if item.name in zipFiles: try: item.delete() except Exception as e: print(e) zipFiles.remove(item.name) uploadedFiles = [] badUploads = [] for zipped in zipFiles: try: uploadZippedToBox(zipped, tfolder) uploadedFiles.append((zipped, True)) except Exception as e: print(e) badUploads.append((zipped, False)) pass return uploadedFiles, badUploads <|reserved_special_token_1|> <|reserved_special_token_0|> def ConfigObject(config_path): """read a configuration file to retrieve access token""" configDict = {} with open(config_path, 'r') as config: for line in config.readlines(): try: configDict[line.split('=')[0]] = line.split('=')[1].rstrip() except: pass return configDict def uploadZippedToBox(zippedFolder, boxfolder=None): if boxfolder is None: boxfolder = accessUploadFolder() try: items = boxfolder.get_items() for item in items: if item.name == os.path.basename(zippedFolder): try: item.delete() except Exception as e: print(e) return False boxfolder.upload(zippedFolder) uploaded = True except Exception as e: print(e) uploaded = False pass finally: return uploaded def accessUploadFolder(year=2020): config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath( __file__)), 'instance', 'Boxapp.cfg'])) CLIENT_ID = config['client_id'] CLIENT_FOLDER = config['client_folder' + str(year)] ACCESS_TOKEN = config['access_token'] auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token= ACCESS_TOKEN) client = Client(auth) try: my = client.user(user_id='me').get() print(my.name) except: sys.exit( 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.' ) tfolder = client.folder(CLIENT_FOLDER) return tfolder def listZipFiles(directory_folder): """ Lists teh zip folders in teh directory folder, including subdirectortories """ zipFiles = [] for root, dirs, files in os.walk(directory_folder): for name in files: if name[-3:] == 'zip': zipFiles.append(os.path.join(root, name)) return zipFiles def uploadAllZippedToBox(zipFolder): """uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed""" zipFiles = listZipFiles(zipFolder) tfolder = accessUploadFolder() items = tfolder.get_items() for item in items: if item.name in zipFiles: try: item.delete() except Exception as e: print(e) zipFiles.remove(item.name) uploadedFiles = [] badUploads = [] for zipped in zipFiles: try: uploadZippedToBox(zipped, tfolder) uploadedFiles.append((zipped, True)) except Exception as e: print(e) badUploads.append((zipped, False)) pass return uploadedFiles, badUploads <|reserved_special_token_1|> from boxsdk import Client, OAuth2 import os import sys def ConfigObject(config_path): """read a configuration file to retrieve access token""" configDict = {} with open(config_path, 'r') as config: for line in config.readlines(): try: configDict[line.split('=')[0]] = line.split('=')[1].rstrip() except: pass return configDict def uploadZippedToBox(zippedFolder, boxfolder=None): if boxfolder is None: boxfolder = accessUploadFolder() try: items = boxfolder.get_items() for item in items: if item.name == os.path.basename(zippedFolder): try: item.delete() except Exception as e: print(e) return False boxfolder.upload(zippedFolder) uploaded = True except Exception as e: print(e) uploaded = False pass finally: return uploaded def accessUploadFolder(year=2020): config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath( __file__)), 'instance', 'Boxapp.cfg'])) CLIENT_ID = config['client_id'] CLIENT_FOLDER = config['client_folder' + str(year)] ACCESS_TOKEN = config['access_token'] auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token= ACCESS_TOKEN) client = Client(auth) try: my = client.user(user_id='me').get() print(my.name) except: sys.exit( 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.' ) tfolder = client.folder(CLIENT_FOLDER) return tfolder def listZipFiles(directory_folder): """ Lists teh zip folders in teh directory folder, including subdirectortories """ zipFiles = [] for root, dirs, files in os.walk(directory_folder): for name in files: if name[-3:] == 'zip': zipFiles.append(os.path.join(root, name)) return zipFiles def uploadAllZippedToBox(zipFolder): """uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed""" zipFiles = listZipFiles(zipFolder) tfolder = accessUploadFolder() items = tfolder.get_items() for item in items: if item.name in zipFiles: try: item.delete() except Exception as e: print(e) zipFiles.remove(item.name) uploadedFiles = [] badUploads = [] for zipped in zipFiles: try: uploadZippedToBox(zipped, tfolder) uploadedFiles.append((zipped, True)) except Exception as e: print(e) badUploads.append((zipped, False)) pass return uploadedFiles, badUploads <|reserved_special_token_1|> from boxsdk import Client, OAuth2 import os import sys def ConfigObject(config_path): "read a configuration file to retrieve access token" configDict = {} with open(config_path,'r') as config: for line in config.readlines(): try: configDict[line.split("=")[0]] = line.split("=")[1].rstrip() except: pass return configDict def uploadZippedToBox(zippedFolder, boxfolder = None): if boxfolder is None: boxfolder = accessUploadFolder() try: items = boxfolder.get_items() for item in items: if item.name == os.path.basename(zippedFolder): try: item.delete() except Exception as e: print(e) return False boxfolder.upload(zippedFolder) uploaded = True except Exception as e: print(e) uploaded = False pass finally: return uploaded def accessUploadFolder(year=2020): # Define client ID, client secret, and developer token.path = os.path.join(*[os.path.dirname(os.path.abspath(__file__)),"instance"]) # Read app info from text file config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(__file__)),"instance", 'Boxapp.cfg'])) CLIENT_ID = config['client_id'] CLIENT_FOLDER = config['client_folder' + str(year)] ACCESS_TOKEN = config['access_token'] # Create OAuth2 object. auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=ACCESS_TOKEN) # Create the authenticated client client = Client(auth) # make sure we connected try: my = client.user(user_id='me').get() print(my.name) # developer name tied to the token except: sys.exit("ERROR: Invalid access token; try re-generating an " "access token from the app console on the web.") tfolder = client.folder(CLIENT_FOLDER) # 2020 scada data folder return tfolder def listZipFiles(directory_folder): ''' Lists teh zip folders in teh directory folder, including subdirectortories ''' zipFiles = [] for root, dirs, files in os.walk(directory_folder): for name in files: if name[-3:] == 'zip': zipFiles.append(os.path.join(root, name)) return zipFiles def uploadAllZippedToBox(zipFolder): '''uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed''' #files to upload zipFiles = listZipFiles(zipFolder) tfolder = accessUploadFolder() items = tfolder.get_items() for item in items: if item.name in zipFiles: try: item.delete() #tfolder.file(file_id=item.id).delete() except Exception as e: print(e) #If we coudn't delete the existing zip file don't try to upload a new one. zipFiles.remove(item.name) uploadedFiles = [] badUploads = [] for zipped in zipFiles: try: uploadZippedToBox(zipped, tfolder) uploadedFiles.append((zipped,True)) except Exception as e: print(e) badUploads.append((zipped,False)) pass return uploadedFiles, badUploads
flexible
{ "blob_id": "e76ebbe8dab2e5169ef40b559f783c49ba4de825", "index": 1750, "step-1": "<mask token>\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\n<mask token>\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-2": "<mask token>\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\ndef accessUploadFolder(year=2020):\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(\n __file__)), 'instance', 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=\n ACCESS_TOKEN)\n client = Client(auth)\n try:\n my = client.user(user_id='me').get()\n print(my.name)\n except:\n sys.exit(\n 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.'\n )\n tfolder = client.folder(CLIENT_FOLDER)\n return tfolder\n\n\n<mask token>\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-3": "<mask token>\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\ndef accessUploadFolder(year=2020):\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(\n __file__)), 'instance', 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=\n ACCESS_TOKEN)\n client = Client(auth)\n try:\n my = client.user(user_id='me').get()\n print(my.name)\n except:\n sys.exit(\n 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.'\n )\n tfolder = client.folder(CLIENT_FOLDER)\n return tfolder\n\n\ndef listZipFiles(directory_folder):\n \"\"\"\n Lists teh zip folders in teh directory folder, including subdirectortories\n \"\"\"\n zipFiles = []\n for root, dirs, files in os.walk(directory_folder):\n for name in files:\n if name[-3:] == 'zip':\n zipFiles.append(os.path.join(root, name))\n return zipFiles\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-4": "from boxsdk import Client, OAuth2\nimport os\nimport sys\n\n\ndef ConfigObject(config_path):\n \"\"\"read a configuration file to retrieve access token\"\"\"\n configDict = {}\n with open(config_path, 'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split('=')[0]] = line.split('=')[1].rstrip()\n except:\n pass\n return configDict\n\n\ndef uploadZippedToBox(zippedFolder, boxfolder=None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\n\ndef accessUploadFolder(year=2020):\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(\n __file__)), 'instance', 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=\n ACCESS_TOKEN)\n client = Client(auth)\n try:\n my = client.user(user_id='me').get()\n print(my.name)\n except:\n sys.exit(\n 'ERROR: Invalid access token; try re-generating an access token from the app console on the web.'\n )\n tfolder = client.folder(CLIENT_FOLDER)\n return tfolder\n\n\ndef listZipFiles(directory_folder):\n \"\"\"\n Lists teh zip folders in teh directory folder, including subdirectortories\n \"\"\"\n zipFiles = []\n for root, dirs, files in os.walk(directory_folder):\n for name in files:\n if name[-3:] == 'zip':\n zipFiles.append(os.path.join(root, name))\n return zipFiles\n\n\ndef uploadAllZippedToBox(zipFolder):\n \"\"\"uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed\"\"\"\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n except Exception as e:\n print(e)\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped, True))\n except Exception as e:\n print(e)\n badUploads.append((zipped, False))\n pass\n return uploadedFiles, badUploads\n", "step-5": "from boxsdk import Client, OAuth2\n\nimport os\nimport sys\n\ndef ConfigObject(config_path):\n \"read a configuration file to retrieve access token\"\n configDict = {}\n with open(config_path,'r') as config:\n for line in config.readlines():\n try:\n configDict[line.split(\"=\")[0]] = line.split(\"=\")[1].rstrip()\n except:\n pass\n return configDict\ndef uploadZippedToBox(zippedFolder, boxfolder = None):\n if boxfolder is None:\n boxfolder = accessUploadFolder()\n try:\n items = boxfolder.get_items()\n for item in items:\n if item.name == os.path.basename(zippedFolder):\n try:\n item.delete()\n except Exception as e:\n print(e)\n return False\n boxfolder.upload(zippedFolder)\n uploaded = True\n except Exception as e:\n print(e)\n uploaded = False\n pass\n finally:\n return uploaded\n\ndef accessUploadFolder(year=2020):\n # Define client ID, client secret, and developer token.path = os.path.join(*[os.path.dirname(os.path.abspath(__file__)),\"instance\"])\n\n # Read app info from text file\n config = ConfigObject(os.path.join(*[os.path.dirname(os.path.abspath(__file__)),\"instance\", 'Boxapp.cfg']))\n CLIENT_ID = config['client_id']\n CLIENT_FOLDER = config['client_folder' + str(year)]\n ACCESS_TOKEN = config['access_token']\n\n # Create OAuth2 object.\n auth = OAuth2(client_id=CLIENT_ID, client_secret='', access_token=ACCESS_TOKEN)\n # Create the authenticated client\n client = Client(auth)\n\n # make sure we connected\n try:\n my = client.user(user_id='me').get()\n print(my.name) # developer name tied to the token\n except:\n sys.exit(\"ERROR: Invalid access token; try re-generating an \"\n \"access token from the app console on the web.\")\n\n tfolder = client.folder(CLIENT_FOLDER) # 2020 scada data folder\n return tfolder\ndef listZipFiles(directory_folder):\n '''\n Lists teh zip folders in teh directory folder, including subdirectortories\n '''\n zipFiles = []\n for root, dirs, files in os.walk(directory_folder):\n for name in files:\n if name[-3:] == 'zip':\n zipFiles.append(os.path.join(root, name))\n return zipFiles\ndef uploadAllZippedToBox(zipFolder):\n '''uploads new zip folders to box. Will not upload a zip folder if it already exists on Box even if the contents have changed'''\n #files to upload\n zipFiles = listZipFiles(zipFolder)\n tfolder = accessUploadFolder()\n items = tfolder.get_items()\n for item in items:\n if item.name in zipFiles:\n try:\n item.delete()\n #tfolder.file(file_id=item.id).delete()\n except Exception as e:\n print(e)\n #If we coudn't delete the existing zip file don't try to upload a new one.\n zipFiles.remove(item.name)\n uploadedFiles = []\n badUploads = []\n\n for zipped in zipFiles:\n try:\n uploadZippedToBox(zipped, tfolder)\n uploadedFiles.append((zipped,True))\n except Exception as e:\n print(e)\n badUploads.append((zipped,False))\n pass\n\n return uploadedFiles, badUploads\n\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
from django import template from ..models import Article # 得到django 负责管理标签和过滤器的类 register = template.Library() @register.simple_tag def getlatestarticle(): latearticle = Article.objects.all().order_by("-atime") return latearticle
normal
{ "blob_id": "804c75b3ab0b115e5187d44e4d139cfb553269a9", "index": 6791, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@register.simple_tag\ndef getlatestarticle():\n latearticle = Article.objects.all().order_by('-atime')\n return latearticle\n", "step-3": "<mask token>\nregister = template.Library()\n\n\n@register.simple_tag\ndef getlatestarticle():\n latearticle = Article.objects.all().order_by('-atime')\n return latearticle\n", "step-4": "from django import template\nfrom ..models import Article\nregister = template.Library()\n\n\n@register.simple_tag\ndef getlatestarticle():\n latearticle = Article.objects.all().order_by('-atime')\n return latearticle\n", "step-5": "from django import template\nfrom ..models import Article\n# 得到django 负责管理标签和过滤器的类\nregister = template.Library()\n\n@register.simple_tag\ndef getlatestarticle():\n latearticle = Article.objects.all().order_by(\"-atime\")\n return latearticle", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def prep_folder(args): """ Append to slash to filepath if needed, and generate folder if it doesn't exist""" if args.save_folder[-1] != '/': args.save_folder += '/' if not os.path.isdir(args.save_folder): os.mkdir(args.save_folder) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def prep_folder(args): """ Append to slash to filepath if needed, and generate folder if it doesn't exist""" if args.save_folder[-1] != '/': args.save_folder += '/' if not os.path.isdir(args.save_folder): os.mkdir(args.save_folder) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=3, dest='epochs', help='Number of epochs to run') parser.add_argument('--batch-size', type=int, default=50, dest= 'batch_size', help='Batch size') parser.add_argument('--max-out-length', type=int, default=128, dest= 'max_out_length', help= 'Maximum output length (outputs truncated if longer)') parser.add_argument('--adversarial-model', type=str, default=None, dest ='adv_model', help= 'Type of adversarial model to use. Will use traditional teacher forcing if None.' ) parser.add_argument('--train-disc-only-steps', type=int, default=0, dest='train_disc_only_steps', help= 'Number of steps for which to train discriminator only (without updating generator)' ) parser.add_argument('--gen_weight_decay', type=float, default=0, dest= 'gen_weight_decay', help= "Weight decay for the generator's training scheduler") parser.add_argument('--gen_lr', type=float, default=2e-05, dest= 'gen_lr', help='Learning rate for generator') parser.add_argument('--gen_epsilon', type=float, default=1e-08, dest= 'gen_epsilon', help='Epsilon parameter for generator optimizer') parser.add_argument('--gen_warmup_steps', type=int, default=0, dest= 'gen_warmup_steps', help= 'Number of warmup steps for training generator') parser.add_argument('--disc_weight_decay', type=float, default=0, dest= 'disc_weight_decay', help= "Weight decay for the discriminator's training scheduler") parser.add_argument('--disc_lr', type=float, default=2e-05, dest= 'disc_lr', help='Learning rate for discriminator') parser.add_argument('--disc_epsilon', type=float, default=1e-08, dest= 'disc_epsilon', help='Epsilon parameter for discriminator optimizer') parser.add_argument('--disc_warmup_steps', type=int, default=0, dest= 'disc_warmup_steps', help= 'Number of warmup steps for training discriminator') parser.add_argument('--train-data-path', type=str, dest= 'train_data_path', help='Filepath to preprocessed data') parser.add_argument('--save-folder', type=str, dest='save_folder', help ='Filepath to folder where checkpoints should be saved') parser.add_argument('--pretrained-gen', type=str, default=None, dest= 'pretrained_gen', help= 'Filepath to trained generator. If None, will instantiate a default pretrained generator.' ) parser.add_argument('--pretrained-disc', type=str, default=None, dest= 'pretrained_disc', help= 'Filepath to trained discriminator. If None, will instantiate a default pretrained discriminator of type specified by --adversarial-model option.' ) args = parser.parse_args() assert args.train_data_path is not None assert args.save_folder is not None prep_folder(args) eos_token_id = GPT2Tokenizer.from_pretrained('gpt2').eos_token_id train_dataset = DialogDataset(args.train_data_path, eos_token_id) train_loader = train_dataset.get_loader(args.batch_size, shuffle=True) gen_opt_params = {'weight_decay': args.gen_weight_decay, 'lr': args. gen_lr, 'warmup_steps': args.gen_warmup_steps, 'epsilon': args. gen_epsilon, 'total_steps': int(len(train_dataset) / args. batch_size) * args.epochs} generator = DialogGenerator(args.pretrained_gen, args.save_folder, gen_opt_params) if args.adv_model is not None: disc_opt_params = {'weight_decay': args.disc_weight_decay, 'lr': args.disc_lr, 'warmup_steps': args.disc_warmup_steps, 'epsilon': args.disc_epsilon, 'total_steps': int(len(train_dataset) / args .batch_size) * args.epochs} discriminator = DialogDiscriminator(args.adv_model, args. pretrained_disc, args.save_folder, disc_opt_params) generator.train_adversarial(train_loader, args.epochs, args. max_out_length, discriminator, args.train_disc_only_steps) else: generator.train_traditional(train_loader, args.epochs, args. max_out_length) <|reserved_special_token_1|> import torch import argparse from DialogGenerator import DialogGenerator from DialogDataset import DialogDataset from DialogDiscriminator import DialogDiscriminator from transformers import GPT2Tokenizer import os def prep_folder(args): """ Append to slash to filepath if needed, and generate folder if it doesn't exist""" if args.save_folder[-1] != '/': args.save_folder += '/' if not os.path.isdir(args.save_folder): os.mkdir(args.save_folder) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=3, dest='epochs', help='Number of epochs to run') parser.add_argument('--batch-size', type=int, default=50, dest= 'batch_size', help='Batch size') parser.add_argument('--max-out-length', type=int, default=128, dest= 'max_out_length', help= 'Maximum output length (outputs truncated if longer)') parser.add_argument('--adversarial-model', type=str, default=None, dest ='adv_model', help= 'Type of adversarial model to use. Will use traditional teacher forcing if None.' ) parser.add_argument('--train-disc-only-steps', type=int, default=0, dest='train_disc_only_steps', help= 'Number of steps for which to train discriminator only (without updating generator)' ) parser.add_argument('--gen_weight_decay', type=float, default=0, dest= 'gen_weight_decay', help= "Weight decay for the generator's training scheduler") parser.add_argument('--gen_lr', type=float, default=2e-05, dest= 'gen_lr', help='Learning rate for generator') parser.add_argument('--gen_epsilon', type=float, default=1e-08, dest= 'gen_epsilon', help='Epsilon parameter for generator optimizer') parser.add_argument('--gen_warmup_steps', type=int, default=0, dest= 'gen_warmup_steps', help= 'Number of warmup steps for training generator') parser.add_argument('--disc_weight_decay', type=float, default=0, dest= 'disc_weight_decay', help= "Weight decay for the discriminator's training scheduler") parser.add_argument('--disc_lr', type=float, default=2e-05, dest= 'disc_lr', help='Learning rate for discriminator') parser.add_argument('--disc_epsilon', type=float, default=1e-08, dest= 'disc_epsilon', help='Epsilon parameter for discriminator optimizer') parser.add_argument('--disc_warmup_steps', type=int, default=0, dest= 'disc_warmup_steps', help= 'Number of warmup steps for training discriminator') parser.add_argument('--train-data-path', type=str, dest= 'train_data_path', help='Filepath to preprocessed data') parser.add_argument('--save-folder', type=str, dest='save_folder', help ='Filepath to folder where checkpoints should be saved') parser.add_argument('--pretrained-gen', type=str, default=None, dest= 'pretrained_gen', help= 'Filepath to trained generator. If None, will instantiate a default pretrained generator.' ) parser.add_argument('--pretrained-disc', type=str, default=None, dest= 'pretrained_disc', help= 'Filepath to trained discriminator. If None, will instantiate a default pretrained discriminator of type specified by --adversarial-model option.' ) args = parser.parse_args() assert args.train_data_path is not None assert args.save_folder is not None prep_folder(args) eos_token_id = GPT2Tokenizer.from_pretrained('gpt2').eos_token_id train_dataset = DialogDataset(args.train_data_path, eos_token_id) train_loader = train_dataset.get_loader(args.batch_size, shuffle=True) gen_opt_params = {'weight_decay': args.gen_weight_decay, 'lr': args. gen_lr, 'warmup_steps': args.gen_warmup_steps, 'epsilon': args. gen_epsilon, 'total_steps': int(len(train_dataset) / args. batch_size) * args.epochs} generator = DialogGenerator(args.pretrained_gen, args.save_folder, gen_opt_params) if args.adv_model is not None: disc_opt_params = {'weight_decay': args.disc_weight_decay, 'lr': args.disc_lr, 'warmup_steps': args.disc_warmup_steps, 'epsilon': args.disc_epsilon, 'total_steps': int(len(train_dataset) / args .batch_size) * args.epochs} discriminator = DialogDiscriminator(args.adv_model, args. pretrained_disc, args.save_folder, disc_opt_params) generator.train_adversarial(train_loader, args.epochs, args. max_out_length, discriminator, args.train_disc_only_steps) else: generator.train_traditional(train_loader, args.epochs, args. max_out_length) <|reserved_special_token_1|> import torch import argparse from DialogGenerator import DialogGenerator from DialogDataset import DialogDataset from DialogDiscriminator import DialogDiscriminator from transformers import GPT2Tokenizer import os def prep_folder(args): """ Append to slash to filepath if needed, and generate folder if it doesn't exist""" if(args.save_folder[-1]!='/'): args.save_folder += '/' if(not os.path.isdir(args.save_folder)): os.mkdir(args.save_folder) if(__name__=="__main__"): parser = argparse.ArgumentParser() parser.add_argument('--epochs', type=int, default=3, dest="epochs", help='Number of epochs to run') parser.add_argument('--batch-size', type=int, default=50, dest="batch_size", help='Batch size') parser.add_argument('--max-out-length', type=int, default=128, dest="max_out_length", help='Maximum output length (outputs truncated if longer)') parser.add_argument('--adversarial-model', type=str, default=None, dest="adv_model", help='Type of adversarial model to use. Will use traditional teacher forcing if None.') parser.add_argument('--train-disc-only-steps', type=int, default=0, dest="train_disc_only_steps", help='Number of steps for which to train discriminator only (without updating generator)') parser.add_argument('--gen_weight_decay', type=float, default=0, dest="gen_weight_decay", help='Weight decay for the generator\'s training scheduler') parser.add_argument('--gen_lr', type=float, default=2e-5, dest="gen_lr", help='Learning rate for generator') parser.add_argument('--gen_epsilon', type=float, default=1e-8, dest="gen_epsilon", help='Epsilon parameter for generator optimizer') parser.add_argument('--gen_warmup_steps', type=int, default=0, dest="gen_warmup_steps", help='Number of warmup steps for training generator') parser.add_argument('--disc_weight_decay', type=float, default=0, dest="disc_weight_decay", help='Weight decay for the discriminator\'s training scheduler') parser.add_argument('--disc_lr', type=float, default=2e-5, dest="disc_lr", help='Learning rate for discriminator') parser.add_argument('--disc_epsilon', type=float, default=1e-8, dest="disc_epsilon", help='Epsilon parameter for discriminator optimizer') parser.add_argument('--disc_warmup_steps', type=int, default=0, dest="disc_warmup_steps", help='Number of warmup steps for training discriminator') parser.add_argument('--train-data-path', type=str, dest="train_data_path", help="Filepath to preprocessed data") parser.add_argument('--save-folder', type=str, dest="save_folder", help="Filepath to folder where checkpoints should be saved") parser.add_argument('--pretrained-gen', type=str, default=None, dest="pretrained_gen", help="Filepath to trained generator. If None, will instantiate a default pretrained generator.") parser.add_argument('--pretrained-disc', type=str, default=None, dest="pretrained_disc", help="Filepath to trained discriminator. If None, will instantiate a default pretrained discriminator of type specified by --adversarial-model option.") args = parser.parse_args() assert args.train_data_path is not None assert args.save_folder is not None prep_folder(args) eos_token_id = GPT2Tokenizer.from_pretrained("gpt2").eos_token_id train_dataset = DialogDataset(args.train_data_path, eos_token_id) train_loader = train_dataset.get_loader(args.batch_size, shuffle=True) gen_opt_params = {"weight_decay": args.gen_weight_decay, "lr": args.gen_lr, "warmup_steps": args.gen_warmup_steps, "epsilon": args.gen_epsilon, "total_steps": int(len(train_dataset) / args.batch_size) * args.epochs } generator = DialogGenerator(args.pretrained_gen, args.save_folder, gen_opt_params) if(args.adv_model is not None): disc_opt_params = {"weight_decay": args.disc_weight_decay, "lr": args.disc_lr, "warmup_steps": args.disc_warmup_steps, "epsilon": args.disc_epsilon, "total_steps": int(len(train_dataset) / args.batch_size) * args.epochs } discriminator = DialogDiscriminator(args.adv_model, args.pretrained_disc, args.save_folder, disc_opt_params) generator.train_adversarial(train_loader, args.epochs, args.max_out_length, discriminator, args.train_disc_only_steps) else: generator.train_traditional(train_loader, args.epochs, args.max_out_length)
flexible
{ "blob_id": "18be97061c65185fcebf10c628e0e51bb08522cf", "index": 3609, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef prep_folder(args):\n \"\"\" Append to slash to filepath if needed, and generate folder if it doesn't exist\"\"\"\n if args.save_folder[-1] != '/':\n args.save_folder += '/'\n if not os.path.isdir(args.save_folder):\n os.mkdir(args.save_folder)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef prep_folder(args):\n \"\"\" Append to slash to filepath if needed, and generate folder if it doesn't exist\"\"\"\n if args.save_folder[-1] != '/':\n args.save_folder += '/'\n if not os.path.isdir(args.save_folder):\n os.mkdir(args.save_folder)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=3, dest='epochs',\n help='Number of epochs to run')\n parser.add_argument('--batch-size', type=int, default=50, dest=\n 'batch_size', help='Batch size')\n parser.add_argument('--max-out-length', type=int, default=128, dest=\n 'max_out_length', help=\n 'Maximum output length (outputs truncated if longer)')\n parser.add_argument('--adversarial-model', type=str, default=None, dest\n ='adv_model', help=\n 'Type of adversarial model to use. Will use traditional teacher forcing if None.'\n )\n parser.add_argument('--train-disc-only-steps', type=int, default=0,\n dest='train_disc_only_steps', help=\n 'Number of steps for which to train discriminator only (without updating generator)'\n )\n parser.add_argument('--gen_weight_decay', type=float, default=0, dest=\n 'gen_weight_decay', help=\n \"Weight decay for the generator's training scheduler\")\n parser.add_argument('--gen_lr', type=float, default=2e-05, dest=\n 'gen_lr', help='Learning rate for generator')\n parser.add_argument('--gen_epsilon', type=float, default=1e-08, dest=\n 'gen_epsilon', help='Epsilon parameter for generator optimizer')\n parser.add_argument('--gen_warmup_steps', type=int, default=0, dest=\n 'gen_warmup_steps', help=\n 'Number of warmup steps for training generator')\n parser.add_argument('--disc_weight_decay', type=float, default=0, dest=\n 'disc_weight_decay', help=\n \"Weight decay for the discriminator's training scheduler\")\n parser.add_argument('--disc_lr', type=float, default=2e-05, dest=\n 'disc_lr', help='Learning rate for discriminator')\n parser.add_argument('--disc_epsilon', type=float, default=1e-08, dest=\n 'disc_epsilon', help='Epsilon parameter for discriminator optimizer')\n parser.add_argument('--disc_warmup_steps', type=int, default=0, dest=\n 'disc_warmup_steps', help=\n 'Number of warmup steps for training discriminator')\n parser.add_argument('--train-data-path', type=str, dest=\n 'train_data_path', help='Filepath to preprocessed data')\n parser.add_argument('--save-folder', type=str, dest='save_folder', help\n ='Filepath to folder where checkpoints should be saved')\n parser.add_argument('--pretrained-gen', type=str, default=None, dest=\n 'pretrained_gen', help=\n 'Filepath to trained generator. If None, will instantiate a default pretrained generator.'\n )\n parser.add_argument('--pretrained-disc', type=str, default=None, dest=\n 'pretrained_disc', help=\n 'Filepath to trained discriminator. If None, will instantiate a default pretrained discriminator of type specified by --adversarial-model option.'\n )\n args = parser.parse_args()\n assert args.train_data_path is not None\n assert args.save_folder is not None\n prep_folder(args)\n eos_token_id = GPT2Tokenizer.from_pretrained('gpt2').eos_token_id\n train_dataset = DialogDataset(args.train_data_path, eos_token_id)\n train_loader = train_dataset.get_loader(args.batch_size, shuffle=True)\n gen_opt_params = {'weight_decay': args.gen_weight_decay, 'lr': args.\n gen_lr, 'warmup_steps': args.gen_warmup_steps, 'epsilon': args.\n gen_epsilon, 'total_steps': int(len(train_dataset) / args.\n batch_size) * args.epochs}\n generator = DialogGenerator(args.pretrained_gen, args.save_folder,\n gen_opt_params)\n if args.adv_model is not None:\n disc_opt_params = {'weight_decay': args.disc_weight_decay, 'lr':\n args.disc_lr, 'warmup_steps': args.disc_warmup_steps, 'epsilon':\n args.disc_epsilon, 'total_steps': int(len(train_dataset) / args\n .batch_size) * args.epochs}\n discriminator = DialogDiscriminator(args.adv_model, args.\n pretrained_disc, args.save_folder, disc_opt_params)\n generator.train_adversarial(train_loader, args.epochs, args.\n max_out_length, discriminator, args.train_disc_only_steps)\n else:\n generator.train_traditional(train_loader, args.epochs, args.\n max_out_length)\n", "step-4": "import torch\nimport argparse\nfrom DialogGenerator import DialogGenerator\nfrom DialogDataset import DialogDataset\nfrom DialogDiscriminator import DialogDiscriminator\nfrom transformers import GPT2Tokenizer\nimport os\n\n\ndef prep_folder(args):\n \"\"\" Append to slash to filepath if needed, and generate folder if it doesn't exist\"\"\"\n if args.save_folder[-1] != '/':\n args.save_folder += '/'\n if not os.path.isdir(args.save_folder):\n os.mkdir(args.save_folder)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=3, dest='epochs',\n help='Number of epochs to run')\n parser.add_argument('--batch-size', type=int, default=50, dest=\n 'batch_size', help='Batch size')\n parser.add_argument('--max-out-length', type=int, default=128, dest=\n 'max_out_length', help=\n 'Maximum output length (outputs truncated if longer)')\n parser.add_argument('--adversarial-model', type=str, default=None, dest\n ='adv_model', help=\n 'Type of adversarial model to use. Will use traditional teacher forcing if None.'\n )\n parser.add_argument('--train-disc-only-steps', type=int, default=0,\n dest='train_disc_only_steps', help=\n 'Number of steps for which to train discriminator only (without updating generator)'\n )\n parser.add_argument('--gen_weight_decay', type=float, default=0, dest=\n 'gen_weight_decay', help=\n \"Weight decay for the generator's training scheduler\")\n parser.add_argument('--gen_lr', type=float, default=2e-05, dest=\n 'gen_lr', help='Learning rate for generator')\n parser.add_argument('--gen_epsilon', type=float, default=1e-08, dest=\n 'gen_epsilon', help='Epsilon parameter for generator optimizer')\n parser.add_argument('--gen_warmup_steps', type=int, default=0, dest=\n 'gen_warmup_steps', help=\n 'Number of warmup steps for training generator')\n parser.add_argument('--disc_weight_decay', type=float, default=0, dest=\n 'disc_weight_decay', help=\n \"Weight decay for the discriminator's training scheduler\")\n parser.add_argument('--disc_lr', type=float, default=2e-05, dest=\n 'disc_lr', help='Learning rate for discriminator')\n parser.add_argument('--disc_epsilon', type=float, default=1e-08, dest=\n 'disc_epsilon', help='Epsilon parameter for discriminator optimizer')\n parser.add_argument('--disc_warmup_steps', type=int, default=0, dest=\n 'disc_warmup_steps', help=\n 'Number of warmup steps for training discriminator')\n parser.add_argument('--train-data-path', type=str, dest=\n 'train_data_path', help='Filepath to preprocessed data')\n parser.add_argument('--save-folder', type=str, dest='save_folder', help\n ='Filepath to folder where checkpoints should be saved')\n parser.add_argument('--pretrained-gen', type=str, default=None, dest=\n 'pretrained_gen', help=\n 'Filepath to trained generator. If None, will instantiate a default pretrained generator.'\n )\n parser.add_argument('--pretrained-disc', type=str, default=None, dest=\n 'pretrained_disc', help=\n 'Filepath to trained discriminator. If None, will instantiate a default pretrained discriminator of type specified by --adversarial-model option.'\n )\n args = parser.parse_args()\n assert args.train_data_path is not None\n assert args.save_folder is not None\n prep_folder(args)\n eos_token_id = GPT2Tokenizer.from_pretrained('gpt2').eos_token_id\n train_dataset = DialogDataset(args.train_data_path, eos_token_id)\n train_loader = train_dataset.get_loader(args.batch_size, shuffle=True)\n gen_opt_params = {'weight_decay': args.gen_weight_decay, 'lr': args.\n gen_lr, 'warmup_steps': args.gen_warmup_steps, 'epsilon': args.\n gen_epsilon, 'total_steps': int(len(train_dataset) / args.\n batch_size) * args.epochs}\n generator = DialogGenerator(args.pretrained_gen, args.save_folder,\n gen_opt_params)\n if args.adv_model is not None:\n disc_opt_params = {'weight_decay': args.disc_weight_decay, 'lr':\n args.disc_lr, 'warmup_steps': args.disc_warmup_steps, 'epsilon':\n args.disc_epsilon, 'total_steps': int(len(train_dataset) / args\n .batch_size) * args.epochs}\n discriminator = DialogDiscriminator(args.adv_model, args.\n pretrained_disc, args.save_folder, disc_opt_params)\n generator.train_adversarial(train_loader, args.epochs, args.\n max_out_length, discriminator, args.train_disc_only_steps)\n else:\n generator.train_traditional(train_loader, args.epochs, args.\n max_out_length)\n", "step-5": "import torch\nimport argparse\nfrom DialogGenerator import DialogGenerator\nfrom DialogDataset import DialogDataset\nfrom DialogDiscriminator import DialogDiscriminator\nfrom transformers import GPT2Tokenizer\nimport os\n\ndef prep_folder(args):\n \"\"\" Append to slash to filepath if needed, and generate folder if it doesn't exist\"\"\"\n if(args.save_folder[-1]!='/'):\n args.save_folder += '/'\n if(not os.path.isdir(args.save_folder)):\n os.mkdir(args.save_folder)\n\nif(__name__==\"__main__\"):\n parser = argparse.ArgumentParser()\n parser.add_argument('--epochs', type=int, default=3, dest=\"epochs\", help='Number of epochs to run')\n parser.add_argument('--batch-size', type=int, default=50, dest=\"batch_size\", help='Batch size')\n parser.add_argument('--max-out-length', type=int, default=128, dest=\"max_out_length\", help='Maximum output length (outputs truncated if longer)')\n parser.add_argument('--adversarial-model', type=str, default=None, dest=\"adv_model\", help='Type of adversarial model to use. Will use traditional teacher forcing if None.')\n parser.add_argument('--train-disc-only-steps', type=int, default=0, dest=\"train_disc_only_steps\", help='Number of steps for which to train discriminator only (without updating generator)')\n\n parser.add_argument('--gen_weight_decay', type=float, default=0, dest=\"gen_weight_decay\", help='Weight decay for the generator\\'s training scheduler')\n parser.add_argument('--gen_lr', type=float, default=2e-5, dest=\"gen_lr\", help='Learning rate for generator')\n parser.add_argument('--gen_epsilon', type=float, default=1e-8, dest=\"gen_epsilon\", help='Epsilon parameter for generator optimizer')\n parser.add_argument('--gen_warmup_steps', type=int, default=0, dest=\"gen_warmup_steps\", help='Number of warmup steps for training generator')\n\n parser.add_argument('--disc_weight_decay', type=float, default=0, dest=\"disc_weight_decay\", help='Weight decay for the discriminator\\'s training scheduler')\n parser.add_argument('--disc_lr', type=float, default=2e-5, dest=\"disc_lr\", help='Learning rate for discriminator')\n parser.add_argument('--disc_epsilon', type=float, default=1e-8, dest=\"disc_epsilon\", help='Epsilon parameter for discriminator optimizer')\n parser.add_argument('--disc_warmup_steps', type=int, default=0, dest=\"disc_warmup_steps\", help='Number of warmup steps for training discriminator')\n\n parser.add_argument('--train-data-path', type=str, dest=\"train_data_path\", help=\"Filepath to preprocessed data\")\n parser.add_argument('--save-folder', type=str, dest=\"save_folder\", help=\"Filepath to folder where checkpoints should be saved\")\n parser.add_argument('--pretrained-gen', type=str, default=None, dest=\"pretrained_gen\", help=\"Filepath to trained generator. If None, will instantiate a default pretrained generator.\")\n parser.add_argument('--pretrained-disc', type=str, default=None, dest=\"pretrained_disc\", help=\"Filepath to trained discriminator. If None, will instantiate a default pretrained discriminator of type specified by --adversarial-model option.\")\n\n args = parser.parse_args()\n\n assert args.train_data_path is not None\n assert args.save_folder is not None\n\n prep_folder(args)\n \n eos_token_id = GPT2Tokenizer.from_pretrained(\"gpt2\").eos_token_id\n train_dataset = DialogDataset(args.train_data_path, eos_token_id)\n train_loader = train_dataset.get_loader(args.batch_size, shuffle=True)\n\n gen_opt_params = {\"weight_decay\": args.gen_weight_decay, \n \"lr\": args.gen_lr, \n \"warmup_steps\": args.gen_warmup_steps,\n \"epsilon\": args.gen_epsilon,\n \"total_steps\": int(len(train_dataset) / args.batch_size) * args.epochs }\n\n generator = DialogGenerator(args.pretrained_gen, args.save_folder, gen_opt_params)\n\n if(args.adv_model is not None):\n disc_opt_params = {\"weight_decay\": args.disc_weight_decay, \n \"lr\": args.disc_lr, \n \"warmup_steps\": args.disc_warmup_steps,\n \"epsilon\": args.disc_epsilon,\n \"total_steps\": int(len(train_dataset) / args.batch_size) * args.epochs }\n discriminator = DialogDiscriminator(args.adv_model, args.pretrained_disc, args.save_folder, disc_opt_params)\n \n generator.train_adversarial(train_loader, args.epochs, args.max_out_length, discriminator, args.train_disc_only_steps)\n else:\n generator.train_traditional(train_loader, args.epochs, args.max_out_length)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> while True: o = sys.stdin.read(byte) if qlty > qlty * n % 1: oo = o sys.stdout.write(o) else: sys.stdout.write(oo) if not o: break n = n + 1 <|reserved_special_token_1|> <|reserved_special_token_0|> byte = int(sys.argv[1]) qlty = float(sys.argv[2]) n = 0 while True: o = sys.stdin.read(byte) if qlty > qlty * n % 1: oo = o sys.stdout.write(o) else: sys.stdout.write(oo) if not o: break n = n + 1 <|reserved_special_token_1|> import sys byte = int(sys.argv[1]) qlty = float(sys.argv[2]) n = 0 while True: o = sys.stdin.read(byte) if qlty > qlty * n % 1: oo = o sys.stdout.write(o) else: sys.stdout.write(oo) if not o: break n = n + 1 <|reserved_special_token_1|> import sys byte = int(sys.argv[1]) qlty = float(sys.argv[2]) n = 0 while True: o = sys.stdin.read(byte) if qlty>(qlty*n)%1: oo = o sys.stdout.write(o) else: sys.stdout.write(oo) if not o: break n=n+1
flexible
{ "blob_id": "70845ab4aab80d988a5c01d0b4fb76e63b800527", "index": 6484, "step-1": "<mask token>\n", "step-2": "<mask token>\nwhile True:\n o = sys.stdin.read(byte)\n if qlty > qlty * n % 1:\n oo = o\n sys.stdout.write(o)\n else:\n sys.stdout.write(oo)\n if not o:\n break\n n = n + 1\n", "step-3": "<mask token>\nbyte = int(sys.argv[1])\nqlty = float(sys.argv[2])\nn = 0\nwhile True:\n o = sys.stdin.read(byte)\n if qlty > qlty * n % 1:\n oo = o\n sys.stdout.write(o)\n else:\n sys.stdout.write(oo)\n if not o:\n break\n n = n + 1\n", "step-4": "import sys\nbyte = int(sys.argv[1])\nqlty = float(sys.argv[2])\nn = 0\nwhile True:\n o = sys.stdin.read(byte)\n if qlty > qlty * n % 1:\n oo = o\n sys.stdout.write(o)\n else:\n sys.stdout.write(oo)\n if not o:\n break\n n = n + 1\n", "step-5": "import sys\r\nbyte = int(sys.argv[1])\r\nqlty = float(sys.argv[2])\r\nn = 0\r\nwhile True:\r\n o = sys.stdin.read(byte)\r\n if qlty>(qlty*n)%1:\r\n oo = o\r\n sys.stdout.write(o)\r\n else:\r\n sys.stdout.write(oo)\r\n if not o:\r\n break\r\n n=n+1", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def process_frame(img): global vid_data img = cv2.resize(img, (w, h)) cv2.imshow('Frame', img) cv2.waitKey(1) vid_data = np.append(vid_data, img, axis=0) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def process_frame(img): global vid_data img = cv2.resize(img, (w, h)) cv2.imshow('Frame', img) cv2.waitKey(1) vid_data = np.append(vid_data, img, axis=0) <|reserved_special_token_0|> while vid.isOpened(): ret, frame = vid.read() if ret: process_frame(frame) n = n + 1 """ cv2.imshow('Frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break """ else: break vid.release() cv2.destroyAllWindows() print(vid_data.shape) <|reserved_special_token_0|> print(vid_data.shape) np.savetxt('trackmania_vid_data2D_360x640.csv', vid_data, delimiter=',') <|reserved_special_token_1|> <|reserved_special_token_0|> vid = cv2.VideoCapture('trackmania_test_vid.mp4') w = 1280 // 2 h = 720 // 2 vid_data = np.empty((360, 640, 3)) def process_frame(img): global vid_data img = cv2.resize(img, (w, h)) cv2.imshow('Frame', img) cv2.waitKey(1) vid_data = np.append(vid_data, img, axis=0) n = 0 while vid.isOpened(): ret, frame = vid.read() if ret: process_frame(frame) n = n + 1 """ cv2.imshow('Frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break """ else: break vid.release() cv2.destroyAllWindows() print(vid_data.shape) vid_data = vid_data.reshape((vid_data.shape[0], -1)) print(vid_data.shape) np.savetxt('trackmania_vid_data2D_360x640.csv', vid_data, delimiter=',') <|reserved_special_token_1|> import numpy as np import cv2 vid = cv2.VideoCapture('trackmania_test_vid.mp4') w = 1280 // 2 h = 720 // 2 vid_data = np.empty((360, 640, 3)) def process_frame(img): global vid_data img = cv2.resize(img, (w, h)) cv2.imshow('Frame', img) cv2.waitKey(1) vid_data = np.append(vid_data, img, axis=0) n = 0 while vid.isOpened(): ret, frame = vid.read() if ret: process_frame(frame) n = n + 1 """ cv2.imshow('Frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break """ else: break vid.release() cv2.destroyAllWindows() print(vid_data.shape) vid_data = vid_data.reshape((vid_data.shape[0], -1)) print(vid_data.shape) np.savetxt('trackmania_vid_data2D_360x640.csv', vid_data, delimiter=',') <|reserved_special_token_1|> #train a neural network from input video feed import numpy as np import cv2 vid = cv2.VideoCapture('trackmania_test_vid.mp4') w = 1280//2 h = 720//2 vid_data = np.empty((360, 640, 3)) #print(vid_data.shape) def process_frame(img): global vid_data img = cv2.resize(img, (w, h)) cv2.imshow('Frame', img) cv2.waitKey(1) vid_data = np.append(vid_data, img, axis=0) #print(img.shape) # Read until video is completed n = 0 while vid.isOpened(): # Capture frame-by-frame ret, frame = vid.read() if ret: #print("frame = {}".format(frame.shape)) process_frame(frame) n = n + 1 ''' cv2.imshow('Frame', frame) if cv2.waitKey(25) & 0xFF == ord('q'): break ''' else: break # When everything done, release the video capture object vid.release() # Closes all the frames cv2.destroyAllWindows() print(vid_data.shape) vid_data = vid_data.reshape((vid_data.shape[0], -1)) print(vid_data.shape) # n = 1340 #print('No. of frames = {}'.format(n)) np.savetxt("trackmania_vid_data2D_360x640.csv", vid_data, delimiter=",") #50580,320,3 ---> 281,180,320,3 #101160,640,3 ---> 281,360,640,3
flexible
{ "blob_id": "eb81b0e41743e1785b82e88f6a618dc91eba73e5", "index": 1389, "step-1": "<mask token>\n\n\ndef process_frame(img):\n global vid_data\n img = cv2.resize(img, (w, h))\n cv2.imshow('Frame', img)\n cv2.waitKey(1)\n vid_data = np.append(vid_data, img, axis=0)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef process_frame(img):\n global vid_data\n img = cv2.resize(img, (w, h))\n cv2.imshow('Frame', img)\n cv2.waitKey(1)\n vid_data = np.append(vid_data, img, axis=0)\n\n\n<mask token>\nwhile vid.isOpened():\n ret, frame = vid.read()\n if ret:\n process_frame(frame)\n n = n + 1\n \"\"\"\n cv2.imshow('Frame', frame)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n \"\"\"\n else:\n break\nvid.release()\ncv2.destroyAllWindows()\nprint(vid_data.shape)\n<mask token>\nprint(vid_data.shape)\nnp.savetxt('trackmania_vid_data2D_360x640.csv', vid_data, delimiter=',')\n", "step-3": "<mask token>\nvid = cv2.VideoCapture('trackmania_test_vid.mp4')\nw = 1280 // 2\nh = 720 // 2\nvid_data = np.empty((360, 640, 3))\n\n\ndef process_frame(img):\n global vid_data\n img = cv2.resize(img, (w, h))\n cv2.imshow('Frame', img)\n cv2.waitKey(1)\n vid_data = np.append(vid_data, img, axis=0)\n\n\nn = 0\nwhile vid.isOpened():\n ret, frame = vid.read()\n if ret:\n process_frame(frame)\n n = n + 1\n \"\"\"\n cv2.imshow('Frame', frame)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n \"\"\"\n else:\n break\nvid.release()\ncv2.destroyAllWindows()\nprint(vid_data.shape)\nvid_data = vid_data.reshape((vid_data.shape[0], -1))\nprint(vid_data.shape)\nnp.savetxt('trackmania_vid_data2D_360x640.csv', vid_data, delimiter=',')\n", "step-4": "import numpy as np\nimport cv2\nvid = cv2.VideoCapture('trackmania_test_vid.mp4')\nw = 1280 // 2\nh = 720 // 2\nvid_data = np.empty((360, 640, 3))\n\n\ndef process_frame(img):\n global vid_data\n img = cv2.resize(img, (w, h))\n cv2.imshow('Frame', img)\n cv2.waitKey(1)\n vid_data = np.append(vid_data, img, axis=0)\n\n\nn = 0\nwhile vid.isOpened():\n ret, frame = vid.read()\n if ret:\n process_frame(frame)\n n = n + 1\n \"\"\"\n cv2.imshow('Frame', frame)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n \"\"\"\n else:\n break\nvid.release()\ncv2.destroyAllWindows()\nprint(vid_data.shape)\nvid_data = vid_data.reshape((vid_data.shape[0], -1))\nprint(vid_data.shape)\nnp.savetxt('trackmania_vid_data2D_360x640.csv', vid_data, delimiter=',')\n", "step-5": "#train a neural network from input video feed\nimport numpy as np\nimport cv2\nvid = cv2.VideoCapture('trackmania_test_vid.mp4')\nw = 1280//2\nh = 720//2\n\nvid_data = np.empty((360, 640, 3))\n#print(vid_data.shape)\n\n\ndef process_frame(img):\n global vid_data\n img = cv2.resize(img, (w, h))\n cv2.imshow('Frame', img)\n cv2.waitKey(1)\n vid_data = np.append(vid_data, img, axis=0)\n #print(img.shape)\n\n\n# Read until video is completed\nn = 0\nwhile vid.isOpened():\n # Capture frame-by-frame\n ret, frame = vid.read()\n if ret:\n #print(\"frame = {}\".format(frame.shape))\n process_frame(frame)\n n = n + 1\n '''\n cv2.imshow('Frame', frame)\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n '''\n else:\n break\n\n# When everything done, release the video capture object\nvid.release()\n\n# Closes all the frames\ncv2.destroyAllWindows()\nprint(vid_data.shape)\nvid_data = vid_data.reshape((vid_data.shape[0], -1))\nprint(vid_data.shape)\n# n = 1340\n#print('No. of frames = {}'.format(n))\n\nnp.savetxt(\"trackmania_vid_data2D_360x640.csv\", vid_data, delimiter=\",\")\n\n#50580,320,3 ---> 281,180,320,3\n#101160,640,3 ---> 281,360,640,3\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> class AuthorizationError(ValueError): pass class BearerTokenValidator: def __init__(self, access_token, app_context: AppContext): self.access_token = access_token user_service = app_context.user_service self.blacklist_token_repo = app_context.blacklist_token_repo self.payload = user_service.decode_auth_token(access_token, get_jwk()) def check_is_blacklisted(self): is_blacklisted_token = BlacklistToken.check_blacklist(self. access_token, self.blacklist_token_repo) if is_blacklisted_token: LOGGER.debug('Token blacklisted.') raise AuthenticationError('Invalid token.') return self def check_username_claim(self): if not self.payload.get('sub'): LOGGER.debug('Token missing sub.') raise AuthorizationError('Forbidden.') return self def check_user_exists(self, user): if not user: LOGGER.debug('Token user not found.') raise AuthorizationError('Forbidden.') return self def check_has_permissions(self, user: User, permissions: list): has_permissions = True for permission in permissions: if not user.role.has_permission(Permission.from_enum(permission)): LOGGER.debug(f'Missing permission {permission}.') has_permissions = False LOGGER.debug(f'Required permissions: {permissions}') if not has_permissions: raise AuthorizationError('Forbidden.') return self @staticmethod def from_authorization_header(authorization_header: str, app_context: AppContext): if not authorization_header: LOGGER.debug('Authorization header not found.') raise AuthenticationError('Invalid token.') if 'Bearer ' not in authorization_header: LOGGER.debug('Bearer token not found.') raise AuthenticationError('Invalid token.') access_token = authorization_header.split('Bearer')[1].strip() LOGGER.debug(f'Bearer token is:\n"{access_token}"') return BearerTokenValidator(access_token, app_context) <|reserved_special_token_0|> class ExceptionHandlers: def __init__(self, app): @app.errorhandler(AuthorizationError) def handle_authorization_exception(e): """Return403 forbidden.""" return jsonify(str(e)), 403 @app.errorhandler(AuthenticationError) def handle_authentication_exception(e): """Return401 authentication error.""" return jsonify(str(e)), 401 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class AuthenticationError(ValueError): pass class AuthorizationError(ValueError): pass class BearerTokenValidator: def __init__(self, access_token, app_context: AppContext): self.access_token = access_token user_service = app_context.user_service self.blacklist_token_repo = app_context.blacklist_token_repo self.payload = user_service.decode_auth_token(access_token, get_jwk()) def check_is_blacklisted(self): is_blacklisted_token = BlacklistToken.check_blacklist(self. access_token, self.blacklist_token_repo) if is_blacklisted_token: LOGGER.debug('Token blacklisted.') raise AuthenticationError('Invalid token.') return self def check_username_claim(self): if not self.payload.get('sub'): LOGGER.debug('Token missing sub.') raise AuthorizationError('Forbidden.') return self def check_user_exists(self, user): if not user: LOGGER.debug('Token user not found.') raise AuthorizationError('Forbidden.') return self def check_has_permissions(self, user: User, permissions: list): has_permissions = True for permission in permissions: if not user.role.has_permission(Permission.from_enum(permission)): LOGGER.debug(f'Missing permission {permission}.') has_permissions = False LOGGER.debug(f'Required permissions: {permissions}') if not has_permissions: raise AuthorizationError('Forbidden.') return self @staticmethod def from_authorization_header(authorization_header: str, app_context: AppContext): if not authorization_header: LOGGER.debug('Authorization header not found.') raise AuthenticationError('Invalid token.') if 'Bearer ' not in authorization_header: LOGGER.debug('Bearer token not found.') raise AuthenticationError('Invalid token.') access_token = authorization_header.split('Bearer')[1].strip() LOGGER.debug(f'Bearer token is:\n"{access_token}"') return BearerTokenValidator(access_token, app_context) <|reserved_special_token_0|> class ExceptionHandlers: def __init__(self, app): @app.errorhandler(AuthorizationError) def handle_authorization_exception(e): """Return403 forbidden.""" return jsonify(str(e)), 403 @app.errorhandler(AuthenticationError) def handle_authentication_exception(e): """Return401 authentication error.""" return jsonify(str(e)), 401 <|reserved_special_token_0|> def issue_token_for_user(user: User): access_token = new_token({'iss': 'lorem.ipsum.dev', 'aud': 'lorem.ipsum.auth', 'sub': user.username, 'email': user.email, 'roles': [user.role.name], 'exp': datetime.datetime.now(tz=datetime .timezone.utc) + datetime.timedelta(hours=4), 'iat': datetime. datetime.now(tz=datetime.timezone.utc)}) return access_token <|reserved_special_token_1|> <|reserved_special_token_0|> def app_context(): if 'app_context' not in g: g.app_context = lorem_ipsum.create_app_context() return g.app_context @lru_cache() def get_jwk(): LOGGER.debug('Loading jwk from public key...') key_data = None with open(app_context().config['jwk_public_key_path'], 'rb') as _key_file: key_data = _key_file.read() LOGGER.debug(key_data) key = JsonWebKey.import_key(key_data, {'kty': 'RSA'}) _jwks = {'keys': [{**key.as_dict(), 'kid': 'demo_key'}]} LOGGER.debug(_jwks) return _jwks class AuthenticationError(ValueError): pass class AuthorizationError(ValueError): pass class BearerTokenValidator: def __init__(self, access_token, app_context: AppContext): self.access_token = access_token user_service = app_context.user_service self.blacklist_token_repo = app_context.blacklist_token_repo self.payload = user_service.decode_auth_token(access_token, get_jwk()) def check_is_blacklisted(self): is_blacklisted_token = BlacklistToken.check_blacklist(self. access_token, self.blacklist_token_repo) if is_blacklisted_token: LOGGER.debug('Token blacklisted.') raise AuthenticationError('Invalid token.') return self def check_username_claim(self): if not self.payload.get('sub'): LOGGER.debug('Token missing sub.') raise AuthorizationError('Forbidden.') return self def check_user_exists(self, user): if not user: LOGGER.debug('Token user not found.') raise AuthorizationError('Forbidden.') return self def check_has_permissions(self, user: User, permissions: list): has_permissions = True for permission in permissions: if not user.role.has_permission(Permission.from_enum(permission)): LOGGER.debug(f'Missing permission {permission}.') has_permissions = False LOGGER.debug(f'Required permissions: {permissions}') if not has_permissions: raise AuthorizationError('Forbidden.') return self @staticmethod def from_authorization_header(authorization_header: str, app_context: AppContext): if not authorization_header: LOGGER.debug('Authorization header not found.') raise AuthenticationError('Invalid token.') if 'Bearer ' not in authorization_header: LOGGER.debug('Bearer token not found.') raise AuthenticationError('Invalid token.') access_token = authorization_header.split('Bearer')[1].strip() LOGGER.debug(f'Bearer token is:\n"{access_token}"') return BearerTokenValidator(access_token, app_context) def should_skip_auth(flask_request): """ Return true if should skip auth, e.g. when method is OPTIONS like when performing a React request. :param flask_request: Flask request. :return: """ return flask_request.method in ['HEAD', 'OPTIONS'] <|reserved_special_token_0|> class ExceptionHandlers: def __init__(self, app): @app.errorhandler(AuthorizationError) def handle_authorization_exception(e): """Return403 forbidden.""" return jsonify(str(e)), 403 @app.errorhandler(AuthenticationError) def handle_authentication_exception(e): """Return401 authentication error.""" return jsonify(str(e)), 401 @lru_cache() def jwk_key(): jwk_path = os.environ.get('jwk_private_key_path') or app_context().config[ 'jwk_private_key_path'] with open(jwk_path, 'rb') as f: key = JsonWebKey.import_key(f.read()) return key def new_token(payload: dict): key = jwk_key() header = {'alg': 'RS256', 'kid': 'demo_key'} token = jwt.encode(header, payload, key) LOGGER.debug(token) return token.decode('utf-8') def issue_token_for_user(user: User): access_token = new_token({'iss': 'lorem.ipsum.dev', 'aud': 'lorem.ipsum.auth', 'sub': user.username, 'email': user.email, 'roles': [user.role.name], 'exp': datetime.datetime.now(tz=datetime .timezone.utc) + datetime.timedelta(hours=4), 'iat': datetime. datetime.now(tz=datetime.timezone.utc)}) return access_token <|reserved_special_token_1|> <|reserved_special_token_0|> LOGGER = logging.getLogger('lorem-ipsum') def app_context(): if 'app_context' not in g: g.app_context = lorem_ipsum.create_app_context() return g.app_context @lru_cache() def get_jwk(): LOGGER.debug('Loading jwk from public key...') key_data = None with open(app_context().config['jwk_public_key_path'], 'rb') as _key_file: key_data = _key_file.read() LOGGER.debug(key_data) key = JsonWebKey.import_key(key_data, {'kty': 'RSA'}) _jwks = {'keys': [{**key.as_dict(), 'kid': 'demo_key'}]} LOGGER.debug(_jwks) return _jwks class AuthenticationError(ValueError): pass class AuthorizationError(ValueError): pass class BearerTokenValidator: def __init__(self, access_token, app_context: AppContext): self.access_token = access_token user_service = app_context.user_service self.blacklist_token_repo = app_context.blacklist_token_repo self.payload = user_service.decode_auth_token(access_token, get_jwk()) def check_is_blacklisted(self): is_blacklisted_token = BlacklistToken.check_blacklist(self. access_token, self.blacklist_token_repo) if is_blacklisted_token: LOGGER.debug('Token blacklisted.') raise AuthenticationError('Invalid token.') return self def check_username_claim(self): if not self.payload.get('sub'): LOGGER.debug('Token missing sub.') raise AuthorizationError('Forbidden.') return self def check_user_exists(self, user): if not user: LOGGER.debug('Token user not found.') raise AuthorizationError('Forbidden.') return self def check_has_permissions(self, user: User, permissions: list): has_permissions = True for permission in permissions: if not user.role.has_permission(Permission.from_enum(permission)): LOGGER.debug(f'Missing permission {permission}.') has_permissions = False LOGGER.debug(f'Required permissions: {permissions}') if not has_permissions: raise AuthorizationError('Forbidden.') return self @staticmethod def from_authorization_header(authorization_header: str, app_context: AppContext): if not authorization_header: LOGGER.debug('Authorization header not found.') raise AuthenticationError('Invalid token.') if 'Bearer ' not in authorization_header: LOGGER.debug('Bearer token not found.') raise AuthenticationError('Invalid token.') access_token = authorization_header.split('Bearer')[1].strip() LOGGER.debug(f'Bearer token is:\n"{access_token}"') return BearerTokenValidator(access_token, app_context) def should_skip_auth(flask_request): """ Return true if should skip auth, e.g. when method is OPTIONS like when performing a React request. :param flask_request: Flask request. :return: """ return flask_request.method in ['HEAD', 'OPTIONS'] def requires_permission(permissions: list): def requires_permission_decorator(function): def wrapper(*args, **kwargs): LOGGER.info(f'Authorization...\n{request.headers}') if should_skip_auth(request): return jsonify('ok') authorization_header = request.headers.get('Authorization') context = app_context() with context.transaction_manager.transaction: bearer_token_validator = (BearerTokenValidator. from_authorization_header(authorization_header, context ).check_is_blacklisted().check_username_claim()) user = context.user_repo.get(username= bearer_token_validator.payload['sub']) bearer_token_validator.check_user_exists(user ).check_has_permissions(user, permissions) g.access_token = bearer_token_validator.access_token g.user = user _result = function(*args, **kwargs) return _result wrapper.__name__ = function.__name__ return wrapper return requires_permission_decorator class ExceptionHandlers: def __init__(self, app): @app.errorhandler(AuthorizationError) def handle_authorization_exception(e): """Return403 forbidden.""" return jsonify(str(e)), 403 @app.errorhandler(AuthenticationError) def handle_authentication_exception(e): """Return401 authentication error.""" return jsonify(str(e)), 401 @lru_cache() def jwk_key(): jwk_path = os.environ.get('jwk_private_key_path') or app_context().config[ 'jwk_private_key_path'] with open(jwk_path, 'rb') as f: key = JsonWebKey.import_key(f.read()) return key def new_token(payload: dict): key = jwk_key() header = {'alg': 'RS256', 'kid': 'demo_key'} token = jwt.encode(header, payload, key) LOGGER.debug(token) return token.decode('utf-8') def issue_token_for_user(user: User): access_token = new_token({'iss': 'lorem.ipsum.dev', 'aud': 'lorem.ipsum.auth', 'sub': user.username, 'email': user.email, 'roles': [user.role.name], 'exp': datetime.datetime.now(tz=datetime .timezone.utc) + datetime.timedelta(hours=4), 'iat': datetime. datetime.now(tz=datetime.timezone.utc)}) return access_token <|reserved_special_token_1|> import datetime import logging import os from functools import lru_cache from authlib.jose import JsonWebKey, jwt from flask import g, request, jsonify from lorem_ipsum.model import User, AppContext import lorem_ipsum from lorem_ipsum.model import Permission, BlacklistToken LOGGER = logging.getLogger('lorem-ipsum') def app_context(): if 'app_context' not in g: g.app_context = lorem_ipsum.create_app_context() return g.app_context @lru_cache() def get_jwk(): LOGGER.debug('Loading jwk from public key...') key_data = None with open(app_context().config['jwk_public_key_path'], 'rb') as _key_file: key_data = _key_file.read() LOGGER.debug(key_data) key = JsonWebKey.import_key(key_data, {'kty': 'RSA'}) _jwks = {'keys': [{**key.as_dict(), 'kid': 'demo_key'}]} LOGGER.debug(_jwks) return _jwks class AuthenticationError(ValueError): pass class AuthorizationError(ValueError): pass class BearerTokenValidator: def __init__(self, access_token, app_context: AppContext): self.access_token = access_token user_service = app_context.user_service self.blacklist_token_repo = app_context.blacklist_token_repo self.payload = user_service.decode_auth_token(access_token, get_jwk()) def check_is_blacklisted(self): is_blacklisted_token = BlacklistToken.check_blacklist(self.access_token, self.blacklist_token_repo) if is_blacklisted_token: LOGGER.debug('Token blacklisted.') raise AuthenticationError('Invalid token.') return self def check_username_claim(self): if not self.payload.get('sub'): LOGGER.debug('Token missing sub.') raise AuthorizationError('Forbidden.') return self def check_user_exists(self, user): if not user: LOGGER.debug('Token user not found.') raise AuthorizationError('Forbidden.') return self def check_has_permissions(self, user: User, permissions: list): has_permissions = True for permission in permissions: if not user.role.has_permission(Permission.from_enum(permission)): LOGGER.debug(f'Missing permission {permission}.') has_permissions = False LOGGER.debug(f'Required permissions: {permissions}') if not has_permissions: raise AuthorizationError('Forbidden.') return self @staticmethod def from_authorization_header(authorization_header: str, app_context: AppContext): if not authorization_header: LOGGER.debug('Authorization header not found.') raise AuthenticationError('Invalid token.') if 'Bearer ' not in authorization_header: LOGGER.debug('Bearer token not found.') raise AuthenticationError('Invalid token.') access_token = authorization_header.split('Bearer')[1].strip() LOGGER.debug(f'Bearer token is:\n"{access_token}"') return BearerTokenValidator(access_token, app_context) def should_skip_auth(flask_request): """ Return true if should skip auth, e.g. when method is OPTIONS like when performing a React request. :param flask_request: Flask request. :return: """ return flask_request.method in ['HEAD', 'OPTIONS'] def requires_permission(permissions: list): def requires_permission_decorator(function): def wrapper(*args, **kwargs): LOGGER.info(f'Authorization...\n{request.headers}') if should_skip_auth(request): return jsonify('ok') authorization_header = request.headers.get('Authorization') context = app_context() with context.transaction_manager.transaction: bearer_token_validator = BearerTokenValidator.from_authorization_header(authorization_header, context) \ .check_is_blacklisted() \ .check_username_claim() user = context.user_repo.get(username=bearer_token_validator.payload['sub']) bearer_token_validator.check_user_exists(user) \ .check_has_permissions(user, permissions) g.access_token = bearer_token_validator.access_token g.user = user _result = function(*args, **kwargs) return _result wrapper.__name__ = function.__name__ return wrapper return requires_permission_decorator class ExceptionHandlers: def __init__(self, app): @app.errorhandler(AuthorizationError) def handle_authorization_exception(e): """Return403 forbidden.""" return jsonify(str(e)), 403 @app.errorhandler(AuthenticationError) def handle_authentication_exception(e): """Return401 authentication error.""" return jsonify(str(e)), 401 @lru_cache() def jwk_key(): jwk_path = os.environ.get('jwk_private_key_path') or app_context().config['jwk_private_key_path'] with open(jwk_path, 'rb') as f: key = JsonWebKey.import_key(f.read()) return key def new_token(payload: dict): key = jwk_key() header = {'alg': 'RS256', 'kid': 'demo_key'} token = jwt.encode(header, payload, key) LOGGER.debug(token) return token.decode('utf-8') def issue_token_for_user(user: User): access_token = new_token({ "iss": "lorem.ipsum.dev", "aud": "lorem.ipsum.auth", "sub": user.username, "email": user.email, "roles": [ user.role.name ], "exp": datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(hours=4), "iat": datetime.datetime.now(tz=datetime.timezone.utc) }) return access_token
flexible
{ "blob_id": "97d4387c7bfd141b5a7019b221adb550105d4351", "index": 604, "step-1": "<mask token>\n\n\nclass AuthorizationError(ValueError):\n pass\n\n\nclass BearerTokenValidator:\n\n def __init__(self, access_token, app_context: AppContext):\n self.access_token = access_token\n user_service = app_context.user_service\n self.blacklist_token_repo = app_context.blacklist_token_repo\n self.payload = user_service.decode_auth_token(access_token, get_jwk())\n\n def check_is_blacklisted(self):\n is_blacklisted_token = BlacklistToken.check_blacklist(self.\n access_token, self.blacklist_token_repo)\n if is_blacklisted_token:\n LOGGER.debug('Token blacklisted.')\n raise AuthenticationError('Invalid token.')\n return self\n\n def check_username_claim(self):\n if not self.payload.get('sub'):\n LOGGER.debug('Token missing sub.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_user_exists(self, user):\n if not user:\n LOGGER.debug('Token user not found.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_has_permissions(self, user: User, permissions: list):\n has_permissions = True\n for permission in permissions:\n if not user.role.has_permission(Permission.from_enum(permission)):\n LOGGER.debug(f'Missing permission {permission}.')\n has_permissions = False\n LOGGER.debug(f'Required permissions: {permissions}')\n if not has_permissions:\n raise AuthorizationError('Forbidden.')\n return self\n\n @staticmethod\n def from_authorization_header(authorization_header: str, app_context:\n AppContext):\n if not authorization_header:\n LOGGER.debug('Authorization header not found.')\n raise AuthenticationError('Invalid token.')\n if 'Bearer ' not in authorization_header:\n LOGGER.debug('Bearer token not found.')\n raise AuthenticationError('Invalid token.')\n access_token = authorization_header.split('Bearer')[1].strip()\n LOGGER.debug(f'Bearer token is:\\n\"{access_token}\"')\n return BearerTokenValidator(access_token, app_context)\n\n\n<mask token>\n\n\nclass ExceptionHandlers:\n\n def __init__(self, app):\n\n @app.errorhandler(AuthorizationError)\n def handle_authorization_exception(e):\n \"\"\"Return403 forbidden.\"\"\"\n return jsonify(str(e)), 403\n\n @app.errorhandler(AuthenticationError)\n def handle_authentication_exception(e):\n \"\"\"Return401 authentication error.\"\"\"\n return jsonify(str(e)), 401\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass AuthenticationError(ValueError):\n pass\n\n\nclass AuthorizationError(ValueError):\n pass\n\n\nclass BearerTokenValidator:\n\n def __init__(self, access_token, app_context: AppContext):\n self.access_token = access_token\n user_service = app_context.user_service\n self.blacklist_token_repo = app_context.blacklist_token_repo\n self.payload = user_service.decode_auth_token(access_token, get_jwk())\n\n def check_is_blacklisted(self):\n is_blacklisted_token = BlacklistToken.check_blacklist(self.\n access_token, self.blacklist_token_repo)\n if is_blacklisted_token:\n LOGGER.debug('Token blacklisted.')\n raise AuthenticationError('Invalid token.')\n return self\n\n def check_username_claim(self):\n if not self.payload.get('sub'):\n LOGGER.debug('Token missing sub.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_user_exists(self, user):\n if not user:\n LOGGER.debug('Token user not found.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_has_permissions(self, user: User, permissions: list):\n has_permissions = True\n for permission in permissions:\n if not user.role.has_permission(Permission.from_enum(permission)):\n LOGGER.debug(f'Missing permission {permission}.')\n has_permissions = False\n LOGGER.debug(f'Required permissions: {permissions}')\n if not has_permissions:\n raise AuthorizationError('Forbidden.')\n return self\n\n @staticmethod\n def from_authorization_header(authorization_header: str, app_context:\n AppContext):\n if not authorization_header:\n LOGGER.debug('Authorization header not found.')\n raise AuthenticationError('Invalid token.')\n if 'Bearer ' not in authorization_header:\n LOGGER.debug('Bearer token not found.')\n raise AuthenticationError('Invalid token.')\n access_token = authorization_header.split('Bearer')[1].strip()\n LOGGER.debug(f'Bearer token is:\\n\"{access_token}\"')\n return BearerTokenValidator(access_token, app_context)\n\n\n<mask token>\n\n\nclass ExceptionHandlers:\n\n def __init__(self, app):\n\n @app.errorhandler(AuthorizationError)\n def handle_authorization_exception(e):\n \"\"\"Return403 forbidden.\"\"\"\n return jsonify(str(e)), 403\n\n @app.errorhandler(AuthenticationError)\n def handle_authentication_exception(e):\n \"\"\"Return401 authentication error.\"\"\"\n return jsonify(str(e)), 401\n\n\n<mask token>\n\n\ndef issue_token_for_user(user: User):\n access_token = new_token({'iss': 'lorem.ipsum.dev', 'aud':\n 'lorem.ipsum.auth', 'sub': user.username, 'email': user.email,\n 'roles': [user.role.name], 'exp': datetime.datetime.now(tz=datetime\n .timezone.utc) + datetime.timedelta(hours=4), 'iat': datetime.\n datetime.now(tz=datetime.timezone.utc)})\n return access_token\n", "step-3": "<mask token>\n\n\ndef app_context():\n if 'app_context' not in g:\n g.app_context = lorem_ipsum.create_app_context()\n return g.app_context\n\n\n@lru_cache()\ndef get_jwk():\n LOGGER.debug('Loading jwk from public key...')\n key_data = None\n with open(app_context().config['jwk_public_key_path'], 'rb') as _key_file:\n key_data = _key_file.read()\n LOGGER.debug(key_data)\n key = JsonWebKey.import_key(key_data, {'kty': 'RSA'})\n _jwks = {'keys': [{**key.as_dict(), 'kid': 'demo_key'}]}\n LOGGER.debug(_jwks)\n return _jwks\n\n\nclass AuthenticationError(ValueError):\n pass\n\n\nclass AuthorizationError(ValueError):\n pass\n\n\nclass BearerTokenValidator:\n\n def __init__(self, access_token, app_context: AppContext):\n self.access_token = access_token\n user_service = app_context.user_service\n self.blacklist_token_repo = app_context.blacklist_token_repo\n self.payload = user_service.decode_auth_token(access_token, get_jwk())\n\n def check_is_blacklisted(self):\n is_blacklisted_token = BlacklistToken.check_blacklist(self.\n access_token, self.blacklist_token_repo)\n if is_blacklisted_token:\n LOGGER.debug('Token blacklisted.')\n raise AuthenticationError('Invalid token.')\n return self\n\n def check_username_claim(self):\n if not self.payload.get('sub'):\n LOGGER.debug('Token missing sub.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_user_exists(self, user):\n if not user:\n LOGGER.debug('Token user not found.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_has_permissions(self, user: User, permissions: list):\n has_permissions = True\n for permission in permissions:\n if not user.role.has_permission(Permission.from_enum(permission)):\n LOGGER.debug(f'Missing permission {permission}.')\n has_permissions = False\n LOGGER.debug(f'Required permissions: {permissions}')\n if not has_permissions:\n raise AuthorizationError('Forbidden.')\n return self\n\n @staticmethod\n def from_authorization_header(authorization_header: str, app_context:\n AppContext):\n if not authorization_header:\n LOGGER.debug('Authorization header not found.')\n raise AuthenticationError('Invalid token.')\n if 'Bearer ' not in authorization_header:\n LOGGER.debug('Bearer token not found.')\n raise AuthenticationError('Invalid token.')\n access_token = authorization_header.split('Bearer')[1].strip()\n LOGGER.debug(f'Bearer token is:\\n\"{access_token}\"')\n return BearerTokenValidator(access_token, app_context)\n\n\ndef should_skip_auth(flask_request):\n \"\"\"\n Return true if should skip auth, e.g. when method is OPTIONS like when performing a React request.\n :param flask_request: Flask request.\n :return:\n \"\"\"\n return flask_request.method in ['HEAD', 'OPTIONS']\n\n\n<mask token>\n\n\nclass ExceptionHandlers:\n\n def __init__(self, app):\n\n @app.errorhandler(AuthorizationError)\n def handle_authorization_exception(e):\n \"\"\"Return403 forbidden.\"\"\"\n return jsonify(str(e)), 403\n\n @app.errorhandler(AuthenticationError)\n def handle_authentication_exception(e):\n \"\"\"Return401 authentication error.\"\"\"\n return jsonify(str(e)), 401\n\n\n@lru_cache()\ndef jwk_key():\n jwk_path = os.environ.get('jwk_private_key_path') or app_context().config[\n 'jwk_private_key_path']\n with open(jwk_path, 'rb') as f:\n key = JsonWebKey.import_key(f.read())\n return key\n\n\ndef new_token(payload: dict):\n key = jwk_key()\n header = {'alg': 'RS256', 'kid': 'demo_key'}\n token = jwt.encode(header, payload, key)\n LOGGER.debug(token)\n return token.decode('utf-8')\n\n\ndef issue_token_for_user(user: User):\n access_token = new_token({'iss': 'lorem.ipsum.dev', 'aud':\n 'lorem.ipsum.auth', 'sub': user.username, 'email': user.email,\n 'roles': [user.role.name], 'exp': datetime.datetime.now(tz=datetime\n .timezone.utc) + datetime.timedelta(hours=4), 'iat': datetime.\n datetime.now(tz=datetime.timezone.utc)})\n return access_token\n", "step-4": "<mask token>\nLOGGER = logging.getLogger('lorem-ipsum')\n\n\ndef app_context():\n if 'app_context' not in g:\n g.app_context = lorem_ipsum.create_app_context()\n return g.app_context\n\n\n@lru_cache()\ndef get_jwk():\n LOGGER.debug('Loading jwk from public key...')\n key_data = None\n with open(app_context().config['jwk_public_key_path'], 'rb') as _key_file:\n key_data = _key_file.read()\n LOGGER.debug(key_data)\n key = JsonWebKey.import_key(key_data, {'kty': 'RSA'})\n _jwks = {'keys': [{**key.as_dict(), 'kid': 'demo_key'}]}\n LOGGER.debug(_jwks)\n return _jwks\n\n\nclass AuthenticationError(ValueError):\n pass\n\n\nclass AuthorizationError(ValueError):\n pass\n\n\nclass BearerTokenValidator:\n\n def __init__(self, access_token, app_context: AppContext):\n self.access_token = access_token\n user_service = app_context.user_service\n self.blacklist_token_repo = app_context.blacklist_token_repo\n self.payload = user_service.decode_auth_token(access_token, get_jwk())\n\n def check_is_blacklisted(self):\n is_blacklisted_token = BlacklistToken.check_blacklist(self.\n access_token, self.blacklist_token_repo)\n if is_blacklisted_token:\n LOGGER.debug('Token blacklisted.')\n raise AuthenticationError('Invalid token.')\n return self\n\n def check_username_claim(self):\n if not self.payload.get('sub'):\n LOGGER.debug('Token missing sub.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_user_exists(self, user):\n if not user:\n LOGGER.debug('Token user not found.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_has_permissions(self, user: User, permissions: list):\n has_permissions = True\n for permission in permissions:\n if not user.role.has_permission(Permission.from_enum(permission)):\n LOGGER.debug(f'Missing permission {permission}.')\n has_permissions = False\n LOGGER.debug(f'Required permissions: {permissions}')\n if not has_permissions:\n raise AuthorizationError('Forbidden.')\n return self\n\n @staticmethod\n def from_authorization_header(authorization_header: str, app_context:\n AppContext):\n if not authorization_header:\n LOGGER.debug('Authorization header not found.')\n raise AuthenticationError('Invalid token.')\n if 'Bearer ' not in authorization_header:\n LOGGER.debug('Bearer token not found.')\n raise AuthenticationError('Invalid token.')\n access_token = authorization_header.split('Bearer')[1].strip()\n LOGGER.debug(f'Bearer token is:\\n\"{access_token}\"')\n return BearerTokenValidator(access_token, app_context)\n\n\ndef should_skip_auth(flask_request):\n \"\"\"\n Return true if should skip auth, e.g. when method is OPTIONS like when performing a React request.\n :param flask_request: Flask request.\n :return:\n \"\"\"\n return flask_request.method in ['HEAD', 'OPTIONS']\n\n\ndef requires_permission(permissions: list):\n\n def requires_permission_decorator(function):\n\n def wrapper(*args, **kwargs):\n LOGGER.info(f'Authorization...\\n{request.headers}')\n if should_skip_auth(request):\n return jsonify('ok')\n authorization_header = request.headers.get('Authorization')\n context = app_context()\n with context.transaction_manager.transaction:\n bearer_token_validator = (BearerTokenValidator.\n from_authorization_header(authorization_header, context\n ).check_is_blacklisted().check_username_claim())\n user = context.user_repo.get(username=\n bearer_token_validator.payload['sub'])\n bearer_token_validator.check_user_exists(user\n ).check_has_permissions(user, permissions)\n g.access_token = bearer_token_validator.access_token\n g.user = user\n _result = function(*args, **kwargs)\n return _result\n wrapper.__name__ = function.__name__\n return wrapper\n return requires_permission_decorator\n\n\nclass ExceptionHandlers:\n\n def __init__(self, app):\n\n @app.errorhandler(AuthorizationError)\n def handle_authorization_exception(e):\n \"\"\"Return403 forbidden.\"\"\"\n return jsonify(str(e)), 403\n\n @app.errorhandler(AuthenticationError)\n def handle_authentication_exception(e):\n \"\"\"Return401 authentication error.\"\"\"\n return jsonify(str(e)), 401\n\n\n@lru_cache()\ndef jwk_key():\n jwk_path = os.environ.get('jwk_private_key_path') or app_context().config[\n 'jwk_private_key_path']\n with open(jwk_path, 'rb') as f:\n key = JsonWebKey.import_key(f.read())\n return key\n\n\ndef new_token(payload: dict):\n key = jwk_key()\n header = {'alg': 'RS256', 'kid': 'demo_key'}\n token = jwt.encode(header, payload, key)\n LOGGER.debug(token)\n return token.decode('utf-8')\n\n\ndef issue_token_for_user(user: User):\n access_token = new_token({'iss': 'lorem.ipsum.dev', 'aud':\n 'lorem.ipsum.auth', 'sub': user.username, 'email': user.email,\n 'roles': [user.role.name], 'exp': datetime.datetime.now(tz=datetime\n .timezone.utc) + datetime.timedelta(hours=4), 'iat': datetime.\n datetime.now(tz=datetime.timezone.utc)})\n return access_token\n", "step-5": "import datetime\nimport logging\nimport os\nfrom functools import lru_cache\nfrom authlib.jose import JsonWebKey, jwt\n\nfrom flask import g, request, jsonify\nfrom lorem_ipsum.model import User, AppContext\nimport lorem_ipsum\nfrom lorem_ipsum.model import Permission, BlacklistToken\n\nLOGGER = logging.getLogger('lorem-ipsum')\n\n\ndef app_context():\n if 'app_context' not in g:\n g.app_context = lorem_ipsum.create_app_context()\n return g.app_context\n\n\n@lru_cache()\ndef get_jwk():\n LOGGER.debug('Loading jwk from public key...')\n key_data = None\n with open(app_context().config['jwk_public_key_path'], 'rb') as _key_file:\n key_data = _key_file.read()\n LOGGER.debug(key_data)\n key = JsonWebKey.import_key(key_data, {'kty': 'RSA'})\n _jwks = {'keys': [{**key.as_dict(), 'kid': 'demo_key'}]}\n LOGGER.debug(_jwks)\n return _jwks\n\n\nclass AuthenticationError(ValueError):\n pass\n\n\nclass AuthorizationError(ValueError):\n pass\n\n\nclass BearerTokenValidator:\n def __init__(self, access_token, app_context: AppContext):\n self.access_token = access_token\n user_service = app_context.user_service\n self.blacklist_token_repo = app_context.blacklist_token_repo\n self.payload = user_service.decode_auth_token(access_token, get_jwk())\n\n def check_is_blacklisted(self):\n is_blacklisted_token = BlacklistToken.check_blacklist(self.access_token, self.blacklist_token_repo)\n if is_blacklisted_token:\n LOGGER.debug('Token blacklisted.')\n raise AuthenticationError('Invalid token.')\n return self\n\n def check_username_claim(self):\n if not self.payload.get('sub'):\n LOGGER.debug('Token missing sub.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_user_exists(self, user):\n if not user:\n LOGGER.debug('Token user not found.')\n raise AuthorizationError('Forbidden.')\n return self\n\n def check_has_permissions(self, user: User, permissions: list):\n has_permissions = True\n for permission in permissions:\n if not user.role.has_permission(Permission.from_enum(permission)):\n LOGGER.debug(f'Missing permission {permission}.')\n has_permissions = False\n LOGGER.debug(f'Required permissions: {permissions}')\n if not has_permissions:\n raise AuthorizationError('Forbidden.')\n return self\n\n @staticmethod\n def from_authorization_header(authorization_header: str, app_context: AppContext):\n if not authorization_header:\n LOGGER.debug('Authorization header not found.')\n raise AuthenticationError('Invalid token.')\n if 'Bearer ' not in authorization_header:\n LOGGER.debug('Bearer token not found.')\n raise AuthenticationError('Invalid token.')\n access_token = authorization_header.split('Bearer')[1].strip()\n LOGGER.debug(f'Bearer token is:\\n\"{access_token}\"')\n return BearerTokenValidator(access_token, app_context)\n\n\ndef should_skip_auth(flask_request):\n \"\"\"\n Return true if should skip auth, e.g. when method is OPTIONS like when performing a React request.\n :param flask_request: Flask request.\n :return:\n \"\"\"\n return flask_request.method in ['HEAD', 'OPTIONS']\n\n\ndef requires_permission(permissions: list):\n def requires_permission_decorator(function):\n def wrapper(*args, **kwargs):\n LOGGER.info(f'Authorization...\\n{request.headers}')\n if should_skip_auth(request):\n return jsonify('ok')\n authorization_header = request.headers.get('Authorization')\n context = app_context()\n with context.transaction_manager.transaction:\n bearer_token_validator = BearerTokenValidator.from_authorization_header(authorization_header, context) \\\n .check_is_blacklisted() \\\n .check_username_claim()\n user = context.user_repo.get(username=bearer_token_validator.payload['sub'])\n\n bearer_token_validator.check_user_exists(user) \\\n .check_has_permissions(user, permissions)\n g.access_token = bearer_token_validator.access_token\n g.user = user\n\n _result = function(*args, **kwargs)\n return _result\n\n wrapper.__name__ = function.__name__\n return wrapper\n\n return requires_permission_decorator\n\n\nclass ExceptionHandlers:\n def __init__(self, app):\n @app.errorhandler(AuthorizationError)\n def handle_authorization_exception(e):\n \"\"\"Return403 forbidden.\"\"\"\n return jsonify(str(e)), 403\n\n @app.errorhandler(AuthenticationError)\n def handle_authentication_exception(e):\n \"\"\"Return401 authentication error.\"\"\"\n return jsonify(str(e)), 401\n\n\n@lru_cache()\ndef jwk_key():\n jwk_path = os.environ.get('jwk_private_key_path') or app_context().config['jwk_private_key_path']\n with open(jwk_path, 'rb') as f:\n key = JsonWebKey.import_key(f.read())\n return key\n\n\ndef new_token(payload: dict):\n key = jwk_key()\n header = {'alg': 'RS256', 'kid': 'demo_key'}\n token = jwt.encode(header, payload, key)\n LOGGER.debug(token)\n return token.decode('utf-8')\n\n\ndef issue_token_for_user(user: User):\n access_token = new_token({\n \"iss\": \"lorem.ipsum.dev\",\n \"aud\": \"lorem.ipsum.auth\",\n \"sub\": user.username,\n \"email\": user.email,\n \"roles\": [\n user.role.name\n ],\n \"exp\": datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(hours=4),\n \"iat\": datetime.datetime.now(tz=datetime.timezone.utc)\n })\n return access_token\n", "step-ids": [ 10, 12, 17, 19, 21 ] }
[ 10, 12, 17, 19, 21 ]
import csv with open('./csvs/users.csv', encoding='utf-8', newline='') as users_csv: reader = csv.reader(users_csv) d = {} for row in reader: userId, profileName = row if profileName == 'A Customer': continue value = d.get(profileName) if not value: d.setdefault(profileName, userId) else: if value != userId: print(f'{userId}, {value}, {profileName}')
normal
{ "blob_id": "3b77f7ea5137174e6723368502659390ea064c5a", "index": 8968, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('./csvs/users.csv', encoding='utf-8', newline='') as users_csv:\n reader = csv.reader(users_csv)\n d = {}\n for row in reader:\n userId, profileName = row\n if profileName == 'A Customer':\n continue\n value = d.get(profileName)\n if not value:\n d.setdefault(profileName, userId)\n elif value != userId:\n print(f'{userId}, {value}, {profileName}')\n", "step-3": "import csv\nwith open('./csvs/users.csv', encoding='utf-8', newline='') as users_csv:\n reader = csv.reader(users_csv)\n d = {}\n for row in reader:\n userId, profileName = row\n if profileName == 'A Customer':\n continue\n value = d.get(profileName)\n if not value:\n d.setdefault(profileName, userId)\n elif value != userId:\n print(f'{userId}, {value}, {profileName}')\n", "step-4": "import csv\n\nwith open('./csvs/users.csv', encoding='utf-8', newline='') as users_csv:\n reader = csv.reader(users_csv)\n d = {}\n for row in reader:\n userId, profileName = row\n if profileName == 'A Customer':\n continue\n value = d.get(profileName)\n if not value:\n d.setdefault(profileName, userId)\n else:\n if value != userId:\n print(f'{userId}, {value}, {profileName}')", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
# coding: utf-8 import logging def __gen_logger(): result = logging.getLogger('superslick') return result logger = __gen_logger()
normal
{ "blob_id": "cee9deeeabfec46ee5c132704e8fd653e55987f3", "index": 3430, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef __gen_logger():\n result = logging.getLogger('superslick')\n return result\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef __gen_logger():\n result = logging.getLogger('superslick')\n return result\n\n\nlogger = __gen_logger()\n", "step-4": "import logging\n\n\ndef __gen_logger():\n result = logging.getLogger('superslick')\n return result\n\n\nlogger = __gen_logger()\n", "step-5": "# coding: utf-8\n\nimport logging\n\ndef __gen_logger():\n result = logging.getLogger('superslick')\n return result\n\nlogger = __gen_logger()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
""" stanCode Breakout Project Adapted from Eric Roberts's Breakout by Sonja Johnson-Yu, Kylie Jue, Nick Bowman, and Jerry Liao YOUR DESCRIPTION HERE """ from campy.gui.events.timer import pause from breakoutgraphics import BreakoutGraphics FRAME_RATE = 1000 / 120 # 120 frames per second. NUM_LIVES = 3 def main(): graphics = BreakoutGraphics() lives = NUM_LIVES # 生命 graphics.window.add(graphics.scoreboard, 0, graphics.window_height) # 計分板 # Add animation loop here! while True: pause(FRAME_RATE) if graphics.ball_fall_down(): lives -= 1 if lives > 0: graphics.reset_ball() else: graphics.game_over() break if graphics.you_win(): break vx = graphics.getx() vy = graphics.gety() graphics.ball.move(vx, vy) graphics.boundary() graphics.collision() if __name__ == '__main__': main()
normal
{ "blob_id": "b218f5e401510f844006cb6079737b54aa86827b", "index": 2194, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n graphics = BreakoutGraphics()\n lives = NUM_LIVES\n graphics.window.add(graphics.scoreboard, 0, graphics.window_height)\n while True:\n pause(FRAME_RATE)\n if graphics.ball_fall_down():\n lives -= 1\n if lives > 0:\n graphics.reset_ball()\n else:\n graphics.game_over()\n break\n if graphics.you_win():\n break\n vx = graphics.getx()\n vy = graphics.gety()\n graphics.ball.move(vx, vy)\n graphics.boundary()\n graphics.collision()\n\n\nif __name__ == '__main__':\n main()\n", "step-3": "<mask token>\nFRAME_RATE = 1000 / 120\nNUM_LIVES = 3\n\n\ndef main():\n graphics = BreakoutGraphics()\n lives = NUM_LIVES\n graphics.window.add(graphics.scoreboard, 0, graphics.window_height)\n while True:\n pause(FRAME_RATE)\n if graphics.ball_fall_down():\n lives -= 1\n if lives > 0:\n graphics.reset_ball()\n else:\n graphics.game_over()\n break\n if graphics.you_win():\n break\n vx = graphics.getx()\n vy = graphics.gety()\n graphics.ball.move(vx, vy)\n graphics.boundary()\n graphics.collision()\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "<mask token>\nfrom campy.gui.events.timer import pause\nfrom breakoutgraphics import BreakoutGraphics\nFRAME_RATE = 1000 / 120\nNUM_LIVES = 3\n\n\ndef main():\n graphics = BreakoutGraphics()\n lives = NUM_LIVES\n graphics.window.add(graphics.scoreboard, 0, graphics.window_height)\n while True:\n pause(FRAME_RATE)\n if graphics.ball_fall_down():\n lives -= 1\n if lives > 0:\n graphics.reset_ball()\n else:\n graphics.game_over()\n break\n if graphics.you_win():\n break\n vx = graphics.getx()\n vy = graphics.gety()\n graphics.ball.move(vx, vy)\n graphics.boundary()\n graphics.collision()\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "\"\"\"\nstanCode Breakout Project\nAdapted from Eric Roberts's Breakout by\nSonja Johnson-Yu, Kylie Jue, Nick Bowman,\nand Jerry Liao\n\nYOUR DESCRIPTION HERE\n\"\"\"\n\nfrom campy.gui.events.timer import pause\nfrom breakoutgraphics import BreakoutGraphics\n\nFRAME_RATE = 1000 / 120 # 120 frames per second.\nNUM_LIVES = 3\n\n\ndef main():\n graphics = BreakoutGraphics()\n lives = NUM_LIVES # 生命\n\n graphics.window.add(graphics.scoreboard, 0, graphics.window_height) # 計分板\n\n # Add animation loop here!\n while True:\n pause(FRAME_RATE)\n if graphics.ball_fall_down():\n lives -= 1\n if lives > 0:\n graphics.reset_ball()\n else:\n graphics.game_over()\n break\n if graphics.you_win():\n break\n vx = graphics.getx()\n vy = graphics.gety()\n graphics.ball.move(vx, vy)\n graphics.boundary()\n graphics.collision()\n\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
from ..core.helpers import itemize from ..core.files import backendRep, expandDir, prefixSlash, normpath from .helpers import splitModRef from .repo import checkoutRepo from .links import provenanceLink # GET DATA FOR MAIN SOURCE AND ALL MODULES class AppData: def __init__( self, app, backend, moduleRefs, locations, modules, version, checkout, silent ): """Collects TF data according to specifications. The specifications are passed as arguments when the object is initialized. Parameters ---------- backend: string `github` or `gitlab` or a GitLab instance such as `gitlab.huc.knaw.nl`. app: obj The high-level API object moduleRefs: tuple Each member consists of a module ref, which is a tuple of information that defines a module. locations: string|tuple One or more directory paths. They will be combined with the `modules` argument and used as locations to search for TF data files. modules: string|tuple One or more directory path segments. They will be appended to the paths given by the `locations` argument to form search locations for TF data files. version: string The version of TF data that should be retrievend. Version is a directory level just below the search locations. checkout: string A specifier to use a specific release or commit of a data repository. silent: string, optional tf.core.timestamp.SILENT_D See `tf.core.timestamp.Timestamp` """ self.backend = backend self.app = app self.moduleRefs = ( [] if moduleRefs is None else moduleRefs.split(",") if type(moduleRefs) is str else list(moduleRefs) ) self.locationsArg = locations self.modulesArg = modules self.version = version self.checkout = checkout self.silent = silent def getMain(self): """Get the main data of the corpus. This is specified by the `org`, `repo` and `relative` settings under `provenanceSpec` in `config.yaml`. See Also -------- tf.advanced.settings: options allowed in `config.yaml` """ app = self.app checkout = self.checkout aContext = app.context org = aContext.org repo = aContext.repo relative = prefixSlash(aContext.relative) appPath = aContext.appPath appName = aContext.appName if appName.startswith("app:"): appParent = appPath.rsplit("/", 1)[0] relative = f"{appParent}{relative}" elif org is None or repo is None: appPathRep = f"{appPath}/" if appPath else "" relative = f"{appPathRep}{appName}" self.checkout = "local" if not self.getModule(org, repo, prefixSlash(relative), checkout, isBase=True): self.good = False def getStandard(self): """Get the data of the standard modules specified by the settings of the corpus. These are specified in the `moduleSpecs` setting under `provenanceSpecs` in `config.yaml`. They will be loaded *after* the extra modules specified in the **mod** parameter, and only in as far they have not been specifief in the **mod** parameter. In this way you can pass overriding checkout specifiers to the standard modules. See Also -------- tf.advanced.settings: options allowed in `config.yaml` """ app = self.app loadData = app.loadData if not loadData or loadData == "core": return aContext = app.context moduleSpecs = aContext.moduleSpecs seen = self.seen checkout = self.checkout backend = self.backend for m in moduleSpecs or []: org = m["org"] repo = m["repo"] relative = m["relative"] theCheckout = m.get("checkout", checkout) theBackend = m.get("backend", backend) bRep = backendRep(theBackend, "spec", default=backend) ref = f"{bRep}{org}/{repo}{relative}" if ref in seen: continue if not self.getModule( org, repo, relative, theCheckout, backend=theBackend, specs=m, ): self.good = False def getRefs(self): """Get data from additional modules. These are specified in the `moduleRefs` parameter of `AppData`. We store the set of special modules in order to skip them later when we are loading the standard modules. """ backend = self.backend refs = self.moduleRefs for ref in refs: refPure = ref.rsplit(":", 1)[0] if refPure in self.seen: continue parts = splitModRef(ref) if not parts: self.good = False continue parts[2] = prefixSlash(normpath(parts[2])) # the relative bit theBackend = ( None if parts[-1] is None or parts[-1] == backend else parts[-1] ) if not self.getModule(*parts[0:-1], backend=theBackend): self.good = False def getModules(self): """Get data from additional local directories. These are specified in the `locations` and `modules` parameters of `AppData`. """ self.provenance = [] provenance = self.provenance self.mLocations = [] mLocations = self.mLocations self.locations = None self.modules = None self.good = True self.seen = set() self.getMain() self.getRefs() self.getStandard() version = self.version good = self.good app = self.app if good: app.mLocations = mLocations app.provenance = provenance else: return mModules = [] if mLocations: mModules.append(version or "") locations = self.locationsArg modules = self.modulesArg givenLocations = ( [] if locations is None else [expandDir(app, x.strip()) for x in itemize(locations, "\n")] if type(locations) is str else [str(x) for x in locations] ) givenModules = ( [] if modules is None else [normpath(x.strip()) for x in itemize(modules, "\n")] if type(modules) is str else [normpath(str(x)) for x in modules] ) self.locations = mLocations + givenLocations self.modules = mModules + givenModules def getModule( self, org, repo, relative, checkout, backend=None, isBase=False, specs=None ): """Prepare to load a single module. Eventually, all TF data will be downloaded from local directories, bases on a list of location paths and module paths. This function computes the contribution of a single module to both the location paths and the module paths. Parameters ---------- org: string GitHub organization or GitLab group of the module repo: string: GitHub repository or GitLab project of the module relative: string Path within the repository of the module checkout: string A specifier to use a specific release or commit of a data repository. backend: string The backend if different from the backend of the main module isBase: boolean, optional False Whether this module is the main data of the corpus. specs: dict, optional False Additional informational attributes of the module, e.g. a DOI """ backend = self.backend if backend is None else backendRep(backend, "norm") bRep = backendRep(backend, "spec", default=self.backend) version = self.version silent = self.silent mLocations = self.mLocations provenance = self.provenance seen = self.seen app = self.app _browse = app._browse aContext = app.context branch = aContext.provenanceSpec["branch"] relative = prefixSlash(normpath(relative)) moduleRef = f"{bRep}{org}/{repo}{relative}" if moduleRef in self.seen: return True if org is None or repo is None: relativeBare = relative.removeprefix("/") repoLocation = relativeBare mLocations.append(relativeBare) (commit, local, release) = (None, None, None) else: (commit, release, local, localBase, localDir) = checkoutRepo( backend, _browse=_browse, org=org, repo=repo, folder=relative, version=version, checkout=checkout, withPaths=False, keep=False, silent=silent, ) if not localBase: return False repoLocation = f"{localBase}/{org}/{repo}" mLocations.append(f"{localBase}/{localDir}") seen.add(moduleRef) if isBase: app.repoLocation = repoLocation info = {} for item in ( ("doi", None), ("corpus", f"{org}/{repo}{relative}"), ): (key, default) = item info[key] = ( getattr(aContext, key) if isBase else specs[key] if specs and key in specs else default ) provenance.append( ( ("corpus", info["corpus"]), ("version", version), ("commit", commit or "??"), ("release", release or "none"), ( "live", provenanceLink( backend, org, repo, version, branch, commit, local, release, relative ), ), ("doi", info["doi"]), ) ) return True def getModulesData(*args): """Retrieve all data for a corpus. Parameters ---------- args: list All parameters needed to retrieve all associated data. They are the same as are needed to construct an `AppData` object. """ mData = AppData(*args) mData.getModules() if not mData.good or mData.locations is None: return None return (mData.locations, mData.modules)
normal
{ "blob_id": "7be54b2bd99680beed3e8e9cb14225756a71a4ea", "index": 1135, "step-1": "<mask token>\n\n\nclass AppData:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass AppData:\n\n def __init__(self, app, backend, moduleRefs, locations, modules,\n version, checkout, silent):\n \"\"\"Collects TF data according to specifications.\n\n The specifications are passed as arguments when the object is initialized.\n\n Parameters\n ----------\n backend: string\n `github` or `gitlab` or a GitLab instance such as `gitlab.huc.knaw.nl`.\n app: obj\n The high-level API object\n moduleRefs: tuple\n Each member consists of a module ref, which is a tuple of information\n that defines a module.\n locations: string|tuple\n One or more directory paths. They will be combined with the `modules`\n argument and used as locations to search for TF data files.\n modules: string|tuple\n One or more directory path segments. They will be appended to the\n paths given by the `locations` argument to form search locations\n for TF data files.\n version: string\n The version of TF data that should be retrievend. Version is a directory\n level just below the search locations.\n checkout: string\n A specifier to use a specific release or commit of a data repository.\n silent: string, optional tf.core.timestamp.SILENT_D\n See `tf.core.timestamp.Timestamp`\n\n \"\"\"\n self.backend = backend\n self.app = app\n self.moduleRefs = [] if moduleRefs is None else moduleRefs.split(','\n ) if type(moduleRefs) is str else list(moduleRefs)\n self.locationsArg = locations\n self.modulesArg = modules\n self.version = version\n self.checkout = checkout\n self.silent = silent\n\n def getMain(self):\n \"\"\"Get the main data of the corpus.\n\n This is specified by the `org`, `repo` and `relative` settings under\n `provenanceSpec` in `config.yaml`.\n\n See Also\n --------\n tf.advanced.settings: options allowed in `config.yaml`\n \"\"\"\n app = self.app\n checkout = self.checkout\n aContext = app.context\n org = aContext.org\n repo = aContext.repo\n relative = prefixSlash(aContext.relative)\n appPath = aContext.appPath\n appName = aContext.appName\n if appName.startswith('app:'):\n appParent = appPath.rsplit('/', 1)[0]\n relative = f'{appParent}{relative}'\n elif org is None or repo is None:\n appPathRep = f'{appPath}/' if appPath else ''\n relative = f'{appPathRep}{appName}'\n self.checkout = 'local'\n if not self.getModule(org, repo, prefixSlash(relative), checkout,\n isBase=True):\n self.good = False\n <mask token>\n\n def getRefs(self):\n \"\"\"Get data from additional modules.\n\n These are specified in the `moduleRefs` parameter of `AppData`.\n We store the set of special modules in order to skip them\n later when we are loading the standard modules.\n \"\"\"\n backend = self.backend\n refs = self.moduleRefs\n for ref in refs:\n refPure = ref.rsplit(':', 1)[0]\n if refPure in self.seen:\n continue\n parts = splitModRef(ref)\n if not parts:\n self.good = False\n continue\n parts[2] = prefixSlash(normpath(parts[2]))\n theBackend = None if parts[-1] is None or parts[-1\n ] == backend else parts[-1]\n if not self.getModule(*parts[0:-1], backend=theBackend):\n self.good = False\n\n def getModules(self):\n \"\"\"Get data from additional local directories.\n\n These are specified in the `locations` and `modules` parameters of `AppData`.\n \"\"\"\n self.provenance = []\n provenance = self.provenance\n self.mLocations = []\n mLocations = self.mLocations\n self.locations = None\n self.modules = None\n self.good = True\n self.seen = set()\n self.getMain()\n self.getRefs()\n self.getStandard()\n version = self.version\n good = self.good\n app = self.app\n if good:\n app.mLocations = mLocations\n app.provenance = provenance\n else:\n return\n mModules = []\n if mLocations:\n mModules.append(version or '')\n locations = self.locationsArg\n modules = self.modulesArg\n givenLocations = [] if locations is None else [expandDir(app, x.\n strip()) for x in itemize(locations, '\\n')] if type(locations\n ) is str else [str(x) for x in locations]\n givenModules = [] if modules is None else [normpath(x.strip()) for\n x in itemize(modules, '\\n')] if type(modules) is str else [normpath\n (str(x)) for x in modules]\n self.locations = mLocations + givenLocations\n self.modules = mModules + givenModules\n <mask token>\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass AppData:\n\n def __init__(self, app, backend, moduleRefs, locations, modules,\n version, checkout, silent):\n \"\"\"Collects TF data according to specifications.\n\n The specifications are passed as arguments when the object is initialized.\n\n Parameters\n ----------\n backend: string\n `github` or `gitlab` or a GitLab instance such as `gitlab.huc.knaw.nl`.\n app: obj\n The high-level API object\n moduleRefs: tuple\n Each member consists of a module ref, which is a tuple of information\n that defines a module.\n locations: string|tuple\n One or more directory paths. They will be combined with the `modules`\n argument and used as locations to search for TF data files.\n modules: string|tuple\n One or more directory path segments. They will be appended to the\n paths given by the `locations` argument to form search locations\n for TF data files.\n version: string\n The version of TF data that should be retrievend. Version is a directory\n level just below the search locations.\n checkout: string\n A specifier to use a specific release or commit of a data repository.\n silent: string, optional tf.core.timestamp.SILENT_D\n See `tf.core.timestamp.Timestamp`\n\n \"\"\"\n self.backend = backend\n self.app = app\n self.moduleRefs = [] if moduleRefs is None else moduleRefs.split(','\n ) if type(moduleRefs) is str else list(moduleRefs)\n self.locationsArg = locations\n self.modulesArg = modules\n self.version = version\n self.checkout = checkout\n self.silent = silent\n\n def getMain(self):\n \"\"\"Get the main data of the corpus.\n\n This is specified by the `org`, `repo` and `relative` settings under\n `provenanceSpec` in `config.yaml`.\n\n See Also\n --------\n tf.advanced.settings: options allowed in `config.yaml`\n \"\"\"\n app = self.app\n checkout = self.checkout\n aContext = app.context\n org = aContext.org\n repo = aContext.repo\n relative = prefixSlash(aContext.relative)\n appPath = aContext.appPath\n appName = aContext.appName\n if appName.startswith('app:'):\n appParent = appPath.rsplit('/', 1)[0]\n relative = f'{appParent}{relative}'\n elif org is None or repo is None:\n appPathRep = f'{appPath}/' if appPath else ''\n relative = f'{appPathRep}{appName}'\n self.checkout = 'local'\n if not self.getModule(org, repo, prefixSlash(relative), checkout,\n isBase=True):\n self.good = False\n\n def getStandard(self):\n \"\"\"Get the data of the standard modules specified by the settings of the corpus.\n\n These are specified in the `moduleSpecs` setting under\n `provenanceSpecs` in `config.yaml`.\n\n They will be loaded *after* the extra modules specified in the **mod**\n parameter, and only in as far they have not been specifief in the\n **mod** parameter. In this way you can pass overriding\n checkout specifiers to the standard modules.\n\n See Also\n --------\n tf.advanced.settings: options allowed in `config.yaml`\n \"\"\"\n app = self.app\n loadData = app.loadData\n if not loadData or loadData == 'core':\n return\n aContext = app.context\n moduleSpecs = aContext.moduleSpecs\n seen = self.seen\n checkout = self.checkout\n backend = self.backend\n for m in (moduleSpecs or []):\n org = m['org']\n repo = m['repo']\n relative = m['relative']\n theCheckout = m.get('checkout', checkout)\n theBackend = m.get('backend', backend)\n bRep = backendRep(theBackend, 'spec', default=backend)\n ref = f'{bRep}{org}/{repo}{relative}'\n if ref in seen:\n continue\n if not self.getModule(org, repo, relative, theCheckout, backend\n =theBackend, specs=m):\n self.good = False\n\n def getRefs(self):\n \"\"\"Get data from additional modules.\n\n These are specified in the `moduleRefs` parameter of `AppData`.\n We store the set of special modules in order to skip them\n later when we are loading the standard modules.\n \"\"\"\n backend = self.backend\n refs = self.moduleRefs\n for ref in refs:\n refPure = ref.rsplit(':', 1)[0]\n if refPure in self.seen:\n continue\n parts = splitModRef(ref)\n if not parts:\n self.good = False\n continue\n parts[2] = prefixSlash(normpath(parts[2]))\n theBackend = None if parts[-1] is None or parts[-1\n ] == backend else parts[-1]\n if not self.getModule(*parts[0:-1], backend=theBackend):\n self.good = False\n\n def getModules(self):\n \"\"\"Get data from additional local directories.\n\n These are specified in the `locations` and `modules` parameters of `AppData`.\n \"\"\"\n self.provenance = []\n provenance = self.provenance\n self.mLocations = []\n mLocations = self.mLocations\n self.locations = None\n self.modules = None\n self.good = True\n self.seen = set()\n self.getMain()\n self.getRefs()\n self.getStandard()\n version = self.version\n good = self.good\n app = self.app\n if good:\n app.mLocations = mLocations\n app.provenance = provenance\n else:\n return\n mModules = []\n if mLocations:\n mModules.append(version or '')\n locations = self.locationsArg\n modules = self.modulesArg\n givenLocations = [] if locations is None else [expandDir(app, x.\n strip()) for x in itemize(locations, '\\n')] if type(locations\n ) is str else [str(x) for x in locations]\n givenModules = [] if modules is None else [normpath(x.strip()) for\n x in itemize(modules, '\\n')] if type(modules) is str else [normpath\n (str(x)) for x in modules]\n self.locations = mLocations + givenLocations\n self.modules = mModules + givenModules\n\n def getModule(self, org, repo, relative, checkout, backend=None, isBase\n =False, specs=None):\n \"\"\"Prepare to load a single module.\n\n Eventually, all TF data will be downloaded from local directories, bases\n on a list of location paths and module paths.\n\n This function computes the contribution of a single module to both the\n location paths and the module paths.\n\n Parameters\n ----------\n org: string\n GitHub organization or GitLab group of the module\n repo: string:\n GitHub repository or GitLab project of the module\n relative: string\n Path within the repository of the module\n checkout: string\n A specifier to use a specific release or commit of a data repository.\n backend: string\n The backend if different from the backend of the main module\n isBase: boolean, optional False\n Whether this module is the main data of the corpus.\n specs: dict, optional False\n Additional informational attributes of the module, e.g. a DOI\n \"\"\"\n backend = self.backend if backend is None else backendRep(backend,\n 'norm')\n bRep = backendRep(backend, 'spec', default=self.backend)\n version = self.version\n silent = self.silent\n mLocations = self.mLocations\n provenance = self.provenance\n seen = self.seen\n app = self.app\n _browse = app._browse\n aContext = app.context\n branch = aContext.provenanceSpec['branch']\n relative = prefixSlash(normpath(relative))\n moduleRef = f'{bRep}{org}/{repo}{relative}'\n if moduleRef in self.seen:\n return True\n if org is None or repo is None:\n relativeBare = relative.removeprefix('/')\n repoLocation = relativeBare\n mLocations.append(relativeBare)\n commit, local, release = None, None, None\n else:\n commit, release, local, localBase, localDir = checkoutRepo(backend,\n _browse=_browse, org=org, repo=repo, folder=relative,\n version=version, checkout=checkout, withPaths=False, keep=\n False, silent=silent)\n if not localBase:\n return False\n repoLocation = f'{localBase}/{org}/{repo}'\n mLocations.append(f'{localBase}/{localDir}')\n seen.add(moduleRef)\n if isBase:\n app.repoLocation = repoLocation\n info = {}\n for item in (('doi', None), ('corpus', f'{org}/{repo}{relative}')):\n key, default = item\n info[key] = getattr(aContext, key) if isBase else specs[key\n ] if specs and key in specs else default\n provenance.append((('corpus', info['corpus']), ('version', version),\n ('commit', commit or '??'), ('release', release or 'none'), (\n 'live', provenanceLink(backend, org, repo, version, branch,\n commit, local, release, relative)), ('doi', info['doi'])))\n return True\n\n\ndef getModulesData(*args):\n \"\"\"Retrieve all data for a corpus.\n\n Parameters\n ----------\n args: list\n All parameters needed to retrieve all associated data.\n They are the same as are needed to construct an `AppData` object.\n \"\"\"\n mData = AppData(*args)\n mData.getModules()\n if not mData.good or mData.locations is None:\n return None\n return mData.locations, mData.modules\n", "step-4": "from ..core.helpers import itemize\nfrom ..core.files import backendRep, expandDir, prefixSlash, normpath\nfrom .helpers import splitModRef\nfrom .repo import checkoutRepo\nfrom .links import provenanceLink\n\n\nclass AppData:\n\n def __init__(self, app, backend, moduleRefs, locations, modules,\n version, checkout, silent):\n \"\"\"Collects TF data according to specifications.\n\n The specifications are passed as arguments when the object is initialized.\n\n Parameters\n ----------\n backend: string\n `github` or `gitlab` or a GitLab instance such as `gitlab.huc.knaw.nl`.\n app: obj\n The high-level API object\n moduleRefs: tuple\n Each member consists of a module ref, which is a tuple of information\n that defines a module.\n locations: string|tuple\n One or more directory paths. They will be combined with the `modules`\n argument and used as locations to search for TF data files.\n modules: string|tuple\n One or more directory path segments. They will be appended to the\n paths given by the `locations` argument to form search locations\n for TF data files.\n version: string\n The version of TF data that should be retrievend. Version is a directory\n level just below the search locations.\n checkout: string\n A specifier to use a specific release or commit of a data repository.\n silent: string, optional tf.core.timestamp.SILENT_D\n See `tf.core.timestamp.Timestamp`\n\n \"\"\"\n self.backend = backend\n self.app = app\n self.moduleRefs = [] if moduleRefs is None else moduleRefs.split(','\n ) if type(moduleRefs) is str else list(moduleRefs)\n self.locationsArg = locations\n self.modulesArg = modules\n self.version = version\n self.checkout = checkout\n self.silent = silent\n\n def getMain(self):\n \"\"\"Get the main data of the corpus.\n\n This is specified by the `org`, `repo` and `relative` settings under\n `provenanceSpec` in `config.yaml`.\n\n See Also\n --------\n tf.advanced.settings: options allowed in `config.yaml`\n \"\"\"\n app = self.app\n checkout = self.checkout\n aContext = app.context\n org = aContext.org\n repo = aContext.repo\n relative = prefixSlash(aContext.relative)\n appPath = aContext.appPath\n appName = aContext.appName\n if appName.startswith('app:'):\n appParent = appPath.rsplit('/', 1)[0]\n relative = f'{appParent}{relative}'\n elif org is None or repo is None:\n appPathRep = f'{appPath}/' if appPath else ''\n relative = f'{appPathRep}{appName}'\n self.checkout = 'local'\n if not self.getModule(org, repo, prefixSlash(relative), checkout,\n isBase=True):\n self.good = False\n\n def getStandard(self):\n \"\"\"Get the data of the standard modules specified by the settings of the corpus.\n\n These are specified in the `moduleSpecs` setting under\n `provenanceSpecs` in `config.yaml`.\n\n They will be loaded *after* the extra modules specified in the **mod**\n parameter, and only in as far they have not been specifief in the\n **mod** parameter. In this way you can pass overriding\n checkout specifiers to the standard modules.\n\n See Also\n --------\n tf.advanced.settings: options allowed in `config.yaml`\n \"\"\"\n app = self.app\n loadData = app.loadData\n if not loadData or loadData == 'core':\n return\n aContext = app.context\n moduleSpecs = aContext.moduleSpecs\n seen = self.seen\n checkout = self.checkout\n backend = self.backend\n for m in (moduleSpecs or []):\n org = m['org']\n repo = m['repo']\n relative = m['relative']\n theCheckout = m.get('checkout', checkout)\n theBackend = m.get('backend', backend)\n bRep = backendRep(theBackend, 'spec', default=backend)\n ref = f'{bRep}{org}/{repo}{relative}'\n if ref in seen:\n continue\n if not self.getModule(org, repo, relative, theCheckout, backend\n =theBackend, specs=m):\n self.good = False\n\n def getRefs(self):\n \"\"\"Get data from additional modules.\n\n These are specified in the `moduleRefs` parameter of `AppData`.\n We store the set of special modules in order to skip them\n later when we are loading the standard modules.\n \"\"\"\n backend = self.backend\n refs = self.moduleRefs\n for ref in refs:\n refPure = ref.rsplit(':', 1)[0]\n if refPure in self.seen:\n continue\n parts = splitModRef(ref)\n if not parts:\n self.good = False\n continue\n parts[2] = prefixSlash(normpath(parts[2]))\n theBackend = None if parts[-1] is None or parts[-1\n ] == backend else parts[-1]\n if not self.getModule(*parts[0:-1], backend=theBackend):\n self.good = False\n\n def getModules(self):\n \"\"\"Get data from additional local directories.\n\n These are specified in the `locations` and `modules` parameters of `AppData`.\n \"\"\"\n self.provenance = []\n provenance = self.provenance\n self.mLocations = []\n mLocations = self.mLocations\n self.locations = None\n self.modules = None\n self.good = True\n self.seen = set()\n self.getMain()\n self.getRefs()\n self.getStandard()\n version = self.version\n good = self.good\n app = self.app\n if good:\n app.mLocations = mLocations\n app.provenance = provenance\n else:\n return\n mModules = []\n if mLocations:\n mModules.append(version or '')\n locations = self.locationsArg\n modules = self.modulesArg\n givenLocations = [] if locations is None else [expandDir(app, x.\n strip()) for x in itemize(locations, '\\n')] if type(locations\n ) is str else [str(x) for x in locations]\n givenModules = [] if modules is None else [normpath(x.strip()) for\n x in itemize(modules, '\\n')] if type(modules) is str else [normpath\n (str(x)) for x in modules]\n self.locations = mLocations + givenLocations\n self.modules = mModules + givenModules\n\n def getModule(self, org, repo, relative, checkout, backend=None, isBase\n =False, specs=None):\n \"\"\"Prepare to load a single module.\n\n Eventually, all TF data will be downloaded from local directories, bases\n on a list of location paths and module paths.\n\n This function computes the contribution of a single module to both the\n location paths and the module paths.\n\n Parameters\n ----------\n org: string\n GitHub organization or GitLab group of the module\n repo: string:\n GitHub repository or GitLab project of the module\n relative: string\n Path within the repository of the module\n checkout: string\n A specifier to use a specific release or commit of a data repository.\n backend: string\n The backend if different from the backend of the main module\n isBase: boolean, optional False\n Whether this module is the main data of the corpus.\n specs: dict, optional False\n Additional informational attributes of the module, e.g. a DOI\n \"\"\"\n backend = self.backend if backend is None else backendRep(backend,\n 'norm')\n bRep = backendRep(backend, 'spec', default=self.backend)\n version = self.version\n silent = self.silent\n mLocations = self.mLocations\n provenance = self.provenance\n seen = self.seen\n app = self.app\n _browse = app._browse\n aContext = app.context\n branch = aContext.provenanceSpec['branch']\n relative = prefixSlash(normpath(relative))\n moduleRef = f'{bRep}{org}/{repo}{relative}'\n if moduleRef in self.seen:\n return True\n if org is None or repo is None:\n relativeBare = relative.removeprefix('/')\n repoLocation = relativeBare\n mLocations.append(relativeBare)\n commit, local, release = None, None, None\n else:\n commit, release, local, localBase, localDir = checkoutRepo(backend,\n _browse=_browse, org=org, repo=repo, folder=relative,\n version=version, checkout=checkout, withPaths=False, keep=\n False, silent=silent)\n if not localBase:\n return False\n repoLocation = f'{localBase}/{org}/{repo}'\n mLocations.append(f'{localBase}/{localDir}')\n seen.add(moduleRef)\n if isBase:\n app.repoLocation = repoLocation\n info = {}\n for item in (('doi', None), ('corpus', f'{org}/{repo}{relative}')):\n key, default = item\n info[key] = getattr(aContext, key) if isBase else specs[key\n ] if specs and key in specs else default\n provenance.append((('corpus', info['corpus']), ('version', version),\n ('commit', commit or '??'), ('release', release or 'none'), (\n 'live', provenanceLink(backend, org, repo, version, branch,\n commit, local, release, relative)), ('doi', info['doi'])))\n return True\n\n\ndef getModulesData(*args):\n \"\"\"Retrieve all data for a corpus.\n\n Parameters\n ----------\n args: list\n All parameters needed to retrieve all associated data.\n They are the same as are needed to construct an `AppData` object.\n \"\"\"\n mData = AppData(*args)\n mData.getModules()\n if not mData.good or mData.locations is None:\n return None\n return mData.locations, mData.modules\n", "step-5": "from ..core.helpers import itemize\nfrom ..core.files import backendRep, expandDir, prefixSlash, normpath\nfrom .helpers import splitModRef\nfrom .repo import checkoutRepo\nfrom .links import provenanceLink\n\n\n# GET DATA FOR MAIN SOURCE AND ALL MODULES\n\n\nclass AppData:\n def __init__(\n self, app, backend, moduleRefs, locations, modules, version, checkout, silent\n ):\n \"\"\"Collects TF data according to specifications.\n\n The specifications are passed as arguments when the object is initialized.\n\n Parameters\n ----------\n backend: string\n `github` or `gitlab` or a GitLab instance such as `gitlab.huc.knaw.nl`.\n app: obj\n The high-level API object\n moduleRefs: tuple\n Each member consists of a module ref, which is a tuple of information\n that defines a module.\n locations: string|tuple\n One or more directory paths. They will be combined with the `modules`\n argument and used as locations to search for TF data files.\n modules: string|tuple\n One or more directory path segments. They will be appended to the\n paths given by the `locations` argument to form search locations\n for TF data files.\n version: string\n The version of TF data that should be retrievend. Version is a directory\n level just below the search locations.\n checkout: string\n A specifier to use a specific release or commit of a data repository.\n silent: string, optional tf.core.timestamp.SILENT_D\n See `tf.core.timestamp.Timestamp`\n\n \"\"\"\n self.backend = backend\n self.app = app\n self.moduleRefs = (\n []\n if moduleRefs is None\n else moduleRefs.split(\",\")\n if type(moduleRefs) is str\n else list(moduleRefs)\n )\n self.locationsArg = locations\n self.modulesArg = modules\n self.version = version\n self.checkout = checkout\n self.silent = silent\n\n def getMain(self):\n \"\"\"Get the main data of the corpus.\n\n This is specified by the `org`, `repo` and `relative` settings under\n `provenanceSpec` in `config.yaml`.\n\n See Also\n --------\n tf.advanced.settings: options allowed in `config.yaml`\n \"\"\"\n\n app = self.app\n checkout = self.checkout\n aContext = app.context\n org = aContext.org\n repo = aContext.repo\n relative = prefixSlash(aContext.relative)\n appPath = aContext.appPath\n appName = aContext.appName\n\n if appName.startswith(\"app:\"):\n appParent = appPath.rsplit(\"/\", 1)[0]\n relative = f\"{appParent}{relative}\"\n elif org is None or repo is None:\n appPathRep = f\"{appPath}/\" if appPath else \"\"\n relative = f\"{appPathRep}{appName}\"\n self.checkout = \"local\"\n\n if not self.getModule(org, repo, prefixSlash(relative), checkout, isBase=True):\n self.good = False\n\n def getStandard(self):\n \"\"\"Get the data of the standard modules specified by the settings of the corpus.\n\n These are specified in the `moduleSpecs` setting under\n `provenanceSpecs` in `config.yaml`.\n\n They will be loaded *after* the extra modules specified in the **mod**\n parameter, and only in as far they have not been specifief in the\n **mod** parameter. In this way you can pass overriding\n checkout specifiers to the standard modules.\n\n See Also\n --------\n tf.advanced.settings: options allowed in `config.yaml`\n \"\"\"\n\n app = self.app\n loadData = app.loadData\n\n if not loadData or loadData == \"core\":\n return\n\n aContext = app.context\n moduleSpecs = aContext.moduleSpecs\n seen = self.seen\n checkout = self.checkout\n backend = self.backend\n\n for m in moduleSpecs or []:\n org = m[\"org\"]\n repo = m[\"repo\"]\n relative = m[\"relative\"]\n theCheckout = m.get(\"checkout\", checkout)\n theBackend = m.get(\"backend\", backend)\n bRep = backendRep(theBackend, \"spec\", default=backend)\n\n ref = f\"{bRep}{org}/{repo}{relative}\"\n if ref in seen:\n continue\n\n if not self.getModule(\n org,\n repo,\n relative,\n theCheckout,\n backend=theBackend,\n specs=m,\n ):\n self.good = False\n\n def getRefs(self):\n \"\"\"Get data from additional modules.\n\n These are specified in the `moduleRefs` parameter of `AppData`.\n We store the set of special modules in order to skip them\n later when we are loading the standard modules.\n \"\"\"\n\n backend = self.backend\n refs = self.moduleRefs\n for ref in refs:\n refPure = ref.rsplit(\":\", 1)[0]\n if refPure in self.seen:\n continue\n\n parts = splitModRef(ref)\n if not parts:\n self.good = False\n continue\n\n parts[2] = prefixSlash(normpath(parts[2])) # the relative bit\n theBackend = (\n None if parts[-1] is None or parts[-1] == backend else parts[-1]\n )\n\n if not self.getModule(*parts[0:-1], backend=theBackend):\n self.good = False\n\n def getModules(self):\n \"\"\"Get data from additional local directories.\n\n These are specified in the `locations` and `modules` parameters of `AppData`.\n \"\"\"\n\n self.provenance = []\n provenance = self.provenance\n self.mLocations = []\n mLocations = self.mLocations\n\n self.locations = None\n self.modules = None\n\n self.good = True\n self.seen = set()\n\n self.getMain()\n self.getRefs()\n self.getStandard()\n\n version = self.version\n good = self.good\n app = self.app\n\n if good:\n app.mLocations = mLocations\n app.provenance = provenance\n else:\n return\n\n mModules = []\n if mLocations:\n mModules.append(version or \"\")\n\n locations = self.locationsArg\n modules = self.modulesArg\n\n givenLocations = (\n []\n if locations is None\n else [expandDir(app, x.strip()) for x in itemize(locations, \"\\n\")]\n if type(locations) is str\n else [str(x) for x in locations]\n )\n givenModules = (\n []\n if modules is None\n else [normpath(x.strip()) for x in itemize(modules, \"\\n\")]\n if type(modules) is str\n else [normpath(str(x)) for x in modules]\n )\n\n self.locations = mLocations + givenLocations\n self.modules = mModules + givenModules\n\n def getModule(\n self, org, repo, relative, checkout, backend=None, isBase=False, specs=None\n ):\n \"\"\"Prepare to load a single module.\n\n Eventually, all TF data will be downloaded from local directories, bases\n on a list of location paths and module paths.\n\n This function computes the contribution of a single module to both the\n location paths and the module paths.\n\n Parameters\n ----------\n org: string\n GitHub organization or GitLab group of the module\n repo: string:\n GitHub repository or GitLab project of the module\n relative: string\n Path within the repository of the module\n checkout: string\n A specifier to use a specific release or commit of a data repository.\n backend: string\n The backend if different from the backend of the main module\n isBase: boolean, optional False\n Whether this module is the main data of the corpus.\n specs: dict, optional False\n Additional informational attributes of the module, e.g. a DOI\n \"\"\"\n\n backend = self.backend if backend is None else backendRep(backend, \"norm\")\n bRep = backendRep(backend, \"spec\", default=self.backend)\n version = self.version\n silent = self.silent\n mLocations = self.mLocations\n provenance = self.provenance\n seen = self.seen\n app = self.app\n _browse = app._browse\n aContext = app.context\n branch = aContext.provenanceSpec[\"branch\"]\n\n relative = prefixSlash(normpath(relative))\n\n moduleRef = f\"{bRep}{org}/{repo}{relative}\"\n if moduleRef in self.seen:\n return True\n\n if org is None or repo is None:\n relativeBare = relative.removeprefix(\"/\")\n repoLocation = relativeBare\n mLocations.append(relativeBare)\n (commit, local, release) = (None, None, None)\n else:\n (commit, release, local, localBase, localDir) = checkoutRepo(\n backend,\n _browse=_browse,\n org=org,\n repo=repo,\n folder=relative,\n version=version,\n checkout=checkout,\n withPaths=False,\n keep=False,\n silent=silent,\n )\n if not localBase:\n return False\n\n repoLocation = f\"{localBase}/{org}/{repo}\"\n mLocations.append(f\"{localBase}/{localDir}\")\n\n seen.add(moduleRef)\n if isBase:\n app.repoLocation = repoLocation\n\n info = {}\n for item in (\n (\"doi\", None),\n (\"corpus\", f\"{org}/{repo}{relative}\"),\n ):\n (key, default) = item\n info[key] = (\n getattr(aContext, key)\n if isBase\n else specs[key]\n if specs and key in specs\n else default\n )\n provenance.append(\n (\n (\"corpus\", info[\"corpus\"]),\n (\"version\", version),\n (\"commit\", commit or \"??\"),\n (\"release\", release or \"none\"),\n (\n \"live\",\n provenanceLink(\n backend, org, repo, version, branch, commit, local, release, relative\n ),\n ),\n (\"doi\", info[\"doi\"]),\n )\n )\n return True\n\n\ndef getModulesData(*args):\n \"\"\"Retrieve all data for a corpus.\n\n Parameters\n ----------\n args: list\n All parameters needed to retrieve all associated data.\n They are the same as are needed to construct an `AppData` object.\n \"\"\"\n\n mData = AppData(*args)\n mData.getModules()\n\n if not mData.good or mData.locations is None:\n return None\n\n return (mData.locations, mData.modules)\n", "step-ids": [ 1, 5, 8, 9, 10 ] }
[ 1, 5, 8, 9, 10 ]
import matplotlib.pyplot as plt import numpy as np import scipy.io as scio import estimateGaussian as eg import multivariateGaussian as mvg import visualizeFit as vf import selectThreshold as st plt.ion() # np.set_printoptions(formatter={'float': '{: 0.6f}'.format}) '''第1部分 加载示例数据集''' #先通过一个小数据集进行异常检测 便于可视化 # 数据集包含两个特征 # 一些机器的等待时间和吞吐量 实验目的找出其中可能有异常的机器 print('Visualizing example dataset for outlier detection.') data = scio.loadmat('ex8data1.mat') X = data['X']#训练集样本特征矩阵 Xval = data['Xval'] #验证集样本特征矩阵 yval = data['yval'].flatten() #验证集样本标签 异常/正常 # 可视化样例训练集 plt.figure() plt.scatter(X[:, 0], X[:, 1], c='b', marker='x', s=15, linewidth=1) plt.axis([0, 30, 0, 30]) plt.xlabel('Latency (ms)') #x1等待时间 plt.ylabel('Throughput (mb/s') #x2吞吐量 input('Program paused. Press ENTER to continue') '''第2部分 估计训练集的分布''' # 假设数据集的各个特征服从高斯分布 print('Visualizing Gaussian fit.') # 参数估计 mu, sigma2 = eg.estimate_gaussian(X) # 计算训练集的概率分布 p = mvg.multivariate_gaussian(X, mu, sigma2) #可视化训练集的概率分布 画出等高线图 vf.visualize_fit(X, mu, sigma2) plt.xlabel('Latency (ms)') plt.ylabel('Throughput (mb/s') input('Program paused. Press ENTER to continue') '''第3部分 基于验证集 得到一个最好的概率分布阈值''' pval = mvg.multivariate_gaussian(Xval, mu, sigma2) #根据训练集的概率分布 得到验证集样本的概率 epsilon, f1 = st.select_threshold(yval, pval) #选择合适的概率阈值 print('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon)) print('Best F1 on Cross Validation Set: {:0.6f}'.format(f1)) print('(you should see a value epsilon of about 8.99e-05 and F1 of about 0.875)') # 标出训练集中的异常值 outliers = np.where(p < epsilon) plt.scatter(X[outliers, 0], X[outliers, 1], marker='o', facecolors='none', edgecolors='r') input('Program paused. Press ENTER to continue') '''第4部分 基于大数据集 进行异常检测(特征数很多)''' data = scio.loadmat('ex8data2.mat') X = data['X'] #训练集样本特征矩阵 Xval = data['Xval'] #验证集样本特征矩阵 yval = data['yval'].flatten() #验证集样本标签 1异常 0正常 #参数估计 mu, sigma2 = eg.estimate_gaussian(X) # 计算训练集的概率分布 p = mvg.multivariate_gaussian(X, mu, sigma2) # 得到验证集每个样本的概率 pval = mvg.multivariate_gaussian(Xval, mu, sigma2) # 选择一个最好的阈值 epsilon, f1 = st.select_threshold(yval, pval) #验证程序正确性 print('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon)) print('Best F1 on Cross Validation Set: {:0.6f}'.format(f1)) print('# Outliers found: {}'.format(np.sum(np.less(p, epsilon)))) #训练集上的异常样本数量 print('(you should see a value epsilon of about 1.38e-18, F1 of about 0.615, and 117 outliers)') input('ex8 Finished. Press ENTER to exit')
normal
{ "blob_id": "de6b9961e0572338c87802314e7ae3cded5168b4", "index": 487, "step-1": "<mask token>\n", "step-2": "<mask token>\nplt.ion()\n<mask token>\nprint('Visualizing example dataset for outlier detection.')\n<mask token>\nplt.figure()\nplt.scatter(X[:, 0], X[:, 1], c='b', marker='x', s=15, linewidth=1)\nplt.axis([0, 30, 0, 30])\nplt.xlabel('Latency (ms)')\nplt.ylabel('Throughput (mb/s')\ninput('Program paused. Press ENTER to continue')\n<mask token>\nprint('Visualizing Gaussian fit.')\n<mask token>\nvf.visualize_fit(X, mu, sigma2)\nplt.xlabel('Latency (ms)')\nplt.ylabel('Throughput (mb/s')\ninput('Program paused. Press ENTER to continue')\n<mask token>\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint(\n '(you should see a value epsilon of about 8.99e-05 and F1 of about 0.875)')\n<mask token>\nplt.scatter(X[outliers, 0], X[outliers, 1], marker='o', facecolors='none',\n edgecolors='r')\ninput('Program paused. Press ENTER to continue')\n<mask token>\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint('# Outliers found: {}'.format(np.sum(np.less(p, epsilon))))\nprint(\n '(you should see a value epsilon of about 1.38e-18, F1 of about 0.615, and 117 outliers)'\n )\ninput('ex8 Finished. Press ENTER to exit')\n", "step-3": "<mask token>\nplt.ion()\n<mask token>\nprint('Visualizing example dataset for outlier detection.')\ndata = scio.loadmat('ex8data1.mat')\nX = data['X']\nXval = data['Xval']\nyval = data['yval'].flatten()\nplt.figure()\nplt.scatter(X[:, 0], X[:, 1], c='b', marker='x', s=15, linewidth=1)\nplt.axis([0, 30, 0, 30])\nplt.xlabel('Latency (ms)')\nplt.ylabel('Throughput (mb/s')\ninput('Program paused. Press ENTER to continue')\n<mask token>\nprint('Visualizing Gaussian fit.')\nmu, sigma2 = eg.estimate_gaussian(X)\np = mvg.multivariate_gaussian(X, mu, sigma2)\nvf.visualize_fit(X, mu, sigma2)\nplt.xlabel('Latency (ms)')\nplt.ylabel('Throughput (mb/s')\ninput('Program paused. Press ENTER to continue')\n<mask token>\npval = mvg.multivariate_gaussian(Xval, mu, sigma2)\nepsilon, f1 = st.select_threshold(yval, pval)\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint(\n '(you should see a value epsilon of about 8.99e-05 and F1 of about 0.875)')\noutliers = np.where(p < epsilon)\nplt.scatter(X[outliers, 0], X[outliers, 1], marker='o', facecolors='none',\n edgecolors='r')\ninput('Program paused. Press ENTER to continue')\n<mask token>\ndata = scio.loadmat('ex8data2.mat')\nX = data['X']\nXval = data['Xval']\nyval = data['yval'].flatten()\nmu, sigma2 = eg.estimate_gaussian(X)\np = mvg.multivariate_gaussian(X, mu, sigma2)\npval = mvg.multivariate_gaussian(Xval, mu, sigma2)\nepsilon, f1 = st.select_threshold(yval, pval)\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint('# Outliers found: {}'.format(np.sum(np.less(p, epsilon))))\nprint(\n '(you should see a value epsilon of about 1.38e-18, F1 of about 0.615, and 117 outliers)'\n )\ninput('ex8 Finished. Press ENTER to exit')\n", "step-4": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as scio\nimport estimateGaussian as eg\nimport multivariateGaussian as mvg\nimport visualizeFit as vf\nimport selectThreshold as st\nplt.ion()\n<mask token>\nprint('Visualizing example dataset for outlier detection.')\ndata = scio.loadmat('ex8data1.mat')\nX = data['X']\nXval = data['Xval']\nyval = data['yval'].flatten()\nplt.figure()\nplt.scatter(X[:, 0], X[:, 1], c='b', marker='x', s=15, linewidth=1)\nplt.axis([0, 30, 0, 30])\nplt.xlabel('Latency (ms)')\nplt.ylabel('Throughput (mb/s')\ninput('Program paused. Press ENTER to continue')\n<mask token>\nprint('Visualizing Gaussian fit.')\nmu, sigma2 = eg.estimate_gaussian(X)\np = mvg.multivariate_gaussian(X, mu, sigma2)\nvf.visualize_fit(X, mu, sigma2)\nplt.xlabel('Latency (ms)')\nplt.ylabel('Throughput (mb/s')\ninput('Program paused. Press ENTER to continue')\n<mask token>\npval = mvg.multivariate_gaussian(Xval, mu, sigma2)\nepsilon, f1 = st.select_threshold(yval, pval)\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint(\n '(you should see a value epsilon of about 8.99e-05 and F1 of about 0.875)')\noutliers = np.where(p < epsilon)\nplt.scatter(X[outliers, 0], X[outliers, 1], marker='o', facecolors='none',\n edgecolors='r')\ninput('Program paused. Press ENTER to continue')\n<mask token>\ndata = scio.loadmat('ex8data2.mat')\nX = data['X']\nXval = data['Xval']\nyval = data['yval'].flatten()\nmu, sigma2 = eg.estimate_gaussian(X)\np = mvg.multivariate_gaussian(X, mu, sigma2)\npval = mvg.multivariate_gaussian(Xval, mu, sigma2)\nepsilon, f1 = st.select_threshold(yval, pval)\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint('# Outliers found: {}'.format(np.sum(np.less(p, epsilon))))\nprint(\n '(you should see a value epsilon of about 1.38e-18, F1 of about 0.615, and 117 outliers)'\n )\ninput('ex8 Finished. Press ENTER to exit')\n", "step-5": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as scio\n\nimport estimateGaussian as eg\nimport multivariateGaussian as mvg\nimport visualizeFit as vf\nimport selectThreshold as st\n\nplt.ion()\n# np.set_printoptions(formatter={'float': '{: 0.6f}'.format})\n\n'''第1部分 加载示例数据集'''\n\n#先通过一个小数据集进行异常检测 便于可视化\n\n# 数据集包含两个特征 \n# 一些机器的等待时间和吞吐量 实验目的找出其中可能有异常的机器\n\n\nprint('Visualizing example dataset for outlier detection.')\n\n\ndata = scio.loadmat('ex8data1.mat')\nX = data['X']#训练集样本特征矩阵\nXval = data['Xval'] #验证集样本特征矩阵\nyval = data['yval'].flatten() #验证集样本标签 异常/正常 \n\n# 可视化样例训练集\nplt.figure()\nplt.scatter(X[:, 0], X[:, 1], c='b', marker='x', s=15, linewidth=1)\nplt.axis([0, 30, 0, 30])\nplt.xlabel('Latency (ms)') #x1等待时间\nplt.ylabel('Throughput (mb/s') #x2吞吐量\n\n\ninput('Program paused. Press ENTER to continue')\n\n'''第2部分 估计训练集的分布'''\n# 假设数据集的各个特征服从高斯分布\n\nprint('Visualizing Gaussian fit.')\n\n# 参数估计 \nmu, sigma2 = eg.estimate_gaussian(X)\n\n# 计算训练集的概率分布\np = mvg.multivariate_gaussian(X, mu, sigma2)\n#可视化训练集的概率分布 画出等高线图\nvf.visualize_fit(X, mu, sigma2)\nplt.xlabel('Latency (ms)')\nplt.ylabel('Throughput (mb/s')\n\ninput('Program paused. Press ENTER to continue')\n\n'''第3部分 基于验证集 得到一个最好的概率分布阈值'''\npval = mvg.multivariate_gaussian(Xval, mu, sigma2) #根据训练集的概率分布 得到验证集样本的概率\n\nepsilon, f1 = st.select_threshold(yval, pval) #选择合适的概率阈值\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint('(you should see a value epsilon of about 8.99e-05 and F1 of about 0.875)')\n\n# 标出训练集中的异常值\noutliers = np.where(p < epsilon)\nplt.scatter(X[outliers, 0], X[outliers, 1], marker='o', facecolors='none', edgecolors='r')\n\ninput('Program paused. Press ENTER to continue')\n\n\n'''第4部分 基于大数据集 进行异常检测(特征数很多)'''\ndata = scio.loadmat('ex8data2.mat')\nX = data['X'] #训练集样本特征矩阵\nXval = data['Xval'] #验证集样本特征矩阵\nyval = data['yval'].flatten() #验证集样本标签 1异常 0正常\n\n#参数估计\nmu, sigma2 = eg.estimate_gaussian(X)\n\n# 计算训练集的概率分布\np = mvg.multivariate_gaussian(X, mu, sigma2)\n\n# 得到验证集每个样本的概率\npval = mvg.multivariate_gaussian(Xval, mu, sigma2)\n\n# 选择一个最好的阈值\nepsilon, f1 = st.select_threshold(yval, pval)\n\n#验证程序正确性\nprint('Best epsilon found using cross-validation: {:0.4e}'.format(epsilon))\nprint('Best F1 on Cross Validation Set: {:0.6f}'.format(f1))\nprint('# Outliers found: {}'.format(np.sum(np.less(p, epsilon)))) #训练集上的异常样本数量\nprint('(you should see a value epsilon of about 1.38e-18, F1 of about 0.615, and 117 outliers)')\n\ninput('ex8 Finished. Press ENTER to exit')\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> app.config.from_pyfile('config.py', silent=True) <|reserved_special_token_0|> app.register_blueprint(static_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(cart_blueprint) app.register_blueprint(product_blueprint) app.register_blueprint(account_blueprint) app.register_blueprint(category_blueprint) app.register_blueprint(order_blueprint) <|reserved_special_token_0|> try: AccountUser.query.first() except Exception as e: db.create_all() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile('config.py', silent=True) db = SQLAlchemy(app) <|reserved_special_token_0|> app.register_blueprint(static_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(cart_blueprint) app.register_blueprint(product_blueprint) app.register_blueprint(account_blueprint) app.register_blueprint(category_blueprint) app.register_blueprint(order_blueprint) <|reserved_special_token_0|> try: AccountUser.query.first() except Exception as e: db.create_all() user_datastore = SQLAlchemySessionUserDatastore(db.session, AccountUser, AccountRole) security = Security(app, user_datastore, register_form=RegistrationForm, login_form=LoginForm) <|reserved_special_token_1|> from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_security import SQLAlchemySessionUserDatastore, Security app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile('config.py', silent=True) db = SQLAlchemy(app) from .blueprints.cart.views import cart_blueprint from .blueprints.admin.views import admin_blueprint from .blueprints.products.views import product_blueprint from .blueprints.orders.views import order_blueprint from .blueprints.account.views import account_blueprint from .blueprints.categories.views import category_blueprint from .blueprints.static_pages.views import static_blueprint app.register_blueprint(static_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(cart_blueprint) app.register_blueprint(product_blueprint) app.register_blueprint(account_blueprint) app.register_blueprint(category_blueprint) app.register_blueprint(order_blueprint) from .blueprints.account.models import AccountUser, AccountRole from .blueprints.account.forms import RegistrationForm, LoginForm try: AccountUser.query.first() except Exception as e: db.create_all() user_datastore = SQLAlchemySessionUserDatastore(db.session, AccountUser, AccountRole) security = Security(app, user_datastore, register_form=RegistrationForm, login_form=LoginForm) <|reserved_special_token_1|> from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_security import SQLAlchemySessionUserDatastore, Security app = Flask(__name__, instance_relative_config=True) app.config.from_pyfile("config.py", silent=True) db = SQLAlchemy(app) from .blueprints.cart.views import cart_blueprint from .blueprints.admin.views import admin_blueprint from .blueprints.products.views import product_blueprint from .blueprints.orders.views import order_blueprint from .blueprints.account.views import account_blueprint from .blueprints.categories.views import category_blueprint from .blueprints.static_pages.views import static_blueprint app.register_blueprint(static_blueprint) app.register_blueprint(admin_blueprint) app.register_blueprint(cart_blueprint) app.register_blueprint(product_blueprint) app.register_blueprint(account_blueprint) app.register_blueprint(category_blueprint) app.register_blueprint(order_blueprint) from .blueprints.account.models import AccountUser, AccountRole from .blueprints.account.forms import RegistrationForm, LoginForm try: AccountUser.query.first() except Exception as e: db.create_all() user_datastore = SQLAlchemySessionUserDatastore(db.session, AccountUser, AccountRole) security = Security( app, user_datastore, register_form=RegistrationForm, login_form=LoginForm )
flexible
{ "blob_id": "5d97a2afed26ec4826c8bce30c84863d21f86001", "index": 9370, "step-1": "<mask token>\n", "step-2": "<mask token>\napp.config.from_pyfile('config.py', silent=True)\n<mask token>\napp.register_blueprint(static_blueprint)\napp.register_blueprint(admin_blueprint)\napp.register_blueprint(cart_blueprint)\napp.register_blueprint(product_blueprint)\napp.register_blueprint(account_blueprint)\napp.register_blueprint(category_blueprint)\napp.register_blueprint(order_blueprint)\n<mask token>\ntry:\n AccountUser.query.first()\nexcept Exception as e:\n db.create_all()\n<mask token>\n", "step-3": "<mask token>\napp = Flask(__name__, instance_relative_config=True)\napp.config.from_pyfile('config.py', silent=True)\ndb = SQLAlchemy(app)\n<mask token>\napp.register_blueprint(static_blueprint)\napp.register_blueprint(admin_blueprint)\napp.register_blueprint(cart_blueprint)\napp.register_blueprint(product_blueprint)\napp.register_blueprint(account_blueprint)\napp.register_blueprint(category_blueprint)\napp.register_blueprint(order_blueprint)\n<mask token>\ntry:\n AccountUser.query.first()\nexcept Exception as e:\n db.create_all()\nuser_datastore = SQLAlchemySessionUserDatastore(db.session, AccountUser,\n AccountRole)\nsecurity = Security(app, user_datastore, register_form=RegistrationForm,\n login_form=LoginForm)\n", "step-4": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_security import SQLAlchemySessionUserDatastore, Security\napp = Flask(__name__, instance_relative_config=True)\napp.config.from_pyfile('config.py', silent=True)\ndb = SQLAlchemy(app)\nfrom .blueprints.cart.views import cart_blueprint\nfrom .blueprints.admin.views import admin_blueprint\nfrom .blueprints.products.views import product_blueprint\nfrom .blueprints.orders.views import order_blueprint\nfrom .blueprints.account.views import account_blueprint\nfrom .blueprints.categories.views import category_blueprint\nfrom .blueprints.static_pages.views import static_blueprint\napp.register_blueprint(static_blueprint)\napp.register_blueprint(admin_blueprint)\napp.register_blueprint(cart_blueprint)\napp.register_blueprint(product_blueprint)\napp.register_blueprint(account_blueprint)\napp.register_blueprint(category_blueprint)\napp.register_blueprint(order_blueprint)\nfrom .blueprints.account.models import AccountUser, AccountRole\nfrom .blueprints.account.forms import RegistrationForm, LoginForm\ntry:\n AccountUser.query.first()\nexcept Exception as e:\n db.create_all()\nuser_datastore = SQLAlchemySessionUserDatastore(db.session, AccountUser,\n AccountRole)\nsecurity = Security(app, user_datastore, register_form=RegistrationForm,\n login_form=LoginForm)\n", "step-5": "from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_security import SQLAlchemySessionUserDatastore, Security\n\napp = Flask(__name__, instance_relative_config=True)\napp.config.from_pyfile(\"config.py\", silent=True)\n\ndb = SQLAlchemy(app)\n\nfrom .blueprints.cart.views import cart_blueprint\nfrom .blueprints.admin.views import admin_blueprint\nfrom .blueprints.products.views import product_blueprint\nfrom .blueprints.orders.views import order_blueprint\nfrom .blueprints.account.views import account_blueprint\nfrom .blueprints.categories.views import category_blueprint\nfrom .blueprints.static_pages.views import static_blueprint\n\n\napp.register_blueprint(static_blueprint)\napp.register_blueprint(admin_blueprint)\napp.register_blueprint(cart_blueprint)\napp.register_blueprint(product_blueprint)\napp.register_blueprint(account_blueprint)\napp.register_blueprint(category_blueprint)\napp.register_blueprint(order_blueprint)\n\nfrom .blueprints.account.models import AccountUser, AccountRole\nfrom .blueprints.account.forms import RegistrationForm, LoginForm\n\ntry:\n AccountUser.query.first()\nexcept Exception as e:\n db.create_all()\n\nuser_datastore = SQLAlchemySessionUserDatastore(db.session, AccountUser, AccountRole)\nsecurity = Security(\n app, user_datastore, register_form=RegistrationForm, login_form=LoginForm\n)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> try: i = float(input('Enter the score : ')) if i > 1 or i < 0: print("Entered score isn't valid.") elif i < 0.6: print('Grade: F') elif i < 0.7: print('Grade: D') elif i < 0.8: print('Grade: C') elif i < 0.9: print('Grade: B') elif i <= 1.0: print('Grade: A') except Exception as e: print(str(e)) <|reserved_special_token_1|> # Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message. # If the score is between 0.0 and 1.0, print a grade using the following table: # Score Grade # >= 0.9 A # >= 0.8 B # >= 0.7 C # >= 0.6 D # < 0.6 F # Vinayak Nayak # 27th December 2018 # 12:30 pm try: i = float(input("Enter the score : ")) if(i > 1 or i < 0): print("Entered score isn't valid.") else: if (i < 0.6): print("Grade: F") elif (i < 0.7): print("Grade: D") elif (i < 0.8): print("Grade: C") elif (i < 0.9): print("Grade: B") elif (i <= 1.0): print("Grade: A") except Exception as e: print(str(e))
flexible
{ "blob_id": "6f253da5dc1caa504a3a8aadae7bce6537b5c8c6", "index": 6237, "step-1": "<mask token>\n", "step-2": "try:\n i = float(input('Enter the score : '))\n if i > 1 or i < 0:\n print(\"Entered score isn't valid.\")\n elif i < 0.6:\n print('Grade: F')\n elif i < 0.7:\n print('Grade: D')\n elif i < 0.8:\n print('Grade: C')\n elif i < 0.9:\n print('Grade: B')\n elif i <= 1.0:\n print('Grade: A')\nexcept Exception as e:\n print(str(e))\n", "step-3": "# Exercise 3: Write a program to prompt for a score between 0.0 and 1.0. If the score is out of range, print an error message.\n# If the score is between 0.0 and 1.0, print a grade using the following table:\n# Score Grade\n# >= 0.9 A\n# >= 0.8 B\n# >= 0.7 C\n# >= 0.6 D\n# < 0.6 F\n\n# Vinayak Nayak\n# 27th December 2018\n# 12:30 pm\n\ntry:\n i = float(input(\"Enter the score : \"))\n\n if(i > 1 or i < 0):\n print(\"Entered score isn't valid.\")\n else:\n if (i < 0.6):\n print(\"Grade: F\")\n\n elif (i < 0.7):\n print(\"Grade: D\")\n\n elif (i < 0.8):\n print(\"Grade: C\")\n\n elif (i < 0.9):\n print(\"Grade: B\")\n\n elif (i <= 1.0):\n print(\"Grade: A\")\n\nexcept Exception as e:\n print(str(e))\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
import tty import sys import termios def init(): orig_settings = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin) return orig_settings def get_input(): return sys.stdin.read(1) def exit(orig_settings): termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) if __name__ == "__main__": settings = init() key = 0 while key != chr(27): # esc key = get_input() print("'" + str(key) + "'") exit(settings)
normal
{ "blob_id": "c64e41609a19a20f59446399a2e864ff8834c3f0", "index": 4322, "step-1": "<mask token>\n\n\ndef get_input():\n return sys.stdin.read(1)\n\n\ndef exit(orig_settings):\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef init():\n orig_settings = termios.tcgetattr(sys.stdin)\n tty.setcbreak(sys.stdin)\n return orig_settings\n\n\ndef get_input():\n return sys.stdin.read(1)\n\n\ndef exit(orig_settings):\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef init():\n orig_settings = termios.tcgetattr(sys.stdin)\n tty.setcbreak(sys.stdin)\n return orig_settings\n\n\ndef get_input():\n return sys.stdin.read(1)\n\n\ndef exit(orig_settings):\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n\n\nif __name__ == '__main__':\n settings = init()\n key = 0\n while key != chr(27):\n key = get_input()\n print(\"'\" + str(key) + \"'\")\n exit(settings)\n", "step-4": "import tty\nimport sys\nimport termios\n\n\ndef init():\n orig_settings = termios.tcgetattr(sys.stdin)\n tty.setcbreak(sys.stdin)\n return orig_settings\n\n\ndef get_input():\n return sys.stdin.read(1)\n\n\ndef exit(orig_settings):\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)\n\n\nif __name__ == '__main__':\n settings = init()\n key = 0\n while key != chr(27):\n key = get_input()\n print(\"'\" + str(key) + \"'\")\n exit(settings)\n", "step-5": "import tty\nimport sys\nimport termios\n\n\ndef init():\n orig_settings = termios.tcgetattr(sys.stdin)\n tty.setcbreak(sys.stdin)\n return orig_settings\n\ndef get_input():\n return sys.stdin.read(1)\n\ndef exit(orig_settings):\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings) \n\n\n\nif __name__ == \"__main__\":\n settings = init()\n key = 0\n while key != chr(27): # esc\n key = get_input()\n print(\"'\" + str(key) + \"'\")\n exit(settings)", "step-ids": [ 2, 3, 4, 5, 6 ] }
[ 2, 3, 4, 5, 6 ]
""" purpose :Take an string as input and construct an algorithm to input a string of characters and check whether it is a palindrome. @Author : Reshma Y. Kale """ from com.bridgelabz.utility.Data_structure_utility import * if __name__=="__main__": dq = Deque() dq.palindrom()
normal
{ "blob_id": "d4d47f7abc5c8224188430546a65bfb8f358802f", "index": 1472, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n dq = Deque()\n dq.palindrom()\n", "step-3": "<mask token>\nfrom com.bridgelabz.utility.Data_structure_utility import *\nif __name__ == '__main__':\n dq = Deque()\n dq.palindrom()\n", "step-4": "\"\"\"\npurpose :Take an string as input and construct an algorithm\n to input a string of characters and check whether\n it is a palindrome.\n\n@Author : Reshma Y. Kale\n\n\"\"\"\nfrom com.bridgelabz.utility.Data_structure_utility import *\nif __name__==\"__main__\":\n\n dq = Deque()\n dq.palindrom()", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from prettytable import PrettyTable from time import sleep from customization import * import urllib.request,json chrome_options=webdriver.ChromeOptions() chrome_options.add_argument("--headless") chrome_options.add_argument("--incognito") chrome_options.add_experimental_option('excludeSwitches', ['enable-logging']) chromeBrowser = webdriver.Chrome(chromePath, options=chrome_options) def bio_shortener(bio): lines=[] x=len(bio)/30 y=0 Status=True while Status: y=y+1 lines.append(bio[0:30]) lines.append("\n") bio=bio[30:] if y==int(x)+1: Status=False A=''.join(lines) return A def nb_checker(nb): if nb!='None': return nb.text else: nb def quick_search(username): print("Collecting username information...") insta_url="https://instagram.com/"+username+"/" chromeBrowser.get(insta_url) WebDriverWait(chromeBrowser,5).until(lambda d: d.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input')) chromeBrowser.find_element_by_xpath('//*[@id="loginForm"]/div/div[1]/div/label/input').send_keys(i_email) chromeBrowser.find_element_by_xpath('//*[@id="loginForm"]/div/div[2]/div/label/input').send_keys(i_password) chromeBrowser.find_element_by_xpath('//*[@id="loginForm"]/div[1]/div[3]/button').click() WebDriverWait(chromeBrowser,10).until(lambda d: d.find_element_by_xpath('//*[@id="react-root"]/section/main/div/div/div/div/button')) chromeBrowser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/div/div/div/button').click() try: instaName=chromeBrowser.find_element_by_class_name('rhpdm').text except: instaName="None" try: instaBio=chromeBrowser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/div[2]/span').text except: instaBio="None" try: instaPersonalSite=chromeBrowser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[2]/a[1]').text except NameError: instaPersonalSite=chromeBrowser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/header/section/div[2]/a').text except: instaPersonalSite='None' sleep(1) chromeBrowser.get('https://stackoverflow.com/users/') WebDriverWait(chromeBrowser, 10).until(lambda d: d.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[1]/div[1]/input')) chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[1]/div[1]/input').send_keys(username) sleep(1) try: Name=chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a') if str(Name.text.lower())==username.lower(): placeholder=True except: placeholder=False try: sofLocation=chromeBrowser.find_element_by_class_name('user-location').text except: sofLocation='None' try: sofUser_tag = chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[3]').text except: sofUser_tag='None' try: chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a').click() WebDriverWait(chromeBrowser, 10).until(lambda d: d.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[2]/div[1]/div/div[2]/div/div[1]/div/div[2]')) except: placeholder=True try: sofBio=chromeBrowser.find_element_by_xpath('//*[@id="user-card"]/div/div[2]/div/div[1]/div/div[2]').text except: sofBio='None' githubUrl = "https://api.github.com/users/" + username try: with urllib.request.urlopen(githubUrl) as url: githubData = json.loads(url.read().decode()) gitName=str(githubData['name']) gitCompany=str(githubData['company']) gitBlog=str(githubData['blog']) gitEmail=str(githubData['email']) gitBio=str(githubData['bio']) gitTwitter=str(githubData['twitter_username']) gitLocation=str(githubData['location']) except: placeholder=True pt = PrettyTable( [' ', ' Instagram ', ' StackOverflow ', ' GitHub ']) pt.add_row(["Name", instaName,"X", gitName]) pt.add_row(["Email", "X","X",gitEmail]) pt.add_row(["Company","X","X", gitCompany]) pt.add_row(["Personal Site", instaPersonalSite,"X", gitBlog]) pt.add_row(["Location", "X", sofLocation, gitLocation]) pt.add_row(["Twitter", "X", "X", gitTwitter]) pt.add_row(["Tags", "X", sofUser_tag, "X"]) pt.add_row(["Biography", bio_shortener(instaBio), bio_shortener(sofBio), bio_shortener(gitBio)]) print(pt) input()
normal
{ "blob_id": "e1c902ef340a0a5538b41a03cc93686e0dd31672", "index": 8788, "step-1": "<mask token>\n\n\ndef bio_shortener(bio):\n lines = []\n x = len(bio) / 30\n y = 0\n Status = True\n while Status:\n y = y + 1\n lines.append(bio[0:30])\n lines.append('\\n')\n bio = bio[30:]\n if y == int(x) + 1:\n Status = False\n A = ''.join(lines)\n return A\n\n\ndef nb_checker(nb):\n if nb != 'None':\n return nb.text\n else:\n nb\n\n\ndef quick_search(username):\n print('Collecting username information...')\n insta_url = 'https://instagram.com/' + username + '/'\n chromeBrowser.get(insta_url)\n WebDriverWait(chromeBrowser, 5).until(lambda d: d.find_element_by_xpath\n ('//*[@id=\"loginForm\"]/div/div[1]/div/label/input'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[1]/div/label/input').send_keys(i_email)\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[2]/div/label/input').send_keys(i_password\n )\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div[1]/div[3]/button').click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button').click()\n try:\n instaName = chromeBrowser.find_element_by_class_name('rhpdm').text\n except:\n instaName = 'None'\n try:\n instaBio = chromeBrowser.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/header/section/div[2]/span'\n ).text\n except:\n instaBio = 'None'\n try:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a[1]'\n ).text\n except NameError:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a'\n ).text\n except:\n instaPersonalSite = 'None'\n sleep(1)\n chromeBrowser.get('https://stackoverflow.com/users/')\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input'))\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input').send_keys(username)\n sleep(1)\n try:\n Name = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a')\n if str(Name.text.lower()) == username.lower():\n placeholder = True\n except:\n placeholder = False\n try:\n sofLocation = chromeBrowser.find_element_by_class_name('user-location'\n ).text\n except:\n sofLocation = 'None'\n try:\n sofUser_tag = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[3]').text\n except:\n sofUser_tag = 'None'\n try:\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a'\n ).click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[2]/div[1]/div/div[2]/div/div[1]/div/div[2]'\n ))\n except:\n placeholder = True\n try:\n sofBio = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"user-card\"]/div/div[2]/div/div[1]/div/div[2]').text\n except:\n sofBio = 'None'\n githubUrl = 'https://api.github.com/users/' + username\n try:\n with urllib.request.urlopen(githubUrl) as url:\n githubData = json.loads(url.read().decode())\n gitName = str(githubData['name'])\n gitCompany = str(githubData['company'])\n gitBlog = str(githubData['blog'])\n gitEmail = str(githubData['email'])\n gitBio = str(githubData['bio'])\n gitTwitter = str(githubData['twitter_username'])\n gitLocation = str(githubData['location'])\n except:\n placeholder = True\n pt = PrettyTable([' ', ' Instagram ',\n ' StackOverflow ', ' GitHub '])\n pt.add_row(['Name', instaName, 'X', gitName])\n pt.add_row(['Email', 'X', 'X', gitEmail])\n pt.add_row(['Company', 'X', 'X', gitCompany])\n pt.add_row(['Personal Site', instaPersonalSite, 'X', gitBlog])\n pt.add_row(['Location', 'X', sofLocation, gitLocation])\n pt.add_row(['Twitter', 'X', 'X', gitTwitter])\n pt.add_row(['Tags', 'X', sofUser_tag, 'X'])\n pt.add_row(['Biography', bio_shortener(instaBio), bio_shortener(sofBio),\n bio_shortener(gitBio)])\n print(pt)\n input()\n", "step-2": "<mask token>\nchrome_options.add_argument('--headless')\nchrome_options.add_argument('--incognito')\nchrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])\n<mask token>\n\n\ndef bio_shortener(bio):\n lines = []\n x = len(bio) / 30\n y = 0\n Status = True\n while Status:\n y = y + 1\n lines.append(bio[0:30])\n lines.append('\\n')\n bio = bio[30:]\n if y == int(x) + 1:\n Status = False\n A = ''.join(lines)\n return A\n\n\ndef nb_checker(nb):\n if nb != 'None':\n return nb.text\n else:\n nb\n\n\ndef quick_search(username):\n print('Collecting username information...')\n insta_url = 'https://instagram.com/' + username + '/'\n chromeBrowser.get(insta_url)\n WebDriverWait(chromeBrowser, 5).until(lambda d: d.find_element_by_xpath\n ('//*[@id=\"loginForm\"]/div/div[1]/div/label/input'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[1]/div/label/input').send_keys(i_email)\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[2]/div/label/input').send_keys(i_password\n )\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div[1]/div[3]/button').click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button').click()\n try:\n instaName = chromeBrowser.find_element_by_class_name('rhpdm').text\n except:\n instaName = 'None'\n try:\n instaBio = chromeBrowser.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/header/section/div[2]/span'\n ).text\n except:\n instaBio = 'None'\n try:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a[1]'\n ).text\n except NameError:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a'\n ).text\n except:\n instaPersonalSite = 'None'\n sleep(1)\n chromeBrowser.get('https://stackoverflow.com/users/')\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input'))\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input').send_keys(username)\n sleep(1)\n try:\n Name = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a')\n if str(Name.text.lower()) == username.lower():\n placeholder = True\n except:\n placeholder = False\n try:\n sofLocation = chromeBrowser.find_element_by_class_name('user-location'\n ).text\n except:\n sofLocation = 'None'\n try:\n sofUser_tag = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[3]').text\n except:\n sofUser_tag = 'None'\n try:\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a'\n ).click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[2]/div[1]/div/div[2]/div/div[1]/div/div[2]'\n ))\n except:\n placeholder = True\n try:\n sofBio = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"user-card\"]/div/div[2]/div/div[1]/div/div[2]').text\n except:\n sofBio = 'None'\n githubUrl = 'https://api.github.com/users/' + username\n try:\n with urllib.request.urlopen(githubUrl) as url:\n githubData = json.loads(url.read().decode())\n gitName = str(githubData['name'])\n gitCompany = str(githubData['company'])\n gitBlog = str(githubData['blog'])\n gitEmail = str(githubData['email'])\n gitBio = str(githubData['bio'])\n gitTwitter = str(githubData['twitter_username'])\n gitLocation = str(githubData['location'])\n except:\n placeholder = True\n pt = PrettyTable([' ', ' Instagram ',\n ' StackOverflow ', ' GitHub '])\n pt.add_row(['Name', instaName, 'X', gitName])\n pt.add_row(['Email', 'X', 'X', gitEmail])\n pt.add_row(['Company', 'X', 'X', gitCompany])\n pt.add_row(['Personal Site', instaPersonalSite, 'X', gitBlog])\n pt.add_row(['Location', 'X', sofLocation, gitLocation])\n pt.add_row(['Twitter', 'X', 'X', gitTwitter])\n pt.add_row(['Tags', 'X', sofUser_tag, 'X'])\n pt.add_row(['Biography', bio_shortener(instaBio), bio_shortener(sofBio),\n bio_shortener(gitBio)])\n print(pt)\n input()\n", "step-3": "<mask token>\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument('--headless')\nchrome_options.add_argument('--incognito')\nchrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])\nchromeBrowser = webdriver.Chrome(chromePath, options=chrome_options)\n\n\ndef bio_shortener(bio):\n lines = []\n x = len(bio) / 30\n y = 0\n Status = True\n while Status:\n y = y + 1\n lines.append(bio[0:30])\n lines.append('\\n')\n bio = bio[30:]\n if y == int(x) + 1:\n Status = False\n A = ''.join(lines)\n return A\n\n\ndef nb_checker(nb):\n if nb != 'None':\n return nb.text\n else:\n nb\n\n\ndef quick_search(username):\n print('Collecting username information...')\n insta_url = 'https://instagram.com/' + username + '/'\n chromeBrowser.get(insta_url)\n WebDriverWait(chromeBrowser, 5).until(lambda d: d.find_element_by_xpath\n ('//*[@id=\"loginForm\"]/div/div[1]/div/label/input'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[1]/div/label/input').send_keys(i_email)\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[2]/div/label/input').send_keys(i_password\n )\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div[1]/div[3]/button').click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button').click()\n try:\n instaName = chromeBrowser.find_element_by_class_name('rhpdm').text\n except:\n instaName = 'None'\n try:\n instaBio = chromeBrowser.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/header/section/div[2]/span'\n ).text\n except:\n instaBio = 'None'\n try:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a[1]'\n ).text\n except NameError:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a'\n ).text\n except:\n instaPersonalSite = 'None'\n sleep(1)\n chromeBrowser.get('https://stackoverflow.com/users/')\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input'))\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input').send_keys(username)\n sleep(1)\n try:\n Name = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a')\n if str(Name.text.lower()) == username.lower():\n placeholder = True\n except:\n placeholder = False\n try:\n sofLocation = chromeBrowser.find_element_by_class_name('user-location'\n ).text\n except:\n sofLocation = 'None'\n try:\n sofUser_tag = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[3]').text\n except:\n sofUser_tag = 'None'\n try:\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a'\n ).click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[2]/div[1]/div/div[2]/div/div[1]/div/div[2]'\n ))\n except:\n placeholder = True\n try:\n sofBio = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"user-card\"]/div/div[2]/div/div[1]/div/div[2]').text\n except:\n sofBio = 'None'\n githubUrl = 'https://api.github.com/users/' + username\n try:\n with urllib.request.urlopen(githubUrl) as url:\n githubData = json.loads(url.read().decode())\n gitName = str(githubData['name'])\n gitCompany = str(githubData['company'])\n gitBlog = str(githubData['blog'])\n gitEmail = str(githubData['email'])\n gitBio = str(githubData['bio'])\n gitTwitter = str(githubData['twitter_username'])\n gitLocation = str(githubData['location'])\n except:\n placeholder = True\n pt = PrettyTable([' ', ' Instagram ',\n ' StackOverflow ', ' GitHub '])\n pt.add_row(['Name', instaName, 'X', gitName])\n pt.add_row(['Email', 'X', 'X', gitEmail])\n pt.add_row(['Company', 'X', 'X', gitCompany])\n pt.add_row(['Personal Site', instaPersonalSite, 'X', gitBlog])\n pt.add_row(['Location', 'X', sofLocation, gitLocation])\n pt.add_row(['Twitter', 'X', 'X', gitTwitter])\n pt.add_row(['Tags', 'X', sofUser_tag, 'X'])\n pt.add_row(['Biography', bio_shortener(instaBio), bio_shortener(sofBio),\n bio_shortener(gitBio)])\n print(pt)\n input()\n", "step-4": "from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom prettytable import PrettyTable\nfrom time import sleep\nfrom customization import *\nimport urllib.request, json\nchrome_options = webdriver.ChromeOptions()\nchrome_options.add_argument('--headless')\nchrome_options.add_argument('--incognito')\nchrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])\nchromeBrowser = webdriver.Chrome(chromePath, options=chrome_options)\n\n\ndef bio_shortener(bio):\n lines = []\n x = len(bio) / 30\n y = 0\n Status = True\n while Status:\n y = y + 1\n lines.append(bio[0:30])\n lines.append('\\n')\n bio = bio[30:]\n if y == int(x) + 1:\n Status = False\n A = ''.join(lines)\n return A\n\n\ndef nb_checker(nb):\n if nb != 'None':\n return nb.text\n else:\n nb\n\n\ndef quick_search(username):\n print('Collecting username information...')\n insta_url = 'https://instagram.com/' + username + '/'\n chromeBrowser.get(insta_url)\n WebDriverWait(chromeBrowser, 5).until(lambda d: d.find_element_by_xpath\n ('//*[@id=\"loginForm\"]/div/div[1]/div/label/input'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[1]/div/label/input').send_keys(i_email)\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div/div[2]/div/label/input').send_keys(i_password\n )\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"loginForm\"]/div[1]/div[3]/button').click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button'))\n chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/div/div/div/button').click()\n try:\n instaName = chromeBrowser.find_element_by_class_name('rhpdm').text\n except:\n instaName = 'None'\n try:\n instaBio = chromeBrowser.find_element_by_xpath(\n '/html/body/div[1]/section/main/div/header/section/div[2]/span'\n ).text\n except:\n instaBio = 'None'\n try:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a[1]'\n ).text\n except NameError:\n instaPersonalSite = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a'\n ).text\n except:\n instaPersonalSite = 'None'\n sleep(1)\n chromeBrowser.get('https://stackoverflow.com/users/')\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input'))\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[1]/div[1]/input').send_keys(username)\n sleep(1)\n try:\n Name = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a')\n if str(Name.text.lower()) == username.lower():\n placeholder = True\n except:\n placeholder = False\n try:\n sofLocation = chromeBrowser.find_element_by_class_name('user-location'\n ).text\n except:\n sofLocation = 'None'\n try:\n sofUser_tag = chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[3]').text\n except:\n sofUser_tag = 'None'\n try:\n chromeBrowser.find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a'\n ).click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.\n find_element_by_xpath(\n '/html/body/div[4]/div[2]/div/div[2]/div[1]/div/div[2]/div/div[1]/div/div[2]'\n ))\n except:\n placeholder = True\n try:\n sofBio = chromeBrowser.find_element_by_xpath(\n '//*[@id=\"user-card\"]/div/div[2]/div/div[1]/div/div[2]').text\n except:\n sofBio = 'None'\n githubUrl = 'https://api.github.com/users/' + username\n try:\n with urllib.request.urlopen(githubUrl) as url:\n githubData = json.loads(url.read().decode())\n gitName = str(githubData['name'])\n gitCompany = str(githubData['company'])\n gitBlog = str(githubData['blog'])\n gitEmail = str(githubData['email'])\n gitBio = str(githubData['bio'])\n gitTwitter = str(githubData['twitter_username'])\n gitLocation = str(githubData['location'])\n except:\n placeholder = True\n pt = PrettyTable([' ', ' Instagram ',\n ' StackOverflow ', ' GitHub '])\n pt.add_row(['Name', instaName, 'X', gitName])\n pt.add_row(['Email', 'X', 'X', gitEmail])\n pt.add_row(['Company', 'X', 'X', gitCompany])\n pt.add_row(['Personal Site', instaPersonalSite, 'X', gitBlog])\n pt.add_row(['Location', 'X', sofLocation, gitLocation])\n pt.add_row(['Twitter', 'X', 'X', gitTwitter])\n pt.add_row(['Tags', 'X', sofUser_tag, 'X'])\n pt.add_row(['Biography', bio_shortener(instaBio), bio_shortener(sofBio),\n bio_shortener(gitBio)])\n print(pt)\n input()\n", "step-5": "from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom prettytable import PrettyTable\nfrom time import sleep\nfrom customization import *\n\nimport urllib.request,json\nchrome_options=webdriver.ChromeOptions()\nchrome_options.add_argument(\"--headless\")\nchrome_options.add_argument(\"--incognito\")\nchrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])\nchromeBrowser = webdriver.Chrome(chromePath, options=chrome_options)\ndef bio_shortener(bio):\n lines=[]\n x=len(bio)/30\n y=0\n Status=True\n while Status:\n y=y+1\n lines.append(bio[0:30])\n lines.append(\"\\n\")\n bio=bio[30:]\n if y==int(x)+1:\n Status=False\n\n A=''.join(lines)\n return A\n\ndef nb_checker(nb):\n if nb!='None':\n return nb.text\n else:\n nb\n\n\ndef quick_search(username):\n print(\"Collecting username information...\")\n insta_url=\"https://instagram.com/\"+username+\"/\"\n chromeBrowser.get(insta_url)\n WebDriverWait(chromeBrowser,5).until(lambda d: d.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[1]/div/label/input'))\n chromeBrowser.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[1]/div/label/input').send_keys(i_email)\n chromeBrowser.find_element_by_xpath('//*[@id=\"loginForm\"]/div/div[2]/div/label/input').send_keys(i_password)\n chromeBrowser.find_element_by_xpath('//*[@id=\"loginForm\"]/div[1]/div[3]/button').click()\n WebDriverWait(chromeBrowser,10).until(lambda d: d.find_element_by_xpath('//*[@id=\"react-root\"]/section/main/div/div/div/div/button'))\n chromeBrowser.find_element_by_xpath('//*[@id=\"react-root\"]/section/main/div/div/div/div/button').click()\n try:\n instaName=chromeBrowser.find_element_by_class_name('rhpdm').text\n except:\n instaName=\"None\"\n try:\n instaBio=chromeBrowser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/div[2]/span').text\n except:\n instaBio=\"None\"\n try:\n instaPersonalSite=chromeBrowser.find_element_by_xpath('//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a[1]').text\n except NameError:\n instaPersonalSite=chromeBrowser.find_element_by_xpath('//*[@id=\"react-root\"]/section/main/div/header/section/div[2]/a').text\n except:\n instaPersonalSite='None'\n\n sleep(1)\n chromeBrowser.get('https://stackoverflow.com/users/')\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[1]/div[1]/input'))\n chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[1]/div[1]/input').send_keys(username)\n sleep(1)\n try:\n Name=chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a')\n if str(Name.text.lower())==username.lower():\n placeholder=True\n except:\n placeholder=False\n try:\n sofLocation=chromeBrowser.find_element_by_class_name('user-location').text\n except:\n sofLocation='None'\n try:\n sofUser_tag = chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[3]').text\n except:\n sofUser_tag='None'\n try:\n chromeBrowser.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[3]/div[1]/div[1]/div[2]/a').click()\n WebDriverWait(chromeBrowser, 10).until(lambda d: d.find_element_by_xpath('/html/body/div[4]/div[2]/div/div[2]/div[1]/div/div[2]/div/div[1]/div/div[2]'))\n except:\n placeholder=True\n try:\n sofBio=chromeBrowser.find_element_by_xpath('//*[@id=\"user-card\"]/div/div[2]/div/div[1]/div/div[2]').text\n except:\n sofBio='None'\n\n githubUrl = \"https://api.github.com/users/\" + username\n\n try:\n with urllib.request.urlopen(githubUrl) as url:\n githubData = json.loads(url.read().decode())\n gitName=str(githubData['name'])\n gitCompany=str(githubData['company'])\n gitBlog=str(githubData['blog'])\n gitEmail=str(githubData['email'])\n gitBio=str(githubData['bio'])\n gitTwitter=str(githubData['twitter_username'])\n gitLocation=str(githubData['location'])\n except:\n placeholder=True\n\n pt = PrettyTable(\n [' ', ' Instagram ', ' StackOverflow ', ' GitHub '])\n pt.add_row([\"Name\", instaName,\"X\", gitName])\n pt.add_row([\"Email\", \"X\",\"X\",gitEmail])\n pt.add_row([\"Company\",\"X\",\"X\", gitCompany])\n pt.add_row([\"Personal Site\", instaPersonalSite,\"X\", gitBlog])\n pt.add_row([\"Location\", \"X\", sofLocation, gitLocation])\n pt.add_row([\"Twitter\", \"X\", \"X\", gitTwitter])\n pt.add_row([\"Tags\", \"X\", sofUser_tag, \"X\"])\n pt.add_row([\"Biography\", bio_shortener(instaBio), bio_shortener(sofBio), bio_shortener(gitBio)])\n print(pt)\n input()\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
from flask import request from flask_restful import abort from sqlalchemy.exc import SQLAlchemyError from gm.main.models.model import db, Metric, QuantModelMetricSchema, \ MlModelMetricSchema, Frequency, QuantModelMetric, MlModelMetric, \ ThresholdType from gm.main.resources import success, get_metric_by_id, BaseResource class MetricsResource(BaseResource): """ This resource handles the HTTP requests coming to the endpoint "/metrics". Note: no trailing slash ("/") should be used. Accepted HTTP methods: GET, POST """ def get(self): """ Implements the GET method for endpoint "/metrics". By default the results are order by 'metric_id' ascending. Implemented Query Parameters: - is_active: to filter results that are either active or inactive. Boolean and case insensitive. - frequency: filter results based on a metric frequency. Values of this enum must be respected. Case insensitive. - threshold_type: filter results based on a metric threshold type. Values of this enum must be respected. Case insensitive. - sort: allows one to order the resulting collecting by 'metric_id' in descending order. This should be done by specifying the query parameter as "sort=-metric_id". Case insensitive. Note: if unknown query parameters are given these will be ignored. :return: a collection of metrics """ query = self.build_query() metrics = query.all() result = self.schema_collection.dump(metrics) return success(result) def build_query(self): """ Builds the query (without executing it) to the be used in the GET method. :return: query with all the query conditions specified for obtaining the metrics that are in the database and respect the desired filters (query parameters). """ # this filter is required query = Metric.query.filter(Metric.metric_type == self.metric_type) # get query parameters (parameters which are not here are ignored) is_active = request.args.get('is_active') frequency = request.args.get('frequency') threshold_type = request.args.get('threshold_type') sort = request.args.get('sort') # process each parameter, and if valid add it as a query condition if is_active is not None: is_active = is_active.lower() == 'true' query = Metric.query.filter_by(is_active=is_active) if frequency is not None: try: frequency = Frequency.from_name(frequency) except ValueError as e: msg = f"Invalid 'frequency': {frequency}. Use one of {Frequency.values()}" abort(400, message=msg) query = query.filter_by(frequency=frequency) if threshold_type is not None: try: threshold_type = ThresholdType.from_name(threshold_type) except ValueError as e: msg = f"Invalid 'threshold_type': {threshold_type}. Use one of " \ f"{ThresholdType.values()}" abort(400, message=msg) query = query.filter_by(threshold_type=threshold_type) if sort is not None and sort.lstrip("-") == 'metric_id': query = query.order_by(Metric.metric_id.desc()) else: query = query.order_by(Metric.metric_id) return query def post(self): """ Implements the POST method for endpoint "/metrics". It should be used to create a new metric. :return: the metric as a json created in the database (in case of success) """ json_data = request.get_json(force=True) if not json_data: abort(400, message='No input data provided') # make sure the metric_id (temporary) and metric_type (model) are filled json_data["metric_id"] = "TBD" json_data["metric_type"] = "model" # validate and deserialize input new_metric = self.load(json_data, session=db.session) # get the next metric id and update metric object try: db.session.add(new_metric) db.session.commit() except SQLAlchemyError as e: abort(400, message=f'Database error. Reason: {e}') # dump to json and return result result = self.schema.dump(new_metric) return success(result, code=201) class QuantModelMetricsResource(MetricsResource): """ This resource handles the HTTP requests coming to the endpoint "/quant_model/metrics/{metric_id}". This subclass uses almost everything from the base class, it only needs to specify the appropriate schemas in the constructor, and to override the build_query method so that the appropriate metric_type is filtered and the remaining query parameters (specific to this endpoint) are processed. Implemented Query Parameters: - asset_class: to filter results by a given asset class. - model_name: to filter results by a given model name. - pricing_library: to filter results for a given pricing library. Note: no trailing slash ("/") should be used. Accepted HTTP methods: GET, POST """ def __init__(self, **kwargs): """ Initialize schemas with appropriate classes. :param kwargs: pass through to base constructor (service and metric_type) """ schema = QuantModelMetricSchema() schema_collection = QuantModelMetricSchema(many=True) super().__init__(schema, schema_collection, **kwargs) def build_query(self): """ Override method to include specific query parameters to this model endpoint. """ # build query from base class add required field for joining with parent query = super().build_query() query = query.filter(Metric.metric_id == QuantModelMetric.metric_id) # get the remaining query parameters asset_class = request.args.get('asset_class') model_name = request.args.get('model_name') pricing_library = request.args.get('pricing_library') # process each parameter and, if valid, add as a query condition if asset_class is not None: query = query.filter(QuantModelMetric.asset_class == asset_class) if model_name is not None: query = query.filter(QuantModelMetric.model_name == model_name) if pricing_library is not None: query = query.filter(QuantModelMetric.pricing_library == pricing_library) return query class MlModelMetricsResource(MetricsResource): """ This resource handles the HTTP requests coming to the endpoint "/ml_model/metrics/{metric_id}". This subclass uses almost everything from the base class, it only needs to specify the appropriate schemas in the constructor, and to override the build_query method so that the appropriate metric_type is filtered and the remaining query parameters (specific to this endpoint) are processed. Implemented Query Parameters: - algorithm: to filter results by a given algorithm. Note: no trailing slash ("/") should be used. Accepted HTTP methods: GET, POST """ def __init__(self, **kwargs): """ Initialize schemas with appropriate classes. :param kwargs: pass through to base constructor (service and metric_type) """ schema = MlModelMetricSchema() schema_collection = MlModelMetricSchema(many=True) super().__init__(schema, schema_collection, **kwargs) def build_query(self): """ Override method to include specific query parameters to this ml_model endpoint. """ query = super().build_query() query = query.filter(Metric.metric_id == MlModelMetric.metric_id) algorithm = request.args.get('algorithm') if algorithm is not None: query = query.filter(MlModelMetric.algorithm == algorithm) return query class MetricResource(BaseResource): """ This resource handles the HTTP requests coming to the endpoint "/metrics/{metric_id}". Note: no trailing slash ("/") should be used. Accepted HTTP methods: GET, PUT, DELETE """ def get(self, metric_id): """ Implements the GET method for endpoint "/metrics/{metric_id}". It should be used to get a single metric from the database. :param metric_id: the metric_id associated with this endpoint :return: the json object of metric found in the database (if it exists) """ metric = get_metric_by_id(metric_id) return self.schema.jsonify(metric) def put(self, metric_id): """ Implements the PUT method for endpoint "/metrics/{metric_id}". It should be used to update a metric. :param metric_id: the metric_id associated with this endpoint :return: the metric as a json after the update (in case of success) """ json_data = request.get_json(force=True) if not json_data: abort(400, message='No input data provided') # Validate and deserialize input metric = get_metric_by_id(metric_id) self.load(json_data, metric, db.session, partial=True) # if it was found and deserialized successfully try to commit try: db.session.commit() except SQLAlchemyError as e: abort(400, message=f'Database error. Reason: {e}') return success(json_data) def delete(self, metric_id): """ Implements the DELETE method for endpoint "/metrics/{metric_id}". It should be used to delete a metric result matching the provided metric_id and cob_date. :param metric_id: the metric_id associated with this endpoint :return: the metric as a json after the delete (in case of success) """ metric = get_metric_by_id(metric_id) # dump as json to send in the end if del is successful result = self.schema.dump(metric) # if result was found, delete it from database try: db.session.delete(metric) db.session.commit() except SQLAlchemyError as e: abort(400, message=f'Database error. Reason: {e}') return success(result) class QuantModelMetricResource(MetricResource): """ This resource handles the HTTP requests coming to the endpoint "/quant_model/metrics/{metric_id}". This subclass uses everything from the base class and only needs to specify the appropriate schemas in the constructor. Note: no trailing slash ("/") should be used. Accepted HTTP methods: GET, PUT, DELETE """ def __init__(self, **kwargs): """ Initialize schemas with appropriate classes. :param kwargs: pass through to base constructor (service and metric_type) """ schema = QuantModelMetricSchema() schema_collection = QuantModelMetricSchema(many=True) super().__init__(schema, schema_collection, **kwargs) class MlModelMetricResource(MetricResource): """ This resource handles the HTTP requests coming to the endpoint "/ml_model/metrics/{metric_id}". This subclass uses everything from the base class and only needs to specify the appropriate schemas in the constructor. Note: no trailing slash ("/") should be used. Accepted HTTP methods: GET, PUT, DELETE """ def __init__(self, **kwargs): """ Initialize schemas with appropriate classes. :param kwargs: pass through to base constructor (service and metric_type) """ schema = MlModelMetricSchema() schema_collection = MlModelMetricSchema(many=True) super().__init__(schema, schema_collection, **kwargs)
normal
{ "blob_id": "1431a0049c05a99e0b68052f56bf8e2e3c48e1aa", "index": 622, "step-1": "<mask token>\n\n\nclass QuantModelMetricsResource(MetricsResource):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass MlModelMetricsResource(MetricsResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses almost everything from the base class, it only needs to specify the\n appropriate schemas in the constructor, and to override the build_query method so that\n the appropriate metric_type is filtered and the remaining query parameters (specific\n to this endpoint) are processed.\n\n Implemented Query Parameters:\n - algorithm: to filter results by a given algorithm.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n def build_query(self):\n \"\"\"\n Override method to include specific query parameters to this ml_model\n endpoint.\n \"\"\"\n query = super().build_query()\n query = query.filter(Metric.metric_id == MlModelMetric.metric_id)\n algorithm = request.args.get('algorithm')\n if algorithm is not None:\n query = query.filter(MlModelMetric.algorithm == algorithm)\n return query\n\n\nclass MetricResource(BaseResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint \"/metrics/{metric_id}\".\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def get(self, metric_id):\n \"\"\"\n Implements the GET method for endpoint \"/metrics/{metric_id}\". It should be used\n to get a single metric from the database.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the json object of metric found in the database (if it exists)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n return self.schema.jsonify(metric)\n\n def put(self, metric_id):\n \"\"\"\n Implements the PUT method for endpoint \"/metrics/{metric_id}\". It should be used\n to update a metric.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the update (in case of success)\n \"\"\"\n json_data = request.get_json(force=True)\n if not json_data:\n abort(400, message='No input data provided')\n metric = get_metric_by_id(metric_id)\n self.load(json_data, metric, db.session, partial=True)\n try:\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(json_data)\n\n def delete(self, metric_id):\n \"\"\"\n Implements the DELETE method for endpoint \"/metrics/{metric_id}\". It should be\n used to delete a metric result matching the provided metric_id and cob_date.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the delete (in case of success)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n result = self.schema.dump(metric)\n try:\n db.session.delete(metric)\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(result)\n\n\nclass QuantModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/quant_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = QuantModelMetricSchema()\n schema_collection = QuantModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n\nclass MlModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n", "step-2": "<mask token>\n\n\nclass QuantModelMetricsResource(MetricsResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/quant_model/metrics/{metric_id}\".\n\n This subclass uses almost everything from the base class, it only needs to specify the\n appropriate schemas in the constructor, and to override the build_query method so that\n the appropriate metric_type is filtered and the remaining query parameters (specific\n to this endpoint) are processed.\n\n Implemented Query Parameters:\n - asset_class: to filter results by a given asset class.\n - model_name: to filter results by a given model name.\n - pricing_library: to filter results for a given pricing library.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = QuantModelMetricSchema()\n schema_collection = QuantModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n def build_query(self):\n \"\"\"\n Override method to include specific query parameters to this model endpoint.\n \"\"\"\n query = super().build_query()\n query = query.filter(Metric.metric_id == QuantModelMetric.metric_id)\n asset_class = request.args.get('asset_class')\n model_name = request.args.get('model_name')\n pricing_library = request.args.get('pricing_library')\n if asset_class is not None:\n query = query.filter(QuantModelMetric.asset_class == asset_class)\n if model_name is not None:\n query = query.filter(QuantModelMetric.model_name == model_name)\n if pricing_library is not None:\n query = query.filter(QuantModelMetric.pricing_library ==\n pricing_library)\n return query\n\n\nclass MlModelMetricsResource(MetricsResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses almost everything from the base class, it only needs to specify the\n appropriate schemas in the constructor, and to override the build_query method so that\n the appropriate metric_type is filtered and the remaining query parameters (specific\n to this endpoint) are processed.\n\n Implemented Query Parameters:\n - algorithm: to filter results by a given algorithm.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n def build_query(self):\n \"\"\"\n Override method to include specific query parameters to this ml_model\n endpoint.\n \"\"\"\n query = super().build_query()\n query = query.filter(Metric.metric_id == MlModelMetric.metric_id)\n algorithm = request.args.get('algorithm')\n if algorithm is not None:\n query = query.filter(MlModelMetric.algorithm == algorithm)\n return query\n\n\nclass MetricResource(BaseResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint \"/metrics/{metric_id}\".\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def get(self, metric_id):\n \"\"\"\n Implements the GET method for endpoint \"/metrics/{metric_id}\". It should be used\n to get a single metric from the database.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the json object of metric found in the database (if it exists)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n return self.schema.jsonify(metric)\n\n def put(self, metric_id):\n \"\"\"\n Implements the PUT method for endpoint \"/metrics/{metric_id}\". It should be used\n to update a metric.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the update (in case of success)\n \"\"\"\n json_data = request.get_json(force=True)\n if not json_data:\n abort(400, message='No input data provided')\n metric = get_metric_by_id(metric_id)\n self.load(json_data, metric, db.session, partial=True)\n try:\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(json_data)\n\n def delete(self, metric_id):\n \"\"\"\n Implements the DELETE method for endpoint \"/metrics/{metric_id}\". It should be\n used to delete a metric result matching the provided metric_id and cob_date.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the delete (in case of success)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n result = self.schema.dump(metric)\n try:\n db.session.delete(metric)\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(result)\n\n\nclass QuantModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/quant_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = QuantModelMetricSchema()\n schema_collection = QuantModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n\nclass MlModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n", "step-3": "<mask token>\n\n\nclass MetricsResource(BaseResource):\n <mask token>\n\n def get(self):\n \"\"\"\n Implements the GET method for endpoint \"/metrics\". By default the results are\n order by 'metric_id' ascending.\n\n Implemented Query Parameters:\n - is_active: to filter results that are either active or inactive. Boolean and\n case insensitive.\n - frequency: filter results based on a metric frequency. Values of this enum must\n be respected. Case insensitive.\n - threshold_type: filter results based on a metric threshold type. Values of this\n enum must be respected. Case insensitive.\n - sort: allows one to order the resulting collecting by 'metric_id' in descending\n order. This should be done by specifying the query parameter as \"sort=-metric_id\".\n Case insensitive.\n\n Note: if unknown query parameters are given these will be ignored.\n\n :return: a collection of metrics\n \"\"\"\n query = self.build_query()\n metrics = query.all()\n result = self.schema_collection.dump(metrics)\n return success(result)\n\n def build_query(self):\n \"\"\"\n Builds the query (without executing it) to the be used in the GET method.\n :return: query with all the query conditions specified for obtaining the metrics\n that are in the database and respect the desired filters (query parameters).\n \"\"\"\n query = Metric.query.filter(Metric.metric_type == self.metric_type)\n is_active = request.args.get('is_active')\n frequency = request.args.get('frequency')\n threshold_type = request.args.get('threshold_type')\n sort = request.args.get('sort')\n if is_active is not None:\n is_active = is_active.lower() == 'true'\n query = Metric.query.filter_by(is_active=is_active)\n if frequency is not None:\n try:\n frequency = Frequency.from_name(frequency)\n except ValueError as e:\n msg = (\n f\"Invalid 'frequency': {frequency}. Use one of {Frequency.values()}\"\n )\n abort(400, message=msg)\n query = query.filter_by(frequency=frequency)\n if threshold_type is not None:\n try:\n threshold_type = ThresholdType.from_name(threshold_type)\n except ValueError as e:\n msg = (\n f\"Invalid 'threshold_type': {threshold_type}. Use one of {ThresholdType.values()}\"\n )\n abort(400, message=msg)\n query = query.filter_by(threshold_type=threshold_type)\n if sort is not None and sort.lstrip('-') == 'metric_id':\n query = query.order_by(Metric.metric_id.desc())\n else:\n query = query.order_by(Metric.metric_id)\n return query\n\n def post(self):\n \"\"\"\n Implements the POST method for endpoint \"/metrics\". It should be used to create a\n new metric.\n\n :return: the metric as a json created in the database (in case of success)\n \"\"\"\n json_data = request.get_json(force=True)\n if not json_data:\n abort(400, message='No input data provided')\n json_data['metric_id'] = 'TBD'\n json_data['metric_type'] = 'model'\n new_metric = self.load(json_data, session=db.session)\n try:\n db.session.add(new_metric)\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n result = self.schema.dump(new_metric)\n return success(result, code=201)\n\n\nclass QuantModelMetricsResource(MetricsResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/quant_model/metrics/{metric_id}\".\n\n This subclass uses almost everything from the base class, it only needs to specify the\n appropriate schemas in the constructor, and to override the build_query method so that\n the appropriate metric_type is filtered and the remaining query parameters (specific\n to this endpoint) are processed.\n\n Implemented Query Parameters:\n - asset_class: to filter results by a given asset class.\n - model_name: to filter results by a given model name.\n - pricing_library: to filter results for a given pricing library.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = QuantModelMetricSchema()\n schema_collection = QuantModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n def build_query(self):\n \"\"\"\n Override method to include specific query parameters to this model endpoint.\n \"\"\"\n query = super().build_query()\n query = query.filter(Metric.metric_id == QuantModelMetric.metric_id)\n asset_class = request.args.get('asset_class')\n model_name = request.args.get('model_name')\n pricing_library = request.args.get('pricing_library')\n if asset_class is not None:\n query = query.filter(QuantModelMetric.asset_class == asset_class)\n if model_name is not None:\n query = query.filter(QuantModelMetric.model_name == model_name)\n if pricing_library is not None:\n query = query.filter(QuantModelMetric.pricing_library ==\n pricing_library)\n return query\n\n\nclass MlModelMetricsResource(MetricsResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses almost everything from the base class, it only needs to specify the\n appropriate schemas in the constructor, and to override the build_query method so that\n the appropriate metric_type is filtered and the remaining query parameters (specific\n to this endpoint) are processed.\n\n Implemented Query Parameters:\n - algorithm: to filter results by a given algorithm.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n def build_query(self):\n \"\"\"\n Override method to include specific query parameters to this ml_model\n endpoint.\n \"\"\"\n query = super().build_query()\n query = query.filter(Metric.metric_id == MlModelMetric.metric_id)\n algorithm = request.args.get('algorithm')\n if algorithm is not None:\n query = query.filter(MlModelMetric.algorithm == algorithm)\n return query\n\n\nclass MetricResource(BaseResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint \"/metrics/{metric_id}\".\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def get(self, metric_id):\n \"\"\"\n Implements the GET method for endpoint \"/metrics/{metric_id}\". It should be used\n to get a single metric from the database.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the json object of metric found in the database (if it exists)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n return self.schema.jsonify(metric)\n\n def put(self, metric_id):\n \"\"\"\n Implements the PUT method for endpoint \"/metrics/{metric_id}\". It should be used\n to update a metric.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the update (in case of success)\n \"\"\"\n json_data = request.get_json(force=True)\n if not json_data:\n abort(400, message='No input data provided')\n metric = get_metric_by_id(metric_id)\n self.load(json_data, metric, db.session, partial=True)\n try:\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(json_data)\n\n def delete(self, metric_id):\n \"\"\"\n Implements the DELETE method for endpoint \"/metrics/{metric_id}\". It should be\n used to delete a metric result matching the provided metric_id and cob_date.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the delete (in case of success)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n result = self.schema.dump(metric)\n try:\n db.session.delete(metric)\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(result)\n\n\nclass QuantModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/quant_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = QuantModelMetricSchema()\n schema_collection = QuantModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n\nclass MlModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n", "step-4": "from flask import request\nfrom flask_restful import abort\nfrom sqlalchemy.exc import SQLAlchemyError\nfrom gm.main.models.model import db, Metric, QuantModelMetricSchema, MlModelMetricSchema, Frequency, QuantModelMetric, MlModelMetric, ThresholdType\nfrom gm.main.resources import success, get_metric_by_id, BaseResource\n\n\nclass MetricsResource(BaseResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint \"/metrics\".\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def get(self):\n \"\"\"\n Implements the GET method for endpoint \"/metrics\". By default the results are\n order by 'metric_id' ascending.\n\n Implemented Query Parameters:\n - is_active: to filter results that are either active or inactive. Boolean and\n case insensitive.\n - frequency: filter results based on a metric frequency. Values of this enum must\n be respected. Case insensitive.\n - threshold_type: filter results based on a metric threshold type. Values of this\n enum must be respected. Case insensitive.\n - sort: allows one to order the resulting collecting by 'metric_id' in descending\n order. This should be done by specifying the query parameter as \"sort=-metric_id\".\n Case insensitive.\n\n Note: if unknown query parameters are given these will be ignored.\n\n :return: a collection of metrics\n \"\"\"\n query = self.build_query()\n metrics = query.all()\n result = self.schema_collection.dump(metrics)\n return success(result)\n\n def build_query(self):\n \"\"\"\n Builds the query (without executing it) to the be used in the GET method.\n :return: query with all the query conditions specified for obtaining the metrics\n that are in the database and respect the desired filters (query parameters).\n \"\"\"\n query = Metric.query.filter(Metric.metric_type == self.metric_type)\n is_active = request.args.get('is_active')\n frequency = request.args.get('frequency')\n threshold_type = request.args.get('threshold_type')\n sort = request.args.get('sort')\n if is_active is not None:\n is_active = is_active.lower() == 'true'\n query = Metric.query.filter_by(is_active=is_active)\n if frequency is not None:\n try:\n frequency = Frequency.from_name(frequency)\n except ValueError as e:\n msg = (\n f\"Invalid 'frequency': {frequency}. Use one of {Frequency.values()}\"\n )\n abort(400, message=msg)\n query = query.filter_by(frequency=frequency)\n if threshold_type is not None:\n try:\n threshold_type = ThresholdType.from_name(threshold_type)\n except ValueError as e:\n msg = (\n f\"Invalid 'threshold_type': {threshold_type}. Use one of {ThresholdType.values()}\"\n )\n abort(400, message=msg)\n query = query.filter_by(threshold_type=threshold_type)\n if sort is not None and sort.lstrip('-') == 'metric_id':\n query = query.order_by(Metric.metric_id.desc())\n else:\n query = query.order_by(Metric.metric_id)\n return query\n\n def post(self):\n \"\"\"\n Implements the POST method for endpoint \"/metrics\". It should be used to create a\n new metric.\n\n :return: the metric as a json created in the database (in case of success)\n \"\"\"\n json_data = request.get_json(force=True)\n if not json_data:\n abort(400, message='No input data provided')\n json_data['metric_id'] = 'TBD'\n json_data['metric_type'] = 'model'\n new_metric = self.load(json_data, session=db.session)\n try:\n db.session.add(new_metric)\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n result = self.schema.dump(new_metric)\n return success(result, code=201)\n\n\nclass QuantModelMetricsResource(MetricsResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/quant_model/metrics/{metric_id}\".\n\n This subclass uses almost everything from the base class, it only needs to specify the\n appropriate schemas in the constructor, and to override the build_query method so that\n the appropriate metric_type is filtered and the remaining query parameters (specific\n to this endpoint) are processed.\n\n Implemented Query Parameters:\n - asset_class: to filter results by a given asset class.\n - model_name: to filter results by a given model name.\n - pricing_library: to filter results for a given pricing library.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = QuantModelMetricSchema()\n schema_collection = QuantModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n def build_query(self):\n \"\"\"\n Override method to include specific query parameters to this model endpoint.\n \"\"\"\n query = super().build_query()\n query = query.filter(Metric.metric_id == QuantModelMetric.metric_id)\n asset_class = request.args.get('asset_class')\n model_name = request.args.get('model_name')\n pricing_library = request.args.get('pricing_library')\n if asset_class is not None:\n query = query.filter(QuantModelMetric.asset_class == asset_class)\n if model_name is not None:\n query = query.filter(QuantModelMetric.model_name == model_name)\n if pricing_library is not None:\n query = query.filter(QuantModelMetric.pricing_library ==\n pricing_library)\n return query\n\n\nclass MlModelMetricsResource(MetricsResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses almost everything from the base class, it only needs to specify the\n appropriate schemas in the constructor, and to override the build_query method so that\n the appropriate metric_type is filtered and the remaining query parameters (specific\n to this endpoint) are processed.\n\n Implemented Query Parameters:\n - algorithm: to filter results by a given algorithm.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, POST\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n def build_query(self):\n \"\"\"\n Override method to include specific query parameters to this ml_model\n endpoint.\n \"\"\"\n query = super().build_query()\n query = query.filter(Metric.metric_id == MlModelMetric.metric_id)\n algorithm = request.args.get('algorithm')\n if algorithm is not None:\n query = query.filter(MlModelMetric.algorithm == algorithm)\n return query\n\n\nclass MetricResource(BaseResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint \"/metrics/{metric_id}\".\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def get(self, metric_id):\n \"\"\"\n Implements the GET method for endpoint \"/metrics/{metric_id}\". It should be used\n to get a single metric from the database.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the json object of metric found in the database (if it exists)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n return self.schema.jsonify(metric)\n\n def put(self, metric_id):\n \"\"\"\n Implements the PUT method for endpoint \"/metrics/{metric_id}\". It should be used\n to update a metric.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the update (in case of success)\n \"\"\"\n json_data = request.get_json(force=True)\n if not json_data:\n abort(400, message='No input data provided')\n metric = get_metric_by_id(metric_id)\n self.load(json_data, metric, db.session, partial=True)\n try:\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(json_data)\n\n def delete(self, metric_id):\n \"\"\"\n Implements the DELETE method for endpoint \"/metrics/{metric_id}\". It should be\n used to delete a metric result matching the provided metric_id and cob_date.\n\n :param metric_id: the metric_id associated with this endpoint\n :return: the metric as a json after the delete (in case of success)\n \"\"\"\n metric = get_metric_by_id(metric_id)\n result = self.schema.dump(metric)\n try:\n db.session.delete(metric)\n db.session.commit()\n except SQLAlchemyError as e:\n abort(400, message=f'Database error. Reason: {e}')\n return success(result)\n\n\nclass QuantModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/quant_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = QuantModelMetricSchema()\n schema_collection = QuantModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n\n\nclass MlModelMetricResource(MetricResource):\n \"\"\"\n This resource handles the HTTP requests coming to the endpoint\n \"/ml_model/metrics/{metric_id}\".\n\n This subclass uses everything from the base class and only needs to specify the\n appropriate schemas in the constructor.\n\n Note: no trailing slash (\"/\") should be used.\n\n Accepted HTTP methods: GET, PUT, DELETE\n \"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\n Initialize schemas with appropriate classes.\n\n :param kwargs: pass through to base constructor (service and metric_type)\n \"\"\"\n schema = MlModelMetricSchema()\n schema_collection = MlModelMetricSchema(many=True)\n super().__init__(schema, schema_collection, **kwargs)\n", "step-5": "from flask import request\r\nfrom flask_restful import abort\r\nfrom sqlalchemy.exc import SQLAlchemyError\r\n\r\nfrom gm.main.models.model import db, Metric, QuantModelMetricSchema, \\\r\n MlModelMetricSchema, Frequency, QuantModelMetric, MlModelMetric, \\\r\n ThresholdType\r\nfrom gm.main.resources import success, get_metric_by_id, BaseResource\r\n\r\n\r\nclass MetricsResource(BaseResource):\r\n \"\"\"\r\n This resource handles the HTTP requests coming to the endpoint \"/metrics\".\r\n\r\n Note: no trailing slash (\"/\") should be used.\r\n\r\n Accepted HTTP methods: GET, POST\r\n \"\"\"\r\n\r\n def get(self):\r\n \"\"\"\r\n Implements the GET method for endpoint \"/metrics\". By default the results are\r\n order by 'metric_id' ascending.\r\n\r\n Implemented Query Parameters:\r\n - is_active: to filter results that are either active or inactive. Boolean and\r\n case insensitive.\r\n - frequency: filter results based on a metric frequency. Values of this enum must\r\n be respected. Case insensitive.\r\n - threshold_type: filter results based on a metric threshold type. Values of this\r\n enum must be respected. Case insensitive.\r\n - sort: allows one to order the resulting collecting by 'metric_id' in descending\r\n order. This should be done by specifying the query parameter as \"sort=-metric_id\".\r\n Case insensitive.\r\n\r\n Note: if unknown query parameters are given these will be ignored.\r\n\r\n :return: a collection of metrics\r\n \"\"\"\r\n query = self.build_query()\r\n metrics = query.all()\r\n result = self.schema_collection.dump(metrics)\r\n return success(result)\r\n\r\n def build_query(self):\r\n \"\"\"\r\n Builds the query (without executing it) to the be used in the GET method.\r\n :return: query with all the query conditions specified for obtaining the metrics\r\n that are in the database and respect the desired filters (query parameters).\r\n \"\"\"\r\n\r\n # this filter is required\r\n query = Metric.query.filter(Metric.metric_type == self.metric_type)\r\n\r\n # get query parameters (parameters which are not here are ignored)\r\n is_active = request.args.get('is_active')\r\n frequency = request.args.get('frequency')\r\n threshold_type = request.args.get('threshold_type')\r\n sort = request.args.get('sort')\r\n\r\n # process each parameter, and if valid add it as a query condition\r\n if is_active is not None:\r\n is_active = is_active.lower() == 'true'\r\n query = Metric.query.filter_by(is_active=is_active)\r\n if frequency is not None:\r\n try:\r\n frequency = Frequency.from_name(frequency)\r\n except ValueError as e:\r\n msg = f\"Invalid 'frequency': {frequency}. Use one of {Frequency.values()}\"\r\n abort(400, message=msg)\r\n query = query.filter_by(frequency=frequency)\r\n if threshold_type is not None:\r\n try:\r\n threshold_type = ThresholdType.from_name(threshold_type)\r\n except ValueError as e:\r\n msg = f\"Invalid 'threshold_type': {threshold_type}. Use one of \" \\\r\n f\"{ThresholdType.values()}\"\r\n abort(400, message=msg)\r\n query = query.filter_by(threshold_type=threshold_type)\r\n if sort is not None and sort.lstrip(\"-\") == 'metric_id':\r\n query = query.order_by(Metric.metric_id.desc())\r\n else:\r\n query = query.order_by(Metric.metric_id)\r\n\r\n return query\r\n\r\n\r\n def post(self):\r\n \"\"\"\r\n Implements the POST method for endpoint \"/metrics\". It should be used to create a\r\n new metric.\r\n\r\n :return: the metric as a json created in the database (in case of success)\r\n \"\"\"\r\n json_data = request.get_json(force=True)\r\n if not json_data:\r\n abort(400, message='No input data provided')\r\n # make sure the metric_id (temporary) and metric_type (model) are filled\r\n json_data[\"metric_id\"] = \"TBD\"\r\n json_data[\"metric_type\"] = \"model\"\r\n\r\n # validate and deserialize input\r\n new_metric = self.load(json_data, session=db.session)\r\n\r\n # get the next metric id and update metric object\r\n try:\r\n db.session.add(new_metric)\r\n db.session.commit()\r\n except SQLAlchemyError as e:\r\n abort(400, message=f'Database error. Reason: {e}')\r\n\r\n # dump to json and return result\r\n result = self.schema.dump(new_metric)\r\n return success(result, code=201)\r\n\r\n\r\nclass QuantModelMetricsResource(MetricsResource):\r\n \"\"\"\r\n This resource handles the HTTP requests coming to the endpoint\r\n \"/quant_model/metrics/{metric_id}\".\r\n\r\n This subclass uses almost everything from the base class, it only needs to specify the\r\n appropriate schemas in the constructor, and to override the build_query method so that\r\n the appropriate metric_type is filtered and the remaining query parameters (specific\r\n to this endpoint) are processed.\r\n\r\n Implemented Query Parameters:\r\n - asset_class: to filter results by a given asset class.\r\n - model_name: to filter results by a given model name.\r\n - pricing_library: to filter results for a given pricing library.\r\n\r\n Note: no trailing slash (\"/\") should be used.\r\n\r\n Accepted HTTP methods: GET, POST\r\n \"\"\"\r\n\r\n def __init__(self, **kwargs):\r\n \"\"\"\r\n Initialize schemas with appropriate classes.\r\n\r\n :param kwargs: pass through to base constructor (service and metric_type)\r\n \"\"\"\r\n schema = QuantModelMetricSchema()\r\n schema_collection = QuantModelMetricSchema(many=True)\r\n super().__init__(schema, schema_collection, **kwargs)\r\n\r\n def build_query(self):\r\n \"\"\"\r\n Override method to include specific query parameters to this model endpoint.\r\n \"\"\"\r\n # build query from base class add required field for joining with parent\r\n query = super().build_query()\r\n query = query.filter(Metric.metric_id == QuantModelMetric.metric_id)\r\n\r\n # get the remaining query parameters\r\n asset_class = request.args.get('asset_class')\r\n model_name = request.args.get('model_name')\r\n pricing_library = request.args.get('pricing_library')\r\n\r\n # process each parameter and, if valid, add as a query condition\r\n if asset_class is not None:\r\n query = query.filter(QuantModelMetric.asset_class == asset_class)\r\n if model_name is not None:\r\n query = query.filter(QuantModelMetric.model_name == model_name)\r\n if pricing_library is not None:\r\n query = query.filter(QuantModelMetric.pricing_library == pricing_library)\r\n return query\r\n\r\n\r\nclass MlModelMetricsResource(MetricsResource):\r\n \"\"\"\r\n This resource handles the HTTP requests coming to the endpoint\r\n \"/ml_model/metrics/{metric_id}\".\r\n\r\n This subclass uses almost everything from the base class, it only needs to specify the\r\n appropriate schemas in the constructor, and to override the build_query method so that\r\n the appropriate metric_type is filtered and the remaining query parameters (specific\r\n to this endpoint) are processed.\r\n\r\n Implemented Query Parameters:\r\n - algorithm: to filter results by a given algorithm.\r\n\r\n Note: no trailing slash (\"/\") should be used.\r\n\r\n Accepted HTTP methods: GET, POST\r\n \"\"\"\r\n\r\n def __init__(self, **kwargs):\r\n \"\"\"\r\n Initialize schemas with appropriate classes.\r\n\r\n :param kwargs: pass through to base constructor (service and metric_type)\r\n \"\"\"\r\n schema = MlModelMetricSchema()\r\n schema_collection = MlModelMetricSchema(many=True)\r\n super().__init__(schema, schema_collection, **kwargs)\r\n\r\n def build_query(self):\r\n \"\"\"\r\n Override method to include specific query parameters to this ml_model\r\n endpoint.\r\n \"\"\"\r\n query = super().build_query()\r\n query = query.filter(Metric.metric_id == MlModelMetric.metric_id)\r\n algorithm = request.args.get('algorithm')\r\n if algorithm is not None:\r\n query = query.filter(MlModelMetric.algorithm == algorithm)\r\n return query\r\n\r\n\r\nclass MetricResource(BaseResource):\r\n \"\"\"\r\n This resource handles the HTTP requests coming to the endpoint \"/metrics/{metric_id}\".\r\n\r\n Note: no trailing slash (\"/\") should be used.\r\n\r\n Accepted HTTP methods: GET, PUT, DELETE\r\n \"\"\"\r\n\r\n def get(self, metric_id):\r\n \"\"\"\r\n Implements the GET method for endpoint \"/metrics/{metric_id}\". It should be used\r\n to get a single metric from the database.\r\n\r\n :param metric_id: the metric_id associated with this endpoint\r\n :return: the json object of metric found in the database (if it exists)\r\n \"\"\"\r\n metric = get_metric_by_id(metric_id)\r\n return self.schema.jsonify(metric)\r\n\r\n def put(self, metric_id):\r\n \"\"\"\r\n Implements the PUT method for endpoint \"/metrics/{metric_id}\". It should be used\r\n to update a metric.\r\n\r\n :param metric_id: the metric_id associated with this endpoint\r\n :return: the metric as a json after the update (in case of success)\r\n \"\"\"\r\n json_data = request.get_json(force=True)\r\n if not json_data:\r\n abort(400, message='No input data provided')\r\n\r\n # Validate and deserialize input\r\n metric = get_metric_by_id(metric_id)\r\n self.load(json_data, metric, db.session, partial=True)\r\n\r\n # if it was found and deserialized successfully try to commit\r\n try:\r\n db.session.commit()\r\n except SQLAlchemyError as e:\r\n abort(400, message=f'Database error. Reason: {e}')\r\n\r\n return success(json_data)\r\n\r\n def delete(self, metric_id):\r\n \"\"\"\r\n Implements the DELETE method for endpoint \"/metrics/{metric_id}\". It should be\r\n used to delete a metric result matching the provided metric_id and cob_date.\r\n\r\n :param metric_id: the metric_id associated with this endpoint\r\n :return: the metric as a json after the delete (in case of success)\r\n \"\"\"\r\n metric = get_metric_by_id(metric_id)\r\n # dump as json to send in the end if del is successful\r\n result = self.schema.dump(metric)\r\n\r\n # if result was found, delete it from database\r\n try:\r\n db.session.delete(metric)\r\n db.session.commit()\r\n except SQLAlchemyError as e:\r\n abort(400, message=f'Database error. Reason: {e}')\r\n return success(result)\r\n\r\n\r\nclass QuantModelMetricResource(MetricResource):\r\n \"\"\"\r\n This resource handles the HTTP requests coming to the endpoint\r\n \"/quant_model/metrics/{metric_id}\".\r\n\r\n This subclass uses everything from the base class and only needs to specify the\r\n appropriate schemas in the constructor.\r\n\r\n Note: no trailing slash (\"/\") should be used.\r\n\r\n Accepted HTTP methods: GET, PUT, DELETE\r\n \"\"\"\r\n\r\n def __init__(self, **kwargs):\r\n \"\"\"\r\n Initialize schemas with appropriate classes.\r\n\r\n :param kwargs: pass through to base constructor (service and metric_type)\r\n \"\"\"\r\n schema = QuantModelMetricSchema()\r\n schema_collection = QuantModelMetricSchema(many=True)\r\n super().__init__(schema, schema_collection, **kwargs)\r\n\r\n\r\nclass MlModelMetricResource(MetricResource):\r\n \"\"\"\r\n This resource handles the HTTP requests coming to the endpoint\r\n \"/ml_model/metrics/{metric_id}\".\r\n\r\n This subclass uses everything from the base class and only needs to specify the\r\n appropriate schemas in the constructor.\r\n\r\n Note: no trailing slash (\"/\") should be used.\r\n\r\n Accepted HTTP methods: GET, PUT, DELETE\r\n \"\"\"\r\n\r\n def __init__(self, **kwargs):\r\n \"\"\"\r\n Initialize schemas with appropriate classes.\r\n\r\n :param kwargs: pass through to base constructor (service and metric_type)\r\n \"\"\"\r\n schema = MlModelMetricSchema()\r\n schema_collection = MlModelMetricSchema(many=True)\r\n super().__init__(schema, schema_collection, **kwargs)", "step-ids": [ 16, 19, 23, 25, 26 ] }
[ 16, 19, 23, 25, 26 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> PULPNNInstallPath = cwd = os.getcwd() + '/../' PULPNNSrcDirs = {'script': PULPNNInstallPath + 'scripts/'} PULPNNInstallPath32bit = cwd = os.getcwd() + '/../32bit/' PULPNNInstallPath64bit = cwd = os.getcwd() + '/../64bit/' PULPNNTestFolder32bit = PULPNNInstallPath32bit + 'test/' PULPNNTestFolder64bit = PULPNNInstallPath64bit + 'test/' PULPNNSrcDirs32bit = {'pulp_nn_inc': PULPNNInstallPath32bit + 'include/', 'pulp_nn_pointwise_convolution': PULPNNInstallPath32bit + 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath32bit + 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': PULPNNInstallPath32bit + 'src/DepthwiseConvolutions/', 'pulp_nn_linear_convolution_nq': PULPNNInstallPath32bit + 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': PULPNNInstallPath32bit + 'src/LinearConvolutionsQuant/', 'pulp_nn_support_function': PULPNNInstallPath32bit + 'src/SupportFunctions/', 'include': PULPNNTestFolder32bit + 'include/', 'src': PULPNNTestFolder32bit + 'src/', 'pointwise_convolution': PULPNNTestFolder32bit + 'src/StandardConvolutions/', 'matmul': PULPNNTestFolder32bit + 'src/MatrixMultiplications/', 'depthwise_convolution': PULPNNTestFolder32bit + 'src/DepthwiseConvolutions/', 'linear_convolution_nq': PULPNNTestFolder32bit + 'src/LinearConvolutionsNoQuant/', 'linear_convolution_q': PULPNNTestFolder32bit + 'src/LinearConvolutionsQuant/', 'support_function': PULPNNTestFolder32bit + 'src/SupportFunctions/', 'data_allocation_pw': PULPNNTestFolder32bit + 'include/DataAllocationStandardConvolutions/', 'data_allocation_dw': PULPNNTestFolder32bit + 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq': PULPNNTestFolder32bit + 'include/DataAllocationLinearConvolutionsNoQuant/', 'data_allocation_ln_q': PULPNNTestFolder32bit + 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': PULPNNTestFolder32bit + 'include/GoldenModelStandardConvolutions/', 'golden_model_dw': PULPNNTestFolder32bit + 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': PULPNNTestFolder32bit + 'include/GoldenModelLinearConvolutionsNoQuant/', 'golden_model_ln_q': PULPNNTestFolder32bit + 'include/GoldenModelLinearConvolutionsQuant/', 'test': PULPNNTestFolder32bit} PULPNNSrcDirs64bit = {'pulp_nn_inc': PULPNNInstallPath64bit + 'include/', 'pulp_nn_pointwise_convolution': PULPNNInstallPath64bit + 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath64bit + 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': PULPNNInstallPath64bit + 'src/DepthwiseConvolutions/', 'pulp_nn_linear_convolution_nq': PULPNNInstallPath64bit + 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': PULPNNInstallPath64bit + 'src/LinearConvolutionsQuant/', 'pulp_nn_support_function': PULPNNInstallPath64bit + 'src/SupportFunctions/', 'include': PULPNNTestFolder64bit + 'include/', 'src': PULPNNTestFolder64bit + 'src/', 'pointwise_convolution': PULPNNTestFolder64bit + 'src/StandardConvolutions/', 'matmul': PULPNNTestFolder64bit + 'src/MatrixMultiplications/', 'depthwise_convolution': PULPNNTestFolder64bit + 'src/DepthwiseConvolutions/', 'linear_convolution_nq': PULPNNTestFolder64bit + 'src/LinearConvolutionsNoQuant/', 'linear_convolution_q': PULPNNTestFolder64bit + 'src/LinearConvolutionsQuant/', 'support_function': PULPNNTestFolder64bit + 'src/SupportFunctions/', 'data_allocation_pw': PULPNNTestFolder64bit + 'include/DataAllocationStandardConvolutions/', 'data_allocation_dw': PULPNNTestFolder64bit + 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq': PULPNNTestFolder64bit + 'include/DataAllocationLinearConvolutionsNoQuant/', 'data_allocation_ln_q': PULPNNTestFolder64bit + 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': PULPNNTestFolder64bit + 'include/GoldenModelStandardConvolutions/', 'golden_model_dw': PULPNNTestFolder64bit + 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': PULPNNTestFolder64bit + 'include/GoldenModelLinearConvolutionsNoQuant/', 'golden_model_ln_q': PULPNNTestFolder64bit + 'include/GoldenModelLinearConvolutionsQuant/', 'test': PULPNNTestFolder64bit} <|reserved_special_token_1|> import os PULPNNInstallPath = cwd = os.getcwd() + '/../' PULPNNSrcDirs = {'script': PULPNNInstallPath + 'scripts/'} PULPNNInstallPath32bit = cwd = os.getcwd() + '/../32bit/' PULPNNInstallPath64bit = cwd = os.getcwd() + '/../64bit/' PULPNNTestFolder32bit = PULPNNInstallPath32bit + 'test/' PULPNNTestFolder64bit = PULPNNInstallPath64bit + 'test/' PULPNNSrcDirs32bit = {'pulp_nn_inc': PULPNNInstallPath32bit + 'include/', 'pulp_nn_pointwise_convolution': PULPNNInstallPath32bit + 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath32bit + 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': PULPNNInstallPath32bit + 'src/DepthwiseConvolutions/', 'pulp_nn_linear_convolution_nq': PULPNNInstallPath32bit + 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': PULPNNInstallPath32bit + 'src/LinearConvolutionsQuant/', 'pulp_nn_support_function': PULPNNInstallPath32bit + 'src/SupportFunctions/', 'include': PULPNNTestFolder32bit + 'include/', 'src': PULPNNTestFolder32bit + 'src/', 'pointwise_convolution': PULPNNTestFolder32bit + 'src/StandardConvolutions/', 'matmul': PULPNNTestFolder32bit + 'src/MatrixMultiplications/', 'depthwise_convolution': PULPNNTestFolder32bit + 'src/DepthwiseConvolutions/', 'linear_convolution_nq': PULPNNTestFolder32bit + 'src/LinearConvolutionsNoQuant/', 'linear_convolution_q': PULPNNTestFolder32bit + 'src/LinearConvolutionsQuant/', 'support_function': PULPNNTestFolder32bit + 'src/SupportFunctions/', 'data_allocation_pw': PULPNNTestFolder32bit + 'include/DataAllocationStandardConvolutions/', 'data_allocation_dw': PULPNNTestFolder32bit + 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq': PULPNNTestFolder32bit + 'include/DataAllocationLinearConvolutionsNoQuant/', 'data_allocation_ln_q': PULPNNTestFolder32bit + 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': PULPNNTestFolder32bit + 'include/GoldenModelStandardConvolutions/', 'golden_model_dw': PULPNNTestFolder32bit + 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': PULPNNTestFolder32bit + 'include/GoldenModelLinearConvolutionsNoQuant/', 'golden_model_ln_q': PULPNNTestFolder32bit + 'include/GoldenModelLinearConvolutionsQuant/', 'test': PULPNNTestFolder32bit} PULPNNSrcDirs64bit = {'pulp_nn_inc': PULPNNInstallPath64bit + 'include/', 'pulp_nn_pointwise_convolution': PULPNNInstallPath64bit + 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath64bit + 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': PULPNNInstallPath64bit + 'src/DepthwiseConvolutions/', 'pulp_nn_linear_convolution_nq': PULPNNInstallPath64bit + 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': PULPNNInstallPath64bit + 'src/LinearConvolutionsQuant/', 'pulp_nn_support_function': PULPNNInstallPath64bit + 'src/SupportFunctions/', 'include': PULPNNTestFolder64bit + 'include/', 'src': PULPNNTestFolder64bit + 'src/', 'pointwise_convolution': PULPNNTestFolder64bit + 'src/StandardConvolutions/', 'matmul': PULPNNTestFolder64bit + 'src/MatrixMultiplications/', 'depthwise_convolution': PULPNNTestFolder64bit + 'src/DepthwiseConvolutions/', 'linear_convolution_nq': PULPNNTestFolder64bit + 'src/LinearConvolutionsNoQuant/', 'linear_convolution_q': PULPNNTestFolder64bit + 'src/LinearConvolutionsQuant/', 'support_function': PULPNNTestFolder64bit + 'src/SupportFunctions/', 'data_allocation_pw': PULPNNTestFolder64bit + 'include/DataAllocationStandardConvolutions/', 'data_allocation_dw': PULPNNTestFolder64bit + 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq': PULPNNTestFolder64bit + 'include/DataAllocationLinearConvolutionsNoQuant/', 'data_allocation_ln_q': PULPNNTestFolder64bit + 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': PULPNNTestFolder64bit + 'include/GoldenModelStandardConvolutions/', 'golden_model_dw': PULPNNTestFolder64bit + 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': PULPNNTestFolder64bit + 'include/GoldenModelLinearConvolutionsNoQuant/', 'golden_model_ln_q': PULPNNTestFolder64bit + 'include/GoldenModelLinearConvolutionsQuant/', 'test': PULPNNTestFolder64bit} <|reserved_special_token_1|> # # struct_test.py # Nazareno Bruschi <nazareno.bruschi@unibo.it> # # Copyright (C) 2019-2020 University of Bologna # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os PULPNNInstallPath = cwd = os.getcwd() + "/../" PULPNNSrcDirs = {'script': PULPNNInstallPath + "scripts/"} PULPNNInstallPath32bit = cwd = os.getcwd() + "/../32bit/" PULPNNInstallPath64bit = cwd = os.getcwd() + "/../64bit/" PULPNNTestFolder32bit = PULPNNInstallPath32bit + "test/" PULPNNTestFolder64bit = PULPNNInstallPath64bit + "test/" PULPNNSrcDirs32bit = {'pulp_nn_inc': PULPNNInstallPath32bit + "include/", 'pulp_nn_pointwise_convolution': PULPNNInstallPath32bit + "src/StandardConvolutions/", 'pulp_nn_matmul': PULPNNInstallPath32bit + "src/MatrixMultiplications/", 'pulp_nn_depthwise_convolution': PULPNNInstallPath32bit + "src/DepthwiseConvolutions/", 'pulp_nn_linear_convolution_nq': PULPNNInstallPath32bit + "src/LinearConvolutionsNoQuant/", 'pulp_nn_linear_convolution_q': PULPNNInstallPath32bit + "src/LinearConvolutionsQuant/", 'pulp_nn_support_function': PULPNNInstallPath32bit + "src/SupportFunctions/", 'include': PULPNNTestFolder32bit + "include/", 'src': PULPNNTestFolder32bit + "src/", 'pointwise_convolution': PULPNNTestFolder32bit + "src/StandardConvolutions/", 'matmul': PULPNNTestFolder32bit + "src/MatrixMultiplications/", 'depthwise_convolution': PULPNNTestFolder32bit + "src/DepthwiseConvolutions/", 'linear_convolution_nq': PULPNNTestFolder32bit + "src/LinearConvolutionsNoQuant/", 'linear_convolution_q': PULPNNTestFolder32bit + "src/LinearConvolutionsQuant/", 'support_function': PULPNNTestFolder32bit + "src/SupportFunctions/", 'data_allocation_pw': PULPNNTestFolder32bit + "include/DataAllocationStandardConvolutions/", 'data_allocation_dw': PULPNNTestFolder32bit + "include/DataAllocationDepthwiseConvolutions/", 'data_allocation_ln_nq': PULPNNTestFolder32bit + "include/DataAllocationLinearConvolutionsNoQuant/", 'data_allocation_ln_q': PULPNNTestFolder32bit + "include/DataAllocationLinearConvolutionsQuant/", 'golden_model_pw': PULPNNTestFolder32bit + "include/GoldenModelStandardConvolutions/", 'golden_model_dw': PULPNNTestFolder32bit + "include/GoldenModelDepthwiseConvolutions/", 'golden_model_ln_nq': PULPNNTestFolder32bit + "include/GoldenModelLinearConvolutionsNoQuant/", 'golden_model_ln_q': PULPNNTestFolder32bit + "include/GoldenModelLinearConvolutionsQuant/", 'test': PULPNNTestFolder32bit} PULPNNSrcDirs64bit = {'pulp_nn_inc': PULPNNInstallPath64bit + "include/", 'pulp_nn_pointwise_convolution': PULPNNInstallPath64bit + "src/StandardConvolutions/", 'pulp_nn_matmul': PULPNNInstallPath64bit + "src/MatrixMultiplications/", 'pulp_nn_depthwise_convolution': PULPNNInstallPath64bit + "src/DepthwiseConvolutions/", 'pulp_nn_linear_convolution_nq': PULPNNInstallPath64bit + "src/LinearConvolutionsNoQuant/", 'pulp_nn_linear_convolution_q': PULPNNInstallPath64bit + "src/LinearConvolutionsQuant/", 'pulp_nn_support_function': PULPNNInstallPath64bit + "src/SupportFunctions/", 'include': PULPNNTestFolder64bit + "include/", 'src': PULPNNTestFolder64bit + "src/", 'pointwise_convolution': PULPNNTestFolder64bit + "src/StandardConvolutions/", 'matmul': PULPNNTestFolder64bit + "src/MatrixMultiplications/", 'depthwise_convolution': PULPNNTestFolder64bit + "src/DepthwiseConvolutions/", 'linear_convolution_nq': PULPNNTestFolder64bit + "src/LinearConvolutionsNoQuant/", 'linear_convolution_q': PULPNNTestFolder64bit + "src/LinearConvolutionsQuant/", 'support_function': PULPNNTestFolder64bit + "src/SupportFunctions/", 'data_allocation_pw': PULPNNTestFolder64bit + "include/DataAllocationStandardConvolutions/", 'data_allocation_dw': PULPNNTestFolder64bit + "include/DataAllocationDepthwiseConvolutions/", 'data_allocation_ln_nq': PULPNNTestFolder64bit + "include/DataAllocationLinearConvolutionsNoQuant/", 'data_allocation_ln_q': PULPNNTestFolder64bit + "include/DataAllocationLinearConvolutionsQuant/", 'golden_model_pw': PULPNNTestFolder64bit + "include/GoldenModelStandardConvolutions/", 'golden_model_dw': PULPNNTestFolder64bit + "include/GoldenModelDepthwiseConvolutions/", 'golden_model_ln_nq': PULPNNTestFolder64bit + "include/GoldenModelLinearConvolutionsNoQuant/", 'golden_model_ln_q': PULPNNTestFolder64bit + "include/GoldenModelLinearConvolutionsQuant/", 'test': PULPNNTestFolder64bit}
flexible
{ "blob_id": "d8d0c181fcfc9e0692369cc7a65259c43a68e931", "index": 5688, "step-1": "<mask token>\n", "step-2": "<mask token>\nPULPNNInstallPath = cwd = os.getcwd() + '/../'\nPULPNNSrcDirs = {'script': PULPNNInstallPath + 'scripts/'}\nPULPNNInstallPath32bit = cwd = os.getcwd() + '/../32bit/'\nPULPNNInstallPath64bit = cwd = os.getcwd() + '/../64bit/'\nPULPNNTestFolder32bit = PULPNNInstallPath32bit + 'test/'\nPULPNNTestFolder64bit = PULPNNInstallPath64bit + 'test/'\nPULPNNSrcDirs32bit = {'pulp_nn_inc': PULPNNInstallPath32bit + 'include/',\n 'pulp_nn_pointwise_convolution': PULPNNInstallPath32bit +\n 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath32bit +\n 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': \n PULPNNInstallPath32bit + 'src/DepthwiseConvolutions/',\n 'pulp_nn_linear_convolution_nq': PULPNNInstallPath32bit +\n 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': \n PULPNNInstallPath32bit + 'src/LinearConvolutionsQuant/',\n 'pulp_nn_support_function': PULPNNInstallPath32bit +\n 'src/SupportFunctions/', 'include': PULPNNTestFolder32bit + 'include/',\n 'src': PULPNNTestFolder32bit + 'src/', 'pointwise_convolution': \n PULPNNTestFolder32bit + 'src/StandardConvolutions/', 'matmul': \n PULPNNTestFolder32bit + 'src/MatrixMultiplications/',\n 'depthwise_convolution': PULPNNTestFolder32bit +\n 'src/DepthwiseConvolutions/', 'linear_convolution_nq': \n PULPNNTestFolder32bit + 'src/LinearConvolutionsNoQuant/',\n 'linear_convolution_q': PULPNNTestFolder32bit +\n 'src/LinearConvolutionsQuant/', 'support_function': \n PULPNNTestFolder32bit + 'src/SupportFunctions/', 'data_allocation_pw': \n PULPNNTestFolder32bit + 'include/DataAllocationStandardConvolutions/',\n 'data_allocation_dw': PULPNNTestFolder32bit +\n 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq':\n PULPNNTestFolder32bit +\n 'include/DataAllocationLinearConvolutionsNoQuant/',\n 'data_allocation_ln_q': PULPNNTestFolder32bit +\n 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': \n PULPNNTestFolder32bit + 'include/GoldenModelStandardConvolutions/',\n 'golden_model_dw': PULPNNTestFolder32bit +\n 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': \n PULPNNTestFolder32bit + 'include/GoldenModelLinearConvolutionsNoQuant/',\n 'golden_model_ln_q': PULPNNTestFolder32bit +\n 'include/GoldenModelLinearConvolutionsQuant/', 'test':\n PULPNNTestFolder32bit}\nPULPNNSrcDirs64bit = {'pulp_nn_inc': PULPNNInstallPath64bit + 'include/',\n 'pulp_nn_pointwise_convolution': PULPNNInstallPath64bit +\n 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath64bit +\n 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': \n PULPNNInstallPath64bit + 'src/DepthwiseConvolutions/',\n 'pulp_nn_linear_convolution_nq': PULPNNInstallPath64bit +\n 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': \n PULPNNInstallPath64bit + 'src/LinearConvolutionsQuant/',\n 'pulp_nn_support_function': PULPNNInstallPath64bit +\n 'src/SupportFunctions/', 'include': PULPNNTestFolder64bit + 'include/',\n 'src': PULPNNTestFolder64bit + 'src/', 'pointwise_convolution': \n PULPNNTestFolder64bit + 'src/StandardConvolutions/', 'matmul': \n PULPNNTestFolder64bit + 'src/MatrixMultiplications/',\n 'depthwise_convolution': PULPNNTestFolder64bit +\n 'src/DepthwiseConvolutions/', 'linear_convolution_nq': \n PULPNNTestFolder64bit + 'src/LinearConvolutionsNoQuant/',\n 'linear_convolution_q': PULPNNTestFolder64bit +\n 'src/LinearConvolutionsQuant/', 'support_function': \n PULPNNTestFolder64bit + 'src/SupportFunctions/', 'data_allocation_pw': \n PULPNNTestFolder64bit + 'include/DataAllocationStandardConvolutions/',\n 'data_allocation_dw': PULPNNTestFolder64bit +\n 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq':\n PULPNNTestFolder64bit +\n 'include/DataAllocationLinearConvolutionsNoQuant/',\n 'data_allocation_ln_q': PULPNNTestFolder64bit +\n 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': \n PULPNNTestFolder64bit + 'include/GoldenModelStandardConvolutions/',\n 'golden_model_dw': PULPNNTestFolder64bit +\n 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': \n PULPNNTestFolder64bit + 'include/GoldenModelLinearConvolutionsNoQuant/',\n 'golden_model_ln_q': PULPNNTestFolder64bit +\n 'include/GoldenModelLinearConvolutionsQuant/', 'test':\n PULPNNTestFolder64bit}\n", "step-3": "import os\nPULPNNInstallPath = cwd = os.getcwd() + '/../'\nPULPNNSrcDirs = {'script': PULPNNInstallPath + 'scripts/'}\nPULPNNInstallPath32bit = cwd = os.getcwd() + '/../32bit/'\nPULPNNInstallPath64bit = cwd = os.getcwd() + '/../64bit/'\nPULPNNTestFolder32bit = PULPNNInstallPath32bit + 'test/'\nPULPNNTestFolder64bit = PULPNNInstallPath64bit + 'test/'\nPULPNNSrcDirs32bit = {'pulp_nn_inc': PULPNNInstallPath32bit + 'include/',\n 'pulp_nn_pointwise_convolution': PULPNNInstallPath32bit +\n 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath32bit +\n 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': \n PULPNNInstallPath32bit + 'src/DepthwiseConvolutions/',\n 'pulp_nn_linear_convolution_nq': PULPNNInstallPath32bit +\n 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': \n PULPNNInstallPath32bit + 'src/LinearConvolutionsQuant/',\n 'pulp_nn_support_function': PULPNNInstallPath32bit +\n 'src/SupportFunctions/', 'include': PULPNNTestFolder32bit + 'include/',\n 'src': PULPNNTestFolder32bit + 'src/', 'pointwise_convolution': \n PULPNNTestFolder32bit + 'src/StandardConvolutions/', 'matmul': \n PULPNNTestFolder32bit + 'src/MatrixMultiplications/',\n 'depthwise_convolution': PULPNNTestFolder32bit +\n 'src/DepthwiseConvolutions/', 'linear_convolution_nq': \n PULPNNTestFolder32bit + 'src/LinearConvolutionsNoQuant/',\n 'linear_convolution_q': PULPNNTestFolder32bit +\n 'src/LinearConvolutionsQuant/', 'support_function': \n PULPNNTestFolder32bit + 'src/SupportFunctions/', 'data_allocation_pw': \n PULPNNTestFolder32bit + 'include/DataAllocationStandardConvolutions/',\n 'data_allocation_dw': PULPNNTestFolder32bit +\n 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq':\n PULPNNTestFolder32bit +\n 'include/DataAllocationLinearConvolutionsNoQuant/',\n 'data_allocation_ln_q': PULPNNTestFolder32bit +\n 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': \n PULPNNTestFolder32bit + 'include/GoldenModelStandardConvolutions/',\n 'golden_model_dw': PULPNNTestFolder32bit +\n 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': \n PULPNNTestFolder32bit + 'include/GoldenModelLinearConvolutionsNoQuant/',\n 'golden_model_ln_q': PULPNNTestFolder32bit +\n 'include/GoldenModelLinearConvolutionsQuant/', 'test':\n PULPNNTestFolder32bit}\nPULPNNSrcDirs64bit = {'pulp_nn_inc': PULPNNInstallPath64bit + 'include/',\n 'pulp_nn_pointwise_convolution': PULPNNInstallPath64bit +\n 'src/StandardConvolutions/', 'pulp_nn_matmul': PULPNNInstallPath64bit +\n 'src/MatrixMultiplications/', 'pulp_nn_depthwise_convolution': \n PULPNNInstallPath64bit + 'src/DepthwiseConvolutions/',\n 'pulp_nn_linear_convolution_nq': PULPNNInstallPath64bit +\n 'src/LinearConvolutionsNoQuant/', 'pulp_nn_linear_convolution_q': \n PULPNNInstallPath64bit + 'src/LinearConvolutionsQuant/',\n 'pulp_nn_support_function': PULPNNInstallPath64bit +\n 'src/SupportFunctions/', 'include': PULPNNTestFolder64bit + 'include/',\n 'src': PULPNNTestFolder64bit + 'src/', 'pointwise_convolution': \n PULPNNTestFolder64bit + 'src/StandardConvolutions/', 'matmul': \n PULPNNTestFolder64bit + 'src/MatrixMultiplications/',\n 'depthwise_convolution': PULPNNTestFolder64bit +\n 'src/DepthwiseConvolutions/', 'linear_convolution_nq': \n PULPNNTestFolder64bit + 'src/LinearConvolutionsNoQuant/',\n 'linear_convolution_q': PULPNNTestFolder64bit +\n 'src/LinearConvolutionsQuant/', 'support_function': \n PULPNNTestFolder64bit + 'src/SupportFunctions/', 'data_allocation_pw': \n PULPNNTestFolder64bit + 'include/DataAllocationStandardConvolutions/',\n 'data_allocation_dw': PULPNNTestFolder64bit +\n 'include/DataAllocationDepthwiseConvolutions/', 'data_allocation_ln_nq':\n PULPNNTestFolder64bit +\n 'include/DataAllocationLinearConvolutionsNoQuant/',\n 'data_allocation_ln_q': PULPNNTestFolder64bit +\n 'include/DataAllocationLinearConvolutionsQuant/', 'golden_model_pw': \n PULPNNTestFolder64bit + 'include/GoldenModelStandardConvolutions/',\n 'golden_model_dw': PULPNNTestFolder64bit +\n 'include/GoldenModelDepthwiseConvolutions/', 'golden_model_ln_nq': \n PULPNNTestFolder64bit + 'include/GoldenModelLinearConvolutionsNoQuant/',\n 'golden_model_ln_q': PULPNNTestFolder64bit +\n 'include/GoldenModelLinearConvolutionsQuant/', 'test':\n PULPNNTestFolder64bit}\n", "step-4": "#\n# struct_test.py\n# Nazareno Bruschi <nazareno.bruschi@unibo.it>\n#\n# Copyright (C) 2019-2020 University of Bologna\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\n\nPULPNNInstallPath = cwd = os.getcwd() + \"/../\"\nPULPNNSrcDirs = {'script': PULPNNInstallPath + \"scripts/\"}\nPULPNNInstallPath32bit = cwd = os.getcwd() + \"/../32bit/\"\nPULPNNInstallPath64bit = cwd = os.getcwd() + \"/../64bit/\"\nPULPNNTestFolder32bit = PULPNNInstallPath32bit + \"test/\"\nPULPNNTestFolder64bit = PULPNNInstallPath64bit + \"test/\"\nPULPNNSrcDirs32bit = {'pulp_nn_inc': PULPNNInstallPath32bit + \"include/\",\n 'pulp_nn_pointwise_convolution': PULPNNInstallPath32bit + \"src/StandardConvolutions/\",\n 'pulp_nn_matmul': PULPNNInstallPath32bit + \"src/MatrixMultiplications/\",\n 'pulp_nn_depthwise_convolution': PULPNNInstallPath32bit + \"src/DepthwiseConvolutions/\",\n 'pulp_nn_linear_convolution_nq': PULPNNInstallPath32bit + \"src/LinearConvolutionsNoQuant/\",\n 'pulp_nn_linear_convolution_q': PULPNNInstallPath32bit + \"src/LinearConvolutionsQuant/\",\n 'pulp_nn_support_function': PULPNNInstallPath32bit + \"src/SupportFunctions/\",\n 'include': PULPNNTestFolder32bit + \"include/\",\n 'src': PULPNNTestFolder32bit + \"src/\",\n 'pointwise_convolution': PULPNNTestFolder32bit + \"src/StandardConvolutions/\",\n 'matmul': PULPNNTestFolder32bit + \"src/MatrixMultiplications/\",\n 'depthwise_convolution': PULPNNTestFolder32bit + \"src/DepthwiseConvolutions/\",\n 'linear_convolution_nq': PULPNNTestFolder32bit + \"src/LinearConvolutionsNoQuant/\",\n 'linear_convolution_q': PULPNNTestFolder32bit + \"src/LinearConvolutionsQuant/\",\n 'support_function': PULPNNTestFolder32bit + \"src/SupportFunctions/\",\n 'data_allocation_pw': PULPNNTestFolder32bit + \"include/DataAllocationStandardConvolutions/\",\n 'data_allocation_dw': PULPNNTestFolder32bit + \"include/DataAllocationDepthwiseConvolutions/\",\n 'data_allocation_ln_nq': PULPNNTestFolder32bit + \"include/DataAllocationLinearConvolutionsNoQuant/\",\n 'data_allocation_ln_q': PULPNNTestFolder32bit + \"include/DataAllocationLinearConvolutionsQuant/\",\n 'golden_model_pw': PULPNNTestFolder32bit + \"include/GoldenModelStandardConvolutions/\",\n 'golden_model_dw': PULPNNTestFolder32bit + \"include/GoldenModelDepthwiseConvolutions/\",\n 'golden_model_ln_nq': PULPNNTestFolder32bit + \"include/GoldenModelLinearConvolutionsNoQuant/\",\n 'golden_model_ln_q': PULPNNTestFolder32bit + \"include/GoldenModelLinearConvolutionsQuant/\",\n 'test': PULPNNTestFolder32bit}\nPULPNNSrcDirs64bit = {'pulp_nn_inc': PULPNNInstallPath64bit + \"include/\",\n 'pulp_nn_pointwise_convolution': PULPNNInstallPath64bit + \"src/StandardConvolutions/\",\n 'pulp_nn_matmul': PULPNNInstallPath64bit + \"src/MatrixMultiplications/\",\n 'pulp_nn_depthwise_convolution': PULPNNInstallPath64bit + \"src/DepthwiseConvolutions/\",\n 'pulp_nn_linear_convolution_nq': PULPNNInstallPath64bit + \"src/LinearConvolutionsNoQuant/\",\n 'pulp_nn_linear_convolution_q': PULPNNInstallPath64bit + \"src/LinearConvolutionsQuant/\",\n 'pulp_nn_support_function': PULPNNInstallPath64bit + \"src/SupportFunctions/\",\n 'include': PULPNNTestFolder64bit + \"include/\",\n 'src': PULPNNTestFolder64bit + \"src/\",\n 'pointwise_convolution': PULPNNTestFolder64bit + \"src/StandardConvolutions/\",\n 'matmul': PULPNNTestFolder64bit + \"src/MatrixMultiplications/\",\n 'depthwise_convolution': PULPNNTestFolder64bit + \"src/DepthwiseConvolutions/\",\n 'linear_convolution_nq': PULPNNTestFolder64bit + \"src/LinearConvolutionsNoQuant/\",\n 'linear_convolution_q': PULPNNTestFolder64bit + \"src/LinearConvolutionsQuant/\",\n 'support_function': PULPNNTestFolder64bit + \"src/SupportFunctions/\",\n 'data_allocation_pw': PULPNNTestFolder64bit + \"include/DataAllocationStandardConvolutions/\",\n 'data_allocation_dw': PULPNNTestFolder64bit + \"include/DataAllocationDepthwiseConvolutions/\",\n 'data_allocation_ln_nq': PULPNNTestFolder64bit + \"include/DataAllocationLinearConvolutionsNoQuant/\",\n 'data_allocation_ln_q': PULPNNTestFolder64bit + \"include/DataAllocationLinearConvolutionsQuant/\",\n 'golden_model_pw': PULPNNTestFolder64bit + \"include/GoldenModelStandardConvolutions/\",\n 'golden_model_dw': PULPNNTestFolder64bit + \"include/GoldenModelDepthwiseConvolutions/\",\n 'golden_model_ln_nq': PULPNNTestFolder64bit + \"include/GoldenModelLinearConvolutionsNoQuant/\",\n 'golden_model_ln_q': PULPNNTestFolder64bit + \"include/GoldenModelLinearConvolutionsQuant/\",\n 'test': PULPNNTestFolder64bit}", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class OfferApi(object): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method find_eligible_items" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`' ) collection_formats = {} path_params = {} query_params = [] if 'limit' in params: query_params.append(('limit', params['limit'])) if 'offset' in params: query_params.append(('offset', params['offset'])) header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) auth_settings = ['api_auth'] return self.api_client.call_api('/find_eligible_items', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type= 'PagedEligibleItemCollection', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only= params.get('_return_http_data_only'), _preload_content=params. get('_preload_content', True), _request_timeout=params.get( '_request_timeout'), collection_formats=collection_formats) def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs ): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) else: data = self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) return data def send_offer_to_interested_buyers_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'body'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`' ) collection_formats = {} path_params = {} query_params = [] header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) header_params['Content-Type' ] = self.api_client.select_header_content_type(['application/json'] ) auth_settings = ['api_auth'] return self.api_client.call_api('/send_offer_to_interested_buyers', 'POST', path_params, query_params, header_params, body= body_params, post_params=form_params, files=local_var_files, response_type='SendOfferToInterestedBuyersCollectionResponse', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) <|reserved_special_token_1|> <|reserved_special_token_0|> class OfferApi(object): <|reserved_special_token_0|> <|reserved_special_token_0|> def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs): """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.find_eligible_items_with_http_info( x_ebay_c_marketplace_id, **kwargs) else: data = self.find_eligible_items_with_http_info( x_ebay_c_marketplace_id, **kwargs) return data def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method find_eligible_items" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`' ) collection_formats = {} path_params = {} query_params = [] if 'limit' in params: query_params.append(('limit', params['limit'])) if 'offset' in params: query_params.append(('offset', params['offset'])) header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) auth_settings = ['api_auth'] return self.api_client.call_api('/find_eligible_items', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type= 'PagedEligibleItemCollection', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only= params.get('_return_http_data_only'), _preload_content=params. get('_preload_content', True), _request_timeout=params.get( '_request_timeout'), collection_formats=collection_formats) def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs ): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) else: data = self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) return data def send_offer_to_interested_buyers_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'body'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`' ) collection_formats = {} path_params = {} query_params = [] header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) header_params['Content-Type' ] = self.api_client.select_header_content_type(['application/json'] ) auth_settings = ['api_auth'] return self.api_client.call_api('/send_offer_to_interested_buyers', 'POST', path_params, query_params, header_params, body= body_params, post_params=form_params, files=local_var_files, response_type='SendOfferToInterestedBuyersCollectionResponse', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) <|reserved_special_token_1|> <|reserved_special_token_0|> class OfferApi(object): <|reserved_special_token_0|> def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs): """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.find_eligible_items_with_http_info( x_ebay_c_marketplace_id, **kwargs) else: data = self.find_eligible_items_with_http_info( x_ebay_c_marketplace_id, **kwargs) return data def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method find_eligible_items" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`' ) collection_formats = {} path_params = {} query_params = [] if 'limit' in params: query_params.append(('limit', params['limit'])) if 'offset' in params: query_params.append(('offset', params['offset'])) header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) auth_settings = ['api_auth'] return self.api_client.call_api('/find_eligible_items', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type= 'PagedEligibleItemCollection', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only= params.get('_return_http_data_only'), _preload_content=params. get('_preload_content', True), _request_timeout=params.get( '_request_timeout'), collection_formats=collection_formats) def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs ): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) else: data = self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) return data def send_offer_to_interested_buyers_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'body'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`' ) collection_formats = {} path_params = {} query_params = [] header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) header_params['Content-Type' ] = self.api_client.select_header_content_type(['application/json'] ) auth_settings = ['api_auth'] return self.api_client.call_api('/send_offer_to_interested_buyers', 'POST', path_params, query_params, header_params, body= body_params, post_params=form_params, files=local_var_files, response_type='SendOfferToInterestedBuyersCollectionResponse', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) <|reserved_special_token_1|> <|reserved_special_token_0|> from __future__ import absolute_import import re import six from ...sell_negotiation.api_client import ApiClient class OfferApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs): """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.find_eligible_items_with_http_info( x_ebay_c_marketplace_id, **kwargs) else: data = self.find_eligible_items_with_http_info( x_ebay_c_marketplace_id, **kwargs) return data def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method find_eligible_items" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`' ) collection_formats = {} path_params = {} query_params = [] if 'limit' in params: query_params.append(('limit', params['limit'])) if 'offset' in params: query_params.append(('offset', params['offset'])) header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) auth_settings = ['api_auth'] return self.api_client.call_api('/find_eligible_items', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type= 'PagedEligibleItemCollection', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only= params.get('_return_http_data_only'), _preload_content=params. get('_preload_content', True), _request_timeout=params.get( '_request_timeout'), collection_formats=collection_formats) def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs ): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) else: data = self.send_offer_to_interested_buyers_with_http_info( x_ebay_c_marketplace_id, **kwargs) return data def send_offer_to_interested_buyers_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'body'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers" % key) params[key] = val del params['kwargs'] if 'x_ebay_c_marketplace_id' not in params or params[ 'x_ebay_c_marketplace_id'] is None: raise ValueError( 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`' ) collection_formats = {} path_params = {} query_params = [] header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params[ 'x_ebay_c_marketplace_id'] form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] header_params['Accept'] = self.api_client.select_header_accept([ 'application/json']) header_params['Content-Type' ] = self.api_client.select_header_content_type(['application/json'] ) auth_settings = ['api_auth'] return self.api_client.call_api('/send_offer_to_interested_buyers', 'POST', path_params, query_params, header_params, body= body_params, post_params=form_params, files=local_var_files, response_type='SendOfferToInterestedBuyersCollectionResponse', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) <|reserved_special_token_1|> # coding: utf-8 """ Negotiation API The <b>Negotiations API</b> gives sellers the ability to proactively send discount offers to buyers who have shown an \"interest\" in their listings. <br><br>By sending buyers discount offers on listings where they have shown an interest, sellers can increase the velocity of their sales. <br><br>There are various ways for a buyer to show <i>interest </i> in a listing. For example, if a buyer adds the listing to their <b>Watch</b> list, or if they add the listing to their shopping cart and later abandon the cart, they are deemed to have shown an interest in the listing. <br><br>In the offers that sellers send, they can discount their listings by either a percentage off the listing price, or they can set a new discounted price that is lower than the original listing price. <br><br>For details about how seller offers work, see <a href=\"/api-docs/sell/static/marketing/offers-to-buyers.html\" title=\"Selling Integration Guide\">Sending offers to buyers</a>. # noqa: E501 OpenAPI spec version: v1.1.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from ...sell_negotiation.api_client import ApiClient class OfferApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501 """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501 else: (data) = self.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501 return data def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501 """find_eligible_items # noqa: E501 This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10 :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0 :return: PagedEligibleItemCollection If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method find_eligible_items" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'x_ebay_c_marketplace_id' is set if ('x_ebay_c_marketplace_id' not in params or params['x_ebay_c_marketplace_id'] is None): raise ValueError("Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] if 'limit' in params: query_params.append(('limit', params['limit'])) # noqa: E501 if 'offset' in params: query_params.append(('offset', params['offset'])) # noqa: E501 header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501 form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['api_auth'] # noqa: E501 return self.api_client.call_api( '/find_eligible_items', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='PagedEligibleItemCollection', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501 """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501 else: (data) = self.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501 return data def send_offer_to_interested_buyers_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501 """send_offer_to_interested_buyers # noqa: E501 This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True) >>> result = thread.get() :param async_req bool :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required) :param CreateOffersRequest body: Send offer to eligible items request. :return: SendOfferToInterestedBuyersCollectionResponse If the method is called asynchronously, returns the request thread. """ all_params = ['x_ebay_c_marketplace_id', 'body'] # noqa: E501 all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in six.iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method send_offer_to_interested_buyers" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'x_ebay_c_marketplace_id' is set if ('x_ebay_c_marketplace_id' not in params or params['x_ebay_c_marketplace_id'] is None): raise ValueError("Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`") # noqa: E501 collection_formats = {} path_params = {} query_params = [] header_params = {} if 'x_ebay_c_marketplace_id' in params: header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501 form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept( ['application/json']) # noqa: E501 # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 ['application/json']) # noqa: E501 # Authentication setting auth_settings = ['api_auth'] # noqa: E501 return self.api_client.call_api( '/send_offer_to_interested_buyers', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='SendOfferToInterestedBuyersCollectionResponse', # noqa: E501 auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
flexible
{ "blob_id": "a93818440410bde004f0203f18112fa1b666959c", "index": 9615, "step-1": "<mask token>\n\n\nclass OfferApi(object):\n <mask token>\n <mask token>\n <mask token>\n\n def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id,\n **kwargs):\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method find_eligible_items\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n if 'limit' in params:\n query_params.append(('limit', params['limit']))\n if 'offset' in params:\n query_params.append(('offset', params['offset']))\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n auth_settings = ['api_auth']\n return self.api_client.call_api('/find_eligible_items', 'GET',\n path_params, query_params, header_params, body=body_params,\n post_params=form_params, files=local_var_files, response_type=\n 'PagedEligibleItemCollection', auth_settings=auth_settings,\n async_req=params.get('async_req'), _return_http_data_only=\n params.get('_return_http_data_only'), _preload_content=params.\n get('_preload_content', True), _request_timeout=params.get(\n '_request_timeout'), collection_formats=collection_formats)\n\n def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs\n ):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n else:\n data = self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n return data\n\n def send_offer_to_interested_buyers_with_http_info(self,\n x_ebay_c_marketplace_id, **kwargs):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'body']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n if 'body' in params:\n body_params = params['body']\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n header_params['Content-Type'\n ] = self.api_client.select_header_content_type(['application/json']\n )\n auth_settings = ['api_auth']\n return self.api_client.call_api('/send_offer_to_interested_buyers',\n 'POST', path_params, query_params, header_params, body=\n body_params, post_params=form_params, files=local_var_files,\n response_type='SendOfferToInterestedBuyersCollectionResponse',\n auth_settings=auth_settings, async_req=params.get('async_req'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n", "step-2": "<mask token>\n\n\nclass OfferApi(object):\n <mask token>\n <mask token>\n\n def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs):\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.find_eligible_items_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n else:\n data = self.find_eligible_items_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n return data\n\n def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id,\n **kwargs):\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method find_eligible_items\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n if 'limit' in params:\n query_params.append(('limit', params['limit']))\n if 'offset' in params:\n query_params.append(('offset', params['offset']))\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n auth_settings = ['api_auth']\n return self.api_client.call_api('/find_eligible_items', 'GET',\n path_params, query_params, header_params, body=body_params,\n post_params=form_params, files=local_var_files, response_type=\n 'PagedEligibleItemCollection', auth_settings=auth_settings,\n async_req=params.get('async_req'), _return_http_data_only=\n params.get('_return_http_data_only'), _preload_content=params.\n get('_preload_content', True), _request_timeout=params.get(\n '_request_timeout'), collection_formats=collection_formats)\n\n def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs\n ):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n else:\n data = self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n return data\n\n def send_offer_to_interested_buyers_with_http_info(self,\n x_ebay_c_marketplace_id, **kwargs):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'body']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n if 'body' in params:\n body_params = params['body']\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n header_params['Content-Type'\n ] = self.api_client.select_header_content_type(['application/json']\n )\n auth_settings = ['api_auth']\n return self.api_client.call_api('/send_offer_to_interested_buyers',\n 'POST', path_params, query_params, header_params, body=\n body_params, post_params=form_params, files=local_var_files,\n response_type='SendOfferToInterestedBuyersCollectionResponse',\n auth_settings=auth_settings, async_req=params.get('async_req'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n", "step-3": "<mask token>\n\n\nclass OfferApi(object):\n <mask token>\n\n def __init__(self, api_client=None):\n if api_client is None:\n api_client = ApiClient()\n self.api_client = api_client\n\n def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs):\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.find_eligible_items_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n else:\n data = self.find_eligible_items_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n return data\n\n def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id,\n **kwargs):\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method find_eligible_items\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n if 'limit' in params:\n query_params.append(('limit', params['limit']))\n if 'offset' in params:\n query_params.append(('offset', params['offset']))\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n auth_settings = ['api_auth']\n return self.api_client.call_api('/find_eligible_items', 'GET',\n path_params, query_params, header_params, body=body_params,\n post_params=form_params, files=local_var_files, response_type=\n 'PagedEligibleItemCollection', auth_settings=auth_settings,\n async_req=params.get('async_req'), _return_http_data_only=\n params.get('_return_http_data_only'), _preload_content=params.\n get('_preload_content', True), _request_timeout=params.get(\n '_request_timeout'), collection_formats=collection_formats)\n\n def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs\n ):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n else:\n data = self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n return data\n\n def send_offer_to_interested_buyers_with_http_info(self,\n x_ebay_c_marketplace_id, **kwargs):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'body']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n if 'body' in params:\n body_params = params['body']\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n header_params['Content-Type'\n ] = self.api_client.select_header_content_type(['application/json']\n )\n auth_settings = ['api_auth']\n return self.api_client.call_api('/send_offer_to_interested_buyers',\n 'POST', path_params, query_params, header_params, body=\n body_params, post_params=form_params, files=local_var_files,\n response_type='SendOfferToInterestedBuyersCollectionResponse',\n auth_settings=auth_settings, async_req=params.get('async_req'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n", "step-4": "<mask token>\nfrom __future__ import absolute_import\nimport re\nimport six\nfrom ...sell_negotiation.api_client import ApiClient\n\n\nclass OfferApi(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n Ref: https://github.com/swagger-api/swagger-codegen\n \"\"\"\n\n def __init__(self, api_client=None):\n if api_client is None:\n api_client = ApiClient()\n self.api_client = api_client\n\n def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs):\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.find_eligible_items_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n else:\n data = self.find_eligible_items_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n return data\n\n def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id,\n **kwargs):\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method find_eligible_items\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n if 'limit' in params:\n query_params.append(('limit', params['limit']))\n if 'offset' in params:\n query_params.append(('offset', params['offset']))\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n auth_settings = ['api_auth']\n return self.api_client.call_api('/find_eligible_items', 'GET',\n path_params, query_params, header_params, body=body_params,\n post_params=form_params, files=local_var_files, response_type=\n 'PagedEligibleItemCollection', auth_settings=auth_settings,\n async_req=params.get('async_req'), _return_http_data_only=\n params.get('_return_http_data_only'), _preload_content=params.\n get('_preload_content', True), _request_timeout=params.get(\n '_request_timeout'), collection_formats=collection_formats)\n\n def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs\n ):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n else:\n data = self.send_offer_to_interested_buyers_with_http_info(\n x_ebay_c_marketplace_id, **kwargs)\n return data\n\n def send_offer_to_interested_buyers_with_http_info(self,\n x_ebay_c_marketplace_id, **kwargs):\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n all_params = ['x_ebay_c_marketplace_id', 'body']\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s' to method send_offer_to_interested_buyers\"\n % key)\n params[key] = val\n del params['kwargs']\n if 'x_ebay_c_marketplace_id' not in params or params[\n 'x_ebay_c_marketplace_id'] is None:\n raise ValueError(\n 'Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`'\n )\n collection_formats = {}\n path_params = {}\n query_params = []\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params[\n 'x_ebay_c_marketplace_id']\n form_params = []\n local_var_files = {}\n body_params = None\n if 'body' in params:\n body_params = params['body']\n header_params['Accept'] = self.api_client.select_header_accept([\n 'application/json'])\n header_params['Content-Type'\n ] = self.api_client.select_header_content_type(['application/json']\n )\n auth_settings = ['api_auth']\n return self.api_client.call_api('/send_offer_to_interested_buyers',\n 'POST', path_params, query_params, header_params, body=\n body_params, post_params=form_params, files=local_var_files,\n response_type='SendOfferToInterestedBuyersCollectionResponse',\n auth_settings=auth_settings, async_req=params.get('async_req'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n", "step-5": "# coding: utf-8\n\n\"\"\"\n Negotiation API\n\n The <b>Negotiations API</b> gives sellers the ability to proactively send discount offers to buyers who have shown an \\\"interest\\\" in their listings. <br><br>By sending buyers discount offers on listings where they have shown an interest, sellers can increase the velocity of their sales. <br><br>There are various ways for a buyer to show <i>interest </i> in a listing. For example, if a buyer adds the listing to their <b>Watch</b> list, or if they add the listing to their shopping cart and later abandon the cart, they are deemed to have shown an interest in the listing. <br><br>In the offers that sellers send, they can discount their listings by either a percentage off the listing price, or they can set a new discounted price that is lower than the original listing price. <br><br>For details about how seller offers work, see <a href=\\\"/api-docs/sell/static/marketing/offers-to-buyers.html\\\" title=\\\"Selling Integration Guide\\\">Sending offers to buyers</a>. # noqa: E501\n\n OpenAPI spec version: v1.1.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport re # noqa: F401\n\n# python 2 and python 3 compatibility library\nimport six\n\nfrom ...sell_negotiation.api_client import ApiClient\n\n\nclass OfferApi(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n Ref: https://github.com/swagger-api/swagger-codegen\n \"\"\"\n\n def __init__(self, api_client=None):\n if api_client is None:\n api_client = ApiClient()\n self.api_client = api_client\n\n def find_eligible_items(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501\n else:\n (data) = self.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501\n return data\n\n def find_eligible_items_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501\n \"\"\"find_eligible_items # noqa: E501\n\n This method evaluates a seller's current listings and returns the set of IDs that are eligible for a seller-initiated discount offer to a buyer. A listing ID is returned only when one or more buyers have shown an &quot;interest&quot; in the listing. If any buyers have shown interest in a listing, the seller can initiate a &quot;negotiation&quot; with them by calling sendOfferToInterestedBuyers, which sends all interested buyers a message that offers the listing at a discount. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.find_eligible_items_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which you want to search for eligible listings. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param str limit: This query parameter specifies the maximum number of items to return from the result set on a page in the paginated response. Minimum: 1 &nbsp; &nbsp;Maximum: 200 Default: 10\n :param str offset: This query parameter specifies the number of results to skip in the result set before returning the first result in the paginated response. Combine offset with the limit query parameter to control the items returned in the response. For example, if you supply an offset of 0 and a limit of 10, the first page of the response contains the first 10 results from the complete list of items retrieved by the call. If offset is 10 and limit is 20, the first page of the response contains items 11-30 from the complete result set. Default: 0\n :return: PagedEligibleItemCollection\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['x_ebay_c_marketplace_id', 'limit', 'offset'] # noqa: E501\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method find_eligible_items\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'x_ebay_c_marketplace_id' is set\n if ('x_ebay_c_marketplace_id' not in params or\n params['x_ebay_c_marketplace_id'] is None):\n raise ValueError(\"Missing the required parameter `x_ebay_c_marketplace_id` when calling `find_eligible_items`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n if 'limit' in params:\n query_params.append(('limit', params['limit'])) # noqa: E501\n if 'offset' in params:\n query_params.append(('offset', params['offset'])) # noqa: E501\n\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_auth'] # noqa: E501\n\n return self.api_client.call_api(\n '/find_eligible_items', 'GET',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='PagedEligibleItemCollection', # noqa: E501\n auth_settings=auth_settings,\n async_req=params.get('async_req'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n\n def send_offer_to_interested_buyers(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n kwargs['_return_http_data_only'] = True\n if kwargs.get('async_req'):\n return self.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501\n else:\n (data) = self.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, **kwargs) # noqa: E501\n return data\n\n def send_offer_to_interested_buyers_with_http_info(self, x_ebay_c_marketplace_id, **kwargs): # noqa: E501\n \"\"\"send_offer_to_interested_buyers # noqa: E501\n\n This method sends eligible buyers offers to purchase items in a listing at a discount. When a buyer has shown interest in a listing, they become &quot;eligible&quot; to receive a seller-initiated offer to purchase the item(s). Sellers use findEligibleItems to get the set of listings that have interested buyers. If a listing has interested buyers, sellers can use this method (sendOfferToInterestedBuyers) to send an offer to the buyers who are interested in the listing. The offer gives buyers the ability to purchase the associated listings at a discounted price. For details about how to create seller offers to buyers, see Sending offers to buyers. # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.send_offer_to_interested_buyers_with_http_info(x_ebay_c_marketplace_id, async_req=True)\n >>> result = thread.get()\n\n :param async_req bool\n :param str x_ebay_c_marketplace_id: The eBay marketplace on which your listings with &quot;eligible&quot; buyers appear. For a complete list of supported marketplaces, see Negotiation API requirements and restrictions. (required)\n :param CreateOffersRequest body: Send offer to eligible items request.\n :return: SendOfferToInterestedBuyersCollectionResponse\n If the method is called asynchronously,\n returns the request thread.\n \"\"\"\n\n all_params = ['x_ebay_c_marketplace_id', 'body'] # noqa: E501\n all_params.append('async_req')\n all_params.append('_return_http_data_only')\n all_params.append('_preload_content')\n all_params.append('_request_timeout')\n\n params = locals()\n for key, val in six.iteritems(params['kwargs']):\n if key not in all_params:\n raise TypeError(\n \"Got an unexpected keyword argument '%s'\"\n \" to method send_offer_to_interested_buyers\" % key\n )\n params[key] = val\n del params['kwargs']\n # verify the required parameter 'x_ebay_c_marketplace_id' is set\n if ('x_ebay_c_marketplace_id' not in params or\n params['x_ebay_c_marketplace_id'] is None):\n raise ValueError(\"Missing the required parameter `x_ebay_c_marketplace_id` when calling `send_offer_to_interested_buyers`\") # noqa: E501\n\n collection_formats = {}\n\n path_params = {}\n\n query_params = []\n\n header_params = {}\n if 'x_ebay_c_marketplace_id' in params:\n header_params['X-EBAY-C-MARKETPLACE-ID'] = params['x_ebay_c_marketplace_id'] # noqa: E501\n\n form_params = []\n local_var_files = {}\n\n body_params = None\n if 'body' in params:\n body_params = params['body']\n # HTTP header `Accept`\n header_params['Accept'] = self.api_client.select_header_accept(\n ['application/json']) # noqa: E501\n\n # HTTP header `Content-Type`\n header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501\n ['application/json']) # noqa: E501\n\n # Authentication setting\n auth_settings = ['api_auth'] # noqa: E501\n\n return self.api_client.call_api(\n '/send_offer_to_interested_buyers', 'POST',\n path_params,\n query_params,\n header_params,\n body=body_params,\n post_params=form_params,\n files=local_var_files,\n response_type='SendOfferToInterestedBuyersCollectionResponse', # noqa: E501\n auth_settings=auth_settings,\n async_req=params.get('async_req'),\n _return_http_data_only=params.get('_return_http_data_only'),\n _preload_content=params.get('_preload_content', True),\n _request_timeout=params.get('_request_timeout'),\n collection_formats=collection_formats)\n", "step-ids": [ 4, 5, 6, 8, 9 ] }
[ 4, 5, 6, 8, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> with open('test_9feats.csv', 'w') as f: df = pd.DataFrame(file, columns=['dst_host_srv_serror_rate', 'dst_host_serror_rate', 'serror_rate', 'srv_serror_rate', 'count', 'flag', 'same_srv_rate', 'dst_host_srv_count', 'dst_host_diff_srv_rate', 'Malicious']) df.to_csv(f, index=False, header=True, line_terminator='\n') print(df) <|reserved_special_token_1|> <|reserved_special_token_0|> file = pd.read_csv('KDDTest+.csv') with open('test_9feats.csv', 'w') as f: df = pd.DataFrame(file, columns=['dst_host_srv_serror_rate', 'dst_host_serror_rate', 'serror_rate', 'srv_serror_rate', 'count', 'flag', 'same_srv_rate', 'dst_host_srv_count', 'dst_host_diff_srv_rate', 'Malicious']) df.to_csv(f, index=False, header=True, line_terminator='\n') print(df) <|reserved_special_token_1|> import pandas as pd file = pd.read_csv('KDDTest+.csv') with open('test_9feats.csv', 'w') as f: df = pd.DataFrame(file, columns=['dst_host_srv_serror_rate', 'dst_host_serror_rate', 'serror_rate', 'srv_serror_rate', 'count', 'flag', 'same_srv_rate', 'dst_host_srv_count', 'dst_host_diff_srv_rate', 'Malicious']) df.to_csv(f, index=False, header=True, line_terminator='\n') print(df) <|reserved_special_token_1|> import pandas as pd file = pd.read_csv("KDDTest+.csv") with open("test_9feats.csv", "w") as f: df = pd.DataFrame(file, columns=[ "dst_host_srv_serror_rate", "dst_host_serror_rate", "serror_rate", "srv_serror_rate", "count", "flag", "same_srv_rate", "dst_host_srv_count", "dst_host_diff_srv_rate", "Malicious" ]) df.to_csv(f, index=False, header=True, line_terminator='\n') print(df)
flexible
{ "blob_id": "ce28330db66dcdfad63bdac698ce9d285964d288", "index": 5124, "step-1": "<mask token>\n", "step-2": "<mask token>\nwith open('test_9feats.csv', 'w') as f:\n df = pd.DataFrame(file, columns=['dst_host_srv_serror_rate',\n 'dst_host_serror_rate', 'serror_rate', 'srv_serror_rate', 'count',\n 'flag', 'same_srv_rate', 'dst_host_srv_count',\n 'dst_host_diff_srv_rate', 'Malicious'])\n df.to_csv(f, index=False, header=True, line_terminator='\\n')\n print(df)\n", "step-3": "<mask token>\nfile = pd.read_csv('KDDTest+.csv')\nwith open('test_9feats.csv', 'w') as f:\n df = pd.DataFrame(file, columns=['dst_host_srv_serror_rate',\n 'dst_host_serror_rate', 'serror_rate', 'srv_serror_rate', 'count',\n 'flag', 'same_srv_rate', 'dst_host_srv_count',\n 'dst_host_diff_srv_rate', 'Malicious'])\n df.to_csv(f, index=False, header=True, line_terminator='\\n')\n print(df)\n", "step-4": "import pandas as pd\nfile = pd.read_csv('KDDTest+.csv')\nwith open('test_9feats.csv', 'w') as f:\n df = pd.DataFrame(file, columns=['dst_host_srv_serror_rate',\n 'dst_host_serror_rate', 'serror_rate', 'srv_serror_rate', 'count',\n 'flag', 'same_srv_rate', 'dst_host_srv_count',\n 'dst_host_diff_srv_rate', 'Malicious'])\n df.to_csv(f, index=False, header=True, line_terminator='\\n')\n print(df)\n", "step-5": "import pandas as pd\n\nfile = pd.read_csv(\"KDDTest+.csv\")\nwith open(\"test_9feats.csv\", \"w\") as f:\n df = pd.DataFrame(file,\n columns=[\n \"dst_host_srv_serror_rate\", \"dst_host_serror_rate\",\n \"serror_rate\", \"srv_serror_rate\", \"count\", \"flag\",\n \"same_srv_rate\", \"dst_host_srv_count\",\n \"dst_host_diff_srv_rate\", \"Malicious\"\n ])\n df.to_csv(f, index=False, header=True, line_terminator='\\n')\n print(df)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import pandas as pd from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # from sklearn import tree # import joblib music_data = pd.read_csv(r"C:\Users\junha\PythonProjects\predict_music_preferences\music.csv") # print(music_data) X = music_data.drop(columns=['genre']) y = music_data['genre'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model = DecisionTreeClassifier() model.fit(X_train, y_train) predictions = model.predict(X_test) print(predictions) score = accuracy_score(y_test, predictions) print(score) # joblib.dump(model, 'music-recommender.joblib') # tree.export_graphviz(model, out_file='music-recommender.dot', # feature_names=['age', 'gender'], # class_names=sorted(y.unique()), # label='all', rounded= True, # filled=True)
normal
{ "blob_id": "8dbcd7bba09f8acff860890d8201e016b587796d", "index": 6149, "step-1": "<mask token>\n", "step-2": "<mask token>\nmodel.fit(X_train, y_train)\n<mask token>\nprint(predictions)\n<mask token>\nprint(score)\n", "step-3": "<mask token>\nmusic_data = pd.read_csv(\n 'C:\\\\Users\\\\junha\\\\PythonProjects\\\\predict_music_preferences\\\\music.csv')\nX = music_data.drop(columns=['genre'])\ny = music_data['genre']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\nmodel = DecisionTreeClassifier()\nmodel.fit(X_train, y_train)\npredictions = model.predict(X_test)\nprint(predictions)\nscore = accuracy_score(y_test, predictions)\nprint(score)\n", "step-4": "import pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nmusic_data = pd.read_csv(\n 'C:\\\\Users\\\\junha\\\\PythonProjects\\\\predict_music_preferences\\\\music.csv')\nX = music_data.drop(columns=['genre'])\ny = music_data['genre']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\nmodel = DecisionTreeClassifier()\nmodel.fit(X_train, y_train)\npredictions = model.predict(X_test)\nprint(predictions)\nscore = accuracy_score(y_test, predictions)\nprint(score)\n", "step-5": "\nimport pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n# from sklearn import tree\n# import joblib\nmusic_data = pd.read_csv(r\"C:\\Users\\junha\\PythonProjects\\predict_music_preferences\\music.csv\")\n# print(music_data)\n\n\nX = music_data.drop(columns=['genre'])\ny = music_data['genre']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n\nmodel = DecisionTreeClassifier()\nmodel.fit(X_train, y_train)\npredictions = model.predict(X_test)\nprint(predictions)\n\nscore = accuracy_score(y_test, predictions)\nprint(score)\n\n# joblib.dump(model, 'music-recommender.joblib')\n\n# tree.export_graphviz(model, out_file='music-recommender.dot',\n# feature_names=['age', 'gender'],\n# class_names=sorted(y.unique()), \n# label='all', rounded= True,\n# filled=True)", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('trades', '0001_initial')] operations = [migrations.AddField(model_name='orderinfo', name= 'nonce_str', field=models.CharField(blank=True, max_length=50, null =True, unique=True, verbose_name='随机加密串'))] <|reserved_special_token_1|> from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('trades', '0001_initial')] operations = [migrations.AddField(model_name='orderinfo', name= 'nonce_str', field=models.CharField(blank=True, max_length=50, null =True, unique=True, verbose_name='随机加密串'))] <|reserved_special_token_1|> # Generated by Django 2.2.16 on 2020-10-27 14:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('trades', '0001_initial'), ] operations = [ migrations.AddField( model_name='orderinfo', name='nonce_str', field=models.CharField(blank=True, max_length=50, null=True, unique=True, verbose_name='随机加密串'), ), ]
flexible
{ "blob_id": "4e04e748a97c59a26a394b049c15d96476b98517", "index": 9382, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('trades', '0001_initial')]\n operations = [migrations.AddField(model_name='orderinfo', name=\n 'nonce_str', field=models.CharField(blank=True, max_length=50, null\n =True, unique=True, verbose_name='随机加密串'))]\n", "step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('trades', '0001_initial')]\n operations = [migrations.AddField(model_name='orderinfo', name=\n 'nonce_str', field=models.CharField(blank=True, max_length=50, null\n =True, unique=True, verbose_name='随机加密串'))]\n", "step-5": "# Generated by Django 2.2.16 on 2020-10-27 14:55\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trades', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='orderinfo',\n name='nonce_str',\n field=models.CharField(blank=True, max_length=50, null=True, unique=True, verbose_name='随机加密串'),\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class Ui_Window(QDialog): def __init__(self): super(Ui_Window, self).__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) regex = QRegExp('\\w+') validator = QRegExpValidator(regex) self.ui.usernameLineEdit.setValidator(validator) self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month) self.ui.endDaySpinBox.setValue(datetime.datetime.now().day) self.ui.endYearSpinBox.setValue(datetime.datetime.now().year) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.ui.plotDisplayGroupBox.setLayout(layout) self.ui.processDatesPushButton.clicked.connect(self.plotSentiment) self.ui.exportPushButton.clicked.connect(self.exportValues) settings = configparser.ConfigParser() settings.read(SETTINGS_FILE) helper.print_with_stars('Initializing APIs') twitterApi, googleClient, errors = phase2Functions.init_apis(settings ['KEYS']['api_key'], settings['KEYS']['api_secret_key']) if len(errors) > 0: self.printMessages(errors) sys.exit(1) else: self.twitterApi = twitterApi self.googleClient = googleClient self.show() <|reserved_special_token_0|> def plotSentiment(self): QApplication.setOverrideCursor(Qt.WaitCursor) startDate = self.get_start_date() endDate = self.get_end_date() if startDate is None or endDate is None: return dateList, scoreList, magnitudeList, tweetList, errors = ( phase2Functions.generate_data_lists(self.twitterApi, self. googleClient, self.get_username(), startDate, endDate)) QApplication.restoreOverrideCursor() if len(errors) > 0: self.printMessages(errors) else: self.plotData = dateList, scoreList, magnitudeList self.tweetList = tweetList self.figure.clear() ax = self.figure.add_subplot(111) self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17, right=0.9, hspace=0.2, wspace=0.2) ax.set_title("Sentiment Analysis of @{}'s tweets".format(self. get_username())) ax.set_xlabel('Date') ax.set_ylabel('Sentiment Value') ax.xaxis.set_major_locator(plt.MaxNLocator(10)) for tick in ax.get_xticklabels(): tick.set_rotation(45) ax.plot(self.plotData[0], self.plotData[1], '-bo', label= 'Sentiment Score') ax.plot(self.plotData[0], self.plotData[2], '-ro', label= 'Sentiment Magnitude') ax.legend(loc='lower right') self.canvas.draw() self.enableExport() <|reserved_special_token_0|> def get_username(self): return self.ui.usernameLineEdit.text() <|reserved_special_token_0|> def get_start_date(self): start_month = self.ui.startMonthSpinBox.value() start_day = self.ui.startDaySpinBox.value() start_year = self.ui.startYearSpinBox.value() try: startDate = datetime.datetime(start_year, start_month, start_day) except: self.printMessages([ 'Start date is improperly set. Check to see that the date is correct/exists.' ]) return None return startDate <|reserved_special_token_0|> def get_end_date(self): end_month = self.ui.endMonthSpinBox.value() end_day = self.ui.endDaySpinBox.value() end_year = self.ui.endYearSpinBox.value() try: endDate = datetime.datetime(end_year, end_month, end_day) except: self.printMessages([ 'End date is improperly set. Check to see that the date is correct/exists.' ]) return None return endDate <|reserved_special_token_0|> def enableExport(self): self.ui.exportPushButton.setEnabled(True) <|reserved_special_token_0|> def exportValues(self): currentTimeDate = datetime.datetime.now() currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate .month) + '-' + str(currentTimeDate.day) + '-' + str( currentTimeDate.hour) + '-' + str(currentTimeDate.minute ) + '-' + str(currentTimeDate.second) with open(currentTimeDate + '_' + self.get_username() + '_score.csv', mode='w') as score_file: writer = csv.writer(score_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[1] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) with open(currentTimeDate + '_' + self.get_username() + '_magnitude.csv', mode='w') as magnitude_file: writer = csv.writer(magnitude_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[2] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) msgBox = QMessageBox() msgBox.setText('CSV files exported!') msgBox.exec() <|reserved_special_token_0|> def printMessages(self, messageList): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setWindowTitle('Errors occured!') tempString = '' for message in messageList: tempString += message + '\n' msgBox.setText(tempString) msgBox.exec() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.insert(1, '..\\SharedFiles\\') <|reserved_special_token_0|> class Ui_Window(QDialog): def __init__(self): super(Ui_Window, self).__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) regex = QRegExp('\\w+') validator = QRegExpValidator(regex) self.ui.usernameLineEdit.setValidator(validator) self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month) self.ui.endDaySpinBox.setValue(datetime.datetime.now().day) self.ui.endYearSpinBox.setValue(datetime.datetime.now().year) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.ui.plotDisplayGroupBox.setLayout(layout) self.ui.processDatesPushButton.clicked.connect(self.plotSentiment) self.ui.exportPushButton.clicked.connect(self.exportValues) settings = configparser.ConfigParser() settings.read(SETTINGS_FILE) helper.print_with_stars('Initializing APIs') twitterApi, googleClient, errors = phase2Functions.init_apis(settings ['KEYS']['api_key'], settings['KEYS']['api_secret_key']) if len(errors) > 0: self.printMessages(errors) sys.exit(1) else: self.twitterApi = twitterApi self.googleClient = googleClient self.show() """ Plot the sentiment score Input - self:Ui_Window Output - None """ def plotSentiment(self): QApplication.setOverrideCursor(Qt.WaitCursor) startDate = self.get_start_date() endDate = self.get_end_date() if startDate is None or endDate is None: return dateList, scoreList, magnitudeList, tweetList, errors = ( phase2Functions.generate_data_lists(self.twitterApi, self. googleClient, self.get_username(), startDate, endDate)) QApplication.restoreOverrideCursor() if len(errors) > 0: self.printMessages(errors) else: self.plotData = dateList, scoreList, magnitudeList self.tweetList = tweetList self.figure.clear() ax = self.figure.add_subplot(111) self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17, right=0.9, hspace=0.2, wspace=0.2) ax.set_title("Sentiment Analysis of @{}'s tweets".format(self. get_username())) ax.set_xlabel('Date') ax.set_ylabel('Sentiment Value') ax.xaxis.set_major_locator(plt.MaxNLocator(10)) for tick in ax.get_xticklabels(): tick.set_rotation(45) ax.plot(self.plotData[0], self.plotData[1], '-bo', label= 'Sentiment Score') ax.plot(self.plotData[0], self.plotData[2], '-ro', label= 'Sentiment Magnitude') ax.legend(loc='lower right') self.canvas.draw() self.enableExport() """ Gets username from text field Input - self:Ui_Window Output - string """ def get_username(self): return self.ui.usernameLineEdit.text() """ Gets start date from spin boxes Input - self:Ui_Window Output - datetime.datetime """ def get_start_date(self): start_month = self.ui.startMonthSpinBox.value() start_day = self.ui.startDaySpinBox.value() start_year = self.ui.startYearSpinBox.value() try: startDate = datetime.datetime(start_year, start_month, start_day) except: self.printMessages([ 'Start date is improperly set. Check to see that the date is correct/exists.' ]) return None return startDate """ Gets end date from spin boxes Input - self:Ui_Window Output - datetime.datetime """ def get_end_date(self): end_month = self.ui.endMonthSpinBox.value() end_day = self.ui.endDaySpinBox.value() end_year = self.ui.endYearSpinBox.value() try: endDate = datetime.datetime(end_year, end_month, end_day) except: self.printMessages([ 'End date is improperly set. Check to see that the date is correct/exists.' ]) return None return endDate """ Toggles the export button. Input - self:Ui_Window Output - None """ def enableExport(self): self.ui.exportPushButton.setEnabled(True) """ Exports date, score/magntitude, and tweet text to csv and pops up a window when done Input - self:Ui_Window Output - None """ def exportValues(self): currentTimeDate = datetime.datetime.now() currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate .month) + '-' + str(currentTimeDate.day) + '-' + str( currentTimeDate.hour) + '-' + str(currentTimeDate.minute ) + '-' + str(currentTimeDate.second) with open(currentTimeDate + '_' + self.get_username() + '_score.csv', mode='w') as score_file: writer = csv.writer(score_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[1] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) with open(currentTimeDate + '_' + self.get_username() + '_magnitude.csv', mode='w') as magnitude_file: writer = csv.writer(magnitude_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[2] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) msgBox = QMessageBox() msgBox.setText('CSV files exported!') msgBox.exec() """ Prints out messages in a pop up window Input - self:Ui_Window Output - None """ def printMessages(self, messageList): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setWindowTitle('Errors occured!') tempString = '' for message in messageList: tempString += message + '\n' msgBox.setText(tempString) msgBox.exec() if __name__ == '__main__': app = QApplication(sys.argv) window = Ui_Window() window.show() sys.exit(app.exec_()) <|reserved_special_token_1|> <|reserved_special_token_0|> sys.path.insert(1, '..\\SharedFiles\\') <|reserved_special_token_0|> SETTINGS_FILE = '..\\SharedFiles\\settings.ini' class Ui_Window(QDialog): def __init__(self): super(Ui_Window, self).__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) regex = QRegExp('\\w+') validator = QRegExpValidator(regex) self.ui.usernameLineEdit.setValidator(validator) self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month) self.ui.endDaySpinBox.setValue(datetime.datetime.now().day) self.ui.endYearSpinBox.setValue(datetime.datetime.now().year) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.ui.plotDisplayGroupBox.setLayout(layout) self.ui.processDatesPushButton.clicked.connect(self.plotSentiment) self.ui.exportPushButton.clicked.connect(self.exportValues) settings = configparser.ConfigParser() settings.read(SETTINGS_FILE) helper.print_with_stars('Initializing APIs') twitterApi, googleClient, errors = phase2Functions.init_apis(settings ['KEYS']['api_key'], settings['KEYS']['api_secret_key']) if len(errors) > 0: self.printMessages(errors) sys.exit(1) else: self.twitterApi = twitterApi self.googleClient = googleClient self.show() """ Plot the sentiment score Input - self:Ui_Window Output - None """ def plotSentiment(self): QApplication.setOverrideCursor(Qt.WaitCursor) startDate = self.get_start_date() endDate = self.get_end_date() if startDate is None or endDate is None: return dateList, scoreList, magnitudeList, tweetList, errors = ( phase2Functions.generate_data_lists(self.twitterApi, self. googleClient, self.get_username(), startDate, endDate)) QApplication.restoreOverrideCursor() if len(errors) > 0: self.printMessages(errors) else: self.plotData = dateList, scoreList, magnitudeList self.tweetList = tweetList self.figure.clear() ax = self.figure.add_subplot(111) self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17, right=0.9, hspace=0.2, wspace=0.2) ax.set_title("Sentiment Analysis of @{}'s tweets".format(self. get_username())) ax.set_xlabel('Date') ax.set_ylabel('Sentiment Value') ax.xaxis.set_major_locator(plt.MaxNLocator(10)) for tick in ax.get_xticklabels(): tick.set_rotation(45) ax.plot(self.plotData[0], self.plotData[1], '-bo', label= 'Sentiment Score') ax.plot(self.plotData[0], self.plotData[2], '-ro', label= 'Sentiment Magnitude') ax.legend(loc='lower right') self.canvas.draw() self.enableExport() """ Gets username from text field Input - self:Ui_Window Output - string """ def get_username(self): return self.ui.usernameLineEdit.text() """ Gets start date from spin boxes Input - self:Ui_Window Output - datetime.datetime """ def get_start_date(self): start_month = self.ui.startMonthSpinBox.value() start_day = self.ui.startDaySpinBox.value() start_year = self.ui.startYearSpinBox.value() try: startDate = datetime.datetime(start_year, start_month, start_day) except: self.printMessages([ 'Start date is improperly set. Check to see that the date is correct/exists.' ]) return None return startDate """ Gets end date from spin boxes Input - self:Ui_Window Output - datetime.datetime """ def get_end_date(self): end_month = self.ui.endMonthSpinBox.value() end_day = self.ui.endDaySpinBox.value() end_year = self.ui.endYearSpinBox.value() try: endDate = datetime.datetime(end_year, end_month, end_day) except: self.printMessages([ 'End date is improperly set. Check to see that the date is correct/exists.' ]) return None return endDate """ Toggles the export button. Input - self:Ui_Window Output - None """ def enableExport(self): self.ui.exportPushButton.setEnabled(True) """ Exports date, score/magntitude, and tweet text to csv and pops up a window when done Input - self:Ui_Window Output - None """ def exportValues(self): currentTimeDate = datetime.datetime.now() currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate .month) + '-' + str(currentTimeDate.day) + '-' + str( currentTimeDate.hour) + '-' + str(currentTimeDate.minute ) + '-' + str(currentTimeDate.second) with open(currentTimeDate + '_' + self.get_username() + '_score.csv', mode='w') as score_file: writer = csv.writer(score_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[1] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) with open(currentTimeDate + '_' + self.get_username() + '_magnitude.csv', mode='w') as magnitude_file: writer = csv.writer(magnitude_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[2] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) msgBox = QMessageBox() msgBox.setText('CSV files exported!') msgBox.exec() """ Prints out messages in a pop up window Input - self:Ui_Window Output - None """ def printMessages(self, messageList): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setWindowTitle('Errors occured!') tempString = '' for message in messageList: tempString += message + '\n' msgBox.setText(tempString) msgBox.exec() if __name__ == '__main__': app = QApplication(sys.argv) window = Ui_Window() window.show() sys.exit(app.exec_()) <|reserved_special_token_1|> from PySide2.QtWidgets import QApplication, QDialog, QVBoxLayout, QMessageBox from PySide2.QtCore import Qt, QFile, QRegExp from PySide2.QtGui import QRegExpValidator from phase2GUI import Ui_Dialog from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import configparser, csv, datetime, sys sys.path.insert(1, '..\\SharedFiles\\') import matplotlib.pyplot as plt import helper, phase2Functions SETTINGS_FILE = '..\\SharedFiles\\settings.ini' class Ui_Window(QDialog): def __init__(self): super(Ui_Window, self).__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) regex = QRegExp('\\w+') validator = QRegExpValidator(regex) self.ui.usernameLineEdit.setValidator(validator) self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month) self.ui.endDaySpinBox.setValue(datetime.datetime.now().day) self.ui.endYearSpinBox.setValue(datetime.datetime.now().year) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.ui.plotDisplayGroupBox.setLayout(layout) self.ui.processDatesPushButton.clicked.connect(self.plotSentiment) self.ui.exportPushButton.clicked.connect(self.exportValues) settings = configparser.ConfigParser() settings.read(SETTINGS_FILE) helper.print_with_stars('Initializing APIs') twitterApi, googleClient, errors = phase2Functions.init_apis(settings ['KEYS']['api_key'], settings['KEYS']['api_secret_key']) if len(errors) > 0: self.printMessages(errors) sys.exit(1) else: self.twitterApi = twitterApi self.googleClient = googleClient self.show() """ Plot the sentiment score Input - self:Ui_Window Output - None """ def plotSentiment(self): QApplication.setOverrideCursor(Qt.WaitCursor) startDate = self.get_start_date() endDate = self.get_end_date() if startDate is None or endDate is None: return dateList, scoreList, magnitudeList, tweetList, errors = ( phase2Functions.generate_data_lists(self.twitterApi, self. googleClient, self.get_username(), startDate, endDate)) QApplication.restoreOverrideCursor() if len(errors) > 0: self.printMessages(errors) else: self.plotData = dateList, scoreList, magnitudeList self.tweetList = tweetList self.figure.clear() ax = self.figure.add_subplot(111) self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17, right=0.9, hspace=0.2, wspace=0.2) ax.set_title("Sentiment Analysis of @{}'s tweets".format(self. get_username())) ax.set_xlabel('Date') ax.set_ylabel('Sentiment Value') ax.xaxis.set_major_locator(plt.MaxNLocator(10)) for tick in ax.get_xticklabels(): tick.set_rotation(45) ax.plot(self.plotData[0], self.plotData[1], '-bo', label= 'Sentiment Score') ax.plot(self.plotData[0], self.plotData[2], '-ro', label= 'Sentiment Magnitude') ax.legend(loc='lower right') self.canvas.draw() self.enableExport() """ Gets username from text field Input - self:Ui_Window Output - string """ def get_username(self): return self.ui.usernameLineEdit.text() """ Gets start date from spin boxes Input - self:Ui_Window Output - datetime.datetime """ def get_start_date(self): start_month = self.ui.startMonthSpinBox.value() start_day = self.ui.startDaySpinBox.value() start_year = self.ui.startYearSpinBox.value() try: startDate = datetime.datetime(start_year, start_month, start_day) except: self.printMessages([ 'Start date is improperly set. Check to see that the date is correct/exists.' ]) return None return startDate """ Gets end date from spin boxes Input - self:Ui_Window Output - datetime.datetime """ def get_end_date(self): end_month = self.ui.endMonthSpinBox.value() end_day = self.ui.endDaySpinBox.value() end_year = self.ui.endYearSpinBox.value() try: endDate = datetime.datetime(end_year, end_month, end_day) except: self.printMessages([ 'End date is improperly set. Check to see that the date is correct/exists.' ]) return None return endDate """ Toggles the export button. Input - self:Ui_Window Output - None """ def enableExport(self): self.ui.exportPushButton.setEnabled(True) """ Exports date, score/magntitude, and tweet text to csv and pops up a window when done Input - self:Ui_Window Output - None """ def exportValues(self): currentTimeDate = datetime.datetime.now() currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate .month) + '-' + str(currentTimeDate.day) + '-' + str( currentTimeDate.hour) + '-' + str(currentTimeDate.minute ) + '-' + str(currentTimeDate.second) with open(currentTimeDate + '_' + self.get_username() + '_score.csv', mode='w') as score_file: writer = csv.writer(score_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[1] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) with open(currentTimeDate + '_' + self.get_username() + '_magnitude.csv', mode='w') as magnitude_file: writer = csv.writer(magnitude_file) for i in range(len(self.plotData[0])): writer.writerow([str(self.plotData[0][i]), self.plotData[2] [i], self.tweetList[i].full_text.encode(encoding= 'UTF-8', errors='replace')]) msgBox = QMessageBox() msgBox.setText('CSV files exported!') msgBox.exec() """ Prints out messages in a pop up window Input - self:Ui_Window Output - None """ def printMessages(self, messageList): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setWindowTitle('Errors occured!') tempString = '' for message in messageList: tempString += message + '\n' msgBox.setText(tempString) msgBox.exec() if __name__ == '__main__': app = QApplication(sys.argv) window = Ui_Window() window.show() sys.exit(app.exec_()) <|reserved_special_token_1|> #--------------------------------------------- # File name: phase2app.py # Description: Launches GUI for Twitter User Timeline Sentiment Analysis program # Author: Gilbert Yap (gilberty@bu.edu) # Date: October 03, 2020 #--------------------------------------------- from PySide2.QtWidgets import QApplication, QDialog, QVBoxLayout, QMessageBox from PySide2.QtCore import Qt, QFile, QRegExp from PySide2.QtGui import QRegExpValidator from phase2GUI import Ui_Dialog from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import configparser, csv, datetime, sys sys.path.insert(1, '..\\SharedFiles\\') import matplotlib.pyplot as plt import helper, phase2Functions SETTINGS_FILE = '..\\SharedFiles\\settings.ini' class Ui_Window(QDialog): def __init__(self): super(Ui_Window, self).__init__() self.ui = Ui_Dialog() self.ui.setupUi(self) # Set regex validator for the username regex = QRegExp("\w+") validator = QRegExpValidator(regex) self.ui.usernameLineEdit.setValidator(validator) # Set the end date to today by default self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month) self.ui.endDaySpinBox.setValue(datetime.datetime.now().day) self.ui.endYearSpinBox.setValue(datetime.datetime.now().year) # Place a plot inside of plotDisplayGroupBox self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.ui.plotDisplayGroupBox.setLayout(layout) # Set up signals self.ui.processDatesPushButton.clicked.connect(self.plotSentiment) self.ui.exportPushButton.clicked.connect(self.exportValues) # Init APIs settings = configparser.ConfigParser() settings.read(SETTINGS_FILE) helper.print_with_stars('Initializing APIs') (twitterApi, googleClient, errors) = phase2Functions.init_apis(settings['KEYS']['api_key'], settings['KEYS']['api_secret_key']) if(len(errors) > 0): self.printMessages(errors) sys.exit(1) else: self.twitterApi = twitterApi self.googleClient = googleClient self.show() ''' Plot the sentiment score Input - self:Ui_Window Output - None ''' def plotSentiment(self): QApplication.setOverrideCursor(Qt.WaitCursor) # Get the sentiment data startDate = self.get_start_date() endDate = self.get_end_date() if (startDate is None) or (endDate is None): return (dateList, scoreList, magnitudeList, tweetList, errors) = phase2Functions.generate_data_lists(self.twitterApi, self.googleClient, self.get_username(), startDate, endDate) QApplication.restoreOverrideCursor() # If there were any errors, print them out if(len(errors) > 0): self.printMessages(errors) else: # If there are no errors, format and plot out the data self.plotData = (dateList, scoreList, magnitudeList) self.tweetList = tweetList self.figure.clear() ax = self.figure.add_subplot(111) self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17, right=0.9, hspace=0.2, wspace=0.2) ax.set_title("Sentiment Analysis of @{}'s tweets".format(self.get_username(),)) ax.set_xlabel("Date") ax.set_ylabel("Sentiment Value") ax.xaxis.set_major_locator(plt.MaxNLocator(10)) for tick in ax.get_xticklabels(): tick.set_rotation(45) ax.plot(self.plotData[0],self.plotData[1],"-bo",label='Sentiment Score') ax.plot(self.plotData[0],self.plotData[2], "-ro",label='Sentiment Magnitude') ax.legend(loc="lower right") self.canvas.draw() self.enableExport() ''' Gets username from text field Input - self:Ui_Window Output - string ''' def get_username(self): return (self.ui.usernameLineEdit.text()) ''' Gets start date from spin boxes Input - self:Ui_Window Output - datetime.datetime ''' def get_start_date(self): start_month = self.ui.startMonthSpinBox.value() start_day = self.ui.startDaySpinBox.value() start_year = self.ui.startYearSpinBox.value() try: startDate = datetime.datetime(start_year, start_month,start_day) except: self.printMessages(['Start date is improperly set. Check to see that the date is correct/exists.']) return None return startDate ''' Gets end date from spin boxes Input - self:Ui_Window Output - datetime.datetime ''' def get_end_date(self): end_month = self.ui.endMonthSpinBox.value() end_day = self.ui.endDaySpinBox.value() end_year = self.ui.endYearSpinBox.value() try: endDate = datetime.datetime(end_year, end_month,end_day) except: self.printMessages(['End date is improperly set. Check to see that the date is correct/exists.']) return None return endDate ''' Toggles the export button. Input - self:Ui_Window Output - None ''' def enableExport(self): self.ui.exportPushButton.setEnabled(True) ''' Exports date, score/magntitude, and tweet text to csv and pops up a window when done Input - self:Ui_Window Output - None ''' def exportValues(self): currentTimeDate = datetime.datetime.now() currentTimeDate = str(currentTimeDate.year)+'-'+str(currentTimeDate.month)+'-'+str(currentTimeDate.day)+'-'+str(currentTimeDate.hour)+'-'+str(currentTimeDate.minute)+'-'+str(currentTimeDate.second) with open(currentTimeDate+'_'+self.get_username()+'_score.csv', mode='w') as score_file: writer = csv.writer(score_file) for i in range(len(self.plotData[0])): writer.writerow( [ str(self.plotData[0][i]), self.plotData[1][i], self.tweetList[i].full_text.encode(encoding='UTF-8', errors='replace') ] ) with open(currentTimeDate+'_'+self.get_username()+'_magnitude.csv', mode='w') as magnitude_file: writer = csv.writer(magnitude_file) for i in range(len(self.plotData[0])): writer.writerow( [ str(self.plotData[0][i]), self.plotData[2][i], self.tweetList[i].full_text.encode(encoding='UTF-8', errors='replace') ] ) msgBox = QMessageBox() msgBox.setText('CSV files exported!') msgBox.exec() ''' Prints out messages in a pop up window Input - self:Ui_Window Output - None ''' def printMessages(self, messageList): msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Critical) msgBox.setWindowTitle('Errors occured!') tempString = '' for message in messageList: tempString += (message + '\n') msgBox.setText(tempString) msgBox.exec() if __name__ == "__main__": app = QApplication(sys.argv) window = Ui_Window() window.show() sys.exit(app.exec_())
flexible
{ "blob_id": "8cabacb64f3b193b957c61d6e1ca21f2046e52d1", "index": 8199, "step-1": "<mask token>\n\n\nclass Ui_Window(QDialog):\n\n def __init__(self):\n super(Ui_Window, self).__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n regex = QRegExp('\\\\w+')\n validator = QRegExpValidator(regex)\n self.ui.usernameLineEdit.setValidator(validator)\n self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month)\n self.ui.endDaySpinBox.setValue(datetime.datetime.now().day)\n self.ui.endYearSpinBox.setValue(datetime.datetime.now().year)\n self.figure = plt.figure()\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar(self.canvas, self)\n layout = QVBoxLayout()\n layout.addWidget(self.toolbar)\n layout.addWidget(self.canvas)\n self.ui.plotDisplayGroupBox.setLayout(layout)\n self.ui.processDatesPushButton.clicked.connect(self.plotSentiment)\n self.ui.exportPushButton.clicked.connect(self.exportValues)\n settings = configparser.ConfigParser()\n settings.read(SETTINGS_FILE)\n helper.print_with_stars('Initializing APIs')\n twitterApi, googleClient, errors = phase2Functions.init_apis(settings\n ['KEYS']['api_key'], settings['KEYS']['api_secret_key'])\n if len(errors) > 0:\n self.printMessages(errors)\n sys.exit(1)\n else:\n self.twitterApi = twitterApi\n self.googleClient = googleClient\n self.show()\n <mask token>\n\n def plotSentiment(self):\n QApplication.setOverrideCursor(Qt.WaitCursor)\n startDate = self.get_start_date()\n endDate = self.get_end_date()\n if startDate is None or endDate is None:\n return\n dateList, scoreList, magnitudeList, tweetList, errors = (\n phase2Functions.generate_data_lists(self.twitterApi, self.\n googleClient, self.get_username(), startDate, endDate))\n QApplication.restoreOverrideCursor()\n if len(errors) > 0:\n self.printMessages(errors)\n else:\n self.plotData = dateList, scoreList, magnitudeList\n self.tweetList = tweetList\n self.figure.clear()\n ax = self.figure.add_subplot(111)\n self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17,\n right=0.9, hspace=0.2, wspace=0.2)\n ax.set_title(\"Sentiment Analysis of @{}'s tweets\".format(self.\n get_username()))\n ax.set_xlabel('Date')\n ax.set_ylabel('Sentiment Value')\n ax.xaxis.set_major_locator(plt.MaxNLocator(10))\n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n ax.plot(self.plotData[0], self.plotData[1], '-bo', label=\n 'Sentiment Score')\n ax.plot(self.plotData[0], self.plotData[2], '-ro', label=\n 'Sentiment Magnitude')\n ax.legend(loc='lower right')\n self.canvas.draw()\n self.enableExport()\n <mask token>\n\n def get_username(self):\n return self.ui.usernameLineEdit.text()\n <mask token>\n\n def get_start_date(self):\n start_month = self.ui.startMonthSpinBox.value()\n start_day = self.ui.startDaySpinBox.value()\n start_year = self.ui.startYearSpinBox.value()\n try:\n startDate = datetime.datetime(start_year, start_month, start_day)\n except:\n self.printMessages([\n 'Start date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return startDate\n <mask token>\n\n def get_end_date(self):\n end_month = self.ui.endMonthSpinBox.value()\n end_day = self.ui.endDaySpinBox.value()\n end_year = self.ui.endYearSpinBox.value()\n try:\n endDate = datetime.datetime(end_year, end_month, end_day)\n except:\n self.printMessages([\n 'End date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return endDate\n <mask token>\n\n def enableExport(self):\n self.ui.exportPushButton.setEnabled(True)\n <mask token>\n\n def exportValues(self):\n currentTimeDate = datetime.datetime.now()\n currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate\n .month) + '-' + str(currentTimeDate.day) + '-' + str(\n currentTimeDate.hour) + '-' + str(currentTimeDate.minute\n ) + '-' + str(currentTimeDate.second)\n with open(currentTimeDate + '_' + self.get_username() +\n '_score.csv', mode='w') as score_file:\n writer = csv.writer(score_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[1]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n with open(currentTimeDate + '_' + self.get_username() +\n '_magnitude.csv', mode='w') as magnitude_file:\n writer = csv.writer(magnitude_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[2]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n msgBox = QMessageBox()\n msgBox.setText('CSV files exported!')\n msgBox.exec()\n <mask token>\n\n def printMessages(self, messageList):\n msgBox = QMessageBox()\n msgBox.setIcon(QMessageBox.Critical)\n msgBox.setWindowTitle('Errors occured!')\n tempString = ''\n for message in messageList:\n tempString += message + '\\n'\n msgBox.setText(tempString)\n msgBox.exec()\n\n\n<mask token>\n", "step-2": "<mask token>\nsys.path.insert(1, '..\\\\SharedFiles\\\\')\n<mask token>\n\n\nclass Ui_Window(QDialog):\n\n def __init__(self):\n super(Ui_Window, self).__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n regex = QRegExp('\\\\w+')\n validator = QRegExpValidator(regex)\n self.ui.usernameLineEdit.setValidator(validator)\n self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month)\n self.ui.endDaySpinBox.setValue(datetime.datetime.now().day)\n self.ui.endYearSpinBox.setValue(datetime.datetime.now().year)\n self.figure = plt.figure()\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar(self.canvas, self)\n layout = QVBoxLayout()\n layout.addWidget(self.toolbar)\n layout.addWidget(self.canvas)\n self.ui.plotDisplayGroupBox.setLayout(layout)\n self.ui.processDatesPushButton.clicked.connect(self.plotSentiment)\n self.ui.exportPushButton.clicked.connect(self.exportValues)\n settings = configparser.ConfigParser()\n settings.read(SETTINGS_FILE)\n helper.print_with_stars('Initializing APIs')\n twitterApi, googleClient, errors = phase2Functions.init_apis(settings\n ['KEYS']['api_key'], settings['KEYS']['api_secret_key'])\n if len(errors) > 0:\n self.printMessages(errors)\n sys.exit(1)\n else:\n self.twitterApi = twitterApi\n self.googleClient = googleClient\n self.show()\n \"\"\"\n Plot the sentiment score\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def plotSentiment(self):\n QApplication.setOverrideCursor(Qt.WaitCursor)\n startDate = self.get_start_date()\n endDate = self.get_end_date()\n if startDate is None or endDate is None:\n return\n dateList, scoreList, magnitudeList, tweetList, errors = (\n phase2Functions.generate_data_lists(self.twitterApi, self.\n googleClient, self.get_username(), startDate, endDate))\n QApplication.restoreOverrideCursor()\n if len(errors) > 0:\n self.printMessages(errors)\n else:\n self.plotData = dateList, scoreList, magnitudeList\n self.tweetList = tweetList\n self.figure.clear()\n ax = self.figure.add_subplot(111)\n self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17,\n right=0.9, hspace=0.2, wspace=0.2)\n ax.set_title(\"Sentiment Analysis of @{}'s tweets\".format(self.\n get_username()))\n ax.set_xlabel('Date')\n ax.set_ylabel('Sentiment Value')\n ax.xaxis.set_major_locator(plt.MaxNLocator(10))\n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n ax.plot(self.plotData[0], self.plotData[1], '-bo', label=\n 'Sentiment Score')\n ax.plot(self.plotData[0], self.plotData[2], '-ro', label=\n 'Sentiment Magnitude')\n ax.legend(loc='lower right')\n self.canvas.draw()\n self.enableExport()\n \"\"\"\n Gets username from text field\n Input - self:Ui_Window\n Output - string\n \"\"\"\n\n def get_username(self):\n return self.ui.usernameLineEdit.text()\n \"\"\"\n Gets start date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n \"\"\"\n\n def get_start_date(self):\n start_month = self.ui.startMonthSpinBox.value()\n start_day = self.ui.startDaySpinBox.value()\n start_year = self.ui.startYearSpinBox.value()\n try:\n startDate = datetime.datetime(start_year, start_month, start_day)\n except:\n self.printMessages([\n 'Start date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return startDate\n \"\"\"\n Gets end date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n \"\"\"\n\n def get_end_date(self):\n end_month = self.ui.endMonthSpinBox.value()\n end_day = self.ui.endDaySpinBox.value()\n end_year = self.ui.endYearSpinBox.value()\n try:\n endDate = datetime.datetime(end_year, end_month, end_day)\n except:\n self.printMessages([\n 'End date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return endDate\n \"\"\"\n Toggles the export button.\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def enableExport(self):\n self.ui.exportPushButton.setEnabled(True)\n \"\"\"\n Exports date, score/magntitude, and tweet text to csv and pops up a window when done\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def exportValues(self):\n currentTimeDate = datetime.datetime.now()\n currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate\n .month) + '-' + str(currentTimeDate.day) + '-' + str(\n currentTimeDate.hour) + '-' + str(currentTimeDate.minute\n ) + '-' + str(currentTimeDate.second)\n with open(currentTimeDate + '_' + self.get_username() +\n '_score.csv', mode='w') as score_file:\n writer = csv.writer(score_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[1]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n with open(currentTimeDate + '_' + self.get_username() +\n '_magnitude.csv', mode='w') as magnitude_file:\n writer = csv.writer(magnitude_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[2]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n msgBox = QMessageBox()\n msgBox.setText('CSV files exported!')\n msgBox.exec()\n \"\"\"\n Prints out messages in a pop up window\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def printMessages(self, messageList):\n msgBox = QMessageBox()\n msgBox.setIcon(QMessageBox.Critical)\n msgBox.setWindowTitle('Errors occured!')\n tempString = ''\n for message in messageList:\n tempString += message + '\\n'\n msgBox.setText(tempString)\n msgBox.exec()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = Ui_Window()\n window.show()\n sys.exit(app.exec_())\n", "step-3": "<mask token>\nsys.path.insert(1, '..\\\\SharedFiles\\\\')\n<mask token>\nSETTINGS_FILE = '..\\\\SharedFiles\\\\settings.ini'\n\n\nclass Ui_Window(QDialog):\n\n def __init__(self):\n super(Ui_Window, self).__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n regex = QRegExp('\\\\w+')\n validator = QRegExpValidator(regex)\n self.ui.usernameLineEdit.setValidator(validator)\n self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month)\n self.ui.endDaySpinBox.setValue(datetime.datetime.now().day)\n self.ui.endYearSpinBox.setValue(datetime.datetime.now().year)\n self.figure = plt.figure()\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar(self.canvas, self)\n layout = QVBoxLayout()\n layout.addWidget(self.toolbar)\n layout.addWidget(self.canvas)\n self.ui.plotDisplayGroupBox.setLayout(layout)\n self.ui.processDatesPushButton.clicked.connect(self.plotSentiment)\n self.ui.exportPushButton.clicked.connect(self.exportValues)\n settings = configparser.ConfigParser()\n settings.read(SETTINGS_FILE)\n helper.print_with_stars('Initializing APIs')\n twitterApi, googleClient, errors = phase2Functions.init_apis(settings\n ['KEYS']['api_key'], settings['KEYS']['api_secret_key'])\n if len(errors) > 0:\n self.printMessages(errors)\n sys.exit(1)\n else:\n self.twitterApi = twitterApi\n self.googleClient = googleClient\n self.show()\n \"\"\"\n Plot the sentiment score\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def plotSentiment(self):\n QApplication.setOverrideCursor(Qt.WaitCursor)\n startDate = self.get_start_date()\n endDate = self.get_end_date()\n if startDate is None or endDate is None:\n return\n dateList, scoreList, magnitudeList, tweetList, errors = (\n phase2Functions.generate_data_lists(self.twitterApi, self.\n googleClient, self.get_username(), startDate, endDate))\n QApplication.restoreOverrideCursor()\n if len(errors) > 0:\n self.printMessages(errors)\n else:\n self.plotData = dateList, scoreList, magnitudeList\n self.tweetList = tweetList\n self.figure.clear()\n ax = self.figure.add_subplot(111)\n self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17,\n right=0.9, hspace=0.2, wspace=0.2)\n ax.set_title(\"Sentiment Analysis of @{}'s tweets\".format(self.\n get_username()))\n ax.set_xlabel('Date')\n ax.set_ylabel('Sentiment Value')\n ax.xaxis.set_major_locator(plt.MaxNLocator(10))\n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n ax.plot(self.plotData[0], self.plotData[1], '-bo', label=\n 'Sentiment Score')\n ax.plot(self.plotData[0], self.plotData[2], '-ro', label=\n 'Sentiment Magnitude')\n ax.legend(loc='lower right')\n self.canvas.draw()\n self.enableExport()\n \"\"\"\n Gets username from text field\n Input - self:Ui_Window\n Output - string\n \"\"\"\n\n def get_username(self):\n return self.ui.usernameLineEdit.text()\n \"\"\"\n Gets start date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n \"\"\"\n\n def get_start_date(self):\n start_month = self.ui.startMonthSpinBox.value()\n start_day = self.ui.startDaySpinBox.value()\n start_year = self.ui.startYearSpinBox.value()\n try:\n startDate = datetime.datetime(start_year, start_month, start_day)\n except:\n self.printMessages([\n 'Start date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return startDate\n \"\"\"\n Gets end date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n \"\"\"\n\n def get_end_date(self):\n end_month = self.ui.endMonthSpinBox.value()\n end_day = self.ui.endDaySpinBox.value()\n end_year = self.ui.endYearSpinBox.value()\n try:\n endDate = datetime.datetime(end_year, end_month, end_day)\n except:\n self.printMessages([\n 'End date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return endDate\n \"\"\"\n Toggles the export button.\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def enableExport(self):\n self.ui.exportPushButton.setEnabled(True)\n \"\"\"\n Exports date, score/magntitude, and tweet text to csv and pops up a window when done\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def exportValues(self):\n currentTimeDate = datetime.datetime.now()\n currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate\n .month) + '-' + str(currentTimeDate.day) + '-' + str(\n currentTimeDate.hour) + '-' + str(currentTimeDate.minute\n ) + '-' + str(currentTimeDate.second)\n with open(currentTimeDate + '_' + self.get_username() +\n '_score.csv', mode='w') as score_file:\n writer = csv.writer(score_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[1]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n with open(currentTimeDate + '_' + self.get_username() +\n '_magnitude.csv', mode='w') as magnitude_file:\n writer = csv.writer(magnitude_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[2]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n msgBox = QMessageBox()\n msgBox.setText('CSV files exported!')\n msgBox.exec()\n \"\"\"\n Prints out messages in a pop up window\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def printMessages(self, messageList):\n msgBox = QMessageBox()\n msgBox.setIcon(QMessageBox.Critical)\n msgBox.setWindowTitle('Errors occured!')\n tempString = ''\n for message in messageList:\n tempString += message + '\\n'\n msgBox.setText(tempString)\n msgBox.exec()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = Ui_Window()\n window.show()\n sys.exit(app.exec_())\n", "step-4": "from PySide2.QtWidgets import QApplication, QDialog, QVBoxLayout, QMessageBox\nfrom PySide2.QtCore import Qt, QFile, QRegExp\nfrom PySide2.QtGui import QRegExpValidator\nfrom phase2GUI import Ui_Dialog\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\nimport configparser, csv, datetime, sys\nsys.path.insert(1, '..\\\\SharedFiles\\\\')\nimport matplotlib.pyplot as plt\nimport helper, phase2Functions\nSETTINGS_FILE = '..\\\\SharedFiles\\\\settings.ini'\n\n\nclass Ui_Window(QDialog):\n\n def __init__(self):\n super(Ui_Window, self).__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n regex = QRegExp('\\\\w+')\n validator = QRegExpValidator(regex)\n self.ui.usernameLineEdit.setValidator(validator)\n self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month)\n self.ui.endDaySpinBox.setValue(datetime.datetime.now().day)\n self.ui.endYearSpinBox.setValue(datetime.datetime.now().year)\n self.figure = plt.figure()\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar(self.canvas, self)\n layout = QVBoxLayout()\n layout.addWidget(self.toolbar)\n layout.addWidget(self.canvas)\n self.ui.plotDisplayGroupBox.setLayout(layout)\n self.ui.processDatesPushButton.clicked.connect(self.plotSentiment)\n self.ui.exportPushButton.clicked.connect(self.exportValues)\n settings = configparser.ConfigParser()\n settings.read(SETTINGS_FILE)\n helper.print_with_stars('Initializing APIs')\n twitterApi, googleClient, errors = phase2Functions.init_apis(settings\n ['KEYS']['api_key'], settings['KEYS']['api_secret_key'])\n if len(errors) > 0:\n self.printMessages(errors)\n sys.exit(1)\n else:\n self.twitterApi = twitterApi\n self.googleClient = googleClient\n self.show()\n \"\"\"\n Plot the sentiment score\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def plotSentiment(self):\n QApplication.setOverrideCursor(Qt.WaitCursor)\n startDate = self.get_start_date()\n endDate = self.get_end_date()\n if startDate is None or endDate is None:\n return\n dateList, scoreList, magnitudeList, tweetList, errors = (\n phase2Functions.generate_data_lists(self.twitterApi, self.\n googleClient, self.get_username(), startDate, endDate))\n QApplication.restoreOverrideCursor()\n if len(errors) > 0:\n self.printMessages(errors)\n else:\n self.plotData = dateList, scoreList, magnitudeList\n self.tweetList = tweetList\n self.figure.clear()\n ax = self.figure.add_subplot(111)\n self.figure.subplots_adjust(top=0.88, bottom=0.255, left=0.17,\n right=0.9, hspace=0.2, wspace=0.2)\n ax.set_title(\"Sentiment Analysis of @{}'s tweets\".format(self.\n get_username()))\n ax.set_xlabel('Date')\n ax.set_ylabel('Sentiment Value')\n ax.xaxis.set_major_locator(plt.MaxNLocator(10))\n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n ax.plot(self.plotData[0], self.plotData[1], '-bo', label=\n 'Sentiment Score')\n ax.plot(self.plotData[0], self.plotData[2], '-ro', label=\n 'Sentiment Magnitude')\n ax.legend(loc='lower right')\n self.canvas.draw()\n self.enableExport()\n \"\"\"\n Gets username from text field\n Input - self:Ui_Window\n Output - string\n \"\"\"\n\n def get_username(self):\n return self.ui.usernameLineEdit.text()\n \"\"\"\n Gets start date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n \"\"\"\n\n def get_start_date(self):\n start_month = self.ui.startMonthSpinBox.value()\n start_day = self.ui.startDaySpinBox.value()\n start_year = self.ui.startYearSpinBox.value()\n try:\n startDate = datetime.datetime(start_year, start_month, start_day)\n except:\n self.printMessages([\n 'Start date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return startDate\n \"\"\"\n Gets end date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n \"\"\"\n\n def get_end_date(self):\n end_month = self.ui.endMonthSpinBox.value()\n end_day = self.ui.endDaySpinBox.value()\n end_year = self.ui.endYearSpinBox.value()\n try:\n endDate = datetime.datetime(end_year, end_month, end_day)\n except:\n self.printMessages([\n 'End date is improperly set. Check to see that the date is correct/exists.'\n ])\n return None\n return endDate\n \"\"\"\n Toggles the export button.\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def enableExport(self):\n self.ui.exportPushButton.setEnabled(True)\n \"\"\"\n Exports date, score/magntitude, and tweet text to csv and pops up a window when done\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def exportValues(self):\n currentTimeDate = datetime.datetime.now()\n currentTimeDate = str(currentTimeDate.year) + '-' + str(currentTimeDate\n .month) + '-' + str(currentTimeDate.day) + '-' + str(\n currentTimeDate.hour) + '-' + str(currentTimeDate.minute\n ) + '-' + str(currentTimeDate.second)\n with open(currentTimeDate + '_' + self.get_username() +\n '_score.csv', mode='w') as score_file:\n writer = csv.writer(score_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[1]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n with open(currentTimeDate + '_' + self.get_username() +\n '_magnitude.csv', mode='w') as magnitude_file:\n writer = csv.writer(magnitude_file)\n for i in range(len(self.plotData[0])):\n writer.writerow([str(self.plotData[0][i]), self.plotData[2]\n [i], self.tweetList[i].full_text.encode(encoding=\n 'UTF-8', errors='replace')])\n msgBox = QMessageBox()\n msgBox.setText('CSV files exported!')\n msgBox.exec()\n \"\"\"\n Prints out messages in a pop up window\n Input - self:Ui_Window\n Output - None\n \"\"\"\n\n def printMessages(self, messageList):\n msgBox = QMessageBox()\n msgBox.setIcon(QMessageBox.Critical)\n msgBox.setWindowTitle('Errors occured!')\n tempString = ''\n for message in messageList:\n tempString += message + '\\n'\n msgBox.setText(tempString)\n msgBox.exec()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n window = Ui_Window()\n window.show()\n sys.exit(app.exec_())\n", "step-5": "#---------------------------------------------\n# File name: phase2app.py\n# Description: Launches GUI for Twitter User Timeline Sentiment Analysis program\n# Author: Gilbert Yap (gilberty@bu.edu)\n# Date: October 03, 2020\n#---------------------------------------------\n\nfrom PySide2.QtWidgets import QApplication, QDialog, QVBoxLayout, QMessageBox\nfrom PySide2.QtCore import Qt, QFile, QRegExp\nfrom PySide2.QtGui import QRegExpValidator\nfrom phase2GUI import Ui_Dialog\n\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nfrom matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\n\nimport configparser, csv, datetime, sys\nsys.path.insert(1, '..\\\\SharedFiles\\\\')\nimport matplotlib.pyplot as plt\nimport helper, phase2Functions\n\nSETTINGS_FILE = '..\\\\SharedFiles\\\\settings.ini'\n\nclass Ui_Window(QDialog):\n def __init__(self):\n super(Ui_Window, self).__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n\n # Set regex validator for the username\n regex = QRegExp(\"\\w+\")\n validator = QRegExpValidator(regex)\n self.ui.usernameLineEdit.setValidator(validator)\n\n # Set the end date to today by default\n self.ui.endMonthSpinBox.setValue(datetime.datetime.now().month)\n self.ui.endDaySpinBox.setValue(datetime.datetime.now().day)\n self.ui.endYearSpinBox.setValue(datetime.datetime.now().year)\n \n # Place a plot inside of plotDisplayGroupBox\n self.figure = plt.figure()\n self.canvas = FigureCanvas(self.figure)\n self.toolbar = NavigationToolbar(self.canvas, self)\n layout = QVBoxLayout()\n layout.addWidget(self.toolbar)\n layout.addWidget(self.canvas)\n self.ui.plotDisplayGroupBox.setLayout(layout)\n\n # Set up signals\n self.ui.processDatesPushButton.clicked.connect(self.plotSentiment)\n self.ui.exportPushButton.clicked.connect(self.exportValues)\n\n # Init APIs\n settings = configparser.ConfigParser()\n settings.read(SETTINGS_FILE)\n\n helper.print_with_stars('Initializing APIs')\n (twitterApi, googleClient, errors) = phase2Functions.init_apis(settings['KEYS']['api_key'], settings['KEYS']['api_secret_key'])\n\n if(len(errors) > 0):\n self.printMessages(errors)\n sys.exit(1)\n else:\n self.twitterApi = twitterApi\n self.googleClient = googleClient\n self.show()\n\n '''\n Plot the sentiment score\n Input - self:Ui_Window\n Output - None\n '''\n def plotSentiment(self):\n QApplication.setOverrideCursor(Qt.WaitCursor)\n # Get the sentiment data\n startDate = self.get_start_date()\n endDate = self.get_end_date()\n \n if (startDate is None) or (endDate is None):\n return\n \n (dateList, scoreList, magnitudeList, tweetList, errors) = phase2Functions.generate_data_lists(self.twitterApi, self.googleClient, self.get_username(), startDate, endDate)\n QApplication.restoreOverrideCursor()\n \n # If there were any errors, print them out\n if(len(errors) > 0):\n self.printMessages(errors)\n else:\n # If there are no errors, format and plot out the data\n self.plotData = (dateList, scoreList, magnitudeList)\n self.tweetList = tweetList\n self.figure.clear()\n ax = self.figure.add_subplot(111)\n self.figure.subplots_adjust(top=0.88,\n bottom=0.255,\n left=0.17,\n right=0.9,\n hspace=0.2,\n wspace=0.2)\n\n ax.set_title(\"Sentiment Analysis of @{}'s tweets\".format(self.get_username(),)) \n ax.set_xlabel(\"Date\") \n ax.set_ylabel(\"Sentiment Value\") \n ax.xaxis.set_major_locator(plt.MaxNLocator(10))\n \n for tick in ax.get_xticklabels():\n tick.set_rotation(45)\n\n ax.plot(self.plotData[0],self.plotData[1],\"-bo\",label='Sentiment Score') \n ax.plot(self.plotData[0],self.plotData[2], \"-ro\",label='Sentiment Magnitude')\n ax.legend(loc=\"lower right\")\n self.canvas.draw()\n self.enableExport()\n\n\n '''\n Gets username from text field\n Input - self:Ui_Window\n Output - string\n '''\n def get_username(self):\n return (self.ui.usernameLineEdit.text())\n\n '''\n Gets start date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n '''\n def get_start_date(self):\n start_month = self.ui.startMonthSpinBox.value()\n start_day = self.ui.startDaySpinBox.value()\n start_year = self.ui.startYearSpinBox.value()\n \n try:\n startDate = datetime.datetime(start_year, start_month,start_day)\n except:\n self.printMessages(['Start date is improperly set. Check to see that the date is correct/exists.'])\n return None\n \n return startDate\n\n '''\n Gets end date from spin boxes\n Input - self:Ui_Window\n Output - datetime.datetime\n '''\n def get_end_date(self):\n end_month = self.ui.endMonthSpinBox.value()\n end_day = self.ui.endDaySpinBox.value()\n end_year = self.ui.endYearSpinBox.value()\n \n try:\n endDate = datetime.datetime(end_year, end_month,end_day)\n except:\n self.printMessages(['End date is improperly set. Check to see that the date is correct/exists.'])\n return None\n \n return endDate\n\n '''\n Toggles the export button.\n Input - self:Ui_Window\n Output - None\n '''\n def enableExport(self):\n self.ui.exportPushButton.setEnabled(True)\n\n '''\n Exports date, score/magntitude, and tweet text to csv and pops up a window when done\n Input - self:Ui_Window\n Output - None\n '''\n def exportValues(self):\n currentTimeDate = datetime.datetime.now()\n currentTimeDate = str(currentTimeDate.year)+'-'+str(currentTimeDate.month)+'-'+str(currentTimeDate.day)+'-'+str(currentTimeDate.hour)+'-'+str(currentTimeDate.minute)+'-'+str(currentTimeDate.second)\n\n with open(currentTimeDate+'_'+self.get_username()+'_score.csv', mode='w') as score_file:\n writer = csv.writer(score_file)\n for i in range(len(self.plotData[0])):\n writer.writerow( [ str(self.plotData[0][i]), self.plotData[1][i], \n self.tweetList[i].full_text.encode(encoding='UTF-8', errors='replace') ] )\n\n with open(currentTimeDate+'_'+self.get_username()+'_magnitude.csv', mode='w') as magnitude_file:\n writer = csv.writer(magnitude_file)\n for i in range(len(self.plotData[0])):\n writer.writerow( [ str(self.plotData[0][i]), self.plotData[2][i], \n self.tweetList[i].full_text.encode(encoding='UTF-8', errors='replace') ] )\n\n msgBox = QMessageBox()\n msgBox.setText('CSV files exported!')\n msgBox.exec()\n\n '''\n Prints out messages in a pop up window\n Input - self:Ui_Window\n Output - None\n '''\n def printMessages(self, messageList):\n msgBox = QMessageBox()\n msgBox.setIcon(QMessageBox.Critical)\n msgBox.setWindowTitle('Errors occured!')\n tempString = ''\n\n for message in messageList:\n tempString += (message + '\\n')\n msgBox.setText(tempString)\n msgBox.exec()\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n\n window = Ui_Window()\n window.show()\n\n sys.exit(app.exec_())", "step-ids": [ 9, 11, 12, 13, 14 ] }
[ 9, 11, 12, 13, 14 ]
import dtw import stats import glob import argparse import matplotlib.pyplot as plt GRAPH = False PERCENTAGE = False VERBOSE = False def buildExpectations(queryPath, searchPatternPath): """ Based on SpeechCommand_v0.02 directory structure. """ expectations = [] currentDirectory = "" queryFilename = queryPath.split("/")[-1] queryDirectory = queryPath.split("/")[-2] queryCode = queryFilename.split("_")[0] searchFileList = sorted(glob.glob(searchPatternPath)) for searchFile in searchFileList: searchFilename = searchFile.split("/")[-1] searchDirectory = searchFile.split("/")[-2] searchCode = searchFilename.split("_")[0] if searchDirectory != currentDirectory: currentDirectory = searchDirectory if searchCode == queryCode: if currentDirectory == queryDirectory: expectations.append([[0, 1]]) else: expectations.append([[0, 0]]) return expectations if __name__ == "__main__": # Parse arguments parser = argparse.ArgumentParser(description='Dynamic Time Warping') parser.add_argument('-g', '--graph', action='store_true', help='Enable graph display') parser.add_argument('-t', '--threshold', type=float, default=0.4, help='Set score threshold') parser.add_argument('query_path') parser.add_argument('search_pattern_path') printGroup = parser.add_mutually_exclusive_group() printGroup.add_argument('-p', '--percentage', action='store_true', help='Enable percentage display') printGroup.add_argument('-v', '--verbose', action='store_true', help='Enable verbose display') args = parser.parse_args() GRAPH = args.graph PERCENTAGE = args.percentage threshold = args.threshold VERBOSE = args.verbose queryPath = args.query_path searchPatternPath = args.search_pattern_path dtw.VERBOSE = VERBOSE stats.VERBOSE = VERBOSE labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath) results = dtw.computeResultsPrecisely(sweepList, threshold, positiveOnly=True) for i, result in enumerate(results): print(labels[i] + ": ", end='') for j, (hitIndex, _) in enumerate(result): print(hitIndex * 3, end='') if j < len(result) - 1: print(" | ", end='') print() if GRAPH: dtw.showSweeps(labels, sweepList, bestList) plt.show()
normal
{ "blob_id": "03fb1cf0aac0c37858dd8163562a7139ed4e1179", "index": 776, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = ''\n queryFilename = queryPath.split('/')[-1]\n queryDirectory = queryPath.split('/')[-2]\n queryCode = queryFilename.split('_')[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split('/')[-1]\n searchDirectory = searchFile.split('/')[-2]\n searchCode = searchFilename.split('_')[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help=\n 'Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help=\n 'Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help\n ='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help=\n 'Enable verbose display')\n args = parser.parse_args()\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n results = dtw.computeResultsPrecisely(sweepList, threshold,\n positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + ': ', end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(' | ', end='')\n print()\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n plt.show()\n", "step-3": "<mask token>\nGRAPH = False\nPERCENTAGE = False\nVERBOSE = False\n\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = ''\n queryFilename = queryPath.split('/')[-1]\n queryDirectory = queryPath.split('/')[-2]\n queryCode = queryFilename.split('_')[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split('/')[-1]\n searchDirectory = searchFile.split('/')[-2]\n searchCode = searchFilename.split('_')[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help=\n 'Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help=\n 'Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help\n ='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help=\n 'Enable verbose display')\n args = parser.parse_args()\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n results = dtw.computeResultsPrecisely(sweepList, threshold,\n positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + ': ', end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(' | ', end='')\n print()\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n plt.show()\n", "step-4": "import dtw\nimport stats\nimport glob\nimport argparse\nimport matplotlib.pyplot as plt\nGRAPH = False\nPERCENTAGE = False\nVERBOSE = False\n\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = ''\n queryFilename = queryPath.split('/')[-1]\n queryDirectory = queryPath.split('/')[-2]\n queryCode = queryFilename.split('_')[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split('/')[-1]\n searchDirectory = searchFile.split('/')[-2]\n searchCode = searchFilename.split('_')[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help=\n 'Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help=\n 'Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help\n ='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help=\n 'Enable verbose display')\n args = parser.parse_args()\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n results = dtw.computeResultsPrecisely(sweepList, threshold,\n positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + ': ', end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(' | ', end='')\n print()\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n plt.show()\n", "step-5": "import dtw\nimport stats\n\nimport glob\nimport argparse\nimport matplotlib.pyplot as plt\n\nGRAPH = False\nPERCENTAGE = False\nVERBOSE = False\n\ndef buildExpectations(queryPath, searchPatternPath):\n \"\"\"\n Based on SpeechCommand_v0.02 directory structure.\n \"\"\"\n expectations = []\n currentDirectory = \"\"\n queryFilename = queryPath.split(\"/\")[-1]\n queryDirectory = queryPath.split(\"/\")[-2]\n queryCode = queryFilename.split(\"_\")[0]\n searchFileList = sorted(glob.glob(searchPatternPath))\n for searchFile in searchFileList:\n searchFilename = searchFile.split(\"/\")[-1]\n searchDirectory = searchFile.split(\"/\")[-2]\n searchCode = searchFilename.split(\"_\")[0]\n if searchDirectory != currentDirectory:\n currentDirectory = searchDirectory\n if searchCode == queryCode:\n if currentDirectory == queryDirectory:\n expectations.append([[0, 1]])\n else:\n expectations.append([[0, 0]])\n return expectations\n\nif __name__ == \"__main__\":\n # Parse arguments\n parser = argparse.ArgumentParser(description='Dynamic Time Warping')\n parser.add_argument('-g', '--graph', action='store_true', help='Enable graph display')\n parser.add_argument('-t', '--threshold', type=float, default=0.4, help='Set score threshold')\n parser.add_argument('query_path')\n parser.add_argument('search_pattern_path')\n\n printGroup = parser.add_mutually_exclusive_group()\n printGroup.add_argument('-p', '--percentage', action='store_true', help='Enable percentage display')\n printGroup.add_argument('-v', '--verbose', action='store_true', help='Enable verbose display')\n\n args = parser.parse_args()\n\n GRAPH = args.graph\n PERCENTAGE = args.percentage\n threshold = args.threshold\n VERBOSE = args.verbose\n queryPath = args.query_path\n searchPatternPath = args.search_pattern_path\n\n dtw.VERBOSE = VERBOSE\n stats.VERBOSE = VERBOSE\n\n labels, sweepList, bestList = dtw.runSearch(queryPath, searchPatternPath)\n\n results = dtw.computeResultsPrecisely(sweepList, threshold, positiveOnly=True)\n for i, result in enumerate(results):\n print(labels[i] + \": \", end='')\n for j, (hitIndex, _) in enumerate(result):\n print(hitIndex * 3, end='')\n if j < len(result) - 1:\n print(\" | \", end='')\n print()\n\n if GRAPH:\n dtw.showSweeps(labels, sweepList, bestList)\n\n plt.show()\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
''' 文件读写的步骤 1.打开文件 2.处理数据 3.关闭文件 1.open函数: fileobj = open(filename, mode) fileobj是open()函数返回的文件对象 mode第一个字母指明文件类型和操作的字符串,第二个字母是文件类型: t(可省略)文本类型,b二进制类型。 文件打开模式:r只读(默认),w覆盖写(不存在则新创建) a追加模式(不存在则创建) 2.read(size):从文件读取长度为size的字符串,若未给定或为负则读取所有内容 3.readline():读取整行返回字符串 4.readlines():读取所有行并返回列表 5.write(s):把字符串s的内容写入文件 ''' ''' #复制一个文件 fileobj1 = open("test1.txt", "r") fileobj2 = open("test2.txt", "w") s = fileobj1.read() fileobj2.write(s) fileobj1.close() fileobj2.close() ''' #多行文件读写 fileobj3 = open("lines.txt", "r") for line in fileobj3.readlines(): print(line) fileobj3.close()
normal
{ "blob_id": "25f3c9f48b779d2aec260d529529156ff3c508ca", "index": 7719, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor line in fileobj3.readlines():\n print(line)\nfileobj3.close()\n", "step-3": "<mask token>\nfileobj3 = open('lines.txt', 'r')\nfor line in fileobj3.readlines():\n print(line)\nfileobj3.close()\n", "step-4": "'''\n文件读写的步骤\n 1.打开文件\n 2.处理数据\n 3.关闭文件\n1.open函数:\n fileobj = open(filename, mode)\n fileobj是open()函数返回的文件对象\n mode第一个字母指明文件类型和操作的字符串,第二个字母是文件类型:\n t(可省略)文本类型,b二进制类型。\n 文件打开模式:r只读(默认),w覆盖写(不存在则新创建)\n a追加模式(不存在则创建)\n2.read(size):从文件读取长度为size的字符串,若未给定或为负则读取所有内容\n3.readline():读取整行返回字符串\n4.readlines():读取所有行并返回列表\n5.write(s):把字符串s的内容写入文件\n'''\n'''\n#复制一个文件\nfileobj1 = open(\"test1.txt\", \"r\")\nfileobj2 = open(\"test2.txt\", \"w\")\ns = fileobj1.read()\nfileobj2.write(s)\nfileobj1.close()\nfileobj2.close()\n'''\n\n#多行文件读写\nfileobj3 = open(\"lines.txt\", \"r\")\nfor line in fileobj3.readlines():\n print(line)\nfileobj3.close()", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> class AFB_L1(nn.Module): <|reserved_special_token_0|> <|reserved_special_token_0|> class AFB_L2(nn.Module): def __init__(self, channels, n_l1=4, act=nn.ReLU(True)): super(AFB_L2, self).__init__() self.n = n_l1 self.convs_ = nn.ModuleList() for _ in range(n_l1): self.convs_.append(AFB_L1(channels, 3, act)) self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d( channels * n_l1, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L3(nn.Module): def __init__(self, channels, n_l2=4, act=nn.ReLU(True)): super(AFB_L3, self).__init__() self.n = n_l2 self.convs_ = nn.ModuleList() for _ in range(n_l2): self.convs_.append(AFB_L2(channels, 4, act)) self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d( channels * n_l2, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFN(nn.Module): def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act= nn.LeakyReLU(0.2, True)): super(AFN, self).__init__() self.head = conv_(in_c, n_feats) self.n = n_l3 self.AFBs = nn.ModuleList() for i in range(n_l3): self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act)) self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats * n_l3, n_feats, 1, padding=0, stride=1)]) self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats, kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats, out_c)]) def forward(self, x): res = [] x = self.head(x) for i in range(self.n): x = self.AFBs[i](x) res.append(x) res = self.GFF(torch.cat(res, 1)) x = res + x x = self.tail(x) return x <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class AFB_0(nn.Module): def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)): super(AFB_0, self).__init__() self.op = [] for _ in range(n_blocks): self.op.append(conv_(channels, channels)) self.op.append(act) self.op = nn.Sequential(*self.op) <|reserved_special_token_0|> class AFB_L1(nn.Module): def __init__(self, channels, n_l0=3, act=nn.ReLU(True)): super(AFB_L1, self).__init__() self.n = n_l0 self.convs_ = nn.ModuleList() for _ in range(n_l0): self.convs_.append(AFB_0(channels, 2, act)) self.LFF = nn.Sequential(SELayer(channels * n_l0, 16), nn.Conv2d( channels * n_l0, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L2(nn.Module): def __init__(self, channels, n_l1=4, act=nn.ReLU(True)): super(AFB_L2, self).__init__() self.n = n_l1 self.convs_ = nn.ModuleList() for _ in range(n_l1): self.convs_.append(AFB_L1(channels, 3, act)) self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d( channels * n_l1, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L3(nn.Module): def __init__(self, channels, n_l2=4, act=nn.ReLU(True)): super(AFB_L3, self).__init__() self.n = n_l2 self.convs_ = nn.ModuleList() for _ in range(n_l2): self.convs_.append(AFB_L2(channels, 4, act)) self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d( channels * n_l2, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFN(nn.Module): def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act= nn.LeakyReLU(0.2, True)): super(AFN, self).__init__() self.head = conv_(in_c, n_feats) self.n = n_l3 self.AFBs = nn.ModuleList() for i in range(n_l3): self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act)) self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats * n_l3, n_feats, 1, padding=0, stride=1)]) self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats, kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats, out_c)]) def forward(self, x): res = [] x = self.head(x) for i in range(self.n): x = self.AFBs[i](x) res.append(x) res = self.GFF(torch.cat(res, 1)) x = res + x x = self.tail(x) return x <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def wrapper(args): act = None if args.act == 'relu': act = nn.ReLU(True) elif args.act == 'leak_relu': act = nn.LeakyReLU(0.2, True) elif args.act is None: act = None else: raise NotImplementedError return AFN(in_c=args.n_colors, out_c=args.n_colors, scale=args.scale, n_feats=args.n_feats, act=act) class AFB_0(nn.Module): def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)): super(AFB_0, self).__init__() self.op = [] for _ in range(n_blocks): self.op.append(conv_(channels, channels)) self.op.append(act) self.op = nn.Sequential(*self.op) def forward(self, x): x = x + self.op(x) return x class AFB_L1(nn.Module): def __init__(self, channels, n_l0=3, act=nn.ReLU(True)): super(AFB_L1, self).__init__() self.n = n_l0 self.convs_ = nn.ModuleList() for _ in range(n_l0): self.convs_.append(AFB_0(channels, 2, act)) self.LFF = nn.Sequential(SELayer(channels * n_l0, 16), nn.Conv2d( channels * n_l0, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L2(nn.Module): def __init__(self, channels, n_l1=4, act=nn.ReLU(True)): super(AFB_L2, self).__init__() self.n = n_l1 self.convs_ = nn.ModuleList() for _ in range(n_l1): self.convs_.append(AFB_L1(channels, 3, act)) self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d( channels * n_l1, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L3(nn.Module): def __init__(self, channels, n_l2=4, act=nn.ReLU(True)): super(AFB_L3, self).__init__() self.n = n_l2 self.convs_ = nn.ModuleList() for _ in range(n_l2): self.convs_.append(AFB_L2(channels, 4, act)) self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d( channels * n_l2, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFN(nn.Module): def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act= nn.LeakyReLU(0.2, True)): super(AFN, self).__init__() self.head = conv_(in_c, n_feats) self.n = n_l3 self.AFBs = nn.ModuleList() for i in range(n_l3): self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act)) self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats * n_l3, n_feats, 1, padding=0, stride=1)]) self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats, kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats, out_c)]) def forward(self, x): res = [] x = self.head(x) for i in range(self.n): x = self.AFBs[i](x) res.append(x) res = self.GFF(torch.cat(res, 1)) x = res + x x = self.tail(x) return x if __name__ == '__main__': import numpy as np import torch import torchsummary model = AFN(in_c=3, out_c=3, scale=8, n_feats=128, n_l3=3, act=nn. LeakyReLU(0.2, True)) print(torchsummary.summary(model, (3, 24, 24), device='cpu')) x = np.random.uniform(0, 1, [2, 3, 24, 24]).astype(np.float32) x = torch.tensor(x) with torch.autograd.profiler.profile(use_cuda=True) as prof: y = model(x) print(prof) print(y.shape) <|reserved_special_token_1|> import torch import torch.nn as nn from model.common import UpsampleBlock, conv_, SELayer def wrapper(args): act = None if args.act == 'relu': act = nn.ReLU(True) elif args.act == 'leak_relu': act = nn.LeakyReLU(0.2, True) elif args.act is None: act = None else: raise NotImplementedError return AFN(in_c=args.n_colors, out_c=args.n_colors, scale=args.scale, n_feats=args.n_feats, act=act) class AFB_0(nn.Module): def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)): super(AFB_0, self).__init__() self.op = [] for _ in range(n_blocks): self.op.append(conv_(channels, channels)) self.op.append(act) self.op = nn.Sequential(*self.op) def forward(self, x): x = x + self.op(x) return x class AFB_L1(nn.Module): def __init__(self, channels, n_l0=3, act=nn.ReLU(True)): super(AFB_L1, self).__init__() self.n = n_l0 self.convs_ = nn.ModuleList() for _ in range(n_l0): self.convs_.append(AFB_0(channels, 2, act)) self.LFF = nn.Sequential(SELayer(channels * n_l0, 16), nn.Conv2d( channels * n_l0, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L2(nn.Module): def __init__(self, channels, n_l1=4, act=nn.ReLU(True)): super(AFB_L2, self).__init__() self.n = n_l1 self.convs_ = nn.ModuleList() for _ in range(n_l1): self.convs_.append(AFB_L1(channels, 3, act)) self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d( channels * n_l1, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L3(nn.Module): def __init__(self, channels, n_l2=4, act=nn.ReLU(True)): super(AFB_L3, self).__init__() self.n = n_l2 self.convs_ = nn.ModuleList() for _ in range(n_l2): self.convs_.append(AFB_L2(channels, 4, act)) self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d( channels * n_l2, channels, 1, padding=0, stride=1)) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFN(nn.Module): def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act= nn.LeakyReLU(0.2, True)): super(AFN, self).__init__() self.head = conv_(in_c, n_feats) self.n = n_l3 self.AFBs = nn.ModuleList() for i in range(n_l3): self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act)) self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats * n_l3, n_feats, 1, padding=0, stride=1)]) self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats, kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats, out_c)]) def forward(self, x): res = [] x = self.head(x) for i in range(self.n): x = self.AFBs[i](x) res.append(x) res = self.GFF(torch.cat(res, 1)) x = res + x x = self.tail(x) return x if __name__ == '__main__': import numpy as np import torch import torchsummary model = AFN(in_c=3, out_c=3, scale=8, n_feats=128, n_l3=3, act=nn. LeakyReLU(0.2, True)) print(torchsummary.summary(model, (3, 24, 24), device='cpu')) x = np.random.uniform(0, 1, [2, 3, 24, 24]).astype(np.float32) x = torch.tensor(x) with torch.autograd.profiler.profile(use_cuda=True) as prof: y = model(x) print(prof) print(y.shape) <|reserved_special_token_1|> import torch import torch.nn as nn from model.common import UpsampleBlock, conv_, SELayer def wrapper(args): act = None if args.act == 'relu': act = nn.ReLU(True) elif args.act == 'leak_relu': act = nn.LeakyReLU(0.2, True) elif args.act is None: act = None else: raise NotImplementedError return AFN(in_c=args.n_colors, out_c=args.n_colors, scale=args.scale, n_feats=args.n_feats, act=act) class AFB_0(nn.Module): def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)): super(AFB_0, self).__init__() self.op = [] for _ in range(n_blocks): self.op.append(conv_(channels, channels)) self.op.append(act) self.op = nn.Sequential(*self.op) def forward(self, x): x = x + self.op(x) return x class AFB_L1(nn.Module): def __init__(self, channels, n_l0=3, act=nn.ReLU(True)): super(AFB_L1, self).__init__() self.n = n_l0 self.convs_ = nn.ModuleList() for _ in range(n_l0): self.convs_.append( AFB_0(channels, 2, act) ) self.LFF = nn.Sequential( SELayer(channels * n_l0, 16), nn.Conv2d(channels * n_l0, channels, 1, padding=0, stride=1), ) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L2(nn.Module): def __init__(self, channels, n_l1=4, act=nn.ReLU(True)): super(AFB_L2, self).__init__() self.n = n_l1 self.convs_ = nn.ModuleList() for _ in range(n_l1): self.convs_.append( AFB_L1(channels, 3, act) ) self.LFF = nn.Sequential( SELayer(channels * n_l1, 16), nn.Conv2d(channels * n_l1, channels, 1, padding=0, stride=1), ) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFB_L3(nn.Module): def __init__(self, channels, n_l2=4, act=nn.ReLU(True)): super(AFB_L3, self).__init__() self.n = n_l2 self.convs_ = nn.ModuleList() for _ in range(n_l2): self.convs_.append( AFB_L2(channels, 4, act) ) self.LFF = nn.Sequential( SELayer(channels * n_l2, 16), nn.Conv2d(channels * n_l2, channels, 1, padding=0, stride=1), ) def forward(self, x): res = [] ox = x for i in range(self.n): x = self.convs_[i](x) res.append(x) res = self.LFF(torch.cat(res, 1)) x = res + ox return x class AFN(nn.Module): def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act=nn.LeakyReLU(0.2, True)): super(AFN, self).__init__() self.head = conv_(in_c, n_feats) self.n = n_l3 self.AFBs = nn.ModuleList() for i in range(n_l3): self.AFBs.append( AFB_L3(channels=n_feats, n_l2=4, act=act) ) self.GFF = nn.Sequential(*[ SELayer(n_feats * n_l3), conv_(n_feats * n_l3, n_feats, 1, padding=0, stride=1), ]) self.tail = nn.Sequential(*[ UpsampleBlock(scale, n_feats, kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats, out_c) ]) def forward(self, x): res = [] x = self.head(x) for i in range(self.n): x = self.AFBs[i](x) res.append(x) res = self.GFF(torch.cat(res, 1)) x = res + x x = self.tail(x) return x if __name__ == "__main__": import numpy as np import torch import torchsummary model = AFN(in_c=3, out_c=3, scale=8, n_feats=128, n_l3=3, act=nn.LeakyReLU(0.2, True)) print(torchsummary.summary(model, (3, 24, 24), device='cpu')) x = np.random.uniform(0, 1, [2, 3, 24, 24]).astype(np.float32) x = torch.tensor(x) # loss = nn.L1Loss() # Adam = torch.optim.Adam(model.parameters(), lr=1e-3, betas=(0.99, 0.999)) with torch.autograd.profiler.profile(use_cuda=True) as prof: y = model(x) print(prof) print(y.shape)
flexible
{ "blob_id": "b2c0ef4a0af12b267a54a7ae3fed9edeab2fb879", "index": 6570, "step-1": "<mask token>\n\n\nclass AFB_L1(nn.Module):\n <mask token>\n <mask token>\n\n\nclass AFB_L2(nn.Module):\n\n def __init__(self, channels, n_l1=4, act=nn.ReLU(True)):\n super(AFB_L2, self).__init__()\n self.n = n_l1\n self.convs_ = nn.ModuleList()\n for _ in range(n_l1):\n self.convs_.append(AFB_L1(channels, 3, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d(\n channels * n_l1, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L3(nn.Module):\n\n def __init__(self, channels, n_l2=4, act=nn.ReLU(True)):\n super(AFB_L3, self).__init__()\n self.n = n_l2\n self.convs_ = nn.ModuleList()\n for _ in range(n_l2):\n self.convs_.append(AFB_L2(channels, 4, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d(\n channels * n_l2, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFN(nn.Module):\n\n def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act=\n nn.LeakyReLU(0.2, True)):\n super(AFN, self).__init__()\n self.head = conv_(in_c, n_feats)\n self.n = n_l3\n self.AFBs = nn.ModuleList()\n for i in range(n_l3):\n self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act))\n self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats *\n n_l3, n_feats, 1, padding=0, stride=1)])\n self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats,\n kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats,\n out_c)])\n\n def forward(self, x):\n res = []\n x = self.head(x)\n for i in range(self.n):\n x = self.AFBs[i](x)\n res.append(x)\n res = self.GFF(torch.cat(res, 1))\n x = res + x\n x = self.tail(x)\n return x\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass AFB_0(nn.Module):\n\n def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)):\n super(AFB_0, self).__init__()\n self.op = []\n for _ in range(n_blocks):\n self.op.append(conv_(channels, channels))\n self.op.append(act)\n self.op = nn.Sequential(*self.op)\n <mask token>\n\n\nclass AFB_L1(nn.Module):\n\n def __init__(self, channels, n_l0=3, act=nn.ReLU(True)):\n super(AFB_L1, self).__init__()\n self.n = n_l0\n self.convs_ = nn.ModuleList()\n for _ in range(n_l0):\n self.convs_.append(AFB_0(channels, 2, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l0, 16), nn.Conv2d(\n channels * n_l0, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L2(nn.Module):\n\n def __init__(self, channels, n_l1=4, act=nn.ReLU(True)):\n super(AFB_L2, self).__init__()\n self.n = n_l1\n self.convs_ = nn.ModuleList()\n for _ in range(n_l1):\n self.convs_.append(AFB_L1(channels, 3, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d(\n channels * n_l1, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L3(nn.Module):\n\n def __init__(self, channels, n_l2=4, act=nn.ReLU(True)):\n super(AFB_L3, self).__init__()\n self.n = n_l2\n self.convs_ = nn.ModuleList()\n for _ in range(n_l2):\n self.convs_.append(AFB_L2(channels, 4, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d(\n channels * n_l2, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFN(nn.Module):\n\n def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act=\n nn.LeakyReLU(0.2, True)):\n super(AFN, self).__init__()\n self.head = conv_(in_c, n_feats)\n self.n = n_l3\n self.AFBs = nn.ModuleList()\n for i in range(n_l3):\n self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act))\n self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats *\n n_l3, n_feats, 1, padding=0, stride=1)])\n self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats,\n kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats,\n out_c)])\n\n def forward(self, x):\n res = []\n x = self.head(x)\n for i in range(self.n):\n x = self.AFBs[i](x)\n res.append(x)\n res = self.GFF(torch.cat(res, 1))\n x = res + x\n x = self.tail(x)\n return x\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef wrapper(args):\n act = None\n if args.act == 'relu':\n act = nn.ReLU(True)\n elif args.act == 'leak_relu':\n act = nn.LeakyReLU(0.2, True)\n elif args.act is None:\n act = None\n else:\n raise NotImplementedError\n return AFN(in_c=args.n_colors, out_c=args.n_colors, scale=args.scale,\n n_feats=args.n_feats, act=act)\n\n\nclass AFB_0(nn.Module):\n\n def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)):\n super(AFB_0, self).__init__()\n self.op = []\n for _ in range(n_blocks):\n self.op.append(conv_(channels, channels))\n self.op.append(act)\n self.op = nn.Sequential(*self.op)\n\n def forward(self, x):\n x = x + self.op(x)\n return x\n\n\nclass AFB_L1(nn.Module):\n\n def __init__(self, channels, n_l0=3, act=nn.ReLU(True)):\n super(AFB_L1, self).__init__()\n self.n = n_l0\n self.convs_ = nn.ModuleList()\n for _ in range(n_l0):\n self.convs_.append(AFB_0(channels, 2, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l0, 16), nn.Conv2d(\n channels * n_l0, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L2(nn.Module):\n\n def __init__(self, channels, n_l1=4, act=nn.ReLU(True)):\n super(AFB_L2, self).__init__()\n self.n = n_l1\n self.convs_ = nn.ModuleList()\n for _ in range(n_l1):\n self.convs_.append(AFB_L1(channels, 3, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d(\n channels * n_l1, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L3(nn.Module):\n\n def __init__(self, channels, n_l2=4, act=nn.ReLU(True)):\n super(AFB_L3, self).__init__()\n self.n = n_l2\n self.convs_ = nn.ModuleList()\n for _ in range(n_l2):\n self.convs_.append(AFB_L2(channels, 4, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d(\n channels * n_l2, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFN(nn.Module):\n\n def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act=\n nn.LeakyReLU(0.2, True)):\n super(AFN, self).__init__()\n self.head = conv_(in_c, n_feats)\n self.n = n_l3\n self.AFBs = nn.ModuleList()\n for i in range(n_l3):\n self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act))\n self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats *\n n_l3, n_feats, 1, padding=0, stride=1)])\n self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats,\n kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats,\n out_c)])\n\n def forward(self, x):\n res = []\n x = self.head(x)\n for i in range(self.n):\n x = self.AFBs[i](x)\n res.append(x)\n res = self.GFF(torch.cat(res, 1))\n x = res + x\n x = self.tail(x)\n return x\n\n\nif __name__ == '__main__':\n import numpy as np\n import torch\n import torchsummary\n model = AFN(in_c=3, out_c=3, scale=8, n_feats=128, n_l3=3, act=nn.\n LeakyReLU(0.2, True))\n print(torchsummary.summary(model, (3, 24, 24), device='cpu'))\n x = np.random.uniform(0, 1, [2, 3, 24, 24]).astype(np.float32)\n x = torch.tensor(x)\n with torch.autograd.profiler.profile(use_cuda=True) as prof:\n y = model(x)\n print(prof)\n print(y.shape)\n", "step-4": "import torch\nimport torch.nn as nn\nfrom model.common import UpsampleBlock, conv_, SELayer\n\n\ndef wrapper(args):\n act = None\n if args.act == 'relu':\n act = nn.ReLU(True)\n elif args.act == 'leak_relu':\n act = nn.LeakyReLU(0.2, True)\n elif args.act is None:\n act = None\n else:\n raise NotImplementedError\n return AFN(in_c=args.n_colors, out_c=args.n_colors, scale=args.scale,\n n_feats=args.n_feats, act=act)\n\n\nclass AFB_0(nn.Module):\n\n def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)):\n super(AFB_0, self).__init__()\n self.op = []\n for _ in range(n_blocks):\n self.op.append(conv_(channels, channels))\n self.op.append(act)\n self.op = nn.Sequential(*self.op)\n\n def forward(self, x):\n x = x + self.op(x)\n return x\n\n\nclass AFB_L1(nn.Module):\n\n def __init__(self, channels, n_l0=3, act=nn.ReLU(True)):\n super(AFB_L1, self).__init__()\n self.n = n_l0\n self.convs_ = nn.ModuleList()\n for _ in range(n_l0):\n self.convs_.append(AFB_0(channels, 2, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l0, 16), nn.Conv2d(\n channels * n_l0, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L2(nn.Module):\n\n def __init__(self, channels, n_l1=4, act=nn.ReLU(True)):\n super(AFB_L2, self).__init__()\n self.n = n_l1\n self.convs_ = nn.ModuleList()\n for _ in range(n_l1):\n self.convs_.append(AFB_L1(channels, 3, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l1, 16), nn.Conv2d(\n channels * n_l1, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L3(nn.Module):\n\n def __init__(self, channels, n_l2=4, act=nn.ReLU(True)):\n super(AFB_L3, self).__init__()\n self.n = n_l2\n self.convs_ = nn.ModuleList()\n for _ in range(n_l2):\n self.convs_.append(AFB_L2(channels, 4, act))\n self.LFF = nn.Sequential(SELayer(channels * n_l2, 16), nn.Conv2d(\n channels * n_l2, channels, 1, padding=0, stride=1))\n\n def forward(self, x):\n res = []\n ox = x\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFN(nn.Module):\n\n def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act=\n nn.LeakyReLU(0.2, True)):\n super(AFN, self).__init__()\n self.head = conv_(in_c, n_feats)\n self.n = n_l3\n self.AFBs = nn.ModuleList()\n for i in range(n_l3):\n self.AFBs.append(AFB_L3(channels=n_feats, n_l2=4, act=act))\n self.GFF = nn.Sequential(*[SELayer(n_feats * n_l3), conv_(n_feats *\n n_l3, n_feats, 1, padding=0, stride=1)])\n self.tail = nn.Sequential(*[UpsampleBlock(scale, n_feats,\n kernel_size=3, stride=1, bias=True, act=act), conv_(n_feats,\n out_c)])\n\n def forward(self, x):\n res = []\n x = self.head(x)\n for i in range(self.n):\n x = self.AFBs[i](x)\n res.append(x)\n res = self.GFF(torch.cat(res, 1))\n x = res + x\n x = self.tail(x)\n return x\n\n\nif __name__ == '__main__':\n import numpy as np\n import torch\n import torchsummary\n model = AFN(in_c=3, out_c=3, scale=8, n_feats=128, n_l3=3, act=nn.\n LeakyReLU(0.2, True))\n print(torchsummary.summary(model, (3, 24, 24), device='cpu'))\n x = np.random.uniform(0, 1, [2, 3, 24, 24]).astype(np.float32)\n x = torch.tensor(x)\n with torch.autograd.profiler.profile(use_cuda=True) as prof:\n y = model(x)\n print(prof)\n print(y.shape)\n", "step-5": "import torch\nimport torch.nn as nn\nfrom model.common import UpsampleBlock, conv_, SELayer\n\ndef wrapper(args):\n act = None\n if args.act == 'relu':\n act = nn.ReLU(True)\n elif args.act == 'leak_relu':\n act = nn.LeakyReLU(0.2, True)\n elif args.act is None:\n act = None\n else:\n raise NotImplementedError\n\n return AFN(in_c=args.n_colors, out_c=args.n_colors, scale=args.scale, n_feats=args.n_feats, act=act)\n\nclass AFB_0(nn.Module):\n def __init__(self, channels, n_blocks=2, act=nn.ReLU(True)):\n super(AFB_0, self).__init__()\n self.op = []\n for _ in range(n_blocks):\n self.op.append(conv_(channels, channels))\n self.op.append(act)\n\n self.op = nn.Sequential(*self.op)\n\n def forward(self, x):\n x = x + self.op(x)\n return x\n\n\nclass AFB_L1(nn.Module):\n def __init__(self, channels, n_l0=3, act=nn.ReLU(True)):\n super(AFB_L1, self).__init__()\n\n self.n = n_l0\n self.convs_ = nn.ModuleList()\n for _ in range(n_l0):\n self.convs_.append(\n AFB_0(channels, 2, act)\n )\n\n self.LFF = nn.Sequential(\n SELayer(channels * n_l0, 16),\n nn.Conv2d(channels * n_l0, channels, 1, padding=0, stride=1),\n )\n\n def forward(self, x):\n res = []\n ox = x\n\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L2(nn.Module):\n def __init__(self, channels, n_l1=4, act=nn.ReLU(True)):\n super(AFB_L2, self).__init__()\n\n self.n = n_l1\n self.convs_ = nn.ModuleList()\n for _ in range(n_l1):\n self.convs_.append(\n AFB_L1(channels, 3, act)\n )\n\n self.LFF = nn.Sequential(\n SELayer(channels * n_l1, 16),\n nn.Conv2d(channels * n_l1, channels, 1, padding=0, stride=1),\n )\n\n def forward(self, x):\n res = []\n ox = x\n\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFB_L3(nn.Module):\n def __init__(self, channels, n_l2=4, act=nn.ReLU(True)):\n super(AFB_L3, self).__init__()\n\n self.n = n_l2\n self.convs_ = nn.ModuleList()\n for _ in range(n_l2):\n self.convs_.append(\n AFB_L2(channels, 4, act)\n )\n\n self.LFF = nn.Sequential(\n SELayer(channels * n_l2, 16),\n nn.Conv2d(channels * n_l2, channels, 1, padding=0, stride=1),\n )\n\n def forward(self, x):\n res = []\n ox = x\n\n for i in range(self.n):\n x = self.convs_[i](x)\n res.append(x)\n res = self.LFF(torch.cat(res, 1))\n x = res + ox\n return x\n\n\nclass AFN(nn.Module):\n def __init__(self, in_c=3, out_c=3, scale=4, n_feats=128, n_l3=3, act=nn.LeakyReLU(0.2, True)):\n super(AFN, self).__init__()\n\n self.head = conv_(in_c, n_feats)\n\n self.n = n_l3\n self.AFBs = nn.ModuleList()\n for i in range(n_l3):\n self.AFBs.append(\n AFB_L3(channels=n_feats, n_l2=4, act=act)\n )\n\n self.GFF = nn.Sequential(*[\n SELayer(n_feats * n_l3),\n conv_(n_feats * n_l3, n_feats, 1, padding=0, stride=1),\n ])\n\n self.tail = nn.Sequential(*[\n UpsampleBlock(scale, n_feats, kernel_size=3, stride=1, bias=True, act=act),\n conv_(n_feats, out_c)\n ])\n\n def forward(self, x):\n res = []\n x = self.head(x)\n\n for i in range(self.n):\n x = self.AFBs[i](x)\n res.append(x)\n\n res = self.GFF(torch.cat(res, 1))\n x = res + x\n\n x = self.tail(x)\n return x\n\nif __name__ == \"__main__\":\n import numpy as np\n import torch\n import torchsummary\n\n model = AFN(in_c=3, out_c=3, scale=8, n_feats=128, n_l3=3, act=nn.LeakyReLU(0.2, True))\n print(torchsummary.summary(model, (3, 24, 24), device='cpu'))\n\n x = np.random.uniform(0, 1, [2, 3, 24, 24]).astype(np.float32)\n x = torch.tensor(x)\n\n # loss = nn.L1Loss()\n # Adam = torch.optim.Adam(model.parameters(), lr=1e-3, betas=(0.99, 0.999))\n with torch.autograd.profiler.profile(use_cuda=True) as prof:\n y = model(x)\n print(prof)\n print(y.shape)\n", "step-ids": [ 10, 14, 17, 18, 19 ] }
[ 10, 14, 17, 18, 19 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Order(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Order(models.Model): subscription = models.OneToOneField(Subscription, on_delete=models. CASCADE, related_name='order') order_status = models.CharField(max_length=50, choices=OrderStatus. Choices, default=OrderStatus.IN_PROGRESS) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) email = models.EmailField() price = models.DecimalField(max_digits=10, decimal_places=2) <|reserved_special_token_1|> from django.db import models from orders.constants import OrderStatus from subscriptions.models import Subscription class Order(models.Model): subscription = models.OneToOneField(Subscription, on_delete=models. CASCADE, related_name='order') order_status = models.CharField(max_length=50, choices=OrderStatus. Choices, default=OrderStatus.IN_PROGRESS) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) email = models.EmailField() price = models.DecimalField(max_digits=10, decimal_places=2) <|reserved_special_token_1|> from django.db import models from orders.constants import OrderStatus from subscriptions.models import Subscription class Order(models.Model): subscription = models.OneToOneField( Subscription, on_delete=models.CASCADE, related_name='order', ) order_status = models.CharField( max_length=50, choices=OrderStatus.Choices, default=OrderStatus.IN_PROGRESS, ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) email = models.EmailField() price = models.DecimalField(max_digits=10, decimal_places=2) # def get_email(self): # if self.email is None: # self.email = Subscription.objects.get(client__email=...)
flexible
{ "blob_id": "78ddae64cc576ebaf7f2cfaa4553bddbabe474b7", "index": 6918, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Order(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Order(models.Model):\n subscription = models.OneToOneField(Subscription, on_delete=models.\n CASCADE, related_name='order')\n order_status = models.CharField(max_length=50, choices=OrderStatus.\n Choices, default=OrderStatus.IN_PROGRESS)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n email = models.EmailField()\n price = models.DecimalField(max_digits=10, decimal_places=2)\n", "step-4": "from django.db import models\nfrom orders.constants import OrderStatus\nfrom subscriptions.models import Subscription\n\n\nclass Order(models.Model):\n subscription = models.OneToOneField(Subscription, on_delete=models.\n CASCADE, related_name='order')\n order_status = models.CharField(max_length=50, choices=OrderStatus.\n Choices, default=OrderStatus.IN_PROGRESS)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n email = models.EmailField()\n price = models.DecimalField(max_digits=10, decimal_places=2)\n", "step-5": "from django.db import models\n\nfrom orders.constants import OrderStatus\nfrom subscriptions.models import Subscription\n\n\nclass Order(models.Model):\n subscription = models.OneToOneField(\n Subscription,\n on_delete=models.CASCADE,\n related_name='order',\n )\n order_status = models.CharField(\n max_length=50,\n choices=OrderStatus.Choices,\n default=OrderStatus.IN_PROGRESS,\n )\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n email = models.EmailField()\n price = models.DecimalField(max_digits=10, decimal_places=2)\n\n # def get_email(self):\n # if self.email is None:\n # self.email = Subscription.objects.get(client__email=...)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
'''Given a range of 2 numbers (i.e) L and R count the number of prime numbers in the range (inclusive of L and R ). Input Size : L <= R <= 100000(complexity O(n) read about Sieve of Eratosthenes) Sample Testcase : INPUT 2 5 OUTPUT 3''' x,y=map(int,input().split()) count=0 for i in range(x,y+1): if i>1: for j in range(2,i): if(i%j==0): break else: count+=1 print(count)
normal
{ "blob_id": "06848ec0e327fed1da00446cec6392c6f42130af", "index": 2158, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(x, y + 1):\n if i > 1:\n for j in range(2, i):\n if i % j == 0:\n break\n else:\n count += 1\nprint(count)\n", "step-3": "<mask token>\nx, y = map(int, input().split())\ncount = 0\nfor i in range(x, y + 1):\n if i > 1:\n for j in range(2, i):\n if i % j == 0:\n break\n else:\n count += 1\nprint(count)\n", "step-4": "'''Given a range of 2 numbers (i.e) L and R count the number of prime numbers in the range (inclusive of L and R ).\nInput Size : L <= R <= 100000(complexity O(n) read about Sieve of Eratosthenes)\nSample Testcase :\nINPUT\n2 5\nOUTPUT\n3'''\n\nx,y=map(int,input().split())\ncount=0\nfor i in range(x,y+1):\n if i>1:\n for j in range(2,i):\n if(i%j==0):\n break\n else:\n count+=1\nprint(count)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(word[0]) <|reserved_special_token_0|> print('こんにちわ、私の名前は {} です。'.format(name)) <|reserved_special_token_0|> print('{}/{}/{}'.format(year, month, day)) for i in range(0, 5): print('kamyu'[i]) print('aldous Huxley was born in 1894'.capitalize()) print('when? what? who?'.split()) <|reserved_special_token_0|> print(word) print('A screeming comes across the sky.'.replace('s', '$')) print('Hemingway'.index('m')) print('ケンシロウは言った"お前はもう死んでいる"とな') print('アタタタ,' * 10 + 'オワッター!') print('4月の晴れた寒い日で、時計がどれも十三時を打っていた。'.split('、')[0]) <|reserved_special_token_1|> <|reserved_special_token_0|> word = "what's up" print(word[0]) name = 'lady gaga' print('こんにちわ、私の名前は {} です。'.format(name)) <|reserved_special_token_0|> year = 1990 month = 7 day = 11 print('{}/{}/{}'.format(year, month, day)) for i in range(0, 5): print('kamyu'[i]) print('aldous Huxley was born in 1894'.capitalize()) print('when? what? who?'.split()) <|reserved_special_token_0|> word = ['the', 'fox', 'jumped', 'over', 'the', 'fence', '.'] word = ' '.join(word) word = word[0:-2] + '.' print(word) print('A screeming comes across the sky.'.replace('s', '$')) print('Hemingway'.index('m')) print('ケンシロウは言った"お前はもう死んでいる"とな') print('アタタタ,' * 10 + 'オワッター!') print('4月の晴れた寒い日で、時計がどれも十三時を打っていた。'.split('、')[0]) <|reserved_special_token_1|> # python /Users/lawrie_6strings/be_professional_pythonist/control_string.py # -*- coding: utf-8 -*- # 文字列を3行で書いてみたい場合 """ どないやねん。 最近の若いもんは、 ようやるやんけ。 """ # 文字列の特定の文字を取得したい場合は,インデックスを指定してあげることでなんとかする。 word = "what's up" print(word[0]) # 書式化 name = "lady gaga" print("こんにちわ、私の名前は {} です。".format(name)) "複数の文字列を挿入することもできる。" year = 1990 month = 7 day = 11 print("{}/{}/{}".format(year, month, day)) # チャレンジ ## 1 for i in range(0, 5): print("kamyu"[i]) ## 2 # what = input("what:") # who = input("who:") # print("I write {},I send it to {}".format(what, who)) ## 3 print("aldous Huxley was born in 1894".capitalize()) ## 4 print("when? what? who?".split()) ## 5 "最後のピリオドを再利用しようとしすぎて、詰まってしまった。" word = ["the", "fox", "jumped", "over", "the", "fence", "."] word = " ".join(word) word = word[0:-2] + "." print(word) ## 6 print("A screeming comes across the sky.".replace("s", "$")) ## 7 print("Hemingway".index("m")) ## 8 文字列の中にさらに文字列を入れたい時。 print("ケンシロウは言った\"お前はもう死んでいる\"とな") ## 9 print("アタタタ,"*10 + "オワッター!") ## 10 print("4月の晴れた寒い日で、時計がどれも十三時を打っていた。".split("、")[0])
flexible
{ "blob_id": "0e05eed2d6bc723fd8379e436621a6eba4aa5ab2", "index": 1929, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(word[0])\n<mask token>\nprint('こんにちわ、私の名前は {} です。'.format(name))\n<mask token>\nprint('{}/{}/{}'.format(year, month, day))\nfor i in range(0, 5):\n print('kamyu'[i])\nprint('aldous Huxley was born in 1894'.capitalize())\nprint('when? what? who?'.split())\n<mask token>\nprint(word)\nprint('A screeming comes across the sky.'.replace('s', '$'))\nprint('Hemingway'.index('m'))\nprint('ケンシロウは言った\"お前はもう死んでいる\"とな')\nprint('アタタタ,' * 10 + 'オワッター!')\nprint('4月の晴れた寒い日で、時計がどれも十三時を打っていた。'.split('、')[0])\n", "step-3": "<mask token>\nword = \"what's up\"\nprint(word[0])\nname = 'lady gaga'\nprint('こんにちわ、私の名前は {} です。'.format(name))\n<mask token>\nyear = 1990\nmonth = 7\nday = 11\nprint('{}/{}/{}'.format(year, month, day))\nfor i in range(0, 5):\n print('kamyu'[i])\nprint('aldous Huxley was born in 1894'.capitalize())\nprint('when? what? who?'.split())\n<mask token>\nword = ['the', 'fox', 'jumped', 'over', 'the', 'fence', '.']\nword = ' '.join(word)\nword = word[0:-2] + '.'\nprint(word)\nprint('A screeming comes across the sky.'.replace('s', '$'))\nprint('Hemingway'.index('m'))\nprint('ケンシロウは言った\"お前はもう死んでいる\"とな')\nprint('アタタタ,' * 10 + 'オワッター!')\nprint('4月の晴れた寒い日で、時計がどれも十三時を打っていた。'.split('、')[0])\n", "step-4": "# python /Users/lawrie_6strings/be_professional_pythonist/control_string.py\n# -*- coding: utf-8 -*-\n# 文字列を3行で書いてみたい場合\n\"\"\"\nどないやねん。\n最近の若いもんは、\nようやるやんけ。\n\"\"\"\n\n# 文字列の特定の文字を取得したい場合は,インデックスを指定してあげることでなんとかする。\nword = \"what's up\"\nprint(word[0])\n\n# 書式化\nname = \"lady gaga\"\nprint(\"こんにちわ、私の名前は {} です。\".format(name))\n\n\"複数の文字列を挿入することもできる。\"\nyear = 1990\nmonth = 7\nday = 11\nprint(\"{}/{}/{}\".format(year, month, day))\n\n# チャレンジ\n## 1\nfor i in range(0, 5):\n print(\"kamyu\"[i])\n\n## 2\n# what = input(\"what:\")\n# who = input(\"who:\")\n# print(\"I write {},I send it to {}\".format(what, who))\n\n## 3\nprint(\"aldous Huxley was born in 1894\".capitalize())\n\n## 4\nprint(\"when? what? who?\".split())\n\n## 5\n\"最後のピリオドを再利用しようとしすぎて、詰まってしまった。\"\nword = [\"the\", \"fox\", \"jumped\", \"over\", \"the\", \"fence\", \".\"]\nword = \" \".join(word)\nword = word[0:-2] + \".\"\nprint(word)\n\n## 6\nprint(\"A screeming comes across the sky.\".replace(\"s\", \"$\"))\n\n## 7\nprint(\"Hemingway\".index(\"m\"))\n\n## 8 文字列の中にさらに文字列を入れたい時。\nprint(\"ケンシロウは言った\\\"お前はもう死んでいる\\\"とな\")\n\n\n## 9\nprint(\"アタタタ,\"*10 + \"オワッター!\")\n\n## 10\nprint(\"4月の晴れた寒い日で、時計がどれも十三時を打っていた。\".split(\"、\")[0])", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
a= input("Enter number") a= a.split() b=[] for x in a: b.append(int(x)) print(b) l=len(b) c=0 s=0 for i in range(l): s=len(b[:i]) for j in range(s): if b[s]<b[j]: c=b[s] b.pop(s) b.insert(b.index(b[j]),c) print(b,b[:i],b[s])
normal
{ "blob_id": "24de4f486d4e976850e94a003f8d9cbe3e518402", "index": 33, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor x in a:\n b.append(int(x))\nprint(b)\n<mask token>\nfor i in range(l):\n s = len(b[:i])\n for j in range(s):\n if b[s] < b[j]:\n c = b[s]\n b.pop(s)\n b.insert(b.index(b[j]), c)\n print(b, b[:i], b[s])\n", "step-3": "a = input('Enter number')\na = a.split()\nb = []\nfor x in a:\n b.append(int(x))\nprint(b)\nl = len(b)\nc = 0\ns = 0\nfor i in range(l):\n s = len(b[:i])\n for j in range(s):\n if b[s] < b[j]:\n c = b[s]\n b.pop(s)\n b.insert(b.index(b[j]), c)\n print(b, b[:i], b[s])\n", "step-4": "a= input(\"Enter number\")\r\na= a.split()\r\nb=[]\r\nfor x in a:\r\n b.append(int(x)) \r\n\r\nprint(b)\r\nl=len(b)\r\nc=0\r\ns=0\r\nfor i in range(l):\r\n s=len(b[:i])\r\n for j in range(s):\r\n \r\n if b[s]<b[j]:\r\n c=b[s]\r\n b.pop(s)\r\n b.insert(b.index(b[j]),c)\r\n print(b,b[:i],b[s])\r\n\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import matplotlib.pyplot as plt class Scatter: def __init__(self, values, ylabel, title): self.values = values self.range = list(range(len(values))) self.ylabel = ylabel self.title = title def plot(self): fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) ax.scatter(self.range, self.values, color='r', s=1) ax.set_xlabel('Days') ax.set_ylabel(self.ylabel) ax.set_title(self.title) plt.ylim(0, self.values[-1]) plt.show() class Pie: def __init__(self, values, labels, title): self.style = "fivethirtyeight" self.values = values self.labels = labels self.explode = [0 for i in range(len(values))] self.title = title def plot(self): plt.style.use(self.style) plt.pie(self.values, labels=self.labels, explode=self.explode, shadow=True, startangle=90, autopct='%1.1f%%', wedgeprops={'edgecolor': 'black'}) plt.title(self.title) plt.tight_layout() plt.show() class Column: pass
normal
{ "blob_id": "58385a7713a8f88925ced714d25f1522bc7e39d8", "index": 1181, "step-1": "<mask token>\n\n\nclass Scatter:\n <mask token>\n <mask token>\n\n\nclass Pie:\n\n def __init__(self, values, labels, title):\n self.style = 'fivethirtyeight'\n self.values = values\n self.labels = labels\n self.explode = [(0) for i in range(len(values))]\n self.title = title\n\n def plot(self):\n plt.style.use(self.style)\n plt.pie(self.values, labels=self.labels, explode=self.explode,\n shadow=True, startangle=90, autopct='%1.1f%%', wedgeprops={\n 'edgecolor': 'black'})\n plt.title(self.title)\n plt.tight_layout()\n plt.show()\n\n\nclass Column:\n pass\n", "step-2": "<mask token>\n\n\nclass Scatter:\n\n def __init__(self, values, ylabel, title):\n self.values = values\n self.range = list(range(len(values)))\n self.ylabel = ylabel\n self.title = title\n <mask token>\n\n\nclass Pie:\n\n def __init__(self, values, labels, title):\n self.style = 'fivethirtyeight'\n self.values = values\n self.labels = labels\n self.explode = [(0) for i in range(len(values))]\n self.title = title\n\n def plot(self):\n plt.style.use(self.style)\n plt.pie(self.values, labels=self.labels, explode=self.explode,\n shadow=True, startangle=90, autopct='%1.1f%%', wedgeprops={\n 'edgecolor': 'black'})\n plt.title(self.title)\n plt.tight_layout()\n plt.show()\n\n\nclass Column:\n pass\n", "step-3": "<mask token>\n\n\nclass Scatter:\n\n def __init__(self, values, ylabel, title):\n self.values = values\n self.range = list(range(len(values)))\n self.ylabel = ylabel\n self.title = title\n\n def plot(self):\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1])\n ax.scatter(self.range, self.values, color='r', s=1)\n ax.set_xlabel('Days')\n ax.set_ylabel(self.ylabel)\n ax.set_title(self.title)\n plt.ylim(0, self.values[-1])\n plt.show()\n\n\nclass Pie:\n\n def __init__(self, values, labels, title):\n self.style = 'fivethirtyeight'\n self.values = values\n self.labels = labels\n self.explode = [(0) for i in range(len(values))]\n self.title = title\n\n def plot(self):\n plt.style.use(self.style)\n plt.pie(self.values, labels=self.labels, explode=self.explode,\n shadow=True, startangle=90, autopct='%1.1f%%', wedgeprops={\n 'edgecolor': 'black'})\n plt.title(self.title)\n plt.tight_layout()\n plt.show()\n\n\nclass Column:\n pass\n", "step-4": "import matplotlib.pyplot as plt\n\n\nclass Scatter:\n\n def __init__(self, values, ylabel, title):\n self.values = values\n self.range = list(range(len(values)))\n self.ylabel = ylabel\n self.title = title\n\n def plot(self):\n fig = plt.figure()\n ax = fig.add_axes([0, 0, 1, 1])\n ax.scatter(self.range, self.values, color='r', s=1)\n ax.set_xlabel('Days')\n ax.set_ylabel(self.ylabel)\n ax.set_title(self.title)\n plt.ylim(0, self.values[-1])\n plt.show()\n\n\nclass Pie:\n\n def __init__(self, values, labels, title):\n self.style = 'fivethirtyeight'\n self.values = values\n self.labels = labels\n self.explode = [(0) for i in range(len(values))]\n self.title = title\n\n def plot(self):\n plt.style.use(self.style)\n plt.pie(self.values, labels=self.labels, explode=self.explode,\n shadow=True, startangle=90, autopct='%1.1f%%', wedgeprops={\n 'edgecolor': 'black'})\n plt.title(self.title)\n plt.tight_layout()\n plt.show()\n\n\nclass Column:\n pass\n", "step-5": "import matplotlib.pyplot as plt\r\n\r\n\r\nclass Scatter:\r\n def __init__(self, values, ylabel, title):\r\n self.values = values\r\n self.range = list(range(len(values)))\r\n self.ylabel = ylabel\r\n self.title = title\r\n\r\n def plot(self):\r\n fig = plt.figure()\r\n ax = fig.add_axes([0, 0, 1, 1])\r\n ax.scatter(self.range, self.values, color='r', s=1)\r\n ax.set_xlabel('Days')\r\n ax.set_ylabel(self.ylabel)\r\n ax.set_title(self.title)\r\n plt.ylim(0, self.values[-1])\r\n plt.show()\r\n\r\n\r\nclass Pie:\r\n def __init__(self, values, labels, title):\r\n self.style = \"fivethirtyeight\"\r\n self.values = values\r\n self.labels = labels\r\n self.explode = [0 for i in range(len(values))]\r\n self.title = title\r\n\r\n def plot(self):\r\n plt.style.use(self.style)\r\n\r\n plt.pie(self.values, labels=self.labels, explode=self.explode, shadow=True,\r\n startangle=90, autopct='%1.1f%%',\r\n wedgeprops={'edgecolor': 'black'})\r\n\r\n plt.title(self.title)\r\n plt.tight_layout()\r\n\r\n plt.show()\r\n\r\n\r\nclass Column:\r\n pass", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> class Getter(object): <|reserved_special_token_0|> def __call__(self, url, **kwargs): try: return self._inner_call(url, **kwargs) except (Timeout, ConnectionError, RequestException) as ex: message = ex.response.reason if getattr(ex, 'response', None ) is not None else type(ex).__name__ raise GetterError(message, ex, not isinstance(ex, RequestException) ) def _inner_call(self, url, **kwargs): if 'timeout' not in kwargs: kwargs['timeout'] = 20 result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 401: if self.login(): result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 404: return result.raise_for_status() return result class GetterError(Exception): def __init__(self, message, cause, connection_error): super(GetterError, self).__init__() self.message = message self.cause = cause self.connection_error = connection_error self.request = getattr(cause, 'request', None) self.response = getattr(cause, 'response', None) <|reserved_special_token_1|> <|reserved_special_token_0|> class Getter(object): def __init__(self, contenttype=None, login=lambda : False, session=None): self.session = session or retryable_session() self.login = login if contenttype: self.session.headers['Accept'] = contenttype def __call__(self, url, **kwargs): try: return self._inner_call(url, **kwargs) except (Timeout, ConnectionError, RequestException) as ex: message = ex.response.reason if getattr(ex, 'response', None ) is not None else type(ex).__name__ raise GetterError(message, ex, not isinstance(ex, RequestException) ) def _inner_call(self, url, **kwargs): if 'timeout' not in kwargs: kwargs['timeout'] = 20 result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 401: if self.login(): result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 404: return result.raise_for_status() return result class GetterError(Exception): def __init__(self, message, cause, connection_error): super(GetterError, self).__init__() self.message = message self.cause = cause self.connection_error = connection_error self.request = getattr(cause, 'request', None) self.response = getattr(cause, 'response', None) <|reserved_special_token_1|> <|reserved_special_token_0|> def retryable_session(retries=3, backoff_factor=0.5, status_forcelist=(500, 502, 504, 520), session=None): session = session or requests.Session() retry = Retry(total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) return session class Getter(object): def __init__(self, contenttype=None, login=lambda : False, session=None): self.session = session or retryable_session() self.login = login if contenttype: self.session.headers['Accept'] = contenttype def __call__(self, url, **kwargs): try: return self._inner_call(url, **kwargs) except (Timeout, ConnectionError, RequestException) as ex: message = ex.response.reason if getattr(ex, 'response', None ) is not None else type(ex).__name__ raise GetterError(message, ex, not isinstance(ex, RequestException) ) def _inner_call(self, url, **kwargs): if 'timeout' not in kwargs: kwargs['timeout'] = 20 result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 401: if self.login(): result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 404: return result.raise_for_status() return result class GetterError(Exception): def __init__(self, message, cause, connection_error): super(GetterError, self).__init__() self.message = message self.cause = cause self.connection_error = connection_error self.request = getattr(cause, 'request', None) self.response = getattr(cause, 'response', None) <|reserved_special_token_1|> import requests from requests.adapters import HTTPAdapter from requests.exceptions import ConnectionError, Timeout, RequestException from requests.packages.urllib3.util.retry import Retry def retryable_session(retries=3, backoff_factor=0.5, status_forcelist=(500, 502, 504, 520), session=None): session = session or requests.Session() retry = Retry(total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) return session class Getter(object): def __init__(self, contenttype=None, login=lambda : False, session=None): self.session = session or retryable_session() self.login = login if contenttype: self.session.headers['Accept'] = contenttype def __call__(self, url, **kwargs): try: return self._inner_call(url, **kwargs) except (Timeout, ConnectionError, RequestException) as ex: message = ex.response.reason if getattr(ex, 'response', None ) is not None else type(ex).__name__ raise GetterError(message, ex, not isinstance(ex, RequestException) ) def _inner_call(self, url, **kwargs): if 'timeout' not in kwargs: kwargs['timeout'] = 20 result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 401: if self.login(): result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 404: return result.raise_for_status() return result class GetterError(Exception): def __init__(self, message, cause, connection_error): super(GetterError, self).__init__() self.message = message self.cause = cause self.connection_error = connection_error self.request = getattr(cause, 'request', None) self.response = getattr(cause, 'response', None) <|reserved_special_token_1|> import requests from requests.adapters import HTTPAdapter from requests.exceptions import ConnectionError, Timeout, RequestException # import from `requests` because Jarvis / some platforms still have old urllib3 from requests.packages.urllib3.util.retry import Retry def retryable_session(retries=3, backoff_factor=0.5, status_forcelist=(500, 502, 504, 520), session=None): # from https://www.peterbe.com/plog/best-practice-with-retries-with-requests session = session or requests.Session() # 'Retry-After' 413/503/529 headers are respected by default retry = Retry(total=retries, read=retries, connect=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) return session class Getter(object): def __init__(self, contenttype=None, login=lambda: False, session=None): self.session = session or retryable_session() self.login = login if contenttype: self.session.headers['Accept'] = contenttype def __call__(self, url, **kwargs): try: return self._inner_call(url, **kwargs) except (Timeout, ConnectionError, RequestException) as ex: message = ex.response.reason if getattr(ex, 'response', None) is not None else type(ex).__name__ raise GetterError(message, ex, not isinstance(ex, RequestException)) def _inner_call(self, url, **kwargs): if 'timeout' not in kwargs: kwargs['timeout'] = 20 result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 401: if self.login(): result = self.session.get(url, **kwargs) if result is None: return if result.status_code == 404: return result.raise_for_status() return result class GetterError(Exception): def __init__(self, message, cause, connection_error): super(GetterError, self).__init__() self.message = message self.cause = cause self.connection_error = connection_error self.request = getattr(cause, 'request', None) self.response = getattr(cause, 'response', None)
flexible
{ "blob_id": "603708c830dadb6f1a3e5de00536d558f448b5fb", "index": 1352, "step-1": "<mask token>\n\n\nclass Getter(object):\n <mask token>\n\n def __call__(self, url, **kwargs):\n try:\n return self._inner_call(url, **kwargs)\n except (Timeout, ConnectionError, RequestException) as ex:\n message = ex.response.reason if getattr(ex, 'response', None\n ) is not None else type(ex).__name__\n raise GetterError(message, ex, not isinstance(ex, RequestException)\n )\n\n def _inner_call(self, url, **kwargs):\n if 'timeout' not in kwargs:\n kwargs['timeout'] = 20\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 401:\n if self.login():\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 404:\n return\n result.raise_for_status()\n return result\n\n\nclass GetterError(Exception):\n\n def __init__(self, message, cause, connection_error):\n super(GetterError, self).__init__()\n self.message = message\n self.cause = cause\n self.connection_error = connection_error\n self.request = getattr(cause, 'request', None)\n self.response = getattr(cause, 'response', None)\n", "step-2": "<mask token>\n\n\nclass Getter(object):\n\n def __init__(self, contenttype=None, login=lambda : False, session=None):\n self.session = session or retryable_session()\n self.login = login\n if contenttype:\n self.session.headers['Accept'] = contenttype\n\n def __call__(self, url, **kwargs):\n try:\n return self._inner_call(url, **kwargs)\n except (Timeout, ConnectionError, RequestException) as ex:\n message = ex.response.reason if getattr(ex, 'response', None\n ) is not None else type(ex).__name__\n raise GetterError(message, ex, not isinstance(ex, RequestException)\n )\n\n def _inner_call(self, url, **kwargs):\n if 'timeout' not in kwargs:\n kwargs['timeout'] = 20\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 401:\n if self.login():\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 404:\n return\n result.raise_for_status()\n return result\n\n\nclass GetterError(Exception):\n\n def __init__(self, message, cause, connection_error):\n super(GetterError, self).__init__()\n self.message = message\n self.cause = cause\n self.connection_error = connection_error\n self.request = getattr(cause, 'request', None)\n self.response = getattr(cause, 'response', None)\n", "step-3": "<mask token>\n\n\ndef retryable_session(retries=3, backoff_factor=0.5, status_forcelist=(500,\n 502, 504, 520), session=None):\n session = session or requests.Session()\n retry = Retry(total=retries, read=retries, connect=retries,\n backoff_factor=backoff_factor, status_forcelist=status_forcelist)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n\nclass Getter(object):\n\n def __init__(self, contenttype=None, login=lambda : False, session=None):\n self.session = session or retryable_session()\n self.login = login\n if contenttype:\n self.session.headers['Accept'] = contenttype\n\n def __call__(self, url, **kwargs):\n try:\n return self._inner_call(url, **kwargs)\n except (Timeout, ConnectionError, RequestException) as ex:\n message = ex.response.reason if getattr(ex, 'response', None\n ) is not None else type(ex).__name__\n raise GetterError(message, ex, not isinstance(ex, RequestException)\n )\n\n def _inner_call(self, url, **kwargs):\n if 'timeout' not in kwargs:\n kwargs['timeout'] = 20\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 401:\n if self.login():\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 404:\n return\n result.raise_for_status()\n return result\n\n\nclass GetterError(Exception):\n\n def __init__(self, message, cause, connection_error):\n super(GetterError, self).__init__()\n self.message = message\n self.cause = cause\n self.connection_error = connection_error\n self.request = getattr(cause, 'request', None)\n self.response = getattr(cause, 'response', None)\n", "step-4": "import requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.exceptions import ConnectionError, Timeout, RequestException\nfrom requests.packages.urllib3.util.retry import Retry\n\n\ndef retryable_session(retries=3, backoff_factor=0.5, status_forcelist=(500,\n 502, 504, 520), session=None):\n session = session or requests.Session()\n retry = Retry(total=retries, read=retries, connect=retries,\n backoff_factor=backoff_factor, status_forcelist=status_forcelist)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n\nclass Getter(object):\n\n def __init__(self, contenttype=None, login=lambda : False, session=None):\n self.session = session or retryable_session()\n self.login = login\n if contenttype:\n self.session.headers['Accept'] = contenttype\n\n def __call__(self, url, **kwargs):\n try:\n return self._inner_call(url, **kwargs)\n except (Timeout, ConnectionError, RequestException) as ex:\n message = ex.response.reason if getattr(ex, 'response', None\n ) is not None else type(ex).__name__\n raise GetterError(message, ex, not isinstance(ex, RequestException)\n )\n\n def _inner_call(self, url, **kwargs):\n if 'timeout' not in kwargs:\n kwargs['timeout'] = 20\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 401:\n if self.login():\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 404:\n return\n result.raise_for_status()\n return result\n\n\nclass GetterError(Exception):\n\n def __init__(self, message, cause, connection_error):\n super(GetterError, self).__init__()\n self.message = message\n self.cause = cause\n self.connection_error = connection_error\n self.request = getattr(cause, 'request', None)\n self.response = getattr(cause, 'response', None)\n", "step-5": "import requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.exceptions import ConnectionError, Timeout, RequestException\n# import from `requests` because Jarvis / some platforms still have old urllib3\nfrom requests.packages.urllib3.util.retry import Retry\n\ndef retryable_session(retries=3, backoff_factor=0.5, status_forcelist=(500, 502, 504, 520), session=None):\n # from https://www.peterbe.com/plog/best-practice-with-retries-with-requests\n session = session or requests.Session()\n # 'Retry-After' 413/503/529 headers are respected by default\n retry = Retry(total=retries, read=retries, connect=retries,\n backoff_factor=backoff_factor, status_forcelist=status_forcelist)\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\nclass Getter(object):\n def __init__(self, contenttype=None, login=lambda: False, session=None):\n self.session = session or retryable_session()\n self.login = login\n if contenttype:\n self.session.headers['Accept'] = contenttype\n\n def __call__(self, url, **kwargs):\n try:\n return self._inner_call(url, **kwargs)\n except (Timeout, ConnectionError, RequestException) as ex:\n message = ex.response.reason if getattr(ex, 'response', None) is not None else type(ex).__name__\n raise GetterError(message, ex, not isinstance(ex, RequestException))\n\n def _inner_call(self, url, **kwargs):\n if 'timeout' not in kwargs:\n kwargs['timeout'] = 20\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n if result.status_code == 401:\n if self.login():\n result = self.session.get(url, **kwargs)\n if result is None:\n return\n\n if result.status_code == 404:\n return\n result.raise_for_status()\n return result\n\nclass GetterError(Exception):\n def __init__(self, message, cause, connection_error):\n super(GetterError, self).__init__()\n self.message = message\n self.cause = cause\n self.connection_error = connection_error\n self.request = getattr(cause, 'request', None)\n self.response = getattr(cause, 'response', None)\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> __author__ = 'simsun'
flexible
{ "blob_id": "2b746d89d34435eb5f3a5b04da61c5cc88178852", "index": 8784, "step-1": "<mask token>\n", "step-2": "__author__ = 'simsun'\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
class UrlPath: @staticmethod def combine(*args): result = '' for path in args: result += path if path.endswith('/') else '{}/'.format(path) #result = result[:-1] return result
normal
{ "blob_id": "aa579025cacd11486a101b2dc51b5ba4997bf84a", "index": 95, "step-1": "<mask token>\n", "step-2": "class UrlPath:\n <mask token>\n", "step-3": "class UrlPath:\n\n @staticmethod\n def combine(*args):\n result = ''\n for path in args:\n result += path if path.endswith('/') else '{}/'.format(path)\n return result\n", "step-4": "class UrlPath:\n @staticmethod\n def combine(*args):\n result = ''\n for path in args:\n result += path if path.endswith('/') else '{}/'.format(path)\n #result = result[:-1]\n return result", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> urllib3.disable_warnings() <|reserved_special_token_0|> print(key.decode('ascii')) <|reserved_special_token_1|> <|reserved_special_token_0|> urllib3.disable_warnings() response = requests.get('https://freeaeskey.xyz', verify=False) data = response.text.encode('utf-8') key = data[data.index(b'<b>') + 3:data.index(b'</b>')] print(key.decode('ascii')) <|reserved_special_token_1|> import requests import urllib3 urllib3.disable_warnings() response = requests.get('https://freeaeskey.xyz', verify=False) data = response.text.encode('utf-8') key = data[data.index(b'<b>') + 3:data.index(b'</b>')] print(key.decode('ascii')) <|reserved_special_token_1|> #!/usr/bin/python3 import requests import urllib3 urllib3.disable_warnings() response = requests.get('https://freeaeskey.xyz', verify=False) data = response.text.encode('utf-8') key = data[data.index(b'<b>')+3:data.index(b'</b>')] print(key.decode('ascii'))
flexible
{ "blob_id": "368e209f83cc0cade81791c8357e01e7e3f940c8", "index": 97, "step-1": "<mask token>\n", "step-2": "<mask token>\nurllib3.disable_warnings()\n<mask token>\nprint(key.decode('ascii'))\n", "step-3": "<mask token>\nurllib3.disable_warnings()\nresponse = requests.get('https://freeaeskey.xyz', verify=False)\ndata = response.text.encode('utf-8')\nkey = data[data.index(b'<b>') + 3:data.index(b'</b>')]\nprint(key.decode('ascii'))\n", "step-4": "import requests\nimport urllib3\nurllib3.disable_warnings()\nresponse = requests.get('https://freeaeskey.xyz', verify=False)\ndata = response.text.encode('utf-8')\nkey = data[data.index(b'<b>') + 3:data.index(b'</b>')]\nprint(key.decode('ascii'))\n", "step-5": "#!/usr/bin/python3\n\nimport requests\nimport urllib3\nurllib3.disable_warnings()\nresponse = requests.get('https://freeaeskey.xyz', verify=False)\ndata = response.text.encode('utf-8')\nkey = data[data.index(b'<b>')+3:data.index(b'</b>')]\nprint(key.decode('ascii'))\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
from django.shortcuts import render from django.shortcuts import redirect from block.models import Block from .models import Article from .forms import ArticleForm from django.core.paginator import Paginator from django.contrib.auth.decorators import login_required def article_list(request, block_id): block_id = int(block_id) block = Block.objects.get(id=block_id) all_articles = Article.objects.filter(block=block, article_status=0).order_by("-id") ARTICLE_CNT_1PAGE = 2 p = Paginator(all_articles, ARTICLE_CNT_1PAGE) page_no = int(request.GET.get("page_no", "1")) page = p.page(page_no) articles_objs = page.object_list page_links = [i for i in range(page_no - 2, page_no + 3) if i > 0 and i <= p.num_pages] return render(request, "article_list.html", {"articles": articles_objs, "b": block, "page_no": page_no, "page": page, "page_links": page_links, "p": p}) @login_required def article_create(request, block_id): block_id = int(block_id) block = Block.objects.get(id=block_id) if request.method == "GET": return render(request, "article_create.html", {"b": block}) else: form = ArticleForm(request.POST) if form.is_valid(): article = form.save(commit=False) article.owner = request.user article.block = block article.article_status = 0 article.save() return redirect("/article/list/%s" % block_id) else: return render(request, "article_create.html", {"b": block, "form": form}) def article_detail(request, article_id): article = Article.objects.get(id=article_id) return render(request, "article_detail.html", {"article": article})
normal
{ "blob_id": "0f94537fa64066bb29c5e9e97836b0a8ac01ac19", "index": 9844, "step-1": "<mask token>\n\n\n@login_required\ndef article_create(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n if request.method == 'GET':\n return render(request, 'article_create.html', {'b': block})\n else:\n form = ArticleForm(request.POST)\n if form.is_valid():\n article = form.save(commit=False)\n article.owner = request.user\n article.block = block\n article.article_status = 0\n article.save()\n return redirect('/article/list/%s' % block_id)\n else:\n return render(request, 'article_create.html', {'b': block,\n 'form': form})\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@login_required\ndef article_create(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n if request.method == 'GET':\n return render(request, 'article_create.html', {'b': block})\n else:\n form = ArticleForm(request.POST)\n if form.is_valid():\n article = form.save(commit=False)\n article.owner = request.user\n article.block = block\n article.article_status = 0\n article.save()\n return redirect('/article/list/%s' % block_id)\n else:\n return render(request, 'article_create.html', {'b': block,\n 'form': form})\n\n\ndef article_detail(request, article_id):\n article = Article.objects.get(id=article_id)\n return render(request, 'article_detail.html', {'article': article})\n", "step-3": "<mask token>\n\n\ndef article_list(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n all_articles = Article.objects.filter(block=block, article_status=0\n ).order_by('-id')\n ARTICLE_CNT_1PAGE = 2\n p = Paginator(all_articles, ARTICLE_CNT_1PAGE)\n page_no = int(request.GET.get('page_no', '1'))\n page = p.page(page_no)\n articles_objs = page.object_list\n page_links = [i for i in range(page_no - 2, page_no + 3) if i > 0 and i <=\n p.num_pages]\n return render(request, 'article_list.html', {'articles': articles_objs,\n 'b': block, 'page_no': page_no, 'page': page, 'page_links':\n page_links, 'p': p})\n\n\n@login_required\ndef article_create(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n if request.method == 'GET':\n return render(request, 'article_create.html', {'b': block})\n else:\n form = ArticleForm(request.POST)\n if form.is_valid():\n article = form.save(commit=False)\n article.owner = request.user\n article.block = block\n article.article_status = 0\n article.save()\n return redirect('/article/list/%s' % block_id)\n else:\n return render(request, 'article_create.html', {'b': block,\n 'form': form})\n\n\ndef article_detail(request, article_id):\n article = Article.objects.get(id=article_id)\n return render(request, 'article_detail.html', {'article': article})\n", "step-4": "from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom block.models import Block\nfrom .models import Article\nfrom .forms import ArticleForm\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.decorators import login_required\n\n\ndef article_list(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n all_articles = Article.objects.filter(block=block, article_status=0\n ).order_by('-id')\n ARTICLE_CNT_1PAGE = 2\n p = Paginator(all_articles, ARTICLE_CNT_1PAGE)\n page_no = int(request.GET.get('page_no', '1'))\n page = p.page(page_no)\n articles_objs = page.object_list\n page_links = [i for i in range(page_no - 2, page_no + 3) if i > 0 and i <=\n p.num_pages]\n return render(request, 'article_list.html', {'articles': articles_objs,\n 'b': block, 'page_no': page_no, 'page': page, 'page_links':\n page_links, 'p': p})\n\n\n@login_required\ndef article_create(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n if request.method == 'GET':\n return render(request, 'article_create.html', {'b': block})\n else:\n form = ArticleForm(request.POST)\n if form.is_valid():\n article = form.save(commit=False)\n article.owner = request.user\n article.block = block\n article.article_status = 0\n article.save()\n return redirect('/article/list/%s' % block_id)\n else:\n return render(request, 'article_create.html', {'b': block,\n 'form': form})\n\n\ndef article_detail(request, article_id):\n article = Article.objects.get(id=article_id)\n return render(request, 'article_detail.html', {'article': article})\n", "step-5": "from django.shortcuts import render\nfrom django.shortcuts import redirect\nfrom block.models import Block\nfrom .models import Article\nfrom .forms import ArticleForm\nfrom django.core.paginator import Paginator\nfrom django.contrib.auth.decorators import login_required\n\n\ndef article_list(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n\n all_articles = Article.objects.filter(block=block, article_status=0).order_by(\"-id\")\n ARTICLE_CNT_1PAGE = 2\n p = Paginator(all_articles, ARTICLE_CNT_1PAGE)\n page_no = int(request.GET.get(\"page_no\", \"1\"))\n page = p.page(page_no)\n articles_objs = page.object_list\n\n page_links = [i\n for i in range(page_no - 2, page_no + 3) if i > 0 and i <= p.num_pages]\n\n return render(request, \"article_list.html\",\n {\"articles\": articles_objs, \"b\": block, \"page_no\": page_no, \"page\": page,\n \"page_links\": page_links, \"p\": p})\n\n@login_required\ndef article_create(request, block_id):\n block_id = int(block_id)\n block = Block.objects.get(id=block_id)\n if request.method == \"GET\":\n return render(request, \"article_create.html\", {\"b\": block})\n else:\n form = ArticleForm(request.POST)\n if form.is_valid():\n article = form.save(commit=False)\n article.owner = request.user\n article.block = block\n article.article_status = 0\n article.save()\n return redirect(\"/article/list/%s\" % block_id)\n else:\n return render(request, \"article_create.html\", {\"b\": block, \"form\": form})\n\n\ndef article_detail(request, article_id):\n article = Article.objects.get(id=article_id)\n return render(request, \"article_detail.html\", {\"article\": article})\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Song(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __unicode__(self): return self.name <|reserved_special_token_1|> <|reserved_special_token_0|> class Song(models.Model): name = models.CharField(max_length=255) filename = models.FileField(upload_to='canciones/') album = models.ForeignKey(Albums) def __unicode__(self): return self.name <|reserved_special_token_1|> from django.db import models from albums.models import Albums class Song(models.Model): name = models.CharField(max_length=255) filename = models.FileField(upload_to='canciones/') album = models.ForeignKey(Albums) def __unicode__(self): return self.name <|reserved_special_token_1|> from django.db import models from albums.models import Albums class Song(models.Model): name = models.CharField(max_length=255) filename = models.FileField(upload_to='canciones/') album = models.ForeignKey(Albums) def __unicode__(self,): return self.name
flexible
{ "blob_id": "8ec18e259af1123fad7563aee3a363e095e30e8e", "index": 1064, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Song(models.Model):\n <mask token>\n <mask token>\n <mask token>\n\n def __unicode__(self):\n return self.name\n", "step-3": "<mask token>\n\n\nclass Song(models.Model):\n name = models.CharField(max_length=255)\n filename = models.FileField(upload_to='canciones/')\n album = models.ForeignKey(Albums)\n\n def __unicode__(self):\n return self.name\n", "step-4": "from django.db import models\nfrom albums.models import Albums\n\n\nclass Song(models.Model):\n name = models.CharField(max_length=255)\n filename = models.FileField(upload_to='canciones/')\n album = models.ForeignKey(Albums)\n\n def __unicode__(self):\n return self.name\n", "step-5": "from django.db import models\n\nfrom albums.models import Albums\n\nclass Song(models.Model):\n name = models.CharField(max_length=255)\n filename = models.FileField(upload_to='canciones/')\n album = models.ForeignKey(Albums)\n\n def __unicode__(self,):\n return self.name\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
#!/usr/bin/python import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) ledPin = 4 pinOn = False GPIO.setup(ledPin, GPIO.OUT) GPIO.output(ledPin, GPIO.LOW) def print_pin_status(pin_number): GPIO.setup(pin_number, GPIO.IN) value = GPIO.input(pin_number) print(f'Current Value of {pin_number} is {value}') GPIO.setup(pin_number, GPIO.OUT) while True: print_pin_status(ledPin) key = input("Action, press q to quit: ") print(key) if key == ' ': print("space pushed") if key == '1': if pinOn: print("turning led off") GPIO.output(ledPin, GPIO.LOW) pinOn = False else: print("turning led on") GPIO.output(ledPin, GPIO.HIGH) pinOn = True if key == 'q': print("Quiting. . .") break
normal
{ "blob_id": "492c416becc44deaafef519eae8c9a82ac00cc0e", "index": 8632, "step-1": "<mask token>\n\n\ndef print_pin_status(pin_number):\n GPIO.setup(pin_number, GPIO.IN)\n value = GPIO.input(pin_number)\n print(f'Current Value of {pin_number} is {value}')\n GPIO.setup(pin_number, GPIO.OUT)\n\n\n<mask token>\n", "step-2": "<mask token>\nGPIO.setmode(GPIO.BCM)\n<mask token>\nGPIO.setup(ledPin, GPIO.OUT)\nGPIO.output(ledPin, GPIO.LOW)\n\n\ndef print_pin_status(pin_number):\n GPIO.setup(pin_number, GPIO.IN)\n value = GPIO.input(pin_number)\n print(f'Current Value of {pin_number} is {value}')\n GPIO.setup(pin_number, GPIO.OUT)\n\n\nwhile True:\n print_pin_status(ledPin)\n key = input('Action, press q to quit: ')\n print(key)\n if key == ' ':\n print('space pushed')\n if key == '1':\n if pinOn:\n print('turning led off')\n GPIO.output(ledPin, GPIO.LOW)\n pinOn = False\n else:\n print('turning led on')\n GPIO.output(ledPin, GPIO.HIGH)\n pinOn = True\n if key == 'q':\n print('Quiting. . .')\n break\n", "step-3": "<mask token>\nGPIO.setmode(GPIO.BCM)\nledPin = 4\npinOn = False\nGPIO.setup(ledPin, GPIO.OUT)\nGPIO.output(ledPin, GPIO.LOW)\n\n\ndef print_pin_status(pin_number):\n GPIO.setup(pin_number, GPIO.IN)\n value = GPIO.input(pin_number)\n print(f'Current Value of {pin_number} is {value}')\n GPIO.setup(pin_number, GPIO.OUT)\n\n\nwhile True:\n print_pin_status(ledPin)\n key = input('Action, press q to quit: ')\n print(key)\n if key == ' ':\n print('space pushed')\n if key == '1':\n if pinOn:\n print('turning led off')\n GPIO.output(ledPin, GPIO.LOW)\n pinOn = False\n else:\n print('turning led on')\n GPIO.output(ledPin, GPIO.HIGH)\n pinOn = True\n if key == 'q':\n print('Quiting. . .')\n break\n", "step-4": "import RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\nledPin = 4\npinOn = False\nGPIO.setup(ledPin, GPIO.OUT)\nGPIO.output(ledPin, GPIO.LOW)\n\n\ndef print_pin_status(pin_number):\n GPIO.setup(pin_number, GPIO.IN)\n value = GPIO.input(pin_number)\n print(f'Current Value of {pin_number} is {value}')\n GPIO.setup(pin_number, GPIO.OUT)\n\n\nwhile True:\n print_pin_status(ledPin)\n key = input('Action, press q to quit: ')\n print(key)\n if key == ' ':\n print('space pushed')\n if key == '1':\n if pinOn:\n print('turning led off')\n GPIO.output(ledPin, GPIO.LOW)\n pinOn = False\n else:\n print('turning led on')\n GPIO.output(ledPin, GPIO.HIGH)\n pinOn = True\n if key == 'q':\n print('Quiting. . .')\n break\n", "step-5": "#!/usr/bin/python\n\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BCM)\n\nledPin = 4\npinOn = False\n\nGPIO.setup(ledPin, GPIO.OUT)\nGPIO.output(ledPin, GPIO.LOW)\n\n\ndef print_pin_status(pin_number):\n GPIO.setup(pin_number, GPIO.IN)\n value = GPIO.input(pin_number)\n print(f'Current Value of {pin_number} is {value}')\n GPIO.setup(pin_number, GPIO.OUT)\n\n\nwhile True:\n print_pin_status(ledPin)\n\n key = input(\"Action, press q to quit: \")\n\n print(key)\n\n if key == ' ':\n print(\"space pushed\")\n\n if key == '1':\n\n if pinOn:\n print(\"turning led off\")\n GPIO.output(ledPin, GPIO.LOW)\n pinOn = False\n else:\n print(\"turning led on\")\n GPIO.output(ledPin, GPIO.HIGH)\n pinOn = True\n\n if key == 'q':\n print(\"Quiting. . .\")\n break\n\n\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
from pyathena import connect from Config import config2 from Config import merchants def get_mapped_sku(sku): try: cursor = connect(aws_access_key_id=config2["aws_access_key_id"], aws_secret_access_key=config2["aws_secret_access_key"], s3_staging_dir=config2["s3_staging_dir"], region_name=config2["region_name"]).cursor() cursor.execute("SELECT seller_sku, seller FROM optivations.master_product_list where sc_sku = %(sku)s ", {"sku": str(sku)}) # print(cursor.description) result = cursor.fetchall() for row in result: return {'Cross-Reference No': row[0], 'brand': row[1]} except Exception as e: print(e) return {} return {} def get_sku(seller_sku, sc_sku, seller): try: cursor = connect(aws_access_key_id=config2["aws_access_key_id"], aws_secret_access_key=config2["aws_secret_access_key"], s3_staging_dir=config2["s3_staging_dir"], region_name=config2["region_name"]).cursor() cursor.execute("SELECT seller_sku FROM optivations.master_product_list where sc_sku = %(sku)s ", {"sku": str(sku)}) # print(cursor.description) # print(cursor.fetchall()) for row in cursor: return (row[0]) except Exception as e: print(e) return False return True def add_sku(sc_sku, seller_sku, seller): try: cursor = connect(aws_access_key_id=config2["aws_access_key_id"], aws_secret_access_key=config2["aws_secret_access_key"], s3_staging_dir=config2["s3_staging_dir"], region_name=config2["region_name"]).cursor() cursor.execute("INSERT INTO optivations.master_product_list VALUES ( %(scsku)s, %(sellersku)s, %(seller)s )", {"scsku": str(sc_sku), "sellersku": str(seller_sku), "seller": str(seller)}) return (cursor.description) # print(cursor.fetchall()) # for row in cursor: # return (row[0]) except Exception as e: print(e) return False return True # print(add_sku('test', 'test', 'Adean')) # result = (get_mapped_sku('HDS-3571')) # print(result['Cross-Reference No'])
normal
{ "blob_id": "6add599035573842475c7f9155c5dbbea6c96a8a", "index": 3618, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_mapped_sku(sku):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'SELECT seller_sku, seller FROM optivations.master_product_list where sc_sku = %(sku)s '\n , {'sku': str(sku)})\n result = cursor.fetchall()\n for row in result:\n return {'Cross-Reference No': row[0], 'brand': row[1]}\n except Exception as e:\n print(e)\n return {}\n return {}\n\n\ndef get_sku(seller_sku, sc_sku, seller):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'SELECT seller_sku FROM optivations.master_product_list where sc_sku = %(sku)s '\n , {'sku': str(sku)})\n for row in cursor:\n return row[0]\n except Exception as e:\n print(e)\n return False\n return True\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_mapped_sku(sku):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'SELECT seller_sku, seller FROM optivations.master_product_list where sc_sku = %(sku)s '\n , {'sku': str(sku)})\n result = cursor.fetchall()\n for row in result:\n return {'Cross-Reference No': row[0], 'brand': row[1]}\n except Exception as e:\n print(e)\n return {}\n return {}\n\n\ndef get_sku(seller_sku, sc_sku, seller):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'SELECT seller_sku FROM optivations.master_product_list where sc_sku = %(sku)s '\n , {'sku': str(sku)})\n for row in cursor:\n return row[0]\n except Exception as e:\n print(e)\n return False\n return True\n\n\ndef add_sku(sc_sku, seller_sku, seller):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'INSERT INTO optivations.master_product_list VALUES ( %(scsku)s, %(sellersku)s, %(seller)s )'\n , {'scsku': str(sc_sku), 'sellersku': str(seller_sku), 'seller':\n str(seller)})\n return cursor.description\n except Exception as e:\n print(e)\n return False\n return True\n", "step-4": "from pyathena import connect\nfrom Config import config2\nfrom Config import merchants\n\n\ndef get_mapped_sku(sku):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'SELECT seller_sku, seller FROM optivations.master_product_list where sc_sku = %(sku)s '\n , {'sku': str(sku)})\n result = cursor.fetchall()\n for row in result:\n return {'Cross-Reference No': row[0], 'brand': row[1]}\n except Exception as e:\n print(e)\n return {}\n return {}\n\n\ndef get_sku(seller_sku, sc_sku, seller):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'SELECT seller_sku FROM optivations.master_product_list where sc_sku = %(sku)s '\n , {'sku': str(sku)})\n for row in cursor:\n return row[0]\n except Exception as e:\n print(e)\n return False\n return True\n\n\ndef add_sku(sc_sku, seller_sku, seller):\n try:\n cursor = connect(aws_access_key_id=config2['aws_access_key_id'],\n aws_secret_access_key=config2['aws_secret_access_key'],\n s3_staging_dir=config2['s3_staging_dir'], region_name=config2[\n 'region_name']).cursor()\n cursor.execute(\n 'INSERT INTO optivations.master_product_list VALUES ( %(scsku)s, %(sellersku)s, %(seller)s )'\n , {'scsku': str(sc_sku), 'sellersku': str(seller_sku), 'seller':\n str(seller)})\n return cursor.description\n except Exception as e:\n print(e)\n return False\n return True\n", "step-5": "from pyathena import connect\nfrom Config import config2\nfrom Config import merchants\n\n\ndef get_mapped_sku(sku):\n try:\n cursor = connect(aws_access_key_id=config2[\"aws_access_key_id\"],\n aws_secret_access_key=config2[\"aws_secret_access_key\"],\n s3_staging_dir=config2[\"s3_staging_dir\"],\n region_name=config2[\"region_name\"]).cursor()\n cursor.execute(\"SELECT seller_sku, seller FROM optivations.master_product_list where sc_sku = %(sku)s \",\n {\"sku\": str(sku)})\n\n # print(cursor.description)\n result = cursor.fetchall()\n for row in result:\n return {'Cross-Reference No': row[0], 'brand': row[1]}\n\n except Exception as e:\n print(e)\n return {}\n return {}\n\n\ndef get_sku(seller_sku, sc_sku, seller):\n try:\n cursor = connect(aws_access_key_id=config2[\"aws_access_key_id\"],\n aws_secret_access_key=config2[\"aws_secret_access_key\"],\n s3_staging_dir=config2[\"s3_staging_dir\"],\n region_name=config2[\"region_name\"]).cursor()\n cursor.execute(\"SELECT seller_sku FROM optivations.master_product_list where sc_sku = %(sku)s \",\n {\"sku\": str(sku)})\n\n # print(cursor.description)\n # print(cursor.fetchall())\n for row in cursor:\n return (row[0])\n except Exception as e:\n print(e)\n return False\n return True\n\n\ndef add_sku(sc_sku, seller_sku, seller):\n try:\n cursor = connect(aws_access_key_id=config2[\"aws_access_key_id\"],\n aws_secret_access_key=config2[\"aws_secret_access_key\"],\n s3_staging_dir=config2[\"s3_staging_dir\"],\n region_name=config2[\"region_name\"]).cursor()\n cursor.execute(\"INSERT INTO optivations.master_product_list VALUES ( %(scsku)s, %(sellersku)s, %(seller)s )\",\n {\"scsku\": str(sc_sku), \"sellersku\": str(seller_sku), \"seller\": str(seller)})\n\n return (cursor.description)\n # print(cursor.fetchall())\n # for row in cursor:\n # return (row[0])\n except Exception as e:\n print(e)\n return False\n return True\n# print(add_sku('test', 'test', 'Adean'))\n# result = (get_mapped_sku('HDS-3571'))\n# print(result['Cross-Reference No'])\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class View(Renderable, ABC): <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class View(Renderable, ABC): @abstractmethod def content_size(self, container_size: Size) ->Size: pass <|reserved_special_token_1|> from abc import ABC, abstractmethod from raspberry_home.view.geometry import * from raspberry_home.view.renderable import Renderable class View(Renderable, ABC): @abstractmethod def content_size(self, container_size: Size) ->Size: pass
flexible
{ "blob_id": "913ff9b811d3abbe43bda0554e40a6a2c87053be", "index": 4449, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass View(Renderable, ABC):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass View(Renderable, ABC):\n\n @abstractmethod\n def content_size(self, container_size: Size) ->Size:\n pass\n", "step-4": "from abc import ABC, abstractmethod\nfrom raspberry_home.view.geometry import *\nfrom raspberry_home.view.renderable import Renderable\n\n\nclass View(Renderable, ABC):\n\n @abstractmethod\n def content_size(self, container_size: Size) ->Size:\n pass\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from django import forms from django.contrib.auth.models import User from .models import TblPublish , TblSnippetTopics, TblSnippetData, TblLearnTopics, TblLearnData, TblBlog, TblBlogComments,TblLearnDataComments, TblBlogGvp, TblLearnDataGvp,TblSnippetDataGvp, TblHome, TblAbout, TblQueries from django.contrib.auth.forms import UserCreationForm class UsersigninForm(forms.Form): username = forms.CharField(required = True, label = 'Username', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(required = True, label = 'Password', max_length = 32, widget = forms.PasswordInput(attrs={'placeholder': 'Password'})) class SignupForm(UserCreationForm): email = forms.EmailField(max_length=200, help_text='Required') class Meta: model = User fields = ('username', 'email', 'password1', 'password2') def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['placeholder'] = "Username" self.fields['email'].widget.attrs['placeholder'] = "email" self.fields['password1'].widget.attrs['placeholder'] ="password" self.fields['password2'].widget.attrs['placeholder'] = "password Again" class UserRegistrationForm(forms.Form): username = forms.CharField(required = True, min_length=6,label = 'Username', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'Username'}) ) email = forms.EmailField(required = True, label = 'Email', max_length = 100, widget=forms.EmailInput(attrs={'placeholder': 'e.g. : email@gmail.com'})) firstname = forms.CharField(required = True, label = 'First Name', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'First Name'})) lastname = forms.CharField(required = True, label = 'Last Name', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'Last Name'})) password = forms.CharField(required = True, label = 'Password', max_length = 100, widget = forms.PasswordInput(attrs={'placeholder': 'Password'})) passwordagain = forms.CharField(required = True, label = 'Password (Again)', max_length = 100, widget = forms.PasswordInput(attrs={'placeholder': 'Password (Again)'})) class TblPublishForm(forms.ModelForm): class Meta(): model = TblPublish fields = '__all__' class TblSnippetDataForm(forms.ModelForm): class Meta(): model = TblSnippetData fields = ['snippet_topics','snippet_data_subject','snippet_data_description','snippet_data_keyword','snippet_data_code','snippet_data_datetime','snippet_data_added_by','snippet_topics','snippet_data_publish'] def clean_snippet_topics_added_by(self): if not self.cleaned_data['snippet_topics_added_by']: return User() return self.cleaned_data['snippet_topics_added_by'] def __init__(self, *args, **kwargs): super(TblSnippetDataForm, self).__init__(*args, **kwargs) self.fields['snippet_data_datetime'].widget = forms.HiddenInput() self.fields['snippet_data_added_by'].widget = forms.HiddenInput() self.fields['snippet_topics'].widget = forms.HiddenInput() self.fields['snippet_data_subject'].widget.attrs['placeholder'] = "Title/Topics" self.fields['snippet_data_description'].widget.attrs['placeholder'] = "Brief Description" self.fields['snippet_data_keyword'].widget.attrs['placeholder'] ="Keyword For Search" self.fields['snippet_data_code'].widget.attrs['placeholder'] = "Snippet (Code)" self.fields['snippet_data_publish'].widget.attrs['placeholder'] = "Ready-To-Publish" self.fields['snippet_data_publish'].label = "Publish" class TblBlogForm(forms.ModelForm): class Meta(): model = TblBlog fields = ['blog_title','blog_description','blog_keyword','blog_content','blog_pics','blog_publish','blog_datetime','blog_summary','blog_like','blog_added_by'] def __init__(self, *args, **kwargs): super(TblBlogForm, self).__init__(*args, **kwargs) self.fields['blog_datetime'].widget = forms.HiddenInput() self.fields['blog_summary'].widget = forms.HiddenInput() self.fields['blog_like'].widget = forms.HiddenInput() self.fields['blog_added_by'].widget = forms.HiddenInput() self.fields['blog_title'].widget.attrs['placeholder'] = "Title/Topics" self.fields['blog_description'].widget.attrs['placeholder'] = "Brief Description" self.fields['blog_content'].widget.attrs['placeholder'] = "Blog Content" self.fields['blog_keyword'].widget.attrs['placeholder'] = "Keyword For Search" self.fields['blog_pics'].widget.attrs['placeholder'] = "Upload Pics" self.fields['blog_publish'].label = "Publish" class TblBlogCommentsForm(forms.ModelForm): class Meta(): model = TblBlogComments fields = '__all__' class TblLearnDataForm(forms.ModelForm): class Meta(): model = TblLearnData fields = ['learn_data','learn_data_keyword','learn_data_description','learn_data_publish','learn_data_datetime','learn_data_added_by','learn_topics','learn_data_like','learn_data_icon'] def __init__(self, *args, **kwargs): super(TblLearnDataForm, self).__init__(*args, **kwargs) self.fields['learn_data_datetime'].widget = forms.HiddenInput() self.fields['learn_data_added_by'].widget = forms.HiddenInput() self.fields['learn_topics'].widget = forms.HiddenInput() self.fields['learn_data_like'].widget = forms.HiddenInput() self.fields['learn_data_icon'].widget = forms.HiddenInput() self.fields['learn_data'].widget.attrs['placeholder'] = "Title/Topics" self.fields['learn_data_description'].widget.attrs['placeholder'] = "Brief Description" self.fields['learn_data_keyword'].widget.attrs['placeholder'] = "Keyword For Search" self.fields['learn_data_publish'].label = "Publish" class TblLearnDataCommentsForm(forms.ModelForm): class Meta(): model = TblLearnDataComments fields = '__all__' class TblBlogGvpForm(forms.ModelForm): class Meta(): model = TblBlogGvp fields = '__all__' class TblLearnDataGvpForm(forms.ModelForm): class Meta(): model = TblLearnDataGvp fields = '__all__' class TblHomeForm(forms.ModelForm): class Meta(): model = TblHome fields = '__all__' def __init__(self, *args, **kwargs): super(TblHomeForm, self).__init__(*args, **kwargs) self.fields['home_datetime'].widget = forms.HiddenInput() self.fields['home_added_by'].widget = forms.HiddenInput() self.fields['home_pics'].widget.attrs['placeholder'] = "Upload Image" self.fields['home_content'].widget.attrs['placeholder'] = "Content" self.fields['home_content_description'].widget.attrs['placeholder'] = "Description" self.fields['home_publish'].label = "Publish" class TblAboutForm(forms.ModelForm): class Meta(): model = TblAbout fields = '__all__' def __init__(self, *args, **kwargs): super(TblAboutForm, self).__init__(*args, **kwargs) self.fields['about_datetime'].widget = forms.HiddenInput() self.fields['about_added_by'].widget = forms.HiddenInput() self.fields['about_pics'].widget.attrs['placeholder'] = "Upload Image" self.fields['about_content'].widget.attrs['placeholder'] = "Content" self.fields['about_content_description'].widget.attrs['placeholder'] = "Description" self.fields['about_publish'].label = "Publish" class TblLearnTopicsForm(forms.ModelForm): class Meta(): model = TblLearnTopics fields = '__all__' def __init__(self, *args, **kwargs): super(TblLearnTopicsForm, self).__init__(*args, **kwargs) self.fields['learn_topics_datetime'].widget = forms.HiddenInput() # self.fields['learn_topics_added_by'].widget = forms.HiddenInput() self.fields['learn_topics_icon'].widget.attrs['placeholder'] = 'Icon' self.fields['learn_topics_coverpage_img'].widget = forms.HiddenInput() self.fields['learn_topics'].widget.attrs['placeholder'] = "Topics" self.fields['learn_topics_description'].widget.attrs['placeholder'] = "Description" self.fields['learn_topics_publish'].label = "Publish" def clean_learn_topics_added_by(self): if not self.cleaned_data['learn_topics_added_by']: return User() return self.cleaned_data['learn_topics_added_by'] class TblSnippetTopicsForm(forms.ModelForm): class Meta(): model = TblSnippetTopics fields = '__all__' def __init__(self, *args, **kwargs): super(TblSnippetTopicsForm, self).__init__(*args, **kwargs) self.fields['snippet_topics_datetime'].widget = forms.HiddenInput() self.fields['snippet_topics_added_by'].widget = forms.HiddenInput() self.fields['snippet_topics_icon'].widget = forms.HiddenInput() self.fields['snippet_topics_coverpage_img'].widget = forms.HiddenInput() self.fields['snippet_topics_expire'].widget = forms.HiddenInput() self.fields['snippet_topics'].widget.attrs['placeholder'] = "Topics" self.fields['snippet_topics_description'].widget.attrs['placeholder'] = "Description" self.fields['snippet_topics_publish'].label = "Publish" def clean_snippet_topics_added_by(self): if not self.cleaned_data['snippet_topics_added_by']: return User() return self.cleaned_data['snippet_topics_added_by'] class TblQueriesForm(forms.ModelForm): class Meta(): model = TblQueries fields = '__all__' def __init__(self, *args, **kwargs): super(TblQueriesForm, self).__init__(*args, **kwargs) self.fields['datetime'].widget = forms.HiddenInput() self.fields['name'].widget.attrs['placeholder'] = "Name" self.fields['email'].widget.attrs['placeholder'] = "Email" self.fields['subject'].widget.attrs['placeholder'] = "Subject" self.fields['message'].widget.attrs['placeholder'] = "Message"
normal
{ "blob_id": "9e02b1a90d61de6d794dd350b50417a2f7260df6", "index": 5947, "step-1": "<mask token>\n\n\nclass TblBlogForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlog\n fields = ['blog_title', 'blog_description', 'blog_keyword',\n 'blog_content', 'blog_pics', 'blog_publish', 'blog_datetime',\n 'blog_summary', 'blog_like', 'blog_added_by']\n <mask token>\n\n\nclass TblBlogCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogComments\n fields = '__all__'\n\n\nclass TblLearnDataForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnData\n fields = ['learn_data', 'learn_data_keyword',\n 'learn_data_description', 'learn_data_publish',\n 'learn_data_datetime', 'learn_data_added_by', 'learn_topics',\n 'learn_data_like', 'learn_data_icon']\n\n def __init__(self, *args, **kwargs):\n super(TblLearnDataForm, self).__init__(*args, **kwargs)\n self.fields['learn_data_datetime'].widget = forms.HiddenInput()\n self.fields['learn_data_added_by'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget = forms.HiddenInput()\n self.fields['learn_data_like'].widget = forms.HiddenInput()\n self.fields['learn_data_icon'].widget = forms.HiddenInput()\n self.fields['learn_data'].widget.attrs['placeholder'] = 'Title/Topics'\n self.fields['learn_data_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['learn_data_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['learn_data_publish'].label = 'Publish'\n\n\nclass TblLearnDataCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataComments\n fields = '__all__'\n\n\nclass TblBlogGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogGvp\n fields = '__all__'\n\n\nclass TblLearnDataGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataGvp\n fields = '__all__'\n\n\nclass TblHomeForm(forms.ModelForm):\n\n\n class Meta:\n model = TblHome\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblHomeForm, self).__init__(*args, **kwargs)\n self.fields['home_datetime'].widget = forms.HiddenInput()\n self.fields['home_added_by'].widget = forms.HiddenInput()\n self.fields['home_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['home_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['home_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['home_publish'].label = 'Publish'\n\n\nclass TblAboutForm(forms.ModelForm):\n\n\n class Meta:\n model = TblAbout\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblAboutForm, self).__init__(*args, **kwargs)\n self.fields['about_datetime'].widget = forms.HiddenInput()\n self.fields['about_added_by'].widget = forms.HiddenInput()\n self.fields['about_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['about_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['about_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['about_publish'].label = 'Publish'\n\n\nclass TblLearnTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblLearnTopicsForm, self).__init__(*args, **kwargs)\n self.fields['learn_topics_datetime'].widget = forms.HiddenInput()\n self.fields['learn_topics_icon'].widget.attrs['placeholder'] = 'Icon'\n self.fields['learn_topics_coverpage_img'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['learn_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['learn_topics_publish'].label = 'Publish'\n\n def clean_learn_topics_added_by(self):\n if not self.cleaned_data['learn_topics_added_by']:\n return User()\n return self.cleaned_data['learn_topics_added_by']\n\n\nclass TblSnippetTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblSnippetTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblSnippetTopicsForm, self).__init__(*args, **kwargs)\n self.fields['snippet_topics_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_topics_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics_icon'].widget = forms.HiddenInput()\n self.fields['snippet_topics_coverpage_img'].widget = forms.HiddenInput(\n )\n self.fields['snippet_topics_expire'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['snippet_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['snippet_topics_publish'].label = 'Publish'\n\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\n\nclass TblQueriesForm(forms.ModelForm):\n\n\n class Meta:\n model = TblQueries\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblQueriesForm, self).__init__(*args, **kwargs)\n self.fields['datetime'].widget = forms.HiddenInput()\n self.fields['name'].widget.attrs['placeholder'] = 'Name'\n self.fields['email'].widget.attrs['placeholder'] = 'Email'\n self.fields['subject'].widget.attrs['placeholder'] = 'Subject'\n self.fields['message'].widget.attrs['placeholder'] = 'Message'\n", "step-2": "<mask token>\n\n\nclass TblBlogForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlog\n fields = ['blog_title', 'blog_description', 'blog_keyword',\n 'blog_content', 'blog_pics', 'blog_publish', 'blog_datetime',\n 'blog_summary', 'blog_like', 'blog_added_by']\n\n def __init__(self, *args, **kwargs):\n super(TblBlogForm, self).__init__(*args, **kwargs)\n self.fields['blog_datetime'].widget = forms.HiddenInput()\n self.fields['blog_summary'].widget = forms.HiddenInput()\n self.fields['blog_like'].widget = forms.HiddenInput()\n self.fields['blog_added_by'].widget = forms.HiddenInput()\n self.fields['blog_title'].widget.attrs['placeholder'] = 'Title/Topics'\n self.fields['blog_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['blog_content'].widget.attrs['placeholder'\n ] = 'Blog Content'\n self.fields['blog_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['blog_pics'].widget.attrs['placeholder'] = 'Upload Pics'\n self.fields['blog_publish'].label = 'Publish'\n\n\nclass TblBlogCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogComments\n fields = '__all__'\n\n\nclass TblLearnDataForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnData\n fields = ['learn_data', 'learn_data_keyword',\n 'learn_data_description', 'learn_data_publish',\n 'learn_data_datetime', 'learn_data_added_by', 'learn_topics',\n 'learn_data_like', 'learn_data_icon']\n\n def __init__(self, *args, **kwargs):\n super(TblLearnDataForm, self).__init__(*args, **kwargs)\n self.fields['learn_data_datetime'].widget = forms.HiddenInput()\n self.fields['learn_data_added_by'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget = forms.HiddenInput()\n self.fields['learn_data_like'].widget = forms.HiddenInput()\n self.fields['learn_data_icon'].widget = forms.HiddenInput()\n self.fields['learn_data'].widget.attrs['placeholder'] = 'Title/Topics'\n self.fields['learn_data_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['learn_data_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['learn_data_publish'].label = 'Publish'\n\n\nclass TblLearnDataCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataComments\n fields = '__all__'\n\n\nclass TblBlogGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogGvp\n fields = '__all__'\n\n\nclass TblLearnDataGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataGvp\n fields = '__all__'\n\n\nclass TblHomeForm(forms.ModelForm):\n\n\n class Meta:\n model = TblHome\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblHomeForm, self).__init__(*args, **kwargs)\n self.fields['home_datetime'].widget = forms.HiddenInput()\n self.fields['home_added_by'].widget = forms.HiddenInput()\n self.fields['home_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['home_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['home_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['home_publish'].label = 'Publish'\n\n\nclass TblAboutForm(forms.ModelForm):\n\n\n class Meta:\n model = TblAbout\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblAboutForm, self).__init__(*args, **kwargs)\n self.fields['about_datetime'].widget = forms.HiddenInput()\n self.fields['about_added_by'].widget = forms.HiddenInput()\n self.fields['about_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['about_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['about_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['about_publish'].label = 'Publish'\n\n\nclass TblLearnTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblLearnTopicsForm, self).__init__(*args, **kwargs)\n self.fields['learn_topics_datetime'].widget = forms.HiddenInput()\n self.fields['learn_topics_icon'].widget.attrs['placeholder'] = 'Icon'\n self.fields['learn_topics_coverpage_img'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['learn_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['learn_topics_publish'].label = 'Publish'\n\n def clean_learn_topics_added_by(self):\n if not self.cleaned_data['learn_topics_added_by']:\n return User()\n return self.cleaned_data['learn_topics_added_by']\n\n\nclass TblSnippetTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblSnippetTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblSnippetTopicsForm, self).__init__(*args, **kwargs)\n self.fields['snippet_topics_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_topics_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics_icon'].widget = forms.HiddenInput()\n self.fields['snippet_topics_coverpage_img'].widget = forms.HiddenInput(\n )\n self.fields['snippet_topics_expire'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['snippet_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['snippet_topics_publish'].label = 'Publish'\n\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\n\nclass TblQueriesForm(forms.ModelForm):\n\n\n class Meta:\n model = TblQueries\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblQueriesForm, self).__init__(*args, **kwargs)\n self.fields['datetime'].widget = forms.HiddenInput()\n self.fields['name'].widget.attrs['placeholder'] = 'Name'\n self.fields['email'].widget.attrs['placeholder'] = 'Email'\n self.fields['subject'].widget.attrs['placeholder'] = 'Subject'\n self.fields['message'].widget.attrs['placeholder'] = 'Message'\n", "step-3": "<mask token>\n\n\nclass TblSnippetDataForm(forms.ModelForm):\n\n\n class Meta:\n model = TblSnippetData\n fields = ['snippet_topics', 'snippet_data_subject',\n 'snippet_data_description', 'snippet_data_keyword',\n 'snippet_data_code', 'snippet_data_datetime',\n 'snippet_data_added_by', 'snippet_topics', 'snippet_data_publish']\n\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\n def __init__(self, *args, **kwargs):\n super(TblSnippetDataForm, self).__init__(*args, **kwargs)\n self.fields['snippet_data_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_data_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget = forms.HiddenInput()\n self.fields['snippet_data_subject'].widget.attrs['placeholder'\n ] = 'Title/Topics'\n self.fields['snippet_data_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['snippet_data_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['snippet_data_code'].widget.attrs['placeholder'\n ] = 'Snippet (Code)'\n self.fields['snippet_data_publish'].widget.attrs['placeholder'\n ] = 'Ready-To-Publish'\n self.fields['snippet_data_publish'].label = 'Publish'\n\n\nclass TblBlogForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlog\n fields = ['blog_title', 'blog_description', 'blog_keyword',\n 'blog_content', 'blog_pics', 'blog_publish', 'blog_datetime',\n 'blog_summary', 'blog_like', 'blog_added_by']\n\n def __init__(self, *args, **kwargs):\n super(TblBlogForm, self).__init__(*args, **kwargs)\n self.fields['blog_datetime'].widget = forms.HiddenInput()\n self.fields['blog_summary'].widget = forms.HiddenInput()\n self.fields['blog_like'].widget = forms.HiddenInput()\n self.fields['blog_added_by'].widget = forms.HiddenInput()\n self.fields['blog_title'].widget.attrs['placeholder'] = 'Title/Topics'\n self.fields['blog_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['blog_content'].widget.attrs['placeholder'\n ] = 'Blog Content'\n self.fields['blog_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['blog_pics'].widget.attrs['placeholder'] = 'Upload Pics'\n self.fields['blog_publish'].label = 'Publish'\n\n\nclass TblBlogCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogComments\n fields = '__all__'\n\n\nclass TblLearnDataForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnData\n fields = ['learn_data', 'learn_data_keyword',\n 'learn_data_description', 'learn_data_publish',\n 'learn_data_datetime', 'learn_data_added_by', 'learn_topics',\n 'learn_data_like', 'learn_data_icon']\n\n def __init__(self, *args, **kwargs):\n super(TblLearnDataForm, self).__init__(*args, **kwargs)\n self.fields['learn_data_datetime'].widget = forms.HiddenInput()\n self.fields['learn_data_added_by'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget = forms.HiddenInput()\n self.fields['learn_data_like'].widget = forms.HiddenInput()\n self.fields['learn_data_icon'].widget = forms.HiddenInput()\n self.fields['learn_data'].widget.attrs['placeholder'] = 'Title/Topics'\n self.fields['learn_data_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['learn_data_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['learn_data_publish'].label = 'Publish'\n\n\nclass TblLearnDataCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataComments\n fields = '__all__'\n\n\nclass TblBlogGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogGvp\n fields = '__all__'\n\n\nclass TblLearnDataGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataGvp\n fields = '__all__'\n\n\nclass TblHomeForm(forms.ModelForm):\n\n\n class Meta:\n model = TblHome\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblHomeForm, self).__init__(*args, **kwargs)\n self.fields['home_datetime'].widget = forms.HiddenInput()\n self.fields['home_added_by'].widget = forms.HiddenInput()\n self.fields['home_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['home_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['home_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['home_publish'].label = 'Publish'\n\n\nclass TblAboutForm(forms.ModelForm):\n\n\n class Meta:\n model = TblAbout\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblAboutForm, self).__init__(*args, **kwargs)\n self.fields['about_datetime'].widget = forms.HiddenInput()\n self.fields['about_added_by'].widget = forms.HiddenInput()\n self.fields['about_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['about_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['about_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['about_publish'].label = 'Publish'\n\n\nclass TblLearnTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblLearnTopicsForm, self).__init__(*args, **kwargs)\n self.fields['learn_topics_datetime'].widget = forms.HiddenInput()\n self.fields['learn_topics_icon'].widget.attrs['placeholder'] = 'Icon'\n self.fields['learn_topics_coverpage_img'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['learn_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['learn_topics_publish'].label = 'Publish'\n\n def clean_learn_topics_added_by(self):\n if not self.cleaned_data['learn_topics_added_by']:\n return User()\n return self.cleaned_data['learn_topics_added_by']\n\n\nclass TblSnippetTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblSnippetTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblSnippetTopicsForm, self).__init__(*args, **kwargs)\n self.fields['snippet_topics_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_topics_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics_icon'].widget = forms.HiddenInput()\n self.fields['snippet_topics_coverpage_img'].widget = forms.HiddenInput(\n )\n self.fields['snippet_topics_expire'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['snippet_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['snippet_topics_publish'].label = 'Publish'\n\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\n\nclass TblQueriesForm(forms.ModelForm):\n\n\n class Meta:\n model = TblQueries\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblQueriesForm, self).__init__(*args, **kwargs)\n self.fields['datetime'].widget = forms.HiddenInput()\n self.fields['name'].widget.attrs['placeholder'] = 'Name'\n self.fields['email'].widget.attrs['placeholder'] = 'Email'\n self.fields['subject'].widget.attrs['placeholder'] = 'Subject'\n self.fields['message'].widget.attrs['placeholder'] = 'Message'\n", "step-4": "<mask token>\n\n\nclass SignupForm(UserCreationForm):\n <mask token>\n\n\n class Meta:\n model = User\n fields = 'username', 'email', 'password1', 'password2'\n <mask token>\n\n\nclass UserRegistrationForm(forms.Form):\n username = forms.CharField(required=True, min_length=6, label=\n 'Username', max_length=100, widget=forms.TextInput(attrs={\n 'placeholder': 'Username'}))\n email = forms.EmailField(required=True, label='Email', max_length=100,\n widget=forms.EmailInput(attrs={'placeholder':\n 'e.g. : email@gmail.com'}))\n firstname = forms.CharField(required=True, label='First Name',\n max_length=100, widget=forms.TextInput(attrs={'placeholder':\n 'First Name'}))\n lastname = forms.CharField(required=True, label='Last Name', max_length\n =100, widget=forms.TextInput(attrs={'placeholder': 'Last Name'}))\n password = forms.CharField(required=True, label='Password', max_length=\n 100, widget=forms.PasswordInput(attrs={'placeholder': 'Password'}))\n passwordagain = forms.CharField(required=True, label='Password (Again)',\n max_length=100, widget=forms.PasswordInput(attrs={'placeholder':\n 'Password (Again)'}))\n\n\nclass TblPublishForm(forms.ModelForm):\n\n\n class Meta:\n model = TblPublish\n fields = '__all__'\n\n\nclass TblSnippetDataForm(forms.ModelForm):\n\n\n class Meta:\n model = TblSnippetData\n fields = ['snippet_topics', 'snippet_data_subject',\n 'snippet_data_description', 'snippet_data_keyword',\n 'snippet_data_code', 'snippet_data_datetime',\n 'snippet_data_added_by', 'snippet_topics', 'snippet_data_publish']\n\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\n def __init__(self, *args, **kwargs):\n super(TblSnippetDataForm, self).__init__(*args, **kwargs)\n self.fields['snippet_data_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_data_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget = forms.HiddenInput()\n self.fields['snippet_data_subject'].widget.attrs['placeholder'\n ] = 'Title/Topics'\n self.fields['snippet_data_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['snippet_data_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['snippet_data_code'].widget.attrs['placeholder'\n ] = 'Snippet (Code)'\n self.fields['snippet_data_publish'].widget.attrs['placeholder'\n ] = 'Ready-To-Publish'\n self.fields['snippet_data_publish'].label = 'Publish'\n\n\nclass TblBlogForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlog\n fields = ['blog_title', 'blog_description', 'blog_keyword',\n 'blog_content', 'blog_pics', 'blog_publish', 'blog_datetime',\n 'blog_summary', 'blog_like', 'blog_added_by']\n\n def __init__(self, *args, **kwargs):\n super(TblBlogForm, self).__init__(*args, **kwargs)\n self.fields['blog_datetime'].widget = forms.HiddenInput()\n self.fields['blog_summary'].widget = forms.HiddenInput()\n self.fields['blog_like'].widget = forms.HiddenInput()\n self.fields['blog_added_by'].widget = forms.HiddenInput()\n self.fields['blog_title'].widget.attrs['placeholder'] = 'Title/Topics'\n self.fields['blog_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['blog_content'].widget.attrs['placeholder'\n ] = 'Blog Content'\n self.fields['blog_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['blog_pics'].widget.attrs['placeholder'] = 'Upload Pics'\n self.fields['blog_publish'].label = 'Publish'\n\n\nclass TblBlogCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogComments\n fields = '__all__'\n\n\nclass TblLearnDataForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnData\n fields = ['learn_data', 'learn_data_keyword',\n 'learn_data_description', 'learn_data_publish',\n 'learn_data_datetime', 'learn_data_added_by', 'learn_topics',\n 'learn_data_like', 'learn_data_icon']\n\n def __init__(self, *args, **kwargs):\n super(TblLearnDataForm, self).__init__(*args, **kwargs)\n self.fields['learn_data_datetime'].widget = forms.HiddenInput()\n self.fields['learn_data_added_by'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget = forms.HiddenInput()\n self.fields['learn_data_like'].widget = forms.HiddenInput()\n self.fields['learn_data_icon'].widget = forms.HiddenInput()\n self.fields['learn_data'].widget.attrs['placeholder'] = 'Title/Topics'\n self.fields['learn_data_description'].widget.attrs['placeholder'\n ] = 'Brief Description'\n self.fields['learn_data_keyword'].widget.attrs['placeholder'\n ] = 'Keyword For Search'\n self.fields['learn_data_publish'].label = 'Publish'\n\n\nclass TblLearnDataCommentsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataComments\n fields = '__all__'\n\n\nclass TblBlogGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblBlogGvp\n fields = '__all__'\n\n\nclass TblLearnDataGvpForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnDataGvp\n fields = '__all__'\n\n\nclass TblHomeForm(forms.ModelForm):\n\n\n class Meta:\n model = TblHome\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblHomeForm, self).__init__(*args, **kwargs)\n self.fields['home_datetime'].widget = forms.HiddenInput()\n self.fields['home_added_by'].widget = forms.HiddenInput()\n self.fields['home_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['home_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['home_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['home_publish'].label = 'Publish'\n\n\nclass TblAboutForm(forms.ModelForm):\n\n\n class Meta:\n model = TblAbout\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblAboutForm, self).__init__(*args, **kwargs)\n self.fields['about_datetime'].widget = forms.HiddenInput()\n self.fields['about_added_by'].widget = forms.HiddenInput()\n self.fields['about_pics'].widget.attrs['placeholder'] = 'Upload Image'\n self.fields['about_content'].widget.attrs['placeholder'] = 'Content'\n self.fields['about_content_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['about_publish'].label = 'Publish'\n\n\nclass TblLearnTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblLearnTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblLearnTopicsForm, self).__init__(*args, **kwargs)\n self.fields['learn_topics_datetime'].widget = forms.HiddenInput()\n self.fields['learn_topics_icon'].widget.attrs['placeholder'] = 'Icon'\n self.fields['learn_topics_coverpage_img'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['learn_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['learn_topics_publish'].label = 'Publish'\n\n def clean_learn_topics_added_by(self):\n if not self.cleaned_data['learn_topics_added_by']:\n return User()\n return self.cleaned_data['learn_topics_added_by']\n\n\nclass TblSnippetTopicsForm(forms.ModelForm):\n\n\n class Meta:\n model = TblSnippetTopics\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblSnippetTopicsForm, self).__init__(*args, **kwargs)\n self.fields['snippet_topics_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_topics_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics_icon'].widget = forms.HiddenInput()\n self.fields['snippet_topics_coverpage_img'].widget = forms.HiddenInput(\n )\n self.fields['snippet_topics_expire'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget.attrs['placeholder'] = 'Topics'\n self.fields['snippet_topics_description'].widget.attrs['placeholder'\n ] = 'Description'\n self.fields['snippet_topics_publish'].label = 'Publish'\n\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\n\nclass TblQueriesForm(forms.ModelForm):\n\n\n class Meta:\n model = TblQueries\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblQueriesForm, self).__init__(*args, **kwargs)\n self.fields['datetime'].widget = forms.HiddenInput()\n self.fields['name'].widget.attrs['placeholder'] = 'Name'\n self.fields['email'].widget.attrs['placeholder'] = 'Email'\n self.fields['subject'].widget.attrs['placeholder'] = 'Subject'\n self.fields['message'].widget.attrs['placeholder'] = 'Message'\n", "step-5": "from django import forms\nfrom django.contrib.auth.models import User\nfrom .models import TblPublish , TblSnippetTopics, TblSnippetData, TblLearnTopics, TblLearnData, TblBlog, TblBlogComments,TblLearnDataComments, TblBlogGvp, TblLearnDataGvp,TblSnippetDataGvp, TblHome, TblAbout, TblQueries\nfrom django.contrib.auth.forms import UserCreationForm\n\nclass UsersigninForm(forms.Form):\n username = forms.CharField(required = True, label = 'Username', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'Username'}))\n password = forms.CharField(required = True, label = 'Password', max_length = 32, widget = forms.PasswordInput(attrs={'placeholder': 'Password'}))\n\nclass SignupForm(UserCreationForm):\n email = forms.EmailField(max_length=200, help_text='Required')\n class Meta:\n model = User\n fields = ('username', 'email', 'password1', 'password2')\n\n def __init__(self, *args, **kwargs):\n super(SignupForm, self).__init__(*args, **kwargs)\n self.fields['username'].widget.attrs['placeholder'] = \"Username\"\n self.fields['email'].widget.attrs['placeholder'] = \"email\"\n self.fields['password1'].widget.attrs['placeholder'] =\"password\"\n self.fields['password2'].widget.attrs['placeholder'] = \"password Again\"\n\nclass UserRegistrationForm(forms.Form):\n username = forms.CharField(required = True, min_length=6,label = 'Username', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'Username'}) )\n email = forms.EmailField(required = True, label = 'Email', max_length = 100, widget=forms.EmailInput(attrs={'placeholder': 'e.g. : email@gmail.com'}))\n firstname = forms.CharField(required = True, label = 'First Name', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'First Name'}))\n lastname = forms.CharField(required = True, label = 'Last Name', max_length = 100, widget=forms.TextInput(attrs={'placeholder': 'Last Name'}))\n password = forms.CharField(required = True, label = 'Password', max_length = 100, widget = forms.PasswordInput(attrs={'placeholder': 'Password'}))\n passwordagain = forms.CharField(required = True, label = 'Password (Again)', max_length = 100, widget = forms.PasswordInput(attrs={'placeholder': 'Password (Again)'}))\n\nclass TblPublishForm(forms.ModelForm):\n class Meta():\n model = TblPublish\n fields = '__all__'\n\n\nclass TblSnippetDataForm(forms.ModelForm):\n class Meta():\n model = TblSnippetData\n fields = ['snippet_topics','snippet_data_subject','snippet_data_description','snippet_data_keyword','snippet_data_code','snippet_data_datetime','snippet_data_added_by','snippet_topics','snippet_data_publish']\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\n def __init__(self, *args, **kwargs):\n super(TblSnippetDataForm, self).__init__(*args, **kwargs)\n self.fields['snippet_data_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_data_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget = forms.HiddenInput()\n self.fields['snippet_data_subject'].widget.attrs['placeholder'] = \"Title/Topics\"\n self.fields['snippet_data_description'].widget.attrs['placeholder'] = \"Brief Description\"\n self.fields['snippet_data_keyword'].widget.attrs['placeholder'] =\"Keyword For Search\"\n self.fields['snippet_data_code'].widget.attrs['placeholder'] = \"Snippet (Code)\"\n self.fields['snippet_data_publish'].widget.attrs['placeholder'] = \"Ready-To-Publish\"\n self.fields['snippet_data_publish'].label = \"Publish\"\n\nclass TblBlogForm(forms.ModelForm):\n class Meta():\n model = TblBlog\n fields = ['blog_title','blog_description','blog_keyword','blog_content','blog_pics','blog_publish','blog_datetime','blog_summary','blog_like','blog_added_by']\n\n def __init__(self, *args, **kwargs):\n super(TblBlogForm, self).__init__(*args, **kwargs)\n self.fields['blog_datetime'].widget = forms.HiddenInput()\n self.fields['blog_summary'].widget = forms.HiddenInput()\n self.fields['blog_like'].widget = forms.HiddenInput()\n self.fields['blog_added_by'].widget = forms.HiddenInput()\n self.fields['blog_title'].widget.attrs['placeholder'] = \"Title/Topics\"\n self.fields['blog_description'].widget.attrs['placeholder'] = \"Brief Description\"\n self.fields['blog_content'].widget.attrs['placeholder'] = \"Blog Content\"\n self.fields['blog_keyword'].widget.attrs['placeholder'] = \"Keyword For Search\"\n self.fields['blog_pics'].widget.attrs['placeholder'] = \"Upload Pics\"\n self.fields['blog_publish'].label = \"Publish\"\n\n\n\nclass TblBlogCommentsForm(forms.ModelForm):\n class Meta():\n model = TblBlogComments\n fields = '__all__'\n\nclass TblLearnDataForm(forms.ModelForm):\n class Meta():\n model = TblLearnData\n fields = ['learn_data','learn_data_keyword','learn_data_description','learn_data_publish','learn_data_datetime','learn_data_added_by','learn_topics','learn_data_like','learn_data_icon']\n\n def __init__(self, *args, **kwargs):\n super(TblLearnDataForm, self).__init__(*args, **kwargs)\n self.fields['learn_data_datetime'].widget = forms.HiddenInput()\n self.fields['learn_data_added_by'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget = forms.HiddenInput()\n self.fields['learn_data_like'].widget = forms.HiddenInput()\n self.fields['learn_data_icon'].widget = forms.HiddenInput()\n self.fields['learn_data'].widget.attrs['placeholder'] = \"Title/Topics\"\n self.fields['learn_data_description'].widget.attrs['placeholder'] = \"Brief Description\"\n self.fields['learn_data_keyword'].widget.attrs['placeholder'] = \"Keyword For Search\"\n self.fields['learn_data_publish'].label = \"Publish\"\n\nclass TblLearnDataCommentsForm(forms.ModelForm):\n class Meta():\n model = TblLearnDataComments\n fields = '__all__'\n\nclass TblBlogGvpForm(forms.ModelForm):\n class Meta():\n model = TblBlogGvp\n fields = '__all__'\nclass TblLearnDataGvpForm(forms.ModelForm):\n class Meta():\n model = TblLearnDataGvp\n fields = '__all__'\nclass TblHomeForm(forms.ModelForm):\n class Meta():\n model = TblHome\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(TblHomeForm, self).__init__(*args, **kwargs)\n self.fields['home_datetime'].widget = forms.HiddenInput()\n self.fields['home_added_by'].widget = forms.HiddenInput()\n self.fields['home_pics'].widget.attrs['placeholder'] = \"Upload Image\"\n self.fields['home_content'].widget.attrs['placeholder'] = \"Content\"\n self.fields['home_content_description'].widget.attrs['placeholder'] = \"Description\"\n self.fields['home_publish'].label = \"Publish\"\n\n\nclass TblAboutForm(forms.ModelForm):\n class Meta():\n model = TblAbout\n fields = '__all__'\n def __init__(self, *args, **kwargs):\n super(TblAboutForm, self).__init__(*args, **kwargs)\n self.fields['about_datetime'].widget = forms.HiddenInput()\n self.fields['about_added_by'].widget = forms.HiddenInput()\n self.fields['about_pics'].widget.attrs['placeholder'] = \"Upload Image\"\n self.fields['about_content'].widget.attrs['placeholder'] = \"Content\"\n self.fields['about_content_description'].widget.attrs['placeholder'] = \"Description\"\n self.fields['about_publish'].label = \"Publish\"\n\nclass TblLearnTopicsForm(forms.ModelForm):\n class Meta():\n model = TblLearnTopics\n fields = '__all__'\n def __init__(self, *args, **kwargs):\n super(TblLearnTopicsForm, self).__init__(*args, **kwargs)\n self.fields['learn_topics_datetime'].widget = forms.HiddenInput()\n # self.fields['learn_topics_added_by'].widget = forms.HiddenInput()\n self.fields['learn_topics_icon'].widget.attrs['placeholder'] = 'Icon'\n self.fields['learn_topics_coverpage_img'].widget = forms.HiddenInput()\n self.fields['learn_topics'].widget.attrs['placeholder'] = \"Topics\"\n self.fields['learn_topics_description'].widget.attrs['placeholder'] = \"Description\"\n self.fields['learn_topics_publish'].label = \"Publish\"\n\n\n\n def clean_learn_topics_added_by(self):\n if not self.cleaned_data['learn_topics_added_by']:\n return User()\n return self.cleaned_data['learn_topics_added_by']\n\nclass TblSnippetTopicsForm(forms.ModelForm):\n class Meta():\n model = TblSnippetTopics\n fields = '__all__'\n def __init__(self, *args, **kwargs):\n super(TblSnippetTopicsForm, self).__init__(*args, **kwargs)\n self.fields['snippet_topics_datetime'].widget = forms.HiddenInput()\n self.fields['snippet_topics_added_by'].widget = forms.HiddenInput()\n self.fields['snippet_topics_icon'].widget = forms.HiddenInput()\n self.fields['snippet_topics_coverpage_img'].widget = forms.HiddenInput()\n self.fields['snippet_topics_expire'].widget = forms.HiddenInput()\n self.fields['snippet_topics'].widget.attrs['placeholder'] = \"Topics\"\n self.fields['snippet_topics_description'].widget.attrs['placeholder'] = \"Description\"\n self.fields['snippet_topics_publish'].label = \"Publish\"\n\n def clean_snippet_topics_added_by(self):\n if not self.cleaned_data['snippet_topics_added_by']:\n return User()\n return self.cleaned_data['snippet_topics_added_by']\n\nclass TblQueriesForm(forms.ModelForm):\n class Meta():\n model = TblQueries\n fields = '__all__'\n def __init__(self, *args, **kwargs):\n super(TblQueriesForm, self).__init__(*args, **kwargs)\n self.fields['datetime'].widget = forms.HiddenInput()\n self.fields['name'].widget.attrs['placeholder'] = \"Name\"\n self.fields['email'].widget.attrs['placeholder'] = \"Email\"\n self.fields['subject'].widget.attrs['placeholder'] = \"Subject\"\n self.fields['message'].widget.attrs['placeholder'] = \"Message\"\n", "step-ids": [ 19, 20, 22, 26, 32 ] }
[ 19, 20, 22, 26, 32 ]
from pathlib import Path from build_midi.appenders import * from build_midi.converters import Converter from build_midi.melody_builder import MelodyBuilder from build_midi.sequences import * from build_midi.tracks import * from music_rules.instruments import Instruments from music_rules.music_scale import MusicScale from weather.weather_api import WeatherApi class WeatherToMusicConverter: PHRASE_LENGTH = 1200 OUTPUT_FILE_DIR = 'midi_out' music_scales = MusicScale() def weather_to_music(self, api_key, city) -> MidiFile: api_handling = WeatherApi() converter = Converter() weather_forecast = api_handling.get_weather_forecast_from_api(city, api_key) average_temperature = converter.average_temperature(weather_forecast.weather_timestamps) ticks_per_beat = converter.average_temperature_to_ticks_per_beat(average_temperature) outfile = MidiFile() outfile.ticks_per_beat = ticks_per_beat melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH) temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano) rain = RainTrack(2, Instruments.Celesta) clouds = CloudsTrack(3, Instruments.TremoloStrings) humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean) wind = WindTrack(5, Instruments.Seashore) for track in [temperature, rain, clouds, humidity, wind]: melody_builder.set_instrument(track.get_track(), track.get_channel(), track.get_instrument()) for entry in weather_forecast.weather_timestamps: base_note = converter.temperature_to_base_note(entry.temperature.feels_like) music_scale = self.music_scales.melodic_minor(base_note) temperature_sequence = TemperatureSequence(entry.temperature, self.PHRASE_LENGTH, base_note, temperature.get_track()) temperature_appender = TemperatureAppender() temperature_appender.append(melody_builder, temperature_sequence, temperature) rain_sequence = RainSequence(entry.weather.rain, self.PHRASE_LENGTH, base_note, rain.get_track(), music_scale) rain_appender = RainAppender() rain_appender.append(melody_builder, rain_sequence, rain) clouds_sequence = CloudsSequence(entry.weather.clouds, self.PHRASE_LENGTH, base_note, clouds.get_track()) clouds_appender = CloudsAppender() clouds_appender.append(melody_builder, clouds_sequence, clouds) humidity_sequence = HumiditySequence(entry.weather.humidity, self.PHRASE_LENGTH, base_note, humidity.get_track()) humidity_appender = HumidityAppender() humidity_appender.append(melody_builder, humidity_sequence, humidity) wind_sequence = WindSequence(entry.weather.wind_speed, self.PHRASE_LENGTH, base_note, wind.get_track()) wind_appender = WindAppender() wind_appender.append(melody_builder, wind_sequence, wind) for track in [temperature.get_track(), rain.get_track(), clouds.get_track(), humidity.get_track(), wind.get_track()]: outfile.tracks.append(track) file_name = 'weather_song_' + weather_forecast.city + '_' + weather_forecast.country + '_' + str(weather_forecast.weather_timestamps[0].timestamp) self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name) return outfile def save_file(self, outfile: MidiFile, file_dir: str, file_name: str) -> MidiFile: Path(file_dir).mkdir(exist_ok=True) file_path = file_dir + '/' + file_name + '.mid' outfile.save(file_path) print('file saved at ' + file_path) return outfile def get_midi_track_time(self, midi_track: MidiTrack): sum = 0 for message in midi_track: sum += message.time return sum
normal
{ "blob_id": "c846c33ef13795d51c6d23ffa5a6b564b66e6a3c", "index": 3438, "step-1": "<mask token>\n\n\nclass WeatherToMusicConverter:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass WeatherToMusicConverter:\n <mask token>\n <mask token>\n <mask token>\n\n def weather_to_music(self, api_key, city) ->MidiFile:\n api_handling = WeatherApi()\n converter = Converter()\n weather_forecast = api_handling.get_weather_forecast_from_api(city,\n api_key)\n average_temperature = converter.average_temperature(weather_forecast\n .weather_timestamps)\n ticks_per_beat = converter.average_temperature_to_ticks_per_beat(\n average_temperature)\n outfile = MidiFile()\n outfile.ticks_per_beat = ticks_per_beat\n melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n rain = RainTrack(2, Instruments.Celesta)\n clouds = CloudsTrack(3, Instruments.TremoloStrings)\n humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n wind = WindTrack(5, Instruments.Seashore)\n for track in [temperature, rain, clouds, humidity, wind]:\n melody_builder.set_instrument(track.get_track(), track.\n get_channel(), track.get_instrument())\n for entry in weather_forecast.weather_timestamps:\n base_note = converter.temperature_to_base_note(entry.\n temperature.feels_like)\n music_scale = self.music_scales.melodic_minor(base_note)\n temperature_sequence = TemperatureSequence(entry.temperature,\n self.PHRASE_LENGTH, base_note, temperature.get_track())\n temperature_appender = TemperatureAppender()\n temperature_appender.append(melody_builder,\n temperature_sequence, temperature)\n rain_sequence = RainSequence(entry.weather.rain, self.\n PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n rain_appender = RainAppender()\n rain_appender.append(melody_builder, rain_sequence, rain)\n clouds_sequence = CloudsSequence(entry.weather.clouds, self.\n PHRASE_LENGTH, base_note, clouds.get_track())\n clouds_appender = CloudsAppender()\n clouds_appender.append(melody_builder, clouds_sequence, clouds)\n humidity_sequence = HumiditySequence(entry.weather.humidity,\n self.PHRASE_LENGTH, base_note, humidity.get_track())\n humidity_appender = HumidityAppender()\n humidity_appender.append(melody_builder, humidity_sequence,\n humidity)\n wind_sequence = WindSequence(entry.weather.wind_speed, self.\n PHRASE_LENGTH, base_note, wind.get_track())\n wind_appender = WindAppender()\n wind_appender.append(melody_builder, wind_sequence, wind)\n for track in [temperature.get_track(), rain.get_track(), clouds.\n get_track(), humidity.get_track(), wind.get_track()]:\n outfile.tracks.append(track)\n file_name = ('weather_song_' + weather_forecast.city + '_' +\n weather_forecast.country + '_' + str(weather_forecast.\n weather_timestamps[0].timestamp))\n self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n return outfile\n\n def save_file(self, outfile: MidiFile, file_dir: str, file_name: str\n ) ->MidiFile:\n Path(file_dir).mkdir(exist_ok=True)\n file_path = file_dir + '/' + file_name + '.mid'\n outfile.save(file_path)\n print('file saved at ' + file_path)\n return outfile\n\n def get_midi_track_time(self, midi_track: MidiTrack):\n sum = 0\n for message in midi_track:\n sum += message.time\n return sum\n", "step-3": "<mask token>\n\n\nclass WeatherToMusicConverter:\n PHRASE_LENGTH = 1200\n OUTPUT_FILE_DIR = 'midi_out'\n music_scales = MusicScale()\n\n def weather_to_music(self, api_key, city) ->MidiFile:\n api_handling = WeatherApi()\n converter = Converter()\n weather_forecast = api_handling.get_weather_forecast_from_api(city,\n api_key)\n average_temperature = converter.average_temperature(weather_forecast\n .weather_timestamps)\n ticks_per_beat = converter.average_temperature_to_ticks_per_beat(\n average_temperature)\n outfile = MidiFile()\n outfile.ticks_per_beat = ticks_per_beat\n melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n rain = RainTrack(2, Instruments.Celesta)\n clouds = CloudsTrack(3, Instruments.TremoloStrings)\n humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n wind = WindTrack(5, Instruments.Seashore)\n for track in [temperature, rain, clouds, humidity, wind]:\n melody_builder.set_instrument(track.get_track(), track.\n get_channel(), track.get_instrument())\n for entry in weather_forecast.weather_timestamps:\n base_note = converter.temperature_to_base_note(entry.\n temperature.feels_like)\n music_scale = self.music_scales.melodic_minor(base_note)\n temperature_sequence = TemperatureSequence(entry.temperature,\n self.PHRASE_LENGTH, base_note, temperature.get_track())\n temperature_appender = TemperatureAppender()\n temperature_appender.append(melody_builder,\n temperature_sequence, temperature)\n rain_sequence = RainSequence(entry.weather.rain, self.\n PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n rain_appender = RainAppender()\n rain_appender.append(melody_builder, rain_sequence, rain)\n clouds_sequence = CloudsSequence(entry.weather.clouds, self.\n PHRASE_LENGTH, base_note, clouds.get_track())\n clouds_appender = CloudsAppender()\n clouds_appender.append(melody_builder, clouds_sequence, clouds)\n humidity_sequence = HumiditySequence(entry.weather.humidity,\n self.PHRASE_LENGTH, base_note, humidity.get_track())\n humidity_appender = HumidityAppender()\n humidity_appender.append(melody_builder, humidity_sequence,\n humidity)\n wind_sequence = WindSequence(entry.weather.wind_speed, self.\n PHRASE_LENGTH, base_note, wind.get_track())\n wind_appender = WindAppender()\n wind_appender.append(melody_builder, wind_sequence, wind)\n for track in [temperature.get_track(), rain.get_track(), clouds.\n get_track(), humidity.get_track(), wind.get_track()]:\n outfile.tracks.append(track)\n file_name = ('weather_song_' + weather_forecast.city + '_' +\n weather_forecast.country + '_' + str(weather_forecast.\n weather_timestamps[0].timestamp))\n self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n return outfile\n\n def save_file(self, outfile: MidiFile, file_dir: str, file_name: str\n ) ->MidiFile:\n Path(file_dir).mkdir(exist_ok=True)\n file_path = file_dir + '/' + file_name + '.mid'\n outfile.save(file_path)\n print('file saved at ' + file_path)\n return outfile\n\n def get_midi_track_time(self, midi_track: MidiTrack):\n sum = 0\n for message in midi_track:\n sum += message.time\n return sum\n", "step-4": "from pathlib import Path\nfrom build_midi.appenders import *\nfrom build_midi.converters import Converter\nfrom build_midi.melody_builder import MelodyBuilder\nfrom build_midi.sequences import *\nfrom build_midi.tracks import *\nfrom music_rules.instruments import Instruments\nfrom music_rules.music_scale import MusicScale\nfrom weather.weather_api import WeatherApi\n\n\nclass WeatherToMusicConverter:\n PHRASE_LENGTH = 1200\n OUTPUT_FILE_DIR = 'midi_out'\n music_scales = MusicScale()\n\n def weather_to_music(self, api_key, city) ->MidiFile:\n api_handling = WeatherApi()\n converter = Converter()\n weather_forecast = api_handling.get_weather_forecast_from_api(city,\n api_key)\n average_temperature = converter.average_temperature(weather_forecast\n .weather_timestamps)\n ticks_per_beat = converter.average_temperature_to_ticks_per_beat(\n average_temperature)\n outfile = MidiFile()\n outfile.ticks_per_beat = ticks_per_beat\n melody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n temperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n rain = RainTrack(2, Instruments.Celesta)\n clouds = CloudsTrack(3, Instruments.TremoloStrings)\n humidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n wind = WindTrack(5, Instruments.Seashore)\n for track in [temperature, rain, clouds, humidity, wind]:\n melody_builder.set_instrument(track.get_track(), track.\n get_channel(), track.get_instrument())\n for entry in weather_forecast.weather_timestamps:\n base_note = converter.temperature_to_base_note(entry.\n temperature.feels_like)\n music_scale = self.music_scales.melodic_minor(base_note)\n temperature_sequence = TemperatureSequence(entry.temperature,\n self.PHRASE_LENGTH, base_note, temperature.get_track())\n temperature_appender = TemperatureAppender()\n temperature_appender.append(melody_builder,\n temperature_sequence, temperature)\n rain_sequence = RainSequence(entry.weather.rain, self.\n PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n rain_appender = RainAppender()\n rain_appender.append(melody_builder, rain_sequence, rain)\n clouds_sequence = CloudsSequence(entry.weather.clouds, self.\n PHRASE_LENGTH, base_note, clouds.get_track())\n clouds_appender = CloudsAppender()\n clouds_appender.append(melody_builder, clouds_sequence, clouds)\n humidity_sequence = HumiditySequence(entry.weather.humidity,\n self.PHRASE_LENGTH, base_note, humidity.get_track())\n humidity_appender = HumidityAppender()\n humidity_appender.append(melody_builder, humidity_sequence,\n humidity)\n wind_sequence = WindSequence(entry.weather.wind_speed, self.\n PHRASE_LENGTH, base_note, wind.get_track())\n wind_appender = WindAppender()\n wind_appender.append(melody_builder, wind_sequence, wind)\n for track in [temperature.get_track(), rain.get_track(), clouds.\n get_track(), humidity.get_track(), wind.get_track()]:\n outfile.tracks.append(track)\n file_name = ('weather_song_' + weather_forecast.city + '_' +\n weather_forecast.country + '_' + str(weather_forecast.\n weather_timestamps[0].timestamp))\n self.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n return outfile\n\n def save_file(self, outfile: MidiFile, file_dir: str, file_name: str\n ) ->MidiFile:\n Path(file_dir).mkdir(exist_ok=True)\n file_path = file_dir + '/' + file_name + '.mid'\n outfile.save(file_path)\n print('file saved at ' + file_path)\n return outfile\n\n def get_midi_track_time(self, midi_track: MidiTrack):\n sum = 0\n for message in midi_track:\n sum += message.time\n return sum\n", "step-5": "from pathlib import Path\n\nfrom build_midi.appenders import *\nfrom build_midi.converters import Converter\nfrom build_midi.melody_builder import MelodyBuilder\nfrom build_midi.sequences import *\nfrom build_midi.tracks import *\nfrom music_rules.instruments import Instruments\nfrom music_rules.music_scale import MusicScale\nfrom weather.weather_api import WeatherApi\n\n\nclass WeatherToMusicConverter:\n\n\tPHRASE_LENGTH = 1200\n\tOUTPUT_FILE_DIR = 'midi_out'\n\n\tmusic_scales = MusicScale()\n\n\tdef weather_to_music(self, api_key, city) -> MidiFile:\n\t\tapi_handling = WeatherApi()\n\t\tconverter = Converter()\n\n\t\tweather_forecast = api_handling.get_weather_forecast_from_api(city, api_key)\n\n\t\taverage_temperature = converter.average_temperature(weather_forecast.weather_timestamps)\n\t\tticks_per_beat = converter.average_temperature_to_ticks_per_beat(average_temperature)\n\n\t\toutfile = MidiFile()\n\t\toutfile.ticks_per_beat = ticks_per_beat\n\n\t\tmelody_builder = MelodyBuilder(outfile, self.PHRASE_LENGTH)\n\n\t\ttemperature = TemperatureTrack(1, Instruments.BrightAcousticPiano)\n\t\train = RainTrack(2, Instruments.Celesta)\n\t\tclouds = CloudsTrack(3, Instruments.TremoloStrings)\n\t\thumidity = HumidityTrack(4, Instruments.ElectricGuitar_clean)\n\t\twind = WindTrack(5, Instruments.Seashore)\n\n\t\tfor track in [temperature, rain, clouds, humidity, wind]:\n\t\t\tmelody_builder.set_instrument(track.get_track(), track.get_channel(), track.get_instrument())\n\n\t\tfor entry in weather_forecast.weather_timestamps:\n\n\t\t\tbase_note = converter.temperature_to_base_note(entry.temperature.feels_like)\n\t\t\tmusic_scale = self.music_scales.melodic_minor(base_note)\n\n\t\t\ttemperature_sequence = TemperatureSequence(entry.temperature, self.PHRASE_LENGTH, base_note, temperature.get_track())\n\t\t\ttemperature_appender = TemperatureAppender()\n\t\t\ttemperature_appender.append(melody_builder, temperature_sequence, temperature)\n\n\t\t\train_sequence = RainSequence(entry.weather.rain, self.PHRASE_LENGTH, base_note, rain.get_track(), music_scale)\n\t\t\train_appender = RainAppender()\n\t\t\train_appender.append(melody_builder, rain_sequence, rain)\n\n\t\t\tclouds_sequence = CloudsSequence(entry.weather.clouds, self.PHRASE_LENGTH, base_note, clouds.get_track())\n\t\t\tclouds_appender = CloudsAppender()\n\t\t\tclouds_appender.append(melody_builder, clouds_sequence, clouds)\n\n\t\t\thumidity_sequence = HumiditySequence(entry.weather.humidity, self.PHRASE_LENGTH, base_note, humidity.get_track())\n\t\t\thumidity_appender = HumidityAppender()\n\t\t\thumidity_appender.append(melody_builder, humidity_sequence, humidity)\n\n\t\t\twind_sequence = WindSequence(entry.weather.wind_speed, self.PHRASE_LENGTH, base_note, wind.get_track())\n\t\t\twind_appender = WindAppender()\n\t\t\twind_appender.append(melody_builder, wind_sequence, wind)\n\n\t\tfor track in [temperature.get_track(), rain.get_track(), clouds.get_track(), humidity.get_track(), wind.get_track()]:\n\t\t\toutfile.tracks.append(track)\n\n\t\tfile_name = 'weather_song_' + weather_forecast.city + '_' + weather_forecast.country + '_' + str(weather_forecast.weather_timestamps[0].timestamp)\n\t\tself.save_file(outfile, self.OUTPUT_FILE_DIR, file_name)\n\n\t\treturn outfile\n\n\tdef save_file(self, outfile: MidiFile, file_dir: str, file_name: str) -> MidiFile:\n\t\tPath(file_dir).mkdir(exist_ok=True)\n\t\tfile_path = file_dir + '/' + file_name + '.mid'\n\t\toutfile.save(file_path)\n\t\tprint('file saved at ' + file_path)\n\t\treturn outfile\n\n\tdef get_midi_track_time(self, midi_track: MidiTrack):\n\t\tsum = 0\n\t\tfor message in midi_track:\n\t\t\tsum += message.time\n\t\treturn sum\n\n", "step-ids": [ 1, 4, 5, 6, 7 ] }
[ 1, 4, 5, 6, 7 ]
import xadmin from xadmin import views from .models import EmailVerifyRecord, Banner class BaseMyAdminView(object): ''' enable_themes 启动更改主题 use_bootswatch 启用网上主题 ''' enable_themes = True use_bootswatch = True class GlobalSettings(object): ''' site_title 左上角名称 site_footer 底部名称 menu_style 更改左边样式 ''' site_title = "学习网后台管理系统" site_footer = "学习网" menu_style = "accordion" class EmailVerifyRecordAdmin(object): list_display = ['email', 'code', 'send_type', 'send_time'] search_fields = ['email', 'code', 'send_type'] list_filter = ['email', 'code', 'send_type', 'send_time'] class BannerAdmin(object): list_disply = ['title', 'image', 'url', 'index', 'add_time'] search_fields = ['title', 'image', 'url', 'index'] list_filter = ['title', 'image', 'url', 'index', 'add_time'] xadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin) xadmin.site.register(Banner, BannerAdmin) xadmin.site.register(views.BaseAdminView, BaseMyAdminView) xadmin.site.register(views.CommAdminView, GlobalSettings)
normal
{ "blob_id": "d7b830890400203ee45c9ec59611c0b20ab6bfc7", "index": 8496, "step-1": "<mask token>\n\n\nclass BaseMyAdminView(object):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass BaseMyAdminView(object):\n \"\"\"\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n \"\"\"\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass BaseMyAdminView(object):\n \"\"\"\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n \"\"\"\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\nxadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)\nxadmin.site.register(Banner, BannerAdmin)\nxadmin.site.register(views.BaseAdminView, BaseMyAdminView)\nxadmin.site.register(views.CommAdminView, GlobalSettings)\n", "step-4": "import xadmin\nfrom xadmin import views\nfrom .models import EmailVerifyRecord, Banner\n\n\nclass BaseMyAdminView(object):\n \"\"\"\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n \"\"\"\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n \"\"\"\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n \"\"\"\n site_title = '学习网后台管理系统'\n site_footer = '学习网'\n menu_style = 'accordion'\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\nxadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)\nxadmin.site.register(Banner, BannerAdmin)\nxadmin.site.register(views.BaseAdminView, BaseMyAdminView)\nxadmin.site.register(views.CommAdminView, GlobalSettings)\n", "step-5": "import xadmin\nfrom xadmin import views\n\nfrom .models import EmailVerifyRecord, Banner\n\n\nclass BaseMyAdminView(object):\n '''\n enable_themes 启动更改主题\n use_bootswatch 启用网上主题\n '''\n enable_themes = True\n use_bootswatch = True\n\n\nclass GlobalSettings(object):\n '''\n site_title 左上角名称\n site_footer 底部名称\n menu_style 更改左边样式\n '''\n site_title = \"学习网后台管理系统\"\n site_footer = \"学习网\"\n menu_style = \"accordion\"\n\n\nclass EmailVerifyRecordAdmin(object):\n list_display = ['email', 'code', 'send_type', 'send_time']\n search_fields = ['email', 'code', 'send_type']\n list_filter = ['email', 'code', 'send_type', 'send_time']\n\n\nclass BannerAdmin(object):\n list_disply = ['title', 'image', 'url', 'index', 'add_time']\n search_fields = ['title', 'image', 'url', 'index']\n list_filter = ['title', 'image', 'url', 'index', 'add_time']\n\n\nxadmin.site.register(EmailVerifyRecord, EmailVerifyRecordAdmin)\nxadmin.site.register(Banner, BannerAdmin)\nxadmin.site.register(views.BaseAdminView, BaseMyAdminView)\nxadmin.site.register(views.CommAdminView, GlobalSettings)", "step-ids": [ 8, 10, 11, 12, 13 ] }
[ 8, 10, 11, 12, 13 ]
# Generated by Django 3.2.6 on 2021-08-19 16:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('crm', '0040_auto_20210819_1913'), ] operations = [ migrations.RemoveField( model_name='customer', name='full_name', ), migrations.RemoveField( model_name='managercrm', name='full_name', ), ]
normal
{ "blob_id": "42f021c728a88f34d09f94ea96d91abded8a29fb", "index": 9553, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('crm', '0040_auto_20210819_1913')]\n operations = [migrations.RemoveField(model_name='customer', name=\n 'full_name'), migrations.RemoveField(model_name='managercrm', name=\n 'full_name')]\n", "step-4": "from django.db import migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [('crm', '0040_auto_20210819_1913')]\n operations = [migrations.RemoveField(model_name='customer', name=\n 'full_name'), migrations.RemoveField(model_name='managercrm', name=\n 'full_name')]\n", "step-5": "# Generated by Django 3.2.6 on 2021-08-19 16:17\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('crm', '0040_auto_20210819_1913'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='customer',\n name='full_name',\n ),\n migrations.RemoveField(\n model_name='managercrm',\n name='full_name',\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class WorkRequestForm(forms.ModelForm): <|reserved_special_token_0|> class Meta: model = HhRequest fields = 'profile', 'sphere', 'experience', 'work_request', 'resume' widgets = {'profile': forms.Select(attrs={'id': 'profile', 'required': '', 'class': 'browser-default custom-select'}), 'sphere': forms.Select(attrs={'id': 'sphere', 'required': '', 'class': 'browser-default custom-select'}), 'experience': forms .Select(attrs={'id': 'experience', 'required': '', 'class': 'browser-default custom-select'}), 'work_request': forms.Select (attrs={'id': 'work_request', 'required': '', 'class': 'browser-default custom-select'}), 'resume': forms.FileInput( attrs={'id': 'hh_resume', 'required': '', 'class': 'custom-file-input', 'lang': 'ru'})} <|reserved_special_token_1|> <|reserved_special_token_0|> class WorkRequestForm(forms.ModelForm): """Форма заявки на премию""" class Meta: model = HhRequest fields = 'profile', 'sphere', 'experience', 'work_request', 'resume' widgets = {'profile': forms.Select(attrs={'id': 'profile', 'required': '', 'class': 'browser-default custom-select'}), 'sphere': forms.Select(attrs={'id': 'sphere', 'required': '', 'class': 'browser-default custom-select'}), 'experience': forms .Select(attrs={'id': 'experience', 'required': '', 'class': 'browser-default custom-select'}), 'work_request': forms.Select (attrs={'id': 'work_request', 'required': '', 'class': 'browser-default custom-select'}), 'resume': forms.FileInput( attrs={'id': 'hh_resume', 'required': '', 'class': 'custom-file-input', 'lang': 'ru'})} <|reserved_special_token_1|> from django import forms from .models import HhRequest class WorkRequestForm(forms.ModelForm): """Форма заявки на премию""" class Meta: model = HhRequest fields = 'profile', 'sphere', 'experience', 'work_request', 'resume' widgets = {'profile': forms.Select(attrs={'id': 'profile', 'required': '', 'class': 'browser-default custom-select'}), 'sphere': forms.Select(attrs={'id': 'sphere', 'required': '', 'class': 'browser-default custom-select'}), 'experience': forms .Select(attrs={'id': 'experience', 'required': '', 'class': 'browser-default custom-select'}), 'work_request': forms.Select (attrs={'id': 'work_request', 'required': '', 'class': 'browser-default custom-select'}), 'resume': forms.FileInput( attrs={'id': 'hh_resume', 'required': '', 'class': 'custom-file-input', 'lang': 'ru'})} <|reserved_special_token_1|> from django import forms from .models import HhRequest class WorkRequestForm(forms.ModelForm): """Форма заявки на премию""" class Meta: model = HhRequest fields = ('profile', 'sphere', 'experience', 'work_request', 'resume') widgets = { 'profile': forms.Select( attrs={ 'id': 'profile', 'required': '', 'class': 'browser-default custom-select' } ), 'sphere': forms.Select( attrs={ 'id': 'sphere', 'required': '', 'class': 'browser-default custom-select' } ), 'experience': forms.Select( attrs={ 'id': 'experience', 'required': '', 'class': 'browser-default custom-select' } ), 'work_request': forms.Select( attrs={ 'id': 'work_request', 'required': '', 'class': 'browser-default custom-select' } ), 'resume': forms.FileInput( attrs={ 'id': 'hh_resume', 'required': '', 'class': 'custom-file-input', 'lang': 'ru' } ), }
flexible
{ "blob_id": "3887516e4222504defe439e62bd24b12db3cdd84", "index": 695, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass WorkRequestForm(forms.ModelForm):\n <mask token>\n\n\n class Meta:\n model = HhRequest\n fields = 'profile', 'sphere', 'experience', 'work_request', 'resume'\n widgets = {'profile': forms.Select(attrs={'id': 'profile',\n 'required': '', 'class': 'browser-default custom-select'}),\n 'sphere': forms.Select(attrs={'id': 'sphere', 'required': '',\n 'class': 'browser-default custom-select'}), 'experience': forms\n .Select(attrs={'id': 'experience', 'required': '', 'class':\n 'browser-default custom-select'}), 'work_request': forms.Select\n (attrs={'id': 'work_request', 'required': '', 'class':\n 'browser-default custom-select'}), 'resume': forms.FileInput(\n attrs={'id': 'hh_resume', 'required': '', 'class':\n 'custom-file-input', 'lang': 'ru'})}\n", "step-3": "<mask token>\n\n\nclass WorkRequestForm(forms.ModelForm):\n \"\"\"Форма заявки на премию\"\"\"\n\n\n class Meta:\n model = HhRequest\n fields = 'profile', 'sphere', 'experience', 'work_request', 'resume'\n widgets = {'profile': forms.Select(attrs={'id': 'profile',\n 'required': '', 'class': 'browser-default custom-select'}),\n 'sphere': forms.Select(attrs={'id': 'sphere', 'required': '',\n 'class': 'browser-default custom-select'}), 'experience': forms\n .Select(attrs={'id': 'experience', 'required': '', 'class':\n 'browser-default custom-select'}), 'work_request': forms.Select\n (attrs={'id': 'work_request', 'required': '', 'class':\n 'browser-default custom-select'}), 'resume': forms.FileInput(\n attrs={'id': 'hh_resume', 'required': '', 'class':\n 'custom-file-input', 'lang': 'ru'})}\n", "step-4": "from django import forms\nfrom .models import HhRequest\n\n\nclass WorkRequestForm(forms.ModelForm):\n \"\"\"Форма заявки на премию\"\"\"\n\n\n class Meta:\n model = HhRequest\n fields = 'profile', 'sphere', 'experience', 'work_request', 'resume'\n widgets = {'profile': forms.Select(attrs={'id': 'profile',\n 'required': '', 'class': 'browser-default custom-select'}),\n 'sphere': forms.Select(attrs={'id': 'sphere', 'required': '',\n 'class': 'browser-default custom-select'}), 'experience': forms\n .Select(attrs={'id': 'experience', 'required': '', 'class':\n 'browser-default custom-select'}), 'work_request': forms.Select\n (attrs={'id': 'work_request', 'required': '', 'class':\n 'browser-default custom-select'}), 'resume': forms.FileInput(\n attrs={'id': 'hh_resume', 'required': '', 'class':\n 'custom-file-input', 'lang': 'ru'})}\n", "step-5": "from django import forms\n\nfrom .models import HhRequest\n\n\nclass WorkRequestForm(forms.ModelForm):\n \"\"\"Форма заявки на премию\"\"\"\n class Meta:\n model = HhRequest\n fields = ('profile', 'sphere', 'experience', 'work_request', 'resume')\n\n widgets = {\n\n 'profile': forms.Select(\n attrs={\n 'id': 'profile',\n 'required': '',\n 'class': 'browser-default custom-select'\n }\n ),\n 'sphere': forms.Select(\n attrs={\n 'id': 'sphere',\n 'required': '',\n 'class': 'browser-default custom-select'\n }\n ),\n 'experience': forms.Select(\n attrs={\n 'id': 'experience',\n 'required': '',\n 'class': 'browser-default custom-select'\n }\n ),\n 'work_request': forms.Select(\n attrs={\n 'id': 'work_request',\n 'required': '',\n 'class': 'browser-default custom-select'\n }\n ),\n 'resume': forms.FileInput(\n attrs={\n 'id': 'hh_resume',\n 'required': '',\n 'class': 'custom-file-input',\n 'lang': 'ru'\n }\n ),\n\n }\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!env/bin/python3 from app import app from config import config as cfg app.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)
normal
{ "blob_id": "f97150f60dfb3924cda2c969141d5bfe675725ef", "index": 9150, "step-1": "<mask token>\n", "step-2": "<mask token>\napp.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)\n", "step-3": "from app import app\nfrom config import config as cfg\napp.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)\n", "step-4": "#!env/bin/python3\nfrom app import app\nfrom config import config as cfg\napp.run(debug=True, host=cfg.APP_HOST, port=cfg.APP_PORT)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<<<<<<< HEAD """Module docstring""" import os import numpy as np from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.model_selection import cross_val_score from sklearn.model_selection import KFold from sklearn.metrics import accuracy_score ======= #!/usr/bin/python """Module docstring""" import os import numpy as np from pickle_data_2 import Data from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from sklearn.svm import SVC ### classifier methods ### def linear_discriminant_analysis(data): """Linear Discriminant Analysis""" clf = LinearDiscriminantAnalysis() clf.name = "LDA" train_predict_and_results(data, clf) def nearest_neighbors_classifier(data): """K Nearest neighbors classification""" clf = KNeighborsClassifier(3, 'distance') clf.name = "KNN" train_predict_and_results(data, clf) def support_vector_machine(data): """Support Vector Machines""" clf = SVC() clf.name = "SVC" train_predict_and_results(data, clf) def gaussian_naive_bayes(data): """Naive Bayes""" clf = GaussianNB() clf.name = "GaussNB" train_predict_and_results(data, clf) def logistic_regression(data): """Logistic Regression """ clf = LogisticRegression() clf.name = "LoReg" train_predict_and_results(data, clf) def random_forest(data): """Random Forest""" clf = RandomForestClassifier() clf.name = "RNDForest" train_predict_and_results(data, clf) ### End of classifier methods ### >>>>>>> 05e11c3b88b3fb5313f29e74125ab6fdd8fffd84 def normalize(data): """Returns data with columns normalized input: numpy array output: numpy array """ # normalize data and return # https://stackoverflow.com/questions/29661574/normalize-numpy-array-columns-in-python return (data - data.min(axis=0)) / data.ptp(axis=0) <<<<<<< HEAD def load_data(): """Reads datafile and returns data as numpy array""" # https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.astype.html data = np.load("phase3-data/data_selected_1980_2010.npy").astype(float) return normalize(data) def load_target(column="label"): """Reads target labels and returns two columns: sum15 and label""" columns = {"sum15": 0, "label": 1} if column not in columns.keys(): raise ValueError("%s is not in target data" % column) filepath = os.path.join("phase3-data", "target_1980_2010.npy") target = np.load(filepath) # lets normalize, sum15 might need it target = normalize(target) # return correct column return target[:, columns[column]] def concat_data(data, target): '''Merge dataframe data with dataframe target and returns the final one ''' final_data = np.concatenate((data,target[:,None]), axis=1) return final_data ======= def load_ta_data(): """Reads datafile and returns data as numpy array""" # https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.astype.html data = np.load("data/data_selected_1980_2010.npy").astype(float) return normalize(data) def load_ta_target(): """Reads target labels and returns two columns: sum15 and label""" filepath = os.path.join("data", "target_1980_2010.npy") target = np.load(filepath) return target[:, 1] def load_own_data(): """Loads data corresponding to selected features by custom saola algorithm""" data = Data() features = data.read_selected_features() dataframe = data.get_dataframe_with(features) return normalize(dataframe.values) def load_own_target(): """Loads target column as stored in our data files""" data = Data() target = data.get_label_col() return target.values >>>>>>> 05e11c3b88b3fb5313f29e74125ab6fdd8fffd84 def split_samples(data): """Splits data into training samples and test samples input: numpy array returns tuple (training_samples, test_samples) both are numpy arrays """ training_samples = data[0:9497] test_samples = data[9497:11300] return training_samples, test_samples <<<<<<< HEAD def main(): """The main method""" feat_data = load_data() label_data = load_target() #final = concat_data(feat_data, label_data) #print final X_training, X_test = split_samples(feat_data) Y_training, Y_test = split_samples(label_data) #10- fold cross-validation #knn = KNeighborsClassifier(n_neighbors=3) lda = LinearDiscriminantAnalysis(n_components=3, priors=None, shrinkage=None, solver='svd', store_covariance=False, tol=0.0001) #folds = cross_val_score(lda, X_training, Y_training, cv=10) #print folds #kf = KFold(n_splits=10) #print (kf.get_n_splits(X)) #for training_index, test_index in kf.split(X): # print("TRAIN:", training_index, "TEST:", test_index) # X_training, X_test = X[training_index], X[test_index] # Y_training, Y_test = Y[training_index], Y[test_index] #clf = LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage=None, # solver='svd', store_covariance=False, tol=0.0001) lda.fit(X_training, Y_training) predictions = lda.predict(X_test) print predictions print accuracy_score(Y_test, predictions) ======= def prepare_data(): """Prepare data for classifier to use""" #data, label = load_ta_data(), load_ta_target() data, label = load_own_data(), load_own_target() tra_x, tst_x = split_samples(data) tra_y, tst_y = split_samples(label) return (tra_x, tst_x, tra_y, tst_y) def train_predict_and_results(data, clf): """Perform training, calculate predictions and show results""" tra_x, tst_x, tra_y, tst_y = data clf.fit(tra_x, tra_y) prd_y = clf.predict(tst_x) cnf = confusion_matrix(tst_y, prd_y) print ("Classifier: %s \tAccuracy score:%7.2f %%" "\tTN:%5d FP:%5d FN:%5d TP:%5d" % (clf.name, accuracy_score(tst_y, prd_y) * 100, cnf[0][0], cnf[0][1], cnf[1][0], cnf[1][1])) def main(): """The main method""" data = prepare_data() linear_discriminant_analysis(data) nearest_neighbors_classifier(data) support_vector_machine(data) gaussian_naive_bayes(data) logistic_regression(data) random_forest(data) >>>>>>> 05e11c3b88b3fb5313f29e74125ab6fdd8fffd84 if __name__ == "__main__": main()
normal
{ "blob_id": "2bce18354a53c49274f7dd017e1f65c9ff1327b9", "index": 2264, "step-1": "<<<<<<< HEAD\n\"\"\"Module docstring\"\"\"\nimport os\nimport numpy as np\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import accuracy_score\n\n=======\n#!/usr/bin/python\n\"\"\"Module docstring\"\"\"\nimport os\nimport numpy as np\nfrom pickle_data_2 import Data\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\n### classifier methods ###\n\ndef linear_discriminant_analysis(data):\n \"\"\"Linear Discriminant Analysis\"\"\"\n clf = LinearDiscriminantAnalysis()\n clf.name = \"LDA\"\n train_predict_and_results(data, clf)\n\ndef nearest_neighbors_classifier(data):\n \"\"\"K Nearest neighbors classification\"\"\"\n clf = KNeighborsClassifier(3, 'distance')\n clf.name = \"KNN\"\n train_predict_and_results(data, clf)\n\ndef support_vector_machine(data):\n \"\"\"Support Vector Machines\"\"\"\n clf = SVC()\n clf.name = \"SVC\"\n train_predict_and_results(data, clf)\n\ndef gaussian_naive_bayes(data):\n \"\"\"Naive Bayes\"\"\"\n clf = GaussianNB()\n clf.name = \"GaussNB\"\n train_predict_and_results(data, clf)\n\ndef logistic_regression(data):\n \"\"\"Logistic Regression \"\"\"\n clf = LogisticRegression()\n clf.name = \"LoReg\"\n train_predict_and_results(data, clf)\n\ndef random_forest(data):\n \"\"\"Random Forest\"\"\"\n clf = RandomForestClassifier()\n clf.name = \"RNDForest\"\n train_predict_and_results(data, clf)\n\n### End of classifier methods ###\n>>>>>>> 05e11c3b88b3fb5313f29e74125ab6fdd8fffd84\n\ndef normalize(data):\n \"\"\"Returns data with columns normalized\n input: numpy array\n output: numpy array\n \"\"\"\n # normalize data and return\n # https://stackoverflow.com/questions/29661574/normalize-numpy-array-columns-in-python\n return (data - data.min(axis=0)) / data.ptp(axis=0)\n\n<<<<<<< HEAD\ndef load_data():\n \"\"\"Reads datafile and returns data as numpy array\"\"\"\n\n # https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.astype.html\n data = np.load(\"phase3-data/data_selected_1980_2010.npy\").astype(float)\n\n return normalize(data)\n\ndef load_target(column=\"label\"):\n \"\"\"Reads target labels and returns two columns: sum15 and label\"\"\"\n\n columns = {\"sum15\": 0, \"label\": 1}\n if column not in columns.keys():\n raise ValueError(\"%s is not in target data\" % column)\n\n filepath = os.path.join(\"phase3-data\", \"target_1980_2010.npy\")\n target = np.load(filepath)\n\n # lets normalize, sum15 might need it\n target = normalize(target)\n\n # return correct column\n return target[:, columns[column]]\n\ndef concat_data(data, target):\n '''Merge dataframe data with dataframe target and returns the final one '''\n \n final_data = np.concatenate((data,target[:,None]), axis=1)\n \n return final_data\n=======\ndef load_ta_data():\n \"\"\"Reads datafile and returns data as numpy array\"\"\"\n # https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.ndarray.astype.html\n data = np.load(\"data/data_selected_1980_2010.npy\").astype(float)\n return normalize(data)\n\ndef load_ta_target():\n \"\"\"Reads target labels and returns two columns: sum15 and label\"\"\"\n filepath = os.path.join(\"data\", \"target_1980_2010.npy\")\n target = np.load(filepath)\n return target[:, 1]\n\ndef load_own_data():\n \"\"\"Loads data corresponding to selected features by custom saola algorithm\"\"\"\n data = Data()\n features = data.read_selected_features()\n dataframe = data.get_dataframe_with(features)\n return normalize(dataframe.values)\n\ndef load_own_target():\n \"\"\"Loads target column as stored in our data files\"\"\"\n data = Data()\n target = data.get_label_col()\n return target.values\n>>>>>>> 05e11c3b88b3fb5313f29e74125ab6fdd8fffd84\n\ndef split_samples(data):\n \"\"\"Splits data into training samples and test samples\n input: numpy array\n\n returns tuple (training_samples, test_samples)\n both are numpy arrays\n \"\"\"\n\n training_samples = data[0:9497]\n test_samples = data[9497:11300]\n\n return training_samples, test_samples\n\n<<<<<<< HEAD\ndef main():\n \"\"\"The main method\"\"\"\n\n feat_data = load_data()\n label_data = load_target()\n #final = concat_data(feat_data, label_data)\n\n #print final\n X_training, X_test = split_samples(feat_data)\n Y_training, Y_test = split_samples(label_data)\n\n #10- fold cross-validation\n #knn = KNeighborsClassifier(n_neighbors=3)\n lda = LinearDiscriminantAnalysis(n_components=3, priors=None, shrinkage=None,\n solver='svd', store_covariance=False, tol=0.0001)\n #folds = cross_val_score(lda, X_training, Y_training, cv=10)\n #print folds\n\n #kf = KFold(n_splits=10)\n #print (kf.get_n_splits(X))\n #for training_index, test_index in kf.split(X):\n # print(\"TRAIN:\", training_index, \"TEST:\", test_index)\n # X_training, X_test = X[training_index], X[test_index]\n # Y_training, Y_test = Y[training_index], Y[test_index]\n \n \n #clf = LinearDiscriminantAnalysis(n_components=None, priors=None, shrinkage=None,\n # solver='svd', store_covariance=False, tol=0.0001)\n lda.fit(X_training, Y_training)\n \n predictions = lda.predict(X_test)\n \n print predictions\n print accuracy_score(Y_test, predictions)\n=======\ndef prepare_data():\n \"\"\"Prepare data for classifier to use\"\"\"\n #data, label = load_ta_data(), load_ta_target()\n data, label = load_own_data(), load_own_target()\n tra_x, tst_x = split_samples(data)\n tra_y, tst_y = split_samples(label)\n return (tra_x, tst_x, tra_y, tst_y)\n\ndef train_predict_and_results(data, clf):\n \"\"\"Perform training, calculate predictions and show results\"\"\"\n tra_x, tst_x, tra_y, tst_y = data\n clf.fit(tra_x, tra_y)\n prd_y = clf.predict(tst_x)\n cnf = confusion_matrix(tst_y, prd_y)\n print (\"Classifier: %s \\tAccuracy score:%7.2f %%\"\n \"\\tTN:%5d FP:%5d FN:%5d TP:%5d\"\n % (clf.name, accuracy_score(tst_y, prd_y) * 100,\n cnf[0][0], cnf[0][1], cnf[1][0], cnf[1][1]))\n\ndef main():\n \"\"\"The main method\"\"\"\n data = prepare_data()\n linear_discriminant_analysis(data)\n nearest_neighbors_classifier(data)\n support_vector_machine(data)\n gaussian_naive_bayes(data)\n logistic_regression(data)\n random_forest(data)\n>>>>>>> 05e11c3b88b3fb5313f29e74125ab6fdd8fffd84\n\nif __name__ == \"__main__\":\n main()\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> class IBehaviourBase(Client): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class IBehaviourBase(Client): <|reserved_special_token_0|> def __init__(self, email, password, kwargs): """"abstract class being parent of every user implemented behaviour; it handles logging in and tasks on behaviour loader side""" self.kwargs = kwargs Client.__init__(self, email=email, password=password) self.Run() def Run(self): print('behaviour base abstract method invoked error') <|reserved_special_token_1|> <|reserved_special_token_0|> class IBehaviourBase(Client): BreakFlag = False def __init__(self, email, password, kwargs): """"abstract class being parent of every user implemented behaviour; it handles logging in and tasks on behaviour loader side""" self.kwargs = kwargs Client.__init__(self, email=email, password=password) self.Run() def Run(self): print('behaviour base abstract method invoked error') <|reserved_special_token_1|> from fbchat import Client class IBehaviourBase(Client): BreakFlag = False def __init__(self, email, password, kwargs): """"abstract class being parent of every user implemented behaviour; it handles logging in and tasks on behaviour loader side""" self.kwargs = kwargs Client.__init__(self, email=email, password=password) self.Run() def Run(self): print('behaviour base abstract method invoked error') <|reserved_special_token_1|> from fbchat import Client class IBehaviourBase(Client): BreakFlag = False def __init__(self,email,password, kwargs): """"abstract class being parent of every user implemented behaviour; it handles logging in and tasks on behaviour loader side""" self.kwargs=kwargs Client.__init__(self, email=email, password=password) self.Run() def Run(self): print("behaviour base abstract method invoked error") ## todo add exception here
flexible
{ "blob_id": "e67f27eec53901f27ba5a7ee7e2a20bbb1e8f7f9", "index": 2237, "step-1": "<mask token>\n\n\nclass IBehaviourBase(Client):\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass IBehaviourBase(Client):\n <mask token>\n\n def __init__(self, email, password, kwargs):\n \"\"\"\"abstract class being parent of every user implemented behaviour;\n it handles logging in and tasks on behaviour loader side\"\"\"\n self.kwargs = kwargs\n Client.__init__(self, email=email, password=password)\n self.Run()\n\n def Run(self):\n print('behaviour base abstract method invoked error')\n", "step-3": "<mask token>\n\n\nclass IBehaviourBase(Client):\n BreakFlag = False\n\n def __init__(self, email, password, kwargs):\n \"\"\"\"abstract class being parent of every user implemented behaviour;\n it handles logging in and tasks on behaviour loader side\"\"\"\n self.kwargs = kwargs\n Client.__init__(self, email=email, password=password)\n self.Run()\n\n def Run(self):\n print('behaviour base abstract method invoked error')\n", "step-4": "from fbchat import Client\n\n\nclass IBehaviourBase(Client):\n BreakFlag = False\n\n def __init__(self, email, password, kwargs):\n \"\"\"\"abstract class being parent of every user implemented behaviour;\n it handles logging in and tasks on behaviour loader side\"\"\"\n self.kwargs = kwargs\n Client.__init__(self, email=email, password=password)\n self.Run()\n\n def Run(self):\n print('behaviour base abstract method invoked error')\n", "step-5": "from fbchat import Client\nclass IBehaviourBase(Client):\n BreakFlag = False\n def __init__(self,email,password, kwargs):\n \"\"\"\"abstract class being parent of every user implemented behaviour;\n it handles logging in and tasks on behaviour loader side\"\"\"\n self.kwargs=kwargs\n Client.__init__(self, email=email, password=password)\n\n self.Run()\n\n def Run(self):\n print(\"behaviour base abstract method invoked error\")\n ## todo add exception here\n\n", "step-ids": [ 1, 3, 4, 5, 6 ] }
[ 1, 3, 4, 5, 6 ]
<|reserved_special_token_0|> def tokenize_de(text): return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))] def tokenize_en(text): return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def tokenize_de(text): return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))] def tokenize_en(text): return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))] <|reserved_special_token_0|> print(train.fields) print(len(train)) print(vars(train[0])) print(vars(train[100])) DE.build_vocab(train.src, min_freq=3) EN.build_vocab(train.trg, max_size=50000) <|reserved_special_token_0|> print(DE.vocab.freqs.most_common(10)) print(DE.vocab.size) print(EN.vocab.freqs.most_common(10)) print(EN.vocab.size) <|reserved_special_token_0|> print(batch.src) print(batch.trg) <|reserved_special_token_1|> <|reserved_special_token_0|> spacy_de = spacy.load('de') spacy_en = spacy.load('en') url = re.compile('(<url>.*</url>)') def tokenize_de(text): return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))] def tokenize_en(text): return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))] DE = data.Field(tokenize=tokenize_de) EN = data.Field(tokenize=tokenize_en) train, val = datasets.TranslationDataset.splits(path='~/iwslt2016/de-en/', train='train.tags.de-en', validation='IWSLT16.TED.tst2013.de-en', exts= ('.de', '.en'), fields=(DE, EN)) print(train.fields) print(len(train)) print(vars(train[0])) print(vars(train[100])) DE.build_vocab(train.src, min_freq=3) EN.build_vocab(train.trg, max_size=50000) train_iter, val_iter = data.BucketIterator.splits((train, val), batch_size= 3, device=0) print(DE.vocab.freqs.most_common(10)) print(DE.vocab.size) print(EN.vocab.freqs.most_common(10)) print(EN.vocab.size) batch = next(iter(train_iter)) print(batch.src) print(batch.trg) <|reserved_special_token_1|> from torchtext import data from torchtext import datasets import re import spacy spacy_de = spacy.load('de') spacy_en = spacy.load('en') url = re.compile('(<url>.*</url>)') def tokenize_de(text): return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))] def tokenize_en(text): return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))] DE = data.Field(tokenize=tokenize_de) EN = data.Field(tokenize=tokenize_en) train, val = datasets.TranslationDataset.splits(path='~/iwslt2016/de-en/', train='train.tags.de-en', validation='IWSLT16.TED.tst2013.de-en', exts= ('.de', '.en'), fields=(DE, EN)) print(train.fields) print(len(train)) print(vars(train[0])) print(vars(train[100])) DE.build_vocab(train.src, min_freq=3) EN.build_vocab(train.trg, max_size=50000) train_iter, val_iter = data.BucketIterator.splits((train, val), batch_size= 3, device=0) print(DE.vocab.freqs.most_common(10)) print(DE.vocab.size) print(EN.vocab.freqs.most_common(10)) print(EN.vocab.size) batch = next(iter(train_iter)) print(batch.src) print(batch.trg)
flexible
{ "blob_id": "4e715ccb4f95e7fe7e495a1181ad5df530f5a53f", "index": 5773, "step-1": "<mask token>\n\n\ndef tokenize_de(text):\n return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))]\n\n\ndef tokenize_en(text):\n return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef tokenize_de(text):\n return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))]\n\n\ndef tokenize_en(text):\n return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))]\n\n\n<mask token>\nprint(train.fields)\nprint(len(train))\nprint(vars(train[0]))\nprint(vars(train[100]))\nDE.build_vocab(train.src, min_freq=3)\nEN.build_vocab(train.trg, max_size=50000)\n<mask token>\nprint(DE.vocab.freqs.most_common(10))\nprint(DE.vocab.size)\nprint(EN.vocab.freqs.most_common(10))\nprint(EN.vocab.size)\n<mask token>\nprint(batch.src)\nprint(batch.trg)\n", "step-3": "<mask token>\nspacy_de = spacy.load('de')\nspacy_en = spacy.load('en')\nurl = re.compile('(<url>.*</url>)')\n\n\ndef tokenize_de(text):\n return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))]\n\n\ndef tokenize_en(text):\n return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))]\n\n\nDE = data.Field(tokenize=tokenize_de)\nEN = data.Field(tokenize=tokenize_en)\ntrain, val = datasets.TranslationDataset.splits(path='~/iwslt2016/de-en/',\n train='train.tags.de-en', validation='IWSLT16.TED.tst2013.de-en', exts=\n ('.de', '.en'), fields=(DE, EN))\nprint(train.fields)\nprint(len(train))\nprint(vars(train[0]))\nprint(vars(train[100]))\nDE.build_vocab(train.src, min_freq=3)\nEN.build_vocab(train.trg, max_size=50000)\ntrain_iter, val_iter = data.BucketIterator.splits((train, val), batch_size=\n 3, device=0)\nprint(DE.vocab.freqs.most_common(10))\nprint(DE.vocab.size)\nprint(EN.vocab.freqs.most_common(10))\nprint(EN.vocab.size)\nbatch = next(iter(train_iter))\nprint(batch.src)\nprint(batch.trg)\n", "step-4": "from torchtext import data\nfrom torchtext import datasets\nimport re\nimport spacy\nspacy_de = spacy.load('de')\nspacy_en = spacy.load('en')\nurl = re.compile('(<url>.*</url>)')\n\n\ndef tokenize_de(text):\n return [tok.text for tok in spacy_de.tokenizer(url.sub('@URL@', text))]\n\n\ndef tokenize_en(text):\n return [tok.text for tok in spacy_en.tokenizer(url.sub('@URL@', text))]\n\n\nDE = data.Field(tokenize=tokenize_de)\nEN = data.Field(tokenize=tokenize_en)\ntrain, val = datasets.TranslationDataset.splits(path='~/iwslt2016/de-en/',\n train='train.tags.de-en', validation='IWSLT16.TED.tst2013.de-en', exts=\n ('.de', '.en'), fields=(DE, EN))\nprint(train.fields)\nprint(len(train))\nprint(vars(train[0]))\nprint(vars(train[100]))\nDE.build_vocab(train.src, min_freq=3)\nEN.build_vocab(train.trg, max_size=50000)\ntrain_iter, val_iter = data.BucketIterator.splits((train, val), batch_size=\n 3, device=0)\nprint(DE.vocab.freqs.most_common(10))\nprint(DE.vocab.size)\nprint(EN.vocab.freqs.most_common(10))\nprint(EN.vocab.size)\nbatch = next(iter(train_iter))\nprint(batch.src)\nprint(batch.trg)\n", "step-5": null, "step-ids": [ 2, 3, 4, 5 ] }
[ 2, 3, 4, 5 ]
# settings import config # various modules import sys import time import multiprocessing import threading from queue import Queue import time import os import signal import db import time from random import randint # telepot's msg loop & Bot from telepot.loop import MessageLoop from telepot import Bot import asyncio from handle_msg import handle_msg, get_image # bot object bot = Bot(config.token) mgr = multiprocessing.Manager() shared_dict = mgr.dict() def thread(fork_process,thread_queue,shared_dict): thread = threading.currentThread() post = db.DB(config.username,config.password,config.dbname,config.host,config.port) post.connect() print('fork process - %s, thread - %s' % (fork_process,thread.getName())) while 1: msg = thread_queue.get() print('received msg from fork_process - {}, thread - {}, msg - {}'.format(fork_process,thread.getName(),msg,post)) if 'forward' in shared_dict: if shared_dict['forward'] != msg['chat']['id']: bot.sendMessage(shared_dict['forward'],'{}'.format(msg)) if 'scheduler' not in msg: handle_msg(msg,bot,shared_dict,post) else: if str(msg['chat_id']) + 'n' not in shared_dict: shared_dict[str(msg['chat_id']) + 'n'] = 0 get_image(msg['chat_id'],msg['keyword'],shared_dict,post,bot,False) def worker(parent_process,fork_queue,shared_dict): fork_process = multiprocessing.current_process() thread_queue = Queue() for i in range(config.threads_qt): t = threading.Thread(target=thread,args=(fork_process.name,thread_queue,shared_dict)) t.setDaemon(True) t.start() try: #print 'Starting:',fork_process.name,fork_process.pid while 1: data = fork_queue.get() thread_queue.put(data) except KeyboardInterrupt as e: pass def handle(msg): fork_queue.put(msg) fork_queue = multiprocessing.Queue() parent_process = os.getpid() for i in range(config.forks_qt): p = multiprocessing.Process(target=worker,args=(parent_process,fork_queue,shared_dict)) p.daemon = True p.start() @asyncio.coroutine def scheduler(): while True: yield None for i in config.pida_groups: time.sleep(int(str(3) + str(randint(100,999)))) bot.sendMessage(i,'kuku pidarugi') fork_queue.put({'scheduler':1,'chat_id':i,'keyword':'victoria secret'}) @asyncio.coroutine def telepuzik(): MessageLoop(bot,handle).run_as_thread() yield None if __name__ == "__main__": try: tasks = asyncio.gather(asyncio.async(telepuzik()),asyncio.async(scheduler())) loop = asyncio.get_event_loop() loop.run_forever() except KeyboardInterrupt as e: print("keyboard interrupted")
normal
{ "blob_id": "315fed1806999fed7cf1366ef0772318a0baa84d", "index": 8789, "step-1": "# settings\nimport config\n\n# various modules\nimport sys\nimport time\nimport multiprocessing\nimport threading\nfrom queue import Queue\nimport time\nimport os\nimport signal\nimport db\nimport time\nfrom random import randint\n\n# telepot's msg loop & Bot\nfrom telepot.loop import MessageLoop\nfrom telepot import Bot \nimport asyncio\nfrom handle_msg import handle_msg, get_image\n\n# bot object\nbot = Bot(config.token)\nmgr = multiprocessing.Manager()\nshared_dict = mgr.dict()\n\ndef thread(fork_process,thread_queue,shared_dict):\n thread = threading.currentThread()\n post = db.DB(config.username,config.password,config.dbname,config.host,config.port)\n post.connect()\n print('fork process - %s, thread - %s' % (fork_process,thread.getName()))\n while 1:\n msg = thread_queue.get()\n print('received msg from fork_process - {}, thread - {}, msg - {}'.format(fork_process,thread.getName(),msg,post))\n if 'forward' in shared_dict:\n if shared_dict['forward'] != msg['chat']['id']:\n bot.sendMessage(shared_dict['forward'],'{}'.format(msg))\n if 'scheduler' not in msg:\n handle_msg(msg,bot,shared_dict,post)\n else:\n if str(msg['chat_id']) + 'n' not in shared_dict:\n shared_dict[str(msg['chat_id']) + 'n'] = 0\n get_image(msg['chat_id'],msg['keyword'],shared_dict,post,bot,False)\n\ndef worker(parent_process,fork_queue,shared_dict):\n fork_process = multiprocessing.current_process()\n thread_queue = Queue()\n for i in range(config.threads_qt):\n t = threading.Thread(target=thread,args=(fork_process.name,thread_queue,shared_dict))\n t.setDaemon(True)\n t.start()\n try:\n #print 'Starting:',fork_process.name,fork_process.pid\n while 1:\n data = fork_queue.get()\n thread_queue.put(data)\n except KeyboardInterrupt as e:\n pass\n\ndef handle(msg):\n fork_queue.put(msg)\n\nfork_queue = multiprocessing.Queue()\nparent_process = os.getpid()\n\nfor i in range(config.forks_qt):\n p = multiprocessing.Process(target=worker,args=(parent_process,fork_queue,shared_dict))\n p.daemon = True\n p.start()\n\n@asyncio.coroutine\ndef scheduler():\n while True:\n yield None\n for i in config.pida_groups:\n time.sleep(int(str(3) + str(randint(100,999))))\n bot.sendMessage(i,'kuku pidarugi')\n fork_queue.put({'scheduler':1,'chat_id':i,'keyword':'victoria secret'})\n\n@asyncio.coroutine\ndef telepuzik():\n MessageLoop(bot,handle).run_as_thread()\n yield None\n\nif __name__ == \"__main__\":\n try:\n tasks = asyncio.gather(asyncio.async(telepuzik()),asyncio.async(scheduler()))\n loop = asyncio.get_event_loop()\n loop.run_forever()\n except KeyboardInterrupt as e:\n print(\"keyboard interrupted\")\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_instance(rest_url, params): url = BASEURL + rest_url print(url) twitter = OAuth1Session(CK, CS, AT, AS) return twitter.get(url, params=params) <|reserved_special_token_1|> <|reserved_special_token_0|> BASEURL = 'https://api.twitter.com/1.1/' CK = '3rJOl1ODzm9yZy63FACdg' CS = '5jPoQ5kQvMJFDYRNE8bQ4rHuds4xJqhvgNJM4awaE8' AT = '333312023-6dTniMxvwlQG8bATKNYWBXaQkftz9t4ZjRBt7BWk' AS = 'LQ8xXBTTN8F8CHQv9oDAqsGJFeexdnFf2DFzn3EzGH2L8' def get_instance(rest_url, params): url = BASEURL + rest_url print(url) twitter = OAuth1Session(CK, CS, AT, AS) return twitter.get(url, params=params) <|reserved_special_token_1|> from requests_oauthlib import OAuth1Session BASEURL = 'https://api.twitter.com/1.1/' CK = '3rJOl1ODzm9yZy63FACdg' CS = '5jPoQ5kQvMJFDYRNE8bQ4rHuds4xJqhvgNJM4awaE8' AT = '333312023-6dTniMxvwlQG8bATKNYWBXaQkftz9t4ZjRBt7BWk' AS = 'LQ8xXBTTN8F8CHQv9oDAqsGJFeexdnFf2DFzn3EzGH2L8' def get_instance(rest_url, params): url = BASEURL + rest_url print(url) twitter = OAuth1Session(CK, CS, AT, AS) return twitter.get(url, params=params) <|reserved_special_token_1|> #! /usr/local/bin/python3 # -*- coding: utf-8 -*- from requests_oauthlib import OAuth1Session BASEURL = 'https://api.twitter.com/1.1/' CK = '3rJOl1ODzm9yZy63FACdg' CS = '5jPoQ5kQvMJFDYRNE8bQ4rHuds4xJqhvgNJM4awaE8' AT = '333312023-6dTniMxvwlQG8bATKNYWBXaQkftz9t4ZjRBt7BWk' AS = 'LQ8xXBTTN8F8CHQv9oDAqsGJFeexdnFf2DFzn3EzGH2L8' def get_instance(rest_url, params): url = BASEURL + rest_url print(url) twitter = OAuth1Session(CK, CS, AT, AS) return twitter.get(url, params=params)
flexible
{ "blob_id": "63bfaa6e191e6090060877e737f4b003bed559cf", "index": 9140, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_instance(rest_url, params):\n url = BASEURL + rest_url\n print(url)\n twitter = OAuth1Session(CK, CS, AT, AS)\n return twitter.get(url, params=params)\n", "step-3": "<mask token>\nBASEURL = 'https://api.twitter.com/1.1/'\nCK = '3rJOl1ODzm9yZy63FACdg'\nCS = '5jPoQ5kQvMJFDYRNE8bQ4rHuds4xJqhvgNJM4awaE8'\nAT = '333312023-6dTniMxvwlQG8bATKNYWBXaQkftz9t4ZjRBt7BWk'\nAS = 'LQ8xXBTTN8F8CHQv9oDAqsGJFeexdnFf2DFzn3EzGH2L8'\n\n\ndef get_instance(rest_url, params):\n url = BASEURL + rest_url\n print(url)\n twitter = OAuth1Session(CK, CS, AT, AS)\n return twitter.get(url, params=params)\n", "step-4": "from requests_oauthlib import OAuth1Session\nBASEURL = 'https://api.twitter.com/1.1/'\nCK = '3rJOl1ODzm9yZy63FACdg'\nCS = '5jPoQ5kQvMJFDYRNE8bQ4rHuds4xJqhvgNJM4awaE8'\nAT = '333312023-6dTniMxvwlQG8bATKNYWBXaQkftz9t4ZjRBt7BWk'\nAS = 'LQ8xXBTTN8F8CHQv9oDAqsGJFeexdnFf2DFzn3EzGH2L8'\n\n\ndef get_instance(rest_url, params):\n url = BASEURL + rest_url\n print(url)\n twitter = OAuth1Session(CK, CS, AT, AS)\n return twitter.get(url, params=params)\n", "step-5": "#! /usr/local/bin/python3\n# -*- coding: utf-8 -*-\n\nfrom requests_oauthlib import OAuth1Session\n\nBASEURL = 'https://api.twitter.com/1.1/'\n\nCK = '3rJOl1ODzm9yZy63FACdg'\nCS = '5jPoQ5kQvMJFDYRNE8bQ4rHuds4xJqhvgNJM4awaE8'\nAT = '333312023-6dTniMxvwlQG8bATKNYWBXaQkftz9t4ZjRBt7BWk'\nAS = 'LQ8xXBTTN8F8CHQv9oDAqsGJFeexdnFf2DFzn3EzGH2L8'\n\n\ndef get_instance(rest_url, params):\n url = BASEURL + rest_url\n print(url)\n twitter = OAuth1Session(CK, CS, AT, AS)\n return twitter.get(url, params=params)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
K = input() mat = "".join(raw_input() for i in xrange(4)) print ("YES", "NO")[max(mat.count(str(i)) for i in xrange(1, 10)) > K*2]
normal
{ "blob_id": "879f7503f7f427f92109024b4646d1dc7f15d63d", "index": 2153, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint('YES', 'NO')[max(mat.count(str(i)) for i in xrange(1, 10)) > K * 2]\n", "step-3": "K = input()\nmat = ''.join(raw_input() for i in xrange(4))\nprint('YES', 'NO')[max(mat.count(str(i)) for i in xrange(1, 10)) > K * 2]\n", "step-4": "K = input()\nmat = \"\".join(raw_input() for i in xrange(4))\nprint (\"YES\", \"NO\")[max(mat.count(str(i)) for i in xrange(1, 10)) > K*2]\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class NameSearch(forms.Form): <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class NameSearch(forms.Form): name = forms.CharField(label='Search By Name') <|reserved_special_token_1|> from django import forms from django.core import validators class NameSearch(forms.Form): name = forms.CharField(label='Search By Name')
flexible
{ "blob_id": "7620ff333422d0354cc41c2a66444c3e8a0c011f", "index": 1606, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass NameSearch(forms.Form):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass NameSearch(forms.Form):\n name = forms.CharField(label='Search By Name')\n", "step-4": "from django import forms\nfrom django.core import validators\n\n\nclass NameSearch(forms.Form):\n name = forms.CharField(label='Search By Name')\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
import csv import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit #funktion def func(w,rc): return 1/(np.sqrt(1+w**2*rc**2)) #daten einlesen with open('data/phase.csv' ) as csvfile: reader=csv.reader(csvfile, delimiter=',') header_row=next(reader) f, U, a, b = [], [], [], [] for row in reader: f.append(row[0]) U.append(row[1]) a.append(row[2]) b.append(row[3]) f=np.array(f,dtype=float) U=np.array(U,dtype=float) a=np.array(a,dtype=float) b=np.array(b,dtype=float) #curvefit U0=0.6 popt, pcov = curve_fit(func, f*2*np.pi, U/U0) a1=popt[0] #theoriewerte R_th=11.01*10**3 C_th=93.3*10**(-9) #plots plt.xlabel(r'$f\, / \, Hz$') plt.ylabel(r'$\frac{U_c}{U_0}$', fontsize=15) plt.grid() plt.semilogx(f,U/U0,'rx',label='Messwerte') x=np.linspace(20,30000,10000) plt.semilogx(x,func(x*2*np.pi,a1),'b-',label='Ausgleichsrechnung') plt.semilogx(x,func(x*2*np.pi,R_th*C_th),'g-',label='Theoriekurve') plt.legend() plt.savefig('plotb.pdf') plt.show() #fehlerausgabe uncertainties = np.sqrt(np.diag(pcov)) print('RC =',-a1,'+-',uncertainties[0]) print('Theoriewert:',11.01*1000*93.3*10**(-9)) print('Phase:',(a/b)*np.pi*2)
normal
{ "blob_id": "170d0560c40f3f642f319f6113b68ab8a6bea9ef", "index": 468, "step-1": "<mask token>\n\n\ndef func(w, rc):\n return 1 / np.sqrt(1 + w ** 2 * rc ** 2)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef func(w, rc):\n return 1 / np.sqrt(1 + w ** 2 * rc ** 2)\n\n\nwith open('data/phase.csv') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n header_row = next(reader)\n f, U, a, b = [], [], [], []\n for row in reader:\n f.append(row[0])\n U.append(row[1])\n a.append(row[2])\n b.append(row[3])\n f = np.array(f, dtype=float)\n U = np.array(U, dtype=float)\n a = np.array(a, dtype=float)\n b = np.array(b, dtype=float)\n<mask token>\nplt.xlabel('$f\\\\, / \\\\, Hz$')\nplt.ylabel('$\\\\frac{U_c}{U_0}$', fontsize=15)\nplt.grid()\nplt.semilogx(f, U / U0, 'rx', label='Messwerte')\n<mask token>\nplt.semilogx(x, func(x * 2 * np.pi, a1), 'b-', label='Ausgleichsrechnung')\nplt.semilogx(x, func(x * 2 * np.pi, R_th * C_th), 'g-', label='Theoriekurve')\nplt.legend()\nplt.savefig('plotb.pdf')\nplt.show()\n<mask token>\nprint('RC =', -a1, '+-', uncertainties[0])\nprint('Theoriewert:', 11.01 * 1000 * 93.3 * 10 ** -9)\nprint('Phase:', a / b * np.pi * 2)\n", "step-3": "<mask token>\n\n\ndef func(w, rc):\n return 1 / np.sqrt(1 + w ** 2 * rc ** 2)\n\n\nwith open('data/phase.csv') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n header_row = next(reader)\n f, U, a, b = [], [], [], []\n for row in reader:\n f.append(row[0])\n U.append(row[1])\n a.append(row[2])\n b.append(row[3])\n f = np.array(f, dtype=float)\n U = np.array(U, dtype=float)\n a = np.array(a, dtype=float)\n b = np.array(b, dtype=float)\nU0 = 0.6\npopt, pcov = curve_fit(func, f * 2 * np.pi, U / U0)\na1 = popt[0]\nR_th = 11.01 * 10 ** 3\nC_th = 93.3 * 10 ** -9\nplt.xlabel('$f\\\\, / \\\\, Hz$')\nplt.ylabel('$\\\\frac{U_c}{U_0}$', fontsize=15)\nplt.grid()\nplt.semilogx(f, U / U0, 'rx', label='Messwerte')\nx = np.linspace(20, 30000, 10000)\nplt.semilogx(x, func(x * 2 * np.pi, a1), 'b-', label='Ausgleichsrechnung')\nplt.semilogx(x, func(x * 2 * np.pi, R_th * C_th), 'g-', label='Theoriekurve')\nplt.legend()\nplt.savefig('plotb.pdf')\nplt.show()\nuncertainties = np.sqrt(np.diag(pcov))\nprint('RC =', -a1, '+-', uncertainties[0])\nprint('Theoriewert:', 11.01 * 1000 * 93.3 * 10 ** -9)\nprint('Phase:', a / b * np.pi * 2)\n", "step-4": "import csv\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\n\ndef func(w, rc):\n return 1 / np.sqrt(1 + w ** 2 * rc ** 2)\n\n\nwith open('data/phase.csv') as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n header_row = next(reader)\n f, U, a, b = [], [], [], []\n for row in reader:\n f.append(row[0])\n U.append(row[1])\n a.append(row[2])\n b.append(row[3])\n f = np.array(f, dtype=float)\n U = np.array(U, dtype=float)\n a = np.array(a, dtype=float)\n b = np.array(b, dtype=float)\nU0 = 0.6\npopt, pcov = curve_fit(func, f * 2 * np.pi, U / U0)\na1 = popt[0]\nR_th = 11.01 * 10 ** 3\nC_th = 93.3 * 10 ** -9\nplt.xlabel('$f\\\\, / \\\\, Hz$')\nplt.ylabel('$\\\\frac{U_c}{U_0}$', fontsize=15)\nplt.grid()\nplt.semilogx(f, U / U0, 'rx', label='Messwerte')\nx = np.linspace(20, 30000, 10000)\nplt.semilogx(x, func(x * 2 * np.pi, a1), 'b-', label='Ausgleichsrechnung')\nplt.semilogx(x, func(x * 2 * np.pi, R_th * C_th), 'g-', label='Theoriekurve')\nplt.legend()\nplt.savefig('plotb.pdf')\nplt.show()\nuncertainties = np.sqrt(np.diag(pcov))\nprint('RC =', -a1, '+-', uncertainties[0])\nprint('Theoriewert:', 11.01 * 1000 * 93.3 * 10 ** -9)\nprint('Phase:', a / b * np.pi * 2)\n", "step-5": "import csv\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom scipy.optimize import curve_fit\r\n\r\n#funktion\r\ndef func(w,rc):\r\n return 1/(np.sqrt(1+w**2*rc**2))\r\n\r\n#daten einlesen\r\nwith open('data/phase.csv' ) as csvfile:\r\n reader=csv.reader(csvfile, delimiter=',')\r\n header_row=next(reader)\r\n f, U, a, b = [], [], [], []\r\n for row in reader:\r\n f.append(row[0])\r\n U.append(row[1])\r\n a.append(row[2])\r\n b.append(row[3])\r\n f=np.array(f,dtype=float)\r\n U=np.array(U,dtype=float)\r\n a=np.array(a,dtype=float)\r\n b=np.array(b,dtype=float)\r\n\r\n#curvefit\r\nU0=0.6\r\npopt, pcov = curve_fit(func, f*2*np.pi, U/U0)\r\na1=popt[0]\r\n\r\n#theoriewerte\r\nR_th=11.01*10**3\r\nC_th=93.3*10**(-9)\r\n\r\n#plots\r\nplt.xlabel(r'$f\\, / \\, Hz$')\r\nplt.ylabel(r'$\\frac{U_c}{U_0}$', fontsize=15)\r\nplt.grid()\r\nplt.semilogx(f,U/U0,'rx',label='Messwerte')\r\nx=np.linspace(20,30000,10000)\r\nplt.semilogx(x,func(x*2*np.pi,a1),'b-',label='Ausgleichsrechnung')\r\nplt.semilogx(x,func(x*2*np.pi,R_th*C_th),'g-',label='Theoriekurve')\r\nplt.legend()\r\nplt.savefig('plotb.pdf')\r\nplt.show()\r\n\r\n#fehlerausgabe\r\nuncertainties = np.sqrt(np.diag(pcov))\r\nprint('RC =',-a1,'+-',uncertainties[0])\r\nprint('Theoriewert:',11.01*1000*93.3*10**(-9))\r\nprint('Phase:',(a/b)*np.pi*2)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]