File size: 242,575 Bytes
f3dabac |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
{"index":0,"idx":0,"code":"def secrets_dir(env=os.getenv('D2_ENVIRONMENT', None),\n basedir=os.getenv('D2_SECRETS_BASEDIR', None)):\n if env is not None:\n env_str = str(env)\n else:\n cwd = os.getcwd()\n default_file = os.path.join(cwd, '.python_secrets_environment')\n if os.path.exists(default_file):\n with open(default_file, 'r') as f:\n env_str = f.read().strip()\n else:\n env_str = os.path.basename(cwd)\n if basedir is None:\n basedir = os.path.join(\n HOME,\n 'secrets' if sys.platform.startswith('win') else '.secrets')\n return os.path.join(basedir, env_str)","input":"'testing', '\/home\/XXX\/.tsecrets'","output":"'\/home\/XXX\/.tsecrets\/testing'","cyclomatic_complexity":4,"code_length":17,"category":"Medium"}
{"index":2,"idx":1,"code":"def _identify_environment(environment=None):\n \n cwd = os.getcwd()\n if environment is None:\n env_file = os.path.join(cwd, '.python_secrets_environment')\n if os.path.exists(env_file):\n with open(env_file, 'r') as f:\n environment = f.read().replace('\\n', '')\n else:\n environment = os.getenv('D2_ENVIRONMENT',\n os.path.basename(cwd))\n return environment","input":"'testing'","output":"'testing'","cyclomatic_complexity":3,"code_length":11,"category":"Easy"}
{"index":45,"idx":2,"code":"def client_factory(client_name, **kwargs):\n \n \n dir_name = os.path.dirname(os.path.abspath(__file__))\n error_msg = 'No client found for name %s' % client_name\n client_key = client_name.upper()\n\n \n try:\n client_vals = BALANCING_AUTHORITIES[client_key]\n module_name = client_vals['module']\n\n class_name = client_vals['class']\n except KeyError:\n raise ValueError(error_msg)\n\n \n try:\n fp, pathname, description = imp.find_module(module_name, [dir_name])\n except ImportError:\n raise ValueError(error_msg)\n\n \n try:\n mod = imp.load_module(module_name, fp, pathname, description)\n finally:\n \n if fp:\n fp.close()\n\n \n try:\n client_inst = getattr(mod, class_name)(**kwargs)\n except AttributeError:\n raise ValueError(error_msg)\n\n \n client_inst.NAME = client_name\n\n return client_inst","input":"'BPA', {}","output":"{options={}, NAME='BPA'}","cyclomatic_complexity":8,"code_length":25,"category":"Hard"}
{"index":54,"idx":3,"code":"def get_generation(ba_name, **kwargs):\n \n c = client_factory(ba_name)\n data = c.get_generation(**kwargs)\n \n \n if len(data) == 0:\n msg = '%s: No generation data at %s with args %s' % (ba_name, datetime.utcnow().isoformat(),\n kwargs)\n logger.warn(msg)\n \n \n return data","input":"'CAISO', {'latest': True}","output":"[]","cyclomatic_complexity":2,"code_length":8,"category":"Super Easy"}
{"index":55,"idx":4,"code":"def get_load(ba_name, **kwargs):\n \n c = client_factory(ba_name)\n data = c.get_load(**kwargs)\n \n \n if len(data) == 0:\n msg = '%s: No load data at %s with args %s' % (ba_name, datetime.utcnow().isoformat(),\n kwargs)\n logger.warn(msg)\n \n \n return data","input":"'PJM', {'latest': True}","output":"[]","cyclomatic_complexity":2,"code_length":8,"category":"Super Easy"}
{"index":56,"idx":5,"code":"def get_trade(ba_name, **kwargs):\n \n c = client_factory(ba_name)\n data = c.get_trade(**kwargs)\n \n \n if len(data) == 0:\n msg = '%s: No trade data at %s with args %s' % (ba_name, datetime.utcnow().isoformat(),\n kwargs)\n logger.warn(msg)\n \n \n return data","input":"'NYISO', {'latest': True}","output":"[{'timestamp': Timestamp('2024-04-03 22:45:00+0000', tz='UTC'), 'net_exp_MW': -1022.76, 'ba_name': 'NYISO', 'freq': '5m', 'market': 'RT5M'}]","cyclomatic_complexity":2,"code_length":8,"category":"Super Easy"}
{"index":74,"idx":6,"code":"def get_retry_after(headers):\n \n \n \n\n try:\n retry_after = headers['retry-after']\n except KeyError:\n return None\n\n if not retry_after: \n return None\n\n retry_after = retry_after.strip()\n\n \n \n\n try:\n \n seconds = int(retry_after)\n except ValueError:\n \n retry_date_tuple = email.utils.parsedate_tz(retry_after)\n if retry_date_tuple is None:\n logger.warning('Invalid Retry-After header: %s', retry_after)\n return None\n retry_date = email.utils.mktime_tz(retry_date_tuple)\n seconds = retry_date - time.time()\n\n if seconds < 0:\n seconds = 0\n\n return seconds","input":"{'retry-after': '42'}","output":"42","cyclomatic_complexity":8,"code_length":20,"category":"Hard"}
{"index":86,"idx":7,"code":"def kilometers(meters=0, miles=0, feet=0, nautical=0):\n \n ret = 0.\n if meters:\n ret += meters \/ 1000.\n if feet:\n ret += feet \/ ft(1.)\n if nautical:\n ret += nautical \/ nm(1.)\n ret += miles * 1.609344\n return ret","input":"0, 0, 0, 0","output":"0.0","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":87,"idx":8,"code":"def measure(self, a, b):\n \n \n raise NotImplementedError(\"Distance is an abstract class\")","input":"REPR FAILED, (10, 10, 10), (20, 20, 10), 6371.009","output":"1544.7597432330397","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":88,"idx":9,"code":"def feet(kilometers=0, meters=0, miles=0, nautical=0):\n \n ret = 0.\n if nautical:\n kilometers += nautical \/ nm(1.)\n if meters:\n kilometers += meters \/ 1000.\n if kilometers:\n miles += mi(kilometers=kilometers)\n ret += miles * 5280\n return ret","input":"1.0, 0, 0, 0","output":"3280.839895013123","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":89,"idx":10,"code":"def nautical(kilometers=0, meters=0, miles=0, feet=0):\n \n ret = 0.\n if feet:\n kilometers += feet \/ ft(1.)\n if miles:\n kilometers += km(miles=miles)\n if meters:\n kilometers += meters \/ 1000.\n ret += kilometers \/ 1.852\n return ret","input":"1.0, 0, 0, 0","output":"0.5399568034557235","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":97,"idx":11,"code":"def format_decimal(self, altitude=None):\n \n coordinates = [str(self.latitude), str(self.longitude)]\n\n if altitude is None:\n altitude = bool(self.altitude)\n if altitude:\n if not isinstance(altitude, str):\n altitude = 'km'\n coordinates.append(self.format_altitude(altitude))\n\n return \", \".join(coordinates)","input":"Point(41.5, 81.0, 2.5), None, 2.5, 41.5, 81.0","output":"'41.5, 81.0, 2.5km'","cyclomatic_complexity":4,"code_length":9,"category":"Medium"}
{"index":110,"idx":12,"code":"def xldate_as_tuple(xldate, datemode):\n if datemode not in (0, 1):\n raise XLDateBadDatemode(datemode)\n if xldate == 0.00:\n return (0, 0, 0, 0, 0, 0)\n if xldate < 0.00:\n raise XLDateNegative(xldate)\n xldays = int(xldate)\n frac = xldate - xldays\n seconds = int(round(frac * 86400.0))\n assert 0 <= seconds <= 86400\n if seconds == 86400:\n hour = minute = second = 0\n xldays += 1\n else:\n \n minutes, second = divmod(seconds, 60)\n \n hour, minute = divmod(minutes, 60)\n if xldays >= _XLDAYS_TOO_LARGE[datemode]:\n raise XLDateTooLarge(xldate)\n\n if xldays == 0:\n return (0, 0, 0, hour, minute, second)\n\n if xldays < 61 and datemode == 0:\n raise XLDateAmbiguous(xldate)\n\n jdn = xldays + _JDN_delta[datemode]\n yreg = (ifd(ifd(jdn * 4 + 274277, 146097) * 3, 4) + jdn + 1363) * 4 + 3\n mp = ifd(yreg % 1461, 4) * 535 + 333\n d = ifd(mp % 16384, 535) + 1\n \n mp >>= 14\n if mp >= 10:\n return (ifd(yreg, 1461) - 4715, mp - 9, d, hour, minute, second)\n else:\n return (ifd(yreg, 1461) - 4716, mp + 3, d, hour, minute, second)","input":"2741.0, 0","output":"(1907, 7, 3, 0, 0, 0)","cyclomatic_complexity":9,"code_length":32,"category":"Hard"}
{"index":111,"idx":13,"code":"def xldate_from_date_tuple(date_tuple, datemode):\n \n year, month, day = date_tuple\n\n if datemode not in (0, 1):\n raise XLDateBadDatemode(datemode)\n\n if year == 0 and month == 0 and day == 0:\n return 0.00\n\n if not (1900 <= year <= 9999):\n raise XLDateBadTuple(\"Invalid year: %r\" % ((year, month, day),))\n if not (1 <= month <= 12):\n raise XLDateBadTuple(\"Invalid month: %r\" % ((year, month, day),))\n if day < 1 \\\n or (day > _days_in_month[month] and not(day == 29 and month == 2 and _leap(year))):\n raise XLDateBadTuple(\"Invalid day: %r\" % ((year, month, day),))\n\n Yp = year + 4716\n M = month\n if M <= 2:\n Yp = Yp - 1\n Mp = M + 9\n else:\n Mp = M - 3\n jdn = ifd(1461 * Yp, 4) + ifd(979 * Mp + 16, 32) + \\\n day - 1364 - ifd(ifd(Yp + 184, 100) * 3, 4)\n xldays = jdn - _JDN_delta[datemode]\n if xldays <= 0:\n raise XLDateBadTuple(\"Invalid (year, month, day): %r\" % ((year, month, day),))\n if xldays < 61 and datemode == 0:\n raise XLDateAmbiguous(\"Before 1900-03-01: %r\" % ((year, month, day),))\n return float(xldays)","input":"(1907, 7, 3), 0","output":"2741.0","cyclomatic_complexity":9,"code_length":28,"category":"Hard"}
{"index":138,"idx":14,"code":"def cast_tuple(val, length = None):\n if isinstance(val, list):\n val = tuple(val)\n\n output = val if isinstance(val, tuple) else ((val,) * default(length, 1))\n\n if exists(length):\n assert len(output) == length\n\n return output","input":"1, 4","output":"(1, 1, 1, 1)","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":140,"idx":15,"code":"def _add_notice_to_docstring(doc, no_doc_str, notice):\n \n if not doc:\n lines = [no_doc_str]\n\n else:\n lines = _normalize_docstring(doc).splitlines()\n\n notice = [''] + notice\n\n if len(lines) > 1:\n \n if lines[1].strip():\n notice.append('')\n\n lines[1:1] = notice\n else:\n lines += notice\n\n return '\\n'.join(lines)","input":"None, 'DEPRECATED FUNCTION', ['\\n .. warning::\\n **THIS FUNCTION IS DEPRECATED:** It will be removed after after 2018-09-30.\\n *Instructions for updating:* This API is deprecated. Please use as `tl.logging.warning`.\\n ']","output":"'DEPRECATED FUNCTION\\n\\n\\n .. warning::\\n **THIS FUNCTION IS DEPRECATED:** It will be removed after after 2018-09-30.\\n *Instructions for updating:* This API is deprecated. Please use as `tl.logging.warning`.\\n '","cyclomatic_complexity":4,"code_length":13,"category":"Medium"}
{"index":164,"idx":16,"code":"def make_version_tuple(vstr=None):\n if vstr is None:\n vstr = __version__\n if vstr[0] == \"v\":\n vstr = vstr[1:]\n components = []\n for component in vstr.split(\"+\")[0].split(\".\"):\n try:\n components.append(int(component))\n except ValueError:\n break\n return tuple(components)","input":"'v0.1.1'","output":"(0, 1, 1)","cyclomatic_complexity":6,"code_length":12,"category":"Hard"}
{"index":179,"idx":17,"code":"def get_versions(default={\"version\": \"unknown\", \"full\": \"\"}, verbose=False):\n \n \n \n \n\n keywords = {\"refnames\": git_refnames, \"full\": git_full}\n ver = git_versions_from_keywords(keywords, tag_prefix, verbose)\n if ver:\n return rep_by_pep440(ver)\n\n try:\n root = os.path.abspath(__file__)\n \n \n \n for i in range(len(versionfile_source.split(os.sep))):\n root = os.path.dirname(root)\n except NameError:\n return default\n\n return rep_by_pep440(\n git_versions_from_vcs(tag_prefix, root, verbose)\n or versions_from_parentdir(parentdir_prefix, root, verbose)\n or default)","input":"{'version': 'unknown', 'full': ''}, False","output":"{'version': '0.1.2', 'full': '1ef835aee49f536a5a499db71927deac87f4152e'}","cyclomatic_complexity":5,"code_length":15,"category":"Medium"}
{"index":180,"idx":18,"code":"def git_versions_from_vcs(tag_prefix, root, verbose=False):\n \n \n \n \n\n if not os.path.exists(os.path.join(root, \".git\")):\n if verbose:\n print(\"no .git in %s\" % root)\n return {}\n\n GITS = [\"git\"]\n if sys.platform == \"win32\":\n GITS = [\"git.cmd\", \"git.exe\"]\n stdout = run_command(GITS, [\"describe\", \"--tags\", \"--dirty\", \"--always\"],\n cwd=root)\n if stdout is None:\n return {}\n if not stdout.startswith(tag_prefix):\n if verbose:\n print(\"tag '%s' doesn't start with prefix '%s'\"\n % (stdout, tag_prefix))\n return {}\n tag = stdout[len(tag_prefix):]\n stdout = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n if stdout is None:\n return {}\n full = stdout.strip()\n if tag.endswith(\"-dirty\"):\n full += \"-dirty\"\n return {\"version\": tag, \"full\": full}","input":"'v', '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/andsor+pydevs\/andsor+pydevs', False","output":"{'version': '0.1.2', 'full': '1ef835aee49f536a5a499db71927deac87f4152e'}","cyclomatic_complexity":9,"code_length":25,"category":"Hard"}
{"index":181,"idx":19,"code":"def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):\n assert isinstance(commands, list)\n p = None\n for c in commands:\n try:\n \n p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,\n stderr=(subprocess.PIPE if hide_stderr\n else None))\n break\n except EnvironmentError:\n e = sys.exc_info()[1]\n if e.errno == errno.ENOENT:\n continue\n if verbose:\n print(\"unable to run %s\" % args[0])\n print(e)\n return None\n else:\n if verbose:\n print(\"unable to find command, tried %s\" % (commands,))\n return None\n stdout = p.communicate()[0].strip()\n if sys.version >= '3':\n stdout = stdout.decode()\n if p.returncode != 0:\n if verbose:\n print(\"unable to run %s (error)\" % args[0])\n return None\n return stdout","input":"['git'], ['describe', '--tags', '--dirty', '--always'], '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/andsor+pydevs\/andsor+pydevs', False, False","output":"'v0.1.2'","cyclomatic_complexity":10,"code_length":29,"category":"Hard"}
{"index":203,"idx":20,"code":"def preprocess_python(code):\n \n\n code = code.strip()\n\n \n \n if not any(line.strip().startswith((\"!\", \"%\")) for line in code.split(\"\\n\")):\n code = add_active_line_prints(code)\n\n \n \n\n \n \n code_lines = code.split(\"\\n\")\n code_lines = [c for c in code_lines if c.strip() != \"\"]\n code = \"\\n\".join(code_lines)\n\n return code","input":"'import getpass\\nimport os\\nimport platform'","output":"\"print('##active_line1##')\\nimport getpass\\nprint('##active_line2##')\\nimport os\\nprint('##active_line3##')\\nimport platform\"","cyclomatic_complexity":2,"code_length":8,"category":"Super Easy"}
{"index":216,"idx":21,"code":"def calculate_r_wheels(tyre_dimensions):\n \n if 'diameter' in tyre_dimensions:\n if tyre_dimensions['code'] == 'pax':\n return tyre_dimensions['diameter'] \/ 2000 \n return tyre_dimensions['diameter'] * 0.0254 \n a = tyre_dimensions['aspect_ratio'] \/ 100 \n w = tyre_dimensions['nominal_section_width']\n if tyre_dimensions.get('code', 'iso') == 'iso':\n w \/= 1000 \n else:\n w *= 0.0254 \n\n dr = tyre_dimensions['rim_diameter'] * 0.0254 \n return a * w + dr \/ 2","input":"{'code': 'iso', 'carcass': 'R', 'nominal_section_width': 265.0, 'use': 'LT', 'load_range': 'D', 'rim_diameter': 15.0, 'aspect_ratio': 75.0}","output":"0.38925","cyclomatic_complexity":4,"code_length":13,"category":"Medium"}
{"index":217,"idx":22,"code":"def calculate_tyre_dimensions(tyre_code):\n \n import schema\n it = [\n ('iso', _re_tyre_code_iso),\n ('numeric', _re_tyre_code_numeric),\n ('pax', _re_tyre_code_pax)\n ]\n for c, _r in it:\n try:\n m = _r.match(tyre_code).groupdict()\n m['code'] = c\n if c == 'numeric' and 'aspect_ratio' not in m:\n b = m['nominal_section_width'].split('.')[-1][-1] == '5'\n m['aspect_ratio'] = '82' if b else '92'\n return _format_tyre_dimensions(m)\n except (AttributeError, schema.SchemaError):\n pass\n raise ValueError('Invalid tyre code: %s', tyre_code)","input":"'205-640 R 440 A 94 T (94 V, 97 H)'","output":"{'nominal_section_width': 205.0, 'diameter': 640.0, 'carcass': 'R', 'rim_diameter': 440.0, 'load_range': 'A', 'load_index': '94', 'speed_rating': 'T', 'additional_marks': '(94 V, 97 H)', 'code': 'pax'}","cyclomatic_complexity":5,"code_length":18,"category":"Medium"}
{"index":222,"idx":23,"code":"def parse_cmd_flags(cmd_flags=None):\n \n flags = sh.combine_dicts(cmd_flags or {}, base={\n 'only_summary': False,\n 'hard_validation': False,\n 'declaration_mode': False,\n 'enable_selector': False,\n 'type_approval_mode': False,\n 'encryption_keys': None,\n 'sign_key': None,\n 'output_template': sh.NONE,\n 'encryption_keys_passwords': None,\n 'output_folder': '.\/outputs',\n 'augmented_summary': False\n })\n flags['declaration_mode'] |= flags['type_approval_mode']\n flags['hard_validation'] |= flags['declaration_mode']\n if flags['declaration_mode'] and not flags['type_approval_mode'] and \\\n flags['enable_selector']:\n log.info(\n 'Since CO2MPAS is launched in declaration mode the option '\n '--enable-selector is not used.\\n'\n 'If you want to use it remove -DM from the cmd.'\n )\n flags['enable_selector'] = False\n return sh.selector(_cmd_flags, flags, output_type='list')","input":"{'type_approval_mode': True, 'encryption_keys': '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/JRCSTU+co2mpas-ta\/JRCSTU+co2mpas-ta\/tests\/files\/keys\/dice.co2mpas.keys', 'output_folder': '.\/outputs', 'sign_key': '.\/DICE_KEYS\/sign.co2mpas.key', 'only_summary': False, 'augmented_summary': False, 'hard_validation': False, 'declaration_mode': False, 'enable_selector': False, 'encryption_keys_passwords': '.\/DICE_KEYS\/secret.passwords'}","output":"[False, True, True, False, True, '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/JRCSTU+co2mpas-ta\/JRCSTU+co2mpas-ta\/tests\/files\/keys\/dice.co2mpas.keys', '.\/DICE_KEYS\/sign.co2mpas.key', none, '.\/outputs', '.\/DICE_KEYS\/secret.passwords', False]","cyclomatic_complexity":2,"code_length":25,"category":"Super Easy"}
{"index":226,"idx":24,"code":"def _co2mpas_info2df(start_time, main_flags=None):\n import socket\n import datetime\n from co2mpas import __version__\n from ..load.schema import define_flags_schema\n time_elapsed = (datetime.datetime.today() - start_time).total_seconds()\n hostname = socket.gethostname()\n info = [\n ('CO2MPAS version', __version__),\n ('Simulation started', start_time.strftime('%Y\/%m\/%d-%H:%M:%S')),\n ('Time elapsed', '%.3f sec' % time_elapsed),\n ('Hostname', hostname),\n ]\n\n if main_flags:\n main_flags = define_flags_schema(read=False).validate(main_flags)\n info.extend(sorted(main_flags.items()))\n import pandas as pd\n df = pd.DataFrame(info, columns=['Parameter', 'Value'])\n df.set_index(['Parameter'], inplace=True)\n setattr(df, 'name', 'info')\n return df","input":"datetime.datetime(2024, 4, 3, 16, 28, 9, 62286), None","output":" ValueParameter CO2MPAS version 4.1.6Simulation started 2024\/04\/03-16:28:09Time elapsed 103.530 secHostname thor","cyclomatic_complexity":2,"code_length":21,"category":"Super Easy"}
{"index":237,"idx":25,"code":"def parse_all(raw_dict: Dict[str, List[str]]) -> Mapping[str, Any]:\n \n processed_data = {}\n raw_dict.setdefault(\"CR\", [])\n for key, seq in raw_dict.items():\n processed_data.update(parse(key, seq))\n return processed_data","input":"{'AU': ['L Antuan'], 'PY': ['2008'], 'J9': ['P IEEE'], 'VL': ['69'], 'BP': ['1810'], 'DI': ['DOI 10.1109\/JPROC.2008.2004315']}","output":"{'AU': ['L Antuan'], 'authors': ['L Antuan'], 'PY': 2008, 'year_published': 2008, 'year': 2008, 'publication_year': 2008, 'J9': 'P IEEE', 'source_abbreviation': 'P IEEE', 'VL': '69', 'volume': '69', 'BP': '1810', 'beginning_page': '1810', 'DI': 'DOI 10.1109\/JPROC.2008.2004315', 'digital_object_identifier': 'DOI 10.1109\/JPROC.2008.2004315', 'DOI': 'DOI 10.1109\/JPROC.2008.2004315', 'CR': [], 'cited_references': [], 'references': [], 'citations': []}","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":251,"idx":26,"code":"def _get_builtin_metadata(dataset_name):\n if dataset_name == \"coco\":\n return _get_coco_instances_meta()\n if dataset_name == \"coco_panoptic_separated\":\n return _get_coco_panoptic_separated_meta()\n elif dataset_name == \"coco_panoptic_standard\":\n meta = {}\n \n \n \n \n \n \n thing_classes = [k[\"name\"] for k in COCO_CATEGORIES]\n thing_colors = [k[\"color\"] for k in COCO_CATEGORIES]\n stuff_classes = [k[\"name\"] for k in COCO_CATEGORIES]\n stuff_colors = [k[\"color\"] for k in COCO_CATEGORIES]\n\n meta[\"thing_classes\"] = thing_classes\n meta[\"thing_colors\"] = thing_colors\n meta[\"stuff_classes\"] = stuff_classes\n meta[\"stuff_colors\"] = stuff_colors\n\n \n \n \n \n \n \n \n \n thing_dataset_id_to_contiguous_id = {}\n stuff_dataset_id_to_contiguous_id = {}\n\n for i, cat in enumerate(COCO_CATEGORIES):\n if cat[\"isthing\"]:\n thing_dataset_id_to_contiguous_id[cat[\"id\"]] = i\n else:\n stuff_dataset_id_to_contiguous_id[cat[\"id\"]] = i\n\n meta[\"thing_dataset_id_to_contiguous_id\"] = thing_dataset_id_to_contiguous_id\n meta[\"stuff_dataset_id_to_contiguous_id\"] = stuff_dataset_id_to_contiguous_id\n\n return meta\n elif dataset_name == \"coco_person\":\n return {\n \"thing_classes\": [\"person\"],\n \"keypoint_names\": COCO_PERSON_KEYPOINT_NAMES,\n \"keypoint_flip_map\": COCO_PERSON_KEYPOINT_FLIP_MAP,\n \"keypoint_connection_rules\": KEYPOINT_CONNECTION_RULES,\n }\n elif dataset_name == \"cityscapes\":\n \n CITYSCAPES_THING_CLASSES = [\n \"person\", \"rider\", \"car\", \"truck\",\n \"bus\", \"train\", \"motorcycle\", \"bicycle\",\n ]\n CITYSCAPES_STUFF_CLASSES = [\n \"road\", \"sidewalk\", \"building\", \"wall\", \"fence\", \"pole\", \"traffic light\",\n \"traffic sign\", \"vegetation\", \"terrain\", \"sky\", \"person\", \"rider\", \"car\",\n \"truck\", \"bus\", \"train\", \"motorcycle\", \"bicycle\",\n ]\n \n return {\n \"thing_classes\": CITYSCAPES_THING_CLASSES,\n \"stuff_classes\": CITYSCAPES_STUFF_CLASSES,\n }\n raise KeyError(\"No built-in metadata for dataset {}\".format(dataset_name))","input":"'cityscapes'","output":"{'thing_classes': ['person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle'], 'stuff_classes': ['road', 'sidewalk', 'building', 'wall', 'fence', 'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle', 'bicycle']}","cyclomatic_complexity":8,"code_length":47,"category":"Hard"}
{"index":254,"idx":27,"code":"def set(self, **kwargs):\n \n for k, v in kwargs.items():\n setattr(self, k, v)\n return self","input":"Metadata(name='voc_2007_trainval'), {'thing_classes': ['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'], 'dirname': 'datasets\/VOC2007', 'year': 2007, 'split': 'trainval'}, 'voc_2007_trainval'","output":"Metadata(name='voc_2007_trainval', thing_classes=['aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor'], dirname='datasets\/VOC2007', year=2007, split='trainval')","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":270,"idx":28,"code":"def freeze_module(module: nn.Module, name=None) -> nn.Module:\n \n for param_name, parameter in module.named_parameters():\n if name is None or name in param_name:\n parameter.requires_grad = False\n\n \n for module_name, sub_module in module.named_modules():\n \n if name is None or name in module_name:\n sub_module.eval()\n\n return module","input":"BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), None","output":"BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)","cyclomatic_complexity":5,"code_length":8,"category":"Medium"}
{"index":274,"idx":29,"code":"def fmt_dtype(hdf_dt):\n \n size = hdf_dt.get_size()\n\n if isinstance(hdf_dt, h5t.TypeIntegerID):\n \n for candidate, descr in int_types_by_size().get(size, ()):\n if hdf_dt == candidate:\n return descr\n un = 'un' if hdf_dt.get_sign() == h5t.SGN_NONE else ''\n return \"{}-byte {}signed integer\".format(size, un)\n elif isinstance(hdf_dt, h5t.TypeFloatID):\n \n for candidate, descr in float_types_by_size().get(size, ()):\n if hdf_dt == candidate:\n return descr\n return \"custom {}-byte float\".format(size)\n elif isinstance(hdf_dt, h5t.TypeBitfieldID):\n return \"{}-byte bitfield\".format(size)\n elif isinstance(hdf_dt, h5t.TypeTimeID):\n return \"time\" \n elif isinstance(hdf_dt, h5t.TypeOpaqueID):\n s = \"{}-byte opaque\".format(size)\n tag = hdf_dt.get_tag()\n if tag:\n s += ' ({})'.format(tag.decode('utf-8', 'replace'))\n return s\n elif isinstance(hdf_dt, h5t.TypeStringID):\n cset = cset_names.get(hdf_dt.get_cset(), '?cset')\n if hdf_dt.is_variable_str():\n return \"{} string\".format(cset)\n else:\n return \"{}-byte {} string\".format(size, cset)\n elif isinstance(hdf_dt, h5t.TypeVlenID):\n return \"vlen array of \" + fmt_dtype(hdf_dt.get_super())\n elif isinstance(hdf_dt, h5t.TypeArrayID):\n shape = fmt_shape(hdf_dt.get_array_dims())\n return \"{} array of {}\".format(shape, fmt_dtype(hdf_dt.get_super()))\n\n elif isinstance(hdf_dt, h5t.TypeCompoundID):\n return \"({})\".format(\", \".join(\n \"{}: {}\".format(\n hdf_dt.get_member_name(i).decode('utf-8', 'replace'),\n fmt_dtype(hdf_dt.get_member_type(i))\n )\n for i in range(hdf_dt.get_nmembers())\n ))\n elif isinstance(hdf_dt, h5t.TypeEnumID):\n nmembers = hdf_dt.get_nmembers()\n if nmembers >= 5:\n return \"enum ({} options)\".format(nmembers)\n else:\n return \"enum ({})\".format(\", \".join(\n hdf_dt.get_member_name(i).decode('utf-8', 'replace')\n for i in range(nmembers)\n ))\n elif isinstance(hdf_dt, h5t.TypeReferenceID):\n return \"region ref\" if hdf_dt == h5t.STD_REF_DSETREG else \"object ref\"\n\n return \"unrecognised {}-byte datatype\".format(size)","input":"REPR FAILED","output":"'float32'","cyclomatic_complexity":19,"code_length":54,"category":"Hard"}
{"index":276,"idx":30,"code":"def dtype_description(hdf_dt):\n \n size = hdf_dt.get_size()\n\n if isinstance(hdf_dt, h5t.TypeIntegerID):\n \n for candidate, descr in int_types_by_size().get(size, ()):\n if hdf_dt == candidate:\n un = 'un' if hdf_dt.get_sign() == h5t.SGN_NONE else ''\n return '{}-bit {}signed integer'.format(size * 8, un)\n\n elif isinstance(hdf_dt, h5t.TypeFloatID):\n \n for candidate, descr in float_types_by_size().get(size, ()):\n if hdf_dt == candidate:\n return '{}-bit floating point'.format(size * 8)\n\n return None","input":"REPR FAILED","output":"'32-bit floating point'","cyclomatic_complexity":7,"code_length":12,"category":"Hard"}
{"index":299,"idx":31,"code":"def wrap_text(text, width):\n \n out = []\n for paragraph in text.splitlines():\n \n \n \n lines = wrap(paragraph, width=width) or ['']\n out.extend(lines)\n return out","input":"'four score\\nand seven\\n\\n', 6","output":"['four', 'score', 'and', 'seven', '']","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":303,"idx":32,"code":"def normalize_url(url):\n \n if url.endswith('.json'):\n url = url[:-5]\n if url.endswith('\/'):\n url = url[:-1]\n return url","input":"'https:\/\/www.reddit.com\/r\/CollegeBasketball\/comments\/31owr1.json'","output":"'https:\/\/www.reddit.com\/r\/CollegeBasketball\/comments\/31owr1'","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":328,"idx":33,"code":"def _prepare_references_in_schema(schema: Dict[str, Any]) -> Dict[str, Any]:\n \n \n \n schema = copy.deepcopy(schema)\n\n def _prepare_refs(d: Dict[str, Any]) -> Dict[str, Any]:\n \n for key, value in d.items():\n if key == \"$ref\":\n d[key] = _VEGA_LITE_ROOT_URI + d[key]\n else:\n \n \n \n \n if isinstance(value, dict):\n d[key] = _prepare_refs(value)\n elif isinstance(value, list):\n prepared_values = []\n for v in value:\n if isinstance(v, dict):\n v = _prepare_refs(v)\n prepared_values.append(v)\n d[key] = prepared_values\n return d\n\n schema = _prepare_refs(schema)\n return schema","input":"{'$ref': '#\/definitions\/ExprRef'}","output":"{'$ref': 'urn:vega-lite-schema#\/definitions\/ExprRef'}","cyclomatic_complexity":8,"code_length":19,"category":"Hard"}
{"index":329,"idx":34,"code":"def _group_errors_by_validator(errors: ValidationErrorList) -> GroupedValidationErrors:\n \n errors_by_validator: DefaultDict[\n str, ValidationErrorList\n ] = collections.defaultdict(list)\n for err in errors:\n \n \n \n errors_by_validator[err.validator].append(err) \n return dict(errors_by_validator)","input":"[<ValidationError: \"4 is not of type 'string'\">]","output":"{'type': [<ValidationError: \"4 is not of type 'string'\">]}","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":331,"idx":35,"code":"def eval_block(code, namespace=None, filename=\"<string>\"):\n \n tree = ast.parse(code, filename=\"<ast>\", mode=\"exec\")\n if namespace is None:\n namespace = {}\n catch_display = _CatchDisplay()\n\n if isinstance(tree.body[-1], ast.Expr):\n to_exec, to_eval = tree.body[:-1], tree.body[-1:]\n else:\n to_exec, to_eval = tree.body, []\n\n for node in to_exec:\n compiled = compile(ast.Module([node], []), filename=filename, mode=\"exec\")\n exec(compiled, namespace)\n\n with catch_display:\n for node in to_eval:\n compiled = compile(\n ast.Interactive([node]), filename=filename, mode=\"single\"\n )\n exec(compiled, namespace)\n\n return catch_display.output","input":"b'\"\"\"\\nHorizontal Bar Chart\\n--------------------\\nThis example is a bar chart drawn horizontally by putting the quantitative value on the x axis.\\n\"\"\"\\n# category: bar charts\\nimport altair as alt\\nfrom vega_datasets import data\\n\\nsource = data.wheat()\\n\\nalt.Chart(source).mark_bar().encode(\\n x=\\'wheat:Q\\',\\n y=\"year:O\"\\n).properties(height=700)\\n', None, '<string>'","output":"alt.Chart(...)","cyclomatic_complexity":5,"code_length":19,"category":"Medium"}
{"index":339,"idx":36,"code":"def infer_encoding_types(args: Sequence, kwargs: MutableMapping, channels: ModuleType):\n \n \n \n channel_objs = (getattr(channels, name) for name in dir(channels))\n channel_objs = (\n c for c in channel_objs if isinstance(c, type) and issubclass(c, SchemaBase)\n )\n channel_to_name: Dict[Type[SchemaBase], str] = {\n c: c._encoding_name for c in channel_objs\n }\n name_to_channel: Dict[str, Dict[str, Type[SchemaBase]]] = {}\n for chan, name in channel_to_name.items():\n chans = name_to_channel.setdefault(name, {})\n if chan.__name__.endswith(\"Datum\"):\n key = \"datum\"\n elif chan.__name__.endswith(\"Value\"):\n key = \"value\"\n else:\n key = \"field\"\n chans[key] = chan\n\n \n for arg in args:\n if isinstance(arg, (list, tuple)) and len(arg) > 0:\n type_ = type(arg[0])\n else:\n type_ = type(arg)\n\n encoding = channel_to_name.get(type_, None)\n if encoding is None:\n raise NotImplementedError(\"positional of type {}\" \"\".format(type_))\n if encoding in kwargs:\n raise ValueError(\"encoding {} specified twice.\".format(encoding))\n kwargs[encoding] = arg\n\n def _wrap_in_channel_class(obj, encoding):\n if isinstance(obj, SchemaBase):\n return obj\n\n if isinstance(obj, str):\n obj = {\"shorthand\": obj}\n\n if isinstance(obj, (list, tuple)):\n return [_wrap_in_channel_class(subobj, encoding) for subobj in obj]\n\n if encoding not in name_to_channel:\n warnings.warn(\n \"Unrecognized encoding channel '{}'\".format(encoding), stacklevel=1\n )\n return obj\n\n classes = name_to_channel[encoding]\n cls = classes[\"value\"] if \"value\" in obj else classes[\"field\"]\n\n try:\n \n \n return cls.from_dict(obj, validate=False)\n except jsonschema.ValidationError:\n \n return obj\n\n return {\n encoding: _wrap_in_channel_class(obj, encoding)\n for encoding, obj in kwargs.items()\n }","input":"(), {'latitude': 'latitude:Q', 'longitude': 'longitude:Q', 'latitude2': 'lat2:Q', 'longitude2': 'lon2:Q'}, <module 'altair.vegalite.v5.schema.channels' from '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/altair-viz+altair\/altair-viz+altair\/altair\/vegalite\/v5\/schema\/channels.py'>","output":"{'latitude': Latitude({ shorthand: 'latitude:Q'}), 'longitude': Longitude({ shorthand: 'longitude:Q'}), 'latitude2': Latitude2({ shorthand: 'lat2:Q'}), 'longitude2': Longitude2({ shorthand: 'lon2:Q'})}","cyclomatic_complexity":15,"code_length":51,"category":"Hard"}
{"index":342,"idx":37,"code":"def _get(self, attr, default=Undefined):\n \n attr = self._kwds.get(attr, Undefined)\n if attr is Undefined:\n attr = default\n return attr","input":"alt.LayerChart(...), 'layer', Undefined, (), {'layer': [alt.Chart(...), alt.Chart(...)], 'autosize': Undefined, 'background': Undefined, 'config': Undefined, 'data': Undefined, 'datasets': Undefined, 'description': Undefined, 'encoding': Undefined, 'height': 500, 'name': Undefined, 'padding': Undefined, 'params': Undefined, 'projection': Undefined, 'resolve': Undefined, 'title': Undefined, 'transform': Undefined, 'usermeta': Undefined, 'view': Undefined, 'width': 750}","output":"[alt.Chart(...), alt.Chart(...)]","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":344,"idx":38,"code":"def _consolidate_data(data, context):\n \n values = Undefined\n kwds = {}\n\n if isinstance(data, core.InlineData):\n if data.name is Undefined and data.values is not Undefined:\n if isinstance(data.values, core.InlineDataset):\n values = data.to_dict()[\"values\"]\n else:\n values = data.values\n kwds = {\"format\": data.format}\n\n elif isinstance(data, dict):\n if \"name\" not in data and \"values\" in data:\n values = data[\"values\"]\n kwds = {k: v for k, v in data.items() if k != \"values\"}\n\n if values is not Undefined:\n name = _dataset_name(values)\n data = core.NamedData(name=name, **kwds)\n context.setdefault(\"datasets\", {})[name] = values\n\n return data","input":"UrlData({ url: 'https:\/\/cdn.jsdelivr.net\/npm\/vega-datasets@v1.29.0\/data\/airports.csv'}), {}","output":"UrlData({ url: 'https:\/\/cdn.jsdelivr.net\/npm\/vega-datasets@v1.29.0\/data\/airports.csv'})","cyclomatic_complexity":7,"code_length":19,"category":"Hard"}
{"index":346,"idx":39,"code":"def _remove_layer_props(chart, subcharts, layer_props):\n def remove_prop(subchart, prop):\n \n try:\n if subchart[prop] is not Undefined:\n subchart = subchart.copy()\n subchart[prop] = Undefined\n except KeyError:\n pass\n return subchart\n\n output_dict = {}\n\n if not subcharts:\n \n return output_dict, subcharts\n\n for prop in layer_props:\n if chart[prop] is Undefined:\n \n \n values = []\n for c in subcharts:\n \n try:\n val = c[prop]\n if val is not Undefined:\n values.append(val)\n except KeyError:\n pass\n if len(values) == 0:\n pass\n elif all(v == values[0] for v in values[1:]):\n output_dict[prop] = values[0]\n else:\n raise ValueError(f\"There are inconsistent values {values} for {prop}\")\n else:\n \n \n if all(\n getattr(c, prop, Undefined) is Undefined or c[prop] == chart[prop]\n for c in subcharts\n ):\n output_dict[prop] = chart[prop]\n else:\n raise ValueError(f\"There are inconsistent values {values} for {prop}\")\n subcharts = [remove_prop(c, prop) for c in subcharts]\n\n return output_dict, subcharts","input":"alt.LayerChart(...), [alt.Chart(...), alt.Chart(...)], ('height', 'width', 'view')","output":"({'height': 500, 'width': 750}, [alt.Chart(...), alt.Chart(...)])","cyclomatic_complexity":15,"code_length":38,"category":"Hard"}
{"index":347,"idx":40,"code":"def to_values(data: DataType) -> ToValuesReturnType:\n \n check_data_type(data)\n if hasattr(data, \"__geo_interface__\"):\n if isinstance(data, pd.DataFrame):\n data = sanitize_dataframe(data)\n \n \n data_sanitized = sanitize_geo_interface(data.__geo_interface__) \n return {\"values\": data_sanitized}\n elif isinstance(data, pd.DataFrame):\n data = sanitize_dataframe(data)\n return {\"values\": data.to_dict(orient=\"records\")}\n elif isinstance(data, dict):\n if \"values\" not in data:\n raise KeyError(\"values expected in data dict, but not present.\")\n return data\n elif hasattr(data, \"__dataframe__\"):\n \n pi = import_pyarrow_interchange()\n pa_table = sanitize_arrow_table(pi.from_dataframe(data))\n return {\"values\": pa_table.to_pylist()}\n else:\n \n raise ValueError(\"Unrecognized data type: {}\".format(type(data)))","input":" threshold0 90","output":"{'values': [{'threshold': 90}]}","cyclomatic_complexity":7,"code_length":20,"category":"Hard"}
{"index":348,"idx":41,"code":"def sanitize_dataframe(df: pd.DataFrame) -> pd.DataFrame: \n \n df = df.copy()\n\n if isinstance(df.columns, pd.RangeIndex):\n df.columns = df.columns.astype(str)\n\n for col_name in df.columns:\n if not isinstance(col_name, str):\n raise ValueError(\n \"Dataframe contains invalid column name: {0!r}. \"\n \"Column names must be strings\".format(col_name)\n )\n\n if isinstance(df.index, pd.MultiIndex):\n raise ValueError(\"Hierarchical indices not supported\")\n if isinstance(df.columns, pd.MultiIndex):\n raise ValueError(\"Hierarchical indices not supported\")\n\n def to_list_if_array(val):\n if isinstance(val, np.ndarray):\n return val.tolist()\n else:\n return val\n\n for dtype_item in df.dtypes.items():\n \n \n \n col_name = cast(str, dtype_item[0])\n dtype = dtype_item[1]\n dtype_name = str(dtype)\n if dtype_name == \"category\":\n \n \n \n col = df[col_name].astype(object)\n df[col_name] = col.where(col.notnull(), None)\n elif dtype_name == \"string\":\n \n \n col = df[col_name].astype(object)\n df[col_name] = col.where(col.notnull(), None)\n elif dtype_name == \"bool\":\n \n df[col_name] = df[col_name].astype(object)\n elif dtype_name == \"boolean\":\n \n \n col = df[col_name].astype(object)\n df[col_name] = col.where(col.notnull(), None)\n elif dtype_name.startswith(\"datetime\") or dtype_name.startswith(\"timestamp\"):\n \n \n \n \n \n \n df[col_name] = (\n df[col_name].apply(lambda x: x.isoformat()).replace(\"NaT\", \"\")\n )\n elif dtype_name.startswith(\"timedelta\"):\n raise ValueError(\n 'Field \"{col_name}\" has type \"{dtype}\" which is '\n \"not supported by Altair. Please convert to \"\n \"either a timestamp or a numerical value.\"\n \"\".format(col_name=col_name, dtype=dtype)\n )\n elif dtype_name.startswith(\"geometry\"):\n \n \n continue\n elif (\n dtype_name\n in {\n \"Int8\",\n \"Int16\",\n \"Int32\",\n \"Int64\",\n \"UInt8\",\n \"UInt16\",\n \"UInt32\",\n \"UInt64\",\n \"Float32\",\n \"Float64\",\n }\n ): \n \n col = df[col_name].astype(object)\n df[col_name] = col.where(col.notnull(), None)\n elif numpy_is_subtype(dtype, np.integer):\n \n df[col_name] = df[col_name].astype(object)\n elif numpy_is_subtype(dtype, np.floating):\n \n \n col = df[col_name]\n bad_values = col.isnull() | np.isinf(col)\n df[col_name] = col.astype(object).where(~bad_values, None)\n elif dtype == object:\n \n \n col = df[col_name].astype(object).apply(to_list_if_array)\n df[col_name] = col.where(col.notnull(), None)\n return df","input":" symbol date price0 MSFT 2000-01-01 39.811 MSFT 2000-02-01 36.352 MSFT 2000-03-01 43.223 MSFT 2000-04-01 28.374 MSFT 2000-05-01 25.45.. ... ... ...555 AAPL 2009-11-01 199.91556 AAPL 2009-12-01 210.73557 AAPL 2010-01-01 192.06558 AAPL 2010-02-01 204.62559 AAPL 2010-03-01 223.02[560 rows x 3 columns]","output":" symbol date price0 MSFT 2000-01-01T00:00:00 39.811 MSFT 2000-02-01T00:00:00 36.352 MSFT 2000-03-01T00:00:00 43.223 MSFT 2000-04-01T00:00:00 28.374 MSFT 2000-05-01T00:00:00 25.45.. ... ... ...555 AAPL 2009-11-01T00:00:00 199.91556 AAPL 2009-12-01T00:00:00 210.73557 AAPL 2010-01-01T00:00:00 192.06558 AAPL 2010-02-01T00:00:00 204.62559 AAPL 2010-03-01T00:00:00 223.02[560 rows x 3 columns]","cyclomatic_complexity":20,"code_length":74,"category":"Hard"}
{"index":357,"idx":42,"code":"def lineAfterContext(line, prefix):\n if line.startswith(prefix):\n line = line[len(prefix):]\n\n toks = line.split(' in ', 1)\n if len(toks) == 2:\n rest = toks[1].split(' ')\n line = ' '.join(rest[1:])\n\n return line","input":"'ic| eins: zwei', 'ic| '","output":"'eins: zwei'","cyclomatic_complexity":3,"code_length":8,"category":"Easy"}
{"index":358,"idx":43,"code":"def argumentToString(obj):\n s = DEFAULT_ARG_TO_STRING_FUNCTION(obj)\n s = s.replace('\\\\n', '\\n') \n return s","input":"1","output":"'1'","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":359,"idx":44,"code":"def lineIsContextAndTime(line):\n line = stripPrefix(line) \n context, time = line.split(' at ')\n\n return (\n lineIsContext(context) and\n len(time.split(':')) == 3 and\n len(time.split('.')) == 2)","input":"'ic| test_icecream.py:229 in testAsArgument() at 01:15:24.779'","output":"True","cyclomatic_complexity":1,"code_length":7,"category":"Super Easy"}
{"index":360,"idx":45,"code":"def stripPrefix(line):\n if line.startswith(ic.prefix):\n line = line.strip()[len(ic.prefix):]\n return line","input":"'ic| test_icecream.py:229 in testAsArgument() at 01:15:24.779'","output":"'test_icecream.py:229 in testAsArgument() at 01:15:24.779'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":361,"idx":46,"code":"def lineIsContext(line):\n line = stripPrefix(line) \n sourceLocation, function = line.split(' in ') \n filename, lineNumber = sourceLocation.split(':') \n name, ext = splitext(filename)\n\n return (\n int(lineNumber) > 0 and\n ext in ['.py', '.pyc', '.pyo'] and\n name == splitext(MY_FILENAME)[0] and\n (function == '<module>' or function.endswith('()')))","input":"'test_icecream.py:229 in testAsArgument()'","output":"True","cyclomatic_complexity":1,"code_length":10,"category":"Super Easy"}
{"index":362,"idx":47,"code":"def format_pair(prefix, arg, value):\n if arg is _arg_source_missing:\n arg_lines = []\n value_prefix = prefix\n else:\n arg_lines = indented_lines(prefix, arg)\n value_prefix = arg_lines[-1] + ': '\n\n looksLikeAString = value[0] + value[-1] in [\"''\", '\"\"']\n if looksLikeAString: \n value = prefixLinesAfterFirst(' ', value)\n\n value_lines = indented_lines(value_prefix, value)\n lines = arg_lines[:-1] + value_lines\n return '\\n'.join(lines)","input":"' ', 'multilineStr', \"'line1\\nline2'\"","output":"\" multilineStr: 'line1\\n line2'\"","cyclomatic_complexity":3,"code_length":13,"category":"Easy"}
{"index":363,"idx":48,"code":"def prefixLinesAfterFirst(prefix, s):\n lines = s.splitlines(True)\n\n for i in range(1, len(lines)):\n lines[i] = prefix + lines[i]\n\n return ''.join(lines)","input":"' ', \"'line1\\nline2'\"","output":"\"'line1\\n line2'\"","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":380,"idx":49,"code":"def strip_blank_lines(l):\n \"Remove leading and trailing blank lines from a list of lines\"\n while l and not l[0].strip():\n del l[0]\n while l and not l[-1].strip():\n del l[-1]\n return l","input":"['Aggregate statistic to compute in each bin.', '', '- `count`: show the number of observations in each bin', '- `frequency`: show the number of observations divided by the bin width', '- `probability` or `proportion`: normalize such that bar heights sum to 1', '- `percent`: normalize such that bar heights sum to 100', '- `density`: normalize such that the total area of the histogram equals 1', '']","output":"['Aggregate statistic to compute in each bin.', '', '- `count`: show the number of observations in each bin', '- `frequency`: show the number of observations divided by the bin width', '- `probability` or `proportion`: normalize such that bar heights sum to 1', '- `percent`: normalize such that bar heights sum to 100', '- `density`: normalize such that the total area of the histogram equals 1']","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":400,"idx":50,"code":"def _is_scope_subset(needle_scope, haystack_scope):\n needle_scope = set(needle_scope.split()) if needle_scope else set()\n haystack_scope = (\n set(haystack_scope.split()) if haystack_scope else set()\n )\n return needle_scope <= haystack_scope","input":"'playlist-modify-private', 'playlist-modify-public'","output":"False","cyclomatic_complexity":1,"code_length":6,"category":"Super Easy"}
{"index":409,"idx":51,"code":"def hmac_digest(secret, message, encoding=\"utf-8\"):\n \n if isinstance(secret, str):\n secret = secret.encode(encoding)\n return hmac.new(secret, message.encode(encoding), hashlib.sha256).hexdigest()","input":"'secret_hmac_for_userids', 'mat:secret', 'utf-8'","output":"'a93d8634eee921a11354f428a42e47b74ac2f249bc852896ea267c70d593ef9c'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":413,"idx":52,"code":"def find_csv_separators(csv):\n \n lines = csv.strip().split('\\n')\n \n column_separator_candidates = {',', ';', '\\t', '|'}\n for line in lines:\n if not numeric_start.match(line): \n continue\n remove_candidates = []\n for column_separator in column_separator_candidates:\n if column_separator not in line:\n \n remove_candidates.append(column_separator)\n for remove_candidate in remove_candidates:\n column_separator_candidates.remove(remove_candidate)\n\n if len(column_separator_candidates) == 0:\n raise CsvParseError('Could not find column and decimal separators')\n\n if column_separator_candidates == {','}:\n \n return [',', '.']\n\n if ',' in column_separator_candidates:\n \n decimal_separator = ','\n column_separator_candidates.remove(',')\n else:\n decimal_separator = '.'\n\n if len(column_separator_candidates) > 1:\n raise CsvParseError(f'Found multiple potential column separators: {column_separator_candidates}')\n\n return list(column_separator_candidates)[0], decimal_separator","input":"'frequency,raw\\n20,0\\n1000,3\\n20000,0\\n'","output":"[',', '.']","cyclomatic_complexity":10,"code_length":24,"category":"Hard"}
{"index":414,"idx":53,"code":"def parse_csv(csv):\n lines = csv.strip().split('\\n')\n lines = [line for line in lines if line.strip()]\n csv = '\\n'.join(lines)\n if autoeq_pattern.match(csv): \n columns = lines[0].split(',')\n return {column: [float(line.split(',')[i]) for line in lines[1:]] for i, column in enumerate(columns)}\n\n if rew_pattern.match(csv) or crinacle_pattern.match(csv):\n \n csv = '\\n'.join([re.sub(r'(?:, ?| |\\t)', '\\t', line) for line in lines if numeric_start.match(line) and '?' not in line])\n lines = csv.split('\\n')\n\n column_separator, decimal_separator = find_csv_separators(csv)\n columns = find_csv_columns(csv, column_separator)\n\n \n if columns is None:\n \n ixs = {'frequency': 0, 'raw': 1}\n else:\n ixs = {'frequency': None, 'raw': None}\n for i, column in enumerate(columns):\n if re.match(r'^freq', column, flags=re.IGNORECASE):\n ixs['frequency'] = i\n if re.match(r'^(?:spl|gain|ampl|raw)', column, flags=re.IGNORECASE):\n ixs['raw'] = i\n if ixs['frequency'] is None:\n if len(columns) == 2: \n ixs = {'frequency': 0, 'raw': 1}\n else:\n raise CsvParseError('Failed to find frequency column')\n if ixs['raw'] is None:\n raise CsvParseError('Failed to find SPL column')\n\n \n data_line_pattern = re.compile(rf'^-?\\d+(?:{column_separator}\\d+)?')\n data = {'frequency': [], 'raw': []}\n for line in lines:\n if not data_line_pattern.match(line):\n continue\n cells = line.split(column_separator)\n if decimal_separator == ',':\n cells = [float(cell.replace(',', '.')) for cell in cells]\n else:\n cells = [float(cell) for cell in cells]\n for column, ix in ixs.items():\n data[column].append(cells[ix])\n return data","input":"'frequency,raw\\n20,0\\n1000,3\\n20000,0\\n'","output":"{'frequency': [20.0, 1000.0, 20000.0], 'raw': [0.0, 3.0, 0.0]}","cyclomatic_complexity":14,"code_length":41,"category":"Hard"}
{"index":415,"idx":54,"code":"def find_csv_columns(csv, column_separator):\n lines = csv.strip().split('\\n')\n numeric_lines = [line for line in lines if column_separator in line and numeric_start.search(line)]\n n_columns = list(set([len(line.split(column_separator)) for line in numeric_lines]))\n if len(n_columns) != 1:\n raise CsvParseError('Numeric lines have different number of columns')\n n_columns = n_columns[0]\n for line in lines:\n if not numeric_start.search(line) and len(line.split(column_separator)) == n_columns:\n return [cell.strip() for cell in line.split(column_separator)]","input":"'freq\\tspl\\n20.0\\t0.0\\n1000.0\\t3.0\\n20000.0\\t0.0', '\\t'","output":"['freq', 'spl']","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":418,"idx":55,"code":"def is_sorted(a):\n if len(a) <= 1:\n return True\n for i in range(1, len(a)):\n if less(a[i], a[i - 1]):\n return False\n return True","input":"[1, 2, 13, 22, 123]","output":"True","cyclomatic_complexity":4,"code_length":7,"category":"Medium"}
{"index":423,"idx":56,"code":"def partition(a, lo, hi):\n i = lo\n j = hi\n\n while True:\n while not util.less(a[lo], a[i]):\n i += 1\n if i >= hi:\n break\n\n while util.less(a[lo], a[j]):\n j -= 1\n if j <= lo:\n break\n\n if i >= j:\n break\n\n util.exchange(a, i, j)\n\n util.exchange(a, lo, j)\n return j","input":"[4, 2, 1, 23, 4, 5, 6, 7, 8, 9, 20, 11, 13, 34, 66], 0, 14","output":"3","cyclomatic_complexity":7,"code_length":17,"category":"Hard"}
{"index":443,"idx":57,"code":"def can_file_be_synced_on_current_platform(path):\n \n can_be_synced = True\n\n \n fullpath = os.path.join(os.environ[\"HOME\"], path)\n\n \n \n \n library_path = os.path.join(os.environ[\"HOME\"], \"Library\/\")\n\n if platform.system() == constants.PLATFORM_LINUX:\n if fullpath.startswith(library_path):\n can_be_synced = False\n\n return can_be_synced","input":"'some\/file'","output":"True","cyclomatic_complexity":3,"code_length":8,"category":"Easy"}
{"index":445,"idx":58,"code":"def is_process_running(process_name):\n \n is_running = False\n\n \n if os.path.isfile(\"\/usr\/bin\/pgrep\"):\n dev_null = open(os.devnull, \"wb\")\n returncode = subprocess.call([\"\/usr\/bin\/pgrep\", process_name], stdout=dev_null)\n is_running = bool(returncode == 0)\n\n return is_running","input":"'a*'","output":"True","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":489,"idx":59,"code":"def version_compare(self, other):\n \"Compares version of the form [epoch:]upstream-version[-debian-revision]\" \\\n + \" according to Debian package version number format.\"\n\n \n diff = self.epoch - other.epoch\n if diff != 0:\n return diff\n\n \n for slf, othr in (self.upstream_version, other.upstream_version), (self.revision, other.revision):\n i = 0\n while len(slf) > 0 or len(othr) > 0:\n decimal = (i % 2 == 1) \n slf_part, slf = self._get_part(slf, decimal=decimal)\n othr_part, othr = self._get_part(othr, decimal=decimal)\n diff = self._compare_parts(slf_part, othr_part, decimal=decimal)\n if diff != 0:\n return diff\n i += 1\n\n \n return 0","input":"2.2.0~rc5, 2.2.0~rc5, 0, '0', ('.', '+', '~'), '2.2.0~rc5', ('.', '+', '~', '-', ':'), '2.2.0~rc5'","output":"0","cyclomatic_complexity":5,"code_length":17,"category":"Medium"}
{"index":490,"idx":60,"code":"def _get_part(self, s, decimal):\n \"Strips first part of string containing either non-decimal or decimal characters.\" \\\n + \" Returns tuple (part, remider).\"\n div = 0\n for c in s:\n if decimal and not c.isdecimal():\n break\n elif not decimal and c.isdecimal():\n break\n else:\n div += 1\n\n return (s[:div], s[div:])","input":"2.2.0~rc5, '2.2.0~rc5', False, 0, '0', ('.', '+', '~'), '2.2.0~rc5', ('.', '+', '~', '-', ':'), '2.2.0~rc5'","output":"('', '2.2.0~rc5')","cyclomatic_complexity":4,"code_length":12,"category":"Medium"}
{"index":491,"idx":61,"code":"def _compare_parts(self, a, b, decimal):\n if decimal:\n if a == \"\": a = \"0\"\n if b == \"\": b = \"0\"\n return int(a) - int(b)\n else:\n i = 0\n while i < (min(len(a), len(b)) + 1):\n res = self._order(self._get_empty_str_on_index_error(a, i)) \\\n - self._order(self._get_empty_str_on_index_error(b, i))\n if res != 0:\n return res\n i += 1\n else:\n return 0","input":"2.2.0~rc5, '', '', False, 0, '0', ('.', '+', '~'), '2.2.0~rc5', ('.', '+', '~', '-', ':'), '2.2.0~rc5'","output":"0","cyclomatic_complexity":6,"code_length":15,"category":"Hard"}
{"index":497,"idx":62,"code":"def getorcreatesubcontext(self, path):\n for name in path:\n that = self.resolvables.get(name)\n if that is None:\n self.resolvables[name] = that = Context(self)\n self = that\n return self","input":"Context(SuperContext(), False), ('woo',), False, SuperContext(), OrderedDict()","output":"Context(Context(SuperContext(), False), False)","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":504,"idx":63,"code":"def indent(self):\n indent = []\n for r in self.resolvables:\n if not r.ignorable or r.boundary:\n break\n indent.append(r)\n return Concat.unlesssingleton(indent).resolve(None).cat()","input":"Entry([Text('woo'), Blank(' '), Text('+='), Blank(' '), Text('yay')]), [Text('woo'), Blank(' '), Text('+='), Blank(' '), Text('yay')]","output":"''","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":507,"idx":64,"code":"def __eq__(self, that):\n if type(self) != type(that):\n return False\n if self.__dict__.keys() != that.__dict__.keys():\n return False\n for k, v in self.__dict__.items():\n if v != that.__dict__[k]:\n return False\n return True","input":"Text('*'), Text('woo'), '*'","output":"False","cyclomatic_complexity":5,"code_length":9,"category":"Medium"}
{"index":508,"idx":65,"code":"def resolve(self, context):\n c = Context(self.parent, self.islist)\n for name, r in self.resolvables.items():\n if name is not None:\n c.resolvables[name] = r\n defaults = self.resolvables.get(None)\n if defaults is not None:\n for item in c.resolvables:\n for dn, dr in defaults.resolvables.items():\n if dn not in item.resolvables.keys():\n item.resolvables[dn] = dr\n return c","input":"Context(Context(SuperContext(), False), False), Context(SuperContext(), False), False, Context(SuperContext(), False), OrderedDict([('yay', Text('yay')), ('$(houpla )', Call('', [Text('houpla'), Blank(' ')], '()'))])","output":"Context(Context(SuperContext(), False), False)","cyclomatic_complexity":7,"code_length":12,"category":"Hard"}
{"index":514,"idx":66,"code":"def temporarily(self, name, resolvable, block): \n oldornone = self.resolvables.get(name)\n self.resolvables[name] = resolvable\n try:\n return block()\n finally:\n if oldornone is None:\n del self.resolvables[name]\n else:\n self.resolvables[name] = oldornone","input":"Context(SuperContext(), False), ('v', 'one', '1'), {}, 0, False, SuperContext(), OrderedDict([('v', Context(Context(SuperContext(), False), False))])","output":"Context(Context(Context(Context(SuperContext(), False), False), False), False)","cyclomatic_complexity":2,"code_length":10,"category":"Super Easy"}
{"index":518,"idx":67,"code":"def map(context, objs, *args):\n if 1 == len(args):\n expr, = args\n def g():\n for k, v in objs.resolve(context).resolvables.items():\n c = v.createchild()\n c.label = Text(k)\n yield expr.resolve(c)\n return List(list(g()))\n elif 2 == len(args):\n name, expr = args\n name = name.resolve(context).cat()\n def g():\n for obj in objs.resolve(context):\n c = context.createchild()\n c[name,] = obj\n yield expr.resolve(c)\n return List(list(g()))\n else:\n kname, vname, expr = args\n kname = kname.resolve(context).cat()\n vname = vname.resolve(context).cat()\n def g():\n for k, v in objs.resolve(context).resolvables.items():\n c = context.createchild()\n c[kname,] = Text(k)\n c[vname,] = v\n yield expr.resolve(c)\n return List(list(g()))","input":"Context(SuperContext(), False), Call('', [Text('items')], '()'), (Call('', [Text('value')], '()'),)","output":"List([Text('woo')])","cyclomatic_complexity":9,"code_length":29,"category":"Hard"}
{"index":519,"idx":68,"code":"def resolve(self, context):\n raise NotImplementedError","input":"Call('list', [Text('a'), Blank(' '), Text('bb'), Blank(' '), Text('ccc')], '()'), Context(SuperContext(), False), False, [Text('a'), Blank(' '), Text('bb'), Blank(' '), Text('ccc')], '()', 'list'","output":"Context(Context(SuperContext(), False), True)","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":520,"idx":69,"code":"def merge_dict(source, overrides):\n merged = source.copy()\n merged.update(overrides)\n return merged","input":"{}, {}","output":"{}","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":540,"idx":70,"code":"def static_bool_env(varname: str, default: bool) -> bool:\n \n val = os.getenv(varname, str(default))\n val = val.lower()\n if val in ('y', 'yes', 't', 'true', 'on', '1'):\n return True\n elif val in ('n', 'no', 'f', 'false', 'off', '0'):\n return False\n else:\n raise ValueError(\n 'invalid truth value {!r} for environment {!r}'.format(val, varname)\n )","input":"'FLAX_LAZY_RNG', True","output":"True","cyclomatic_complexity":3,"code_length":11,"category":"Easy"}
{"index":544,"idx":71,"code":"def splitdrive(path):\n \n relative = get_instance(path).relpath(path)\n drive = path.rsplit(relative, 1)[0]\n if drive and not drive[-2:] == '\/\/':\n \n relative = '\/' + relative\n drive = drive.rstrip('\/')\n return drive, relative","input":"'dummy:\/\/dir1\/dir2\/dir3'","output":"('dummy:\/\/', 'dir1\/dir2\/dir3')","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":551,"idx":72,"code":"def copy(src, dst):\n \n \n src, src_is_storage = format_and_is_storage(src)\n dst, dst_is_storage = format_and_is_storage(dst)\n\n \n if not src_is_storage and not dst_is_storage:\n return shutil_copy(src, dst)\n\n \n if not hasattr(dst, 'read'):\n \n if isdir(dst):\n dst = join(dst, basename(src))\n\n \n elif not isdir(dirname(dst)):\n raise IOError(\"No such file or directory: '%s'\" % dst)\n\n \n _copy(src, dst, src_is_storage, dst_is_storage)","input":"'\/tmp\/pytest-of-XXX\/pytest-198\/test_cos_open0\/file.txt', '\/tmp\/pytest-of-XXX\/pytest-198\/test_cos_open0\/file_dst.txt'","output":"'\/tmp\/pytest-of-XXX\/pytest-198\/test_cos_open0\/file_dst.txt'","cyclomatic_complexity":5,"code_length":11,"category":"Medium"}
{"index":553,"idx":73,"code":"def _handle_http_errors(response):\n \n code = response.status_code\n if 200 <= code < 400:\n return response\n elif code in (403, 404):\n raise {403: ObjectPermissionError,\n 404: ObjectNotFoundError}[code](response.reason)\n response.raise_for_status()","input":"{}","output":"{}","cyclomatic_complexity":3,"code_length":8,"category":"Easy"}
{"index":563,"idx":74,"code":"def _getmtime_from_header(header):\n \n \n for key in ('Last-Modified', 'last-modified'):\n try:\n return mktime(parsedate(header.pop(key)))\n except KeyError:\n continue\n else:\n raise UnsupportedOperation('getmtime')","input":"{'Accept-Ranges': 'bytes', 'Content-Length': '100', 'Last-Modified': 'Wed, 03 Apr 2024 20:18:10 GMT'}","output":"1712189890.0","cyclomatic_complexity":4,"code_length":8,"category":"Medium"}
{"index":565,"idx":75,"code":"def _getsize_from_header(header):\n \n \n for key in ('Content-Length', 'content-length'):\n try:\n return int(header.pop(key))\n except KeyError:\n continue\n else:\n raise UnsupportedOperation('getsize')","input":"{'Accept-Ranges': 'bytes', 'Content-Length': '100'}","output":"100","cyclomatic_complexity":4,"code_length":8,"category":"Medium"}
{"index":568,"idx":76,"code":"def parse_range(header):\n \n\n data_range = (header or dict()).get('Range')\n if data_range is None:\n \n content = BYTE * SIZE\n\n else:\n \n data_range = data_range.split('=')[1]\n start, end = data_range.split('-')\n start = int(start)\n try:\n end = int(end) + 1\n except ValueError:\n end = SIZE\n\n if start >= SIZE:\n \n raise ValueError\n\n if end > SIZE:\n end = SIZE\n content = BYTE * (end - start)\n\n return content","input":"{'Range': 'bytes=10-'}","output":"b'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'","cyclomatic_complexity":6,"code_length":18,"category":"Hard"}
{"index":603,"idx":77,"code":"def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):\n assert isinstance(commands, list)\n p = None\n for c in commands:\n try:\n dispcmd = str([c] + args)\n \n p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,\n stderr=(subprocess.PIPE if hide_stderr\n else None))\n break\n except EnvironmentError:\n e = sys.exc_info()[1]\n if e.errno == errno.ENOENT:\n continue\n if verbose:\n print(\"unable to run %s\" % dispcmd)\n print(e)\n return None\n else:\n if verbose:\n print(\"unable to find command, tried %s\" % (commands,))\n return None\n stdout = p.communicate()[0].strip()\n if sys.version_info[0] >= 3:\n stdout = stdout.decode()\n if p.returncode != 0:\n if verbose:\n print(\"unable to run %s (error)\" % dispcmd)\n return None\n return stdout","input":"['git'], ['describe', '--tags', '--dirty', '--always', '--long'], '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/danielfrg+datasciencebox\/danielfrg+datasciencebox', False, False","output":"'v0.3-35-g74ca80e'","cyclomatic_complexity":10,"code_length":30,"category":"Hard"}
{"index":718,"idx":78,"code":"def _makeNPIndex(indexList):\n newinds = []\n for i, item in enumerate(indexList):\n if isinstance(item, list):\n newinds.append(item)\n elif isinstance(item,int):\n newinds.append([item])\n\n numpyInd = list(np.ix_(*newinds))\n newinds=[]\n for item in indexList:\n if not item is None:\n newinds.append(numpyInd.pop(0))\n else:\n newinds.append(None)\n\n return tuple(newinds)","input":"[[0, 1], [0, 1]]","output":"(array([[0], [1]]), array([[0, 1]]))","cyclomatic_complexity":6,"code_length":15,"category":"Hard"}
{"index":734,"idx":79,"code":"def get_bound(pts: Iterable[Point]) -> Rect:\n \n limit: Rect = (INF, INF, -INF, -INF)\n (x0, y0, x1, y1) = limit\n for (x, y) in pts:\n x0 = min(x0, x)\n y0 = min(y0, y)\n x1 = max(x1, x)\n y1 = max(y1, y)\n return x0, y0, x1, y1","input":"[(6, 7), (7, 7)]","output":"(6, 7, 7, 7)","cyclomatic_complexity":2,"code_length":9,"category":"Super Easy"}
{"index":816,"idx":80,"code":"def make_input_stream(input, charset):\n \n if hasattr(input, 'read'):\n if PY2:\n return input\n rv = _find_binary_reader(input)\n if rv is not None:\n return rv\n raise TypeError('Could not find binary reader for input stream.')\n\n if input is None:\n input = b''\n elif not isinstance(input, bytes):\n input = input.encode(charset)\n if PY2:\n return StringIO(input)\n return io.BytesIO(input)","input":"None, 'utf-8'","output":"{}","cyclomatic_complexity":7,"code_length":15,"category":"Hard"}
{"index":831,"idx":81,"code":"def _unpack_args(args, nargs_spec):\n \n args = deque(args)\n nargs_spec = deque(nargs_spec)\n rv = []\n spos = None\n\n def _fetch(c):\n try:\n if spos is None:\n return c.popleft()\n else:\n return c.pop()\n except IndexError:\n return None\n\n while nargs_spec:\n nargs = _fetch(nargs_spec)\n if nargs == 1:\n rv.append(_fetch(args))\n elif nargs > 1:\n x = [_fetch(args) for _ in range(nargs)]\n \n \n if spos is not None:\n x.reverse()\n rv.append(tuple(x))\n elif nargs < 0:\n if spos is not None:\n raise TypeError('Cannot have two nargs < 0')\n spos = len(rv)\n rv.append(None)\n\n \n \n if spos is not None:\n rv[spos] = tuple(args)\n args = []\n rv[spos + 1:] = reversed(rv[spos + 1:])\n\n return tuple(rv), list(args)","input":"['foo.txt', 'bar.txt', 'dir'], [-1, 1]","output":"((('foo.txt', 'bar.txt'), 'dir'), [])","cyclomatic_complexity":12,"code_length":32,"category":"Hard"}
{"index":832,"idx":82,"code":"def _fetch(c):\n try:\n if spos is None:\n return c.popleft()\n else:\n return c.pop()\n except IndexError:\n return None","input":"deque([-1, 1]), None","output":"-1","cyclomatic_complexity":4,"code_length":8,"category":"Medium"}
{"index":870,"idx":83,"code":"def make_default_short_help(help, max_length=45):\n words = help.split()\n total_length = 0\n result = []\n done = False\n\n for word in words:\n if word[-1:] == '.':\n done = True\n new_length = result and 1 + len(word) or len(word)\n if total_length + new_length > max_length:\n result.append('...')\n done = True\n else:\n if result:\n result.append(' ')\n result.append(word)\n if done:\n break\n total_length += new_length\n\n return ''.join(result)","input":"'Hello World!', 45","output":"'Hello World!'","cyclomatic_complexity":6,"code_length":20,"category":"Hard"}
{"index":878,"idx":84,"code":"def join_options(options):\n \n rv = []\n any_prefix_is_slash = False\n for opt in options:\n prefix = split_opt(opt)[0]\n if prefix == '\/':\n any_prefix_is_slash = True\n rv.append((len(prefix), opt))\n\n rv.sort(key=lambda x: x[0])\n\n rv = ', '.join(x[1] for x in rv)\n return rv, any_prefix_is_slash","input":"['--help']","output":"('--help', False)","cyclomatic_complexity":3,"code_length":11,"category":"Easy"}
{"index":881,"idx":85,"code":"def measure_table(rows):\n widths = {}\n for row in rows:\n for idx, col in enumerate(row):\n widths[idx] = max(widths.get(idx, 0), term_len(col))\n return tuple(y for x, y in sorted(widths.items()))","input":"[('--help', 'Show this message and exit.')]","output":"(6, 27)","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":887,"idx":86,"code":"def filename_to_ui(value):\n if isinstance(value, bytes):\n value = value.decode(get_filesystem_encoding(), 'replace')\n return value","input":"b'foo.txt'","output":"'foo.txt'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":907,"idx":87,"code":"def _build_prompt(text, suffix, show_default=False, default=None):\n prompt = text\n if default is not None and show_default:\n prompt = '%s [%s]' % (prompt, default)\n return prompt + suffix","input":"'Foo', ': ', True, None","output":"'Foo: '","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":908,"idx":88,"code":"def format_filename(filename, shorten=False):\n \n if shorten:\n filename = os.path.basename(filename)\n return filename_to_ui(filename)","input":"'\/x\/foo.txt', True","output":"'foo.txt'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":913,"idx":89,"code":"def encode_request(*args):\n \n result = [\"*\" + str(len(args)) + CRLF]\n \n for arg in args:\n if arg is None:\n result.append('$-1' + CRLF)\n else:\n s = str(arg)\n result.append('$' + str(len(s)) + CRLF + s + CRLF)\n\n return \"\".join(result)","input":"('ping',)","output":"'*1\\r\\n$4\\r\\nping\\r\\n'","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":914,"idx":90,"code":"def parse_array(data, start=0):\n endcnt = data.find(CRLF, start + 1)\n\n if endcnt == -1:\n raise ParseError(\"Unterminated array element count after pos {}.\".format(start + 1))\n\n try:\n count = int(data[start + 1:endcnt])\n except (ValueError, TypeError):\n raise ParseError(\"Invalid array element count at pos {} - {}.\".format(start + 1, endcnt))\n\n start = endcnt + CRLFLEN\n\n if count == -1:\n return None, endcnt\n\n result = []\n \n for i in range(count):\n if start + 4 < len(data):\n obj, start = _decode(data, start)\n result.append(obj)\n else:\n raise ParseError(\"Unterminated array element at pos {}\".format(start))\n \n return result, start","input":"'*3\\r\\n$3\\r\\nSET\\r\\n$15\\r\\nmemtier-8232902\\r\\n$2\\r\\nxx\\r\\n*3\\r\\n$3\\r\\nSET\\r\\n$15\\r\\nmemtier-8232902\\r\\n$2\\r\\nxx\\r\\n*3\\r\\n$3\\r\\nSET\\r\\n$15\\r\\nmemtier-7630684\\r\\n$3\\r\\nAAA\\r\\n', 0","output":"(['SET', 'memtier-8232902', 'xx'], 43)","cyclomatic_complexity":7,"code_length":19,"category":"Hard"}
{"index":938,"idx":91,"code":"def fill_style(complete, filling): \n odd = bool(complete % 2)\n fill = (None,) if odd != bool(filling) else () \n fill += (chars[-1], None) * int(complete \/ 2) \n if filling and odd:\n fill += mark_graphemes((chars[filling - 1],))\n return fill","input":"0, 0, ('=',)","output":"()","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":951,"idx":92,"code":"def _input(x):\n return name_lookup(x) or func_lookup(x) or default","input":"0, 0, 86400","output":"0.0","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":963,"idx":93,"code":"def elapsed_text(seconds, precise, prefix=''):\n seconds = round(seconds, 1 if precise else 0)\n if seconds < 60.:\n return '{}{:{}f}s'.format(prefix, seconds, .1 if precise else .0)\n\n minutes, seconds = divmod(seconds, 60.)\n if minutes < 60.:\n return '{}{:.0f}:{:0{}f}'.format(prefix, minutes, seconds, 4.1 if precise else 2.0)\n\n hours, minutes = divmod(minutes, 60.)\n return '{}{:.0f}:{:02.0f}:{:0{}f}'.format(prefix, hours, minutes, seconds,\n 4.1 if precise else 2.0)","input":"1.23, True, ''","output":"'1.2s'","cyclomatic_complexity":3,"code_length":10,"category":"Easy"}
{"index":975,"idx":94,"code":"def block():\n nonlocal r\n r += 1\n return getblock(text, r, r, '\\xb6')","input":"10, 10","output":"'class with\\n block after blank\\n \\tand its own indented block\\n and back again after a wrong blank\\n'","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":978,"idx":95,"code":"def strip(tokens):\n output = \"\"\n for type_, value in tokens:\n if type_ == TokenType.TEXT:\n output += value\n return output","input":"[(1, ''), (1, '{message}'), (1, '\\n'), (1, '{exception}')]","output":"'{message}\\n{exception}'","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":979,"idx":96,"code":"def parse(text, *, strip=False, strict=True):\n parser = loguru._colorizer.AnsiParser()\n parser.feed(text)\n tokens = parser.done(strict=strict)\n\n if strip:\n return parser.strip(tokens)\n return parser.colorize(tokens, \"\")","input":"'<red>Foo<\/red>\\n', False, True","output":"'\\x1b[31mFoo\\x1b[0m\\n'","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":986,"idx":97,"code":"def _parse_without_formatting(string, *, recursion_depth=2, recursive=False):\n if recursion_depth < 0:\n raise ValueError(\"Max string recursion exceeded\")\n\n formatter = Formatter()\n parser = AnsiParser()\n\n messages_color_tokens = []\n\n for literal_text, field_name, format_spec, conversion in formatter.parse(string):\n if literal_text and literal_text[-1] in \"{}\":\n literal_text += literal_text[-1]\n\n parser.feed(literal_text, raw=recursive)\n\n if field_name is not None:\n if field_name == \"message\":\n if recursive:\n messages_color_tokens.append(None)\n else:\n color_tokens = parser.current_color_tokens()\n messages_color_tokens.append(color_tokens)\n field = \"{%s\" % field_name\n if conversion:\n field += \"!%s\" % conversion\n if format_spec:\n field += \":%s\" % format_spec\n field += \"}\"\n parser.feed(field, raw=True)\n\n _, color_tokens = Colorizer._parse_without_formatting(\n format_spec, recursion_depth=recursion_depth - 1, recursive=True\n )\n messages_color_tokens.extend(color_tokens)\n\n return parser.done(), messages_color_tokens","input":"'', 1, True","output":"([], [])","cyclomatic_complexity":9,"code_length":29,"category":"Hard"}
{"index":997,"idx":98,"code":"def random_port():\n port = helper.random_port()\n while port in generated_ports:\n port = helper.random_port()\n generated_ports.add(port)\n return port","input":"set()","output":"56663","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":1031,"idx":99,"code":"def strtobool(val):\n \n val = val.lower()\n if val in ('y', 'yes', 't', 'true', 'on', '1'):\n return 1\n if val in ('n', 'no', 'f', 'false', 'off', '0'):\n return 0\n raise ValueError(f\"invalid truth value {val!r}\")","input":"'False'","output":"0","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":1042,"idx":100,"code":"def parse_search_terms(raw_search_value):\n search_regexp = r'(?:[^\\s,\"]|\"(?:\\\\.|[^\"])*\")+' \n if not raw_search_value:\n return {}\n parsed_search = {}\n for query_part in re.findall(search_regexp, raw_search_value):\n if not query_part:\n continue\n if query_part.startswith('result:'):\n parsed_search['result'] = preprocess_search_value(query_part[len('result:'):])\n elif query_part.startswith('args:'):\n if 'args' not in parsed_search:\n parsed_search['args'] = []\n parsed_search['args'].append(preprocess_search_value(query_part[len('args:'):]))\n elif query_part.startswith('kwargs:'):\n if 'kwargs'not in parsed_search:\n parsed_search['kwargs'] = {}\n try:\n key, value = [p.strip() for p in query_part[len('kwargs:'):].split('=')]\n except ValueError:\n continue\n parsed_search['kwargs'][key] = preprocess_search_value(value)\n elif query_part.startswith('state'):\n if 'state' not in parsed_search:\n parsed_search['state'] = []\n parsed_search['state'].append(preprocess_search_value(query_part[len('state:'):]))\n else:\n parsed_search['any'] = preprocess_search_value(query_part)\n return parsed_search","input":"{}","output":"{}","cyclomatic_complexity":13,"code_length":29,"category":"Hard"}
{"index":1050,"idx":101,"code":"def stringified_dict_contains_value(key, value, str_dict):\n \n if not str_dict:\n return False\n value = str(value)\n try:\n \n key_index = str_dict.index(key) + len(key) + 3\n except ValueError:\n return False\n try:\n comma_index = str_dict.index(',', key_index)\n except ValueError:\n \n comma_index = str_dict.index('}', key_index)\n return str(value) == str_dict[key_index:comma_index].strip('\"\\'')","input":"'test', 5, \"{'test': 5}\"","output":"True","cyclomatic_complexity":6,"code_length":13,"category":"Hard"}
{"index":1051,"idx":102,"code":"def humanize(obj, type=None, length=None):\n if obj is None:\n obj = ''\n elif type and type.startswith('time'):\n tz = type[len('time'):].lstrip('-')\n tz = timezone(tz) if tz else getattr(current_app, 'timezone', '') or utc\n obj = format_time(float(obj), tz) if obj else ''\n elif type and type.startswith('natural-time'):\n tz = type[len('natural-time'):].lstrip('-')\n tz = timezone(tz) if tz else getattr(current_app, 'timezone', '') or utc\n delta = datetime.now(tz) - datetime.fromtimestamp(float(obj), tz)\n if delta < timedelta(days=1):\n obj = naturaltime(delta)\n else:\n obj = format_time(float(obj), tz) if obj else ''\n elif isinstance(obj, str) and not re.match(UUID_REGEX, obj):\n obj = obj.replace('-', ' ').replace('_', ' ')\n obj = re.sub('|'.join(KEYWORDS_UP),\n lambda m: m.group(0).upper(), obj)\n if obj and obj not in KEYWORDS_DOWN:\n obj = obj[0].upper() + obj[1:]\n elif isinstance(obj, list):\n if all(isinstance(x, (int, float, str)) for x in obj):\n obj = ', '.join(map(str, obj))\n if length is not None and len(obj) > length:\n obj = obj[:length - 4] + ' ...'\n return obj","input":"'ssl', None, None","output":"'SSL'","cyclomatic_complexity":10,"code_length":27,"category":"Hard"}
{"index":1053,"idx":103,"code":"def abs_path(path):\n path = os.path.expanduser(path)\n if not os.path.isabs(path):\n cwd = os.environ.get('PWD') or os.getcwd()\n path = os.path.join(cwd, path)\n return path","input":"'~\/file.txt'","output":"'\/home\/XXX\/file.txt'","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":1070,"idx":104,"code":"def to_tuple(param, low=None, bias=None):\n \n if low is not None and bias is not None:\n raise ValueError(\"Arguments low and bias are mutually exclusive\")\n\n if param is None:\n return param\n\n if isinstance(param, (int, float)):\n if low is None:\n param = -param, +param\n else:\n param = (low, param) if low < param else (param, low)\n elif isinstance(param, Sequence):\n if len(param) != 2:\n raise ValueError(\"to_tuple expects 1 or 2 values\")\n param = tuple(param)\n else:\n raise ValueError(\"Argument param must be either scalar (int, float) or tuple\")\n\n if bias is not None:\n return tuple(bias + x for x in param)\n\n return tuple(param)","input":"7, 3, None","output":"(3, 7)","cyclomatic_complexity":8,"code_length":19,"category":"Hard"}
{"index":1078,"idx":105,"code":"def _position_of_committer_with_initials(all_committers: List[str], initials: str) -> int:\n for index, committer in enumerate(all_committers):\n if committer.startswith(initials):\n return index\n return _COMMITTER_NOT_PRESENT","input":"['initials1,name1,email1\\n', 'initials2,name2,email2\\n'], 'initials3'","output":"-1","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":1096,"idx":106,"code":"def all_valid_hooks(hooks: List[Hook]) -> bool:\n hook_names = [_name(hook) for hook in _normal_hooks(hooks)]\n valid_names = GUET_HOOKS == hook_names\n valid_content = all([hook.is_guet_hook() for hook in _normal_hooks(hooks)])\n if not (valid_names and valid_content):\n hook_names = [_name(hook).replace('-guet', '') for hook in _dash_guet_normal_hooks(hooks)]\n valid_names = GUET_HOOKS == hook_names\n valid_content = all([hook.is_guet_hook() for hook in _dash_guet_normal_hooks(hooks)])\n return valid_names and valid_content\n return True","input":"[<Mock id='140465523545424'>, <Mock id='140465523545520'>, <Mock id='140465523546288'>]","output":"False","cyclomatic_complexity":2,"code_length":10,"category":"Super Easy"}
{"index":1097,"idx":107,"code":"def _dash_guet_normal_hooks(hooks: List[Hook]) -> List[Hook]:\n final = []\n for hook in hooks:\n name = _name(hook)\n if name.endswith('-guet') and name.replace('-guet', '') in GUET_HOOKS:\n final.append(hook)\n return final","input":"[<Mock id='140465523545424'>, <Mock id='140465523545520'>, <Mock id='140465523546288'>]","output":"[]","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":1103,"idx":108,"code":"def _parse_file_content(create, path_to_hook):\n _content = Hook._get_file_content(path_to_hook, create)\n if _content != GUET_HOOK_FILE:\n _content = Hook._handle_mismatched_content(_content, create)\n return _content","input":"True, '\/path\/to\/.git\/hooks\/name'","output":"['#! \/usr\/bin\/env python3', 'from guet.hooks import manage', 'import sys', 'manage(sys.argv[0])']","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":1104,"idx":109,"code":"def _handle_mismatched_content(_content, create):\n if create:\n _content = GUET_HOOK_FILE\n return _content","input":"['Other', 'Content'], True","output":"['#! \/usr\/bin\/env python3', 'from guet.hooks import manage', 'import sys', 'manage(sys.argv[0])']","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":1125,"idx":110,"code":"def which(exe=None):\n \n\n if not exe:\n log.error(\"No executable was passed to be searched by salt.utils.path.which()\")\n return None\n\n \n def is_executable_common(path):\n \n return os.path.isfile(path) and os.access(path, os.X_OK)\n\n def resolve(path):\n \n while os.path.islink(path):\n res = readlink(path)\n\n \n \n if not os.path.isabs(res):\n directory, _ = os.path.split(path)\n res = join(directory, res)\n path = res\n return path\n\n \n def has_executable_ext(path, ext_membership):\n \n p, ext = os.path.splitext(path)\n return ext.lower() in ext_membership\n\n \n res = salt.utils.stringutils.to_unicode(os.environ.get(\"PATH\", \"\"))\n system_path = res.split(os.pathsep)\n\n \n if not salt.utils.platform.is_windows():\n res = set(system_path)\n extended_path = [\n \"\/sbin\",\n \"\/bin\",\n \"\/usr\/sbin\",\n \"\/usr\/bin\",\n \"\/usr\/local\/sbin\",\n \"\/usr\/local\/bin\",\n ]\n system_path.extend([p for p in extended_path if p not in res])\n\n \n if salt.utils.platform.is_windows():\n \n res = salt.utils.stringutils.to_str(os.environ.get(\"PATHEXT\", \".EXE\"))\n\n \n \n \n \n pathext = res.split(os.pathsep)\n res = {ext.lower() for ext in pathext}\n\n \n _, ext = os.path.splitext(exe)\n if ext.lower() in res:\n pathext = [\"\"]\n\n is_executable = is_executable_common\n\n \n \n else:\n is_executable = lambda path, membership=res: is_executable_common(\n path\n ) and has_executable_ext(path, membership)\n\n else:\n \n pathext = [\"\"]\n\n \n is_executable = is_executable_common\n\n \n\n \n \n if is_executable(exe):\n return exe\n\n \n for path in system_path:\n p = join(path, exe)\n\n \n for ext in pathext:\n pext = p + ext\n rp = resolve(pext)\n if is_executable(rp):\n return p + ext\n continue\n continue\n\n \n log.trace(\n \"'%s' could not be found in the following search path: '%s'\", exe, system_path\n )\n return None","input":"'true'","output":"'\/usr\/bin\/true'","cyclomatic_complexity":14,"code_length":60,"category":"Hard"}
{"index":1126,"idx":111,"code":"def join(*parts, **kwargs):\n \n parts = [salt.utils.stringutils.to_str(part) for part in parts]\n\n kwargs = salt.utils.args.clean_kwargs(**kwargs)\n use_posixpath = kwargs.pop(\"use_posixpath\", False)\n if kwargs:\n salt.utils.args.invalid_kwargs(kwargs)\n\n pathlib = posixpath if use_posixpath else os.path\n\n \n parts = [pathlib.normpath(p) for p in parts]\n\n try:\n root = parts.pop(0)\n except IndexError:\n \n return \"\"\n\n root = salt.utils.stringutils.to_unicode(root)\n if not parts:\n ret = root\n else:\n stripped = [p.lstrip(os.sep) for p in parts]\n ret = pathlib.join(root, *salt.utils.data.decode(stripped))\n return pathlib.normpath(ret)","input":"('\/home\/XXX\/.gdrive-downloader', 'true'), {}","output":"'\/home\/XXX\/.gdrive-downloader\/true'","cyclomatic_complexity":5,"code_length":19,"category":"Medium"}
{"index":1127,"idx":112,"code":"def to_str(s, encoding=None, errors=\"strict\", normalize=False):\n \n\n def _normalize(s):\n try:\n return unicodedata.normalize(\"NFC\", s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n \n encoding = (\"utf-8\", __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError(\"encoding cannot be empty\")\n\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n \n \n \n raise exc \n raise TypeError(f\"expected str, bytes, or bytearray not {type(s)}\")","input":"'\/home\/XXX\/.gdrive-downloader', None, 'strict', False","output":"'\/home\/XXX\/.gdrive-downloader'","cyclomatic_complexity":12,"code_length":24,"category":"Hard"}
{"index":1128,"idx":113,"code":"def _remove_circular_refs(ob, _seen=None):\n \n if _seen is None:\n _seen = set()\n if id(ob) in _seen:\n \n \n log.exception(\n \"Caught a circular reference in data structure below.\"\n \"Cleaning and continuing execution.\\n%r\\n\",\n ob,\n )\n return None\n _seen.add(id(ob))\n res = ob\n if isinstance(ob, dict):\n res = {\n _remove_circular_refs(k, _seen): _remove_circular_refs(v, _seen)\n for k, v in ob.items()\n }\n elif isinstance(ob, (list, tuple, set, frozenset)):\n res = type(ob)(_remove_circular_refs(v, _seen) for v in ob)\n \n _seen.remove(id(ob))\n return res","input":"['true'], None, 'strict', False, False, False, False, False","output":"['true']","cyclomatic_complexity":5,"code_length":21,"category":"Medium"}
{"index":1134,"idx":114,"code":"def file(input_file, light=False):\n \n util.create_dir(os.path.join(CONF_DIR, \"colorschemes\/light\/\"))\n util.create_dir(os.path.join(CONF_DIR, \"colorschemes\/dark\/\"))\n\n theme_name = \".\".join((input_file, \"json\"))\n bri = \"light\" if light else \"dark\"\n\n user_theme_file = os.path.join(CONF_DIR, \"colorschemes\", bri, theme_name)\n theme_file = os.path.join(MODULE_DIR, \"colorschemes\", bri, theme_name)\n\n \n if input_file in (\"random\", \"random_dark\"):\n theme_file = get_random_theme()\n\n elif input_file == \"random_light\":\n theme_file = get_random_theme(light)\n\n elif input_file == \"random_user\":\n theme_file = get_random_theme_user()\n\n elif os.path.isfile(user_theme_file):\n theme_file = user_theme_file\n\n elif os.path.isfile(input_file):\n theme_file = input_file\n\n \n if os.path.isfile(theme_file):\n logging.info(\"Set theme to \\033[1;37m%s\\033[0m.\",\n os.path.basename(theme_file))\n util.save_file(os.path.basename(theme_file),\n os.path.join(CACHE_DIR, \"last_used_theme\"))\n return parse(theme_file)\n\n logging.error(\"No %s colorscheme file found.\", bri)\n logging.error(\"Try adding '-l' to set light themes.\")\n logging.error(\"Try removing '-l' to set dark themes.\")\n sys.exit(1)","input":"'tests\/test_files\/test_file.json', False","output":"{'wallpaper': '5.png', 'alpha': '100', 'special': {'background': '#1F211E', 'foreground': '#F5F1F4', 'cursor': '#F5F1F4'}, 'colors': {'color0': '#1F211E', 'color1': '#4B7A85', 'color2': '#CC6A93', 'color3': '#5C9894', 'color4': '#A0A89B', 'color5': '#D1B9A9', 'color6': '#E3D6D8', 'color7': '#F5F1F4', 'color8': '#666666', 'color9': '#4B7A85', 'color10': '#CC6A93', 'color11': '#5C9894', 'color12': '#A0A89B', 'color13': '#D1B9A9', 'color14': '#E3D6D8', 'color15': '#F5F1F4'}}","cyclomatic_complexity":7,"code_length":27,"category":"Hard"}
{"index":1135,"idx":115,"code":"def parse(theme_file):\n \n data = util.read_file_json(theme_file)\n\n if \"wallpaper\" not in data:\n data[\"wallpaper\"] = \"None\"\n\n if \"alpha\" not in data:\n data[\"alpha\"] = util.Color.alpha_num\n\n \n if \"color\" in data:\n data = terminal_sexy_to_wal(data)\n\n return data","input":"'tests\/test_files\/test_file.json'","output":"{'wallpaper': '5.png', 'alpha': '100', 'special': {'background': '#1F211E', 'foreground': '#F5F1F4', 'cursor': '#F5F1F4'}, 'colors': {'color0': '#1F211E', 'color1': '#4B7A85', 'color2': '#CC6A93', 'color3': '#5C9894', 'color4': '#A0A89B', 'color5': '#D1B9A9', 'color6': '#E3D6D8', 'color7': '#F5F1F4', 'color8': '#666666', 'color9': '#4B7A85', 'color10': '#CC6A93', 'color11': '#5C9894', 'color12': '#A0A89B', 'color13': '#D1B9A9', 'color14': '#E3D6D8', 'color15': '#F5F1F4'}}","cyclomatic_complexity":4,"code_length":9,"category":"Medium"}
{"index":1137,"idx":116,"code":"def get(img, cache_dir=CACHE_DIR, iterative=False, recursive=False):\n \n if os.path.isfile(img):\n wal_img = img\n\n elif os.path.isdir(img):\n if iterative:\n wal_img = get_next_image(img, recursive)\n\n else:\n wal_img = get_random_image(img, recursive)\n\n else:\n logging.error(\"No valid image file found.\")\n sys.exit(1)\n\n wal_img = os.path.abspath(wal_img)\n\n \n util.save_file(wal_img, os.path.join(cache_dir, \"wal\"))\n\n logging.info(\"Using image \\033[1;37m%s\\033[0m.\", os.path.basename(wal_img))\n return wal_img","input":"'tests\/test_files\/test.jpg', '\/home\/XXX\/.cache\/wal', False, False","output":"'\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/dylanaraps+pywal\/dylanaraps+pywal\/tests\/test_files\/test.jpg'","cyclomatic_complexity":4,"code_length":15,"category":"Medium"}
{"index":1138,"idx":117,"code":"def get_random_image(img_dir, recursive):\n \n if recursive:\n images, current_wall = get_image_dir_recursive(img_dir)\n else:\n images, current_wall = get_image_dir(img_dir)\n\n if len(images) > 2 and current_wall in images:\n images.remove(current_wall)\n\n elif not images:\n logging.error(\"No images found in directory.\")\n sys.exit(1)\n\n random.shuffle(images)\n return os.path.join(img_dir if not recursive else \"\", images[0])","input":"'tests\/test_files', False","output":"'tests\/test_files\/test.png'","cyclomatic_complexity":4,"code_length":12,"category":"Medium"}
{"index":1139,"idx":118,"code":"def get_image_dir(img_dir):\n \n current_wall = wallpaper.get()\n current_wall = os.path.basename(current_wall)\n\n file_types = (\".png\", \".jpg\", \".jpeg\", \".jpe\", \".gif\")\n\n return [img.name for img in os.scandir(img_dir)\n if img.name.lower().endswith(file_types)], current_wall","input":"'tests\/test_files'","output":"(['test2.jpg', 'test.jpg', 'test.png'], 'test.jpg')","cyclomatic_complexity":1,"code_length":6,"category":"Super Easy"}
{"index":1140,"idx":119,"code":"def check_impl_detail(**guards):\n \n guards, default = _parse_guards(guards)\n return guards.get(sys.implementation.name, default)","input":"{}","output":"True","cyclomatic_complexity":1,"code_length":3,"category":"Super Easy"}
{"index":1142,"idx":120,"code":"def _find_and_replace_patterns(content, patterns_and_insertions):\n r\n for pattern_and_insertion in patterns_and_insertions:\n pattern = pattern_and_insertion['pattern']\n insertion = pattern_and_insertion['insertion']\n description = pattern_and_insertion['description']\n logging.info('Processing pattern: %s.', description)\n p = regex.compile(pattern)\n m = p.search(content)\n while m is not None:\n local_insertion = insertion.format(**m.groupdict())\n if pattern_and_insertion.get('strip_whitespace', True):\n local_insertion = strip_whitespace(local_insertion)\n logging.info(f'Found {content[m.start():m.end()]:<70}')\n logging.info(f'Replacing with {local_insertion:<30}')\n content = content[: m.start()] + local_insertion + content[m.end() :]\n m = p.search(content)\n logging.info('Finished pattern: %s.', description)\n return content","input":"'& \\\\figcompfigures{\\n\\timage1.jpg\\n}{\\n\\t\\\\ww\\n}{\\n\\t1.0\\n\\t}\\n& \\\\figcompfigures{image2.jpg}{\\\\ww}{1.0}', [{'pattern': '(?:\\\\\\\\figcompfigures{\\\\s*)(?P<first>.*?)\\\\s*}\\\\s*{\\\\s*(?P<second>.*?)\\\\s*}\\\\s*{\\\\s*(?P<third>.*?)\\\\s*}', 'insertion': '\\\\parbox[c]{{\\n {second}\\\\linewidth\\n }}{{\\n \\\\includegraphics[\\n width={third}\\\\linewidth\\n ]{{\\n figures\/{first}\\n }}\\n }} ', 'description': 'Replace figcompfigures'}]","output":"'& \\\\parbox[c]{\\\\ww\\\\linewidth}{\\\\includegraphics[width=1.0\\\\linewidth]{figures\/image1.jpg}}\\n& \\\\parbox[c]{\\\\ww\\\\linewidth}{\\\\includegraphics[width=1.0\\\\linewidth]{figures\/image2.jpg}}'","cyclomatic_complexity":4,"code_length":19,"category":"Medium"}
{"index":1143,"idx":121,"code":"def strip_whitespace(text):\n \n pattern = regex.compile(r'\\s+')\n text = regex.sub(pattern, '', text)\n return text","input":"'\\\\parbox[c]{\\n \\\\ww\\\\linewidth\\n }{\\n \\\\includegraphics[\\n width=1.0\\\\linewidth\\n ]{\\n figures\/image1.jpg\\n }\\n } '","output":"'\\\\parbox[c]{\\\\ww\\\\linewidth}{\\\\includegraphics[width=1.0\\\\linewidth]{figures\/image1.jpg}}'","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1144,"idx":122,"code":"def _keep_pattern(haystack, patterns_to_keep):\n \n out = []\n for item in haystack:\n if any((regex.findall(rem, item) for rem in patterns_to_keep)):\n out.append(item)\n return out","input":"['abc', 'bca'], ['a']","output":"['abc', 'bca']","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":1145,"idx":123,"code":"def merge_args_into_config(args, config_params):\n final_args = copy.deepcopy(config_params)\n config_keys = config_params.keys()\n for key, value in args.items():\n if key in config_keys:\n if any([isinstance(value, t) for t in [str, bool, float, int]]):\n \n final_args[key] = value\n elif isinstance(value, list):\n \n final_args[key] = value + config_params[key]\n elif isinstance(value, dict):\n \n final_args[key].update(**value)\n else:\n final_args[key] = value\n return final_args","input":"{'input_folder': 'foo\/bar', 'resize_images': False, 'im_size': 500, 'compress_pdf': False, 'pdf_im_resolution': 500, 'images_allowlist': {'path1\/': 1000}, 'commands_to_delete': ['\\\\todo1'], 'use_external_tikz': 'foo\/bar\/tikz'}, {'input_folder': 'foo_\/bar_', 'resize_images': True, 'im_size': 1000, 'compress_pdf': True, 'pdf_im_resolution': 1000, 'images_allowlist': {'path2\/': 1000}, 'commands_to_delete': ['\\\\todo2'], 'use_external_tikz': 'foo_\/bar_\/tikz_'}","output":"{'input_folder': 'foo\/bar', 'resize_images': False, 'im_size': 500, 'compress_pdf': False, 'pdf_im_resolution': 500, 'images_allowlist': {'path2\/': 1000, 'path1\/': 1000}, 'commands_to_delete': ['\\\\todo1', '\\\\todo2'], 'use_external_tikz': 'foo\/bar\/tikz'}","cyclomatic_complexity":6,"code_length":14,"category":"Hard"}
{"index":1146,"idx":124,"code":"def _remove_command(text, command, keep_text=False):\n \n base_pattern = r'\\\\' + command + r'\\{((?:[^{}]+|\\{(?1)\\})*)\\}'\n \n \n while True:\n all_substitutions = []\n has_match = False\n for match in regex.finditer(base_pattern, text):\n \n \n has_match = True\n new_substring = (\n ''\n if not keep_text\n else text[match.span()[0] + len(command) + 2 : match.span()[1] - 1]\n )\n if match.span()[1] < len(text):\n next_newline = text[match.span()[1] :].find('\\n')\n if next_newline != -1:\n text_until_newline = text[\n match.span()[1] : match.span()[1] + next_newline\n ]\n if (\n not text_until_newline or text_until_newline.isspace()\n ) and not keep_text:\n new_substring = '%'\n all_substitutions.append(\n (match.span()[0], match.span()[1], new_substring)\n )\n\n for start, end, new_substring in reversed(all_substitutions):\n text = text[:start] + new_substring + text[end:]\n\n if not keep_text or not has_match:\n break\n\n return text","input":"'A\\\\todo{B\\nC}D\\nE\\n\\\\end{document}', 'todo', False","output":"'AD\\nE\\n\\\\end{document}'","cyclomatic_complexity":8,"code_length":30,"category":"Hard"}
{"index":1147,"idx":125,"code":"def _remove_comments_inline(text):\n \n if 'auto-ignore' in text:\n return text\n if text.lstrip(' ').lstrip('\\t').startswith('%'):\n return ''\n\n url_pattern = r'\\\\url\\{(?>[^{}]|(?R))*\\}'\n\n def remove_comments(segment):\n \n if segment.lstrip().startswith('%'):\n return ''\n match = regex.search(r'(?<!\\\\)%', segment)\n if match:\n return segment[: match.end()] + '\\n'\n else:\n return segment\n\n \n segments = regex.split(f'({url_pattern})', text)\n\n for i in range(len(segments)):\n \n if not regex.match(url_pattern, segments[i]):\n segments[i] = remove_comments(segments[i])\n\n final_text = ''.join(segments)\n return (\n final_text\n if final_text.endswith('\\n') or final_text.endswith('\\\\n')\n else final_text + '\\n'\n )","input":"'Foo %Comment\\n'","output":"'Foo %\\n'","cyclomatic_complexity":8,"code_length":24,"category":"Hard"}
{"index":1148,"idx":126,"code":"def _remove_iffalse_block(text):\n \n p = regex.compile(r'\\\\if\\s*(\\w+)|\\\\fi(?!\\w)')\n level = -1\n positions_to_delete = []\n start, end = 0, 0\n for m in p.finditer(text):\n if (\n m.group().replace(' ', '') == r'\\iffalse'\n or m.group().replace(' ', '') == r'\\if0'\n ) and level == -1:\n level += 1\n start = m.start()\n elif m.group().startswith(r'\\if') and level >= 0:\n level += 1\n elif m.group() == r'\\fi' and level >= 0:\n if level == 0:\n end = m.end()\n positions_to_delete.append((start, end))\n level -= 1\n else:\n pass\n\n for start, end in reversed(positions_to_delete):\n if end < len(text) and text[end].isspace():\n end_to_del = end + 1\n else:\n end_to_del = end\n text = text[:start] + text[end_to_del:]\n\n return text","input":"'\\\\newcommand\\\\figref[1]{Figure~\\\\ref{fig:\\\\#1}}'","output":"'\\\\newcommand\\\\figref[1]{Figure~\\\\ref{fig:\\\\#1}}'","cyclomatic_complexity":8,"code_length":28,"category":"Hard"}
{"index":1149,"idx":127,"code":"def _replace_includesvg(content, svg_inkscape_files):\n def repl_svg(matchobj):\n svg_path = matchobj.group(2)\n svg_filename = os.path.basename(svg_path)\n \n matching_pdf_tex_files = _keep_pattern(\n svg_inkscape_files, ['\/' + svg_filename + '-tex.pdf_tex']\n )\n if len(matching_pdf_tex_files) == 1:\n options = '' if matchobj.group(1) is None else matchobj.group(1)\n return f'\\\\includeinkscape{options}{{{matching_pdf_tex_files[0]}}}'\n else:\n return matchobj.group(0)\n\n content = regex.sub(r'\\\\includesvg(\\[.*?\\])?{(.*?)}', repl_svg, content)\n\n return content","input":"'Foo\\\\includesvg{test2}\\nFoo', ['ext_svg\/test1-tex.pdf_tex', 'ext_svg\/test2-tex.pdf_tex']","output":"'Foo\\\\includeinkscape{ext_svg\/test2-tex.pdf_tex}\\nFoo'","cyclomatic_complexity":3,"code_length":14,"category":"Easy"}
{"index":1150,"idx":128,"code":"def _replace_tikzpictures(content, figures):\n \n\n def get_figure(matchobj):\n found_tikz_filename = regex.search(\n r'\\\\tikzsetnextfilename{(.*?)}', matchobj.group(0)\n ).group(1)\n \n matching_tikz_filenames = _keep_pattern(\n figures, ['\/' + found_tikz_filename + '.pdf']\n )\n if len(matching_tikz_filenames) == 1:\n return '\\\\includegraphics{' + matching_tikz_filenames[0] + '}'\n else:\n return matchobj.group(0)\n\n content = regex.sub(\n r'\\\\tikzsetnextfilename{[\\s\\S]*?\\\\end{tikzpicture}', get_figure, content\n )\n\n return content","input":"'Foo\\n', ['ext_tikz\/test1.pdf', 'ext_tikz\/test2.pdf']","output":"'Foo\\n'","cyclomatic_complexity":3,"code_length":16,"category":"Easy"}
{"index":1156,"idx":129,"code":"def _list_all_files(in_folder, ignore_dirs=None):\n if ignore_dirs is None:\n ignore_dirs = []\n to_consider = [\n os.path.join(os.path.relpath(path, in_folder), name)\n if path != in_folder\n else name\n for path, _, files in os.walk(in_folder)\n for name in files\n ]\n return _remove_pattern(to_consider, ignore_dirs)","input":"'tex_arXiv', None","output":"['main.bbl', 'main.tex', 'ext_tikz\/test2.pdf', 'ext_tikz\/test1.pdf', 'figures\/figure_included.tikz', 'figures\/figure_included.tex', 'figures\/data_included.txt', 'images\/im4_included.png', 'images\/im3_included.png', 'images\/im2_included.jpg', 'images\/im5_included.jpg', 'images\/im1_included.png', 'images\/include\/images\/im3_included.png']","cyclomatic_complexity":2,"code_length":11,"category":"Super Easy"}
{"index":1158,"idx":130,"code":"def _read_file_content(filename):\n with open(filename, 'r', encoding='utf-8') as fp:\n lines = fp.readlines()\n lines = _strip_tex_contents(lines, '\\\\end{document}')\n return lines","input":"'tex\/figures\/figure_not_included.tex'","output":"['\\\\addplot{figures\/data_not_included.txt}\\n', '\\\\input{figures\/figure_not_included_2.tex}\\n']","cyclomatic_complexity":1,"code_length":5,"category":"Super Easy"}
{"index":1159,"idx":131,"code":"def _strip_tex_contents(lines, end_str):\n \n for i in range(len(lines)):\n if end_str in lines[i]:\n if '%' not in lines[i]:\n return lines[: i + 1]\n elif lines[i].index('%') > lines[i].index(end_str):\n return lines[: i + 1]\n return lines","input":"['\\\\addplot{figures\/data_not_included.txt}\\n', '\\\\input{figures\/figure_not_included_2.tex}\\n'], '\\\\end{document}'","output":"['\\\\addplot{figures\/data_not_included.txt}\\n', '\\\\input{figures\/figure_not_included_2.tex}\\n']","cyclomatic_complexity":5,"code_length":8,"category":"Medium"}
{"index":1193,"idx":132,"code":"def remove_python_path_suffix(path):\n for suffix in all_suffixes() + ['.pyi']:\n if path.suffix == suffix:\n path = path.with_name(path.stem)\n break\n return path","input":"PosixPath('\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/davidhalter+jedi\/davidhalter+jedi\/example.py')","output":"PosixPath('\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/davidhalter+jedi\/davidhalter+jedi\/example')","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":1197,"idx":133,"code":"def complete_dict(module_context, code_lines, leaf, position, string, fuzzy):\n bracket_leaf = leaf\n if bracket_leaf != '[':\n bracket_leaf = leaf.get_previous_leaf()\n\n cut_end_quote = ''\n if string:\n cut_end_quote = get_quote_ending(string, code_lines, position, invert_result=True)\n\n if bracket_leaf == '[':\n if string is None and leaf is not bracket_leaf:\n string = cut_value_at_position(leaf, position)\n\n context = module_context.create_context(bracket_leaf)\n\n before_node = before_bracket_leaf = bracket_leaf.get_previous_leaf()\n if before_node in (')', ']', '}'):\n before_node = before_node.parent\n if before_node.type in ('atom', 'trailer', 'name'):\n values = infer_call_of_leaf(context, before_bracket_leaf)\n return list(_completions_for_dicts(\n module_context.inference_state,\n values,\n '' if string is None else string,\n cut_end_quote,\n fuzzy=fuzzy,\n ))\n return []","input":"ModuleContext(<ModuleValue: example@2-3 is_stub=False>), ['\\n', 'import json\\n', 'json.lo'], <Name: lo@3,5>, (3, 7), None, False","output":"[]","cyclomatic_complexity":7,"code_length":24,"category":"Hard"}
{"index":1199,"idx":134,"code":"def _get_code_for_stack(code_lines, leaf, position):\n \n \n if leaf.start_pos >= position:\n \n leaf = leaf.get_previous_leaf()\n if leaf is None:\n return '' \n\n is_after_newline = leaf.type == 'newline'\n while leaf.type == 'newline':\n leaf = leaf.get_previous_leaf()\n if leaf is None:\n return ''\n\n if leaf.type == 'error_leaf' or leaf.type == 'string':\n if leaf.start_pos[0] < position[0]:\n \n return ''\n\n \n \n raise OnErrorLeaf(leaf)\n else:\n user_stmt = leaf\n while True:\n if user_stmt.parent.type in ('file_input', 'suite', 'simple_stmt'):\n break\n user_stmt = user_stmt.parent\n\n if is_after_newline:\n if user_stmt.start_pos[1] > position[1]:\n \n \n return ''\n\n \n return _get_code(code_lines, user_stmt.get_start_pos_of_prefix(), position)","input":"['\\n', 'import json\\n', 'json.lo'], <Name: lo@3,5>, (3, 5)","output":"'json.'","cyclomatic_complexity":11,"code_length":24,"category":"Hard"}
{"index":1200,"idx":135,"code":"def _get_code(code_lines, start_pos, end_pos):\n \n lines = code_lines[start_pos[0] - 1:end_pos[0]]\n \n lines[-1] = lines[-1][:end_pos[1]]\n \n lines[0] = lines[0][start_pos[1]:]\n return ''.join(lines)","input":"['\\n', 'import json\\n', 'json.lo'], (3, 0), (3, 5)","output":"'json.'","cyclomatic_complexity":1,"code_length":5,"category":"Super Easy"}
{"index":1222,"idx":136,"code":"def _get_definition_names(parso_cache_node, used_names, name_key):\n if parso_cache_node is None:\n names = used_names.get(name_key, ())\n return tuple(name for name in names if name.is_definition(include_setitem=True))\n\n try:\n for_module = _definition_name_cache[parso_cache_node]\n except KeyError:\n for_module = _definition_name_cache[parso_cache_node] = {}\n\n try:\n return for_module[name_key]\n except KeyError:\n names = used_names.get(name_key, ())\n result = for_module[name_key] = tuple(\n name for name in names if name.is_definition(include_setitem=True)\n )\n return result","input":"{node=<Module: @1-3>, lines=['def f(a, b=1):\\n', ' \"Document for function f.\"\\n', ''], change_time=1712197932.5185623, last_used=1712197932.5185623}, {_dict={'f': [<Name: f@1,4>], 'a': [<Name: a@1,6>], 'b': [<Name: b@1,9>]}}, 'f'","output":"(<Name: f@1,4>,)","cyclomatic_complexity":6,"code_length":16,"category":"Hard"}
{"index":1238,"idx":137,"code":"def _search_param_in_docstr(docstr, param_str):\n \n \n patterns = [re.compile(p % re.escape(param_str))\n for p in DOCSTRING_PARAM_PATTERNS]\n for pattern in patterns:\n match = pattern.search(docstr)\n if match:\n return [_strip_rst_role(match.group(1))]\n\n return _search_param_in_numpydocstr(docstr, param_str)","input":"':type param: int', 'param'","output":"['int']","cyclomatic_complexity":3,"code_length":8,"category":"Easy"}
{"index":1254,"idx":138,"code":"def _underscore(word: str) -> str:\n \n word = re.sub(r\"([A-Z]+)([A-Z][a-z])\", r'\\1_\\2', word)\n word = re.sub(r\"([a-z\\d])([A-Z])\", r'\\1_\\2', word)\n word = word.replace(\"-\", \"_\")\n return word.lower()","input":"'TestKlass'","output":"'test_klass'","cyclomatic_complexity":1,"code_length":5,"category":"Super Easy"}
{"index":1266,"idx":139,"code":"def to_json_line(self):\n raise NotImplementedError","input":"AsciiCastV2Header(version=2, width=212, height=53, theme=None, idle_time_limit=None), 2, 212, 53, None, None","output":"'{\"version\": 2, \"width\": 212, \"height\": 53}'","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":1268,"idx":140,"code":"def integral_duration_validation(duration):\n if duration.lower().endswith('ms'):\n duration = duration[:-len('ms')]\n\n if duration.isdigit() and int(duration) >= 1:\n return int(duration)\n raise ValueError('duration must be an integer greater than 0')","input":"'100ms'","output":"100","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":1271,"idx":141,"code":"def __get_command_output(command, cwd=None):\n \n\n p = subprocess.Popen(command, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE, cwd=cwd)\n p.wait()\n return p.returncode, p.stdout.read(), p.stderr.read()","input":"['git', 'rev-parse'], '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/ASPP+pelita\/ASPP+pelita\/pelita'","output":"(0, b'', b'')","cyclomatic_complexity":1,"code_length":5,"category":"Super Easy"}
{"index":1276,"idx":142,"code":"def initial_positions(walls):\n \n width = max(walls)[0] + 1\n height = max(walls)[1] + 1\n\n left_start = (1, height - 2)\n left = []\n right_start = (width - 2, 1)\n right = []\n\n dist = 0\n while len(left) < 2:\n \n for x_dist in range(dist + 1):\n y_dist = dist - x_dist\n pos = (left_start[0] + x_dist, left_start[1] - y_dist)\n \n if not (0 <= pos[0] < width) and not (0 <= pos[1] < height):\n raise ValueError(\"Not enough free initial positions.\")\n \n if not (0 <= pos[0] < width) or not (0 <= pos[1] < height):\n continue\n \n if pos not in walls:\n left.append(pos)\n\n if len(left) == 2:\n break\n\n dist += 1\n\n dist = 0\n while len(right) < 2:\n \n for x_dist in range(dist + 1):\n y_dist = dist - x_dist\n pos = (right_start[0] - x_dist, right_start[1] + y_dist)\n \n if not (0 <= pos[0] < width) and not (0 <= pos[1] < height):\n raise ValueError(\"Not enough free initial positions.\")\n \n if not (0 <= pos[0] < width) or not (0 <= pos[1] < height):\n continue\n \n if pos not in walls:\n right.append(pos)\n\n if len(right) == 2:\n break\n\n dist += 1\n\n \n left.reverse()\n right.reverse()\n return [left[0], right[0], left[1], right[1]]","input":"[(0, 0), (0, 1), (0, 2), (0, 3), (1, 0), (1, 3), (2, 0), (2, 1), (2, 3), (3, 0), (3, 1), (3, 3), (4, 0), (4, 1), (4, 3), (5, 0), (5, 3), (6, 0), (6, 3), (7, 0), (7, 1), (7, 2), (7, 3)]","output":"[(1, 1), (6, 2), (1, 2), (6, 1)]","cyclomatic_complexity":13,"code_length":38,"category":"Hard"}
{"index":1280,"idx":143,"code":"def deep_extend(*args):\n \n def clone_obj(item):\n if isinstance(item, dict):\n return dict(**item)\n if isinstance(item, (list, tuple)):\n return list(item)\n return None\n\n def iterator(item, i, iterable):\n obj = clone_obj(item)\n if obj is None:\n iterable[i] = item\n else:\n if isinstance(obj, dict):\n iterable[i] = deep_extend({}, obj)\n elif isinstance(obj, (list, tuple)):\n FuncFlow.each(obj, iterator)\n iterable[i] = obj\n else:\n raise TypeError(\"deep_copy cannot handle this type: {}\".format(type(obj)))\n \n args = list(args)\n dest = args.pop(0)\n\n for source in args:\n if source:\n for k, v in source.items():\n obj = clone_obj(v)\n if obj is None:\n dest[k] = v\n else:\n FuncFlow.each(obj, iterator)\n dest[k] = obj\n return dest","input":"(2,)","output":"2","cyclomatic_complexity":12,"code_length":31,"category":"Hard"}
{"index":1284,"idx":144,"code":"def get_nested(d, path, delimiter=\"\/\"):\n \n def item_by_tag(d, tags):\n \n t = tags[-1]\n if len(tags) == 1:\n return d[t]\n return item_by_tag(d[t], tags[:-1])\n\n tags = path.split(delimiter)\n tags.reverse()\n \n return item_by_tag(d, tags)","input":"{'nested': {'data': 'should be unchanged', 'event': None}}, 'nested', '\/'","output":"{'data': 'should be unchanged', 'event': None}","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":1287,"idx":145,"code":"def extend(*args):\n args = list(args)\n dest = args.pop(0)\n for source in args:\n if source:\n dest.update(source)\n return dest","input":"({}, {})","output":"{}","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":1301,"idx":146,"code":"def dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d","input":"REPR FAILED, ('My Way',)","output":"{'name': 'My Way'}","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":1307,"idx":147,"code":"def digit_version(version_str: str, length: int = 4):\n \n assert 'parrots' not in version_str\n version = parse(version_str)\n assert version.release, f'failed to parse version {version_str}'\n release = list(version.release)\n release = release[:length]\n if len(release) < length:\n release = release + [0] * (length - len(release))\n if version.is_prerelease:\n mapping = {'a': -3, 'b': -2, 'rc': -1}\n val = -4\n \n if version.pre:\n if version.pre[0] not in mapping:\n warnings.warn(f'unknown prerelease version {version.pre[0]}, '\n 'version checking may go wrong')\n else:\n val = mapping[version.pre[0]]\n release.extend([val, version.pre[-1]])\n else:\n release.extend([val, 0])\n\n elif version.is_postrelease:\n release.extend([1, version.post])\n else:\n release.extend([0, 0])\n return tuple(release)","input":"'2.2.2+cu121', 4","output":"(2, 2, 2, 0, 0, 0)","cyclomatic_complexity":6,"code_length":25,"category":"Hard"}
{"index":1317,"idx":148,"code":"def __ne__(self, other: object) -> bool:\n return not self == other","input":"{'Properties': {'callcorrect': False}}","output":"{'Properties': {'callcorrect': False}}","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":1318,"idx":149,"code":"def get_or_add_parameter(self, parameter: Parameter) -> Parameter:\n if parameter.title in self.parameters:\n return self.parameters[parameter.title]\n else:\n self.add_parameter(parameter)\n return parameter","input":"{'Value': 'myvalue'}","output":"{'Value': 'myvalue'}","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":1350,"idx":150,"code":"def notification_event(events):\n \n\n valid_events = [\"All\", \"InProgress\", \"Success\", \"TimedOut\", \"Cancelled\", \"Failed\"]\n for event in events:\n if event not in valid_events:\n raise ValueError(\n 'NotificationEvents must be at least one of: \"%s\"'\n % (\", \".join(valid_events))\n )\n return events","input":"['All', 'InProgress', 'Success', 'TimedOut', 'Cancelled', 'Failed']","output":"['All', 'InProgress', 'Success', 'TimedOut', 'Cancelled', 'Failed']","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":1351,"idx":151,"code":"def get_air_quality(city):\n \n\n if not city or not city.strip():\n return\n print('\u83b7\u53d6 {} \u7684\u7a7a\u6c14\u8d28\u91cf...'.format(city))\n try:\n\n url = 'http:\/\/api.waqi.info\/feed\/{city}\/?token={token}'.format(city=city, token=AQICN_TOKEN)\n resp = requests.get(url)\n if resp.status_code == 200:\n \n content_dict = resp.json()\n if content_dict.get('status') == 'ok':\n data_dict = content_dict['data']\n aqi = data_dict['aqi']\n air_status = '\u4e25\u91cd\u6c61\u67d3'\n for key in sorted(AIR_STATUS_DICT):\n if key >= aqi:\n air_status = AIR_STATUS_DICT[key]\n break\n aqi_info = '{city} PM2.5\uff1a{aqi} {air_status}'.format(city=city, aqi=aqi, air_status=air_status)\n \n return aqi_info\n else:\n print('\u83b7\u53d6\u7a7a\u6c14\u8d28\u91cf\u5931\u8d25:{}'.format(content_dict['data']))\n return None\n print('\u83b7\u53d6\u7a7a\u6c14\u8d28\u91cf\u5931\u8d25\u3002')\n except Exception as exception:\n print(str(exception))\n return None","input":"'\u6842\u6797'","output":"'\u6842\u6797 PM2.5\uff1a50 \u4f18'","cyclomatic_complexity":8,"code_length":26,"category":"Hard"}
{"index":1366,"idx":152,"code":"def _LiteralEval(value):\n \n root = ast.parse(value, mode='eval')\n if isinstance(root.body, ast.BinOp):\n raise ValueError(value)\n\n for node in ast.walk(root):\n for field, child in ast.iter_fields(node):\n if isinstance(child, list):\n for index, subchild in enumerate(child):\n if isinstance(subchild, ast.Name):\n child[index] = _Replacement(subchild)\n\n elif isinstance(child, ast.Name):\n replacement = _Replacement(child)\n node.__setattr__(field, replacement)\n\n \n \n \n return ast.literal_eval(root)","input":"'[one, 2, \"3\"]'","output":"['one', 2, '3']","cyclomatic_complexity":8,"code_length":14,"category":"Hard"}
{"index":1367,"idx":153,"code":"def SeparateFlagArgs(args: list):\n \n if len(args) > 0 and (args[-1] == '-h' or args[-1] == '--help') and '--' not in args:\n args.pop()\n args.append('--')\n args.append('-h')\n\n if '--' in args:\n separator_index = len(args) - 1 - args[::-1].index('--') \n flag_args = args[separator_index + 1:]\n args = args[:separator_index]\n return args, flag_args\n\n return args, []","input":"['a', 'b', '--']","output":"(['a', 'b'], [])","cyclomatic_complexity":3,"code_length":11,"category":"Easy"}
{"index":1371,"idx":154,"code":"def prepare_docstring_help(N):\n \n \n\n args = []\n if hasattr(N, '__annotations__'):\n for attr_name, cls in N.__annotations__.items():\n\n filtered = filter_params(N)\n parsed = parse_source_for_params(filtered)\n attr = attr_map(parsed).get(attr_name)\n if attr is None:\n continue\n\n args.append(argument_help(attr_name, attr))\n\n return '\\n'.join(args)","input":"{}","output":"' --bar (int): (Default is 0)'","cyclomatic_complexity":4,"code_length":11,"category":"Medium"}
{"index":1372,"idx":155,"code":"def filter_params(N):\n \n filtered_source = []\n for line in inspect.getsourcelines(N.__class__)[0][1:]:\n \n if line.strip().startswith('def '):\n break\n filtered_source.append(line)\n return filtered_source","input":"{}","output":"[' bar: int = 0\\n']","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":1378,"idx":156,"code":"def _ParseFn(args):\n \n kwargs, remaining_kwargs, remaining_args = _ParseKeywordArgs(\n args, all_args, fn_spec.varkw)\n\n \n parsed_args, kwargs, remaining_args, capacity = _ParseArgs(\n fn_spec.args, fn_spec.defaults, num_required_args, kwargs,\n remaining_args, metadata)\n\n if fn_spec.varargs or fn_spec.varkw:\n \n capacity = True\n\n extra_kw = set(kwargs) - set(fn_spec.kwonlyargs)\n if fn_spec.varkw is None and extra_kw:\n raise FireError('Unexpected kwargs present:', extra_kw)\n\n missing_kwonly = set(required_kwonly) - set(kwargs)\n if missing_kwonly:\n raise FireError('Missing required flags:', missing_kwonly)\n\n \n if fn_spec.varargs is not None:\n varargs, remaining_args = remaining_args, []\n else:\n varargs = []\n\n for index, value in enumerate(varargs):\n varargs[index] = _ParseValue(value, None, None, metadata)\n\n varargs = parsed_args + varargs\n remaining_args += remaining_kwargs\n\n consumed_args = args[:len(args) - len(remaining_args)]\n return (varargs, kwargs), consumed_args, remaining_args, capacity","input":"['x'], [], {args=[], varargs=None, varkw='cli_args', defaults=(), kwonlyargs=[], kwonlydefaults={}, annotations={}}, {'ACCEPTS_POSITIONAL_ARGS': False}, 0, set()","output":"(([], {}), [], ['x'], True)","cyclomatic_complexity":6,"code_length":24,"category":"Hard"}
{"index":1380,"idx":157,"code":"def config_dict(configuration_tuple):\n config_dict = {}\n\n config_file = configuration_tuple._asdict().get('CFG')\n if config_file is None:\n config_file = configfile.get_config_path(configuration_tuple)\n\n if config_file is not None:\n config_dict = utils.filter_fields(configfile.read_config(config_file), configuration_tuple)\n config_dict = utils.type_correct_with(config_dict, configuration_tuple)\n\n return config_dict","input":"{}","output":"{'bar': 42}","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":1381,"idx":158,"code":"def read_config(_filepath='test.cfg') -> dict:\n filepath = Path(_filepath)\n if not filepath.exists():\n return {}\n\n file_config = configparser.ConfigParser()\n file_config.read(filepath)\n if 'Default' in file_config:\n return dict(file_config['Default'])\n else:\n print('warning: config file found at {}, but it was missing section named [Default]'.format(str(filepath)))\n return {}","input":"PosixPath('\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/d3rp+clima\/d3rp+clima\/tests\/test_configfile.py')","output":"PosixPath('\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/pypibugs\/tried\/d3rp+clima\/d3rp+clima\/foo.cfg')","cyclomatic_complexity":3,"code_length":11,"category":"Easy"}
{"index":1382,"idx":159,"code":"def filter_fields(d: dict, nt):\n \n res = {}\n for k, v in d.items():\n if k in nt._fields:\n res.update({k: v})\n\n return res","input":"{'bar': '42'}, {}","output":"{'bar': '42'}","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":1383,"idx":160,"code":"def type_correct_with(cdict, cfg_tuple):\n \n \n \n res = {}\n for k, v in cdict.items():\n typename = getattr(cfg_tuple, k)\n res.update({k: type(typename)(v)})\n return res","input":"{'bar': '42'}, {}","output":"{'bar': 42}","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":1428,"idx":161,"code":"def safe_abs_path(res):\n \"Gives an abs path, which safely returns a full (not 8.3) windows path\"\n res = Path(res).resolve()\n return str(res)","input":"'\/tmp\/tmpbbwa2p3f'","output":"'\/tmp\/tmpbbwa2p3f'","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1442,"idx":162,"code":"def is_image_file(file_name):\n \n file_name = str(file_name) \n return any(file_name.endswith(ext) for ext in IMAGE_EXTENSIONS)","input":"PosixPath('\/tmp\/tmpcr1f5en7\/.gitignore')","output":"False","cyclomatic_complexity":1,"code_length":3,"category":"Super Easy"}
{"index":1458,"idx":163,"code":"def mock_get_commit_message(diffs, context):\n self.assertNotIn(\"one\", diffs)\n self.assertNotIn(\"ONE\", diffs)\n return \"commit message\"","input":"'diff --git a\/file.txt b\/file.txt\\nindex 5626abf..f719efd 100644\\n--- a\/file.txt\\n+++ b\/file.txt\\n@@ -1 +1 @@\\n-one\\n+two', None, []","output":"'commit message'","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1459,"idx":164,"code":"def do_replace(fname, content, before_text, after_text, fence=None):\n before_text = strip_quoted_wrapping(before_text, fname, fence)\n after_text = strip_quoted_wrapping(after_text, fname, fence)\n fname = Path(fname)\n\n \n if not fname.exists() and not before_text.strip():\n fname.touch()\n content = \"\"\n\n if content is None:\n return\n\n if not before_text.strip():\n \n new_content = content + after_text\n else:\n new_content = replace_most_similar_chunk(content, before_text, after_text)\n\n return new_content","input":"'\/tmp\/tmp7g7a2csg\/file.txt', 'two\\n', 'two\\n', 'three\\n', ('```', '```')","output":"'three\\n'","cyclomatic_complexity":4,"code_length":14,"category":"Medium"}
{"index":1460,"idx":165,"code":"def strip_quoted_wrapping(res, fname=None, fence=DEFAULT_FENCE):\n \n if not res:\n return res\n\n res = res.splitlines()\n\n if fname and res[0].strip().endswith(Path(fname).name):\n res = res[1:]\n\n if res[0].startswith(fence[0]) and res[-1].startswith(fence[1]):\n res = res[1:-1]\n\n res = \"\\n\".join(res)\n if res and res[-1] != \"\\n\":\n res += \"\\n\"\n\n return res","input":"'two\\n', '\/tmp\/tmp7g7a2csg\/file.txt', ('```', '```')","output":"'two\\n'","cyclomatic_complexity":5,"code_length":12,"category":"Medium"}
{"index":1461,"idx":166,"code":"def replace_most_similar_chunk(whole, part, replace):\n \n\n whole, whole_lines = prep(whole)\n part, part_lines = prep(part)\n replace, replace_lines = prep(replace)\n\n res = perfect_or_whitespace(whole_lines, part_lines, replace_lines)\n if res:\n return res\n\n \n if len(part_lines) > 2 and not part_lines[0].strip():\n skip_blank_line_part_lines = part_lines[1:]\n res = perfect_or_whitespace(whole_lines, skip_blank_line_part_lines, replace_lines)\n if res:\n return res\n\n \n try:\n res = try_dotdotdots(whole, part, replace)\n if res:\n return res\n except ValueError:\n pass\n\n return\n \n res = replace_closest_edit_distance(whole_lines, part, part_lines, replace_lines)\n if res:\n return res","input":"'two\\n', 'two\\n', 'three\\n'","output":"'three\\n'","cyclomatic_complexity":8,"code_length":22,"category":"Hard"}
{"index":1462,"idx":167,"code":"def perfect_or_whitespace(whole_lines, part_lines, replace_lines):\n \n res = perfect_replace(whole_lines, part_lines, replace_lines)\n if res:\n return res\n\n \n res = replace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines)\n if res:\n return res","input":"['two\\n'], ['two\\n'], ['three\\n']","output":"'three\\n'","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":1463,"idx":168,"code":"def perfect_replace(whole_lines, part_lines, replace_lines):\n part_tup = tuple(part_lines)\n part_len = len(part_lines)\n\n for i in range(len(whole_lines) - part_len + 1):\n whole_tup = tuple(whole_lines[i : i + part_len])\n if part_tup == whole_tup:\n res = whole_lines[:i] + replace_lines + whole_lines[i + part_len :]\n return \"\".join(res)","input":"['two\\n'], ['two\\n'], ['three\\n']","output":"'three\\n'","cyclomatic_complexity":3,"code_length":8,"category":"Easy"}
{"index":1469,"idx":169,"code":"def parse_quoted_filenames(args):\n filenames = re.findall(r\"\\\"(.+?)\\\"|(\\S+)\", args)\n filenames = [name for sublist in filenames for name in sublist if name]\n return filenames","input":"'foo.txt bar.txt'","output":"['foo.txt', 'bar.txt']","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1473,"idx":170,"code":"def replace_part_with_missing_leading_whitespace(whole_lines, part_lines, replace_lines):\n \n \n \n\n \n leading = [len(p) - len(p.lstrip()) for p in part_lines if p.strip()] + [\n len(p) - len(p.lstrip()) for p in replace_lines if p.strip()\n ]\n\n if leading and min(leading):\n num_leading = min(leading)\n part_lines = [p[num_leading:] if p.strip() else p for p in part_lines]\n replace_lines = [p[num_leading:] if p.strip() else p for p in replace_lines]\n\n \n num_part_lines = len(part_lines)\n\n for i in range(len(whole_lines) - num_part_lines + 1):\n add_leading = match_but_for_leading_whitespace(\n whole_lines[i : i + num_part_lines], part_lines\n )\n\n if add_leading is None:\n continue\n\n replace_lines = [add_leading + rline if rline.strip() else rline for rline in replace_lines]\n whole_lines = whole_lines[:i] + replace_lines + whole_lines[i + num_part_lines :]\n return \"\".join(whole_lines)\n\n return None","input":"[' line1\\n', ' line2\\n', ' line3\\n'], [' line1\\n', ' line2\\n'], [' new_line1\\n', ' new_line2\\n']","output":"' new_line1\\n new_line2\\n line3\\n'","cyclomatic_complexity":4,"code_length":19,"category":"Medium"}
{"index":1474,"idx":171,"code":"def match_but_for_leading_whitespace(whole_lines, part_lines):\n num = len(whole_lines)\n\n \n if not all(whole_lines[i].lstrip() == part_lines[i].lstrip() for i in range(num)):\n return\n\n \n add = set(\n whole_lines[i][: len(whole_lines[i]) - len(part_lines[i])]\n for i in range(num)\n if whole_lines[i].strip()\n )\n\n if len(add) != 1:\n return\n\n return add.pop()","input":"[' line1\\n', ' line2\\n'], ['line1\\n', 'line2\\n']","output":"' '","cyclomatic_complexity":3,"code_length":12,"category":"Easy"}
{"index":1481,"idx":172,"code":"def find_diffs(content):\n \n \n\n if not content.endswith(\"\\n\"):\n content = content + \"\\n\"\n\n lines = content.splitlines(keepends=True)\n line_num = 0\n edits = []\n while line_num < len(lines):\n while line_num < len(lines):\n line = lines[line_num]\n if line.startswith(\"```diff\"):\n line_num, these_edits = process_fenced_block(lines, line_num + 1)\n edits += these_edits\n break\n line_num += 1\n\n \n \n\n return edits","input":"'\\nSome text...\\n\\n```diff\\n--- \/dev\/null\\n+++ file.txt\\n@@ ... @@\\n-Original\\n+Modified\\n```\\n'","output":"[('file.txt', ['-Original\\n', '+Modified\\n'])]","cyclomatic_complexity":5,"code_length":15,"category":"Medium"}
{"index":1482,"idx":173,"code":"def process_fenced_block(lines, start_line_num):\n for line_num in range(start_line_num, len(lines)):\n line = lines[line_num]\n if line.startswith(\"```\"):\n break\n\n block = lines[start_line_num:line_num]\n block.append(\"@@ @@\")\n\n if block[0].startswith(\"--- \") and block[1].startswith(\"+++ \"):\n \n fname = block[1][4:].strip()\n block = block[2:]\n else:\n fname = None\n\n edits = []\n\n keeper = False\n hunk = []\n op = \" \"\n for line in block:\n hunk.append(line)\n if len(line) < 2:\n continue\n\n if line.startswith(\"+++ \") and hunk[-2].startswith(\"--- \"):\n if hunk[-3] == \"\\n\":\n hunk = hunk[:-3]\n else:\n hunk = hunk[:-2]\n\n edits.append((fname, hunk))\n hunk = []\n keeper = False\n\n fname = line[4:].strip()\n continue\n\n op = line[0]\n if op in \"-+\":\n keeper = True\n continue\n if op != \"@\":\n continue\n if not keeper:\n hunk = []\n continue\n\n hunk = hunk[:-1]\n edits.append((fname, hunk))\n hunk = []\n keeper = False\n\n return line_num + 1, edits","input":"['\\n', 'Some text...\\n', '\\n', '```diff\\n', '--- \/dev\/null\\n', '+++ file.txt\\n', '@@ ... @@\\n', '-Original\\n', '+Modified\\n', '```\\n'], 4","output":"(10, [('file.txt', ['-Original\\n', '+Modified\\n'])])","cyclomatic_complexity":11,"code_length":44,"category":"Hard"}
{"index":1525,"idx":174,"code":"def _addpoints(sol, distances, prec):\n \n res = []\n\n posfound = False\n\n \n pleft = []\n for n, m in enumerate(sol):\n if np.ndim(m) == 0:\n pleft.append(n)\n\n \n for i in pleft:\n ires, state = _addpoint(sol, i, distances, prec)\n\n \n if state == 0:\n posfound = True\n for j in ires:\n res.append(dcopy(j))\n \n elif state == 2:\n return [], 2\n\n \n if posfound:\n return res, 0\n\n return res, 1","input":"[array([0., 0.]), array([3., 0.]), 0, 0], array([[ 0., 3., 4., 1.], [ 3., 0., 2., 3.], [ 4., 2., 0., -1.], [ 1., 3., -1., 0.]]), 0.1","output":"([[array([0., 0.]), array([3., 0.]), array([3.5 , 1.93649167]), 0], [array([0., 0.]), array([3., 0.]), array([ 3.5 , -1.93649167]), 0], [array([0., 0.]), array([3., 0.]), 0, array([0.16666667, 0.9860133 ])], [array([0., 0.]), array([3., 0.]), 0, array([ 0.16666667, -0.9860133 ])]], 0)","cyclomatic_complexity":8,"code_length":18,"category":"Hard"}
{"index":1526,"idx":175,"code":"def _addpoint(sol, i, distances, prec):\n \n res = []\n\n \n if np.ndim(sol[i]) != 0:\n return [sol], 0\n\n \n solpnts = []\n for n, m in enumerate(sol):\n if np.ndim(m) != 0:\n solpnts.append(n)\n\n \n pntscount = len(solpnts)\n\n \n for n in range(pntscount - 1):\n for m in range(n + 1, pntscount):\n tmppnt, state = _pntcoord(\n sol, i, solpnts[n], solpnts[m], distances, prec\n )\n\n \n if state == 0:\n for pnt in tmppnt:\n res.append(dcopy(sol))\n res[-1][i] = pnt\n\n \n if state != 1:\n return res, state\n\n \n return res, state","input":"[array([0., 0.]), array([3., 0.]), 0, 0], 2, array([[ 0., 3., 4., 1.], [ 3., 0., 2., 3.], [ 4., 2., 0., -1.], [ 1., 3., -1., 0.]]), 0.1","output":"([[array([0., 0.]), array([3., 0.]), array([3.5 , 1.93649167]), 0], [array([0., 0.]), array([3., 0.]), array([ 3.5 , -1.93649167]), 0]], 0)","cyclomatic_complexity":9,"code_length":21,"category":"Hard"}
{"index":1527,"idx":176,"code":"def _pntcoord(sol, i, n, m, distances, prec):\n \n tmppnt = []\n\n state = 1\n\n pntscount = len(sol)\n\n \n if distances[i, n] < -0.5 or distances[i, m] < -0.5:\n return tmppnt, state\n\n \n if distances[i, n] + distances[i, m] < _dist(sol[n], sol[m]):\n state = 2\n return tmppnt, state\n\n \n g = _affinef(*_invtranmat(*_tranmat(sol[n], sol[m])))\n\n \n x = _xvalue(distances[i, n], distances[i, m], _dist(sol[n], sol[m]))\n y1, y2 = _yvalue(distances[i, n], distances[i, m], _dist(sol[n], sol[m]))\n\n \n pos1 = g(np.array([x, y1]))\n pos2 = g(np.array([x, y2]))\n\n valid1 = True\n valid2 = True\n\n \n for k in range(pntscount):\n if np.ndim(sol[k]) != 0 and distances[i, k] > -0.5:\n valid1 &= abs(_dist(sol[k], pos1) - distances[i, k]) < prec\n valid2 &= abs(_dist(sol[k], pos2) - distances[i, k]) < prec\n\n \n if valid1 or valid2:\n state = 0\n same = abs(y1 - y2) < prec \/ 4.0\n if valid1:\n tmppnt.append(dcopy(pos1))\n if valid2 and not same:\n tmppnt.append(dcopy(pos2))\n \n else:\n state = 2\n\n return tmppnt, state","input":"[array([0., 0.]), array([3., 0.]), 0, 0], 2, 0, 1, array([[ 0., 3., 4., 1.], [ 3., 0., 2., 3.], [ 4., 2., 0., -1.], [ 1., 3., -1., 0.]]), 0.1","output":"([array([3.5 , 1.93649167]), array([ 3.5 , -1.93649167])], 0)","cyclomatic_complexity":8,"code_length":30,"category":"Hard"}
{"index":1528,"idx":177,"code":"def _tranmat(a, b):\n \n A = np.zeros((2, 2))\n A[0, 0] = b[0] - a[0]\n A[1, 1] = b[0] - a[0]\n A[1, 0] = -(b[1] - a[1])\n A[0, 1] = +(b[1] - a[1])\n A \/= _dist(a, b)\n s = -np.dot(A, a)\n return A, s","input":"array([0., 0.]), array([3., 0.])","output":"(array([[ 1., 0.], [-0., 1.]]), array([-0., -0.]))","cyclomatic_complexity":1,"code_length":9,"category":"Super Easy"}
{"index":1529,"idx":178,"code":"def _yvalue(b, a, c):\n \n \n if a + b <= c or a + c <= b or b + c <= a:\n return 0.0, -0.0\n\n res = 2 * ((a * b) ** 2 + (a * c) ** 2 + (b * c) ** 2)\n res -= a ** 4 + b ** 4 + c ** 4\n \n res = max(res, 0.0)\n res = np.sqrt(res)\n res \/= 2 * c\n return res, -res","input":"4.0, 2.0, 3.0","output":"(1.9364916731037083, -1.9364916731037083)","cyclomatic_complexity":2,"code_length":9,"category":"Super Easy"}
{"index":1530,"idx":179,"code":"def _solequal(sol1, sol2, prec):\n \n res = True\n\n for sol_1, sol_2 in zip(sol1, sol2):\n if np.ndim(sol_1) != 0 and np.ndim(sol_2) != 0:\n res &= _dist(sol_1, sol_2) < prec\n elif np.ndim(sol_1) != 0 and np.ndim(sol_2) == 0:\n return False\n elif np.ndim(sol_1) == 0 and np.ndim(sol_2) != 0:\n return False\n\n return res","input":"[array([0., 0.]), array([3., 0.]), array([3.5 , 1.93649167]), array([ 0.16666667, -0.9860133 ])], [array([0., 0.]), array([3., 0.]), array([3.5 , 1.93649167]), array([0.16666667, 0.9860133 ])], 0.1","output":"False","cyclomatic_complexity":5,"code_length":10,"category":"Medium"}
{"index":1535,"idx":180,"code":"def _process_namespace(name, namespaces, ns_sep=':', attr_prefix='@'):\n if not namespaces:\n return name\n try:\n ns, name = name.rsplit(ns_sep, 1)\n except ValueError:\n pass\n else:\n ns_res = namespaces.get(ns.strip(attr_prefix))\n name = '{}{}{}{}'.format(\n attr_prefix if ns.startswith(attr_prefix) else '',\n ns_res, ns_sep, name) if ns_res else name\n return name","input":"'http:\/\/defaultns.com\/:root', {'http:\/\/defaultns.com\/': '', 'http:\/\/a.com\/': 'a', 'http:\/\/b.com\/': 'b'}, ':', '@'","output":"'root'","cyclomatic_complexity":4,"code_length":13,"category":"Medium"}
{"index":1545,"idx":181,"code":"def check_data(a, b):\n if not isinstance(a, np.ndarray):\n a = np.array(a)\n\n if not isinstance(b, np.ndarray):\n b = np.array(b)\n\n if type(a) != type(b):\n raise ValueError(\"Type mismatch: %s and %s\" % (type(a), type(b)))\n\n if a.size != b.size:\n raise ValueError(\"Arrays must be equal in length.\")\n return a, b","input":"[1, 2, 3], [3, 2, 1]","output":"(array([1, 2, 3]), array([3, 2, 1]))","cyclomatic_complexity":5,"code_length":10,"category":"Medium"}
{"index":1548,"idx":182,"code":"def logloss(actual, predicted):\n predicted = np.clip(predicted, EPS, 1 - EPS)\n loss = -np.sum(actual * np.log(predicted))\n return loss \/ float(actual.shape[0])","input":"array([1]), array([1])","output":"9.992007221626415e-16","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1549,"idx":183,"code":"def clasifier(optimizer):\n X, y = make_classification(\n n_samples=1000, n_features=100, n_informative=75, random_state=1111, n_classes=2, class_sep=2.5\n )\n y = one_hot(y)\n\n X -= np.mean(X, axis=0)\n X \/= np.std(X, axis=0)\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=1111)\n\n model = NeuralNet(\n layers=[\n Dense(128, Parameters(init=\"uniform\")),\n Activation(\"relu\"),\n Dropout(0.5),\n Dense(64, Parameters(init=\"normal\")),\n Activation(\"relu\"),\n Dense(2),\n Activation(\"softmax\"),\n ],\n loss=\"categorical_crossentropy\",\n optimizer=optimizer,\n metric=\"accuracy\",\n batch_size=64,\n max_epochs=10,\n )\n model.fit(X_train, y_train)\n predictions = model.predict(X_test)\n return roc_auc_score(y_test[:, 0], predictions[:, 0])","input":"{rho=0.95, eps=1e-08, lr=1.0}","output":"0.92549786628734","cyclomatic_complexity":1,"code_length":27,"category":"Super Easy"}
{"index":1567,"idx":184,"code":"def str2datetime(string):\n \n\n if string == \"0000-00-00T24:60:60Z\":\n return None\n\n ms = string[20:-1]\n ms += \"000000\"[:6 - len(ms)]\n return datetime.datetime(\n int(string[:4]),\n int(string[5:7]),\n int(string[8:10]),\n int(string[11:13]),\n int(string[14:16]),\n int(string[17:19]),\n int(ms))","input":"'1970-01-01T00:00:00.0Z'","output":"datetime.datetime(1970, 1, 1, 0, 0)","cyclomatic_complexity":2,"code_length":13,"category":"Super Easy"}
{"index":1568,"idx":185,"code":"def flatten(d, parent_key=\"\", sep=\"\/\") -> Dict[str, Any]:\n \n items: List[Tuple[str, List[str]]] = []\n for k, v in d.items():\n new_key = parent_key + sep + k if parent_key else k\n if isinstance(v, MutableMapping):\n items.extend(flatten(v, new_key, sep=sep).items())\n else:\n items.append((new_key, v))\n return dict(items)","input":"{'aprtoapy': [], 'il': []}, 'crypto\/tools', '\/'","output":"{'crypto\/tools\/aprtoapy': [], 'crypto\/tools\/il': []}","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":1578,"idx":186,"code":"def load_json_dict(filename, *args):\n \n data = {}\n if os.path.exists(filename):\n lock.acquire()\n with open(filename, \"r\") as f:\n try:\n data = _json.load(f)\n if not isinstance(data, dict):\n data = {}\n except:\n data = {} \n lock.release()\n if args:\n return {key: data[key] for key in args if key in data}\n return data","input":"'\/home\/XXX\/.plotly\/.config', ()","output":"{'plotly_domain': 'https:\/\/plot.ly', 'plotly_streaming_domain': 'stream.plot.ly', 'plotly_api_domain': 'https:\/\/api.plot.ly', 'plotly_ssl_verification': True, 'plotly_proxy_authorization': False, 'world_readable': True, 'sharing': 'public', 'auto_open': True}","cyclomatic_complexity":6,"code_length":15,"category":"Hard"}
{"index":1598,"idx":187,"code":"def export_data(self) -> typing.Dict[str, dict]:\n \n\n nested_ip_objects = dict()\n\n if self.__children_ip_object and None in self.__children_ip_object:\n children_per_version = dict()\n for child in self.__children_ip_object[None]:\n version_set = children_per_version.setdefault(\n child.version, set()\n )\n version_set.add(child)\n\n for version in children_per_version:\n version_nest = nested_ip_objects.setdefault(version, dict())\n for child in children_per_version[version]:\n version_nest[child] = self.__gather_nested_children(child)\n\n return dict({\n \"description\": dict(self.__description),\n \"nested_ip_objects\": nested_ip_objects,\n })","input":"AddressSpace(_AddressSpace__strict=True, _AddressSpace__description={}, _AddressSpace__networks={}, _AddressSpace__addresses={}, _AddressSpace__parent_supernet={}, _AddressSpace__children_ip_object={None: set()}), {}, {None: set()}, {}, {}, {}, True","output":"{'description': {}, 'nested_ip_objects': {}}","cyclomatic_complexity":5,"code_length":17,"category":"Medium"}
{"index":1605,"idx":188,"code":"def get_idx(ndim, axis=None, axis_idx=None):\n s = [midx] * ndim\n if axis is not None:\n if hasattr(axis, \"__iter__\"):\n for ax, axidx in zip(axis, axis_idx):\n s[ax] = axidx\n else:\n s[axis] = axis_idx\n return tuple(s)","input":"1, 0, slice(None, -2, None)","output":"(slice(None, -2, None),)","cyclomatic_complexity":4,"code_length":9,"category":"Medium"}
{"index":1607,"idx":189,"code":"def det_hess(u):\n \n ndim = np.ndim(u)\n inshape = np.asarray(u.shape)\n outshape = list(inshape - 2)\n\n \n hess_unarranged = np.zeros([ndim, ndim] + outshape)\n for i in range(ndim):\n for j in range(i,ndim):\n grad2_val = grad2(u, (i,j))\n hess_unarranged[i,j] = grad2_val\n hess_unarranged[j,i] = grad2_val\n\n \n perm_idx = list(range(2,ndim+2)) + list(range(2))\n hess = np.transpose(hess_unarranged, perm_idx)\n\n \n return np.linalg.det(hess)","input":"array([ 0., 1., 4., 9., 16., 25., 36., 49., 64., 81., 100., 121., 144., 169., 196., 225., 256., 289., 324., 361., 400., 441., 484., 529., 576., 625., 676., 729., 784., 841., 900., 961.])","output":"array([2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.])","cyclomatic_complexity":3,"code_length":13,"category":"Easy"}
{"index":1609,"idx":190,"code":"def _get_default_expanded_coordinate(shape, ndim):\n x_coords = []\n for i in range(ndim):\n idx = [None] * ndim\n idx[i] = slice(None, None, None)\n x_coords.append(np.arange(shape[i])[tuple(idx)])\n return x_coords","input":"array([92]), 1","output":"[array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91])]","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":1610,"idx":191,"code":"def _pad_conserve_grads(phi):\n \n ndim = np.ndim(phi)\n pw = [1, 1]\n pp = np.pad(phi, [tuple(pw)]*ndim, mode=\"constant\")\n for dim in range(ndim):\n \n idx_pad0_l = _get_idx(ndim, dim, slice(pw[0], pw[0]+1, None))\n idx_pad0_r = _get_idx(ndim, dim, slice(pw[0]+1, pw[0]+2, None))\n idx_pad0 = _get_idx(ndim, dim, slice(pw[0], pw[0]+1, None))\n idx_pad0_fill = _get_idx(ndim, dim, slice(None, pw[0], None))\n idx_pad1_l = _get_idx(ndim, dim, slice(-pw[1]-2, -pw[1]-1, None))\n idx_pad1_r = _get_idx(ndim, dim, slice(-pw[1]-1, -pw[1], None))\n idx_pad1 = _get_idx(ndim, dim, slice(-pw[1]-1, -pw[1], None))\n idx_pad1_fill = _get_idx(ndim, dim, slice(-pw[1], None, None))\n\n \n grad0 = pp[idx_pad0_r] - pp[idx_pad0_l] \n grad1 = pp[idx_pad1_r] - pp[idx_pad1_l]\n pad_arange0 = np.arange(-pw[0],0) \n pad_arange1 = np.arange(1,pw[0]+1)\n pad0 = pad_arange0 * grad0 + pp[idx_pad0] \n pad1 = pad_arange1 * grad1 + pp[idx_pad1]\n pp[idx_pad0_fill] = pad0\n pp[idx_pad1_fill] = pad1\n\n return pp","input":"array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])","output":"array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])","cyclomatic_complexity":2,"code_length":22,"category":"Super Easy"}
{"index":1611,"idx":192,"code":"def _get_idx(ndim, dim, s, defidx=None):\n defidx = slice(None, None, None) if defidx is None else defidx\n idx = [defidx] * ndim\n idx[dim] = s\n return tuple(idx)","input":"1, 0, slice(1, 2, None), None","output":"(slice(1, 2, None),)","cyclomatic_complexity":1,"code_length":5,"category":"Super Easy"}
{"index":1619,"idx":193,"code":"def _makeComplementTable(complementData):\n \n table = list(range(256))\n for _from, to in complementData.items():\n table[ord(_from[0].lower())] = ord(to[0].lower())\n table[ord(_from[0].upper())] = ord(to[0].upper())\n return ''.join(map(chr, table))","input":"{'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'M': 'K', 'R': 'Y', 'W': 'W', 'S': 'S', 'Y': 'R', 'K': 'M', 'V': 'B', 'H': 'D', 'D': 'H', 'B': 'V', 'X': 'X', 'N': 'N'}","output":"'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-.\/0123456789:;<=>?@TVGHEFCDIJMLKNOPQYSAUBWXRZ[\\\\]^_`tvghefcdijmlknopqysaubwxrz{|}~\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\u00a1\u00a2\u00a3\u00a4\u00a5\u00a6\u00a7\u00a8\u00a9\u00aa\u00ab\u00ac\\xad\u00ae\u00af\u00b0\u00b1\u00b2\u00b3\u00b4\u00b5\u00b6\u00b7\u00b8\u00b9\u00ba\u00bb\u00bc\u00bd\u00be\u00bf\u00c0\u00c1\u00c2\u00c3\u00c4\u00c5\u00c6\u00c7\u00c8\u00c9\u00ca\u00cb\u00cc\u00cd\u00ce\u00cf\u00d0\u00d1\u00d2\u00d3\u00d4\u00d5\u00d6\u00d7\u00d8\u00d9\u00da\u00db\u00dc\u00dd\u00de\u00df\u00e0\u00e1\u00e2\u00e3\u00e4\u00e5\u00e6\u00e7\u00e8\u00e9\u00ea\u00eb\u00ec\u00ed\u00ee\u00ef\u00f0\u00f1\u00f2\u00f3\u00f4\u00f5\u00f6\u00f7\u00f8\u00f9\u00fa\u00fb\u00fc\u00fd\u00fe\u00ff'","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":1664,"idx":194,"code":"def find_extension(codec):\n \n if codec in extensions_dict:\n \n return codec\n\n for ext, infos in extensions_dict.items():\n if codec in infos.get(\"codec\", []):\n return ext\n raise ValueError(\n \"The audio_codec you chose is unknown by MoviePy. \"\n \"You should report this. In the meantime, you can \"\n \"specify a temp_audiofile with the right extension \"\n \"in write_videofile.\"\n )","input":"'libmp3lame'","output":"'mp3'","cyclomatic_complexity":4,"code_length":12,"category":"Medium"}
{"index":1683,"idx":195,"code":"def version_compare(v1, v2):\n \n\n arr1 = v1.split(\".\")\n arr2 = v2.split(\".\")\n n = len(arr1)\n m = len(arr2)\n\n \n arr1 = [int(i) for i in arr1]\n arr2 = [int(i) for i in arr2]\n\n \n \n if n > m:\n for i in range(m, n):\n arr2.append(0)\n elif m > n:\n for i in range(n, m):\n arr1.append(0)\n\n \n \n for i in range(len(arr1)):\n if arr1[i] > arr2[i]:\n return 1\n elif arr2[i] > arr1[i]:\n return -1\n return 0","input":"'3.8.18', '3.8.27'","output":"-1","cyclomatic_complexity":8,"code_length":19,"category":"Hard"}
{"index":1684,"idx":196,"code":"def parse_access_method(access_method: str):\n num_workers = 0\n scheduler = \"threaded\"\n download = access_method.startswith(\"download\")\n local = access_method.startswith(\"local\")\n if download or local:\n split = access_method.split(\":\")\n if len(split) == 1:\n split.extend((\"threaded\", \"0\"))\n elif len(split) == 2:\n split.append(\"threaded\" if split[1].isnumeric() else \"0\")\n elif len(split) >= 3:\n num_integers = sum(1 for i in split if i.isnumeric())\n if num_integers != 1 or len(split) > 3:\n raise ValueError(\n \"Invalid access_method format. Expected format is one of the following: {download, download:scheduler, download:num_workers, download:scheduler:num_workers, download:num_workers:scheduler}\"\n )\n\n access_method = \"download\" if download else \"local\"\n num_worker_index = 1 if split[1].isnumeric() else 2\n scheduler_index = 3 - num_worker_index\n num_workers = int(split[num_worker_index])\n scheduler = split[scheduler_index]\n return access_method, num_workers, scheduler","input":"'download'","output":"('download', 0, 'threaded')","cyclomatic_complexity":6,"code_length":23,"category":"Hard"}
{"index":1711,"idx":197,"code":"def write_shape_info(shape_info, buffer, offset) -> int:\n \n if shape_info.ndim == 1:\n offset += 8\n else:\n buffer[offset : offset + 8] = struct.pack(\"<ii\", *shape_info.shape)\n offset += 8\n\n buffer[offset : offset + shape_info.nbytes] = shape_info.tobytes()\n offset += shape_info.nbytes\n return offset","input":"array([[2, 3]], dtype=uint32), bytearray(b'\\x063.8.18\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'), 7","output":"23","cyclomatic_complexity":2,"code_length":9,"category":"Super Easy"}
{"index":1715,"idx":198,"code":"def _get_new_player_rack_list(self, num_players):\n player_rack_list = []\n\n for _ in range(num_players):\n this_rack = []\n for _ in range(config.PLAYER_RACK_SIZE):\n this_tile = self._draw_random_tile()\n this_rack.append(this_tile)\n\n player_rack_list.append(this_rack)\n\n return player_rack_list","input":"REPR FAILED, 4, [*, *, A, A, A, A, A, A, A, A, A, B, B, C, C, D, D, D, D, E, E, E, E, E, E, E, E, E, E, E, E, F, F, G, G, G, H, H, I, I, I, I, I, I, I, I, I, J, K, L, L, L, L, M, M, N, N, N, N, N, N, O, O, O, O, O, O, O, O, P, P, Q, R, R, R, R, R, R, S, S, S, S, T, T, T, T, T, T, U, U, U, U, V, V, W, W, X, Y, Y, Z]","output":"[[U, A, E, F, K, H, V], [U, N, E, I, N, C, I], [B, H, T, Q, O, D, T], [A, R, B, O, O, N, I]]","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":1716,"idx":199,"code":"def _draw_random_tile(self):\n random_index = random.randrange(0, len(self.tile_bag))\n selected_tile = self.tile_bag.pop(random_index)\n\n return selected_tile","input":"REPR FAILED, [*, *, A, A, A, A, A, A, A, A, A, B, B, C, C, D, D, D, D, E, E, E, E, E, E, E, E, E, E, E, E, F, F, G, G, G, H, H, I, I, I, I, I, I, I, I, I, J, K, L, L, L, L, M, M, N, N, N, N, N, N, O, O, O, O, O, O, O, O, P, P, Q, R, R, R, R, R, R, S, S, S, S, T, T, T, T, T, T, U, U, U, U, V, V, W, W, X, Y, Y, Z]","output":"U","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1718,"idx":200,"code":"def move_is_sublist(letter_list_1, letter_list_2):\n letter_counter_1 = collections.Counter(letter_list_1)\n letter_counter_2 = collections.Counter(letter_list_2)\n for letter, cardinality in letter_counter_1.items():\n if cardinality > letter_counter_2[letter]:\n \n return False\n\n return True","input":"[1, 2, 3], [1, 2, 3, 4]","output":"True","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":1721,"idx":201,"code":"def get_word_letter_location_set(word, start_location, is_vertical_move):\n letter_location_set = set()\n next_location_func = get_next_location_function(\n use_positive_seek=True,\n use_vertical_words=is_vertical_move\n )\n\n current_location = start_location\n word_iterator = iter(word)\n for character in word_iterator:\n if character == '(': \n character = next(word_iterator, None)\n while character != ')':\n current_location = next_location_func(current_location)\n character = next(word_iterator, None)\n\n character = next(word_iterator, None)\n\n if character:\n letter_location_set.add((character, current_location))\n current_location = next_location_func(current_location)\n\n return letter_location_set","input":"'BAKER', ('h', 8), False","output":"{('K', ('j', 8)), ('B', ('h', 8)), ('A', ('i', 8)), ('E', ('k', 8)), ('R', ('l', 8))}","cyclomatic_complexity":5,"code_length":19,"category":"Medium"}
{"index":1723,"idx":202,"code":"def move_is_legal(board, move_number, letter_location_set, player_rack=None):\n letter_list = [letter for letter, _ in letter_location_set]\n location_set = set(location for _, location in letter_location_set)\n\n return_bool = (\n move_is_rack_size_or_less(location_set) and\n move_does_not_misalign_tiles(location_set) and\n move_is_not_out_of_bounds(location_set) and\n all_move_tiles_connected(board, location_set) and\n move_does_not_stack_tiles(letter_list, location_set) and\n move_does_not_cover_tiles(board, location_set) and\n move_touches_tile(move_number, board, location_set)\n )\n\n if player_rack:\n player_rack_letter_list = [tile.letter for tile in player_rack]\n return_bool = return_bool and move_is_sublist(letter_list,\n player_rack_letter_list)\n\n return return_bool","input":" abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______\u2605_______9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, 0, {('K', ('j', 8)), ('B', ('h', 8)), ('A', ('i', 8)), ('E', ('k', 8)), ('R', ('l', 8))}, [Q, E, O, S, G, H, E, B, A, K, E, R]","output":"True","cyclomatic_complexity":2,"code_length":17,"category":"Super Easy"}
{"index":1724,"idx":203,"code":"def move_is_not_out_of_bounds(location_set):\n for location in location_set:\n if location_is_out_of_bounds(location):\n \n return False\n\n return True","input":"{('j', 8), ('l', 8), ('h', 8), ('i', 8), ('k', 8)}","output":"True","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":1725,"idx":204,"code":"def all_move_tiles_connected(board, location_set):\n column_list = [column for column, _ in location_set]\n row_list = [row for _, row in location_set]\n move_is_vertical = (len(set(column_list)) == 1)\n\n if move_is_vertical:\n this_column = column_list[0]\n for this_row in range(min(row_list), max(row_list) + 1):\n this_tile = board[(this_column, this_row)]\n if not (this_tile or (this_column, this_row) in location_set):\n \n \n\n return False\n else:\n column_range = range(\n config.LETTER_CODE_DICT[min(column_list)],\n config.LETTER_CODE_DICT[max(column_list)] + 1\n )\n\n this_row = row_list[0]\n for this_column_num in column_range:\n this_column = chr(this_column_num)\n this_tile = board[(this_column, this_row)]\n if not (this_tile or (this_column, this_row) in location_set):\n \n \n\n return False\n\n return True","input":" abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______\u2605_______9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {('j', 8), ('l', 8), ('h', 8), ('i', 8), ('k', 8)}","output":"True","cyclomatic_complexity":6,"code_length":22,"category":"Hard"}
{"index":1726,"idx":205,"code":"def move_does_not_cover_tiles(board, location_set):\n for location in location_set:\n if board[location]:\n \n \n \n\n return False\n\n return True","input":" abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______\u2605_______9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {('j', 8), ('l', 8), ('h', 8), ('i', 8), ('k', 8)}","output":"True","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":1727,"idx":206,"code":"def move_touches_tile(move_number, board, location_set):\n if move_number == 0:\n if board.start_square_location in location_set:\n return True\n else:\n for this_location in location_set:\n if location_touches_tile(board, this_location):\n return True\n\n \n return False","input":"1, abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______SCRAB___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {('i', 13), ('i', 10), ('i', 9), ('i', 12), ('i', 11)}","output":"True","cyclomatic_complexity":5,"code_length":9,"category":"Medium"}
{"index":1728,"idx":207,"code":"def get_rack_tile_index(player_rack, move_letter):\n for i, rack_tile in enumerate(player_rack):\n if rack_tile.letter == move_letter:\n return i\n\n return None","input":"[Q, E, O, S, G, H, E, B, A, K, E, R], 'K'","output":"9","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":1730,"idx":208,"code":"def get_word_location_set(board, initial_location, use_vertical_words):\n word_location_set = set()\n\n for use_positive_seek in [True, False]: \n current_location = initial_location \n current_tile = board[current_location]\n next_location_func = get_next_location_function(use_positive_seek,\n use_vertical_words)\n\n while current_tile:\n word_location_set.add(current_location)\n current_location = next_location_func(current_location)\n if location_is_out_of_bounds(current_location):\n current_tile = None\n else:\n current_tile = board[current_location]\n\n if len(word_location_set) > 1: \n return frozenset(word_location_set) \n else: \n return frozenset()","input":" abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______BAKER___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, ('j', 8), True","output":"frozenset()","cyclomatic_complexity":5,"code_length":18,"category":"Medium"}
{"index":1731,"idx":209,"code":"def get_word_set_total_score(board, word_set, num_move_locations):\n total_score = 0\n word_score = 0\n\n for word_location_set in word_set:\n word_score = 0\n word_multiplier = 1\n\n for location in word_location_set:\n square = board.board_square_dict[location]\n word_multiplier *= square.word_multiplier\n word_score += square.tile.point_value * square.letter_multiplier\n\n word_score *= word_multiplier\n total_score += word_score\n\n if num_move_locations == config.PLAYER_RACK_SIZE:\n total_score += config.BINGO_SCORE\n\n return total_score","input":" abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______BAKER___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, {frozenset(), frozenset({('h', 8), ('j', 8), ('l', 8), ('i', 8), ('k', 8)})}, 5","output":"24","cyclomatic_complexity":4,"code_length":15,"category":"Medium"}
{"index":1734,"idx":210,"code":"def location_touches_tile(board, location):\n adjacent_location_set = get_adjacent_location_set(location)\n for adjacent_location in adjacent_location_set:\n if board[adjacent_location]:\n return True\n\n return False","input":" abcdefghijklmno1 _______________2 _______________3 _______________4 _______________5 _______________6 _______________7 _______________8 _______SCRAB___9 _______________10_______________11_______________12_______________13_______________14_______________15_______________, ('i', 13)","output":"False","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":1737,"idx":211,"code":"def rolling_mean_by_h(x, h, w, name):\n \n \n df = pd.DataFrame({'x': x, 'h': h})\n df2 = (\n df.groupby('h').agg(['sum', 'count']).reset_index().sort_values('h')\n )\n xs = df2['x']['sum'].values\n ns = df2['x']['count'].values\n hs = df2.h.values\n\n trailing_i = len(df2) - 1\n x_sum = 0\n n_sum = 0\n \n res_x = np.empty(len(df2))\n\n \n for i in range(len(df2) - 1, -1, -1):\n x_sum += xs[i]\n n_sum += ns[i]\n while n_sum >= w:\n \n \n excess_n = n_sum - w\n excess_x = excess_n * xs[i] \/ ns[i]\n res_x[trailing_i] = (x_sum - excess_x)\/ w\n x_sum -= xs[trailing_i]\n n_sum -= ns[trailing_i]\n trailing_i -= 1\n\n res_h = hs[(trailing_i + 1):]\n res_x = res_x[(trailing_i + 1):]\n\n return pd.DataFrame({'horizon': res_h, name: res_x})","input":"array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 1, 'x'","output":" horizon x0 0 0.01 1 1.02 2 2.03 3 3.04 4 4.05 5 5.06 6 6.07 7 7.08 8 8.09 9 9.0","cyclomatic_complexity":3,"code_length":25,"category":"Easy"}
{"index":1738,"idx":212,"code":"def rolling_median_by_h(x, h, w, name):\n \n \n df = pd.DataFrame({'x': x, 'h': h})\n grouped = df.groupby('h')\n df2 = grouped.size().reset_index().sort_values('h')\n hs = df2['h']\n\n res_h = []\n res_x = []\n \n i = len(hs) - 1\n while i >= 0:\n h_i = hs[i]\n xs = grouped.get_group(h_i).x.tolist()\n\n \n next_idx_to_add = np.array(h == h_i).argmax() - 1\n while (len(xs) < w) and (next_idx_to_add >= 0):\n \n \n xs.append(x[next_idx_to_add])\n next_idx_to_add -= 1\n if len(xs) < w:\n \n break\n res_h.append(hs[i])\n res_x.append(np.median(xs))\n i -= 1\n res_h.reverse()\n res_x.reverse()\n return pd.DataFrame({'horizon': res_h, name: res_x})","input":"array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), 1, 'x'","output":" horizon x0 0 0.01 1 1.02 2 2.03 3 3.04 4 4.05 5 5.06 6 6.07 7 7.08 8 8.09 9 9.0","cyclomatic_complexity":4,"code_length":23,"category":"Medium"}
{"index":1766,"idx":213,"code":"def create_request_parameters(parent, request_model, params=None, index=None):\n \n if params is None:\n params = {}\n\n for param in request_model.params:\n source = param.source\n target = param.target\n\n if source == 'identifier':\n \n value = getattr(parent, xform_name(param.name))\n elif source == 'data':\n \n \n value = get_data_member(parent, param.path)\n elif source in ['string', 'integer', 'boolean']:\n \n value = param.value\n elif source == 'input':\n \n continue\n else:\n raise NotImplementedError(f'Unsupported source type: {source}')\n\n build_param_structure(params, target, value, index)\n\n return params","input":"dynamodb.Table(name='MyTable'), {_definition=OrderedDict([('operation', 'Scan'), ('params', [OrderedDict([('target', 'TableName'), ('source', 'identifier'), ('name', 'Name')])])]), operation='Scan'}, None, None","output":"{'TableName': 'MyTable'}","cyclomatic_complexity":7,"code_length":18,"category":"Hard"}
{"index":1777,"idx":214,"code":"def suggest_type(full_text, text_before_cursor):\n \n\n word_before_cursor = last_word(text_before_cursor,\n include='many_punctuations')\n\n identifier = None\n\n \n try:\n \n \n \n \n \n if word_before_cursor:\n if word_before_cursor.endswith(\n '(') or word_before_cursor.startswith('\\\\'):\n parsed = sqlparse.parse(text_before_cursor)\n else:\n parsed = sqlparse.parse(\n text_before_cursor[:-len(word_before_cursor)])\n\n \n \n \n p = sqlparse.parse(word_before_cursor)[0]\n\n if p.tokens and isinstance(p.tokens[0], Identifier):\n identifier = p.tokens[0]\n else:\n parsed = sqlparse.parse(text_before_cursor)\n except (TypeError, AttributeError):\n return [{'type': 'keyword'}]\n\n if len(parsed) > 1:\n \n \n \n current_pos = len(text_before_cursor)\n stmt_start, stmt_end = 0, 0\n\n for statement in parsed:\n stmt_len = len(str(statement))\n stmt_start, stmt_end = stmt_end, stmt_end + stmt_len\n\n if stmt_end >= current_pos:\n text_before_cursor = full_text[stmt_start:current_pos]\n full_text = full_text[stmt_start:]\n break\n\n elif parsed:\n \n statement = parsed[0]\n else:\n \n statement = None\n\n \n if statement:\n \n \n tok1 = statement.token_first()\n if tok1 and (tok1.value == 'source' or tok1.value.startswith('\\\\')):\n return suggest_special(text_before_cursor)\n\n last_token = statement and statement.token_prev(len(statement.tokens))[1] or ''\n\n return suggest_based_on_last_token(last_token, text_before_cursor,\n full_text, identifier)","input":"'SELECT FROM tabl', 'SELECT '","output":"[{'type': 'column', 'tables': [(None, 'tabl', None)]}, {'type': 'function', 'schema': []}, {'type': 'alias', 'aliases': ['tabl']}, {'type': 'keyword'}]","cyclomatic_complexity":12,"code_length":40,"category":"Hard"}
{"index":1784,"idx":215,"code":"def parse_special_command(sql):\n command, _, arg = sql.partition(' ')\n verbose = '+' in command\n command = command.strip().replace('+', '')\n return (command, verbose, arg.strip())","input":"'\\\\. '","output":"('\\\\.', False, '')","cyclomatic_complexity":1,"code_length":5,"category":"Super Easy"}
{"index":1789,"idx":216,"code":"def strip_matching_quotes(s):\n \n if (isinstance(s, basestring) and len(s) >= 2 and\n s[0] == s[-1] and s[0] in ('\"', \"'\")):\n s = s[1:-1]\n return s","input":"'\"May the force be with you.\"'","output":"'May the force be with you.'","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":1790,"idx":217,"code":"def format_uptime(uptime_in_seconds):\n \n\n m, s = divmod(int(uptime_in_seconds), 60)\n h, m = divmod(m, 60)\n d, h = divmod(h, 24)\n\n uptime_values = []\n\n for value, unit in ((d, 'days'), (h, 'hours'), (m, 'min'), (s, 'sec')):\n if value == 0 and not uptime_values:\n \n \n continue\n elif value == 1 and unit.endswith('s'):\n \n unit = unit[:-1]\n uptime_values.append('{0} {1}'.format(value, unit))\n\n uptime = ' '.join(uptime_values)\n return uptime","input":"59","output":"'59 sec'","cyclomatic_complexity":4,"code_length":13,"category":"Medium"}
{"index":1800,"idx":218,"code":"def _grid(string: str, attr: Mapping[str, str]) -> Grid:\n method = None\n try:\n if attr[\"source\"] in (\"grid\", \"grid_l\"):\n method = \"linear\"\n elif attr[\"source\"] in (\"grid_s\", \"grid_c\"):\n method = \"spline\"\n elif attr[\"source\"] in (\"grid_q\", \"grid_n\"):\n method = \"nearest\"\n except KeyError:\n if re.fullmatch(r\"\\S[\\S ]*\\.nc\", string):\n method = \"linear\"\n if method:\n return Grid(\n file=string, x=attr.get(\"x\", \"lon\"), y=attr.get(\"y\", \"lat\"), method=method\n )\n \n raise TextParseError(f\"'{string}' does not represent a grid\")","input":"'abc.nc', {}","output":"Grid(file='abc.nc', x='lon', y='lat', method='linear')","cyclomatic_complexity":8,"code_length":17,"category":"Hard"}
{"index":1803,"idx":219,"code":"def _time(string: str) -> datetime:\n formats = [\n \"%Y-%m-%dT%H:%M:%S\",\n \"%Y-%m-%dT%H:%M\",\n \"%Y-%m-%dT%H\",\n \"%Y-%m-%dT\",\n \"%Y-%m-%d\",\n ]\n for format_ in formats:\n try:\n return datetime.strptime(string, format_)\n except ValueError:\n pass\n \n raise ValueError(f\"time data '{string}' does not match format '%Y-%m-%dT%H:%M:%S'\")","input":"'2016-03-01T21:00:11'","output":"datetime.datetime(2016, 3, 1, 21, 0, 11)","cyclomatic_complexity":4,"code_length":14,"category":"Medium"}
{"index":1804,"idx":220,"code":"def contains_nan(stack: MutableSequence[NumberOrArray]) -> bool:\n for item in stack:\n try:\n if math.isnan(item):\n return True\n except TypeError:\n pass\n return False","input":"[-2]","output":"False","cyclomatic_complexity":5,"code_length":8,"category":"Medium"}
{"index":1805,"idx":221,"code":"def contains_array(stack: MutableSequence[NumberOrArray]) -> bool:\n for item in stack:\n if isinstance(item, np.ndarray):\n return True\n return False","input":"[-2]","output":"False","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":1806,"idx":222,"code":"def _get_x(stack: MutableSequence[NumberOrArray]) -> NumberOrArray:\n if not stack:\n raise StackUnderflowError(\n \"attempted to get element from the 'stack' but the stack is empty\"\n )\n return stack.pop()","input":"[1]","output":"1","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":1809,"idx":223,"code":"def _simulate(self) -> Tuple[int, int]:\n \n inputs = 0\n outputs = 0\n for token_ in self._tokens:\n outputs -= token_.pops\n inputs = max(inputs, -outputs)\n outputs += token_.puts\n return inputs, outputs + inputs","input":"Expression([Literal(1)]), Literal(1)","output":"(0, 1)","cyclomatic_complexity":2,"code_length":8,"category":"Super Easy"}
{"index":1810,"idx":224,"code":"def contains_sublist(list_: List[Any], sublist: List[Any]) -> bool:\n \n \n if not sublist:\n return False\n for i in range(len(list_)):\n if list_[i] == sublist[0] and list_[i : i + len(sublist)] == sublist:\n return True\n return False","input":"[1, 2, 3, 4], [1, 2]","output":"True","cyclomatic_complexity":4,"code_length":7,"category":"Medium"}
{"index":1811,"idx":225,"code":"def delete_sublist(list_: List[Any], sublist: List[Any]) -> List[Any]:\n \n if not sublist:\n return list_[:]\n for i in range(len(list_)):\n if list_[i] == sublist[0] and list_[i : i + len(sublist)] == sublist:\n return list_[:i] + list_[i + len(sublist) :]\n return list_[:]","input":"[1, 2, 3, 4], [1, 2]","output":"[3, 4]","cyclomatic_complexity":4,"code_length":7,"category":"Medium"}
{"index":1817,"idx":226,"code":"def bounded_product(sequence, n=None, seed=None):\n \n p = list(itertools.product(*sequence))\n if seed is not None:\n random.seed(seed)\n random.shuffle(p)\n return p if n is None else p[:n]","input":"([{'type': 'adam', 'params': {'lr': 0.0006}}, {'type': 'onebitadam', 'params': {'lr': 0.0006}}, {'type': 'cpu_adam', 'params': {'lr': 0.0006}}, {'type': 'cpu_torch_adam', 'params': {'lr': 0.0006}}, {'type': 'sm3', 'params': {'lr': 0.0006}}, {'type': 'lion', 'params': {'lr': 0.0006}}, {'type': 'madgrad_wd', 'params': {'lr': 0.0006}}],), 50, None","output":"[({'type': 'cpu_adam', 'params': {'lr': 0.0006}},), ({'type': 'sm3', 'params': {'lr': 0.0006}},), ({'type': 'onebitadam', 'params': {'lr': 0.0006}},), ({'type': 'lion', 'params': {'lr': 0.0006}},), ({'type': 'adam', 'params': {'lr': 0.0006}},), ({'type': 'madgrad_wd', 'params': {'lr': 0.0006}},), ({'type': 'cpu_torch_adam', 'params': {'lr': 0.0006}},)]","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":1827,"idx":227,"code":"def expand_attention_types(attention_config, num_layers):\n \n \n if all([isinstance(i, str) for i in attention_config]):\n return attention_config\n newlist = []\n for item in attention_config:\n \n if item[1] == \"all\":\n assert num_layers % len(item[0]) == 0, (\n f\"Number of layers ({num_layers}) is not divisible by the length \"\n f\"of pattern: {item[0]}\"\n )\n return item[0] * (num_layers \/\/ len(item[0]))\n for _ in range(item[1]):\n newlist.extend(item[0])\n return newlist","input":"[[['global'], 2]], 2","output":"['global', 'global']","cyclomatic_complexity":5,"code_length":14,"category":"Medium"}
{"index":1843,"idx":228,"code":"def get_args(input_args=None):\n parser = argparse.ArgumentParser()\n group = parser.add_argument_group(title=\"input data\")\n group.add_argument(\n \"--input\",\n type=str,\n required=True,\n help=\"Path to input jsonl files or lmd archive(s) - if using multiple archives, put them in a comma separated \"\n \"list\",\n )\n group.add_argument(\n \"--jsonl-keys\",\n nargs=\"+\",\n default=[\"text\"],\n help=\"space separate listed of keys to extract from jsonl. Defa\",\n )\n group.add_argument(\n \"--num-docs\",\n default=None,\n help=\"Optional: Number of documents in the input data (if known) for an accurate progress bar.\",\n type=int,\n )\n group = parser.add_argument_group(title=\"tokenizer\")\n group.add_argument(\n \"--tokenizer-type\",\n type=str,\n required=True,\n choices=[\n \"HFGPT2Tokenizer\",\n \"HFTokenizer\",\n \"GPT2BPETokenizer\",\n \"CharLevelTokenizer\",\n \"TiktokenTokenizer\",\n \"SPMTokenizer\",\n ],\n help=\"What type of tokenizer to use.\",\n )\n group.add_argument(\n \"--vocab-file\", type=str, default=None, help=\"Path to the vocab file\"\n )\n group.add_argument(\n \"--merge-file\",\n type=str,\n default=None,\n help=\"Path to the BPE merge file (if necessary).\",\n )\n group.add_argument(\n \"--append-eod\",\n action=\"store_true\",\n help=\"Append an <eod> token to the end of a document.\",\n )\n group.add_argument(\"--ftfy\", action=\"store_true\", help=\"Use ftfy to clean text\")\n group = parser.add_argument_group(title=\"output data\")\n group.add_argument(\n \"--output-prefix\",\n type=str,\n required=True,\n help=\"Path to binary output file without suffix\",\n )\n group.add_argument(\n \"--dataset-impl\",\n type=str,\n default=\"mmap\",\n choices=[\"lazy\", \"cached\", \"mmap\"],\n help=\"Dataset implementation to use. Default: mmap\",\n )\n\n group = parser.add_argument_group(title=\"runtime\")\n group.add_argument(\n \"--workers\", type=int, default=1, help=\"Number of worker processes to launch\"\n )\n group.add_argument(\n \"--log-interval\",\n type=int,\n default=100,\n help=\"Interval between progress updates\",\n )\n args = parser.parse_args(input_args)\n args.keep_empty = False\n\n \n args.rank = 0\n args.make_vocab_size_divisible_by = 128\n args.model_parallel_size = 1\n\n return args","input":"['--input', '.\/tests\/data\/enwik8_first100.txt', '--output-prefix', '.\/tests\/data\/enwik8_first100', '--vocab', 'gpt2', '--tokenizer-type', 'HFGPT2Tokenizer', '--merge-file', '.\/data\/gpt2-merges.txt', '--append-eod']","output":"Namespace(input='.\/tests\/data\/enwik8_first100.txt', jsonl_keys=['text'], num_docs=None, tokenizer_type='HFGPT2Tokenizer', vocab_file='gpt2', merge_file='.\/data\/gpt2-merges.txt', append_eod=True, ftfy=False, output_prefix='.\/tests\/data\/enwik8_first100', dataset_impl='mmap', workers=1, log_interval=100, keep_empty=False, rank=0, make_vocab_size_divisible_by=128, model_parallel_size=1)","cyclomatic_complexity":1,"code_length":82,"category":"Super Easy"}
{"index":1849,"idx":229,"code":"def gen_search_gzh_url(keyword, page=1):\n \n assert isinstance(page, int) and page > 0\n\n qs_dict = OrderedDict()\n qs_dict['type'] = _search_type_gzh\n qs_dict['page'] = page\n qs_dict['ie'] = 'utf8'\n qs_dict['query'] = keyword\n\n return 'http:\/\/weixin.sogou.com\/weixin?{}'.format(urlencode(qs_dict))","input":"'\u9ad8\u8003', 1","output":"'http:\/\/weixin.sogou.com\/weixin?type=1&page=1&ie=utf8&query=%E9%AB%98%E8%80%83'","cyclomatic_complexity":1,"code_length":8,"category":"Super Easy"}
{"index":1855,"idx":230,"code":"def __handle_content_url(content_url):\n content_url = replace_html(content_url)\n return ('http:\/\/mp.weixin.qq.com{}'.format(\n content_url) if 'http:\/\/mp.weixin.qq.com' not in content_url else content_url) if content_url else ''","input":"'\/s?timestamp=1500903767&src=3&ver=1&signature=X4l0IQ091w0DY2ERU7fD*h0VUwBxeHPOJH-Uk-vAfaPamMl6ij7fqAIHomnXQ2X2*2J94H0pixVjsjEkL0TbILtKInZ4hqPp3-lC1nQZcN9Fd*BGbTQp7WlZyzLvCXy0Z8yFVF*lIDlo75pemv7kW8wov4Hz5-uiVzBT5q*Nwaw='","output":"'http:\/\/mp.weixin.qq.com\/s?timestamp=1500903767&src=3&ver=1&signature=X4l0IQ091w0DY2ERU7fD*h0VUwBxeHPOJH-Uk-vAfaPamMl6ij7fqAIHomnXQ2X2*2J94H0pixVjsjEkL0TbILtKInZ4hqPp3-lC1nQZcN9Fd*BGbTQp7WlZyzLvCXy0Z8yFVF*lIDlo75pemv7kW8wov4Hz5-uiVzBT5q*Nwaw='","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1869,"idx":231,"code":"def glob_absolute_paths(file: Union[str, Path]) -> List[Path]:\n path = Path(file)\n if not path.is_absolute():\n path = base \/ path\n return sorted(path.parent.glob(path.name), key=lambda p: p.stem)","input":"'aggrid.js', PosixPath('\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/zauberzeug+nicegui\/zauberzeug+nicegui\/nicegui\/elements')","output":"[PosixPath('\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/zauberzeug+nicegui\/zauberzeug+nicegui\/nicegui\/elements\/aggrid.js')]","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":1870,"idx":232,"code":"def compute_key(path: Path) -> str:\n \n nicegui_base = Path(__file__).parent\n is_file = path.is_file()\n try:\n path = path.relative_to(nicegui_base)\n except ValueError:\n pass\n if is_file:\n return f'{hash_file_path(path.parent)}\/{path.name}'\n return f'{hash_file_path(path)}'","input":"PosixPath('\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/zauberzeug+nicegui\/zauberzeug+nicegui\/nicegui\/elements\/aggrid.js')","output":"'b0b17893a51343979e2090deee730538\/aggrid.js'","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":1879,"idx":233,"code":"def _class_is_prefixed_with_native(class_name: str) -> bool:\n \n\n for prefix in native_prefixes:\n\n if class_name.startswith(prefix):\n return True\n\n return False","input":"'FooBar'","output":"False","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":1885,"idx":234,"code":"def sizeof_fmt(num: float, suffix: str = 'B') -> str:\n \n\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(num) < 1024.0:\n return '%3.1f %s%s' % (num, unit, suffix)\n num \/= 1024.0\n return '%.1f %s%s' % (num, 'Yi', suffix)","input":"249.0, 'B'","output":"'249.0 B'","cyclomatic_complexity":3,"code_length":6,"category":"Easy"}
{"index":1912,"idx":235,"code":"def aes(text, key):\n pad = 16 - len(text) % 16\n text = text + bytearray([pad] * pad)\n encryptor = AES.new(key, 2, b\"0102030405060708\")\n ciphertext = encryptor.encrypt(text)\n return base64.b64encode(ciphertext)","input":"b'{\"ids\": [347230, 496619464, 405998841, 28012031], \"br\": 320000, \"csrf_token\": \"\"}', b'0CoJUm6Qyw8W8jud'","output":"b'fTgoCpE76coDCyvDtrXvwgYOrj9p0x3SYp0c6oD5dhysewaiWVMq\/bz2Ko9aUxLs6HlaBhlklrZFYBFHAVbPp8+9kHtWeFTjHMQhlixwM\/9Lx2cX\/AwR31z\/qIQshWoS'","cyclomatic_complexity":1,"code_length":6,"category":"Super Easy"}
{"index":1913,"idx":236,"code":"def rsa(text, pubkey, modulus):\n text = text[::-1]\n rs = pow(int(binascii.hexlify(text), 16), int(pubkey, 16), int(modulus, 16))\n return format(rs, \"x\").zfill(256)","input":"b'8f0f5370d2e586d8', '010001', '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'","output":"'3acc2a8278d1470cb5a0c5c1ba1fb65331fa5b459568f896d2e348f416b871cb15f2ced68cdee0f4b799b74df42aa0591700ab387ec8082d7a177ddeaeec7f25b98db25dd2761bc6856db12bf30ff351f38b97a98db9ad19e9d10abf3909b6935630235c76269759f8811a7118de552f3450138c62e06e7ce592669aac5192db'","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1920,"idx":237,"code":"def _get_nested(data, key):\n \n\n if not data or not isinstance(data, dict):\n return None\n if '.' not in key:\n return data.get(key)\n if key in data:\n return data[key]\n\n parts = key.split('.')\n for i in range(len(parts))[::-1]:\n prefix = \".\".join(parts[:i])\n if prefix in data:\n return _get_nested(data[prefix], \".\".join(parts[i:]))\n\n return None","input":"{'server': {'address': '0.0.0.0'}, 'cache': {'type': 'redis'}}, 'cache.type'","output":"'redis'","cyclomatic_complexity":6,"code_length":13,"category":"Hard"}
{"index":1939,"idx":238,"code":"def layer_template(layer_name: str, idx: int) -> Tuple[str, int]:\n split = layer_name.split(\".\")\n number = int(split[idx])\n split[idx] = \"{}\"\n from_name = \".\".join(split)\n return from_name, number","input":"'model.layers.0.self_attn.q_proj.weight', 2","output":"('model.layers.{}.self_attn.q_proj.weight', 0)","cyclomatic_complexity":1,"code_length":6,"category":"Super Easy"}
{"index":1953,"idx":239,"code":"def rowcol_to_a1(row, col):\n \n row = int(row)\n col = int(col)\n\n if row < 1 or col < 1:\n raise IncorrectCellLabel(\"({}, {})\".format(row, col))\n\n div = col\n column_label = \"\"\n\n while div:\n (div, mod) = divmod(div, 26)\n if mod == 0:\n mod = 26\n div -= 1\n column_label = chr(mod + MAGIC_NUMBER) + column_label\n\n label = \"{}{}\".format(column_label, row)\n\n return label","input":"4, 4","output":"'D4'","cyclomatic_complexity":4,"code_length":15,"category":"Medium"}
{"index":1956,"idx":240,"code":"def a1_to_rowcol(label):\n \n m = CELL_ADDR_RE.match(label)\n if m:\n column_label = m.group(1).upper()\n row = int(m.group(2))\n\n col = 0\n for i, c in enumerate(reversed(column_label)):\n col += (ord(c) - MAGIC_NUMBER) * (26**i)\n else:\n raise IncorrectCellLabel(label)\n\n return (row, col)","input":"'B1'","output":"(1, 2)","cyclomatic_complexity":3,"code_length":11,"category":"Easy"}
{"index":1957,"idx":241,"code":"def fill_gaps(L, rows=None, cols=None, padding_value=\"\"):\n \n try:\n max_cols = max(len(row) for row in L) if cols is None else cols\n max_rows = len(L) if rows is None else rows\n\n pad_rows = max_rows - len(L)\n\n if pad_rows:\n L = L + ([[]] * pad_rows)\n\n return [rightpad(row, max_cols, padding_value=padding_value) for row in L]\n except ValueError:\n return []","input":"[['', 'Dummy']], None, None, ''","output":"[['', 'Dummy']]","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":1959,"idx":242,"code":"def _a1_to_rowcol_unbounded(label):\n \n m = A1_ADDR_ROW_COL_RE.match(label)\n if m:\n column_label, row = m.groups()\n\n if column_label:\n col = 0\n for i, c in enumerate(reversed(column_label.upper())):\n col += (ord(c) - MAGIC_NUMBER) * (26**i)\n else:\n col = inf\n\n if row:\n row = int(row)\n else:\n row = inf\n else:\n raise IncorrectCellLabel(label)\n\n return (row, col)","input":"'A1'","output":"(1, 1)","cyclomatic_complexity":5,"code_length":17,"category":"Medium"}
{"index":1971,"idx":243,"code":"def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=None):\n \n assert isinstance(commands, list)\n process = None\n for command in commands:\n try:\n dispcmd = str([command] + args)\n \n process = subprocess.Popen(\n [command] + args,\n cwd=cwd,\n env=env,\n stdout=subprocess.PIPE,\n stderr=(subprocess.PIPE if hide_stderr else None),\n )\n break\n except OSError:\n e = sys.exc_info()[1]\n if e.errno == errno.ENOENT:\n continue\n if verbose:\n print(\"unable to run %s\" % dispcmd)\n print(e)\n return None, None\n else:\n if verbose:\n print(\"unable to find command, tried %s\" % (commands,))\n return None, None\n stdout = process.communicate()[0].strip().decode()\n if process.returncode != 0:\n if verbose:\n print(\"unable to run %s (error)\" % dispcmd)\n print(\"stdout was %s\" % stdout)\n return None, process.returncode\n return stdout, process.returncode","input":"['git'], ['rev-parse', '--git-dir'], '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/danielgatis+rembg\/danielgatis+rembg', False, True, None","output":"('.git', 0)","cyclomatic_complexity":9,"code_length":33,"category":"Hard"}
{"index":1979,"idx":244,"code":"def render_pep440_feature(pieces):\n \n if pieces[\"closest-tag\"] and pieces[\"develop\"]:\n rendered = pieces[\"closest-tag\"]\n distance_to_develop = pieces[\"distance-to-develop\"]\n distance_to_merge = pieces[\"distance-to-master\"]\n distance_merge_to_tag = (pieces[\"distance\"] - distance_to_merge)\n distance_dev_to_merge = (distance_to_merge - distance_to_develop)\n if (distance_merge_to_tag > 0):\n rendered += \".%d\" % distance_merge_to_tag\n rendered += \".post.dev%d\" % distance_dev_to_merge\n rendered += plus_or_dot(pieces)\n rendered += \"g%s\" % pieces[\"short\"]\n rendered += \".%s\" % pieces[\"branch\"]\n rendered += \".%d\" % distance_to_develop\n else:\n \n rendered = \"0.post.dev%d\" % (pieces[\"distance\"] - 1)\n rendered += plus_or_dot(pieces)\n rendered += \"g%s\" % pieces[\"short\"]\n if pieces[\"dirty\"]:\n rendered += \".dirty\"\n return rendered","input":"{'long': 'e60d005d389cb31b6e99f937e35adbe3fccb7aaf', 'short': 'e60d005', 'error': None, 'dirty': False, 'closest-tag': '0.8', 'distance': 3, 'branch': 'HEAD', 'distance-to-master': 0, 'develop': None, 'distance-to-develop': None, 'date': '2018-05-05T22:17:58-0700', 'authors': ['Padraic Shafer']}","output":"'0.post.dev2+ge60d005'","cyclomatic_complexity":4,"code_length":21,"category":"Medium"}
{"index":1984,"idx":245,"code":"def forward(ctx, a, b):\n new_tensor = Tensor(a.data + b.data)\n return new_tensor","input":"{}, {data=array([[1., 2., 3., 4.], [5., 6., 7., 8.]]), grad=None, grad_fn=None, is_leaf=True, require_grad=True}","output":"{data=array([[-3.4401897, -2.4401897, -1.4401897, -0.4401897], [-3.4401897, -2.4401897, -1.4401897, -0.4401897]]), grad=None, grad_fn=None, is_leaf=True, require_grad=False}","cyclomatic_complexity":1,"code_length":3,"category":"Super Easy"}
{"index":1988,"idx":246,"code":"def backward(ctx, grad_output):\n b_grad = grad_output * 1\n a_grad = grad_output * 1\n return a_grad, b_grad","input":"{store=(array([[9.11881966e-04, 2.47875218e-03, 6.73794700e-03, 1.83156389e-02], [4.97870684e-02, 1.35335283e-01, 3.67879441e-01, 1.00000000e+00]]), array([[0.02844422], [1.55300179]]))}, array([[1., 1., 1., 1.], [1., 1., 1., 1.]])","output":"array([[ 0.87176559, 0.65142273, 0.05246873, -1.57565704], [ 0.87176559, 0.65142273, 0.05246873, -1.57565704]])","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":1989,"idx":247,"code":"def compute_loc(idx, shape):\n loc = [0] * len(shape)\n for i in range(len(shape)):\n prod = int(np.prod(shape[i + 1:]))\n loc[i] = idx \/\/ prod\n idx = idx % prod\n return tuple(loc)","input":"0, (2, 4)","output":"(0, 0)","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":2006,"idx":248,"code":"def create_mock_page_scrapers(number_mock_scrapers):\n mock_scrapers = []\n for _ in range(0, number_mock_scrapers):\n mock_scrapers.append(mock.create_autospec(PageScraper))\n return mock_scrapers","input":"1","output":"[<MagicMock spec='PageScraper' id='140669237222752'>]","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":2019,"idx":249,"code":"def encode_number(n):\n b128_digits = []\n while n:\n b128_digits.insert(0, (n & 0x7f) | 0x80)\n n = n >> 7\n if not b128_digits:\n b128_digits.append(0)\n b128_digits[-1] &= 0x7f\n return b''.join([int.to_bytes(d, 1, 'big') for d in b128_digits])","input":"840","output":"b'\\x86H'","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":2024,"idx":250,"code":"def getLimit(self, symbol, limit):\n pass","input":"[{'symbol': 'BTC\/USDT', 'id': '0', 'i': 0}, {'symbol': 'BTC\/USDT', 'id': '1', 'i': 1}, {'symbol': 'BTC\/USDT', 'id': '2', 'i': 2}, {'symbol': 'BTC\/USDT', 'id': '3', 'i': 3}, {'symbol': 'BTC\/USDT', 'id': '4', 'i': 4}], 'BTC\/USDT', None, {'symbol': 'BTC\/USDT', 'id': '0', 'i': 0}, {'symbol': 'BTC\/USDT', 'id': '1', 'i': 1}, {'symbol': 'BTC\/USDT', 'id': '2', 'i': 2}, {'symbol': 'BTC\/USDT', 'id': '3', 'i': 3}, {'symbol': 'BTC\/USDT', 'id': '4', 'i': 4}","output":"5","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":2030,"idx":251,"code":"def key_exists(dictionary, key):\n if hasattr(dictionary, '__getitem__') and not isinstance(dictionary, str):\n if isinstance(dictionary, list) and type(key) is not int:\n return False\n try:\n value = dictionary[key]\n return value is not None and value != ''\n except LookupError:\n return False\n return False","input":"(None, {'taker': [[0.0, 0.0005], [250.0, 0.00045], [2500.0, 0.0004], [7500.0, 0.0003], [22500.0, 0.00025], [50000.0, 0.00024], [100000.0, 0.00024], [200000.0, 0.00024], [400000.0, 0.00024], [750000.0, 0.00024]], 'maker': [[0.0, 0.0001], [250.0, 8e-05], [2500.0, 5e-05], [7500.0, 3e-06], [22500.0, 0.0], [50000.0, -5e-05], [100000.0, -6e-05], [200000.0, -7e-05], [400000.0, -8e-05], [750000.0, -9e-05]]})","output":"{'taker': [[0.0, 0.0005], [250.0, 0.00045], [2500.0, 0.0004], [7500.0, 0.0003], [22500.0, 0.00025], [50000.0, 0.00024], [100000.0, 0.00024], [200000.0, 0.00024], [400000.0, 0.00024], [750000.0, 0.00024]], 'maker': [[0.0, 0.0001], [250.0, 8e-05], [2500.0, 5e-05], [7500.0, 3e-06], [22500.0, 0.0], [50000.0, -5e-05], [100000.0, -6e-05], [200000.0, -7e-05], [400000.0, -8e-05], [750000.0, -9e-05]]}","cyclomatic_complexity":5,"code_length":10,"category":"Medium"}
{"index":2031,"idx":252,"code":"def safe_value(dictionary, key, default_value=None):\n return dictionary[key] if Exchange.key_exists(dictionary, key) else default_value","input":"(None, {'TRC20': 'TRX'})","output":"{'TRC20': 'TRX'}","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":2032,"idx":253,"code":"def extend(*args):\n if args is not None:\n result = None\n if type(args[0]) is collections.OrderedDict:\n result = collections.OrderedDict()\n else:\n result = {}\n for arg in args:\n result.update(arg)\n return result\n return {}","input":"({'refillRate': 0.02, 'delay': 0.001, 'capacity': 1.0, 'defaultCost': 1.0}, {})","output":"{'refillRate': 0.02, 'delay': 0.001, 'capacity': 1.0, 'defaultCost': 1.0}","cyclomatic_complexity":4,"code_length":11,"category":"Medium"}
{"index":2038,"idx":254,"code":"def sort_by(array, key, descending=False, default=0):\n return sorted(array, key=lambda k: k[key] if k[key] is not None else default, reverse=descending)","input":"(None, {'id': 'foobar', 'symbol': 'FOO\/BAR', 'base': 'FOO', 'quote': 'BAR', 'taker': 0.0025, 'maker': 0.001, 'precision': {'price': 8, 'amount': 8}})","output":"{'id': 'foobar', 'symbol': 'FOO\/BAR', 'base': 'FOO', 'quote': 'BAR', 'taker': 0.0025, 'maker': 0.001, 'precision': {'price': 8, 'amount': 8}}","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":2039,"idx":255,"code":"def leftmost_bit(x):\n assert x > 0\n result = 1\n while result <= x:\n result = 2 * result\n return result \/\/ 2","input":"35418756707884953894268771885010418872764936485960643117951731578891074948686","output":"28948022309329048855892746252171976963317496166410141009864396001978282409984","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":2040,"idx":256,"code":"def inverse_mod(a, m):\n \n\n if a < 0 or m <= a:\n a = a % m\n\n \n\n c, d = a, m\n uc, vc, ud, vd = 1, 0, 0, 1\n while c != 0:\n q, c, d = divmod(d, c) + (c,)\n uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc\n\n \n \n\n assert d == 1\n if ud > 0:\n return ud\n else:\n return ud + m","input":"65341020041517633956166170261014086368942546761318486551877808671514674964848, 115792089237316195423570985008687907853269984665640564039457584007908834671663","output":"83174505189910067536517124096019359197644205712500122884473429251812128958118","cyclomatic_complexity":4,"code_length":13,"category":"Medium"}
{"index":2041,"idx":257,"code":"def generate_k(order, secexp, hash_func, data, retry_gen=0, extra_entropy=b''):\n \n\n qlen = bit_length(order)\n holen = hash_func().digest_size\n rolen = (qlen + 7) \/ 8\n bx = number_to_string(secexp, order) + bits2octets(data, order) + \\\n extra_entropy\n\n \n v = b'\\x01' * holen\n\n \n k = b'\\x00' * holen\n\n \n\n k = hmac.new(k, v + b'\\x00' + bx, hash_func).digest()\n\n \n v = hmac.new(k, v, hash_func).digest()\n\n \n k = hmac.new(k, v + b'\\x01' + bx, hash_func).digest()\n\n \n v = hmac.new(k, v, hash_func).digest()\n\n \n while True:\n \n t = b''\n\n \n while len(t) < rolen:\n v = hmac.new(k, v, hash_func).digest()\n t += v\n\n \n secret = bits2int(t, qlen)\n\n if secret >= 1 and secret < order:\n if retry_gen <= 0:\n return secret\n else:\n retry_gen -= 1\n\n k = hmac.new(k, v + b'\\x00', hash_func).digest()\n v = hmac.new(k, v, hash_func).digest()","input":"115792089237316195423570985008687907852837564279074904382605163141518161494337, 11806252235961651298089590628336806290921645495320214372650577192963691649562, <built-in function openssl_sha256>, b'\\xa7?\\xcf3\\x96@\\x92\\x92\\x07(\\x1f\\xb8\\xe08\\x88H\\x06\\xe2\\xeb\\x08@\\xf2$V\\x94\\xdb\\xba\\x1d\\\\\\xc8\\x9ee', 0, b''","output":"27904662249631320277791388928992251959336708715070119348399332397999654013035","cyclomatic_complexity":5,"code_length":25,"category":"Medium"}
{"index":2042,"idx":258,"code":"def bit_length(num):\n \n s = bin(num) \n s = s.lstrip('-0b') \n return len(s)","input":"115792089237316195423570985008687907852837564279074904382605163141518161494337","output":"256","cyclomatic_complexity":1,"code_length":4,"category":"Super Easy"}
{"index":2043,"idx":259,"code":"def bits2octets(data, order):\n z1 = bits2int(data, bit_length(order))\n z2 = z1 - order\n\n if z2 < 0:\n z2 = z1\n\n return number_to_string_crop(z2, order)","input":"b'\\xa7?\\xcf3\\x96@\\x92\\x92\\x07(\\x1f\\xb8\\xe08\\x88H\\x06\\xe2\\xeb\\x08@\\xf2$V\\x94\\xdb\\xba\\x1d\\\\\\xc8\\x9ee', 115792089237316195423570985008687907852837564279074904382605163141518161494337","output":"b'\\xa7?\\xcf3\\x96@\\x92\\x92\\x07(\\x1f\\xb8\\xe08\\x88H\\x06\\xe2\\xeb\\x08@\\xf2$V\\x94\\xdb\\xba\\x1d\\\\\\xc8\\x9ee'","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":2045,"idx":260,"code":"def __str__(self):\n self.reduce()\n sign = '-' if self.integer < 0 else ''\n integer_array = list(str(abs(self.integer)).rjust(self.decimals, '0'))\n index = len(integer_array) - self.decimals\n if index == 0:\n item = '0.'\n elif self.decimals < 0:\n item = '0' * (-self.decimals)\n elif self.decimals == 0:\n item = ''\n else:\n item = '.'\n integer_array.insert(index, item)\n return sign + ''.join(integer_array)","input":"Precise(1393.938), 10, 3, 1393938","output":"'1393.938'","cyclomatic_complexity":4,"code_length":15,"category":"Medium"}
{"index":2046,"idx":261,"code":"def string_abs(string):\n if string is None:\n return None\n return str(Precise(string).abs())","input":"Precise(0.001434784043479695), 10, 18, 1434784043479695","output":"'0.001434784043479695'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":2047,"idx":262,"code":"def string_add(string1, string2):\n if string1 is None and string2 is None:\n return None\n if string1 is None:\n return string2\n elif string2 is None:\n return string1\n return str(Precise(string1).add(Precise(string2)))","input":"Precise(1393.938), 10, 3, 1393938","output":"'1393.938'","cyclomatic_complexity":4,"code_length":8,"category":"Medium"}
{"index":2048,"idx":263,"code":"def string_sub(string1, string2):\n if string1 is None or string2 is None:\n return None\n return str(Precise(string1).sub(Precise(string2)))","input":"Precise(69696900000.00000002), 10, 8, 6969690000000000002","output":"'69696900000.00000002'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":2049,"idx":264,"code":"def string_div(string1, string2, precision=18):\n if string1 is None or string2 is None:\n return None\n string2_precise = Precise(string2)\n if string2_precise.integer == 0:\n return None\n return str(Precise(string1).div(string2_precise, precision))","input":"Precise(69696899999.99999998), 10, 8, 6969689999999999998","output":"'69696899999.99999998'","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":2050,"idx":265,"code":"def reduce(self):\n string = str(self.integer)\n start = len(string) - 1\n if start == 0:\n if string == \"0\":\n self.decimals = 0\n return self\n for i in range(start, -1, -1):\n if string[i] != '0':\n break\n difference = start - i\n if difference == 0:\n return self\n self.decimals -= difference\n self.integer = int(string[:i + 1])","input":"Precise(30), 10, -1, 3","output":"'30'","cyclomatic_complexity":6,"code_length":15,"category":"Hard"}
{"index":2051,"idx":266,"code":"def string_min(string1, string2):\n if string1 is None or string2 is None:\n return None\n return str(Precise(string1).min(Precise(string2)))","input":"Precise(5.534), 10, 3, 5534","output":"Precise(5.534)","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":2052,"idx":267,"code":"def div(self, other, precision=18):\n distance = precision - self.decimals + other.decimals\n if distance == 0:\n numerator = self.integer\n elif distance < 0:\n exponent = self.base ** -distance\n numerator = self.integer \/\/ exponent\n else:\n exponent = self.base ** distance\n numerator = self.integer * exponent\n result, mod = divmod(numerator, other.integer)\n \n \n result = result + 1 if result < 0 and mod else result\n return Precise(result, precision)","input":"Precise(0.00000002), Precise(69696900000), 1, 10, 8, 2","output":"Precise(0)","cyclomatic_complexity":3,"code_length":13,"category":"Easy"}
{"index":2053,"idx":268,"code":"def string_neg(string):\n if string is None:\n return None\n return str(Precise(string).neg())","input":"Precise(213), 10, 0, 213","output":"'213'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":2054,"idx":269,"code":"def string_mod(string1, string2):\n if string1 is None or string2 is None:\n return None\n return str(Precise(string1).mod(Precise(string2)))","input":"Precise(-213), 10, 0, -213","output":"'-213'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":2055,"idx":270,"code":"def string_max(string1, string2):\n if string1 is None or string2 is None:\n return None\n return str(Precise(string1).max(Precise(string2)))","input":"Precise(0), 10, 0, 0","output":"'0'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":2056,"idx":271,"code":"def string_gt(string1, string2):\n if string1 is None or string2 is None:\n return None\n return Precise(string1).gt(Precise(string2))","input":"Precise(0), 10, 0, 0","output":"'0'","cyclomatic_complexity":2,"code_length":4,"category":"Super Easy"}
{"index":2082,"idx":272,"code":"def _retryable_test_not_exception_message_delay(thing):\n return thing.go()","input":"{counter=0, count=3}","output":"True","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":2083,"idx":273,"code":"def _retryable_test_with_unless_exception_type_name(thing):\n return thing.go()","input":"{counter=0, count=5}","output":"True","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":2084,"idx":274,"code":"def _retryable_test_with_unless_exception_type_no_input(thing):\n return thing.go()","input":"{counter=0, count=5}","output":"True","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":2085,"idx":275,"code":"def _retryable_test_with_unless_exception_type_name_attempt_limit(thing):\n return thing.go()","input":"{counter=0, count=2}","output":"True","cyclomatic_complexity":1,"code_length":2,"category":"Super Easy"}
{"index":2100,"idx":276,"code":"def _import_plugins(plugin_names):\n plugins = []\n for name, path in plugin_names.items():\n log.debug(\"Importing plugin %s: %s\", name, path)\n if '.' not in path:\n plugins.append(__import__(path))\n else:\n package, module = path.rsplit('.', 1)\n module = __import__(path, fromlist=[module])\n plugins.append(module)\n return plugins","input":"{'__builtin__': 'awscli.handlers'}","output":"[<module 'awscli.handlers' from '\/local\/rcs\/XXX\/code\/pytrace-collector\/logs\/self_collected\/tried\/aws+aws-cli\/aws+aws-cli\/awscli\/handlers.py'>]","cyclomatic_complexity":3,"code_length":11,"category":"Easy"}
{"index":2214,"idx":277,"code":"def dict_to_ini_section(ini_dict, section_header):\n section_str = f'[{section_header}]\\n'\n for key, value in ini_dict.items():\n if isinstance(value, dict):\n section_str += f\"{key} =\\n\"\n for new_key, new_value in value.items():\n section_str += f\" {new_key}={new_value}\\n\"\n else:\n section_str += f\"{key}={value}\\n\"\n return section_str + \"\\n\"","input":"{'aws_access_key_id': '123', 'aws_secret_access_key': '456', 'region': 'fake-region-10', 'endpoint_url': 'https:\/\/global.endpoint.aws'}, 'profile service_global_only'","output":"'[profile service_global_only]\\naws_access_key_id=123\\naws_secret_access_key=456\\nregion=fake-region-10\\nendpoint_url=https:\/\/global.endpoint.aws\\n\\n'","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":2320,"idx":278,"code":"def load_translation(self) -> \"I18N\":\n \n try:\n dir_path = os.path.dirname(os.path.realpath(__file__))\n prompts_path = os.path.join(\n dir_path, f\"..\/translations\/{self.language}.json\"\n )\n\n with open(prompts_path, \"r\") as f:\n self._translations = json.load(f)\n except FileNotFoundError:\n raise ValidationError(\n f\"Trasnlation file for language '{self.language}' not found.\"\n )\n except json.JSONDecodeError:\n raise ValidationError(f\"Error decoding JSON from the prompts file.\")\n return self","input":"I18N(language='en'), {'language': 'en'}, None, set(), {}, 'en'","output":"I18N(language='en')","cyclomatic_complexity":4,"code_length":15,"category":"Medium"}
{"index":2326,"idx":279,"code":"def _to_str(size, suffixes, base):\n \n try:\n size = int(size)\n except ValueError:\n raise TypeError(\"filesize requires a numeric value, not {!r}\".format(size))\n if size == 1:\n return \"1 byte\"\n elif size < base:\n return \"{:,} bytes\".format(size)\n\n for i, suffix in enumerate(suffixes, 2):\n unit = base ** i\n if size < unit:\n break\n return \"{:,.1f} {}\".format((base * size \/ unit), suffix)","input":"1024, ('KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'), 1024","output":"'1.0 KiB'","cyclomatic_complexity":7,"code_length":14,"category":"Hard"}
{"index":2328,"idx":280,"code":"def decode_linux(line, match):\n perms, links, uid, gid, size, mtime, name = match.groups()\n is_link = perms.startswith(\"l\")\n is_dir = perms.startswith(\"d\") or is_link\n if is_link:\n name, _, _link_name = name.partition(\"->\")\n name = name.strip()\n _link_name = _link_name.strip()\n permissions = Permissions.parse(perms[1:])\n\n mtime_epoch = _parse_time(mtime)\n\n name = unicodedata.normalize(\"NFC\", name)\n\n raw_info = {\n \"basic\": {\"name\": name, \"is_dir\": is_dir},\n \"details\": {\n \"size\": int(size),\n \"type\": int(ResourceType.directory if is_dir else ResourceType.file),\n },\n \"access\": {\"permissions\": permissions.dump()},\n \"ftp\": {\"ls\": line},\n }\n access = raw_info[\"access\"]\n details = raw_info[\"details\"]\n if mtime_epoch is not None:\n details[\"modified\"] = mtime_epoch\n\n access[\"user\"] = uid\n access[\"group\"] = gid\n\n return raw_info","input":"'lrwxrwxrwx 1 0 0 19 Jan 18 2006 debian -> .\/pub\/mirror\/debian', <re.Match object; span=(0, 85), match='lrwxrwxrwx 1 0 0 19 Jan 18>","output":"{'basic': {'name': 'debian', 'is_dir': True}, 'details': {'size': 19, 'type': 1, 'modified': 1137542400.0}, 'access': {'permissions': ['g_r', 'g_w', 'g_x', 'o_r', 'o_w', 'o_x', 'u_r', 'u_w', 'u_x'], 'user': '0', 'group': '0'}, 'ftp': {'ls': 'lrwxrwxrwx 1 0 0 19 Jan 18 2006 debian -> .\/pub\/mirror\/debian'}}","cyclomatic_complexity":3,"code_length":27,"category":"Easy"}
{"index":2329,"idx":281,"code":"def _parse_time(t):\n t = \" \".join(token.strip() for token in t.lower().split(\" \"))\n try:\n try:\n _t = time.strptime(t, \"%b %d %Y\")\n except ValueError:\n _t = time.strptime(t, \"%b %d %H:%M\")\n except ValueError:\n \n return None\n\n year = _t.tm_year if _t.tm_year != 1900 else time.localtime().tm_year\n month = _t.tm_mon\n day = _t.tm_mday\n hour = _t.tm_hour\n minutes = _t.tm_min\n dt = datetime.datetime(year, month, day, hour, minutes, tzinfo=UTC)\n\n epoch_time = (dt - epoch_dt).total_seconds()\n return epoch_time","input":"'Jan 18 2006'","output":"1137542400.0","cyclomatic_complexity":5,"code_length":17,"category":"Medium"}
{"index":2370,"idx":282,"code":"def _is_ascii(s):\n if isinstance(s, str):\n for c in s:\n if ord(c) > 255:\n return False\n return True\n return _supports_unicode(s)","input":"' 123456789#'","output":"True","cyclomatic_complexity":4,"code_length":7,"category":"Medium"}
{"index":2376,"idx":283,"code":"def make_context(headers):\n \n\n \n \n headers = {k.lower(): v for k, v in headers.items()}\n\n if not all(h in headers for h in (\n TRACE_ID_HEADER.lower(), SPAN_ID_HEADER.lower())):\n return None\n\n context = TraceContext(\n trace_id=headers.get(TRACE_ID_HEADER.lower()),\n parent_id=headers.get(PARENT_ID_HEADER.lower(), None),\n span_id=headers.get(SPAN_ID_HEADER.lower()),\n sampled=parse_sampled(headers),\n shared=False,\n debug=parse_debug(headers),\n )\n return context","input":"{'X-B3-Flags': '0', 'X-B3-ParentSpanId': None, 'X-B3-Sampled': '1', 'X-B3-SpanId': '41baf1be2fb9bfc5', 'X-B3-TraceId': '6f9a20b5092fa5e144fd15cc31141cd4'}","output":"TraceContext(trace_id='6f9a20b5092fa5e144fd15cc31141cd4', parent_id=None, span_id='41baf1be2fb9bfc5', sampled=True, debug=False, shared=False)","cyclomatic_complexity":2,"code_length":14,"category":"Super Easy"}
{"index":2430,"idx":284,"code":"def _prep_ordered_arg(desired_length, arguments=None):\n \n arguments = listify(arguments) if arguments is not None else [None]\n if len(arguments) != desired_length and len(arguments) != 1:\n raise ValueError(\"Argument length must be either 1 or the same length as \"\n \"the number of transitions.\")\n if len(arguments) == 1:\n return arguments * desired_length\n return arguments","input":"3, None","output":"[None, None, None]","cyclomatic_complexity":3,"code_length":8,"category":"Easy"}
{"index":2443,"idx":285,"code":"def quat_from_axis_angle(axis, angle):\n axis_ = np.array(axis, dtype=np.float64)\n half_angle = angle * 0.5\n ret = np.empty(4)\n ret[0] = math.cos(half_angle)\n ret[1:4] = math.sin(half_angle) * axis_\n return ret","input":"[1.0, 0.0, 0.0], 6.1086523819801535","output":"array([-0.9961947 , 0.08715574, 0. , 0. ])","cyclomatic_complexity":1,"code_length":7,"category":"Super Easy"}
{"index":2444,"idx":286,"code":"def remove_component(x, *, indices):\n \n ma = np.ma.array(x, mask=False)\n ma.mask[indices] = True\n shape = x.shape[:-1] + (x.shape[-1] - 1,)\n return ma.compressed().reshape(shape)","input":"array([-0.9961947 , 0.08715574, 0. , 0. ], dtype=float32), (0,)","output":"array([0.08715574, 0. , 0. ], dtype=float32)","cyclomatic_complexity":1,"code_length":5,"category":"Super Easy"}
{"index":2456,"idx":287,"code":"def base64url_decode(input: Union[bytes, str]) -> bytes:\n input_bytes = force_bytes(input)\n\n rem = len(input_bytes) % 4\n\n if rem > 0:\n input_bytes += b\"=\" * (4 - rem)\n\n return base64.urlsafe_b64decode(input_bytes)","input":"'hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg'","output":"b'\\x84\\x9bW!\\x9d\\xaeH\\xdedm\\x07\\xdb\\xb53Vn\\x97f\\x86E|\\x14\\x91\\xbe:v\\xdc\\xealBq\\x88'","cyclomatic_complexity":2,"code_length":6,"category":"Super Easy"}
{"index":2461,"idx":288,"code":"def to_base64url_uint(val: int) -> bytes:\n if val < 0:\n raise ValueError(\"Must be a positive integer\")\n\n int_bytes = bytes_from_int(val)\n\n if len(int_bytes) == 0:\n int_bytes = b\"\\x00\"\n\n return base64url_encode(int_bytes)","input":"0","output":"b'AA'","cyclomatic_complexity":3,"code_length":7,"category":"Easy"}
{"index":2462,"idx":289,"code":"def bytes_from_int(val: int) -> bytes:\n remaining = val\n byte_length = 0\n\n while remaining != 0:\n remaining >>= 8\n byte_length += 1\n\n return val.to_bytes(byte_length, \"big\", signed=False)","input":"0","output":"b''","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":2477,"idx":290,"code":"def exists(self, func):\n \n for element in self:\n if func(element):\n return True\n return False","input":"['aaa', 'BBB', 'ccc'], <method 'islower' of 'str' objects>, ['aaa', 'BBB', 'ccc'], Lineage: sequence","output":"True","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":2480,"idx":291,"code":"def for_all(self, func):\n \n for element in self:\n if not func(element):\n return False\n return True","input":"['aaa', 'bbb', 'ccc'], <method 'islower' of 'str' objects>, ['aaa', 'bbb', 'ccc'], Lineage: sequence","output":"True","cyclomatic_complexity":3,"code_length":5,"category":"Easy"}
{"index":2482,"idx":292,"code":"def to_list(self):\n \n self.cache()\n return self._base_sequence","input":"[['1', '2', '3', '4'], ['a', 'b', 'c', 'd']], True, [['1', '2', '3', '4'], ['a', 'b', 'c', 'd']], Lineage: sequence -> cache","output":"[['1', '2', '3', '4'], ['a', 'b', 'c', 'd']]","cyclomatic_complexity":1,"code_length":3,"category":"Super Easy"}
{"index":2483,"idx":293,"code":"def sqlite3(conn, sql, parameters=None, *args, **kwargs):\n \n\n if parameters is None:\n parameters = ()\n\n if isinstance(conn, (sqlite3api.Connection, sqlite3api.Cursor)):\n return seq(conn.execute(sql, parameters))\n elif isinstance(conn, str):\n with sqlite3api.connect(conn, *args, **kwargs) as input_conn:\n return seq(input_conn.execute(sql, parameters))\n else:\n raise ValueError('conn must be a must be a file path or sqlite3 Connection\/Cursor')","input":"'functional\/test\/data\/test_sqlite3.db', 'SELECT id, name FROM user;', None, (), {}","output":"[(1, 'Tom'), (2, 'Jack'), (3, 'Jane'), (4, 'Stephan')]","cyclomatic_complexity":4,"code_length":10,"category":"Medium"}
{"index":2494,"idx":294,"code":"def _create_key_val_str(input_dict: Union[Mapping[Any, Any], Any]) -> str:\n \n\n def list_to_str(input_list: List[str]) -> str:\n \n converted_list = []\n for item in sorted(input_list, key=lambda x: str(x)):\n if isinstance(item, dict):\n item = _create_key_val_str(item)\n elif isinstance(item, list):\n item = list_to_str(item)\n\n converted_list.append(str(item))\n list_str = \", \".join(converted_list)\n return \"[\" + list_str + \"]\"\n\n items_list = []\n for key in sorted(input_dict.keys(), key=lambda x: str(x)):\n val = input_dict[key]\n if isinstance(val, dict):\n val = _create_key_val_str(val)\n elif isinstance(val, list):\n val = list_to_str(input_list=val)\n\n items_list.append(f\"{key}: {val}\")\n\n key_val_str = \"{{{}}}\".format(\", \".join(items_list))\n return key_val_str","input":"{}","output":"'{}'","cyclomatic_complexity":8,"code_length":21,"category":"Hard"}
{"index":2495,"idx":295,"code":"def _compare_with_regex(request_headers: Union[Mapping[Any, Any], Any]) -> bool:\n if strict_match and len(request_headers) != len(headers):\n return False\n\n for k, v in headers.items():\n if request_headers.get(k) is not None:\n if isinstance(v, re.Pattern):\n if re.match(v, request_headers[k]) is None:\n return False\n else:\n if not v == request_headers[k]:\n return False\n elif strict_match:\n return False\n\n return True","input":"{'Accept': 'application\/json'}, {'Accept': 'application\/json'}, False","output":"True","cyclomatic_complexity":8,"code_length":14,"category":"Hard"}
{"index":2503,"idx":296,"code":"def _clean_unicode(url: str) -> str:\n \n urllist = list(urlsplit(url))\n netloc = urllist[1]\n if _has_unicode(netloc):\n domains = netloc.split(\".\")\n for i, d in enumerate(domains):\n if _has_unicode(d):\n d = \"xn--\" + d.encode(\"punycode\").decode(\"ascii\")\n domains[i] = d\n urllist[1] = \".\".join(domains)\n url = urlunsplit(urllist)\n\n \n chars = list(url)\n for i, x in enumerate(chars):\n if ord(x) > 128:\n chars[i] = quote(x)\n\n return \"\".join(chars)","input":"'http:\/\/example.com\/test?type=2&ie=utf8&query=\u6c49\u5b57'","output":"'http:\/\/example.com\/test?type=2&ie=utf8&query=%E6%B1%89%E5%AD%97'","cyclomatic_complexity":6,"code_length":16,"category":"Hard"}
{"index":2509,"idx":297,"code":"def class_to_tg(sub_class: str):\n trans = {\"Online\": \"_online\", \"Offline\": \"_offline\"}\n\n for upper, lower in trans.items():\n sub_class = sub_class.replace(upper, lower)\n\n return sub_class.lower()","input":"'YYeTsOffline'","output":"'yyets_offline'","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":2512,"idx":298,"code":"def generate_samples_loguniform(low, high, step, base, size=1):\n \n\n samples = base ** (random.uniform(low=logb(low, base), high=logb(high, base), size=size))\n if step:\n samples = step * np.floor(samples \/ step)\n return samples","input":"5.8884365535558836e-08, 2.6977394324449206e-07, None, 10, 100000","output":"array([8.36400364e-08, 2.64090744e-07, 2.64351674e-07, ..., 6.02217873e-08, 1.13953435e-07, 8.52185827e-08])","cyclomatic_complexity":2,"code_length":5,"category":"Super Easy"}
{"index":2513,"idx":299,"code":"def generate_samples_uniform(low, high, step, size=1):\n \n samples = random.uniform(low=low,\n high=high,\n size=size)\n if step:\n samples = step * np.floor(samples \/ step)\n return samples","input":"0, 1, None, 10000","output":"array([0.40589487, 0.11308253, 0.31209565, ..., 0.14268188, 0.68390556, 0.14199635])","cyclomatic_complexity":2,"code_length":7,"category":"Super Easy"}
{"index":2516,"idx":300,"code":"def validate_uniform(search_space):\n \n search_space = search_space.copy()\n\n if type(search_space) != dict:\n raise ValueError\n\n if \"low\" not in search_space.keys():\n raise ValueError\n\n if \"high\" not in search_space.keys():\n raise ValueError\n\n if \"low\" in search_space.keys():\n if type(search_space[\"low\"]) not in (int, float):\n raise ValueError\n\n if \"high\" in search_space.keys():\n if type(search_space[\"high\"]) not in (int, float):\n raise ValueError\n\n if \"high\" in search_space.keys() and \"low\" in search_space.keys():\n if search_space[\"high\"] <= search_space[\"low\"]:\n raise ValueError(\"low <= high\")\n\n if \"step\" in search_space.keys():\n if type(search_space[\"step\"]) not in (int, float):\n raise ValueError\n if search_space[\"step\"] >= search_space[\"high\"]:\n raise ValueError(\"Step must be strictly lower than high bound.\")\n\n search_space.setdefault(\"step\", None)\n\n return search_space","input":"{'low': 0, 'high': 3.141592653589793}","output":"{'low': 0, 'high': 3.141592653589793, 'step': None}","cyclomatic_complexity":13,"code_length":24,"category":"Hard"}
{"index":2523,"idx":301,"code":"def validate_mixture(search_space):\n \n search_space = search_space.copy()\n\n if type(search_space) != dict:\n raise ValueError\n\n if \"parameters\" not in search_space.keys():\n raise ValueError\n\n if type(search_space[\"parameters\"]) != list:\n raise ValueError\n\n for i, parameter in enumerate(search_space[\"parameters\"]):\n if (\"category\" not in parameter.keys()) or (parameter[\"category\"] not in (\"normal\",\n \"uniform\",\n \"categorical\")):\n raise ValueError\n\n if \"search_space\" not in parameter.keys() or type(parameter[\"search_space\"]) != dict:\n raise ValueError\n\n search_space[\"parameters\"][i][\"search_space\"] = validate_search_space[\n parameter[\"category\"]](parameter[\"search_space\"])\n\n if \"weights\" not in search_space.keys():\n number_of_values = len(search_space[\"parameters\"])\n search_space[\"probabilities\"] = list(np.ones(number_of_values) \/ number_of_values)\n\n return search_space","input":"{'parameters': [{'category': 'normal', 'search_space': {'mu': 1.5707963267948966, 'sigma': 3.141592653589793, 'low': 0, 'high': 3.141592653589793, 'step': None}}], 'weights': [1.0]}","output":"{'parameters': [{'category': 'normal', 'search_space': {'mu': 1.5707963267948966, 'sigma': 3.141592653589793, 'low': 0, 'high': 3.141592653589793, 'step': None}}], 'weights': [1.0]}","cyclomatic_complexity":8,"code_length":21,"category":"Hard"}
{"index":2524,"idx":302,"code":"def validate_normal(search_space):\n \n search_space = search_space.copy()\n\n if type(search_space) != dict:\n raise ValueError\n\n if \"mu\" not in search_space.keys() or type(search_space[\"mu\"]) not in (int, float):\n print(search_space)\n raise ValueError\n\n if \"sigma\" not in search_space.keys() or type(search_space[\"sigma\"]) not in (int, float):\n raise ValueError\n\n if \"step\" in search_space.keys():\n if search_space[\"step\"] and type(search_space[\"step\"]) not in (int, float):\n raise ValueError\n\n if \"low\" in search_space.keys():\n if type(search_space[\"low\"]) not in (int, float):\n raise ValueError\n\n if \"high\" in search_space.keys():\n if type(search_space[\"high\"]) not in (int, float):\n raise ValueError\n\n if \"high\" in search_space.keys() and \"low\" in search_space.keys():\n if search_space[\"high\"] <= search_space[\"low\"]:\n raise ValueError(\"low <= high\")\n\n search_space.setdefault(\"low\", -np.inf)\n search_space.setdefault(\"high\", -np.inf)\n\n search_space.setdefault(\"step\", None)\n\n return search_space","input":"{'mu': 1.5707963267948966, 'sigma': 0.3, 'low': 0, 'high': 3.141592653589793}","output":"{'mu': 1.5707963267948966, 'sigma': 0.3, 'low': 0, 'high': 3.141592653589793, 'step': None}","cyclomatic_complexity":12,"code_length":25,"category":"Hard"}
{"index":2527,"idx":303,"code":"def validate_categorical(search_space):\n \n search_space = search_space.copy()\n\n if type(search_space) != dict:\n raise ValueError\n if \"values\" not in search_space.keys() or type(search_space['values']) != list:\n raise ValueError\n if \"probabilities\" in search_space.keys() and (\n type(search_space['probabilities']) != list or\n len(search_space['probabilities']) != len(search_space['values'])):\n raise ValueError\n\n \n if \"probabilities\" in search_space.keys():\n np.random.choice(range(len(search_space[\"probabilities\"])),\n p=search_space[\"probabilities\"])\n\n if \"probabilities\" not in search_space.keys():\n number_of_values = len(search_space[\"values\"])\n search_space[\"probabilities\"] = list(np.ones(number_of_values) \/ number_of_values)\n\n return search_space","input":"{'values': [0, 0.6283185307179586, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966, 3.141592653589793]}","output":"{'values': [0, 0.6283185307179586, 0.7853981633974483, 1.0471975511965976, 1.5707963267948966, 3.141592653589793], 'probabilities': [0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666, 0.16666666666666666]}","cyclomatic_complexity":6,"code_length":17,"category":"Hard"}
{"index":2555,"idx":304,"code":"def __missing__(self, b):\n \n if b in _TILDE_ENCODING_SAFE:\n res = chr(b)\n elif b == _space:\n res = \"+\"\n else:\n res = \"~{:02X}\".format(b)\n self[b] = res\n return res","input":"{}, 102","output":"'f'","cyclomatic_complexity":3,"code_length":9,"category":"Easy"}
{"index":2559,"idx":305,"code":"def remove_infinites(row):\n to_check = row\n if isinstance(row, dict):\n to_check = row.values()\n if not any((c in _infinities) if isinstance(c, float) else 0 for c in to_check):\n return row\n if isinstance(row, dict):\n return {\n k: (None if (isinstance(v, float) and v in _infinities) else v)\n for k, v in row.items()\n }\n else:\n return [None if (isinstance(c, float) and c in _infinities) else c for c in row]","input":"REPR FAILED","output":"REPR FAILED","cyclomatic_complexity":4,"code_length":13,"category":"Medium"}
{"index":2560,"idx":306,"code":"def to_css_class(s):\n \n if css_class_re.match(s):\n return s\n md5_suffix = hashlib.md5(s.encode(\"utf8\")).hexdigest()[:6]\n \n s = s.lstrip(\"_\").lstrip(\"-\")\n \n s = \"-\".join(s.split())\n \n s = css_invalid_chars_re.sub(\"\", s)\n \n bits = [b for b in (s, md5_suffix) if b]\n return \"-\".join(bits)","input":"'table\/with\/slashes.csv'","output":"'tablewithslashescsv-fa7563'","cyclomatic_complexity":2,"code_length":9,"category":"Super Easy"}
{"index":2568,"idx":307,"code":"def path_from_row_pks(row, pks, use_rowid, quote=True):\n \n if use_rowid:\n bits = [row[\"rowid\"]]\n else:\n bits = [\n row[pk][\"value\"] if isinstance(row[pk], dict) else row[pk] for pk in pks\n ]\n if quote:\n bits = [tilde_encode(str(bit)) for bit in bits]\n else:\n bits = [str(bit) for bit in bits]\n\n return \",\".join(bits)","input":"REPR FAILED, ['id'], False, False","output":"'1'","cyclomatic_complexity":3,"code_length":12,"category":"Easy"}
|