"{\"inputs\":\"I wrote the below code\\n\\n original_uri = uri\\n seen_uris = set()\\n deadline = (time.time() + timeout)\\n while (time.time() < deadline):\\n if (uri in seen_uris):\\n logger.info(u'Unwrapping stream from URI (%s) failed: playlist referenced itself', uri)\\n return (None, None)\\n else:\\n seen_uris.add(uri)\\n logger.debug(u'Unwrapping stream from URI: %s', uri)\\n try:\\n scan_timeout = (deadline - time.time())\\n if (scan_timeout < 0):\\n logger.info(u'Unwrapping stream from URI (%s) failed: timed out in %sms', uri, timeout)\\n return (None, None)\\n scan_result = scanner.scan(uri, timeout=scan_timeout)\\n except exceptions.ScannerError as exc:\\n logger.debug(u'GStreamer failed scanning URI (%s): %s', uri, exc)\\n scan_result = None\\n if (scan_result is not None):\\n if (scan_result.playable or ((not scan_result.mime.startswith(u'text\\/')) and (not scan_result.mime.startswith(u'application\\/')))):\\n logger.debug(u'Unwrapped potential %s stream: %s', scan_result.mime, uri)\\n return (uri, scan_result)\\n download_timeout = (deadline - time.time())\\n if (download_timeout < 0):\\n logger.info(u'Unwrapping stream from URI (%s) failed: timed out in %sms', uri, timeout)\\n return (None, None)\\n content = http.download(requests_session, uri, timeout=(download_timeout \\/ 1000))\\n if (content is None):\\n logger.info(u'Unwrapping stream from URI (%s) failed: error downloading URI %s', original_uri, uri)\\n return (None, None)\\n uris = playlists.parse(content)\\n if (not uris):\\n logger.debug(u'Failed parsing URI (%s) as playlist; found potential stream.', uri)\\n return (uri, None)\\n logger.debug(u'Parsed ...\\n\\nWhat's a good function header?\",\"targets\":\"def _unwrap_stream(uri, timeout, scanner, requests_session):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef f_classif(X, y):\\n\\n ''''Compute the ANOVA F-value for the provided sample.\\n Read more in the :ref:`User Guide `.\\n Parameters\\n X : {array-like, sparse matrix} shape = [n_samples, n_features]\\n The set of regressors that will be tested sequentially.\\n y : array of shape(n_samples)\\n The data matrix.\\n Returns\\n F : array, shape = [n_features,]\\n The set of F values.\\n pval : array, shape = [n_features,]\\n The set of p-values.\\n See also\\n chi2: Chi-squared stats of non-negative features for classification tasks.\\n f_regression: F-value between label\\/feature for regression tasks.'\\n '''\",\"targets\":\"(X, y) = check_X_y(X, y, ['csr', 'csc', 'coo'])\\n args = [X[safe_mask(X, (y == k))] for k in np.unique(y)]\\n return f_oneway(*args)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@pytest.fixture\\ndef wiki_user(db, django_user_model):\\n\\n ''''A test user.'\\n '''\",\"targets\":\"return django_user_model.objects.create(username='wiki_user', email='wiki_user@example.com', date_joined=datetime(2017, 4, 14, 12, 0))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef make_collectstatic():\\n\\n ''''make_collectstatic() -> True\\/False'\\n '''\",\"targets\":\"statuses = []\\n hue_exec = os.path.join(common.INSTALL_ROOT, 'build', 'env', 'bin', 'hue')\\n if os.path.exists(hue_exec):\\n statuses.append(runcmd([hue_exec, 'collectstatic', '--noinput']))\\n return (not any(statuses))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def install_packages(module, opkg_path, packages):\",\"targets\":\"\\\"\\\"\\\"Installs one or more packages if not already installed.\\n \\\"\\\"\\\"\\n p = module.params\\n force = p['force']\\n if force:\\n force = ('--force-%s' % force)\\n install_c = 0\\n for package in packages:\\n if query_package(module, opkg_path, package):\\n continue\\n (rc, out, err) = module.run_command(('%s install %s %s' % (opkg_path, force, package)))\\n if (not query_package(module, opkg_path, package)):\\n module.fail_json(msg=('failed to install %s: %s' % (package, out)))\\n install_c += 1\\n if (install_c > 0):\\n module.exit_json(changed=True, msg=('installed %s package(s)' % install_c))\\n module.exit_json(changed=False, msg='package(s) already present')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n gemm_code = ''\\n const = 'const'\\n if (not config.blas.ldflags):\\n current_filedir = dirname(__file__)\\n gemm_common_filepath = normpath((current_filedir + '\\/alt_gemm_common.c'))\\n gemm_template_filepath = normpath((current_filedir + '\\/alt_gemm_template.c'))\\n common_code = ''\\n sgemm_code = ''\\n dgemm_code = ''\\n with open(gemm_common_filepath) as code:\\n common_code = code.read()\\n with open(gemm_template_filepath) as code:\\n template_code = code.read()\\n sgemm_code = (template_code % {'float_type': 'float', 'float_size': 4, 'npy_float': 'NPY_FLOAT32', 'name': 'sgemm_'})\\n dgemm_code = (template_code % {'float_type': 'double', 'float_size': 8, 'npy_float': 'NPY_FLOAT64', 'name': 'dgemm_'})\\n if ((not common_code) or (not sgemm_code)):\\n raise IOError('Unable to load NumPy implementation of gemm code from C source files.')\\n else:\\n const = ''\\n gemm_code += common_code\\n gemm_code += sgemm_code\\n gemm_code += dgemm_code\\n header = '\\\\n extern \\\"C\\\"\\\\n {\\\\n\\\\n void xerbla_(char*, void *);\\\\n\\\\n \\/***********\\/\\\\n \\/* Level 1 *\\/\\\\n \\/***********\\/\\\\n\\\\n \\/* Single Precision *\\/\\\\n\\\\n void srot_(const int*, float *, const int*, float *, const int*, const float *, const float *);\\\\n void srotg_(float *,float *,float *,float *);\\\\n void srotm_( const int*, float *, const int*, float *, const int*, const float *);\\\\n void srotmg_(float *,float *,float *,const float *, float *);\\\\n void sswap_( const int*, float *, ...\\n\\nWhat's a good function header?\",\"targets\":\"def blas_header_text():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (kwargs.get('instance') and kwargs.get('created')):\\n return\\n comment = ((('comment' in kwargs) and kwargs['comment']) or kwargs['instance'])\\n entry = comment.content_object\\n if isinstance(entry, Entry):\\n entry.comment_count = entry.comments.count()\\n entry.pingback_count = entry.pingbacks.count()\\n entry.trackback_count = entry.trackbacks.count()\\n entry.save(update_fields=['comment_count', 'pingback_count', 'trackback_count'])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def count_discussions_handler(sender, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def density(w, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Compute density of a sparse vector\\n Return a value between 0 and 1\\n \\\"\\\"\\\"\\n if hasattr(w, 'toarray'):\\n d = (float(w.nnz) \\/ (w.shape[0] * w.shape[1]))\\n else:\\n d = (0 if (w is None) else (float((w != 0).sum()) \\/ w.size))\\n return d\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n auth_logout(request)\\n if (redirect_field_name in request.REQUEST):\\n next_page = request.REQUEST[redirect_field_name]\\n if (not is_safe_url(url=next_page, host=request.get_host())):\\n next_page = request.path\\n if next_page:\\n return HttpResponseRedirect(next_page)\\n current_site = get_current_site(request)\\n context = {'site': current_site, 'site_name': current_site.name, 'title': _('Logged out')}\\n if (extra_context is not None):\\n context.update(extra_context)\\n return TemplateResponse(request, template_name, context, current_app=current_app)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def logout(request, next_page=None, template_name='registration\\/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef add_path(path, config=None):\\n\\n ''''Ensure that the path, or the root of the current package (if\\n path is in a package), is in sys.path.'\\n '''\",\"targets\":\"log.debug(('Add path %s' % path))\\n if (not path):\\n return []\\n added = []\\n parent = os.path.dirname(path)\\n if (parent and os.path.exists(os.path.join(path, '__init__.py'))):\\n added.extend(add_path(parent, config))\\n elif (not (path in sys.path)):\\n log.debug('insert %s into sys.path', path)\\n sys.path.insert(0, path)\\n added.append(path)\\n if (config and config.srcDirs):\\n for dirname in config.srcDirs:\\n dirpath = os.path.join(path, dirname)\\n if os.path.isdir(dirpath):\\n sys.path.insert(0, dirpath)\\n added.append(dirpath)\\n return added\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def expand_args(args, flist):\",\"targets\":\"\\\"\\\"\\\"read names in flist and append to args\\n \\\"\\\"\\\"\\n expanded = args[:]\\n if flist:\\n try:\\n if (flist == '-'):\\n fd = sys.stdin\\n else:\\n fd = open(flist)\\n while 1:\\n line = fd.readline()\\n if (not line):\\n break\\n expanded.append(line[:(-1)])\\n except IOError:\\n print ('Error reading file list %s' % flist)\\n raise\\n return expanded\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def find_space(addr_space, procs, mod_base):\",\"targets\":\"\\\"\\\"\\\"Search for an address space (usually looking for a GUI process)\\n \\\"\\\"\\\"\\n if addr_space.is_valid_address(mod_base):\\n return addr_space\\n for proc in procs:\\n ps_ad = proc.get_process_address_space()\\n if (ps_ad != None):\\n if ps_ad.is_valid_address(mod_base):\\n return ps_ad\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef find_scene_absolute_numbering(indexer_id, indexer, absolute_number):\\n\\n ''''Same as get_scene_numbering(), but returns None if scene numbering is not set'\\n '''\",\"targets\":\"if ((indexer_id is None) or (absolute_number is None)):\\n return absolute_number\\n indexer_id = int(indexer_id)\\n indexer = int(indexer)\\n main_db_con = db.DBConnection()\\n rows = main_db_con.select(u'SELECT scene_absolute_number FROM scene_numbering WHERE indexer = ? and indexer_id = ? and absolute_number = ? and scene_absolute_number != 0', [indexer, indexer_id, absolute_number])\\n if rows:\\n return int(rows[0]['scene_absolute_number'])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_query_handle_and_state(query_history):\\n\\n ''''Front-end wrapper to handle exceptions. Expects the query to be submitted.'\\n '''\",\"targets\":\"handle = query_history.get_handle()\\n if (handle is None):\\n raise PopupException(_('Failed to retrieve query state from the Query Server.'))\\n state = dbms.get(query_history.owner, query_history.get_query_server_config()).get_state(handle)\\n if (state is None):\\n raise PopupException(_('Failed to contact Server to check query status.'))\\n return (handle, state)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __get_image(conn, vm_):\",\"targets\":\"\\\"\\\"\\\"The get_image for GCE allows partial name matching and returns a\\n libcloud object.\\n \\\"\\\"\\\"\\n img = config.get_cloud_config_value('image', vm_, __opts__, default='debian-7', search_global=False)\\n return conn.ex_get_image(img)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n attributes = {}\\n attrs = ''\\n if (';' in header):\\n (header, attrs) = [x.strip() for x in header.split(';', 1)]\\n m = True\\n while m:\\n m = ATTRIBUTES_RE.match(attrs)\\n if m:\\n attrs = attrs[len(m.group(0)):]\\n attributes[m.group(1)] = m.group(2).strip('\\\"')\\n return (header, attributes)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_content_disposition(header):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef chrome_extensions(attrs=None, where=None):\\n\\n ''''Return chrome_extensions information from osquery\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' osquery.chrome_extensions'\\n '''\",\"targets\":\"if salt.utils.platform.is_darwin():\\n return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where)\\n return {'result': False, 'comment': 'Only available on macOS systems.'}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n name = config.get(CONF_NAME)\\n ohmid = config.get(CONF_ID)\\n add_devices([OhmconnectSensor(name, ohmid)], True)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def setup_platform(hass, config, add_devices, discovery_info=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef load_pack_index_file(path, f):\\n\\n ''''Load an index file from a file-like object.\\n :param path: Path for the index file\\n :param f: File-like object\\n :return: A PackIndex loaded from the given file'\\n '''\",\"targets\":\"(contents, size) = _load_file_contents(f)\\n if (contents[:4] == '\\\\xfftOc'):\\n version = struct.unpack('>L', contents[4:8])[0]\\n if (version == 2):\\n return PackIndex2(path, file=f, contents=contents, size=size)\\n else:\\n raise KeyError(('Unknown pack index format %d' % version))\\n else:\\n return PackIndex1(path, file=f, contents=contents, size=size)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def color_config(text):\",\"targets\":\"\\\"\\\"\\\"Set color opitons of Text widget.\\n Should be called whenever ColorDelegator is called.\\n \\\"\\\"\\\"\\n theme = idleConf.CurrentTheme()\\n normal_colors = idleConf.GetHighlight(theme, 'normal')\\n cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg')\\n select_colors = idleConf.GetHighlight(theme, 'hilite')\\n text.config(foreground=normal_colors['foreground'], background=normal_colors['background'], insertbackground=cursor_color, selectforeground=select_colors['foreground'], selectbackground=select_colors['background'], inactiveselectbackground=select_colors['background'])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef GetRequestCpuUsage():\\n\\n ''''Returns the number of megacycles used so far by this request.\\n Returns:\\n The number of megacycles used so far by this request. Does not include CPU\\n used by API calls.'\\n '''\",\"targets\":\"return _apphosting_runtime___python__apiproxy.get_request_cpu_usage()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (type(ob) != pythoncom.TypeIIDs[pythoncom.IID_IEnumVARIANT]):\\n ob = ob.QueryInterface(pythoncom.IID_IEnumVARIANT)\\n return EnumVARIANT(ob, resultCLSID)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def WrapEnum(ob, resultCLSID=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_email(recipients, sender=u'', msg=u'', subject=u'[No Subject]', text_content=None, footer=None, print_html=None, formatted=None, attachments=None, content=None, reply_to=None, cc=[], email_account=None, expose_recipients=None, inline_images=[], header=None):\",\"targets\":\"\\\"\\\"\\\"Prepare an email with the following format:\\n - multipart\\/mixed\\n - multipart\\/alternative\\n - text\\/plain\\n - multipart\\/related\\n - text\\/html\\n - inline image\\n - attachment\\n \\\"\\\"\\\"\\n content = (content or msg)\\n emailobj = EMail(sender, recipients, subject, reply_to=reply_to, cc=cc, email_account=email_account, expose_recipients=expose_recipients)\\n if (not content.strip().startswith(u'<')):\\n content = markdown(content)\\n emailobj.set_html(content, text_content, footer=footer, header=header, print_html=print_html, formatted=formatted, inline_images=inline_images)\\n if isinstance(attachments, dict):\\n attachments = [attachments]\\n for attach in (attachments or []):\\n if (attach.get(u'fcontent') is None):\\n continue\\n emailobj.add_attachment(**attach)\\n return emailobj\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not hasattr(package, 'rindex')):\\n raise ValueError(\\\"'package' not set to a string\\\")\\n dot = len(package)\\n for x in range(level, 1, (-1)):\\n try:\\n dot = package.rindex('.', 0, dot)\\n except ValueError:\\n raise ValueError('attempted relative import beyond top-level package')\\n return ('%s.%s' % (package[:dot], name))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _resolve_name(name, package, level):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n finder = PackageFinder([data.find_links], [], session=PipSession())\\n req = InstallRequirement.from_line('gmpy')\\n found = finder.find_requirement(req, False)\\n assert found.url.endswith('gmpy-1.15.tar.gz'), found\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_no_partial_name_match(data):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def extract(request, response=None):\",\"targets\":\"\\\"\\\"\\\"Extract the IDs of products in the history cookie\\n \\\"\\\"\\\"\\n ids = []\\n cookie_name = settings.OSCAR_RECENTLY_VIEWED_COOKIE_NAME\\n if (cookie_name in request.COOKIES):\\n try:\\n ids = json.loads(request.COOKIES[cookie_name])\\n except ValueError:\\n if response:\\n response.delete_cookie(cookie_name)\\n else:\\n if (not isinstance(ids, list)):\\n ids = []\\n return ids\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _parse_canonical_dbpointer(doc):\",\"targets\":\"\\\"\\\"\\\"Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef.\\n \\\"\\\"\\\"\\n dbref = doc['$dbPointer']\\n if (len(doc) != 1):\\n raise TypeError(('Bad $dbPointer, extra field(s): %s' % (doc,)))\\n if isinstance(dbref, DBRef):\\n dbref_doc = dbref.as_doc()\\n if (dbref.database is not None):\\n raise TypeError(('Bad $dbPointer, extra field $db: %s' % (dbref_doc,)))\\n if (not isinstance(dbref.id, ObjectId)):\\n raise TypeError(('Bad $dbPointer, $id must be an ObjectId: %s' % (dbref_doc,)))\\n if (len(dbref_doc) != 2):\\n raise TypeError(('Bad $dbPointer, extra field(s) in DBRef: %s' % (dbref_doc,)))\\n return dbref\\n else:\\n raise TypeError(('Bad $dbPointer, expected a DBRef: %s' % (doc,)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n pubsub_client = pubsub.Client()\\n topic = pubsub_client.topic(topic_name)\\n subscription = topic.subscription(subscription_name)\\n permissions_to_check = ['pubsub.subscriptions.consume', 'pubsub.subscriptions.update']\\n allowed_permissions = subscription.check_iam_permissions(permissions_to_check)\\n print 'Allowed permissions for subscription {} on topic {}: {}'.format(subscription.name, topic.name, allowed_permissions)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_subscription_permissions(topic_name, subscription_name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_meth_class(obj):\",\"targets\":\"\\\"\\\"\\\"Return method class\\n \\\"\\\"\\\"\\n if PY2:\\n return obj.im_class\\n else:\\n return obj.__self__.__class__\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def f(rv):\\n if (not rv.is_Mul):\\n return rv\\n (n, d) = rv.as_numer_denom()\\n if (n.is_Atom or d.is_Atom):\\n return rv\\n def ok(k, e):\\n return ((e.is_integer or k.is_positive) and ((k.func in (sin, cos)) or (half and k.is_Add and (len(k.args) >= 2) and any((any((((ai.func is cos) or (ai.is_Pow and (ai.base is cos))) for ai in Mul.make_args(a))) for a in k.args)))))\\n n = n.as_powers_dict()\\n ndone = [(k, n.pop(k)) for k in list(n.keys()) if (not ok(k, n[k]))]\\n if (not n):\\n return rv\\n d = d.as_powers_dict()\\n ddone = [(k, d.pop(k)) for k in list(d.keys()) if (not ok(k, d[k]))]\\n if (not d):\\n return rv\\n def factorize(d, ddone):\\n newk = []\\n for k in d:\\n if (k.is_Add and (len(k.args) > 1)):\\n knew = (factor(k) if half else factor_terms(k))\\n if (knew != k):\\n newk.append((k, knew))\\n if newk:\\n for (i, (k, knew)) in enumerate(newk):\\n del d[k]\\n newk[i] = knew\\n newk = Mul(*newk).as_powers_dict()\\n for k in newk:\\n v = (d[k] + newk[k])\\n if ok(k, v):\\n d[k] = v\\n else:\\n ddone.append((k, v))\\n del newk\\n factorize(n, ndone)\\n factorize(d, ddone)\\n t = []\\n for k in n:\\n if (k.func is sin):\\n a = cos(k.args[0], evaluate=False)\\n if ((a in d) and (d[a] == n[k])):\\n t.append((tan(k.args[0]) ** n[k]))\\n n[k] = d[a] = None\\n elif half:\\n a1 = (1 + a)\\n if ((a1 in d) and (d[a1] == n[k])):\\n t.append((tan((k.args[0] \\/ 2)) ** n[k]))\\n n[k] = d[a1] = None\\n elif (k.func is cos):\\n a =...\\n\\nWhat's a good function header?\",\"targets\":\"def TR2i(rv, half=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_logout_url(dest_url, _auth_domain=None):\",\"targets\":\"\\\"\\\"\\\"Computes the logout URL for this request and specified destination URL,\\n for both federated login App and Google Accounts App.\\n Args:\\n dest_url: String that is the desired final destination URL for the user\\n once logout is complete. If \\\\dest_url\\\\ does not have a host\\n specified, we will use the host from the current request.\\n Returns:\\n Logout URL as a string\\n \\\"\\\"\\\"\\n req = user_service_pb.CreateLogoutURLRequest()\\n resp = user_service_pb.CreateLogoutURLResponse()\\n req.set_destination_url(dest_url)\\n if _auth_domain:\\n req.set_auth_domain(_auth_domain)\\n try:\\n apiproxy_stub_map.MakeSyncCall('user', 'CreateLogoutURL', req, resp)\\n except apiproxy_errors.ApplicationError as e:\\n if (e.application_error == user_service_pb.UserServiceError.REDIRECT_URL_TOO_LONG):\\n raise RedirectTooLongError\\n else:\\n raise e\\n return resp.logout_url()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _retry_on_unavailable(exc):\",\"targets\":\"\\\"\\\"\\\"Retry only errors whose status code is \\\\UNAVAILABLE\\\\.\\n \\\"\\\"\\\"\\n from grpc import StatusCode\\n return (exc.code() == StatusCode.UNAVAILABLE)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def load(parser, token):\",\"targets\":\"\\\"\\\"\\\"Load a custom template tag set.\\n For example, to load the template tags in ``django\\/templatetags\\/news\\/photos.py``::\\n {% load news.photos %}\\n \\\"\\\"\\\"\\n bits = token.contents.split()\\n for taglib in bits[1:]:\\n try:\\n lib = get_library(('django.templatetags.%s' % taglib.split('.')[(-1)]))\\n parser.add_library(lib)\\n except InvalidTemplateLibrary as e:\\n raise TemplateSyntaxError, (\\\"'%s' is not a valid tag library: %s\\\" % (taglib, e))\\n return LoadNode()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_lexicon_context(path):\",\"targets\":\"\\\"\\\"\\\"Construct a SyntaxNet TaskContext file for standard lexical resources.\\n \\\"\\\"\\\"\\n context = task_spec_pb2.TaskSpec()\\n for name in ['word-map', 'tag-map', 'tag-to-category', 'lcword-map', 'category-map', 'char-map', 'char-ngram-map', 'label-map', 'prefix-table', 'suffix-table']:\\n context.input.add(name=name).part.add(file_pattern=os.path.join(path, name))\\n return context\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef id_srando():\\n\\n ''''Reset seed values to their original values.'\\n '''\",\"targets\":\"_id.id_srando()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _check_precisions_full(precisions, covariance_type):\",\"targets\":\"\\\"\\\"\\\"Check the precision matrices are symmetric and positive-definite.\\n \\\"\\\"\\\"\\n for prec in precisions:\\n _check_precision_matrix(prec, covariance_type)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@deprecated_renamed_argument('clobber', 'overwrite', '2.0')\\ndef writeto(filename, data, header=None, output_verify='exception', overwrite=False, checksum=False):\",\"targets\":\"\\\"\\\"\\\"Create a new FITS file using the supplied data\\/header.\\n Parameters\\n filename : file path, file object, or file like object\\n File to write to. If opened, must be opened in a writeable binary\\n mode such as \\\\wb\\\\ or \\\\ab+\\\\.\\n data : array, record array, or groups data object\\n data to write to the new file\\n header : `Header` object, optional\\n the header associated with ``data``. If `None`, a header\\n of the appropriate type is created for the supplied data. This\\n argument is optional.\\n output_verify : str\\n Output verification option. Must be one of ``\\\"fix\\\"``, ``\\\"silentfix\\\"``,\\n ``\\\"ignore\\\"``, ``\\\"warn\\\"``, or ``\\\"exception\\\"``. May also be any\\n combination of ``\\\"fix\\\"`` or ``\\\"silentfix\\\"`` with ``\\\"+ignore\\\"``,\\n ``+warn``, or ``+exception\\\" (e.g. ``\\\"fix+warn\\\"``). See :ref:`verify`\\n for more info.\\n overwrite : bool, optional\\n If ``True``, overwrite the output file if it exists. Raises an\\n ``OSError`` (``IOError`` for Python 2) if ``False`` and the\\n output file exists. Default is ``False``.\\n .. versionchanged:: 1.3\\n ``overwrite`` replaces the deprecated ``clobber`` argument.\\n checksum : bool, optional\\n If `True`, adds both ``DATASUM`` and ``CHECKSUM`` cards to the\\n headers of all HDU\\\\s written to the file.\\n \\\"\\\"\\\"\\n hdu = _makehdu(data, header)\\n if (hdu.is_image and (not isinstance(hdu, PrimaryHDU))):\\n hdu = PrimaryHDU(data, header=header)\\n hdu.writeto(filename, overwrite=overwrite, output_verify=output_verify, checksum=checksum)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.filter(is_safe=True)\\ndef random(value):\\n\\n ''''Returns a random item from the list.'\\n '''\",\"targets\":\"return random_module.choice(value)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef addFacesByGrid(faces, grid):\\n\\n ''''Add faces from grid.'\\n '''\",\"targets\":\"cellTopLoops = getIndexedCellLoopsFromIndexedGrid(grid)\\n for cellTopLoop in cellTopLoops:\\n addFacesByConvex(faces, cellTopLoop)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def add_multi_constructor(tag_prefix, multi_constructor, Loader=Loader):\",\"targets\":\"\\\"\\\"\\\"Add a multi-constructor for the given tag prefix.\\n Multi-constructor is called for a node if its tag starts with tag_prefix.\\n Multi-constructor accepts a Loader instance, a tag suffix,\\n and a node object and produces the corresponding Python object.\\n \\\"\\\"\\\"\\n Loader.add_multi_constructor(tag_prefix, multi_constructor)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n alpha = ppf(((confidence + 1) \\/ 2), (sample_size - 1))\\n margin = (stddev \\/ sqrt(sample_size))\\n return ((point_estimate - (alpha * margin)), (point_estimate + (alpha * margin)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def confidence_interval_continuous(point_estimate, stddev, sample_size, confidence=0.95, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n data = f.read(1)\\n if data:\\n return ord(data)\\n raise ValueError('not enough data in stream to read uint1')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def read_uint1(f):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n proxy_username = None\\n proxy_password = None\\n proxy_username = os.environ.get('proxy-username')\\n if (not proxy_username):\\n proxy_username = os.environ.get('proxy_username')\\n proxy_password = os.environ.get('proxy-password')\\n if (not proxy_password):\\n proxy_password = os.environ.get('proxy_password')\\n if (not proxy_username):\\n if ('@' in proxy_settings):\\n protocol_and_proxy_auth = proxy_settings.split('@')[0].split(':')\\n if (len(protocol_and_proxy_auth) == 3):\\n proxy_username = protocol_and_proxy_auth[1].lstrip('\\/')\\n proxy_password = protocol_and_proxy_auth[2]\\n elif (len(protocol_and_proxy_auth) == 2):\\n proxy_username = protocol_and_proxy_auth[0]\\n proxy_password = protocol_and_proxy_auth[1]\\n if proxy_username:\\n user_auth = base64.encodestring(('%s:%s' % (proxy_username, proxy_password)))\\n return ('Basic %s\\\\r\\\\n' % user_auth.strip())\\n else:\\n return ''\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_proxy_auth(proxy_settings):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _collins_crt(r, R, P, p, K):\\n\\n ''''Wrapper of CRT for Collins\\\\'s resultant algorithm.'\\n '''\",\"targets\":\"return gf_int(gf_crt([r, R], [P, p], K), (P * p))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def batch_normalization_test(inputs, gamma, beta, mean, var, axes='per-activation', epsilon=0.0001):\",\"targets\":\"\\\"\\\"\\\"Performs batch normalization of the given inputs, using the given mean and\\n variance.\\n Parameters\\n axes : \\\\per-activation\\\\, \\\\spatial\\\\ or a tuple of ints\\n The axes along which the input should be normalized. ``\\\\per-activation\\\\``\\n normalizes per activation and is equal to ``axes=(0,)``.\\n ``\\\\spatial\\\\`` shares normalization factors across spatial dimensions\\n (i.e., all dimensions past the second), which for 4D inputs would be\\n equal to ``axes=(0, 2, 3)``.\\n gamma : tensor\\n Scale factors. The shape must match the shape of `inputs`,\\n except for the axes in `axes`. These axes should be set to 1 or be\\n skipped altogether (such that `gamma.ndim == inputs.ndim - len(axes)`).\\n beta : tensor\\n Biases. Must match the tensor layout of `gamma`.\\n mean : tensor\\n Means. Usually these are running averages computed during training.\\n Must match the tensor layout of `gamma`.\\n var : tensor\\n Variances. Usually these are running averages computed during training.\\n Must match the tensor layout of `gamma`.\\n epsilon : float\\n Epsilon value used in the batch normalization formula. Minimum allowed\\n value is 1e-5 (imposed by cuDNN).\\n Returns\\n out : tensor\\n Batch-normalized inputs.\\n Notes\\n If per-activation or spatial normalization is selected, this operation\\n will use the cuDNN implementation. (This requires cuDNN 5 or newer.)\\n The returned value is equivalent to:\\n .. code-block:: python\\n # for per-activation normalization\\n axes = (0,)\\n # for spatial normalization\\n axes = (0,) + tuple(range(2, inputs.ndim))\\n gamma, beta, mean, var = (T.addbroadcast(t, *axes)\\n for t in (gamma, beta, mean, var))\\n out = (inputs - mean) * gamma \\/ T.sqrt(var + epsilon) + beta\\n \\\"\\\"\\\"\\n ndim = inputs.ndim\\n (axes, non_bc_axes) = _prepare_batch_normalization_axes(axes, ndim)\\n if (gamma.ndim == ndim):\\n params_ndim = ndim\\n else:\\n params_ndim = len(non_bc_axes)\\n params_dimshuffle_pattern = (['x'] * ndim)\\n for (i, axis) in enumerate(non_bc_axes):\\n params_dimshuffle_pattern[axis] = i\\n if ((gamma.ndim != params_ndim) or (beta.ndim != params_ndim)):\\n raise ValueError(('gamma and beta dimensionality must match the number of non-normalized axes, or have the same number of dimensions as the inputs; got %d and %d instead of %d' % (gamma.ndim, beta.ndim, params_ndim)))\\n if ((mean.ndim != params_ndim) or (var.ndim != params_ndim)):\\n raise ValueError(('mean and var must be of the same dimensionality as gamma and beta; got %d and %d instead of %d' % (mean.ndim, var.ndim, params_ndim)))\\n epsilon = np.cast[theano.config.floatX](epsilon)\\n if (epsilon < 1e-05):\\n raise ValueError(('epsilon must be at least 1e-5, got %s' % str(epsilon)))\\n gamma = as_tensor_variable(gamma)\\n beta = as_tensor_variable(beta)\\n mean = as_tensor_variable(mean)\\n var = as_tensor_variable(var)\\n if (params_ndim != ndim):\\n gamma = gamma.dimshuffle(params_dimshuffle_pattern)\\n beta = beta.dimshuffle(params_dimshuffle_pattern)\\n mean = mean.dimshuffle(params_dimshuffle_pattern)\\n var = var.dimshuffle(params_dimshuffle_pattern)\\n else:\\n gamma = T.addbroadcast(gamma, *axes)\\n beta = T.addbroadcast(beta, *axes)\\n mean = T.addbroadcast(mean, *axes)\\n var = T.addbroadcast(var, *axes)\\n batchnorm_op = AbstractBatchNormInference(axes=axes)\\n return batchnorm_op(inputs, gamma, beta, mean, var, epsilon=epsilon)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef describe_token(token):\\n\\n ''''Returns a description of the token.'\\n '''\",\"targets\":\"if (token.type == 'name'):\\n return token.value\\n return _describe_token_type(token.type)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (lin_op.type is lo.NEG):\\n result = value\\n elif (lin_op.type is lo.MUL):\\n coeff = mul(lin_op.data, {}, True)\\n if np.isscalar(coeff):\\n result = (coeff * value)\\n else:\\n result = (coeff.T * value)\\n elif (lin_op.type is lo.DIV):\\n divisor = mul(lin_op.data, {}, True)\\n result = (value \\/ divisor)\\n elif (lin_op.type is lo.CONV):\\n result = conv_mul(lin_op, value, True, True)\\n else:\\n result = op_tmul(lin_op, value)\\n return result\\n\\n\\nWhat's a good function header?\",\"targets\":\"def op_abs_tmul(lin_op, value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef load():\\n\\n ''''Load the yearly sunspot data and returns a data class.\\n Returns\\n Dataset instance:\\n See DATASET_PROPOSAL.txt for more information.\\n Notes\\n This dataset only contains data for one variable, so the attributes\\n data, raw_data, and endog are all the same variable. There is no exog\\n attribute defined.'\\n '''\",\"targets\":\"data = _get_data()\\n endog_name = 'SUNACTIVITY'\\n endog = array(data[endog_name], dtype=float)\\n dataset = Dataset(data=data, names=[endog_name], endog=endog, endog_name=endog_name)\\n return dataset\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _get_network_obj(addr):\",\"targets\":\"\\\"\\\"\\\"Try to convert a string into a valid IP Network object.\\n \\\"\\\"\\\"\\n ip_netw = None\\n try:\\n ip_netw = IPNetwork(addr)\\n except AddrFormatError:\\n return ip_netw\\n return ip_netw\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef ensure_dir_exists(directory):\\n\\n ''''Given a valid directory path, make sure it exists.'\\n '''\",\"targets\":\"if dir:\\n if (not os.path.isdir(directory)):\\n os.makedirs(directory)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def _eat_client_exception(*args):\\n try:\\n return direct_head_container(*args)\\n except ClientException as err:\\n if (err.http_status == 404):\\n return err.http_headers\\n except (Timeout, socket.error):\\n pass\\n pile = GreenPile()\\n (part, nodes) = container_ring.get_nodes(account_name, container_name)\\n for node in nodes:\\n pile.spawn(_eat_client_exception, node, part, account_name, container_name)\\n headers = [x for x in pile if (x is not None)]\\n if (len(headers) < majority_size(len(nodes))):\\n return\\n return best_policy_index(headers)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@LRUCache(maxtime=CONTAINER_POLICY_TTL)\\ndef direct_get_container_policy_index(container_ring, account_name, container_name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef collect_members(module_to_name):\\n\\n ''''Collect all symbols from a list of modules.\\n Args:\\n module_to_name: Dictionary mapping modules to short names.\\n Returns:\\n Dictionary mapping name to (fullname, member) pairs.'\\n '''\",\"targets\":\"members = {}\\n for (module, module_name) in module_to_name.items():\\n all_names = getattr(module, '__all__', None)\\n for (name, member) in inspect.getmembers(module):\\n if ((inspect.isfunction(member) or inspect.isclass(member)) and (not _always_drop_symbol_re.match(name)) and ((all_names is None) or (name in all_names))):\\n fullname = ('%s.%s' % (module_name, name))\\n if (name in members):\\n (other_fullname, other_member) = members[name]\\n if (member is not other_member):\\n raise RuntimeError(('Short name collision between %s and %s' % (fullname, other_fullname)))\\n if (len(fullname) == len(other_fullname)):\\n raise RuntimeError((\\\"Can't decide whether to use %s or %s for %s: both full names have length %d\\\" % (fullname, other_fullname, name, len(fullname))))\\n if (len(fullname) > len(other_fullname)):\\n continue\\n members[name] = (fullname, member)\\n return members\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def lookup_object(model, object_id, slug, slug_field):\",\"targets\":\"\\\"\\\"\\\"Return the ``model`` object with the passed ``object_id``. If\\n ``object_id`` is None, then return the object whose ``slug_field``\\n equals the passed ``slug``. If ``slug`` and ``slug_field`` are not passed,\\n then raise Http404 exception.\\n \\\"\\\"\\\"\\n lookup_kwargs = {}\\n if object_id:\\n lookup_kwargs[('%s__exact' % model._meta.pk.name)] = object_id\\n elif (slug and slug_field):\\n lookup_kwargs[('%s__exact' % slug_field)] = slug\\n else:\\n raise GenericViewError('Generic view must be called with either an object_id or a slug\\/slug_field.')\\n try:\\n return model.objects.get(**lookup_kwargs)\\n except ObjectDoesNotExist:\\n raise Http404(('No %s found for %s' % (model._meta.verbose_name, lookup_kwargs)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _sweep_poly_phase(t, poly):\",\"targets\":\"\\\"\\\"\\\"Calculate the phase used by sweep_poly to generate its output.\\n See `sweep_poly` for a description of the arguments.\\n \\\"\\\"\\\"\\n intpoly = polyint(poly)\\n phase = ((2 * pi) * polyval(intpoly, t))\\n return phase\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef histogram(image_data, rpc=None):\\n\\n ''''Calculates the histogram of the given image.\\n Args:\\n image_data: str, source image data.\\n rpc: An optional UserRPC object.\\n Returns: 3 256-element lists containing the number of occurences of each\\n value of each color in the order RGB.\\n Raises:\\n NotImageError when the image data given is not an image.\\n BadImageError when the image data given is corrupt.\\n LargeImageError when the image data given is too large to process.\\n Error when something unknown, but bad, happens.'\\n '''\",\"targets\":\"rpc = histogram_async(image_data, rpc=rpc)\\n return rpc.get_result()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef make_cookie_values(cj, class_name):\\n\\n ''''Makes a string of cookie keys and values.\\n Can be used to set a Cookie header.'\\n '''\",\"targets\":\"path = ('\\/' + class_name)\\n cookies = [((c.name + '=') + c.value) for c in cj if ((c.domain == 'class.coursera.org') and (c.path == path))]\\n return '; '.join(cookies)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def compat_patch_logging_config(logging_config):\",\"targets\":\"\\\"\\\"\\\"Backwards-compatibility shim for #16288 fix. Takes initial value of\\n ``LOGGING`` setting and patches it in-place (issuing deprecation warning)\\n if \\\"mail_admins\\\" logging handler is configured but has no filters.\\n \\\"\\\"\\\"\\n if ('filters' not in logging_config.get('handlers', {}).get('mail_admins', {'filters': []})):\\n warnings.warn(\\\"You have no filters defined on the 'mail_admins' logging handler: adding implicit debug-false-only filter. See http:\\/\\/docs.djangoproject.com\\/en\\/dev\\/releases\\/1.4\\/#request-exceptions-are-now-always-logged\\\", DeprecationWarning)\\n filter_name = 'require_debug_false'\\n filters = logging_config.setdefault('filters', {})\\n while (filter_name in filters):\\n filter_name = (filter_name + '_')\\n filters[filter_name] = {'()': 'django.utils.log.RequireDebugFalse'}\\n logging_config['handlers']['mail_admins']['filters'] = [filter_name]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n info = show_fiff(fname_evoked)\\n keys = ['FIFF_EPOCH', 'FIFFB_HPI_COIL', 'FIFFB_PROJ_ITEM', 'FIFFB_PROCESSED_DATA', 'FIFFB_EVOKED', 'FIFF_NAVE', 'FIFF_EPOCH']\\n assert_true(all(((key in info) for key in keys)))\\n info = show_fiff(fname_raw, read_limit=1024)\\n assert_true(('COORD_TRANS' in show_fiff(fname_fsaverage_trans)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"@testing.requires_testing_data\\ndef test_show_fiff():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n p = subprocess.Popen(args=command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\\n (stdout, stderr) = p.communicate()\\n if p.returncode:\\n template = description\\n template += ' failed: (cmd=[%s], stdout=[%s], stderr=[%s])'\\n message = (template % (command, stdout, stderr))\\n raise AssertionError(message)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_command(command, description):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n logging.warning('Hermes is shutting down.')\\n IOLoop.instance().stop()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def shutdown():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not bin_env):\\n raise CommandNotFoundError('Could not find a `activate` binary')\\n if os.path.isdir(bin_env):\\n if salt.utils.platform.is_windows():\\n activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')\\n else:\\n activate_bin = os.path.join(bin_env, 'bin', 'activate')\\n if os.path.isfile(activate_bin):\\n return activate_bin\\n raise CommandNotFoundError('Could not find a `activate` binary')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_env_activate(bin_env):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if filename.split('\\/')[2].startswith(_CREATION_HANDLE_PREFIX):\\n raise InvalidFileNameError(('File %s should have finalized filename' % filename))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def __checkIsFinalizedName(filename):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (fc, f) = dmp_ground_primitive(f, u, K)\\n (gc, g) = dmp_ground_primitive(g, u, K)\\n c = K.lcm(fc, gc)\\n h = dmp_quo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K)\\n return dmp_mul_ground(h, c, u, K)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def dmp_rr_lcm(f, g, u, K):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def libvlc_media_player_new(p_libvlc_instance):\",\"targets\":\"\\\"\\\"\\\"Create an empty Media Player object.\\n @param p_libvlc_instance: the libvlc instance in which the Media Player should be created.\\n @return: a new media player object, or NULL on error.\\n \\\"\\\"\\\"\\n f = (_Cfunctions.get('libvlc_media_player_new', None) or _Cfunction('libvlc_media_player_new', ((1,),), class_result(MediaPlayer), ctypes.c_void_p, Instance))\\n return f(p_libvlc_instance)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef laplacian(csgraph, normed=False, return_diag=False, use_out_degree=False):\\n\\n ''''Return the Laplacian matrix of a directed graph.\\n Parameters\\n csgraph : array_like or sparse matrix, 2 dimensions\\n compressed-sparse graph, with shape (N, N).\\n normed : bool, optional\\n If True, then compute normalized Laplacian.\\n return_diag : bool, optional\\n If True, then also return an array related to vertex degrees.\\n use_out_degree : bool, optional\\n If True, then use out-degree instead of in-degree.\\n This distinction matters only if the graph is asymmetric.\\n Default: False.\\n Returns\\n lap : ndarray or sparse matrix\\n The N x N laplacian matrix of csgraph. It will be a numpy array (dense)\\n if the input was dense, or a sparse matrix otherwise.\\n diag : ndarray, optional\\n The length-N diagonal of the Laplacian matrix.\\n For the normalized Laplacian, this is the array of square roots\\n of vertex degrees or 1 if the degree is zero.\\n Notes\\n The Laplacian matrix of a graph is sometimes referred to as the\\n \\\"Kirchoff matrix\\\" or the \\\"admittance matrix\\\", and is useful in many\\n parts of spectral graph theory. In particular, the eigen-decomposition\\n of the laplacian matrix can give insight into many properties of the graph.\\n Examples\\n >>> from scipy.sparse import csgraph\\n >>> G = np.arange(5) * np.arange(5)[:, np.newaxis]\\n >>> G\\n array([[ 0, 0, 0, 0, 0],\\n [ 0, 1, 2, 3, 4],\\n [ 0, 2, 4, 6, 8],\\n [ 0, 3, 6, 9, 12],\\n [ 0, 4, 8, 12, 16]])\\n >>> csgraph.laplacian(G, normed=False)\\n array([[ 0, 0, 0, 0, 0],\\n [ 0, 9, -2, -3, -4],\\n [ 0, -2, 16, -6, -8],\\n [ 0, -3, -6, 21, -12],\\n [ 0, -4, -8, -12, 24]])'\\n '''\",\"targets\":\"if ((csgraph.ndim != 2) or (csgraph.shape[0] != csgraph.shape[1])):\\n raise ValueError('csgraph must be a square matrix or array')\\n if (normed and (np.issubdtype(csgraph.dtype, np.signedinteger) or np.issubdtype(csgraph.dtype, np.uint))):\\n csgraph = csgraph.astype(float)\\n create_lap = (_laplacian_sparse if isspmatrix(csgraph) else _laplacian_dense)\\n degree_axis = (1 if use_out_degree else 0)\\n (lap, d) = create_lap(csgraph, normed=normed, axis=degree_axis)\\n if return_diag:\\n return (lap, d)\\n return lap\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@shared_task(bind=True)\\ndef ids(self, i):\",\"targets\":\"\\\"\\\"\\\"Returns a tuple of ``root_id``, ``parent_id`` and\\n the argument passed as ``i``.\\n \\\"\\\"\\\"\\n return (self.request.root_id, self.request.parent_id, i)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef kit_item():\\n\\n ''''REST controller to retrieve budget_kit_item field options'\\n '''\",\"targets\":\"s3.prep = (lambda r: (r.representation == 's3json'))\\n return s3_rest_controller()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not name):\\n raise SaltInvocationError('Required parameter `name` is missing.')\\n server = _connect()\\n if (not job_exists(name)):\\n raise SaltInvocationError('Job `{0}` does not exist.'.format(name))\\n job_info = server.get_job_info(name)\\n if job_info:\\n return job_info\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_job_info(name=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_tld_list():\\n\\n ''''Returns a list of TLDs as objects\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'my-minion\\\\' namecheap_domains.get_tld_list'\\n '''\",\"targets\":\"response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist'))\\n if (response_xml is None):\\n return []\\n tldresult = response_xml.getElementsByTagName('Tlds')[0]\\n tlds = []\\n for e in tldresult.getElementsByTagName('Tld'):\\n tld = salt.utils.namecheap.atts_to_dict(e)\\n tld['data'] = e.firstChild.data\\n categories = []\\n subcategories = e.getElementsByTagName('Categories')[0]\\n for c in subcategories.getElementsByTagName('TldCategory'):\\n categories.append(salt.utils.namecheap.atts_to_dict(c))\\n tld['categories'] = categories\\n tlds.append(tld)\\n return tlds\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getdecoder(encoding):\",\"targets\":\"\\\"\\\"\\\"Lookup up the codec for the given encoding and return\\n its decoder function.\\n Raises a LookupError in case the encoding cannot be found.\\n \\\"\\\"\\\"\\n return lookup(encoding).decode\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef internal_prep_stream_message(realm, sender, stream_name, topic, content):\\n\\n ''''See _internal_prep_message for details of how this works.'\\n '''\",\"targets\":\"parsed_recipients = [stream_name]\\n return _internal_prep_message(realm=realm, sender=sender, recipient_type_name='stream', parsed_recipients=parsed_recipients, subject=topic, content=content)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef crc32(path):\\n\\n ''''Return a CRC32 checksum of a file'\\n '''\",\"targets\":\"return (binascii.crc32(open(path, 'rb').read()) & 4294967295)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _nssplit(qualifiedName):\",\"targets\":\"\\\"\\\"\\\"Split a qualified name into namespace part and local part.\\n \\\"\\\"\\\"\\n fields = qualifiedName.split(':', 1)\\n if (len(fields) == 2):\\n return fields\\n else:\\n return (None, fields[0])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _parse_localename(localename):\\n\\n ''''Parses the locale code for localename and returns the\\n result as tuple (language code, encoding).\\n The localename is normalized and passed through the locale\\n alias engine. A ValueError is raised in case the locale name\\n cannot be parsed.\\n The language code corresponds to RFC 1766. code and encoding\\n can be None in case the values cannot be determined or are\\n unknown to this implementation.'\\n '''\",\"targets\":\"code = normalize(localename)\\n if ('@' in code):\\n (code, modifier) = code.split('@')\\n if ((modifier == 'euro') and ('.' not in code)):\\n return (code, 'iso-8859-15')\\n if ('.' in code):\\n return tuple(code.split('.')[:2])\\n elif (code == 'C'):\\n return (None, None)\\n raise ValueError, ('unknown locale: %s' % localename)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@np.deprecate(message='stats.betai is deprecated in scipy 0.17.0; use special.betainc instead')\\ndef betai(a, b, x):\",\"targets\":\"\\\"\\\"\\\"Return the incomplete beta function.\\n I_x(a,b) = 1\\/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt)\\n where a,b>0 and B(a,b) = G(a)*G(b)\\/(G(a+b)) where G(a) is the gamma\\n function of a.\\n The standard broadcasting rules apply to a, b, and x.\\n Parameters\\n a : array_like or float > 0\\n b : array_like or float > 0\\n x : array_like or float\\n x will be clipped to be no greater than 1.0 .\\n Returns\\n betai : ndarray\\n Incomplete beta function.\\n \\\"\\\"\\\"\\n return _betai(a, b, x)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_iterable(x):\\n\\n ''''A implementation independent way of checking for iterables'\\n '''\",\"targets\":\"try:\\n iter(x)\\n except TypeError:\\n return False\\n else:\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_file_mode(filename, default='readonly'):\\n\\n ''''Allow file object to already be opened in any of the valid modes and\\n and leave the file in the same state (opened or closed) as when\\n the function was called.'\\n '''\",\"targets\":\"mode = default\\n closed = fileobj_closed(filename)\\n fmode = fileobj_mode(filename)\\n if (fmode is not None):\\n mode = FILE_MODES.get(fmode)\\n if (mode is None):\\n raise IOError('File mode of the input file object ({!r}) cannot be used to read\\/write FITS files.'.format(fmode))\\n return (mode, closed)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Only load this module if pymongo is installed'\\n '''\",\"targets\":\"if HAS_MONGODB:\\n return 'mongodb'\\n else:\\n return (False, 'The mongodb execution module cannot be loaded: the pymongo library is not available.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_port_from_device(port_id):\",\"targets\":\"\\\"\\\"\\\"Get port from database\\n \\\"\\\"\\\"\\n LOG.debug(_('get_port_with_securitygroups() called:port_id=%s'), port_id)\\n session = db.get_session()\\n sg_binding_port = sg_db.SecurityGroupPortBinding.port_id\\n query = session.query(models_v2.Port, sg_db.SecurityGroupPortBinding.security_group_id)\\n query = query.outerjoin(sg_db.SecurityGroupPortBinding, (models_v2.Port.id == sg_binding_port))\\n query = query.filter((models_v2.Port.id == port_id))\\n port_and_sgs = query.all()\\n if (not port_and_sgs):\\n return None\\n port = port_and_sgs[0][0]\\n plugin = manager.QuantumManager.get_plugin()\\n port_dict = plugin._make_port_dict(port)\\n port_dict[ext_sg.SECURITYGROUPS] = [sg_id for (port, sg_id) in port_and_sgs if sg_id]\\n port_dict['security_group_rules'] = []\\n port_dict['security_group_source_groups'] = []\\n port_dict['fixed_ips'] = [ip['ip_address'] for ip in port['fixed_ips']]\\n return port_dict\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@mock_ec2_deprecated\\ndef test_igw_detach_unattached():\\n\\n ''''internet gateway fail to detach unattached'\\n '''\",\"targets\":\"conn = boto.connect_vpc(u'the_key', u'the_secret')\\n igw = conn.create_internet_gateway()\\n vpc = conn.create_vpc(VPC_CIDR)\\n with assert_raises(EC2ResponseError) as cm:\\n conn.detach_internet_gateway(igw.id, vpc.id)\\n cm.exception.code.should.equal(u'Gateway.NotAttached')\\n cm.exception.status.should.equal(400)\\n cm.exception.request_id.should_not.be.none\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def S_IMODE(mode):\",\"targets\":\"\\\"\\\"\\\"Return the portion of the file\\\\s mode that can be set by\\n os.chmod().\\n \\\"\\\"\\\"\\n return (mode & 4095)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@frame_transform_graph.transform(coord.StaticMatrixTransform, Sagittarius, coord.Galactic)\\ndef sgr_to_galactic():\",\"targets\":\"\\\"\\\"\\\"Compute the transformation matrix from heliocentric Sgr coordinates to\\n spherical Galactic.\\n \\\"\\\"\\\"\\n return matrix_transpose(SGR_MATRIX)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for key in keys:\\n if ((key in b) and (a[key] != b[key])):\\n return False\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def targets_equal(keys, a, b):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_host_info(node_info, host):\",\"targets\":\"\\\"\\\"\\\"Simple callback that takes the node info from `\\/_cluster\\/nodes` and a\\n parsed connection information and return the connection information. If\\n `None` is returned this node will be skipped.\\n Useful for filtering nodes (by proximity for example) or if additional\\n information needs to be provided for the :class:`~elasticsearch.Connection`\\n class. By default master only nodes are filtered out since they shouldn\\\\t\\n typically be used for API operations.\\n :arg node_info: node information from `\\/_cluster\\/nodes`\\n :arg host: connection information (host, port) extracted from the node info\\n \\\"\\\"\\\"\\n if (node_info.get('roles', []) == ['master']):\\n return None\\n return host\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _anderson_ksamp_right(samples, Z, Zstar, k, n, N):\\n\\n ''''Compute A2akN equation 6 of Scholz & Stephens.\\n Parameters\\n samples : sequence of 1-D array_like\\n Array of sample arrays.\\n Z : array_like\\n Sorted array of all observations.\\n Zstar : array_like\\n Sorted array of unique observations.\\n k : int\\n Number of samples.\\n n : array_like\\n Number of observations in each sample.\\n N : int\\n Total number of observations.\\n Returns\\n A2KN : float\\n The A2KN statistics of Scholz and Stephens 1987.'\\n '''\",\"targets\":\"A2kN = 0.0\\n lj = (Z.searchsorted(Zstar[:(-1)], 'right') - Z.searchsorted(Zstar[:(-1)], 'left'))\\n Bj = lj.cumsum()\\n for i in arange(0, k):\\n s = np.sort(samples[i])\\n Mij = s.searchsorted(Zstar[:(-1)], side='right')\\n inner = (((lj \\/ float(N)) * (((N * Mij) - (Bj * n[i])) ** 2)) \\/ (Bj * (N - Bj)))\\n A2kN += (inner.sum() \\/ n[i])\\n return A2kN\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (VCR_RECORD_MODE == u'off'):\\n (yield None)\\n else:\\n module = request.module.__name__.split(u'tests.')[(-1)]\\n class_name = request.cls.__name__\\n cassette_name = u'.'.join([module, class_name, request.function.__name__])\\n cassette_path = os.path.join(VCR_CASSETTE_DIR, cassette_name)\\n online = True\\n if (vcr.record_mode == u'none'):\\n online = False\\n elif (vcr.record_mode == u'once'):\\n online = (not os.path.exists(cassette_path))\\n if (not online):\\n log.debug(u'Disabling domain limiters during VCR playback.')\\n monkeypatch.setattr(u'flexget.utils.requests.limit_domains', mock.Mock())\\n with vcr.use_cassette(path=cassette_path) as cassette:\\n (yield cassette)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.yield_fixture()\\ndef use_vcr(request, monkeypatch):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getnameinfo(sockaddr, flags):\\n\\n ''''getnameinfo(sockaddr, flags) -> (host, port)\\n Get host and port for a sockaddr.\\n .. seealso:: :doc:`dns`'\\n '''\",\"targets\":\"return get_hub().resolver.getnameinfo(sockaddr, flags)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _compressed_sparse_stack(blocks, axis):\\n\\n ''''Stacking fast path for CSR\\/CSC matrices\\n (i) vstack for CSR, (ii) hstack for CSC.'\\n '''\",\"targets\":\"other_axis = (1 if (axis == 0) else 0)\\n data = np.concatenate([b.data for b in blocks])\\n indices = np.concatenate([b.indices for b in blocks])\\n indptr = []\\n last_indptr = 0\\n constant_dim = blocks[0].shape[other_axis]\\n sum_dim = 0\\n for b in blocks:\\n if (b.shape[other_axis] != constant_dim):\\n raise ValueError(('incompatible dimensions for axis %d' % other_axis))\\n sum_dim += b.shape[axis]\\n indptr.append((b.indptr[:(-1)] + last_indptr))\\n last_indptr += b.indptr[(-1)]\\n indptr.append([last_indptr])\\n indptr = np.concatenate(indptr)\\n if (axis == 0):\\n return csr_matrix((data, indices, indptr), shape=(sum_dim, constant_dim))\\n else:\\n return csc_matrix((data, indices, indptr), shape=(constant_dim, sum_dim))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef main():\\n\\n ''''Check starting conditions and start GUI.\\n First, check command line arguments and start loggers. Set log levels. Try\\n all imports and exit verbosely if a library is not found. Disable outputs\\n to stdout and start the GUI.'\\n '''\",\"targets\":\"qtlogger = logging.getLogger('PyQt5')\\n qtlogger.setLevel(logging.ERROR)\\n parser = argparse.ArgumentParser(description='cfclient - Crazyflie graphical control client')\\n parser.add_argument('--debug', '-d', nargs=1, default='info', type=str, help='set debug level [minimal, info, debug, debugfile]')\\n args = parser.parse_args()\\n debug = args.debug\\n cflogger = logging.getLogger('')\\n if ('debugfile' in debug):\\n logging.basicConfig(level=logging.DEBUG)\\n formatter = logging.Formatter('%(asctime)s:%(threadName)s:%(name)s:%(levelname)s:%(message)s')\\n filename = ('debug-%s.log' % datetime.datetime.now())\\n filehandler = logging.FileHandler(filename)\\n filehandler.setLevel(logging.DEBUG)\\n filehandler.setFormatter(formatter)\\n cflogger.addHandler(filehandler)\\n elif ('debug' in debug):\\n logging.basicConfig(level=logging.DEBUG)\\n elif ('minimal' in debug):\\n logging.basicConfig(level=logging.WARNING)\\n elif ('info' in debug):\\n logging.basicConfig(level=logging.INFO)\\n logger = logging.getLogger(__name__)\\n logger.debug('Using config path {}'.format(cfclient.config_path))\\n logger.debug('sys.path={}'.format(sys.path))\\n try:\\n import usb\\n except ImportError:\\n logger.critical('No pyusb installation found, exiting!')\\n sys.exit(1)\\n if (not sys.platform.startswith('linux')):\\n try:\\n import sdl2\\n except ImportError:\\n logger.critical('No pysdl2 installation found, exiting!')\\n sys.exit(1)\\n try:\\n import PyQt5\\n except ImportError:\\n logger.critical('No PyQT5 installation found, exiting!')\\n sys.exit(1)\\n if (os.name == 'posix'):\\n stdout = os.dup(1)\\n os.dup2(os.open('\\/dev\\/null', os.O_WRONLY), 1)\\n sys.stdout = os.fdopen(stdout, 'w')\\n logger.info('Disabling STL printouts')\\n if (os.name == 'nt'):\\n stdout = os.dup(1)\\n...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef check_known_inconsistencies(bill_data, bond_data):\\n\\n ''''There are a couple quirks in the data provided by Bank of Canada.\\n Check that no new quirks have been introduced in the latest download.'\\n '''\",\"targets\":\"inconsistent_dates = bill_data.index.sym_diff(bond_data.index)\\n known_inconsistencies = [pd.Timestamp('2006-09-04', tz='UTC'), pd.Timestamp('2010-02-15', tz='UTC'), pd.Timestamp('2013-07-25', tz='UTC')]\\n unexpected_inconsistences = inconsistent_dates.drop(known_inconsistencies)\\n if len(unexpected_inconsistences):\\n in_bills = bill_data.index.difference(bond_data.index).difference(known_inconsistencies)\\n in_bonds = bond_data.index.difference(bill_data.index).difference(known_inconsistencies)\\n raise ValueError('Inconsistent dates for Canadian treasury bills vs bonds. \\\\nDates with bills but not bonds: {in_bills}.\\\\nDates with bonds but not bills: {in_bonds}.'.format(in_bills=in_bills, in_bonds=in_bonds))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n be = get_backend(request)\\n def cleanup():\\n be = request.getfuncargvalue('backend_default')\\n del be\\n request.addfinalizer(cleanup)\\n return be\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.fixture(scope='module', params=['gpu', 'cpu'])\\ndef backend_default(request):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n assert (errors == 'strict')\\n output = zlib.decompress(input)\\n return (output, len(input))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def zlib_decode(input, errors='strict'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef delete_object(container_name, object_name, profile, **libcloud_kwargs):\\n\\n ''''Delete an object in the cloud\\n :param container_name: Container name\\n :type container_name: ``str``\\n :param object_name: Object name\\n :type object_name: ``str``\\n :param profile: The profile key\\n :type profile: ``str``\\n :param libcloud_kwargs: Extra arguments for the driver\\\\'s delete_object method\\n :type libcloud_kwargs: ``dict``\\n :return: True if an object has been successfully deleted, False\\n otherwise.\\n :rtype: ``bool``\\n CLI Example:\\n .. code-block:: bash\\n salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1'\\n '''\",\"targets\":\"conn = _get_driver(profile=profile)\\n libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)\\n obj = conn.get_object(container_name, object_name, **libcloud_kwargs)\\n return conn.delete_object(obj)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (pattern is None):\\n pattern = sickbeard.NAMING_PATTERN\\n if (anime_type is None):\\n anime_type = sickbeard.NAMING_ANIME\\n valid = (not validate_name(pattern, None, anime_type, file_only=True))\\n if (multi is not None):\\n valid = (valid or (not validate_name(pattern, multi, anime_type, file_only=True)))\\n return valid\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_force_season_folders(pattern=None, multi=None, anime_type=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n a = np.atleast_1d(a)\\n if (len(a) == 1):\\n b = np.asarray(b)\\n a = np.asarray(a)\\n if ((b.ndim != 1) and (a.ndim != 1)):\\n raise ValueError('object of too small depth for desired array')\\n x = np.asarray(x)\\n inputs = [b, a, x]\\n if (zi is not None):\\n zi = np.asarray(zi)\\n if (zi.ndim != x.ndim):\\n raise ValueError('object of too small depth for desired array')\\n expected_shape = list(x.shape)\\n expected_shape[axis] = (b.shape[0] - 1)\\n expected_shape = tuple(expected_shape)\\n if (zi.shape != expected_shape):\\n strides = (zi.ndim * [None])\\n if (axis < 0):\\n axis += zi.ndim\\n for k in range(zi.ndim):\\n if ((k == axis) and (zi.shape[k] == expected_shape[k])):\\n strides[k] = zi.strides[k]\\n elif ((k != axis) and (zi.shape[k] == expected_shape[k])):\\n strides[k] = zi.strides[k]\\n elif ((k != axis) and (zi.shape[k] == 1)):\\n strides[k] = 0\\n else:\\n raise ValueError(('Unexpected shape for zi: expected %s, found %s.' % (expected_shape, zi.shape)))\\n zi = np.lib.stride_tricks.as_strided(zi, expected_shape, strides)\\n inputs.append(zi)\\n dtype = np.result_type(*inputs)\\n if (dtype.char not in 'fdgFDGO'):\\n raise NotImplementedError((\\\"input type '%s' not supported\\\" % dtype))\\n b = np.array(b, dtype=dtype)\\n a = np.array(a, dtype=dtype, copy=False)\\n b \\/= a[0]\\n x = np.array(x, dtype=dtype, copy=False)\\n out_full = np.apply_along_axis((lambda y: np.convolve(b, y)), axis, x)\\n ind = (out_full.ndim * [slice(None)])\\n if (zi is not None):\\n ind[axis] = slice(zi.shape[axis])\\n out_full[ind] += zi\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def lfilter(b, a, x, axis=(-1), zi=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def load_smbclient_auth_file(path):\",\"targets\":\"\\\"\\\"\\\"Load credentials from an smbclient-style authentication file (used by\\n smbclient, mount.cifs and others). returns (domain, username, password)\\n or raises AuthFileSyntaxError or any I\\/O exceptions.\\n \\\"\\\"\\\"\\n lineno = 0\\n domain = None\\n username = None\\n password = None\\n for line in open(path):\\n lineno += 1\\n line = line.strip()\\n if (line.startswith('#') or (line == '')):\\n continue\\n parts = line.split('=', 1)\\n if (len(parts) != 2):\\n raise AuthFileSyntaxError(path, lineno, 'No \\\"=\\\" present in line')\\n (k, v) = (parts[0].strip(), parts[1].strip())\\n if (k == 'username'):\\n username = v\\n elif (k == 'password'):\\n password = v\\n elif (k == 'domain'):\\n domain = v\\n else:\\n raise AuthFileSyntaxError(path, lineno, ('Unknown option %s' % repr(k)))\\n return (domain, username, password)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n draft_dir = (course_data_path + '\\/drafts')\\n if (not os.path.exists(draft_dir)):\\n return\\n errorlog = make_error_tracker()\\n data_dir = xml_module_store.data_dir\\n if (not data_dir.endswith('\\/')):\\n data_dir += '\\/'\\n draft_course_dir = draft_dir.replace(data_dir, '', 1)\\n system = ImportSystem(xmlstore=xml_module_store, course_id=source_course_id, course_dir=draft_course_dir, error_tracker=errorlog.tracker, load_error_modules=False, mixins=xml_module_store.xblock_mixins, field_data=KvsFieldData(kvs=DictKeyValueStore()), target_course_id=target_id)\\n def _import_module(module):\\n module_location = module.location.map_into_course(target_id)\\n _update_module_location(module, module_location.replace(revision=MongoRevisionKey.draft))\\n parent_url = get_parent_url(module)\\n index = index_in_children_list(module)\\n if ((parent_url is not None) and (index is not None)):\\n course_key = descriptor.location.course_key\\n parent_location = course_key.make_usage_key_from_deprecated_string(parent_url)\\n parent_location = parent_location.map_into_course(target_id)\\n parent = store.get_item(parent_location, depth=0)\\n non_draft_location = module.location.map_into_course(target_id)\\n if (not any(((child.block_id == module.location.block_id) for child in parent.children))):\\n parent.children.insert(index, non_draft_location)\\n store.update_item(parent, user_id)\\n _update_and_import_module(module, store, user_id, source_course_id, target_id, runtime=mongo_runtime)\\n for child in module.get_children():\\n _import_module(child)\\n drafts = []\\n for (rootdir, __, filenames) in os.walk(draft_dir):\\n for filename in filenames:\\n if filename.startswith('._'):\\n continue\\n module_path = os.path.join(rootdir, filename)\\n with open(module_path, 'r') as f:\\n try:\\n xml =...\\n\\nWhat's a good function header?\",\"targets\":\"def _import_course_draft(xml_module_store, store, user_id, course_data_path, source_course_id, target_id, mongo_runtime):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_limits():\",\"targets\":\"\\\"\\\"\\\"\\\"limits\\\": {\\n \\\"users\\\": 1,\\n \\\"space\\\": 0.5, # in GB\\n \\\"emails\\\": 1000 # per month\\n \\\"expiry\\\": \\\"2099-12-31\\\"\\n \\\"\\\"\\\"\\n return frappe._dict((frappe.local.conf.limits or {}))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef create_quiver(x, y, u, v, scale=0.1, arrow_scale=0.3, angle=(math.pi \\/ 9), **kwargs):\\n\\n ''''Returns data for a quiver plot.\\n :param (list|ndarray) x: x coordinates of the arrow locations\\n :param (list|ndarray) y: y coordinates of the arrow locations\\n :param (list|ndarray) u: x components of the arrow vectors\\n :param (list|ndarray) v: y components of the arrow vectors\\n :param (float in [0,1]) scale: scales size of the arrows(ideally to\\n avoid overlap). Default = .1\\n :param (float in [0,1]) arrow_scale: value multiplied to length of barb\\n to get length of arrowhead. Default = .3\\n :param (angle in radians) angle: angle of arrowhead. Default = pi\\/9\\n :param kwargs: kwargs passed through plotly.graph_objs.Scatter\\n for more information on valid kwargs call\\n help(plotly.graph_objs.Scatter)\\n :rtype (dict): returns a representation of quiver figure.\\n Example 1: Trivial Quiver\\n import plotly.plotly as py\\n from plotly.figure_factory import create_quiver\\n import math\\n # 1 Arrow from (0,0) to (1,1)\\n fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1)\\n py.plot(fig, filename=\\\\'quiver\\\\')\\n Example 2: Quiver plot using meshgrid\\n import plotly.plotly as py\\n from plotly.figure_factory import create_quiver\\n import numpy as np\\n import math\\n # Add data\\n x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))\\n u = np.cos(x)*y\\n v = np.sin(x)*y\\n #Create quiver\\n fig = create_quiver(x, y, u, v)\\n # Plot\\n py.plot(fig, filename=\\\\'quiver\\\\')\\n Example 3: Styling the quiver plot\\n import plotly.plotly as py\\n from plotly.figure_factory import create_quiver\\n import numpy as np\\n import math\\n # Add data\\n x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5),\\n np.arange(-math.pi, math.pi, .5))\\n u = np.cos(x)*y\\n v = np.sin(x)*y\\n # Create quiver\\n fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi\\/6,\\n name=\\\\'Wind Velocity\\\\', line=Line(width=1))\\n # Add title to layout\\n fig[\\\\'layout\\\\'].update(title=\\\\'Quiver Plot\\\\')\\n # Plot\\n py.plot(fig, filename=\\\\'quiver\\\\')'\\n '''\",\"targets\":\"utils.validate_equal_length(x, y, u, v)\\n utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale)\\n (barb_x, barb_y) = _Quiver(x, y, u, v, scale, arrow_scale, angle).get_barbs()\\n (arrow_x, arrow_y) = _Quiver(x, y, u, v, scale, arrow_scale, angle).get_quiver_arrows()\\n quiver = graph_objs.Scatter(x=(barb_x + arrow_x), y=(barb_y + arrow_y), mode='lines', **kwargs)\\n data = [quiver]\\n layout = graph_objs.Layout(hovermode='closest')\\n return graph_objs.Figure(data=data, layout=layout)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _add_name_space(message, namespace=None):\\n\\n ''''Populate the name_space field in a messagecol buffer.\\n Args:\\n message: A messagecol buffer supporting the set_name_space() operation.\\n namespace: The name of the namespace part. If None, use the\\n default namespace. The empty namespace (i.e. \\\\'\\\\') will clear\\n the name_space field.'\\n '''\",\"targets\":\"if (namespace is None):\\n namespace = namespace_manager.get_namespace()\\n if (not namespace):\\n message.clear_name_space()\\n else:\\n message.set_name_space(namespace)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if is_available('pgrep'):\\n results = call((GET_PID_BY_NAME_PGREP % process_name), None)\\n if results:\\n try:\\n pids = list(map(int, results))\\n if multiple:\\n return pids\\n elif (len(pids) == 1):\\n return pids[0]\\n except ValueError:\\n pass\\n if is_available('pidof'):\\n results = call((GET_PID_BY_NAME_PIDOF % process_name), None)\\n if (results and (len(results) == 1)):\\n try:\\n pids = list(map(int, results[0].split()))\\n if multiple:\\n return pids\\n elif (len(pids) == 1):\\n return pids[0]\\n except ValueError:\\n pass\\n if is_available('ps'):\\n if (not is_bsd()):\\n results = call((GET_PID_BY_NAME_PS_LINUX % process_name), None)\\n if results:\\n try:\\n pids = list(map(int, results[1:]))\\n if multiple:\\n return pids\\n elif (len(pids) == 1):\\n return pids[0]\\n except ValueError:\\n pass\\n if is_bsd():\\n results = call(GET_PID_BY_NAME_PS_BSD, None)\\n if results:\\n results = [r.split()[0] for r in results if r.endswith((' %s' % process_name))]\\n try:\\n pids = list(map(int, results))\\n if multiple:\\n return pids\\n elif (len(pids) == 1):\\n return pids[0]\\n except ValueError:\\n pass\\n if is_available('lsof'):\\n results = call((GET_PID_BY_NAME_LSOF % process_name), None)\\n if results:\\n try:\\n pids = list(map(int, results))\\n if multiple:\\n return pids\\n elif (len(pids) == 1):\\n return pids[0]\\n except...\\n\\nWhat's a good function header?\",\"targets\":\"def pid_by_name(process_name, multiple=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef iso8601_from_timestamp(timestamp):\\n\\n ''''Returns a iso8601 formated date from timestamp'\\n '''\",\"targets\":\"return isotime(datetime.datetime.utcfromtimestamp(timestamp))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_brick(var):\\n\\n ''''Retrieves the brick that created this variable.\\n See :func:`get_annotation`.'\\n '''\",\"targets\":\"return get_annotation(var, Brick)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n arr = np.asarray(arr)\\n shape = arr.shape\\n if (shape[(-1)] < 3):\\n raise ValueError('Input array has less than 3 color channels')\\n return dtype.img_as_float(arr, force_copy=True)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _prepare_lab_array(arr):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if ((source not in _MAPPINGS) or (target not in _MAPPINGS[source])):\\n if (target == u'universal'):\\n _load_universal_map(source)\\n return _MAPPINGS[source][target]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def tagset_mapping(source, target):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef items_for_result(cl, result, form):\\n\\n ''''Generates the actual list of data.'\\n '''\",\"targets\":\"first = True\\n pk = cl.lookup_opts.pk.attname\\n for field_name in cl.list_display:\\n row_class = u''\\n try:\\n (f, attr, value) = lookup_field(field_name, result, cl.model_admin)\\n except ObjectDoesNotExist:\\n result_repr = EMPTY_CHANGELIST_VALUE\\n else:\\n if (f is None):\\n if (field_name == u'action_checkbox'):\\n row_class = mark_safe(u' class=\\\"action-checkbox\\\"')\\n allow_tags = getattr(attr, u'allow_tags', False)\\n boolean = getattr(attr, u'boolean', False)\\n if boolean:\\n allow_tags = True\\n result_repr = display_for_value(value, boolean)\\n if allow_tags:\\n result_repr = mark_safe(result_repr)\\n if isinstance(value, (datetime.date, datetime.time)):\\n row_class = mark_safe(u' class=\\\"nowrap\\\"')\\n else:\\n if isinstance(f.rel, models.ManyToOneRel):\\n field_val = getattr(result, f.name)\\n if (field_val is None):\\n result_repr = EMPTY_CHANGELIST_VALUE\\n else:\\n result_repr = field_val\\n else:\\n result_repr = display_for_field(value, f)\\n if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):\\n row_class = mark_safe(u' class=\\\"nowrap\\\"')\\n if (force_text(result_repr) == u''):\\n result_repr = mark_safe(u' ')\\n if ((first and (not cl.list_display_links)) or (field_name in cl.list_display_links)):\\n table_tag = {True: u'th', False: u'td'}[first]\\n first = False\\n url = cl.url_for_result(result)\\n if cl.to_field:\\n attr = str(cl.to_field)\\n else:\\n attr = pk\\n value = result.serializable_value(attr)\\n result_id = repr(force_text(value))[1:]\\n (yield...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@contextlib.contextmanager\\ndef silence():\\n\\n ''''A context manager that silences sys.stdout and sys.stderr.'\\n '''\",\"targets\":\"old_stdout = sys.stdout\\n old_stderr = sys.stderr\\n sys.stdout = _DummyFile()\\n sys.stderr = _DummyFile()\\n (yield)\\n sys.stdout = old_stdout\\n sys.stderr = old_stderr\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n pass\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _snapshot_metadata_update(context, snapshot_id, metadata, delete):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (code in ct.INDEX_LABELS):\\n return ct.INDEX_LIST[code]\\n elif (len(code) != 6):\\n return ''\\n else:\\n return (('sh%s' % code) if (code[:1] in ['5', '6', '9']) else ('sz%s' % code))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _code_to_symbol(code):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@transaction.non_atomic_requests\\n@ensure_csrf_cookie\\n@cache_control(no_cache=True, no_store=True, must_revalidate=True)\\n@require_global_staff\\n@require_http_methods(['POST', 'DELETE'])\\ndef certificate_invalidation_view(request, course_id):\\n\\n ''''Invalidate\\/Re-Validate students to\\/from certificate.\\n :param request: HttpRequest object\\n :param course_id: course identifier of the course for whom to add\\/remove certificates exception.\\n :return: JsonResponse object with success\\/error message or certificate invalidation data.'\\n '''\",\"targets\":\"course_key = CourseKey.from_string(course_id)\\n try:\\n certificate_invalidation_data = parse_request_data(request)\\n certificate = validate_request_data_and_get_certificate(certificate_invalidation_data, course_key)\\n except ValueError as error:\\n return JsonResponse({'message': error.message}, status=400)\\n if (request.method == 'POST'):\\n try:\\n certificate_invalidation = invalidate_certificate(request, certificate, certificate_invalidation_data)\\n except ValueError as error:\\n return JsonResponse({'message': error.message}, status=400)\\n return JsonResponse(certificate_invalidation)\\n elif (request.method == 'DELETE'):\\n try:\\n re_validate_certificate(request, course_key, certificate)\\n except ValueError as error:\\n return JsonResponse({'message': error.message}, status=400)\\n return JsonResponse({}, status=204)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _print_unix(objects, sep, end, file, flush):\",\"targets\":\"\\\"\\\"\\\"A print_() implementation which writes bytes\\n \\\"\\\"\\\"\\n encoding = _encoding\\n if isinstance(sep, text_type):\\n sep = sep.encode(encoding, 'replace')\\n if (not isinstance(sep, bytes)):\\n raise TypeError\\n if isinstance(end, text_type):\\n end = end.encode(encoding, 'replace')\\n if (not isinstance(end, bytes)):\\n raise TypeError\\n if (end == '\\\\n'):\\n end = os.linesep\\n if PY3:\\n end = end.encode('ascii')\\n parts = []\\n for obj in objects:\\n if ((not isinstance(obj, text_type)) and (not isinstance(obj, bytes))):\\n obj = text_type(obj)\\n if isinstance(obj, text_type):\\n if PY2:\\n obj = obj.encode(encoding, 'replace')\\n else:\\n try:\\n obj = obj.encode(encoding, 'surrogateescape')\\n except UnicodeEncodeError:\\n obj = obj.encode(encoding, 'replace')\\n assert isinstance(obj, bytes)\\n parts.append(obj)\\n data = (sep.join(parts) + end)\\n assert isinstance(data, bytes)\\n file = getattr(file, 'buffer', file)\\n try:\\n file.write(data)\\n except TypeError:\\n if PY3:\\n surr_data = data.decode(encoding, 'surrogateescape')\\n try:\\n file.write(surr_data)\\n except (TypeError, ValueError):\\n file.write(data.decode(encoding, 'replace'))\\n else:\\n file.write(data.decode(encoding, 'replace'))\\n if flush:\\n file.flush()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n ctx.db.commit()\\n ctx.db_transaction = True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def transact():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n inner_mlp = MLP(layers=[Linear(10, 'h0', 0.1), Linear(10, 'h1', 0.1)], layer_name='inner_mlp')\\n outer_mlp = MLP(layers=[CompositeLayer(layer_name='composite', layers=[inner_mlp, Linear(10, 'h2', 0.1)])], nvis=10)\\n X = outer_mlp.get_input_space().make_theano_batch()\\n f = theano.function([X], outer_mlp.fprop(X))\\n f(np.random.rand(5, 10).astype(theano.config.floatX))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_nested_mlp():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _minpoly_exp(ex, x):\\n\\n ''''Returns the minimal polynomial of ``exp(ex)``'\\n '''\",\"targets\":\"(c, a) = ex.args[0].as_coeff_Mul()\\n p = sympify(c.p)\\n q = sympify(c.q)\\n if (a == (I * pi)):\\n if c.is_rational:\\n if ((c.p == 1) or (c.p == (-1))):\\n if (q == 3):\\n return (((x ** 2) - x) + 1)\\n if (q == 4):\\n return ((x ** 4) + 1)\\n if (q == 6):\\n return (((x ** 4) - (x ** 2)) + 1)\\n if (q == 8):\\n return ((x ** 8) + 1)\\n if (q == 9):\\n return (((x ** 6) - (x ** 3)) + 1)\\n if (q == 10):\\n return (((((x ** 8) - (x ** 6)) + (x ** 4)) - (x ** 2)) + 1)\\n if q.is_prime:\\n s = 0\\n for i in range(q):\\n s += ((- x) ** i)\\n return s\\n factors = [cyclotomic_poly(i, x) for i in divisors((2 * q))]\\n mp = _choose_factor(factors, x, ex)\\n return mp\\n else:\\n raise NotAlgebraic((\\\"%s doesn't seem to be an algebraic element\\\" % ex))\\n raise NotAlgebraic((\\\"%s doesn't seem to be an algebraic element\\\" % ex))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def GetOrderedIntersection(handler_list):\",\"targets\":\"\\\"\\\"\\\"Implements algorithm for combining and reordering Handlers.\\n GetOrderedIntersection performs the heavy lifting of converting a randomly\\n ordered list of Handlers (globbed patterns, each with various potentially\\n conflicting properties attached), into an ordered list of handlers with\\n property values resolved.\\n The purpose of this process is to convert the Web.xml URL mapping scheme to\\n that of app.yaml. In Web.xml the most specific path, according to\\n literal-ness and length, is chosen. In app.yaml the first listed matching\\n path is chosen. Thus to preserve user preferences through the translation\\n process we order the patterns from specific to general.\\n For example, if three handlers are given as input (in any order):\\n \\\"\\/admin\\/*\\\" (security=admin)\\n \\\"\\/*.png\\\" (type=static)\\n \\\"*\\\" (type=dynamic, security=required)\\n we want to get this ordered list as output:\\n 1. \\\"\\/admin\\/*.png\\\" (security=admin, type=static)\\n 2. \\\"\\/admin\\/*\\\" (security=admin, type=dynamic)\\n 3. \\\"\\/*.png\\\" (security=required, type=static)\\n 4. \\\"*\\\" (type=dynamic, security=required).\\n so that the properties of any given path are those of the longest matching\\n path. The SimpleHandler and OverlappedHandler classes provide the logic for\\n attaching globbed patterns to the right properties and resolving potential\\n property value conflicts.\\n Args:\\n handler_list: List of SimpleHandlers in arbitrary order.\\n Returns:\\n An ordered list of OverlappedHandlers and SimpleHandlers. See the above\\n example for what this would look like.\\n \\\"\\\"\\\"\\n results = _Intersect(handler_list)\\n results = sorted(results, key=(lambda h: h.pattern))\\n _ReorderHandlers(results)\\n _GivePropertiesFromGeneralToSpecific(results)\\n return _RemoveRedundantHandlers(results)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef load_vint(buf, pos):\\n\\n ''''Load variable-size int.'\\n '''\",\"targets\":\"limit = min((pos + 11), len(buf))\\n res = ofs = 0\\n while (pos < limit):\\n b = _byte_code(buf[pos])\\n res += ((b & 127) << ofs)\\n pos += 1\\n ofs += 7\\n if (b < 128):\\n return (res, pos)\\n raise BadRarFile('cannot load vint')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_created(created):\\n\\n ''''Returns a datetime.\\n If `created` is \\\"now\\\", it returns `datetime.datetime.now()`. If `created`\\n is set use that. Otherwise generate a random datetime in the year 2011.'\\n '''\",\"targets\":\"if (created == 'now'):\\n return datetime.now()\\n elif created:\\n return created\\n else:\\n return datetime(2011, random.randint(1, 12), random.randint(1, 28), random.randint(0, 23), random.randint(0, 59), random.randint(0, 59))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@frappe.whitelist()\\ndef mark_as_trash(communication):\",\"targets\":\"\\\"\\\"\\\"set email status to trash\\n \\\"\\\"\\\"\\n frappe.db.set_value('Communication', communication, 'email_status', 'Trash')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef gen_key(path):\\n\\n ''''Generate a key for use with salt-ssh'\\n '''\",\"targets\":\"cmd = u'ssh-keygen -P \\\"\\\" -f {0} -t rsa -q'.format(path)\\n if (not os.path.isdir(os.path.dirname(path))):\\n os.makedirs(os.path.dirname(path))\\n subprocess.call(cmd, shell=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def abstractMethod():\",\"targets\":\"\\\"\\\"\\\"This should be called when an abstract method is called that should have been\\n implemented by a subclass. It should not be called in situations where no implementation\\n (i.e. a \\\\pass\\\\ behavior) is acceptable.\\n \\\"\\\"\\\"\\n raise NotImplementedError('Method not implemented!')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n family = address_type(address)\\n s = socket.socket(getattr(socket, family))\\n t = _init_timeout()\\n while 1:\\n try:\\n s.connect(address)\\n except socket.error as e:\\n if ((e.args[0] != errno.ECONNREFUSED) or _check_timeout(t)):\\n debug('failed to connect to address %s', address)\\n raise\\n time.sleep(0.01)\\n else:\\n break\\n else:\\n raise\\n fd = duplicate(s.fileno())\\n conn = _multiprocessing.Connection(fd)\\n s.close()\\n return conn\\n\\n\\nWhat's a good function header?\",\"targets\":\"def SocketClient(address):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_easy_s3(config_file=None, cache=False):\",\"targets\":\"\\\"\\\"\\\"Factory for EasyS3 class that attempts to load AWS credentials from\\n the StarCluster config file. Returns an EasyS3 object if\\n successful.\\n \\\"\\\"\\\"\\n cfg = get_config(config_file, cache)\\n return cfg.get_easy_s3()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n f.contextfunction = True\\n return f\\n\\n\\nWhat's a good function header?\",\"targets\":\"def contextfunction(f):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef expire():\\n\\n ''''Expire the current session cookie.'\\n '''\",\"targets\":\"name = cherrypy.serving.request.config.get('tools.sessions.name', 'session_id')\\n one_year = (((60 * 60) * 24) * 365)\\n e = (time.time() - one_year)\\n cherrypy.serving.response.cookie[name]['expires'] = httputil.HTTPDate(e)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_token(request):\",\"targets\":\"\\\"\\\"\\\"Returns the CSRF token required for a POST form. The token is an\\n alphanumeric value.\\n A side effect of calling this function is to make the csrf_protect\\n decorator and the CsrfViewMiddleware add a CSRF cookie and a \\\\Vary: Cookie\\\\\\n header to the outgoing response. For this reason, you may need to use this\\n function lazily, as is done by the csrf context processor.\\n \\\"\\\"\\\"\\n request.META[u'CSRF_COOKIE_USED'] = True\\n return request.META.get(u'CSRF_COOKIE', None)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if __salt__['config.option']('virt.tunnel'):\\n return 'virsh migrate --p2p --tunnelled --live --persistent --undefinesource '\\n return 'virsh migrate --live --persistent --undefinesource '\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_migrate_command():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n names[t[1]] = t[3]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def p_statement_assign(t):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@hooks.before('Events > Events under an Event Sub-topic > List All Events under an Event Sub-topic')\\ndef evnt_sub_topic_event_get_list(transaction):\",\"targets\":\"\\\"\\\"\\\"GET \\/event-sub-topics\\/1\\/events\\n :param transaction:\\n :return:\\n \\\"\\\"\\\"\\n with stash['app'].app_context():\\n event_sub_topic = EventSubTopicFactory()\\n db.session.add(event_sub_topic)\\n event = EventFactoryBasic(event_sub_topic_id=1)\\n db.session.add(event)\\n db.session.commit()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (b, a) = normalize(b, a)\\n b = ((b + 0.0) \\/ a[0])\\n a = ((a + 0.0) \\/ a[0])\\n k = b[0]\\n b \\/= b[0]\\n z = roots(b)\\n p = roots(a)\\n return (z, p, k)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def tf2zpk(b, a):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef fetch_differentiable_fixed_embeddings(comp, state, stride):\\n\\n ''''Looks up fixed features with separate, differentiable, embedding lookup.\\n Args:\\n comp: Component whose fixed features we wish to look up.\\n state: live MasterState object for the component.\\n stride: Tensor containing current batch * beam size.\\n Returns:\\n state handle: updated state handle to be used after this call\\n fixed_embeddings: list of NamedTensor objects'\\n '''\",\"targets\":\"_validate_embedded_fixed_features(comp)\\n num_channels = len(comp.spec.fixed_feature)\\n if (not num_channels):\\n return (state.handle, [])\\n (state.handle, indices, ids, weights, num_steps) = dragnn_ops.bulk_fixed_features(state.handle, component=comp.name, num_channels=num_channels)\\n fixed_embeddings = []\\n for (channel, feature_spec) in enumerate(comp.spec.fixed_feature):\\n differentiable_or_constant = ('constant' if feature_spec.is_constant else 'differentiable')\\n tf.logging.info('[%s] Adding %s fixed feature \\\"%s\\\"', comp.name, differentiable_or_constant, feature_spec.name)\\n size = ((stride * num_steps) * feature_spec.size)\\n fixed_embedding = network_units.embedding_lookup(comp.get_variable(network_units.fixed_embeddings_name(channel)), indices[channel], ids[channel], weights[channel], size)\\n if feature_spec.is_constant:\\n fixed_embedding = tf.stop_gradient(fixed_embedding)\\n fixed_embeddings.append(network_units.NamedTensor(fixed_embedding, feature_spec.name))\\n return (state.handle, fixed_embeddings)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef import_no_db_in_virt(logical_line, filename):\\n\\n ''''Check for db calls from nova\\/virt\\n As of grizzly-2 all the database calls have been removed from\\n nova\\/virt, and we want to keep it that way.\\n N307'\\n '''\",\"targets\":\"if (('nova\\/virt' in filename) and (not filename.endswith('fake.py'))):\\n if logical_line.startswith('from nova import db'):\\n (yield (0, 'N307: nova.db import not allowed in nova\\/virt\\/*'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_registered(msg_type_name, default_package=None):\\n\\n ''''@param msg_type_name: name of message type\\n @type msg_type_name: str\\n @return: msg spec for msg type name\\n @rtype: L{MsgSpec}'\\n '''\",\"targets\":\"if (msg_type_name in REGISTERED_TYPES):\\n return REGISTERED_TYPES[msg_type_name]\\n elif default_package:\\n (p, n) = roslib.names.package_resource_name(msg_type_name)\\n if (not p):\\n return REGISTERED_TYPES[roslib.names.resource_name(default_package, msg_type_name)]\\n raise KeyError(msg_type_name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef encrypt_int(message, ekey, n):\\n\\n ''''Encrypts a message using encryption key \\\\'ekey\\\\', working modulo n'\\n '''\",\"targets\":\"assert_int(message, 'message')\\n assert_int(ekey, 'ekey')\\n assert_int(n, 'n')\\n if (message < 0):\\n raise ValueError('Only non-negative numbers are supported')\\n if (message > n):\\n raise OverflowError(('The message %i is too long for n=%i' % (message, n)))\\n return pow(message, ekey, n)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n a = np.copy(a)\\n b = np.copy(b)\\n nan_mask = np.logical_or(np.isnan(a), np.isnan(b))\\n a[nan_mask] = 0\\n b[nan_mask] = 0\\n assert_almost_equal(a, b, rtol, atol, names)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def assert_almost_equal_ignore_nan(a, b, rtol=None, atol=None, names=('a', 'b')):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):\\n\\n ''''Return a wrapped version of file which provides transparent\\n encoding translation.\\n Strings written to the wrapped file are interpreted according\\n to the given data_encoding and then written to the original\\n file as string using file_encoding. The intermediate encoding\\n will usually be Unicode but depends on the specified codecs.\\n Strings are read from the file using file_encoding and then\\n passed back to the caller as string using data_encoding.\\n If file_encoding is not given, it defaults to data_encoding.\\n errors may be given to define the error handling. It defaults\\n to \\\\'strict\\\\' which causes ValueErrors to be raised in case an\\n encoding error occurs.\\n The returned wrapped file object provides two extra attributes\\n .data_encoding and .file_encoding which reflect the given\\n parameters of the same name. The attributes can be used for\\n introspection by Python programs.'\\n '''\",\"targets\":\"if (file_encoding is None):\\n file_encoding = data_encoding\\n data_info = lookup(data_encoding)\\n file_info = lookup(file_encoding)\\n sr = StreamRecoder(file, data_info.encode, data_info.decode, file_info.streamreader, file_info.streamwriter, errors)\\n sr.data_encoding = data_encoding\\n sr.file_encoding = file_encoding\\n return sr\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_search_score(query, choice, ignore_case=True, apply_regex=True, template='{}'):\\n\\n ''''Returns a tuple with the enriched text (if a template is provided) and\\n a score for the match.\\n Parameters\\n query : str\\n String with letters to search in choice (in order of appearance).\\n choice : str\\n Sentence\\/words in which to search for the \\\\'query\\\\' letters.\\n ignore_case : bool, optional\\n Optional value perform a case insensitive search (True by default).\\n apply_regex : bool, optional\\n Optional value (True by default) to perform a regex search. Useful\\n when this function is called directly.\\n template : str, optional\\n Optional template string to surround letters found in choices. This is\\n useful when using a rich text editor (\\\\'{}\\\\' by default).\\n Examples: \\\\'{}<\\/b>\\\\', \\\\'{}<\\/code>\\\\', \\\\'{}<\\/i>\\\\'\\n Returns\\n results : tuple\\n Tuples where the first item is the text (enriched if a template was\\n used) and the second item is a search score.\\n Notes\\n The score is given according the following precedence (high to low):\\n - Letters in one word and no spaces with exact match.\\n Example: \\\\'up\\\\' in \\\\'up stroke\\\\'\\n - Letters in one word and no spaces with partial match.\\n Example: \\\\'up\\\\' in \\\\'upstream stroke\\\\'\\n - Letters in one word but with skip letters.\\n Example: \\\\'cls\\\\' in \\\\'close up\\\\'\\n - Letters in two or more words\\n Example: \\\\'cls\\\\' in \\\\'car lost\\\\''\\n '''\",\"targets\":\"original_choice = choice\\n result = (original_choice, NOT_FOUND_SCORE)\\n if (not query):\\n return result\\n if ignore_case:\\n query = query.lower()\\n choice = choice.lower()\\n if apply_regex:\\n pattern = get_search_regex(query, ignore_case=ignore_case)\\n r = re.search(pattern, choice)\\n if (r is None):\\n return result\\n else:\\n sep = u'-'\\n let = u'x'\\n score = 0\\n exact_words = [(query == word) for word in choice.split(u' ')]\\n partial_words = [(query in word) for word in choice.split(u' ')]\\n if (any(exact_words) or any(partial_words)):\\n pos_start = choice.find(query)\\n pos_end = (pos_start + len(query))\\n score += pos_start\\n text = choice.replace(query, (sep * len(query)), 1)\\n enriched_text = ((original_choice[:pos_start] + template.format(original_choice[pos_start:pos_end])) + original_choice[pos_end:])\\n if any(exact_words):\\n score += 1\\n elif any(partial_words):\\n score += 100\\n else:\\n text = [l for l in original_choice]\\n if ignore_case:\\n temp_text = [l.lower() for l in original_choice]\\n else:\\n temp_text = text[:]\\n score += temp_text.index(query[0])\\n enriched_text = text[:]\\n for char in query:\\n if ((char != u'') and (char in temp_text)):\\n index = temp_text.index(char)\\n enriched_text[index] = template.format(text[index])\\n text[index] = sep\\n temp_text = (([u' '] * (index + 1)) + temp_text[(index + 1):])\\n enriched_text = u''.join(enriched_text)\\n patterns_text = []\\n for (i, char) in enumerate(text):\\n if ((char != u' ') and (char != sep)):\\n new_char = let\\n else:\\n new_char = char\\n patterns_text.append(new_char)\\n patterns_text =...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def formatdate(timeval=None, localtime=False, usegmt=False):\",\"targets\":\"\\\"\\\"\\\"Returns a date string as specified by RFC 2822, e.g.:\\n Fri, 09 Nov 2001 01:08:47 -0000\\n Optional timeval if given is a floating point time value as accepted by\\n gmtime() and localtime(), otherwise the current time is used.\\n Optional localtime is a flag that when True, interprets timeval, and\\n returns a date relative to the local timezone instead of UTC, properly\\n taking daylight savings time into account.\\n Optional argument usegmt means that the timezone is written out as\\n an ascii string, not numeric one (so \\\"GMT\\\" instead of \\\"+0000\\\"). This\\n is needed for HTTP, and is only used when localtime==False.\\n \\\"\\\"\\\"\\n if (timeval is None):\\n timeval = time.time()\\n if localtime:\\n now = time.localtime(timeval)\\n if (time.daylight and now[(-1)]):\\n offset = time.altzone\\n else:\\n offset = time.timezone\\n (hours, minutes) = divmod(abs(offset), 3600)\\n if (offset > 0):\\n sign = '-'\\n else:\\n sign = '+'\\n zone = ('%s%02d%02d' % (sign, hours, (minutes \\/\\/ 60)))\\n else:\\n now = time.gmtime(timeval)\\n if usegmt:\\n zone = 'GMT'\\n else:\\n zone = '-0000'\\n return ('%s, %02d %s %04d %02d:%02d:%02d %s' % (['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]], now[2], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(now[1] - 1)], now[0], now[3], now[4], now[5], zone))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def login_protected_view(request):\",\"targets\":\"\\\"\\\"\\\"A simple view that is login protected.\\n \\\"\\\"\\\"\\n t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template')\\n c = Context({'user': request.user})\\n return HttpResponse(t.render(c))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n _sanity_check(fh)\\n dhead = _parse_header(fh)\\n (dcmetrics_ascii, dcmetrics_name) = _parse_char_metrics(fh)\\n doptional = _parse_optional(fh)\\n return (dhead, dcmetrics_ascii, dcmetrics_name, doptional[0], doptional[1])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_afm(fh):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _SharedSuffix(pattern1, pattern2):\",\"targets\":\"\\\"\\\"\\\"Returns the shared suffix of two patterns.\\n \\\"\\\"\\\"\\n return _SharedPrefix(pattern1[::(-1)], pattern2[::(-1)])[::(-1)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef absent(name, user='root', identifier=False, special=None, **kwargs):\\n\\n ''''Verifies that the specified cron job is absent for the specified user; only\\n the name is matched when removing a cron job.\\n name\\n The command that should be absent in the user crontab.\\n user\\n The name of the user whose crontab needs to be modified, defaults to\\n the root user\\n identifier\\n Custom-defined identifier for tracking the cron line for future crontab\\n edits. This defaults to the state id\\n special\\n The special keyword used in the job (eg. @reboot, @hourly...)'\\n '''\",\"targets\":\"name = name.strip()\\n if (identifier is False):\\n identifier = name\\n ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}\\n if __opts__['test']:\\n status = _check_cron(user, name, identifier=identifier)\\n ret['result'] = None\\n if (status == 'absent'):\\n ret['result'] = True\\n ret['comment'] = 'Cron {0} is absent'.format(name)\\n elif ((status == 'present') or (status == 'update')):\\n ret['comment'] = 'Cron {0} is set to be removed'.format(name)\\n return ret\\n if (special is None):\\n data = __salt__['cron.rm_job'](user, name, identifier=identifier)\\n else:\\n data = __salt__['cron.rm_special'](user, special, name)\\n if (data == 'absent'):\\n ret['comment'] = 'Cron {0} already absent'.format(name)\\n return ret\\n if (data == 'removed'):\\n ret['comment'] = \\\"Cron {0} removed from {1}'s crontab\\\".format(name, user)\\n ret['changes'] = {user: name}\\n return ret\\n ret['comment'] = 'Cron {0} for user {1} failed to commit with error {2}'.format(name, user, data)\\n ret['result'] = False\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _get_marker_param(request):\",\"targets\":\"\\\"\\\"\\\"Extract marker id from request or fail\\n \\\"\\\"\\\"\\n return request.GET['marker']\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def Name(name, prefix=None):\",\"targets\":\"\\\"\\\"\\\"Return a NAME leaf\\n \\\"\\\"\\\"\\n return Leaf(token.NAME, name, prefix=prefix)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@task(rate_limit='5\\/m')\\n@timeit\\ndef _rebuild_kb_chunk(data):\",\"targets\":\"\\\"\\\"\\\"Re-render a chunk of documents.\\n Note: Don\\\\t use host components when making redirects to wiki pages; those\\n redirects won\\\\t be auto-pruned when they\\\\re 404s.\\n \\\"\\\"\\\"\\n log.info(('Rebuilding %s documents.' % len(data)))\\n pin_this_thread()\\n messages = []\\n start = time.time()\\n for pk in data:\\n message = None\\n try:\\n document = Document.objects.get(pk=pk)\\n url = document.redirect_url()\\n if (url and points_to_document_view(url) and (not document.redirect_document())):\\n log.warn(('Invalid redirect document: %d' % pk))\\n html = document.parse_and_calculate_links()\\n if (document.html != html):\\n Document.objects.filter(pk=pk).update(html=html)\\n statsd.incr('wiki.rebuild_chunk.change')\\n else:\\n statsd.incr('wiki.rebuild_chunk.nochange')\\n except Document.DoesNotExist:\\n message = ('Missing document: %d' % pk)\\n except Revision.DoesNotExist:\\n message = ('Missing revision for document: %d' % pk)\\n except ValidationError as e:\\n message = ('ValidationError for %d: %s' % (pk, e.messages[0]))\\n except SlugCollision:\\n message = ('SlugCollision: %d' % pk)\\n except TitleCollision:\\n message = ('TitleCollision: %d' % pk)\\n if message:\\n log.debug(message)\\n messages.append(message)\\n d = (time.time() - start)\\n statsd.timing('wiki.rebuild_chunk', int(round((d * 1000))))\\n if messages:\\n subject = ('[%s] Exceptions raised in _rebuild_kb_chunk()' % settings.PLATFORM_NAME)\\n mail_admins(subject=subject, message='\\\\n'.join(messages))\\n if (not transaction.get_connection().in_atomic_block):\\n transaction.commit()\\n unpin_this_thread()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef createsuperuser(username=None, email=None, password=None):\\n\\n ''''Helper function for creating a superuser from the command line. All\\n arguments are optional and will be prompted-for if invalid or not given.'\\n '''\",\"targets\":\"try:\\n import pwd\\n except ImportError:\\n default_username = ''\\n else:\\n default_username = pwd.getpwuid(os.getuid())[0].replace(' ', '').lower()\\n if default_username:\\n try:\\n User.objects.get(username=default_username)\\n except User.DoesNotExist:\\n pass\\n else:\\n default_username = ''\\n try:\\n while 1:\\n if (not username):\\n input_msg = 'Username'\\n if default_username:\\n input_msg += (' (Leave blank to use %r)' % default_username)\\n username = raw_input((input_msg + ': '))\\n if (default_username and (username == '')):\\n username = default_username\\n if (not username.isalnum()):\\n sys.stderr.write('Error: That username is invalid. Use only letters, digits and underscores.\\\\n')\\n username = None\\n continue\\n try:\\n User.objects.get(username=username)\\n except User.DoesNotExist:\\n break\\n else:\\n sys.stderr.write('Error: That username is already taken.\\\\n')\\n username = None\\n while 1:\\n if (not email):\\n email = raw_input('E-mail address: ')\\n try:\\n validators.isValidEmail(email, None)\\n except validators.ValidationError:\\n sys.stderr.write('Error: That e-mail address is invalid.\\\\n')\\n email = None\\n else:\\n break\\n while 1:\\n if (not password):\\n password = getpass.getpass()\\n password2 = getpass.getpass('Password (again): ')\\n if (password != password2):\\n sys.stderr.write(\\\"Error: Your passwords didn't match.\\\\n\\\")\\n password = None\\n continue\\n if...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef digestAuth(realm, algorithm=MD5, nonce=None, qop=AUTH):\\n\\n ''''Challenges the client for a Digest authentication.'\\n '''\",\"targets\":\"global SUPPORTED_ALGORITHM, DIGEST_AUTH_ENCODERS, SUPPORTED_QOP\\n assert (algorithm in SUPPORTED_ALGORITHM)\\n assert (qop in SUPPORTED_QOP)\\n if (nonce is None):\\n nonce = calculateNonce(realm, algorithm)\\n return ('Digest realm=\\\"%s\\\", nonce=\\\"%s\\\", algorithm=\\\"%s\\\", qop=\\\"%s\\\"' % (realm, nonce, algorithm, qop))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if ('x' in dictionary):\\n valueComplex = complex(euclidean.getFloatFromValue(dictionary['x']), valueComplex.imag)\\n if ('y' in dictionary):\\n valueComplex = complex(valueComplex.real, euclidean.getFloatFromValue(dictionary['y']))\\n return valueComplex\\n\\n\\nWhat's a good function header?\",\"targets\":\"def getComplexByDictionary(dictionary, valueComplex):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n i2h = mx.sym.FullyConnected(data=indata, weight=param.i2h_weight, bias=param.i2h_bias, num_hidden=(num_hidden * 4), name=('t%d_l%d_i2h' % (seqidx, layeridx)))\\n h2h = mx.sym.FullyConnected(data=prev_state.h, weight=param.h2h_weight, bias=param.h2h_bias, num_hidden=(num_hidden * 4), name=('t%d_l%d_h2h' % (seqidx, layeridx)))\\n gates = (i2h + h2h)\\n slice_gates = mx.sym.SliceChannel(gates, num_outputs=4, name=('t%d_l%d_slice' % (seqidx, layeridx)))\\n in_gate = mx.sym.Activation(slice_gates[0], act_type='sigmoid')\\n in_transform = mx.sym.Activation(slice_gates[1], act_type='tanh')\\n forget_gate = mx.sym.Activation(slice_gates[2], act_type='sigmoid')\\n out_gate = mx.sym.Activation(slice_gates[3], act_type='sigmoid')\\n next_c = ((forget_gate * prev_state.c) + (in_gate * in_transform))\\n next_h = (out_gate * mx.sym.Activation(next_c, act_type='tanh'))\\n return LSTMState(c=next_c, h=next_h)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@raises(ValueError)\\ndef test_bootstrap_arglength():\",\"targets\":\"\\\"\\\"\\\"Test that different length args raise ValueError.\\n \\\"\\\"\\\"\\n algo.bootstrap(np.arange(5), np.arange(10))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n imagepath = album.artpath\\n if (not imagepath):\\n log.info(u'No album art present for {0}', album)\\n return\\n if (not os.path.isfile(syspath(imagepath))):\\n log.info(u'Album art not found at {0} for {1}', displayable_path(imagepath), album)\\n return\\n if maxwidth:\\n imagepath = resize_image(log, imagepath, maxwidth)\\n log.info(u'Embedding album art into {0}', album)\\n for item in album.items():\\n embed_item(log, item, imagepath, maxwidth, None, compare_threshold, ifempty, as_album=True)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def embed_album(log, album, maxwidth=None, quiet=False, compare_threshold=0, ifempty=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def epoch2num(e):\",\"targets\":\"\\\"\\\"\\\"Convert an epoch or sequence of epochs to the new date format,\\n that is days since 0001.\\n \\\"\\\"\\\"\\n spd = (24.0 * 3600.0)\\n return (719163 + (np.asarray(e) \\/ spd))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef have_qstring():\\n\\n ''''p3\\/qt5 get rid of QString wrapper as py3 has native unicode str type'\\n '''\",\"targets\":\"return (not ((sys.version_info.major >= 3) or QT_VERSION_STR.startswith('5.')))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n actual = [x[0] for x in data_shapes]\\n if (sorted(data_names) != sorted(actual)):\\n msg = (\\\"Data provided by %s_shapes don't match names specified by %s_names (%s vs. %s)\\\" % (name, name, str(data_shapes), str(data_names)))\\n if throw:\\n raise ValueError(msg)\\n else:\\n warnings.warn(msg)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _check_names_match(data_names, data_shapes, name, throw):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef android_emulator(registry, xml_parent, data):\\n\\n ''''yaml: android-emulator\\n Automates many Android development tasks including SDK installation,\\n build file generation, emulator creation and launch,\\n APK (un)installation...\\n Requires the Jenkins :jenkins-wiki:`Android Emulator Plugin\\n `.\\n :arg str avd: Enter the name of an existing Android emulator configuration.\\n If this is exclusive with the \\\\'os\\\\' arg.\\n :arg str os: Can be an OS version, target name or SDK add-on\\n :arg str screen-density: Density in dots-per-inch (dpi) or as an alias,\\n e.g. \\\"160\\\" or \\\"mdpi\\\". (default mdpi)\\n :arg str screen-resolution: Can be either a named resolution or explicit\\n size, e.g. \\\"WVGA\\\" or \\\"480x800\\\". (default WVGA)\\n :arg str locale: Language and country pair. (default en_US)\\n :arg str target-abi: Name of the ABI \\/ system image to be used. (optional)\\n :arg str sd-card: sd-card size e.g. \\\"32M\\\" or \\\"10240K\\\". (optional)\\n :arg bool wipe: if true, the emulator will have its user data reset at\\n start-up (default false)\\n :arg bool show-window: if true, the Android emulator user interface will\\n be displayed on screen during the build. (default false)\\n :arg bool snapshot: Start emulator from stored state (default false)\\n :arg bool delete: Delete Android emulator at the end of build\\n (default false)\\n :arg int startup-delay: Wait this many seconds before attempting\\n to start the emulator (default 0)\\n :arg str commandline-options: Will be given when starting the\\n Android emulator executable (optional)\\n :arg str exe: The emulator executable. (optional)\\n :arg list hardware-properties: Dictionary of hardware properties. Allows\\n you to override the default values for an AVD. (optional)\\n Example:\\n .. literalinclude:: \\/..\\/..\\/tests\\/wrappers\\/fixtures\\/android003.yaml'\\n '''\",\"targets\":\"root = XML.SubElement(xml_parent, 'hudson.plugins.android__emulator.AndroidEmulator')\\n if (data.get('avd') and data.get('os')):\\n raise JenkinsJobsException(\\\"'avd' and 'os' options are exclusive, please pick one only\\\")\\n if ((not data.get('avd')) and (not data.get('os'))):\\n raise JenkinsJobsException(\\\"AndroidEmulator requires an AVD name orOS version to run: specify 'os' or 'avd'\\\")\\n if data.get('avd'):\\n XML.SubElement(root, 'avdName').text = str(data['avd'])\\n else:\\n mapping = [('os', 'osVersion', None), ('screen-density', 'screenDensity', 'mdpi'), ('screen-resolution', 'screenResolution', 'WVGA'), ('locale', 'deviceLocale', 'en_US'), ('target-abi', 'targetAbi', ''), ('sd-card', 'sdCardSize', '')]\\n convert_mapping_to_xml(root, data, mapping, fail_required=True)\\n hardware = XML.SubElement(root, 'hardwareProperties')\\n for (prop_name, prop_val) in data.get('hardware-properties', {}).items():\\n prop_node = XML.SubElement(hardware, 'hudson.plugins.android__emulator.AndroidEmulator_-HardwareProperty')\\n mapping = [('', 'key', prop_name), ('', 'value', prop_val)]\\n convert_mapping_to_xml(prop_node, data, mapping, fail_required=True)\\n mapping = [('wipe', 'wipeData', False), ('show-window', 'showWindow', False), ('snapshot', 'useSnapshots', False), ('delete', 'deleteAfterBuild', False), ('startup-delay', 'startupDelay', 0), ('commandline-options', 'commandLineOptions', ''), ('exe', 'executable', '')]\\n convert_mapping_to_xml(root, data, mapping, fail_required=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _capabilities():\",\"targets\":\"\\\"\\\"\\\"Return connection capabilities\\n It\\\\s a huge klutz to parse right,\\n so hide func for now and pass on the XML instead\\n \\\"\\\"\\\"\\n conn = __get_conn()\\n caps = conn.getCapabilities()\\n caps = minidom.parseString(caps)\\n return caps\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef foldr(fn, elems, initializer=None, name=None):\\n\\n ''''Reduce elems using fn to combine them from right to left.\\n # Arguments\\n fn: Callable that will be called upon each element in elems and an\\n accumulator, for instance `lambda acc, x: acc + x`\\n elems: tensor\\n initializer: The first value used (`elems[-1]` in case of None)\\n name: A string name for the foldr node in the graph\\n # Returns\\n Tensor with same type and shape as `initializer`.'\\n '''\",\"targets\":\"return tf.foldr(fn, elems, initializer=initializer, name=name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_importer(path_name):\\n\\n ''''Python version of PyImport_GetImporter C API function'\\n '''\",\"targets\":\"cache = sys.path_importer_cache\\n try:\\n importer = cache[path_name]\\n except KeyError:\\n cache[path_name] = None\\n for hook in sys.path_hooks:\\n try:\\n importer = hook(path_name)\\n break\\n except ImportError:\\n pass\\n else:\\n try:\\n importer = imp.NullImporter(path_name)\\n except ImportError:\\n return None\\n cache[path_name] = importer\\n return importer\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_attachments(xml):\",\"targets\":\"\\\"\\\"\\\"returns a dictionary of posts that have attachments with a list\\n of the attachment_urls\\n \\\"\\\"\\\"\\n items = get_items(xml)\\n names = {}\\n attachments = []\\n for item in items:\\n kind = item.find(u'post_type').string\\n filename = item.find(u'post_name').string\\n post_id = item.find(u'post_id').string\\n if (kind == u'attachment'):\\n attachments.append((item.find(u'post_parent').string, item.find(u'attachment_url').string))\\n else:\\n filename = get_filename(filename, post_id)\\n names[post_id] = filename\\n attachedposts = {}\\n for (parent, url) in attachments:\\n try:\\n parent_name = names[parent]\\n except KeyError:\\n parent_name = None\\n try:\\n attachedposts[parent_name].append(url)\\n except KeyError:\\n attachedposts[parent_name] = []\\n attachedposts[parent_name].append(url)\\n return attachedposts\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n class _FakeUser(ndb.Model, ):\\n _use_memcache = False\\n _use_cache = False\\n user = ndb.UserProperty(required=True)\\n try:\\n fake_user = users.User(email)\\n except users.UserNotFoundError:\\n logging.error(('The email address %s does not correspond to a valid user_id' % email))\\n return None\\n key = _FakeUser(id=email, user=fake_user).put()\\n obj = _FakeUser.get_by_id(key.id())\\n user_id = obj.user.user_id()\\n if user_id:\\n return unicode(user_id)\\n else:\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_user_id_from_email(email):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef itervalues(d):\\n\\n ''''Return an iterator over the values of a dictionary.'\\n '''\",\"targets\":\"return iter(getattr(d, _itervalues)())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef integration_reduction(facets, index, a, b, expr, dims, degree):\\n\\n ''''Helper method for main_integrate. Returns the value of the input\\n expression evaluated over the polytope facet referenced by a given index.\\n Parameters\\n facets : List of facets of the polytope.\\n index : Index referencing the facet to integrate the expression over.\\n a : Hyperplane parameter denoting direction.\\n b : Hyperplane parameter denoting distance.\\n expr : The expression to integrate over the facet.\\n dims : List of symbols denoting axes.\\n degree : Degree of the homogeneous polynomial.\\n >>> from sympy.abc import x, y\\n >>> from sympy.integrals.intpoly import integration_reduction, hyperplane_parameters\\n >>> from sympy.geometry.point import Point\\n >>> from sympy.geometry.polygon import Polygon\\n >>> triangle = Polygon(Point(0, 3), Point(5, 3), Point(1, 1))\\n >>> facets = triangle.sides\\n >>> a, b = hyperplane_parameters(triangle)[0]\\n >>> integration_reduction(facets, 0, a, b, 1, (x, y), 0)\\n 5'\\n '''\",\"targets\":\"if (expr == S.Zero):\\n return expr\\n (a, b) = ((S(a[0]), S(a[1])), S(b))\\n value = S.Zero\\n x0 = facets[index].points[0]\\n m = len(facets)\\n gens = (x, y)\\n inner_product = ((diff(expr, gens[0]) * x0[0]) + (diff(expr, gens[1]) * x0[1]))\\n if (inner_product != 0):\\n value += integration_reduction(facets, index, a, b, inner_product, dims, (degree - 1))\\n value += left_integral(m, index, facets, x0, expr, gens)\\n return (value \\/ ((len(dims) + degree) - 1))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dict_from_cookiejar(cj):\",\"targets\":\"\\\"\\\"\\\"Returns a key\\/value dictionary from a CookieJar.\\n :param cj: CookieJar object to extract cookies from.\\n \\\"\\\"\\\"\\n cookie_dict = {}\\n for cookie in cj:\\n cookie_dict[cookie.name] = cookie.value\\n return cookie_dict\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _environment_sanity_check(environment):\",\"targets\":\"\\\"\\\"\\\"Perform a sanity check on the environment.\\n \\\"\\\"\\\"\\n assert issubclass(environment.undefined, Undefined), 'undefined must be a subclass of undefined because filters depend on it.'\\n assert (environment.block_start_string != environment.variable_start_string != environment.comment_start_string), 'block, variable and comment start strings must be different'\\n assert (environment.newline_sequence in ('\\\\r', '\\\\r\\\\n', '\\\\n')), 'newline_sequence set to unknown line ending string.'\\n return environment\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dummyModelParams(perm):\",\"targets\":\"\\\"\\\"\\\"This function can be used for Hypersearch algorithm development. When\\n present, we don\\\\t actually run the CLA model in the OPF, but instead run\\n a dummy model. This function returns the dummy model params that will be\\n used. See the OPFDummyModelRunner class source code (in\\n nupic.swarming.ModelRunner) for a description of the schema for\\n the dummy model params.\\n \\\"\\\"\\\"\\n errScore = 500\\n if (not (perm['modelParams']['sensorParams']['encoders']['A'] is None)):\\n errScore -= 50\\n if (not (perm['modelParams']['sensorParams']['encoders']['B'] is None)):\\n errScore -= 40\\n if (not (perm['modelParams']['sensorParams']['encoders']['C'] is None)):\\n errScore -= 30\\n if (not (perm['modelParams']['sensorParams']['encoders']['D'] is None)):\\n errScore -= 20\\n if (not (perm['modelParams']['sensorParams']['encoders']['E'] is None)):\\n errScore -= 15\\n if (not (perm['modelParams']['sensorParams']['encoders']['F'] is None)):\\n errScore -= 10\\n if (not (perm['modelParams']['sensorParams']['encoders']['G'] is None)):\\n errScore -= 5\\n delay = 0\\n encoderCount = 0\\n for key in perm.keys():\\n if (('encoder' in key) and (not (perm[key] is None))):\\n encoderCount += 1\\n delay = ((encoderCount * encoderCount) * 0.1)\\n dummyModelParams = dict(metricValue=errScore, metricFunctions=None, delay=delay)\\n return dummyModelParams\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef file_upload_echo(request):\\n\\n ''''Simple view to echo back info about uploaded files for tests.'\\n '''\",\"targets\":\"r = {k: f.name for (k, f) in request.FILES.items()}\\n return JsonResponse(r)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if hasattr(target, 'im_self'):\\n if (target.im_self is not None):\\n assert hasattr(target, 'im_func'), (\\\"safeRef target %r has im_self, but no im_func, don't know how to create reference\\\" % (target,))\\n reference = get_bound_method_weakref(target=target, onDelete=onDelete)\\n return reference\\n if callable(onDelete):\\n return weakref.ref(target, onDelete)\\n else:\\n return weakref.ref(target)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def safeRef(target, onDelete=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _mini_batch_convergence(model, iteration_idx, n_iter, tol, n_samples, centers_squared_diff, batch_inertia, context, verbose=0):\\n\\n ''''Helper function to encapsulate the early stopping logic'\\n '''\",\"targets\":\"batch_inertia \\/= model.batch_size\\n centers_squared_diff \\/= model.batch_size\\n ewa_diff = context.get('ewa_diff')\\n ewa_inertia = context.get('ewa_inertia')\\n if (ewa_diff is None):\\n ewa_diff = centers_squared_diff\\n ewa_inertia = batch_inertia\\n else:\\n alpha = ((float(model.batch_size) * 2.0) \\/ (n_samples + 1))\\n alpha = (1.0 if (alpha > 1.0) else alpha)\\n ewa_diff = ((ewa_diff * (1 - alpha)) + (centers_squared_diff * alpha))\\n ewa_inertia = ((ewa_inertia * (1 - alpha)) + (batch_inertia * alpha))\\n if verbose:\\n progress_msg = ('Minibatch iteration %d\\/%d: mean batch inertia: %f, ewa inertia: %f ' % ((iteration_idx + 1), n_iter, batch_inertia, ewa_inertia))\\n print progress_msg\\n if ((tol > 0.0) and (ewa_diff <= tol)):\\n if verbose:\\n print ('Converged (small centers change) at iteration %d\\/%d' % ((iteration_idx + 1), n_iter))\\n return True\\n ewa_inertia_min = context.get('ewa_inertia_min')\\n no_improvement = context.get('no_improvement', 0)\\n if ((ewa_inertia_min is None) or (ewa_inertia < ewa_inertia_min)):\\n no_improvement = 0\\n ewa_inertia_min = ewa_inertia\\n else:\\n no_improvement += 1\\n if ((model.max_no_improvement is not None) and (no_improvement >= model.max_no_improvement)):\\n if verbose:\\n print ('Converged (lack of improvement in inertia) at iteration %d\\/%d' % ((iteration_idx + 1), n_iter))\\n return True\\n context['ewa_diff'] = ewa_diff\\n context['ewa_inertia'] = ewa_inertia\\n context['ewa_inertia_min'] = ewa_inertia_min\\n context['no_improvement'] = no_improvement\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if node.ownerDocument.isSameNode(newOwnerDocument):\\n operation = xml.dom.UserDataHandler.NODE_CLONED\\n else:\\n operation = xml.dom.UserDataHandler.NODE_IMPORTED\\n if (node.nodeType == Node.ELEMENT_NODE):\\n clone = newOwnerDocument.createElementNS(node.namespaceURI, node.nodeName)\\n for attr in node.attributes.values():\\n clone.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value)\\n a = clone.getAttributeNodeNS(attr.namespaceURI, attr.localName)\\n a.specified = attr.specified\\n if deep:\\n for child in node.childNodes:\\n c = _clone_node(child, deep, newOwnerDocument)\\n clone.appendChild(c)\\n elif (node.nodeType == Node.DOCUMENT_FRAGMENT_NODE):\\n clone = newOwnerDocument.createDocumentFragment()\\n if deep:\\n for child in node.childNodes:\\n c = _clone_node(child, deep, newOwnerDocument)\\n clone.appendChild(c)\\n elif (node.nodeType == Node.TEXT_NODE):\\n clone = newOwnerDocument.createTextNode(node.data)\\n elif (node.nodeType == Node.CDATA_SECTION_NODE):\\n clone = newOwnerDocument.createCDATASection(node.data)\\n elif (node.nodeType == Node.PROCESSING_INSTRUCTION_NODE):\\n clone = newOwnerDocument.createProcessingInstruction(node.target, node.data)\\n elif (node.nodeType == Node.COMMENT_NODE):\\n clone = newOwnerDocument.createComment(node.data)\\n elif (node.nodeType == Node.ATTRIBUTE_NODE):\\n clone = newOwnerDocument.createAttributeNS(node.namespaceURI, node.nodeName)\\n clone.specified = True\\n clone.value = node.value\\n elif (node.nodeType == Node.DOCUMENT_TYPE_NODE):\\n assert (node.ownerDocument is not newOwnerDocument)\\n operation = xml.dom.UserDataHandler.NODE_IMPORTED\\n clone = newOwnerDocument.implementation.createDocumentType(node.name, node.publicId, node.systemId)\\n clone.ownerDocument = newOwnerDocument\\n if deep:\\n clone.entities._seq = []\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def _clone_node(node, deep, newOwnerDocument):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getRadioPluginsAddPluginFrame(directoryPath, importantFileNames, names, repository):\",\"targets\":\"\\\"\\\"\\\"Get the radio plugins and add the plugin frame.\\n \\\"\\\"\\\"\\n repository.pluginFrame = PluginFrame()\\n radioPlugins = []\\n for name in names:\\n radioPlugin = RadioPlugin().getFromRadio((name in importantFileNames), repository.pluginFrame.latentStringVar, name, repository, (name == importantFileNames[0]))\\n radioPlugin.updateFunction = repository.pluginFrame.update\\n radioPlugins.append(radioPlugin)\\n defaultRadioButton = getSelectedRadioPlugin((importantFileNames + [radioPlugins[0].name]), radioPlugins)\\n repository.pluginFrame.getFromPath(defaultRadioButton, directoryPath, repository)\\n return radioPlugins\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n a = use_app()\\n if (a.backend_name.lower() == 'pyglet'):\\n return\\n if (a.backend_name.lower() == 'osmesa'):\\n return\\n configs = [dict(samples=4), dict(stencil_size=8), dict(samples=4, stencil_size=8)]\\n if (a.backend_name.lower() != 'glfw'):\\n configs.append(dict(double_buffer=False, samples=4))\\n configs.append(dict(double_buffer=False))\\n else:\\n assert_raises(RuntimeError, Canvas, app=a, config=dict(double_buffer=False))\\n if ((a.backend_name.lower() == 'sdl2') and (os.getenv('TRAVIS') == 'true')):\\n raise SkipTest('Travis SDL cannot set context')\\n for config in configs:\\n n_items = len(config)\\n with Canvas(config=config):\\n if ('true' in (os.getenv('TRAVIS', ''), os.getenv('APPVEYOR', '').lower())):\\n props = config\\n else:\\n props = get_gl_configuration()\\n assert_equal(len(config), n_items)\\n for (key, val) in config.items():\\n if (key == 'samples'):\\n iswx = (a.backend_name.lower() == 'wx')\\n if (not (sys.platform.startswith('win') or iswx)):\\n assert_equal(val, props[key], key)\\n assert_raises(TypeError, Canvas, config='foo')\\n assert_raises(KeyError, Canvas, config=dict(foo=True))\\n assert_raises(TypeError, Canvas, config=dict(double_buffer='foo'))\\n\\n\\nWhat's a good function header?\",\"targets\":\"@requires_application()\\ndef test_context_properties():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n host = urlparse(url)[1]\\n if (not host):\\n return None\\n return host\\n\\n\\nWhat's a good function header?\",\"targets\":\"def host_for_url(url):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_all_uncheck_express():\",\"targets\":\"\\\"\\\"\\\"\\n \\\"\\\"\\\"\\n express_info = Express.query.filter((Express.ischeck != 3)).all()\\n return express_info\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n kwds = dict(root_id=lpar_uuid, suffix_type='quick', suffix_parm=qprop)\\n if (not log_errors):\\n helpers = adapter.helpers\\n try:\\n helpers.remove(pvm_log.log_helper)\\n except ValueError:\\n pass\\n kwds['helpers'] = helpers\\n try:\\n resp = adapter.read(pvm_lpar.LPAR.schema_type, **kwds)\\n except pvm_exc.HttpError as e:\\n with excutils.save_and_reraise_exception(logger=LOG) as sare:\\n if (e.response and (e.response.status == 404)):\\n sare.reraise = False\\n raise exc.InstanceNotFound(instance_id=lpar_uuid)\\n return jsonutils.loads(resp.body)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_vm_qp(adapter, lpar_uuid, qprop=None, log_errors=True):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _lock_file(f, dotlock=True):\\n\\n ''''Lock file f using lockf and dot locking.'\\n '''\",\"targets\":\"dotlock_done = False\\n try:\\n if fcntl:\\n try:\\n fcntl.lockf(f, (fcntl.LOCK_EX | fcntl.LOCK_NB))\\n except IOError as e:\\n if (e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS)):\\n raise ExternalClashError(('lockf: lock unavailable: %s' % f.name))\\n else:\\n raise\\n if dotlock:\\n try:\\n pre_lock = _create_temporary((f.name + '.lock'))\\n pre_lock.close()\\n except IOError as e:\\n if (e.errno in (errno.EACCES, errno.EROFS)):\\n return\\n else:\\n raise\\n try:\\n if hasattr(os, 'link'):\\n os.link(pre_lock.name, (f.name + '.lock'))\\n dotlock_done = True\\n os.unlink(pre_lock.name)\\n else:\\n os.rename(pre_lock.name, (f.name + '.lock'))\\n dotlock_done = True\\n except OSError as e:\\n if ((e.errno == errno.EEXIST) or ((os.name == 'os2') and (e.errno == errno.EACCES))):\\n os.remove(pre_lock.name)\\n raise ExternalClashError(('dot lock unavailable: %s' % f.name))\\n else:\\n raise\\n except:\\n if fcntl:\\n fcntl.lockf(f, fcntl.LOCK_UN)\\n if dotlock_done:\\n os.remove((f.name + '.lock'))\\n raise\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (f is not None):\\n return os.path.normpath(os.path.relpath(f, path))\\n else:\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def relative_normpath(f, path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __virtual__():\",\"targets\":\"\\\"\\\"\\\"Only load if boto is available.\\n \\\"\\\"\\\"\\n if ('boto3_elasticache.cache_cluster_exists' in __salt__):\\n return 'boto3_elasticache'\\n else:\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n newly_determined = []\\n col = list(col)\\n if (all((isinstance(x, (Float, Integer)) for x in col)) and any((isinstance(x, Float) for x in col))):\\n col_abs = [abs(x) for x in col]\\n max_value = max(col_abs)\\n if iszerofunc(max_value):\\n if (max_value != 0):\\n newly_determined = [(i, 0) for (i, x) in enumerate(col) if (x != 0)]\\n return (None, None, False, newly_determined)\\n index = col_abs.index(max_value)\\n return (index, col[index], False, newly_determined)\\n possible_zeros = []\\n for (i, x) in enumerate(col):\\n is_zero = iszerofunc(x)\\n if (is_zero == False):\\n return (i, x, False, newly_determined)\\n possible_zeros.append(is_zero)\\n if all(possible_zeros):\\n return (None, None, False, newly_determined)\\n for (i, x) in enumerate(col):\\n if (possible_zeros[i] is not None):\\n continue\\n simped = simpfunc(x)\\n is_zero = iszerofunc(simped)\\n if ((is_zero == True) or (is_zero == False)):\\n newly_determined.append((i, simped))\\n if (is_zero == False):\\n return (i, simped, False, newly_determined)\\n possible_zeros[i] = is_zero\\n if all(possible_zeros):\\n return (None, None, False, newly_determined)\\n for (i, x) in enumerate(col):\\n if (possible_zeros[i] is not None):\\n continue\\n if x.equals(S.Zero):\\n possible_zeros[i] = True\\n newly_determined.append((i, S.Zero))\\n if all(possible_zeros):\\n return (None, None, False, newly_determined)\\n i = possible_zeros.index(None)\\n return (i, col[i], True, newly_determined)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _find_reasonable_pivot(col, iszerofunc=_iszero, simpfunc=_simplify):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get(schema=None, key=None, user=None, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Get key in a particular GNOME schema\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ gnome.get user= schema=org.gnome.desktop.screensaver key=idle-activation-enabled\\n \\\"\\\"\\\"\\n _gsession = _GSettings(user=user, schema=schema, key=key)\\n return _gsession._get()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n net = Mininet(autoStaticArp=True)\\n net.addController('c0')\\n h1 = net.addHost('h1')\\n h2 = net.addHost('h2')\\n s1 = net.addSwitch('s1')\\n link1 = net.addLink(h1, s1, cls=TCLink)\\n net.addLink(h2, s1)\\n net.start()\\n net.pingAll()\\n info('\\\\n*** Configuring one intf with bandwidth of 5 Mb\\\\n')\\n link1.intf1.config(bw=5)\\n info('\\\\n*** Running iperf to test\\\\n')\\n net.iperf()\\n info('\\\\n*** Configuring one intf with loss of 50%\\\\n')\\n link1.intf1.config(loss=50)\\n info('\\\\n')\\n net.iperf((h1, h2), l4Type='UDP')\\n info('\\\\n*** Configuring one intf with delay of 15ms\\\\n')\\n link1.intf1.config(delay='15ms')\\n info('\\\\n*** Run a ping to confirm delay\\\\n')\\n net.pingPairFull()\\n info('\\\\n*** Done testing\\\\n')\\n net.stop()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def intfOptions():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def log_file(msg, filename='game.log'):\",\"targets\":\"\\\"\\\"\\\"Arbitrary file logger using threads.\\n Args:\\n msg (str): String to append to logfile.\\n filename (str, optional): Defaults to \\\\game.log\\\\. All logs\\n will appear in the logs directory and log entries will start\\n on new lines following datetime info.\\n \\\"\\\"\\\"\\n def callback(filehandle, msg):\\n 'Writing to file and flushing result'\\n msg = ('\\\\n%s [-] %s' % (timeformat(), msg.strip()))\\n filehandle.write(msg)\\n filehandle.flush()\\n def errback(failure):\\n 'Catching errors to normal log'\\n log_trace()\\n filehandle = _open_log_file(filename)\\n if filehandle:\\n deferToThread(callback, filehandle, msg).addErrback(errback)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global _sum_operands\\n _sum_operands = []\\n os.chdir(str(tmpdir))\\n wf = pe.Workflow(name=u'test')\\n inputspec = pe.Node(IdentityInterface(fields=[u'n']), name=u'inputspec')\\n inputspec.iterables = [(u'n', [3, 1, 2, 1, 3])]\\n pre_join1 = pe.Node(IncrementInterface(), name=u'pre_join1')\\n wf.connect(inputspec, u'n', pre_join1, u'input1')\\n join = pe.JoinNode(SumInterface(), joinsource=u'inputspec', joinfield=u'input1', unique=True, name=u'join')\\n wf.connect(pre_join1, u'output1', join, u'input1')\\n wf.run()\\n assert (_sum_operands[0] == [4, 2, 3]), (u'The unique join output value is incorrect: %s.' % _sum_operands[0])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_unique_join_node(tmpdir):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def init(mpstate):\",\"targets\":\"\\\"\\\"\\\"initialise module\\n \\\"\\\"\\\"\\n return FollowTestModule(mpstate)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def arg_to_softmax(prob):\",\"targets\":\"\\\"\\\"\\\"Oh no! Someone has passed you the probability output,\\n \\\"prob\\\", of a softmax function, and you want the unnormalized\\n log probability--the argument to the softmax.\\n Verify that prob really is the output of a softmax. Raise a\\n TypeError if it is not.\\n If it is, return the argument to the softmax.\\n \\\"\\\"\\\"\\n if (not isinstance(prob, Variable)):\\n raise TypeError()\\n if (prob.owner is None):\\n raise TypeError()\\n owner = prob.owner\\n if (not isinstance(owner.op, T.nnet.Softmax)):\\n raise TypeError()\\n (rval,) = owner.inputs\\n return rval\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _inFilesystemNamespace(path):\",\"targets\":\"\\\"\\\"\\\"Determine whether the given unix socket path is in a filesystem namespace.\\n While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and\\n above support PF_UNIX sockets in an \\\"abstract namespace\\\" that does not\\n correspond to any path. This function returns C{True} if the given socket\\n path is stored in the filesystem and C{False} if the path is in this\\n abstract namespace.\\n \\\"\\\"\\\"\\n return (path[:1] != '\\\\x00')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_str(s):\\n\\n ''''@brief Determines if string.\\n @param s String\\n @return True if string, False otherwise.'\\n '''\",\"targets\":\"return isinstance(s, basestring)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_alarm(name, region=None, key=None, keyid=None, profile=None):\\n\\n ''''Get alarm details. Also can be used to check to see if an alarm exists.\\n CLI example::\\n salt myminion boto_cloudwatch.get_alarm myalarm region=us-east-1'\\n '''\",\"targets\":\"conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n alarms = conn.describe_alarms(alarm_names=[name])\\n if (len(alarms) == 0):\\n return None\\n if (len(alarms) > 1):\\n log.error(\\\"multiple alarms matched name '{0}'\\\".format(name))\\n return _metric_alarm_to_dict(alarms[0])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (global_dict, local_dict) = get_twill_glocals()\\n d = global_dict.copy()\\n d.update(local_dict)\\n print d.get(str(which))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def showvar(which):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def intColor(index, hues=9, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255):\",\"targets\":\"\\\"\\\"\\\"Creates a QColor from a single index. Useful for stepping through a predefined list of colors.\\n The argument *index* determines which color from the set will be returned. All other arguments determine what the set of predefined colors will be\\n Colors are chosen by cycling across hues while varying the value (brightness).\\n By default, this selects from a list of 9 hues.\\n \\\"\\\"\\\"\\n hues = int(hues)\\n values = int(values)\\n ind = (int(index) % (hues * values))\\n indh = (ind % hues)\\n indv = (ind \\/\\/ hues)\\n if (values > 1):\\n v = (minValue + (indv * ((maxValue - minValue) \\/ (values - 1))))\\n else:\\n v = maxValue\\n h = (minHue + ((indh * (maxHue - minHue)) \\/ hues))\\n c = QtGui.QColor()\\n c.setHsv(h, sat, v)\\n c.setAlpha(alpha)\\n return c\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _generateExtraMetricSpecs(options):\",\"targets\":\"\\\"\\\"\\\"Generates the non-default metrics specified by the expGenerator params\\n \\\"\\\"\\\"\\n global _metricSpecSchema\\n results = []\\n for metric in options['metrics']:\\n for propertyName in _metricSpecSchema['properties'].keys():\\n _getPropertyValue(_metricSpecSchema, propertyName, metric)\\n (specString, label) = _generateMetricSpecString(field=metric['field'], metric=metric['metric'], params=metric['params'], inferenceElement=metric['inferenceElement'], returnLabel=True)\\n if metric['logged']:\\n options['loggedMetrics'].append(label)\\n results.append(specString)\\n return results\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n index = p.ring.gens.index(x)\\n n = 1\\n for k in p:\\n power = k[index]\\n if isinstance(power, Rational):\\n (num, den) = power.as_numer_denom()\\n n = ((n * den) \\/\\/ igcd(n, den))\\n elif (power != int(power)):\\n (num, den) = (power.numerator, power.denominator)\\n n = ((n * den) \\/\\/ igcd(n, den))\\n if (n != 1):\\n p1 = pow_xin(p, index, n)\\n r = f(p1, q, x, (prec * n))\\n n1 = QQ(1, n)\\n r = pow_xin(r, index, n1)\\n else:\\n r = f(p, q, x, prec)\\n return r\\n\\n\\nWhat's a good function header?\",\"targets\":\"def rs_puiseux2(f, p, q, x, prec):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def list_groups(api):\",\"targets\":\"\\\"\\\"\\\"This function prints a list of all host groups. This function requires\\n one argument, the FreeIPA\\/IPA API object.\\n \\\"\\\"\\\"\\n inventory = {}\\n hostvars = {}\\n meta = {}\\n result = api.Command.hostgroup_find()['result']\\n for hostgroup in result:\\n members = []\\n if ('member_host' in hostgroup):\\n members = [host for host in hostgroup['member_host']]\\n if ('memberindirect_host' in hostgroup):\\n members += (host for host in hostgroup['memberindirect_host'])\\n inventory[hostgroup['cn'][0]] = {'hosts': [host for host in members]}\\n for member in members:\\n hostvars[member] = {}\\n inventory['_meta'] = {'hostvars': hostvars}\\n inv_string = json.dumps(inventory, indent=1, sort_keys=True)\\n print inv_string\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (host_platform == 'darwin'):\\n sysroot = macosx_sdk_root()\\n for dir in std_dirs:\\n f = os.path.join(dir, filename)\\n if ((host_platform == 'darwin') and is_macosx_sdk_path(dir)):\\n f = os.path.join(sysroot, dir[1:], filename)\\n if os.path.exists(f):\\n return []\\n for dir in paths:\\n f = os.path.join(dir, filename)\\n if ((host_platform == 'darwin') and is_macosx_sdk_path(dir)):\\n f = os.path.join(sysroot, dir[1:], filename)\\n if os.path.exists(f):\\n return [dir]\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def find_file(filename, std_dirs, paths):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def load_command_class(app_name, name):\",\"targets\":\"\\\"\\\"\\\"Given a command name and an application name, returns the Command\\n class instance. All errors raised by the import process\\n (ImportError, AttributeError) are allowed to propagate.\\n \\\"\\\"\\\"\\n module = import_module(('%s.management.commands.%s' % (app_name, name)))\\n return module.Command()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def cxMessyOnePoint(ind1, ind2):\",\"targets\":\"\\\"\\\"\\\"Executes a one point crossover on :term:`sequence` individual.\\n The crossover will in most cases change the individuals size. The two\\n individuals are modified in place.\\n :param ind1: The first individual participating in the crossover.\\n :param ind2: The second individual participating in the crossover.\\n :returns: A tuple of two individuals.\\n This function uses the :func:`~random.randint` function from the python base\\n :mod:`random` module.\\n \\\"\\\"\\\"\\n cxpoint1 = random.randint(0, len(ind1))\\n cxpoint2 = random.randint(0, len(ind2))\\n (ind1[cxpoint1:], ind2[cxpoint2:]) = (ind2[cxpoint2:], ind1[cxpoint1:])\\n return (ind1, ind2)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef has_comments_in_diffsets_excluding(review, diffset_pair):\\n\\n ''''Returns whether the specified review has \\\"other comments\\\".\\n This is used to notify users that their review has comments on diff\\n revisions other than the one that they happen to be looking at at any given\\n moment.'\\n '''\",\"targets\":\"if (not review):\\n return False\\n (current_diffset, interdiff) = diffset_pair\\n q = DiffSet.objects.filter(files__comments__review=review)\\n q = q.filter(files__comments__interfilediff__isnull=True).distinct()\\n if (not interdiff):\\n q = q.exclude(pk=current_diffset.id)\\n if (q.count() > 0):\\n return True\\n q = DiffSet.objects.filter(files__comments__review=review)\\n q = q.filter(files__comments__interfilediff__isnull=False)\\n if interdiff:\\n q = q.exclude(pk=current_diffset.id, files__comments__interfilediff__diffset=interdiff)\\n return (q.count() > 0)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@receiver(SignalHandler.course_published)\\ndef _listen_for_course_publish(sender, course_key, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Catches the signal that a course has been published in Studio and\\n sets the verification deadline date to a default.\\n \\\"\\\"\\\"\\n course = modulestore().get_course(course_key)\\n if course:\\n try:\\n deadline = VerificationDeadline.objects.get(course_key=course_key)\\n if ((not deadline.deadline_is_explicit) and (deadline.deadline != course.end)):\\n VerificationDeadline.set_deadline(course_key, course.end)\\n except ObjectDoesNotExist:\\n VerificationDeadline.set_deadline(course_key, course.end)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def cloudfiles(module, container, src, dest, method, typ, meta, clear_meta, structure, expires):\",\"targets\":\"\\\"\\\"\\\"Dispatch from here to work with metadata or file objects\\n \\\"\\\"\\\"\\n cf = pyrax.cloudfiles\\n if (cf is None):\\n module.fail_json(msg='Failed to instantiate client. This typically indicates an invalid region or an incorrectly capitalized region name.')\\n if (typ == 'file'):\\n if (method == 'put'):\\n upload(module, cf, container, src, dest, meta, expires)\\n elif (method == 'get'):\\n download(module, cf, container, src, dest, structure)\\n elif (method == 'delete'):\\n delete(module, cf, container, src, dest)\\n else:\\n if (method == 'get'):\\n get_meta(module, cf, container, src, dest)\\n if (method == 'put'):\\n put_meta(module, cf, container, src, dest, meta, clear_meta)\\n if (method == 'delete'):\\n delete_meta(module, cf, container, src, dest, meta)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def filter_by_version(test_class, version_dict, current_version):\",\"targets\":\"\\\"\\\"\\\"Remove test methods that do not work with the current lib version.\\n \\\"\\\"\\\"\\n find_required_version = version_dict.get\\n def dummy_test_method(self):\\n pass\\n for name in dir(test_class):\\n expected_version = find_required_version(name, (0, 0, 0))\\n if (expected_version > current_version):\\n setattr(test_class, name, dummy_test_method)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def batch_tasks(registry, xml_parent, data):\",\"targets\":\"\\\"\\\"\\\"yaml: batch-tasks\\n Batch tasks can be tasks for events like releases, integration, archiving,\\n etc. In this way, anyone in the project team can execute them in a way that\\n leaves a record.\\n A batch task consists of a shell script and a name. When you execute\\n a build, the shell script gets run on the workspace, just like a build.\\n Batch tasks and builds \\\"lock\\\" the workspace, so when one of those\\n activities is in progress, all the others will block in the queue.\\n Requires the Jenkins :jenkins-wiki:`Batch Task Plugin `.\\n :arg list batch-tasks: Batch tasks.\\n :Tasks:\\n * **name** (`str`) Task name.\\n * **script** (`str`) Task script.\\n Example:\\n .. literalinclude:: \\/..\\/..\\/tests\\/properties\\/fixtures\\/batch-task.yaml\\n :language: yaml\\n \\\"\\\"\\\"\\n pdef = XML.SubElement(xml_parent, 'hudson.plugins.batch__task.BatchTaskProperty')\\n tasks = XML.SubElement(pdef, 'tasks')\\n for task in data:\\n batch_task = XML.SubElement(tasks, 'hudson.plugins.batch__task.BatchTask')\\n mapping = [('name', 'name', None), ('script', 'script', None)]\\n helpers.convert_mapping_to_xml(batch_task, task, mapping, fail_required=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@XFAIL\\ndef test_mul2():\",\"targets\":\"\\\"\\\"\\\"When this fails, remove things labelled \\\"2-arg hack\\\"\\n 1) remove special handling in the fallback of subs that\\n was added in the same commit as this test\\n 2) remove the special handling in Mul.flatten\\n \\\"\\\"\\\"\\n assert (2 * (x + 1)).is_Mul\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef dup_pquo(f, g, K):\\n\\n ''''Polynomial exact pseudo-quotient in ``K[X]``.\\n Examples\\n >>> from sympy.polys import ring, ZZ\\n >>> R, x = ring(\\\"x\\\", ZZ)\\n >>> R.dup_pquo(x**2 - 1, 2*x - 2)\\n 2*x + 2\\n >>> R.dup_pquo(x**2 + 1, 2*x - 4)\\n 2*x + 4'\\n '''\",\"targets\":\"return dup_pdiv(f, g, K)[0]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef map_references(value, field, actual_course_key):\\n\\n ''''Map the references in value to actual_course_key and return value'\\n '''\",\"targets\":\"if (not value):\\n return value\\n if isinstance(field, Reference):\\n return value.map_into_course(actual_course_key)\\n if isinstance(field, ReferenceList):\\n return [sub.map_into_course(actual_course_key) for sub in value]\\n if isinstance(field, ReferenceValueDict):\\n return {key: ele.map_into_course(actual_course_key) for (key, ele) in value.iteritems()}\\n return value\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n opened_files = []\\n try:\\n if (in_file == '-'):\\n in_file = sys.stdin\\n elif isinstance(in_file, basestring):\\n if (name is None):\\n name = os.path.basename(in_file)\\n if (mode is None):\\n try:\\n mode = os.stat(in_file).st_mode\\n except AttributeError:\\n pass\\n in_file = open(in_file, 'rb')\\n opened_files.append(in_file)\\n if (out_file == '-'):\\n out_file = sys.stdout\\n elif isinstance(out_file, basestring):\\n out_file = open(out_file, 'wb')\\n opened_files.append(out_file)\\n if (name is None):\\n name = '-'\\n if (mode is None):\\n mode = 438\\n out_file.write(('begin %o %s\\\\n' % ((mode & 511), name)))\\n data = in_file.read(45)\\n while (len(data) > 0):\\n out_file.write(binascii.b2a_uu(data))\\n data = in_file.read(45)\\n out_file.write(' \\\\nend\\\\n')\\n finally:\\n for f in opened_files:\\n f.close()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def encode(in_file, out_file, name=None, mode=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _bootstrap_debian(name, **kwargs):\\n\\n ''''Bootstrap a Debian Linux container'\\n '''\",\"targets\":\"version = kwargs.get('version', False)\\n if (not version):\\n if (__grains__['os'].lower() == 'debian'):\\n version = __grains__['osrelease']\\n else:\\n version = 'stable'\\n release_blacklist = ['hamm', 'slink', 'potato', 'woody', 'sarge', 'etch', 'lenny', 'squeeze', 'wheezy']\\n if (version in release_blacklist):\\n raise CommandExecutionError('Unsupported Debian version \\\"{0}\\\". Only \\\"stable\\\" or \\\"jessie\\\" and newer are supported'.format(version))\\n dst = _make_container_root(name)\\n cmd = 'debootstrap --arch=amd64 {0} {1}'.format(version, dst)\\n ret = __salt__['cmd.run_all'](cmd, python_shell=False)\\n if (ret['retcode'] != 0):\\n _build_failed(dst, name)\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def app(environ, start_response):\",\"targets\":\"\\\"\\\"\\\"Application which cooperatively pauses 20 seconds (needed to surpass normal timeouts) before responding\\n \\\"\\\"\\\"\\n status = '200 OK'\\n response_headers = [('Content-type', 'text\\/plain'), ('Transfer-Encoding', 'chunked')]\\n sys.stdout.write('request received')\\n sys.stdout.flush()\\n start_response(status, response_headers)\\n return TestIter()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef initRepeat(container, func, n):\\n\\n ''''Call the function *container* with a generator function corresponding\\n to the calling *n* times the function *func*.\\n :param container: The type to put in the data from func.\\n :param func: The function that will be called n times to fill the\\n container.\\n :param n: The number of times to repeat func.\\n :returns: An instance of the container filled with data from func.\\n This helper function can can be used in conjunction with a Toolbox\\n to register a generator of filled containers, as individuals or\\n population.\\n >>> initRepeat(list, random.random, 2) # doctest: +ELLIPSIS,\\n ... # doctest: +NORMALIZE_WHITESPACE\\n [0.4761..., 0.6302...]\\n See the :ref:`list-of-floats` and :ref:`population` tutorials for more examples.'\\n '''\",\"targets\":\"return container((func() for _ in xrange(n)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def UpdateWithDict(tablename, props, prere):\",\"targets\":\"\\\"\\\"\\\"\\n \\\"\\\"\\\"\\n sql = forEachUpdateProps(tablename, props, prere)\\n conn = dbpool.connection()\\n cursor = conn.cursor()\\n count = 0\\n try:\\n count = cursor.execute(sql)\\n conn.commit()\\n except Exception as e:\\n log.err(e)\\n log.err(sql)\\n cursor.close()\\n conn.close()\\n if (count >= 1):\\n return True\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_journal():\\n\\n ''''Return the active running journal object'\\n '''\",\"targets\":\"if ('systemd.journald' in __context__):\\n return __context__['systemd.journald']\\n __context__['systemd.journald'] = systemd.journal.Reader()\\n __context__['systemd.journald'].seek_tail()\\n __context__['systemd.journald'].get_previous()\\n return __context__['systemd.journald']\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef all_methods(obj):\\n\\n ''''Return a list of names of methods of `obj`'\\n '''\",\"targets\":\"temp = []\\n for name in dir(obj):\\n func = getattr(obj, name)\\n if hasattr(func, '__call__'):\\n temp.append(name)\\n return temp\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def TranslateXmlToYamlForDevAppServer(app_engine_web_xml, web_xml, war_root):\",\"targets\":\"\\\"\\\"\\\"Does parsed-XML to YAML-string translation.\\n This method is used in the Dev App Server context, where files are served\\n directly from the input war directory, unlike the appcfg case where they are\\n copied or linked into a parallel hierarchy. This means that there is no\\n __static__ directory containing exactly the files that are supposed to be\\n served statically.\\n Args:\\n app_engine_web_xml: parsed AppEngineWebXml object corresponding to the\\n contents of app-engine.web.xml.\\n web_xml: parsed WebXml object corresponding to the contents of web.xml.\\n war_root: the path to the root directory of the war hierarchy\\n Returns:\\n The full text of the app.yaml generated from the xml files.\\n Raises:\\n AppEngineConfigException: raised in processing stage for illegal XML.\\n \\\"\\\"\\\"\\n translator = AppYamlTranslatorForDevAppServer(app_engine_web_xml, web_xml, war_root)\\n return translator.GetYaml()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def format_filesize(size):\",\"targets\":\"\\\"\\\"\\\"Formats the file size into a human readable format.\\n \\\"\\\"\\\"\\n for suffix in ('bytes', 'KB', 'MB', 'GB', 'TB'):\\n if (size < 1024.0):\\n if (suffix in ('GB', 'TB')):\\n return '{0:3.2f} {1}'.format(size, suffix)\\n else:\\n return '{0:3.1f} {1}'.format(size, suffix)\\n size \\/= 1024.0\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ackley(individual):\",\"targets\":\"\\\"\\\"\\\"Ackley test objective function.\\n .. list-table::\\n :widths: 10 50\\n :stub-columns: 1\\n * - Type\\n - minimization\\n * - Range\\n - :math:`x_i \\\\in [-15, 30]`\\n * - Global optima\\n - :math:`x_i = 0, \\\\forall i \\\\in \\\\lbrace 1 \\\\ldots N\\\\rbrace`, :math:`f(\\\\mathbf{x}) = 0`\\n * - Function\\n - :math:`f(\\\\mathbf{x}) = 20 - 20\\\\exp\\\\left(-0.2\\\\sqrt{\\\\frac{1}{N} \\\\sum_{i=1}^N x_i^2} \\\\right) + e - \\\\exp\\\\left(\\\\frac{1}{N}\\\\sum_{i=1}^N \\\\cos(2\\\\pi x_i) \\\\right)`\\n .. plot:: code\\/benchmarks\\/ackley.py\\n :width: 67 %\\n \\\"\\\"\\\"\\n N = len(individual)\\n return ((((20 - (20 * exp(((-0.2) * sqrt(((1.0 \\/ N) * sum(((x ** 2) for x in individual)))))))) + e) - exp(((1.0 \\/ N) * sum((cos(((2 * pi) * x)) for x in individual))))),)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef check_pool(lb, name):\\n\\n ''''Check to see if a pool exists\\n CLI Examples:\\n .. code-block:: bash\\n salt-run f5.check_pool load_balancer pool_name'\\n '''\",\"targets\":\"if __opts__['load_balancers'].get(lb, None):\\n (username, password) = list(__opts__['load_balancers'][lb].values())\\n else:\\n raise Exception('Unable to find `{0}` load balancer'.format(lb))\\n F5 = F5Mgmt(lb, username, password)\\n return F5.check_pool(name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def customized(*args, **kwargs):\\n 'Customized constructor'\\n kwargs = kwargs.copy()\\n kwargs.update(params)\\n return cls(*args, **kwargs)\\n customized.__name__ = ('custom(%s,%s)' % (cls, params))\\n return customized\\n\\n\\nWhat's a good function header?\",\"targets\":\"def custom(cls, **params):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef linked_data(prefix, ignore_channels=False):\\n\\n ''''Return a dictionary of the linked packages in prefix.'\\n '''\",\"targets\":\"pd = PrefixData(prefix)\\n return {Dist(prefix_record): prefix_record for prefix_record in itervalues(pd._prefix_records)}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def generate_nonce(length=8):\",\"targets\":\"\\\"\\\"\\\"Generate pseudorandom number.\\n \\\"\\\"\\\"\\n return ''.join([str(random.randint(0, 9)) for i in range(length)])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef gaussian_conj(s_in, z_r_in, f):\\n\\n ''''Conjugation relation for gaussian beams.\\n Parameters\\n s_in : the distance to optical element from the waist\\n z_r_in : the rayleigh range of the incident beam\\n f : the focal length of the optical element\\n Returns\\n a tuple containing (s_out, z_r_out, m)\\n s_out : the distance between the new waist and the optical element\\n z_r_out : the rayleigh range of the emergent beam\\n m : the ration between the new and the old waists\\n Examples\\n >>> from sympy.physics.optics import gaussian_conj\\n >>> from sympy import symbols\\n >>> s_in, z_r_in, f = symbols(\\\\'s_in z_r_in f\\\\')\\n >>> gaussian_conj(s_in, z_r_in, f)[0]\\n 1\\/(-1\\/(s_in + z_r_in**2\\/(-f + s_in)) + 1\\/f)\\n >>> gaussian_conj(s_in, z_r_in, f)[1]\\n z_r_in\\/(1 - s_in**2\\/f**2 + z_r_in**2\\/f**2)\\n >>> gaussian_conj(s_in, z_r_in, f)[2]\\n 1\\/sqrt(1 - s_in**2\\/f**2 + z_r_in**2\\/f**2)'\\n '''\",\"targets\":\"(s_in, z_r_in, f) = map(sympify, (s_in, z_r_in, f))\\n s_out = (1 \\/ (((-1) \\/ (s_in + ((z_r_in ** 2) \\/ (s_in - f)))) + (1 \\/ f)))\\n m = (1 \\/ sqrt(((1 - ((s_in \\/ f) ** 2)) + ((z_r_in \\/ f) ** 2))))\\n z_r_out = (z_r_in \\/ ((1 - ((s_in \\/ f) ** 2)) + ((z_r_in \\/ f) ** 2)))\\n return (s_out, z_r_out, m)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _zpkbilinear(z, p, k, fs):\\n\\n ''''Return a digital filter from an analog one using a bilinear transform.\\n Transform a set of poles and zeros from the analog s-plane to the digital\\n z-plane using Tustin\\\\'s method, which substitutes ``(z-1) \\/ (z+1)`` for\\n ``s``, maintaining the shape of the frequency response.\\n Parameters\\n z : array_like\\n Zeros of the analog IIR filter transfer function.\\n p : array_like\\n Poles of the analog IIR filter transfer function.\\n k : float\\n System gain of the analog IIR filter transfer function.\\n fs : float\\n Sample rate, as ordinary frequency (e.g. hertz). No prewarping is\\n done in this function.\\n Returns\\n z : ndarray\\n Zeros of the transformed digital filter transfer function.\\n p : ndarray\\n Poles of the transformed digital filter transfer function.\\n k : float\\n System gain of the transformed digital filter.'\\n '''\",\"targets\":\"z = atleast_1d(z)\\n p = atleast_1d(p)\\n degree = _relative_degree(z, p)\\n fs2 = (2.0 * fs)\\n z_z = ((fs2 + z) \\/ (fs2 - z))\\n p_z = ((fs2 + p) \\/ (fs2 - p))\\n z_z = append(z_z, (- ones(degree)))\\n k_z = (k * real((prod((fs2 - z)) \\/ prod((fs2 - p)))))\\n return (z_z, p_z, k_z)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (splt, coll, props) = generate_EventCollection_plot()\\n coll.switch_orientation()\\n coll.switch_orientation()\\n new_positions = coll.get_positions()\\n assert_equal(props[u'orientation'], coll.get_orientation())\\n assert_equal(True, coll.is_horizontal())\\n np.testing.assert_array_equal(props[u'positions'], new_positions)\\n check_segments(coll, new_positions, props[u'linelength'], props[u'lineoffset'], props[u'orientation'])\\n splt.set_title(u'EventCollection: switch_orientation 2x')\\n\\n\\nWhat's a good function header?\",\"targets\":\"@image_comparison(baseline_images=[u'EventCollection_plot__switch_orientation__2x'])\\ndef test__EventCollection__switch_orientation_2x():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n outputs = fgraph.outputs\\n assert isinstance(outputs, (tuple, list, deque))\\n parent_counts = {}\\n node_to_children = {}\\n visitable = deque()\\n for var in fgraph.variables:\\n owner = var.owner\\n if owner:\\n node_to_children.setdefault(owner, []).append(var)\\n parent_counts[var] = 1\\n else:\\n visitable.append(var)\\n parent_counts[var] = 0\\n for a_n in fgraph.apply_nodes:\\n parents = list(a_n.inputs)\\n parents.extend(orderings.get(a_n, []))\\n if parents:\\n for parent in parents:\\n node_to_children.setdefault(parent, []).append(a_n)\\n parent_counts[a_n] = len(parents)\\n else:\\n visitable.append(a_n)\\n parent_counts[a_n] = 0\\n visited = 0\\n while visitable:\\n node = visitable.popleft()\\n visited += 1\\n for client in node_to_children.get(node, []):\\n parent_counts[client] -= 1\\n if (not parent_counts[client]):\\n visitable.append(client)\\n return (visited != len(parent_counts))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _contains_cycle(fgraph, orderings):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_proc_create_time(proc):\\n\\n ''''Returns the create_time of a Process instance.\\n It\\\\'s backward compatible with < 2.0 versions of psutil.'\\n '''\",\"targets\":\"try:\\n return (proc.create_time() if PSUTIL2 else proc.create_time)\\n except (psutil.NoSuchProcess, psutil.AccessDenied):\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_distribution(dist):\",\"targets\":\"\\\"\\\"\\\"Return a current distribution object for a Requirement or string\\n \\\"\\\"\\\"\\n if isinstance(dist, basestring):\\n dist = Requirement.parse(dist)\\n if isinstance(dist, Requirement):\\n dist = get_provider(dist)\\n if (not isinstance(dist, Distribution)):\\n raise TypeError('Expected string, Requirement, or Distribution', dist)\\n return dist\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n paths = (os.environ.get('PATH', os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS)\\n oc_binary = 'oc'\\n try:\\n which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))\\n if (which_result is not None):\\n oc_binary = which_result\\n except AttributeError:\\n for path in paths:\\n if os.path.exists(os.path.join(path, oc_binary)):\\n oc_binary = os.path.join(path, oc_binary)\\n break\\n return oc_binary\\n\\n\\nWhat's a good function header?\",\"targets\":\"def locate_oc_binary():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def addsitedir(sitedir, known_paths=None):\",\"targets\":\"\\\"\\\"\\\"Add \\\\sitedir\\\\ argument to sys.path if missing and handle .pth files in\\n \\\\sitedir\\\\\\n \\\"\\\"\\\"\\n if (known_paths is None):\\n known_paths = _init_pathinfo()\\n reset = 1\\n else:\\n reset = 0\\n (sitedir, sitedircase) = makepath(sitedir)\\n if (sitedircase not in known_paths):\\n sys.path.append(sitedir)\\n try:\\n names = os.listdir(sitedir)\\n except os.error:\\n return\\n dotpth = (os.extsep + 'pth')\\n names = [name for name in names if name.endswith(dotpth)]\\n for name in sorted(names):\\n addpackage(sitedir, name, known_paths)\\n if reset:\\n known_paths = None\\n return known_paths\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not host):\\n raise ValueError(\\\"Host values of '' or None are not allowed.\\\")\\n if (timeout is None):\\n timeout = free_port_timeout\\n for trial in range(50):\\n try:\\n check_port(host, port, timeout=timeout)\\n except IOError:\\n time.sleep(timeout)\\n else:\\n return\\n raise IOError(('Port %r not free on %r' % (port, host)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def wait_for_free_port(host, port, timeout=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n body = BytesIO()\\n if (boundary is None):\\n boundary = choose_boundary()\\n for (fieldname, value) in iter_fields(fields):\\n body.write(b(('--%s\\\\r\\\\n' % boundary)))\\n if isinstance(value, tuple):\\n (filename, data) = value\\n writer(body).write(('Content-Disposition: form-data; name=\\\"%s\\\"; filename=\\\"%s\\\"\\\\r\\\\n' % (fieldname, filename)))\\n body.write(b(('Content-Type: %s\\\\r\\\\n\\\\r\\\\n' % get_content_type(filename))))\\n else:\\n data = value\\n writer(body).write(('Content-Disposition: form-data; name=\\\"%s\\\"\\\\r\\\\n' % fieldname))\\n body.write('Content-Type: text\\/plain\\\\r\\\\n\\\\r\\\\n')\\n if isinstance(data, int):\\n data = str(data)\\n if isinstance(data, six.text_type):\\n writer(body).write(data)\\n else:\\n body.write(data)\\n body.write('\\\\r\\\\n')\\n body.write(b(('--%s--\\\\r\\\\n' % boundary)))\\n content_type = b(('multipart\\/form-data; boundary=%s' % boundary))\\n return (body.getvalue(), content_type)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def encode_multipart_formdata(fields, boundary=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef MX(domain, resolve=False, nameserver=None):\\n\\n ''''Return a list of lists for the MX of ``domain``.\\n If the \\\\'resolve\\\\' argument is True, resolve IPs for the servers.\\n It\\\\'s limited to one IP, because although in practice it\\\\'s very rarely a\\n round robin, it is an acceptable configuration and pulling just one IP lets\\n the data be similar to the non-resolved version. If you think an MX has\\n multiple IPs, don\\\\'t use the resolver here, resolve them in a separate step.\\n CLI Example:\\n .. code-block:: bash\\n salt ns1 dnsutil.MX google.com'\\n '''\",\"targets\":\"if _has_dig():\\n return __salt__['dig.MX'](domain, resolve, nameserver)\\n return 'This function requires dig, which is not currently available'\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _exists_in_path(cmd, environ):\",\"targets\":\"\\\"\\\"\\\"Based on a code snippet from\\n http:\\/\\/orip.org\\/2009\\/08\\/python-checking-if-executable-exists-in.html\\n \\\"\\\"\\\"\\n if (u'PATH' in environ):\\n input_environ = environ.get(u'PATH')\\n else:\\n input_environ = os.environ.get(u'PATH', u'')\\n extensions = os.environ.get(u'PATHEXT', u'').split(os.pathsep)\\n for directory in input_environ.split(os.pathsep):\\n base = os.path.join(directory, cmd)\\n options = ([base] + [(base + ext) for ext in extensions])\\n for filename in options:\\n if os.path.exists(filename):\\n return (True, filename)\\n return (False, None)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@utils.arg('monitor', metavar='', help='ID of the monitor to backup.')\\n@utils.arg('--container', metavar='', help='Optional Backup container name. (Default=None)', default=None)\\n@utils.arg('--display-name', metavar='', help='Optional backup name. (Default=None)', default=None)\\n@utils.arg('--display-description', metavar='', help='Optional backup description. (Default=None)', default=None)\\n@utils.service_type('monitor')\\ndef do_backup_create(cs, args):\",\"targets\":\"\\\"\\\"\\\"Creates a backup.\\n \\\"\\\"\\\"\\n cs.backups.create(args.monitor, args.container, args.display_name, args.display_description)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _negotiate_value(r):\",\"targets\":\"\\\"\\\"\\\"Extracts the gssapi authentication token from the appropriate header\\n \\\"\\\"\\\"\\n authreq = r.headers.get('www-authenticate', None)\\n if authreq:\\n rx = re.compile('(?:.*,)*\\\\\\\\s*Negotiate\\\\\\\\s*([^,]*),?', re.I)\\n mo = rx.search(authreq)\\n if mo:\\n return mo.group(1)\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def debug_script(src, pm=False, globs=None):\",\"targets\":\"\\\"\\\"\\\"Debug a test script. `src` is the script, as a string.\\n \\\"\\\"\\\"\\n import pdb\\n srcfilename = tempfile.mktemp('.py', 'doctestdebug')\\n f = open(srcfilename, 'w')\\n f.write(src)\\n f.close()\\n try:\\n if globs:\\n globs = globs.copy()\\n else:\\n globs = {}\\n if pm:\\n try:\\n execfile(srcfilename, globs, globs)\\n except:\\n print sys.exc_info()[1]\\n pdb.post_mortem(sys.exc_info()[2])\\n else:\\n pdb.run(('execfile(%r)' % srcfilename), globs, globs)\\n finally:\\n os.remove(srcfilename)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def k_random_intersection_graph(n, m, k):\",\"targets\":\"\\\"\\\"\\\"Return a intersection graph with randomly chosen attribute sets for\\n each node that are of equal size (k).\\n Parameters\\n n : int\\n The number of nodes in the first bipartite set (nodes)\\n m : int\\n The number of nodes in the second bipartite set (attributes)\\n k : float\\n Size of attribute set to assign to each node.\\n seed : int, optional\\n Seed for random number generator (default=None).\\n See Also\\n gnp_random_graph, uniform_random_intersection_graph\\n References\\n .. [1] Godehardt, E., and Jaworski, J.\\n Two models of random intersection graphs and their applications.\\n Electronic Notes in Discrete Mathematics 10 (2001), 129--132.\\n \\\"\\\"\\\"\\n G = nx.empty_graph((n + m))\\n mset = range(n, (n + m))\\n for v in range(n):\\n targets = random.sample(mset, k)\\n G.add_edges_from(zip(([v] * len(targets)), targets))\\n return nx.projected_graph(G, range(n))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def coerce_indexer_dtype(indexer, categories):\",\"targets\":\"\\\"\\\"\\\"coerce the indexer input array to the smallest dtype possible\\n \\\"\\\"\\\"\\n l = len(categories)\\n if (l < _int8_max):\\n return _ensure_int8(indexer)\\n elif (l < _int16_max):\\n return _ensure_int16(indexer)\\n elif (l < _int32_max):\\n return _ensure_int32(indexer)\\n return _ensure_int64(indexer)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n cmd = ['shutdown', '-i', state, '-g', '0', '-y']\\n ret = __salt__['cmd.run'](cmd, python_shell=False)\\n return ret\\n\\n\\nWhat's a good function header?\",\"targets\":\"def init(state):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def do_with(parser, token):\",\"targets\":\"\\\"\\\"\\\"Adds a value to the context (inside of this block) for caching and easy\\n access.\\n For example::\\n {% with person.some_sql_method as total %}\\n {{ total }} object{{ total|pluralize }}\\n {% endwith %}\\n \\\"\\\"\\\"\\n bits = list(token.split_contents())\\n if ((len(bits) != 4) or (bits[2] != 'as')):\\n raise TemplateSyntaxError((\\\"%r expected format is 'value as name'\\\" % bits[0]))\\n var = parser.compile_filter(bits[1])\\n name = bits[3]\\n nodelist = parser.parse(('endwith',))\\n parser.delete_first_token()\\n return WithNode(var, name, nodelist)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _setup_constants(alphabet=NAMESPACE_CHARACTERS, max_length=MAX_NAMESPACE_LENGTH):\",\"targets\":\"\\\"\\\"\\\"Calculate derived constant values. Only useful for testing.\\n \\\"\\\"\\\"\\n global NAMESPACE_CHARACTERS\\n global MAX_NAMESPACE_LENGTH\\n global MAX_NAMESPACE\\n global _LEX_DISTANCE\\n NAMESPACE_CHARACTERS = alphabet\\n MAX_NAMESPACE_LENGTH = max_length\\n MAX_NAMESPACE = (NAMESPACE_CHARACTERS[(-1)] * MAX_NAMESPACE_LENGTH)\\n _LEX_DISTANCE = [1]\\n for i in range(1, MAX_NAMESPACE_LENGTH):\\n _LEX_DISTANCE.append(((_LEX_DISTANCE[(i - 1)] * len(NAMESPACE_CHARACTERS)) + 1))\\n del i\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def check_api_key(key):\",\"targets\":\"\\\"\\\"\\\"Validate an API key by calling an API endpoint with no quota cost\\n \\\"\\\"\\\"\\n url = 'https:\\/\\/www.googleapis.com\\/youtube\\/v3\\/i18nLanguages'\\n query = {'part': 'snippet', 'fields': 'items\\/id', 'key': key}\\n try:\\n urlopen(((url + '?') + urlencode(query))).read()\\n message = ((\\\"The key, '\\\" + key) + \\\"' will now be used for API requests.\\\")\\n pafy.set_api_key(Config.API_KEY.get)\\n return dict(valid=True, message=message)\\n except HTTPError:\\n message = ((\\\"Invalid key or quota exceeded, '\\\" + key) + \\\"'\\\")\\n return dict(valid=False, message=message)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_vmdk_adapter_type(adapter_type):\",\"targets\":\"\\\"\\\"\\\"Return the adapter type to be used in vmdk descriptor.\\n Adapter type in vmdk descriptor is same for LSI-SAS, LSILogic & ParaVirtual\\n because Virtual Disk Manager API does not recognize the newer controller\\n types.\\n \\\"\\\"\\\"\\n if (adapter_type in [constants.ADAPTER_TYPE_LSILOGICSAS, constants.ADAPTER_TYPE_PARAVIRTUAL]):\\n vmdk_adapter_type = constants.DEFAULT_ADAPTER_TYPE\\n else:\\n vmdk_adapter_type = adapter_type\\n return vmdk_adapter_type\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getDeprecated(self, decorators):\\n\\n ''''With a list of decorators, and the object it is running on, set the\\n C{_deprecated_info} flag if any of the decorators are a Twisted deprecation\\n decorator.'\\n '''\",\"targets\":\"for a in decorators:\\n if isinstance(a, ast.CallFunc):\\n decorator = a.asList()\\n if isinstance(decorator[0], ast.Getattr):\\n getAttr = decorator[0].asList()\\n name = getAttr[0].name\\n fn = ((self.expandName(name) + '.') + getAttr[1])\\n else:\\n fn = self.expandName(decorator[0].name)\\n if (fn == 'twisted.python.deprecate.deprecated'):\\n try:\\n self._deprecated_info = deprecatedToUsefulText(self.name, decorator)\\n except AttributeError:\\n pass\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef libvlc_media_library_new(p_instance):\\n\\n ''''Create an new Media Library object.\\n @param p_instance: the libvlc instance.\\n @return: a new object or NULL on error.'\\n '''\",\"targets\":\"f = (_Cfunctions.get('libvlc_media_library_new', None) or _Cfunction('libvlc_media_library_new', ((1,),), class_result(MediaLibrary), ctypes.c_void_p, Instance))\\n return f(p_instance)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def foobar_triangle(side_A, side_B, side_C):\",\"targets\":\"\\\"\\\"\\\"This returns perimeter of a triangle.\\n :param side_A:\\n length of side_A\\n :param side_B:\\n length of side_B\\n :param side_C:\\n length of side_C\\n :return: returns perimeter\\n \\\"\\\"\\\"\\n return ((side_A + side_B) + side_C)\\n triple_quote_string_literal_test = '\\\\nThis is a triple quoted string and is not a valid docstring.\\\\n'\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_variables_to_train():\\n\\n ''''Returns a list of variables to train.\\n Returns:\\n A list of variables to train by the optimizer.'\\n '''\",\"targets\":\"if (FLAGS.trainable_scopes is None):\\n return tf.trainable_variables()\\n else:\\n scopes = [scope.strip() for scope in FLAGS.trainable_scopes.split(',')]\\n variables_to_train = []\\n for scope in scopes:\\n variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope)\\n variables_to_train.extend(variables)\\n return variables_to_train\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n edges = _make_edges_3d(n_x, n_y, n_z)\\n if (dtype is None):\\n if (img is None):\\n dtype = np.int\\n else:\\n dtype = img.dtype\\n if (img is not None):\\n img = np.atleast_3d(img)\\n weights = _compute_gradient_3d(edges, img)\\n if (mask is not None):\\n (edges, weights) = _mask_edges_weights(mask, edges, weights)\\n diag = img.squeeze()[mask]\\n else:\\n diag = img.ravel()\\n n_voxels = diag.size\\n else:\\n if (mask is not None):\\n mask = mask.astype(dtype=np.bool, copy=False)\\n mask = np.asarray(mask, dtype=np.bool)\\n edges = _mask_edges_weights(mask, edges)\\n n_voxels = np.sum(mask)\\n else:\\n n_voxels = ((n_x * n_y) * n_z)\\n weights = np.ones(edges.shape[1], dtype=dtype)\\n diag = np.ones(n_voxels, dtype=dtype)\\n diag_idx = np.arange(n_voxels)\\n i_idx = np.hstack((edges[0], edges[1]))\\n j_idx = np.hstack((edges[1], edges[0]))\\n graph = sparse.coo_matrix((np.hstack((weights, weights, diag)), (np.hstack((i_idx, diag_idx)), np.hstack((j_idx, diag_idx)))), (n_voxels, n_voxels), dtype=dtype)\\n if (return_as is np.ndarray):\\n return graph.toarray()\\n return return_as(graph)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _to_graph(n_x, n_y, n_z, mask=None, img=None, return_as=sparse.coo_matrix, dtype=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def GetMountpoints():\",\"targets\":\"\\\"\\\"\\\"List all the filesystems mounted on the system.\\n \\\"\\\"\\\"\\n devices = {}\\n for filesys in GetFileSystems():\\n devices[filesys.f_mntonname] = (filesys.f_mntfromname, filesys.f_fstypename)\\n return devices\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getmacbyip(ip, chainCC=0):\\n\\n ''''Return MAC address corresponding to a given IP address'\\n '''\",\"targets\":\"if isinstance(ip, Net):\\n ip = iter(ip).next()\\n tmp = map(ord, inet_aton(ip))\\n if ((tmp[0] & 240) == 224):\\n return ('01:00:5e:%.2x:%.2x:%.2x' % ((tmp[1] & 127), tmp[2], tmp[3]))\\n (iff, a, gw) = conf.route.route(ip)\\n if ((iff == LOOPBACK_NAME) or (ip == conf.route.get_if_bcast(iff))):\\n return 'ff:ff:ff:ff:ff:ff'\\n ifip = str(pcapdnet.dnet.intf().get(iff)['addr'])\\n if (gw != ifip.split('\\/')[0]):\\n ip = gw\\n mac = conf.netcache.arp_cache.get(ip)\\n if mac:\\n return mac\\n res = srp1((Ether(dst=ETHER_BROADCAST) \\/ ARP(op='who-has', pdst=ip)), type=ETH_P_ARP, iface=iff, timeout=2, verbose=0, chainCC=chainCC, nofilter=1)\\n if (res is not None):\\n mac = res.payload.hwsrc\\n conf.netcache.arp_cache[ip] = mac\\n return mac\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef make_subrequest(env, method=None, path=None, body=None, headers=None, agent='Swift', swift_source=None, make_env=make_env):\\n\\n ''''Makes a new swob.Request based on the current env but with the\\n parameters specified.\\n :param env: The WSGI environment to base the new request on.\\n :param method: HTTP method of new request; default is from\\n the original env.\\n :param path: HTTP path of new request; default is from the\\n original env. path should be compatible with what you\\n would send to Request.blank. path should be quoted and it\\n can include a query string. for example:\\n \\\\'\\/a%20space?unicode_str%E8%AA%9E=y%20es\\\\'\\n :param body: HTTP body of new request; empty by default.\\n :param headers: Extra HTTP headers of new request; None by\\n default.\\n :param agent: The HTTP user agent to use; default \\\\'Swift\\\\'. You\\n can put %(orig)s in the agent to have it replaced\\n with the original env\\\\'s HTTP_USER_AGENT, such as\\n \\\\'%(orig)s StaticWeb\\\\'. You also set agent to None to\\n use the original env\\\\'s HTTP_USER_AGENT or \\\\'\\\\' to\\n have no HTTP_USER_AGENT.\\n :param swift_source: Used to mark the request as originating out of\\n middleware. Will be logged in proxy logs.\\n :param make_env: make_subrequest calls this make_env to help build the\\n swob.Request.\\n :returns: Fresh swob.Request object.'\\n '''\",\"targets\":\"query_string = None\\n path = (path or '')\\n if (path and ('?' in path)):\\n (path, query_string) = path.split('?', 1)\\n newenv = make_env(env, method, path=unquote(path), agent=agent, query_string=query_string, swift_source=swift_source)\\n if (not headers):\\n headers = {}\\n if body:\\n return Request.blank(path, environ=newenv, body=body, headers=headers)\\n else:\\n return Request.blank(path, environ=newenv, headers=headers)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n op = node.op\\n if (not isinstance(op, T.Rebroadcast)):\\n return False\\n input = node.inputs[0]\\n inode = input.owner\\n if (inode and isinstance(inode.op, Elemwise) and (len(inode.inputs) == 1)):\\n if (hasattr(input, 'clients') and (len(input.clients) == 1)):\\n rebroadcasted = T.Rebroadcast(*list(op.axis.items()))(inode.inputs[0])\\n copy_stack_trace(node.outputs, rebroadcasted)\\n rval = inode.op.make_node(rebroadcasted).outputs\\n copy_stack_trace((node.outputs + node.inputs), rval)\\n return rval\\n if (inode and isinstance(inode.op, T.Rebroadcast)):\\n axis = inode.op.axis.copy()\\n axis.update(op.axis)\\n iinput = inode.inputs[0]\\n rval = [T.Rebroadcast(*list(axis.items()))(iinput)]\\n copy_stack_trace((node.outputs + node.inputs), rval)\\n return rval\\n\\n\\nWhat's a good function header?\",\"targets\":\"@register_canonicalize\\n@register_specialize\\n@gof.local_optimizer([T.Rebroadcast])\\ndef local_rebroadcast_lift(node):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef flatten(lst):\\n\\n ''''flatten list or return scalar'\\n '''\",\"targets\":\"if atomp(lst):\\n return lst\\n return _flatten(lst)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"main entry point for module execution\\n \\\"\\\"\\\"\\n argument_spec = dict(src=dict(type='path'), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block']), multiline_delimiter=dict(default='@'), force=dict(default=False, type='bool'), config=dict(), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save=dict(default=False, type='bool'))\\n mutually_exclusive = [('lines', 'src')]\\n required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines'])]\\n module = NetworkModule(argument_spec=argument_spec, connect_on_load=False, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True)\\n if (module.params['force'] is True):\\n module.params['match'] = 'none'\\n warnings = list()\\n check_args(module, warnings)\\n result = dict(changed=False, warnings=warnings)\\n if module.params['backup']:\\n result['__backup__'] = module.config.get_config()\\n try:\\n run(module, result)\\n except NetworkError:\\n exc = get_exception()\\n module.disconnect()\\n module.fail_json(msg=str(exc))\\n module.disconnect()\\n module.exit_json(**result)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef libvlc_media_player_has_vout(p_mi):\\n\\n ''''How many video outputs does this media player have?\\n @param p_mi: the media player.\\n @return: the number of video outputs.'\\n '''\",\"targets\":\"f = (_Cfunctions.get('libvlc_media_player_has_vout', None) or _Cfunction('libvlc_media_player_has_vout', ((1,),), None, ctypes.c_uint, MediaPlayer))\\n return f(p_mi)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n P = Vector(a[0], a[1])\\n Q = Vector(b[0], b[1])\\n R = Vector(c[0], c[1])\\n mPQ = ((P + Q) * 0.5)\\n mQR = ((Q + R) * 0.5)\\n numer = (- (((((((((- mPQ.y) * R.y) + (mPQ.y * Q.y)) + (mQR.y * R.y)) - (mQR.y * Q.y)) - (mPQ.x * R.x)) + (mPQ.x * Q.x)) + (mQR.x * R.x)) - (mQR.x * Q.x)))\\n denom = (((((((- Q.x) * R.y) + (P.x * R.y)) - (P.x * Q.y)) + (Q.y * R.x)) - (P.y * R.x)) + (P.y * Q.x))\\n t = (numer \\/ denom)\\n cx = (((- t) * (Q.y - P.y)) + mPQ.x)\\n cy = ((t * (Q.x - P.x)) + mPQ.y)\\n return ((cx, cy), (P - (cx, cy)).length())\\n\\n\\nWhat's a good function header?\",\"targets\":\"def circumcircle(a, b, c):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def consistencygroup_destroy(context, consistencygroup_id):\",\"targets\":\"\\\"\\\"\\\"Destroy the consistencygroup or raise if it does not exist.\\n \\\"\\\"\\\"\\n return IMPL.consistencygroup_destroy(context, consistencygroup_id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _codec_fails_on_encode_surrogates(codec, _cache={}):\",\"targets\":\"\\\"\\\"\\\"Returns if a codec fails correctly when passing in surrogates with\\n a surrogatepass\\/surrogateescape error handler. Some codecs were broken\\n in Python <3.4\\n \\\"\\\"\\\"\\n try:\\n return _cache[codec]\\n except KeyError:\\n try:\\n u'\\\\ud800\\\\udc01'.encode(codec)\\n except UnicodeEncodeError:\\n _cache[codec] = True\\n else:\\n _cache[codec] = False\\n return _cache[codec]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def keyname(vm_):\",\"targets\":\"\\\"\\\"\\\"Return the keyname\\n \\\"\\\"\\\"\\n return config.get_cloud_config_value('keyname', vm_, __opts__, search_global=False)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _platform(*args):\",\"targets\":\"\\\"\\\"\\\"Helper to format the platform string in a filename\\n compatible format e.g. \\\"system-version-machine\\\".\\n \\\"\\\"\\\"\\n platform = '-'.join((x.strip() for x in filter(len, args)))\\n platform = platform.replace(' ', '_')\\n platform = platform.replace('\\/', '-')\\n platform = platform.replace('\\\\\\\\', '-')\\n platform = platform.replace(':', '-')\\n platform = platform.replace(';', '-')\\n platform = platform.replace('\\\"', '-')\\n platform = platform.replace('(', '-')\\n platform = platform.replace(')', '-')\\n platform = platform.replace('unknown', '')\\n while 1:\\n cleaned = platform.replace('--', '-')\\n if (cleaned == platform):\\n break\\n platform = cleaned\\n while (platform[(-1)] == '-'):\\n platform = platform[:(-1)]\\n return platform\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_sha256_str(base_str):\\n\\n ''''Returns string that represents sha256 hash of base_str (in hex format).\\n sha1 and md5 are known to be breakable, so sha256 is a better option\\n when the hash is being used for security purposes. If hashing passwords\\n or anything else that needs to be retained for a long period a salted\\n hash is better.'\\n '''\",\"targets\":\"if isinstance(base_str, six.text_type):\\n base_str = base_str.encode('utf-8')\\n return hashlib.sha256(base_str).hexdigest()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef datatype(dbtype, description):\\n\\n ''''Helper to convert a data type into a string.'\\n '''\",\"targets\":\"dt = connection.introspection.get_field_type(dbtype, description)\\n if (type(dt) is tuple):\\n return dt[0]\\n else:\\n return dt\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@testing.requires_testing_data\\ndef test_read_write_head_pos():\\n\\n ''''Test reading and writing head position quaternion parameters.'\\n '''\",\"targets\":\"tempdir = _TempDir()\\n temp_name = op.join(tempdir, 'temp.pos')\\n head_pos_rand = np.random.RandomState(0).randn(20, 10)\\n head_pos_read = read_head_pos(pos_fname)\\n for head_pos_orig in (head_pos_rand, head_pos_read):\\n write_head_pos(temp_name, head_pos_orig)\\n head_pos = read_head_pos(temp_name)\\n assert_allclose(head_pos_orig, head_pos, atol=0.001)\\n assert_raises(TypeError, write_head_pos, 0, head_pos_read)\\n assert_raises(ValueError, write_head_pos, temp_name, 'foo')\\n assert_raises(ValueError, write_head_pos, temp_name, head_pos_read[:, :9])\\n assert_raises(TypeError, read_head_pos, 0)\\n assert_raises(IOError, read_head_pos, (temp_name + 'foo'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef hex_decode(input, errors='strict'):\\n\\n ''''Decodes the object input and returns a tuple (output\\n object, length consumed).\\n input must be an object which provides the bf_getreadbuf\\n buffer slot. Python strings, buffer objects and memory\\n mapped files are examples of objects providing this slot.\\n errors defines the error handling to apply. It defaults to\\n \\\\'strict\\\\' handling which is the only currently supported\\n error handling for this codec.'\\n '''\",\"targets\":\"assert (errors == 'strict')\\n output = binascii.a2b_hex(input)\\n return (output, len(input))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n f = open('app.yaml', 'r')\\n content = f.read()\\n os.remove('app.yaml')\\n content = content.replace('oppiaserver', APP_NAME)\\n d = open('app.yaml', 'w+')\\n d.write(content)\\n if (not os.path.exists(DEPLOY_DATA_PATH)):\\n raise Exception(('Could not find deploy_data directory at %s' % DEPLOY_DATA_PATH))\\n for filename in FILES_AT_ROOT_IN_COMMON:\\n src = os.path.join(DEPLOY_DATA_PATH, 'common', filename)\\n dst = os.path.join(os.getcwd(), 'assets', 'common', filename)\\n if (not os.path.exists(src)):\\n raise Exception(('Could not find source path %s. Please check your deploy_data folder.' % src))\\n if (not os.path.exists(dst)):\\n raise Exception(('Could not find destination path %s. Has the code been updated in the meantime?' % dst))\\n shutil.copyfile(src, dst)\\n for dir_name in IMAGE_DIRS:\\n src_dir = os.path.join(DEPLOY_DATA_PATH, 'images', dir_name)\\n dst_dir = os.path.join(os.getcwd(), 'assets', 'images', dir_name)\\n if (not os.path.exists(src_dir)):\\n raise Exception(('Could not find source dir %s. Please check your deploy_data folder.' % src_dir))\\n common.ensure_directory_exists(dst_dir)\\n for filename in os.listdir(src_dir):\\n src = os.path.join(src_dir, filename)\\n dst = os.path.join(dst_dir, filename)\\n shutil.copyfile(src, dst)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def preprocess_release():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@library.global_function\\ndef wiki_url(path):\\n\\n ''''Create a URL pointing to Kuma.\\n Look for a wiki page in the current locale, or default to given path'\\n '''\",\"targets\":\"if ('#' in path):\\n (slug, fragment) = path.split('#', 1)\\n else:\\n slug = path\\n fragment = ''\\n new_path = reverse('wiki.document', args=[slug])\\n if fragment:\\n new_path += ('#' + fragment)\\n return new_path\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n item_status = get_object_or_404(ItemStatus, pk=status_id)\\n if (not request.user.profile.has_permission(item_status, mode='w')):\\n return user_denied(request, message=\\\"You don't have access to this Item Status\\\", response_format=response_format)\\n if request.POST:\\n if ('delete' in request.POST):\\n if ('trash' in request.POST):\\n item_status.trash = True\\n item_status.save()\\n else:\\n item_status.delete()\\n return HttpResponseRedirect(reverse('infrastructure_settings_view'))\\n elif ('cancel' in request.POST):\\n return HttpResponseRedirect(reverse('infrastructure_item_view', args=[item_status.id]))\\n context = _get_default_context(request)\\n context.update({'item_status': item_status})\\n return render_to_response('infrastructure\\/item_status_delete', context, context_instance=RequestContext(request), response_format=response_format)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@treeio_login_required\\n@handle_response_format\\ndef status_delete(request, status_id, response_format='html'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef ensure_list(indices):\\n\\n ''''Return a list, even if indices is a single value\\n :arg indices: A list of indices to act upon\\n :rtype: list'\\n '''\",\"targets\":\"if (not isinstance(indices, list)):\\n indices = [indices]\\n return indices\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n name = config.get(CONF_NAME)\\n token = config.get(CONF_TOKEN)\\n async_add_devices([TOTPSensor(name, token)], True)\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"@asyncio.coroutine\\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n image = np.arange(0, 255, 4, np.uint8).reshape((8, 8))\\n expected = np.array([[0, 5, 11, 16, 22, 27, 33, 38], [43, 48, 53, 58, 63, 68, 73, 77], [82, 86, 91, 95, 100, 104, 109, 113], [117, 121, 125, 129, 133, 137, 141, 145], [149, 153, 157, 160, 164, 168, 172, 175], [179, 182, 186, 189, 193, 196, 199, 203], [206, 209, 213, 216, 219, 222, 225, 228], [231, 234, 238, 241, 244, 246, 249, 252]], dtype=np.uint8)\\n result = exposure.adjust_log(image, 1)\\n assert_array_equal(result, expected)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_adjust_log():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _parse_header(fh):\",\"targets\":\"\\\"\\\"\\\"Reads the font metrics header (up to the char metrics) and returns\\n a dictionary mapping *key* to *val*. *val* will be converted to the\\n appropriate python type as necessary; e.g.:\\n * \\\\False\\\\->False\\n * \\\\0\\\\->0\\n * \\\\-168 -218 1000 898\\\\-> [-168, -218, 1000, 898]\\n Dictionary keys are\\n StartFontMetrics, FontName, FullName, FamilyName, Weight,\\n ItalicAngle, IsFixedPitch, FontBBox, UnderlinePosition,\\n UnderlineThickness, Version, Notice, EncodingScheme, CapHeight,\\n XHeight, Ascender, Descender, StartCharMetrics\\n \\\"\\\"\\\"\\n headerConverters = {'StartFontMetrics': _to_float, 'FontName': _to_str, 'FullName': _to_str, 'FamilyName': _to_str, 'Weight': _to_str, 'ItalicAngle': _to_float, 'IsFixedPitch': _to_bool, 'FontBBox': _to_list_of_ints, 'UnderlinePosition': _to_int, 'UnderlineThickness': _to_int, 'Version': _to_str, 'Notice': _to_str, 'EncodingScheme': _to_str, 'CapHeight': _to_float, 'Capheight': _to_float, 'XHeight': _to_float, 'Ascender': _to_float, 'Descender': _to_float, 'StdHW': _to_float, 'StdVW': _to_float, 'StartCharMetrics': _to_int, 'CharacterSet': _to_str, 'Characters': _to_int}\\n d = {}\\n for line in fh:\\n line = line.rstrip()\\n if line.startswith('Comment'):\\n continue\\n lst = line.split(' ', 1)\\n key = lst[0]\\n if (len(lst) == 2):\\n val = lst[1]\\n else:\\n val = ''\\n try:\\n d[key] = headerConverters[key](val)\\n except ValueError:\\n print(u'Value error parsing header in AFM:', key, val, file=sys.stderr)\\n continue\\n except KeyError:\\n print((u'Found an unknown keyword in AFM header (was %r)' % key), file=sys.stderr)\\n continue\\n if (key == 'StartCharMetrics'):\\n return d\\n raise RuntimeError(u'Bad parse')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef EC2Token_filter_factory(global_conf, **local_conf):\\n\\n ''''Factory method for paste.deploy.'\\n '''\",\"targets\":\"conf = global_conf.copy()\\n conf.update(local_conf)\\n def filter(app):\\n return EC2Token(app, conf)\\n return filter\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from distutils.version import StrictVersion\\n from distutils.spawn import find_executable\\n import re\\n gcc_exe = find_executable('gcc')\\n if gcc_exe:\\n out = os.popen((gcc_exe + ' -dumpversion'), 'r')\\n try:\\n out_string = out.read()\\n finally:\\n out.close()\\n result = re.search('(\\\\\\\\d+\\\\\\\\.\\\\\\\\d+\\\\\\\\.\\\\\\\\d+)', out_string)\\n if result:\\n gcc_version = StrictVersion(result.group(1))\\n else:\\n gcc_version = None\\n else:\\n gcc_version = None\\n ld_version = None\\n return (gcc_version, ld_version)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_versions():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@frappe.whitelist()\\ndef install_app(name):\",\"targets\":\"\\\"\\\"\\\"Install app, if app is not installed in local environment, install it via git url in\\n `frappe\\/data\\/app_listing\\/`\\n \\\"\\\"\\\"\\n frappe.only_for(u'System Manager')\\n if (name not in frappe.get_all_apps(True)):\\n if (not frappe.conf.disallow_app_listing):\\n get_app(name)\\n frappe.cache().delete_value([u'app_hooks'])\\n import site\\n reload(site)\\n else:\\n frappe.throw(_(u'Listing app not allowed'))\\n app_hooks = frappe.get_hooks(app_name=name)\\n if app_hooks.get(u'hide_in_installer'):\\n frappe.throw(_(u'You cannot install this app'))\\n enqueue(u'frappe.desk.page.applications.applications.start_install', name=name)\\n frappe.msgprint(_(u'Queued for install'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@given(u'a run having mixed text content')\\ndef given_a_run_having_mixed_text_content(context):\\n\\n ''''Mixed here meaning it contains ````, ````, etc. elements.'\\n '''\",\"targets\":\"r_xml = (u' \\\\n abc<\\/w:t>\\\\n \\\\n def<\\/w:t>\\\\n \\\\n ghi<\\/w:t>\\\\n \\\\n \\\\n jkl<\\/w:t>\\\\n <\\/w:r>' % nsdecls(u'w'))\\n r = parse_xml(r_xml)\\n context.run = Run(r, None)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef cast_to_server(context, server_params, topic, msg):\\n\\n ''''Invoke a remote method that does not return anything.\\n :param context: Information that identifies the user that has made this\\n request.\\n :param server_params: Connection information\\n :param topic: The topic to send the notification to.\\n :param msg: This is a dict in the form { \\\"method\\\" : \\\"method_to_invoke\\\",\\n \\\"args\\\" : dict_of_kwargs }\\n :returns: None'\\n '''\",\"targets\":\"return _get_impl().cast_to_server(CONF, context, server_params, topic, msg)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for image in images:\\n box = [0, 0, image.size[0], image.size[1]]\\n if (border is not None):\\n for (idx, val) in enumerate(box):\\n box[idx] = max(0, (val - border))\\n click.echo(('Cropping \\\"%s\\\" by %dpx' % (image.filename, border)))\\n (yield copy_filename(image.crop(box), image))\\n else:\\n (yield image)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@cli.command('crop')\\n@click.option('-b', '--border', type=int, help='Crop the image from all sides by this amount.')\\n@processor\\ndef crop_cmd(images, border):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef format_header_param(name, value):\\n\\n ''''Helper function to format and quote a single header parameter.\\n Particularly useful for header parameters which might contain\\n non-ASCII values, like file names. This follows RFC 2231, as\\n suggested by RFC 2388 Section 4.4.\\n :param name:\\n The name of the parameter, a string expected to be ASCII only.\\n :param value:\\n The value of the parameter, provided as a unicode string.'\\n '''\",\"targets\":\"if (not any(((ch in value) for ch in '\\\"\\\\\\\\\\\\r\\\\n'))):\\n result = ('%s=\\\"%s\\\"' % (name, value))\\n try:\\n result.encode('ascii')\\n except (UnicodeEncodeError, UnicodeDecodeError):\\n pass\\n else:\\n return result\\n if ((not six.PY3) and isinstance(value, six.text_type)):\\n value = value.encode('utf-8')\\n value = email.utils.encode_rfc2231(value, 'utf-8')\\n value = ('%s*=%s' % (name, value))\\n return value\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_service(hass, config, discovery_info=None):\\n\\n ''''Get the CiscoSpark notification service.'\\n '''\",\"targets\":\"return CiscoSparkNotificationService(config.get(CONF_TOKEN), config.get(CONF_ROOMID))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n old_keys = set(old_module_dict.keys())\\n new_keys = set(new_module_dict.keys())\\n for deleted_module_name in (old_keys - new_keys):\\n if (old_module_dict[deleted_module_name] is None):\\n continue\\n segments = deleted_module_name.rsplit('.', 1)\\n if (len(segments) == 2):\\n parent_module = new_module_dict.get(segments[0])\\n if (parent_module and hasattr(parent_module, segments[1])):\\n delattr(parent_module, segments[1])\\n for added_module_name in (new_keys - old_keys):\\n if (new_module_dict[added_module_name] is None):\\n continue\\n segments = added_module_name.rsplit('.', 1)\\n if (len(segments) == 2):\\n parent_module = old_module_dict.get(segments[0])\\n child_module = new_module_dict[added_module_name]\\n if (parent_module and (getattr(parent_module, segments[1], None) is not child_module)):\\n setattr(parent_module, segments[1], child_module)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ConnectAndDisconnectChildModules(old_module_dict, new_module_dict):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _object_matcher(obj):\",\"targets\":\"\\\"\\\"\\\"Retrieve a matcher function by passing an arbitrary object.\\n i.e. passing a `TreeElement` such as a `Clade` or `Tree` instance returns an\\n identity matcher, passing a type such as the `PhyloXML.Taxonomy` class\\n returns a class matcher, and passing a dictionary returns an attribute\\n matcher.\\n The resulting \\\\match\\\\ function returns True when given an object matching\\n the specification (identity, type or attribute values), otherwise False.\\n This is useful for writing functions that search the tree, and probably\\n shouldn\\\\t be used directly by the end user.\\n \\\"\\\"\\\"\\n if isinstance(obj, TreeElement):\\n return _identity_matcher(obj)\\n if isinstance(obj, type):\\n return _class_matcher(obj)\\n if isinstance(obj, basestring):\\n return _string_matcher(obj)\\n if isinstance(obj, dict):\\n return _attribute_matcher(obj)\\n if callable(obj):\\n return _function_matcher(obj)\\n raise ValueError(('%s (type %s) is not a valid type for comparison.' % (obj, type(obj))))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef inject_into_urllib3():\\n\\n ''''Monkey-patch urllib3 with PyOpenSSL-backed SSL-support.'\\n '''\",\"targets\":\"connectionpool.ssl_wrap_socket = ssl_wrap_socket\\n util.HAS_SNI = HAS_SNI\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _uninstall_helper(verbosity=0):\",\"targets\":\"\\\"\\\"\\\"Helper to support a clean default uninstall process on Windows\\n Note that calling this function may alter os.environ.\\n \\\"\\\"\\\"\\n try:\\n import pip\\n except ImportError:\\n return\\n if (pip.__version__ != _PIP_VERSION):\\n msg = 'ensurepip will only uninstall a matching version ({!r} installed, {!r} bundled)'\\n print(msg.format(pip.__version__, _PIP_VERSION), file=sys.stderr)\\n return\\n _require_ssl_for_pip()\\n _disable_pip_configuration_settings()\\n args = ['uninstall', '-y', '--disable-pip-version-check']\\n if verbosity:\\n args += [('-' + ('v' * verbosity))]\\n _run_pip((args + [p[0] for p in reversed(_PROJECTS)]))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _clean_credentials(credentials):\\n\\n ''''Cleans a dictionary of credentials of potentially sensitive info before\\n sending to less secure functions.\\n Not comprehensive - intended for user_login_failed signal'\\n '''\",\"targets\":\"SENSITIVE_CREDENTIALS = re.compile('api|token|key|secret|password|signature', re.I)\\n CLEANSED_SUBSTITUTE = '********************'\\n for key in credentials:\\n if SENSITIVE_CREDENTIALS.search(key):\\n credentials[key] = CLEANSED_SUBSTITUTE\\n return credentials\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef choose_best_location(locations, **kwargs):\\n\\n ''''Choose best location from image location list by configured strategy.\\n :param locations: The original image location list.\\n :param kwargs: Strategy-specific arguments for under layer strategy module.\\n :returns: The best location from image location list.'\\n '''\",\"targets\":\"locations = get_ordered_locations(locations, **kwargs)\\n if locations:\\n return locations[0]\\n else:\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n fig = plt.figure()\\n ax1 = plt.subplot2grid((3, 3), (0, 0))\\n ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)\\n ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)\\n ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)\\n example_plot(ax1)\\n example_plot(ax2)\\n example_plot(ax3)\\n example_plot(ax4)\\n plt.tight_layout()\\n\\n\\nWhat's a good function header?\",\"targets\":\"@image_comparison(baseline_images=[u'tight_layout4'], freetype_version=(u'2.5.5', u'2.6.1'))\\ndef test_tight_layout4():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef any_to_tensor_and_labels(x, labels=None):\\n\\n ''''Util for converting input x to tensor trying to\\n create labels for columns if they are not provided.\\n Default names for columns are [\\\\'x0\\\\', \\\\'x1\\\\', ...], for mappable\\n arrays (e.g. pd.DataFrame) their names are treated as labels.\\n You can override them with `labels` argument.\\n If you have tensor input you should provide labels as we\\n cannot get their shape directly\\n If you pass dict input we cannot rely on labels order thus dict\\n keys are treated as labels anyway\\n Parameters\\n x : np.ndarray | pd.DataFrame | tt.Variable | dict | list\\n labels : list - names for columns of output tensor\\n Returns\\n (x, labels) - tensor and labels for its columns'\\n '''\",\"targets\":\"if isinstance(labels, six.string_types):\\n labels = [labels]\\n if isinstance(x, pd.DataFrame):\\n if (not labels):\\n labels = x.columns\\n x = x.as_matrix()\\n elif isinstance(x, pd.Series):\\n if (not labels):\\n labels = [x.name]\\n x = x.as_matrix()[:, None]\\n elif isinstance(x, dict):\\n try:\\n x = pd.DataFrame.from_dict(x)\\n labels = x.columns\\n x = x.as_matrix()\\n except (ValueError, TypeError):\\n res = []\\n labels = []\\n for (k, v) in x.items():\\n res.append(v)\\n labels.append(k)\\n x = tt.stack(res, axis=1)\\n if (x.ndim == 1):\\n x = x[:, None]\\n elif (not isinstance(x, tt.Variable)):\\n x = np.asarray(x)\\n if (x.ndim == 0):\\n raise ValueError('Cannot use scalars')\\n elif (x.ndim == 1):\\n x = x[:, None]\\n elif (labels is not None):\\n x = tt.as_tensor_variable(x)\\n if (x.ndim == 0):\\n raise ValueError('Cannot use scalars')\\n elif (x.ndim == 1):\\n x = x[:, None]\\n else:\\n pass\\n if ((labels is None) and (not isinstance(x, tt.Variable))):\\n labels = [('x%d' % i) for i in range(x.shape[1])]\\n elif (labels is None):\\n raise ValueError('Please provide labels as we cannot infer shape of input')\\n else:\\n pass\\n if (not isinstance(x, tt.Variable)):\\n if (not (len(labels) == x.shape[1])):\\n raise ValueError(('Please provide full list of labels for coefficients, got len(labels)=%d instead of %d' % (len(labels), x.shape[1])))\\n else:\\n pass\\n if isinstance(labels, pd.RangeIndex):\\n labels = [('x%d' % i) for i in labels]\\n elif (not isinstance(labels, list)):\\n labels = list(labels)\\n if (not isinstance(x, tt.Variable)):\\n x = tt.as_tensor_variable(x)\\n if (x.ndim == 0):\\n raise...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def RebuildProxy(func, token, serializer, kwds):\",\"targets\":\"\\\"\\\"\\\"Function used for unpickling proxy objects.\\n If possible the shared object is returned, or otherwise a proxy for it.\\n \\\"\\\"\\\"\\n server = getattr(current_process(), '_manager_server', None)\\n if (server and (server.address == token.address)):\\n return server.id_to_obj[token.id][0]\\n else:\\n incref = (kwds.pop('incref', True) and (not getattr(current_process(), '_inheriting', False)))\\n return func(token, serializer, incref=incref, **kwds)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_cmd(args, basename_binary=False):\",\"targets\":\"\\\"\\\"\\\"Takes an array of strings to be passed to subprocess.Popen and creates\\n a string that can be pasted into a terminal\\n :param args:\\n The array containing the binary name\\/path and all arguments\\n :param basename_binary:\\n If only the basename of the binary should be disabled instead of the full path\\n :return:\\n The command string\\n \\\"\\\"\\\"\\n if basename_binary:\\n args[0] = os.path.basename(args[0])\\n if (os.name == 'nt'):\\n return subprocess.list2cmdline(args)\\n else:\\n escaped_args = []\\n for arg in args:\\n if (re.search('^[a-zA-Z0-9\\/_^\\\\\\\\-\\\\\\\\.:=]+$', arg) is None):\\n arg = ((u\\\"'\\\" + arg.replace(u\\\"'\\\", u\\\"'\\\\\\\\''\\\")) + u\\\"'\\\")\\n escaped_args.append(arg)\\n return u' '.join(escaped_args)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_cert_days(module, cert_file):\",\"targets\":\"\\\"\\\"\\\"Return the days the certificate in cert_file remains valid and -1\\n if the file was not found.\\n \\\"\\\"\\\"\\n if (not os.path.exists(cert_file)):\\n return (-1)\\n openssl_bin = module.get_bin_path('openssl', True)\\n openssl_cert_cmd = [openssl_bin, 'x509', '-in', cert_file, '-noout', '-text']\\n (_, out, _) = module.run_command(openssl_cert_cmd, check_rc=True)\\n try:\\n not_after_str = re.search('\\\\\\\\s+Not After\\\\\\\\s*:\\\\\\\\s+(.*)', out.decode('utf8')).group(1)\\n not_after = datetime.datetime.fromtimestamp(time.mktime(time.strptime(not_after_str, '%b %d %H:%M:%S %Y %Z')))\\n except AttributeError:\\n module.fail_json(msg=\\\"No 'Not after' date found in {0}\\\".format(cert_file))\\n except ValueError:\\n module.fail_json(msg=\\\"Failed to parse 'Not after' date of {0}\\\".format(cert_file))\\n now = datetime.datetime.utcnow()\\n return (not_after - now).days\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def isValidColor(color):\",\"targets\":\"\\\"\\\"\\\"check color validity (equivalent to existing checks in _setColor)\\n \\\"\\\"\\\"\\n try:\\n color = float(color)\\n return True\\n except Exception:\\n if (isinstance(color, basestring) and len(color)):\\n return ((color.lower() in list(colors255.keys())) or (color[0] == '#') or (color[0:2] == '0x'))\\n return ((type(color) in [tuple, list, numpy.ndarray]) or (not color))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (C, J, v) = ([], ([0] * len(E)), (u - 1))\\n for h in H:\\n c = dmp_one(v, K)\\n d = (dup_LC(h, K) * cs)\\n for i in reversed(range(len(E))):\\n (k, e, (t, _)) = (0, E[i], T[i])\\n while (not (d % e)):\\n (d, k) = ((d \\/\\/ e), (k + 1))\\n if (k != 0):\\n (c, J[i]) = (dmp_mul(c, dmp_pow(t, k, v, K), v, K), 1)\\n C.append(c)\\n if any(((not j) for j in J)):\\n raise ExtraneousFactors\\n (CC, HH) = ([], [])\\n for (c, h) in zip(C, H):\\n d = dmp_eval_tail(c, A, v, K)\\n lc = dup_LC(h, K)\\n if K.is_one(cs):\\n cc = (lc \\/\\/ d)\\n else:\\n g = K.gcd(lc, d)\\n (d, cc) = ((d \\/\\/ g), (lc \\/\\/ g))\\n (h, cs) = (dup_mul_ground(h, d, K), (cs \\/\\/ d))\\n c = dmp_mul_ground(c, cc, v, K)\\n CC.append(c)\\n HH.append(h)\\n if K.is_one(cs):\\n return (f, HH, CC)\\n (CCC, HHH) = ([], [])\\n for (c, h) in zip(CC, HH):\\n CCC.append(dmp_mul_ground(c, cs, v, K))\\n HHH.append(dmp_mul_ground(h, cs, 0, K))\\n f = dmp_mul_ground(f, (cs ** (len(H) - 1)), u, K)\\n return (f, HHH, CCC)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def dmp_zz_wang_lead_coeffs(f, T, cs, E, H, A, u, K):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef inverse(x, n):\\n\\n ''''Returns x^-1 (mod n)\\n >>> inverse(7, 4)\\n 3\\n >>> (inverse(143, 4) * 143) % 4\\n 1'\\n '''\",\"targets\":\"(divider, inv, _) = extended_gcd(x, n)\\n if (divider != 1):\\n raise ValueError(('x (%d) and n (%d) are not relatively prime' % (x, n)))\\n return inv\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@register.tag\\ndef debug(parser, token):\",\"targets\":\"\\\"\\\"\\\"Outputs a whole load of debugging information, including the current\\n context and imported modules.\\n Sample usage::\\n
\\n    {% debug %}\\n    <\\/pre>\\n    \\\"\\\"\\\"\\n    return DebugNode()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    message_settings = MessageSettings.query.filter_by(action=EVENT_ROLE).first()\\n    if ((not message_settings) or (message_settings.mail_status == 1)):\\n        subject = MAILS[EVENT_ROLE]['subject'].format(role=role, event=event)\\n        message = MAILS[EVENT_ROLE]['message'].format(email=email, role=role, event=event, link=link)\\n        send_email(to=email, action=EVENT_ROLE, subject=subject, html=message)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def send_email_for_event_role_invite(email, role, event, link):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    assert (u.Mbit is u.Mb)\\n    assert (u.megabit is u.Mb)\\n    assert (u.Mbyte is u.MB)\\n    assert (u.megabyte is u.MB)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_megabit():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (version is None):\\n        from wiki import VERSION as version\\n    else:\\n        assert (len(version) == 5)\\n        assert (version[3] in (u'alpha', u'beta', u'rc', u'final'))\\n    return version\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_complete_version(version=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _import_module(name):\",\"targets\":\"\\\"\\\"\\\"Import module, returning the module after the last dot.\\n    \\\"\\\"\\\"\\n    __import__(name)\\n    return sys.modules[name]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    matching_headers = find_matching_headers(name, headers)\\n    return ','.join((str(headers[h]) for h in matching_headers if (headers[h] is not None)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def merge_headers_by_name(name, headers):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _cql_from_cass_type(cass_type):\\n\\n    ''''A string representation of the type for this column, such as \\\"varchar\\\"\\n    or \\\"map\\\".'\\n    '''\",\"targets\":\"if issubclass(cass_type, types.ReversedType):\\n        return cass_type.subtypes[0].cql_parameterized_type()\\n    else:\\n        return cass_type.cql_parameterized_type()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    __tracebackhide__ = True\\n    raise Skipped(msg=msg)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def skip(msg=''):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    r = re.compile(CONF_VARIABLE_REGEX)\\n    def sub(s, depth=0):\\n        if (depth > 100):\\n            logging.warn(('Max    recursion    depth    exceeded    when    substituting    jobconf    value:    %s' % s))\\n            return s\\n        m = r.search(s)\\n        if m:\\n            for g in [g for g in m.groups() if (g in conf)]:\\n                substr = ('${%s}' % g)\\n                s = s.replace(substr, sub(conf[g], (depth + 1)))\\n        return s\\n    for (k, v) in conf.items():\\n        conf[k] = sub(v)\\n    return conf\\n\\n\\nWhat's a good function header?\",\"targets\":\"def make_substitutions(conf):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (not hasattr(sys, 'frozen')):\\n        return os.listdir(path)\\n    (zipPath, archivePath) = splitZip(path)\\n    if (archivePath is None):\\n        return os.listdir(path)\\n    with zipfile.ZipFile(zipPath, 'r') as zipobj:\\n        contents = zipobj.namelist()\\n    results = set()\\n    for name in contents:\\n        if (name.startswith(archivePath) and (len(name) > len(archivePath))):\\n            name = name[len(archivePath):].split('\\/')[0]\\n            results.add(name)\\n    return list(results)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def listdir(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_doc_with_call_signature(scope_node):\",\"targets\":\"\\\"\\\"\\\"Return a document string including call signature.\\n    \\\"\\\"\\\"\\n    call_signature = None\\n    if (scope_node.type == 'classdef'):\\n        for funcdef in scope_node.iter_funcdefs():\\n            if (funcdef.name.value == '__init__'):\\n                call_signature = get_call_signature(funcdef, call_string=scope_node.name.value)\\n    elif (scope_node.type in ('funcdef', 'lambdef')):\\n        call_signature = get_call_signature(scope_node)\\n    doc = clean_scope_docstring(scope_node)\\n    if (call_signature is None):\\n        return doc\\n    return ('%s\\\\n\\\\n%s' % (call_signature, doc))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    TextTestRunner(verbosity=verbosity).run(suite())\\n\\n\\nWhat's a good function header?\",\"targets\":\"def run(verbosity=1):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def availability_zone_list(request):\",\"targets\":\"\\\"\\\"\\\"Utility method to retrieve a list of availability zones.\\n    \\\"\\\"\\\"\\n    try:\\n        if api.cinder.extension_supported(request, 'AvailabilityZones'):\\n            return api.cinder.availability_zone_list(request)\\n        return []\\n    except Exception:\\n        exceptions.handle(request, _('Unable    to    retrieve    volumes    availability    zones.'))\\n        return []\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@_ignore_in_changes\\ndef delete_note(workspace_name, note_id):\",\"targets\":\"\\\"\\\"\\\"Delete the note of id note_id on workspace workspace_name.\\n    Return the json response from the server.\\n    \\\"\\\"\\\"\\n    return server.delete_note(workspace_name, note_id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@public\\ndef invert(f, g, *gens, **args):\",\"targets\":\"\\\"\\\"\\\"Invert ``f`` modulo ``g`` when possible.\\n    Examples\\n    >>> from sympy import invert, S\\n    >>> from sympy.core.numbers import mod_inverse\\n    >>> from sympy.abc import x\\n    >>> invert(x**2 - 1, 2*x - 1)\\n    -4\\/3\\n    >>> invert(x**2 - 1, x - 1)\\n    Traceback (most recent call last):\\n    NotInvertible: zero divisor\\n    For more efficient inversion of Rationals,\\n    use the ``mod_inverse`` function:\\n    >>> mod_inverse(3, 5)\\n    2\\n    >>> (S(2)\\/5).invert(S(7)\\/3)\\n    5\\/2\\n    See Also\\n    sympy.core.numbers.mod_inverse\\n    \\\"\\\"\\\"\\n    options.allowed_flags(args, ['auto', 'polys'])\\n    try:\\n        ((F, G), opt) = parallel_poly_from_expr((f, g), *gens, **args)\\n    except PolificationFailed as exc:\\n        (domain, (a, b)) = construct_domain(exc.exprs)\\n        try:\\n            return domain.to_sympy(domain.invert(a, b))\\n        except NotImplementedError:\\n            raise ComputationFailed('invert', 2, exc)\\n    h = F.invert(G, auto=opt.auto)\\n    if (not opt.polys):\\n        return h.as_expr()\\n    else:\\n        return h\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@register.assignment_tag\\ndef assignment_one_default(one, two='hi'):\",\"targets\":\"\\\"\\\"\\\"Expected assignment_one_default __doc__\\n    \\\"\\\"\\\"\\n    return ('assignment_one_default    -    Expected    result:    %s,    %s' % (one, two))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@coroutine\\ndef component1(reactor, session):\\n\\n    ''''A first component, which gets called \\\"setup-like\\\". When\\n    it returns, this signals that the component is ready for work.'\\n    '''\",\"targets\":\"(yield session.expose(api))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef list_available():\\n\\n    ''''List available features to install\\n    Returns:\\n    str: A list of available features as returned by the\\n    ``Get-WindowsFeature`` PowerShell command\\n    CLI Example:\\n    .. code-block:: bash\\n    salt \\\\'*\\\\' win_servermanager.list_available'\\n    '''\",\"targets\":\"cmd = 'Import-Module    ServerManager;    Get-WindowsFeature    -ErrorAction    SilentlyContinue    -WarningAction    SilentlyContinue'\\n    return __salt__['cmd.shell'](cmd, shell='powershell')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef make_instance_save(instance, fields, fail_message):\\n\\n    ''''Returns the save() method for a Form.'\\n    '''\",\"targets\":\"def save(self, commit=True):\\n        return save_instance(self, instance, fields, fail_message, commit)\\n    return save\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    (c, lower) = c_and_lower\\n    if check_finite:\\n        b1 = asarray_chkfinite(b)\\n        c = asarray_chkfinite(c)\\n    else:\\n        b1 = asarray(b)\\n        c = asarray(c)\\n    if ((c.ndim != 2) or (c.shape[0] != c.shape[1])):\\n        raise ValueError('The    factored    matrix    c    is    not    square.')\\n    if (c.shape[1] != b1.shape[0]):\\n        raise ValueError('incompatible    dimensions.')\\n    overwrite_b = (overwrite_b or _datacopied(b1, b))\\n    (potrs,) = get_lapack_funcs(('potrs',), (c, b1))\\n    (x, info) = potrs(c, b1, lower=lower, overwrite_b=overwrite_b)\\n    if (info != 0):\\n        raise ValueError(('illegal    value    in    %d-th    argument    of    internal    potrs' % (- info)))\\n    return x\\n\\n\\nWhat's a good function header?\",\"targets\":\"def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def custom_object_scope(*args):\",\"targets\":\"\\\"\\\"\\\"Provides a scope that changes to `_GLOBAL_CUSTOM_OBJECTS` cannot escape.\\n    Convenience wrapper for `CustomObjectScope`.\\n    Code within a `with` statement will be able to access custom objects\\n    by name. Changes to global custom objects persist\\n    within the enclosing `with` statement. At end of the `with` statement,\\n    global custom objects are reverted to state\\n    at beginning of the `with` statement.\\n    # Example\\n    Consider a custom object `MyObject`\\n    ```python\\n    with custom_object_scope({\\\\MyObject\\\\:MyObject}):\\n    layer = Dense(..., kernel_regularizer=\\\\MyObject\\\\)\\n    # save, load, etc. will recognize custom object by name\\n    # Arguments\\n    *args: Variable length list of dictionaries of name,\\n    class pairs to add to custom objects.\\n    # Returns\\n    Object of type `CustomObjectScope`.\\n    \\\"\\\"\\\"\\n    return CustomObjectScope(*args)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    grid = DiagramGrid(diagram, groups, **hints)\\n    drawer = XypicDiagramDrawer()\\n    return drawer.draw(diagram, grid, masked, diagram_format)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def xypic_draw_diagram(diagram, masked=None, diagram_format='', groups=None, **hints):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def NotUnicode(string):\",\"targets\":\"\\\"\\\"\\\"Make sure a string is NOT unicode.\\n    \\\"\\\"\\\"\\n    if isinstance(string, unicode):\\n        string = string.encode('utf-8')\\n    if (not isinstance(string, str)):\\n        return str(string)\\n    return string\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def MoveFiles(rebalance, is_master):\",\"targets\":\"\\\"\\\"\\\"Commit the received files into the database.\\n    \\\"\\\"\\\"\\n    loc = data_store.DB.Location()\\n    if (not os.path.exists(loc)):\\n        return False\\n    if (not os.path.isdir(loc)):\\n        return False\\n    tempdir = _CreateDirectory(loc, rebalance.id)\\n    remove_file = _FileWithRemoveList(loc, rebalance)\\n    to_remove = []\\n    if os.path.exists(remove_file):\\n        to_remove = [line.decode('utf8').rstrip('\\\\n') for line in open(remove_file, 'rb')]\\n    for fname in to_remove:\\n        if (not fname.startswith(loc)):\\n            logging.warning('Wrong    file    to    remove:    %s', fname)\\n            continue\\n        if (not os.path.exists(fname)):\\n            logging.warning('File    does    not    exist:    %s', fname)\\n            continue\\n        if (not os.path.isfile(fname)):\\n            logging.warning('Not    a    file:    %s', fname)\\n            continue\\n        os.unlink(fname)\\n        logging.info('Removing    file    %s', fname)\\n    try:\\n        os.unlink(remove_file)\\n    except OSError:\\n        pass\\n    try:\\n        _RecMoveFiles(tempdir, loc, '')\\n    except OSError:\\n        return False\\n    if (not is_master):\\n        if tempdir.startswith(loc):\\n            shutil.rmtree(tempdir)\\n    return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def cached_resource(url, base_dir, force=False, max_size=250, directory=u'cached_resources'):\",\"targets\":\"\\\"\\\"\\\"Caches a remote resource to local filesystem. Return a tuple of local file name and mime type, use primarily\\n    for API\\/WebUI.\\n    :param url: Resource URL\\n    :param force: Does not check for existence of cached resource, fetches the remote URL, ignores directory size limit\\n    :param max_size: Maximum allowed size of directory, in MB.\\n    :param directory: Name of directory to use. Default is `cached_resources`\\n    :return: Tuple of file path and mime type\\n    \\\"\\\"\\\"\\n    mime_type = None\\n    hashed_name = hashlib.md5(url.encode(u'utf-8')).hexdigest()\\n    file_path = os.path.join(base_dir, directory, hashed_name)\\n    directory = os.path.dirname(file_path)\\n    if ((not os.path.exists(file_path)) or force):\\n        log.debug(u'caching    %s', url)\\n        response = requests.get(url)\\n        response.raise_for_status()\\n        mime_type = response.headers.get(u'content-type')\\n        content = response.content\\n        if (not os.path.exists(directory)):\\n            os.makedirs(directory)\\n        size = (dir_size(directory) \\/ (1024 * 1024.0))\\n        if (not force):\\n            while (size >= max_size):\\n                log.debug(u'directory    %s    size    is    over    the    allowed    limit    of    %s,    trimming', size, max_size)\\n                trim_dir(directory)\\n                size = (dir_size(directory) \\/ (1024 * 1024.0))\\n        with io.open(file_path, u'wb') as file:\\n            file.write(content)\\n    return (file_path, mime_type)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    _col_name_map = col_name_map\\n    if (join_type not in (u'inner', u'exact', u'outer')):\\n        raise ValueError(u\\\"join_type    arg    must    be    either    'inner',    'exact'    or    'outer'\\\")\\n    if (table_names is None):\\n        table_names = [u'{0}'.format((ii + 1)) for ii in range(len(arrays))]\\n    if (len(arrays) != len(table_names)):\\n        raise ValueError(u'Number    of    arrays    must    match    number    of    table_names')\\n    if (len(arrays) == 1):\\n        return arrays[0]\\n    col_name_map = get_col_name_map(arrays, [], uniq_col_name, table_names)\\n    arr_lens = [len(arr) for arr in arrays]\\n    if (join_type == u'exact'):\\n        if (len(set(arr_lens)) > 1):\\n            raise TableMergeError(u\\\"Inconsistent    number    of    rows    in    input    arrays    (use    'inner'    or    'outer'    join_type    to    allow    non-matching    rows)\\\")\\n        join_type = u'outer'\\n    if (join_type == u'inner'):\\n        min_arr_len = min(arr_lens)\\n        if (len(set(arr_lens)) > 1):\\n            arrays = [arr[:min_arr_len] for arr in arrays]\\n        arr_lens = [min_arr_len for arr in arrays]\\n    masked = (any((getattr(arr, u'masked', False) for arr in arrays)) or (len(set(arr_lens)) > 1))\\n    n_rows = max(arr_lens)\\n    out = _get_out_class(arrays)(masked=masked)\\n    for (out_name, in_names) in six.iteritems(col_name_map):\\n        for (name, array, arr_len) in zip(in_names, arrays, arr_lens):\\n            if (name is None):\\n                continue\\n            if (n_rows > arr_len):\\n                indices = np.arange(n_rows)\\n                indices[arr_len:] = 0\\n                out[out_name] = array[name][indices]\\n                try:\\n                    out[out_name].mask[arr_len:] = True\\n                except ValueError:\\n                    raise NotImplementedError(u\\\"hstack    requires    masking    column    '{}'    but    column    type    {}    does    not    support    masking\\\".format(out_name, out[out_name].__class__.__name__))\\n            else:\\n                out[out_name] =...\\n\\nWhat's a good function header?\",\"targets\":\"def _hstack(arrays, join_type=u'outer', uniq_col_name=u'{col_name}_{table_name}', table_names=None, col_name_map=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    def wrap(self, name, value):\\n        paramcache = self.cache_choiceparams(name)\\n        old = self.get(name)\\n        f(self, name, value)\\n        if (not self.hasValidValue(name)):\\n            self._trch_set(name, old)\\n            raise exception.CmdErr, ('Invalid    value    for    %s    (%s)' % (name, value))\\n        for param in paramcache:\\n            if (param.name in util.iDict(self.cache_choiceparams(name))):\\n                try:\\n                    if (not self.getParameter(param.name).isHidden()):\\n                        self.set(*param)\\n                except (exception.CmdErr, AttributeError):\\n                    pass\\n    return wrap\\n\\n\\nWhat's a good function header?\",\"targets\":\"def safesetchoice(f):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef execute(func, args, msg=None, verbose=0, dry_run=0):\\n\\n    ''''Perform some action that affects the outside world (eg.  by\\n    writing to the filesystem).  Such actions are special because they\\n    are disabled by the \\\\'dry_run\\\\' flag.  This method takes care of all\\n    that bureaucracy for you; all you have to do is supply the\\n    function to call and an argument tuple for it (to embody the\\n    \\\"external action\\\" being performed), and an optional message to\\n    print.'\\n    '''\",\"targets\":\"if (msg is None):\\n        msg = ('%s%r' % (func.__name__, args))\\n        if (msg[(-2):] == ',)'):\\n            msg = (msg[0:(-2)] + ')')\\n    log.info(msg)\\n    if (not dry_run):\\n        func(*args)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def apply_received_command(event):\",\"targets\":\"\\\"\\\"\\\"Apply command from rfxtrx.\\n    \\\"\\\"\\\"\\n    device_id = slugify(event.device.id_string.lower())\\n    if (device_id not in RFX_DEVICES):\\n        return\\n    _LOGGER.debug('Device_id:    %s    device_update.    Command:    %s', device_id, event.values['Command'])\\n    if ((event.values['Command'] == 'On') or (event.values['Command'] == 'Off')):\\n        is_on = (event.values['Command'] == 'On')\\n        RFX_DEVICES[device_id].update_state(is_on)\\n    elif (hasattr(RFX_DEVICES[device_id], 'brightness') and (event.values['Command'] == 'Set    level')):\\n        _brightness = ((event.values['Dim    level'] * 255) \\/\\/ 100)\\n        is_on = (_brightness > 0)\\n        RFX_DEVICES[device_id].update_state(is_on, _brightness)\\n    if RFX_DEVICES[device_id].should_fire_event:\\n        RFX_DEVICES[device_id].hass.bus.fire(EVENT_BUTTON_PRESSED, {ATTR_ENTITY_ID: RFX_DEVICES[device_id].entity_id, ATTR_STATE: event.values['Command'].lower()})\\n        _LOGGER.info('Rfxtrx    fired    event:    (event_type:    %s,    %s:    %s,    %s:    %s)', EVENT_BUTTON_PRESSED, ATTR_ENTITY_ID, RFX_DEVICES[device_id].entity_id, ATTR_STATE, event.values['Command'].lower())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef locate_oc_binary():\\n\\n    ''''Find and return oc binary file'\\n    '''\",\"targets\":\"paths = (os.environ.get('PATH', os.defpath).split(os.pathsep) + ADDITIONAL_PATH_LOOKUPS)\\n    oc_binary = 'oc'\\n    try:\\n        which_result = shutil.which(oc_binary, path=os.pathsep.join(paths))\\n        if (which_result is not None):\\n            oc_binary = which_result\\n    except AttributeError:\\n        for path in paths:\\n            if os.path.exists(os.path.join(path, oc_binary)):\\n                oc_binary = os.path.join(path, oc_binary)\\n                break\\n    return oc_binary\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    lib = libraries.get(library_name, None)\\n    if (not lib):\\n        templatetags_modules = get_templatetags_modules()\\n        tried_modules = []\\n        for module in templatetags_modules:\\n            taglib_module = ('%s.%s' % (module, library_name))\\n            tried_modules.append(taglib_module)\\n            lib = import_library(taglib_module)\\n            if lib:\\n                libraries[library_name] = lib\\n                break\\n        if (not lib):\\n            raise InvalidTemplateLibrary(('Template    library    %s    not    found,    tried    %s' % (library_name, ','.join(tried_modules))))\\n    return lib\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_library(library_name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef is_target(t):\\n\\n    '''''\\n    '''\",\"targets\":\"if (t == None):\\n        return ''\\n    parts = t.split(':')\\n    try:\\n        ip = is_ip_addr(parts[0])\\n        if (len(parts) > 1):\\n            port = int(parts[1])\\n        return t\\n    except Exception as e:\\n        raise ArgumentTypeError(('%r    is    not    a    valid    target!' % t))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_version(package):\",\"targets\":\"\\\"\\\"\\\"Return package version as listed in `__version__` in `init.py`.\\n    \\\"\\\"\\\"\\n    init_py = open(os.path.join(package, '__init__.py')).read()\\n    return re.search('__version__    =    [\\\\'\\\"]([^\\\\'\\\"]+)[\\\\'\\\"]', init_py).group(1)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    for body in (content_ratings or {}):\\n        content_ratings[body] = dehydrate_content_rating(content_ratings[body])\\n    return content_ratings\\n\\n\\nWhat's a good function header?\",\"targets\":\"def dehydrate_content_ratings(content_ratings):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@app.route(('%s\\/functions\\/' % PATH_ROOT), methods=['DELETE'])\\ndef delete_function(function):\",\"targets\":\"\\\"\\\"\\\"Delete an existing function\\n    operationId: \\\\deleteFunction\\\\\\n    parameters:\\n    - name: \\\\request\\\\\\n    in: body\\n    \\\"\\\"\\\"\\n    arn = func_arn(function)\\n    try:\\n        lambda_arn_to_handler.pop(arn)\\n    except KeyError:\\n        return error_response(('Function    does    not    exist:    %s' % function), 404, error_type='ResourceNotFoundException')\\n    event_publisher.fire_event(event_publisher.EVENT_LAMBDA_DELETE_FUNC, payload={'n': event_publisher.get_hash(function)})\\n    lambda_arn_to_cwd.pop(arn, None)\\n    lambda_arn_to_function.pop(arn, None)\\n    i = 0\\n    while (i < len(event_source_mappings)):\\n        mapping = event_source_mappings[i]\\n        if (mapping['FunctionArn'] == arn):\\n            del event_source_mappings[i]\\n            i -= 1\\n        i += 1\\n    result = {}\\n    return jsonify(result)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    from simplipy.api import SimpliSafeApiInterface, get_systems\\n    name = config.get(CONF_NAME)\\n    code = config.get(CONF_CODE)\\n    username = config.get(CONF_USERNAME)\\n    password = config.get(CONF_PASSWORD)\\n    simplisafe = SimpliSafeApiInterface()\\n    status = simplisafe.set_credentials(username, password)\\n    if status:\\n        hass.data[DOMAIN] = simplisafe\\n        locations = get_systems(simplisafe)\\n        for location in locations:\\n            add_devices([SimpliSafeAlarm(location, name, code)])\\n    else:\\n        message = 'Failed    to    log    into    SimpliSafe.    Check    credentials.'\\n        _LOGGER.error(message)\\n        hass.components.persistent_notification.create(message, title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID)\\n        return False\\n    def logout(event):\\n        'Logout    of    the    SimpliSafe    API.'\\n        hass.data[DOMAIN].logout()\\n    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, logout)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def setup_platform(hass, config, add_devices, discovery_info=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef activities_from_everything_followed_by_user(user_id, limit, offset):\\n\\n    ''''Return activities from everything that the given user is following.\\n    Returns all activities where the object of the activity is anything\\n    (user, dataset, group...) that the given user is following.'\\n    '''\",\"targets\":\"q = _activities_from_everything_followed_by_user_query(user_id, (limit + offset))\\n    return _activities_at_offset(q, limit, offset)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def __virtual__():\",\"targets\":\"\\\"\\\"\\\"Set the virtual pkg module if the os is supported by pkgin\\n    \\\"\\\"\\\"\\n    supported = ['NetBSD', 'SunOS', 'DragonFly', 'Minix', 'Darwin', 'SmartOS']\\n    if ((__grains__['os'] in supported) and _check_pkgin()):\\n        return __virtualname__\\n    return (False, 'The    pkgin    execution    module    cannot    be    loaded:    only    available    on    {0}    systems.'.format(',    '.join(supported)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (config is None):\\n        config = BareConfig(read_configfile=True, quietness=1)\\n    return LaymanAPI(config)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def init_layman(config=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (not isinstance(name, (list, tuple))):\\n        name = [name]\\n    if isinstance(info, Info):\\n        picks = pick_types(info, meg=True, exclude=())\\n        if ((len(picks) > 0) and ('    ' not in info['ch_names'][picks[0]])):\\n            spacing = 'new'\\n        else:\\n            spacing = 'old'\\n    elif (info is not None):\\n        raise TypeError(('info    must    be    an    instance    of    Info    or    None,    not    %s' % (type(info),)))\\n    else:\\n        spacing = 'old'\\n    if (fname is None):\\n        fname = path.join(path.dirname(__file__), 'data', 'mne_analyze.sel')\\n    if (not path.isfile(fname)):\\n        raise ValueError(('The    file    %s    does    not    exist.' % fname))\\n    name_found = dict(((n, False) for n in name))\\n    with open(fname, 'r') as fid:\\n        sel = []\\n        for line in fid:\\n            line = line.strip()\\n            if ((len(line) == 0) or (line[0] == '#')):\\n                continue\\n            pos = line.find(':')\\n            if (pos < 0):\\n                logger.info('\\\":\\\"    delimiter    not    found    in    selections    file,    skipping    line')\\n                continue\\n            sel_name_file = line[:pos]\\n            for n in name:\\n                if (sel_name_file.find(n) >= 0):\\n                    sel.extend(line[(pos + 1):].split('|'))\\n                    name_found[n] = True\\n                    break\\n    for (n, found) in name_found.items():\\n        if (not found):\\n            raise ValueError(('No    match    for    selection    name    \\\"%s\\\"    found' % n))\\n    sel = list(set(sel))\\n    sel.sort()\\n    if (spacing == 'new'):\\n        sel = [s.replace('MEG    ', 'MEG') for s in sel]\\n    return sel\\n\\n\\nWhat's a good function header?\",\"targets\":\"@verbose\\ndef read_selection(name, fname=None, info=None, verbose=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@core_helper\\ndef get_featured_groups(count=1):\",\"targets\":\"\\\"\\\"\\\"Returns a list of favourite group the form\\n    of organization_list action function\\n    \\\"\\\"\\\"\\n    config_groups = config.get('ckan.featured_groups', '').split()\\n    groups = featured_group_org(get_action='group_show', list_action='group_list', count=count, items=config_groups)\\n    return groups\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    (name, value) = header\\n    if isinstance(value, bytes):\\n        pat = _CLEAN_HEADER_REGEX_BYTE\\n    else:\\n        pat = _CLEAN_HEADER_REGEX_STR\\n    try:\\n        if (not pat.match(value)):\\n            raise InvalidHeader(('Invalid    return    character    or    leading    space    in    header:    %s' % name))\\n    except TypeError:\\n        raise InvalidHeader(('Header    value    %s    must    be    of    type    str    or    bytes,    not    %s' % (value, type(value))))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_header_validity(header):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef make_or_pipe(pipe):\\n\\n    ''''wraps a pipe into two pipe-like objects which are \\\"or\\\"d together to\\n    affect the real pipe. if either returned pipe is set, the wrapped pipe\\n    is set. when both are cleared, the wrapped pipe is cleared.'\\n    '''\",\"targets\":\"p1 = OrPipe(pipe)\\n    p2 = OrPipe(pipe)\\n    p1._partner = p2\\n    p2._partner = p1\\n    return (p1, p2)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    it = itertools.groupby(query_result, operator.itemgetter(0))\\n    forums = []\\n    if user.is_authenticated:\\n        for (key, value) in it:\\n            forums.append((key, [(item[1], item[2]) for item in value]))\\n    else:\\n        for (key, value) in it:\\n            forums.append((key, [(item[1], None) for item in value]))\\n    return forums\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_categories_and_forums(query_result, user):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _find_spec_from_path(name, path=None):\\n\\n    ''''Return the spec for the specified module.\\n    First, sys.modules is checked to see if the module was already imported. If\\n    so, then sys.modules[name].__spec__ is returned. If that happens to be\\n    set to None, then ValueError is raised. If the module is not in\\n    sys.modules, then sys.meta_path is searched for a suitable spec with the\\n    value of \\\\'path\\\\' given to the finders. None is returned if no spec could\\n    be found.\\n    Dotted names do not have their parent packages implicitly imported. You will\\n    most likely need to explicitly import all parent packages in the proper\\n    order for a submodule to get the correct spec.'\\n    '''\",\"targets\":\"if (name not in sys.modules):\\n        return _find_spec(name, path)\\n    else:\\n        module = sys.modules[name]\\n        if (module is None):\\n            return None\\n        try:\\n            spec = module.__spec__\\n        except AttributeError:\\n            raise ValueError('{}.__spec__    is    not    set'.format(name))\\n        else:\\n            if (spec is None):\\n                raise ValueError('{}.__spec__    is    None'.format(name))\\n            return spec\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def KeyLEQ(key1, key2):\",\"targets\":\"\\\"\\\"\\\"Compare two keys for less-than-or-equal-to.\\n    All keys with numeric ids come before all keys with names. None represents\\n    an unbounded end-point so it is both greater and less than any other key.\\n    Args:\\n    key1: An int or datastore.Key instance.\\n    key2: An int or datastore.Key instance.\\n    Returns:\\n    True if key1 <= key2\\n    \\\"\\\"\\\"\\n    if ((key1 is None) or (key2 is None)):\\n        return True\\n    return (key1 <= key2)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_writer_class(writer_name):\\n\\n    ''''Return the Writer class from the `writer_name` module.'\\n    '''\",\"targets\":\"writer_name = writer_name.lower()\\n    if (writer_name in _writer_aliases):\\n        writer_name = _writer_aliases[writer_name]\\n    try:\\n        module = __import__(writer_name, globals(), locals(), level=1)\\n    except ImportError:\\n        module = __import__(writer_name, globals(), locals(), level=0)\\n    return module.Writer\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    core = CORE_MANAGER.get_core_service()\\n    peer = core.peer_manager.get_by_addr(neigh_ip_address)\\n    at_maps_key = const.ATTR_MAPS_LABEL_DEFAULT\\n    at_maps_dict = {}\\n    if (route_dist is not None):\\n        vrf_conf = CORE_MANAGER.vrfs_conf.get_vrf_conf(route_dist, route_family)\\n        if vrf_conf:\\n            at_maps_key = ':'.join([route_dist, route_family])\\n        else:\\n            raise RuntimeConfigError(desc=('No    VrfConf    with    rd    %s' % route_dist))\\n    at_maps_dict[const.ATTR_MAPS_LABEL_KEY] = at_maps_key\\n    at_maps_dict[const.ATTR_MAPS_VALUE] = at_maps\\n    peer.attribute_maps = at_maps_dict\\n    return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"@RegisterWithArgChecks(name='neighbor.attribute_map.set', req_args=[neighbors.IP_ADDRESS, neighbors.ATTRIBUTE_MAP], opt_args=[ROUTE_DISTINGUISHER, VRF_RF])\\ndef set_neighbor_attribute_map(neigh_ip_address, at_maps, route_dist=None, route_family=VRF_RF_IPV4):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@contextmanager\\ndef webserver(app, port=0, host=None):\\n\\n    ''''Context manager entry point for the \\\\'with\\\\' statement.\\n    Pass 0 as port number to dynamically allocate a free port.\\n    Usage:\\n    with webserver(wsgi_app_function, 8080) as host_url:\\n    do_ws_calls(host_url)'\\n    '''\",\"targets\":\"server = build_web_server(app, port, (host or '127.0.0.1'))\\n    (host, port) = server.socket.getsockname()\\n    import threading\\n    thread = threading.Thread(target=server.serve_forever, kwargs={'poll_interval': 0.5})\\n    thread.setDaemon(True)\\n    thread.start()\\n    try:\\n        (yield ('http:\\/\\/%s:%s\\/' % (host, port)))\\n    finally:\\n        server.shutdown()\\n        server.server_close()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def getCraftedText(fileName, text, jitterRepository=None):\",\"targets\":\"\\\"\\\"\\\"Jitter a gcode linear move text.\\n    \\\"\\\"\\\"\\n    return getCraftedTextFromText(archive.getTextIfEmpty(fileName, text), jitterRepository)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    force_param = ''\\n    if force:\\n        force_param = '-force'\\n    return _hadoop_cmd('namenode', 'format', '-nonInteractive', force_param)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def namenode_format(force=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (window_size is None):\\n        window_size = DEFAULT_PACK_DELTA_WINDOW_SIZE\\n    magic = []\\n    for (obj, path) in objects:\\n        magic.append((obj.type_num, path, (- obj.raw_length()), obj))\\n    magic.sort()\\n    possible_bases = deque()\\n    for (type_num, path, neg_length, o) in magic:\\n        raw = o.as_raw_string()\\n        winner = raw\\n        winner_base = None\\n        for base in possible_bases:\\n            if (base.type_num != type_num):\\n                continue\\n            delta = create_delta(base.as_raw_string(), raw)\\n            if (len(delta) < len(winner)):\\n                winner_base = base.sha().digest()\\n                winner = delta\\n        (yield (type_num, o.sha().digest(), winner_base, winner))\\n        possible_bases.appendleft(o)\\n        while (len(possible_bases) > window_size):\\n            possible_bases.pop()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def deltify_pack_objects(objects, window_size=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_issue(issue_number, repo_name=None, profile='github', output='min'):\",\"targets\":\"\\\"\\\"\\\"Return information about a single issue in a named repository.\\n    .. versionadded:: 2016.11.0\\n    issue_number\\n    The number of the issue to retrieve.\\n    repo_name\\n    The name of the repository from which to get the issue. This argument is\\n    required, either passed via the CLI, or defined in the configured\\n    profile. A ``repo_name`` passed as a CLI argument will override the\\n    repo_name defined in the configured profile, if provided.\\n    profile\\n    The name of the profile configuration to use. Defaults to ``github``.\\n    output\\n    The amount of data returned by each issue. Defaults to ``min``. Change\\n    to ``full`` to see all issue output.\\n    CLI Example:\\n    .. code-block:: bash\\n    salt myminion github.get_issue 514\\n    salt myminion github.get_issue 514 repo_name=salt\\n    \\\"\\\"\\\"\\n    org_name = _get_config_value(profile, 'org_name')\\n    if (repo_name is None):\\n        repo_name = _get_config_value(profile, 'repo_name')\\n    action = '\\/'.join(['repos', org_name, repo_name])\\n    command = ('issues\\/' + str(issue_number))\\n    ret = {}\\n    issue_data = _query(profile, action=action, command=command)\\n    issue_id = issue_data.get('id')\\n    if (output == 'full'):\\n        ret[issue_id] = issue_data\\n    else:\\n        ret[issue_id] = _format_issue(issue_data)\\n    return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def find_failing_tests(result_images, source):\",\"targets\":\"\\\"\\\"\\\"Find all of the failing tests by looking for files with\\n    `-failed-diff` at the end of the basename.\\n    \\\"\\\"\\\"\\n    entries = []\\n    for (root, dirs, files) in os.walk(result_images):\\n        for fname in files:\\n            (basename, ext) = os.path.splitext(fname)\\n            if basename.endswith(u'-failed-diff'):\\n                path = os.path.join(root, fname)\\n                entry = Entry(path, result_images, source)\\n                entries.append(entry)\\n    entries.sort(key=(lambda x: x.name))\\n    return entries\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _exception_traceback(exc_info):\",\"targets\":\"\\\"\\\"\\\"Return a string containing a traceback message for the given\\n    exc_info tuple (as returned by sys.exc_info()).\\n    \\\"\\\"\\\"\\n    excout = StringIO()\\n    (exc_type, exc_val, exc_tb) = exc_info\\n    traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)\\n    return excout.getvalue()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def create_tree(base_dir, files, mode=511, verbose=1, dry_run=0):\",\"targets\":\"\\\"\\\"\\\"Create all the empty directories under \\\\base_dir\\\\ needed to put \\\\files\\\\\\n    there.\\n    \\\\base_dir\\\\ is just the name of a directory which doesn\\\\t necessarily\\n    exist yet; \\\\files\\\\ is a list of filenames to be interpreted relative to\\n    \\\\base_dir\\\\.  \\\\base_dir\\\\ + the directory portion of every file in \\\\files\\\\\\n    will be created if it doesn\\\\t already exist.  \\\\mode\\\\, \\\\verbose\\\\ and\\n    \\\\dry_run\\\\ flags are as for \\\\mkpath()\\\\.\\n    \\\"\\\"\\\"\\n    need_dir = {}\\n    for file in files:\\n        need_dir[os.path.join(base_dir, os.path.dirname(file))] = 1\\n    need_dirs = need_dir.keys()\\n    need_dirs.sort()\\n    for dir in need_dirs:\\n        mkpath(dir, mode, verbose=verbose, dry_run=dry_run)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def bind_row_anchor_column(column_name):\",\"targets\":\"\\\"\\\"\\\"A decorator to bind table region method to a anchor in a column.\\n    Typical examples of such tables are Project -> Compute -> Images, Admin\\n    -> System -> Flavors, Project -> Compute -> Instancies.\\n    The method can be used to follow the link in the anchor by the click.\\n    \\\"\\\"\\\"\\n    def decorator(method):\\n        @functools.wraps(method)\\n        def wrapper(table, row):\\n            cell = row.cells[column_name]\\n            action_element = cell.find_element(by.By.CSS_SELECTOR, ('td.%s    >    a' % NORMAL_COLUMN_CLASS))\\n            return method(table, action_element, row)\\n        return wrapper\\n    return decorator\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef add_instance_fault_from_exc(context, instance, fault, exc_info=None, fault_message=None):\\n\\n    ''''Adds the specified fault to the database.'\\n    '''\",\"targets\":\"fault_obj = objects.InstanceFault(context=context)\\n    fault_obj.host = CONF.host\\n    fault_obj.instance_uuid = instance.uuid\\n    fault_obj.update(exception_to_dict(fault, message=fault_message))\\n    code = fault_obj.code\\n    fault_obj.details = _get_fault_details(exc_info, code)\\n    fault_obj.create()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _configure_base(module, base, conf_file, disable_gpg_check):\",\"targets\":\"\\\"\\\"\\\"Configure the dnf Base object.\\n    \\\"\\\"\\\"\\n    conf = base.conf\\n    conf.debuglevel = 0\\n    conf.gpgcheck = (not disable_gpg_check)\\n    conf.assumeyes = True\\n    if conf_file:\\n        if (not os.access(conf_file, os.R_OK)):\\n            module.fail_json(msg='cannot    read    configuration    file', conf_file=conf_file)\\n        else:\\n            conf.config_file_path = conf_file\\n    conf.read()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef cummingsify(poem):\\n\\n    ''''Randomly do one of the following:\\n    1. Return a cummingsified version of the poem.\\n    2. Raise a GibberishError.\\n    3. Raise a ValueError.'\\n    '''\",\"targets\":\"def success():\\n        return poem.lower()\\n    def gibberish():\\n        raise GibberishError()\\n    def bug():\\n        raise ValueError()\\n    return random.choice([success, gibberish, bug])()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def main(unused_argv):\",\"targets\":\"\\\"\\\"\\\"Main.\\n    \\\"\\\"\\\"\\n    server_startup.Init()\\n    filename = flags.FLAGS.filename\\n    if (not os.path.exists(filename)):\\n        print ('File    %s    does    not    exist' % filename)\\n        return\\n    with aff4.FACTORY.Create(filestore.NSRLFileStore.PATH, filestore.NSRLFileStore, mode='rw', token=aff4.FACTORY.root_token) as store:\\n        imported = ImportFile(store, filename, flags.FLAGS.start)\\n        data_store.DB.Flush()\\n        print ('Imported    %d    hashes' % imported)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def do_not_report_as_logging_caller(func):\",\"targets\":\"\\\"\\\"\\\"Decorator to annotate functions we will tell logging not to log.\\n    \\\"\\\"\\\"\\n    _caller_code_to_skip_in_logging_stack.add(func.func_code)\\n    return func\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    checkout_path = _create_test_package(script)\\n    repo_url = _create_svn_repo(script, checkout_path)\\n    result = script.pip('install', '-e', (('svn+' + repo_url) + '#egg=version-pkg'))\\n    result.assert_installed('version-pkg', with_files=['.svn'])\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.mark.svn\\ndef test_install_editable_from_svn(script):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def examplesfullTest(vm, prompt=Prompt):\",\"targets\":\"\\\"\\\"\\\"Full (slow) test of mininet examples\\n    \\\"\\\"\\\"\\n    installPexpect(vm, prompt)\\n    vm.sendline('sudo    -n    python    ~\\/mininet\\/examples\\/test\\/runner.py    -v')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef capitalize(s):\\n\\n    ''''capitalize(s) -> string\\n    Return a copy of the string s with only its first character\\n    capitalized.'\\n    '''\",\"targets\":\"return s.capitalize()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    log.js.debug('confirm:    {}'.format(js_msg))\\n    if config.get('ui', 'modal-js-dialog'):\\n        raise CallSuper\\n    msg = 'From    {}<\\/b>:{}'.format(html.escape(url.toDisplayString()), html.escape(js_msg))\\n    ans = message.ask('Javascript    confirm', msg, mode=usertypes.PromptMode.yesno, abort_on=abort_on)\\n    return bool(ans)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def javascript_confirm(url, js_msg, abort_on):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def getFirstAncestorWithSectionHeader(entry):\",\"targets\":\"\\\"\\\"\\\"Visit the ancestors of C{entry} until one with at least one C{h2} child\\n    node is found, then return all of that node\\\\s C{h2} child nodes.\\n    @type entry: A DOM Node\\n    @param entry: The node from which to begin traversal.  This node itself is\\n    excluded from consideration.\\n    @rtype: C{list} of DOM Nodes\\n    @return: All C{h2} nodes of the ultimately selected parent node.\\n    \\\"\\\"\\\"\\n    for a in domhelpers.getParents(entry)[1:]:\\n        headers = domhelpers.findNodesNamed(a, 'h2')\\n        if (len(headers) > 0):\\n            return headers\\n    return []\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (release not in {'2', '3'}):\\n        raise ValueError((\\\"release    must    be    one    of    '2',    '3',    not    %s\\\" % release))\\n    venv = '\\/home\\/vagrant\\/repos\\/test-{release}-virtualenv'.format(release=release)\\n    tarball_formatter_dict = tarball_formatter()\\n    with use_venv(release):\\n        make_virtualenv(venv)\\n        with virtualenv(venv):\\n            run('cp    \\/vagrant\\/release\\/{source}    releasetar.tar'.format(**tarball_formatter_dict))\\n            run('tar    xvf    releasetar.tar')\\n            with cd('\\/home\\/vagrant\\/{source-orig-notar}'.format(**tarball_formatter_dict)):\\n                run('python    setup.py    install')\\n                run('python    -c    \\\"import    sympy;    print(sympy.__version__)\\\"')\\n\\n\\nWhat's a good function header?\",\"targets\":\"@task\\ndef test_tarball(release='2'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef create_default_plugins(request, placeholders, template, lang):\\n\\n    ''''Create all default plugins for the given ``placeholders`` if they have\\n    a \\\"default_plugins\\\" configuration value in settings.\\n    return all plugins, children, grandchildren (etc.) created'\\n    '''\",\"targets\":\"from cms.api import add_plugin\\n    def _create_default_plugins(placeholder, confs, parent=None):\\n        \\\"\\\\n                                Auxillary    function    that    builds    all    of    a    placeholder's    default    plugins\\\\n                                at    the    current    level    and    drives    the    recursion    down    the    tree.\\\\n                                Returns    the    plugins    at    the    current    level    along    with    all    descendants.\\\\n                                \\\"\\n        (plugins, descendants) = ([], [])\\n        addable_confs = (conf for conf in confs if has_plugin_permission(request.user, conf['plugin_type'], 'add'))\\n        for conf in addable_confs:\\n            plugin = add_plugin(placeholder, conf['plugin_type'], lang, target=parent, **conf['values'])\\n            if ('children' in conf):\\n                args = (placeholder, conf['children'], plugin)\\n                descendants += _create_default_plugins(*args)\\n            plugin.notify_on_autoadd(request, conf)\\n            plugins.append(plugin)\\n        if parent:\\n            parent.notify_on_autoadd_children(request, conf, plugins)\\n        return (plugins + descendants)\\n    unfiltered_confs = ((ph, get_placeholder_conf('default_plugins', ph.slot, template)) for ph in placeholders)\\n    mutable_confs = ((ph, default_plugin_confs) for (ph, default_plugin_confs) in filter(itemgetter(1), unfiltered_confs) if ph.has_change_permission(request.user))\\n    return sum(starmap(_create_default_plugins, mutable_confs), [])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef customize_compiler_for_nvcc(self):\\n\\n    ''''inject deep into distutils to customize how the dispatch\\n    to gcc\\/nvcc works.\\n    If you subclass UnixCCompiler, it\\\\'s not trivial to get your subclass\\n    injected in, and still have the right customizations (i.e.\\n    distutils.sysconfig.customize_compiler) run on it. So instead of going\\n    the OO route, I have this. Note, it\\\\'s kindof like a wierd functional\\n    subclassing going on.'\\n    '''\",\"targets\":\"self.src_extensions.append('.cu')\\n    default_compiler_so = self.compiler_so\\n    super = self._compile\\n    def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):\\n        if (os.path.splitext(src)[1] == '.cu'):\\n            self.set_executable('compiler_so', CUDA['nvcc'])\\n            postargs = extra_postargs['nvcc']\\n        else:\\n            postargs = extra_postargs['gcc']\\n        super(obj, src, ext, cc_args, postargs, pp_opts)\\n        self.compiler_so = default_compiler_so\\n    self._compile = _compile\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    len_trf = (smax - smin)\\n    (len_x, n_ch_x) = X.shape\\n    (len_y, n_ch_y) = y.shape\\n    assert (len_x == len_y)\\n    n_fft = next_fast_len((((X.shape[0] + max(smax, 0)) - min(smin, 0)) - 1))\\n    X_fft = np.fft.rfft(X.T, n_fft)\\n    y_fft = np.fft.rfft(y.T, n_fft)\\n    ac = np.zeros((n_ch_x, n_ch_x, ((len_trf * 2) - 1)))\\n    for ch0 in range(n_ch_x):\\n        for ch1 in range(ch0, n_ch_x):\\n            ac_temp = np.fft.irfft((X_fft[ch0] * X_fft[ch1].conj()), n_fft)\\n            ac[(ch0, ch1)] = np.concatenate((ac_temp[((- len_trf) + 1):], ac_temp[:len_trf]))\\n            if (ch0 != ch1):\\n                ac[(ch1, ch0)] = ac[(ch0, ch1)][::(-1)]\\n    x_y = np.zeros((n_ch_y, n_ch_x, len_trf))\\n    for ch_in in range(n_ch_x):\\n        for ch_out in range(n_ch_y):\\n            cc_temp = np.fft.irfft((y_fft[ch_out] * X_fft[ch_in].conj()), n_fft)\\n            if ((smin < 0) and (smax >= 0)):\\n                x_y[(ch_out, ch_in)] = np.append(cc_temp[smin:], cc_temp[:smax])\\n            else:\\n                x_y[(ch_out, ch_in)] = cc_temp[smin:smax]\\n    x_xt = _make_x_xt(ac)\\n    x_y.shape = (n_ch_y, (n_ch_x * len_trf))\\n    return (x_xt, x_y, n_ch_x)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _compute_corrs(X, y, smin, smax):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _check_copy_from_header(req):\\n\\n    ''''Validate that the value from x-copy-from header is\\n    well formatted. We assume the caller ensures that\\n    x-copy-from header is present in req.headers.\\n    :param req: HTTP request object\\n    :returns: A tuple with container name and object name\\n    :raise HTTPPreconditionFailed: if x-copy-from value\\n    is not well formatted.'\\n    '''\",\"targets\":\"return _check_path_header(req, 'X-Copy-From', 2, 'X-Copy-From    header    must    be    of    the    form    \\/')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def create_apppool(name):\",\"targets\":\"\\\"\\\"\\\"Create an IIS application pool.\\n    .. note:\\n    This function only validates against the application pool name, and will return\\n    True even if the application pool already exists with a different configuration.\\n    It will not modify the configuration of an existing application pool.\\n    :param str name: The name of the IIS application pool.\\n    Usage:\\n    .. code-block:: yaml\\n    site0-apppool:\\n    win_iis.create_apppool:\\n    - name: site0\\n    \\\"\\\"\\\"\\n    ret = {'name': name, 'changes': {}, 'result': None, 'comment': ''}\\n    current_apppools = __salt__['win_iis.list_apppools']()\\n    if (name in current_apppools):\\n        ret['comment'] = 'Application    pool    already    present:    {0}'.format(name)\\n        ret['result'] = True\\n    elif __opts__['test']:\\n        ret['comment'] = 'Application    pool    will    be    created:    {0}'.format(name)\\n        ret['changes'] = {'old': None, 'new': name}\\n    else:\\n        ret['comment'] = 'Created    application    pool:    {0}'.format(name)\\n        ret['changes'] = {'old': None, 'new': name}\\n        ret['result'] = __salt__['win_iis.create_apppool'](name)\\n    return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _stdin_ready_other():\\n\\n    ''''Return True, assuming there\\\\'s something to read on stdin.'\\n    '''\",\"targets\":\"return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_updates_and_outputs(ls):\",\"targets\":\"\\\"\\\"\\\"This function tries to recognize the updates OrderedDict, the\\n    list of outputs and the stopping condition returned by the\\n    lambda expression and arrange them in a predefined order.\\n    WRITEME: what is the type of ls? how is it formatted?\\n    if it\\\\s not in the predefined order already, how does\\n    this function know how to put it in that order?\\n    \\\"\\\"\\\"\\n    def is_outputs(elem):\\n        if (isinstance(elem, (list, tuple)) and all([isinstance(x, theano.Variable) for x in elem])):\\n            return True\\n        if isinstance(elem, theano.Variable):\\n            return True\\n        return False\\n    def is_updates(elem):\\n        if isinstance(elem, dict):\\n            if ((not isinstance(elem, compat.OrderedDict)) and (len(elem) > 1)):\\n                warnings.warn((('Expected    OrderedDict    or    OrderedUpdates,    got    ' + str(type(elem))) + '.    This    can    make    your    script    non-deterministic.'))\\n            return True\\n        if (isinstance(elem, (list, tuple)) and all([(isinstance(x, (list, tuple)) and (len(x) == 2)) for x in elem])):\\n            return True\\n        return False\\n    def is_condition(elem):\\n        return isinstance(elem, theano.scan_module.until)\\n    def _list(x):\\n        if isinstance(x, (list, tuple)):\\n            return list(x)\\n        else:\\n            return [x]\\n    def _filter(x):\\n        '\\\\n                                Ensure    `x`    is    made    only    of    allowed    data    types.\\\\n\\\\n                                Return    True    iff    `x`    is    made    only    of    lists,    tuples,    dictionaries,    Theano\\\\n                                variables    or    `theano.scan_module.until`    objects.\\\\n\\\\n                                '\\n        iter_on = None\\n        if (isinstance(x, list) or isinstance(x, tuple)):\\n            iter_on = x\\n        elif isinstance(x, dict):\\n            iter_on = iteritems(x)\\n        if (iter_on is not None):\\n            return all((_filter(y) for y in iter_on))\\n        else:\\n            return (isinstance(x, theano.Variable) or isinstance(x, theano.scan_module.until))\\n    if (not _filter(ls)):\\n        raise ValueError('The    return    value    of    your    scan    lambda    expression    may    only    be    made    of    lists,    tuples,    or    dictionaries    containing    Theano    variables    (or    `theano.scan_module.until`    objects    for   ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def decode(encoding=None, default_encoding='utf-8'):\",\"targets\":\"\\\"\\\"\\\"Replace or extend the list of charsets used to decode a request entity.\\n    Either argument may be a single string or a list of strings.\\n    encoding\\n    If not None, restricts the set of charsets attempted while decoding\\n    a request entity to the given set (even if a different charset is\\n    given in the Content-Type request header).\\n    default_encoding\\n    Only in effect if the \\\\encoding\\\\ argument is not given.\\n    If given, the set of charsets attempted while decoding a request\\n    entity is *extended* with the given value(s).\\n    \\\"\\\"\\\"\\n    body = cherrypy.request.body\\n    if (encoding is not None):\\n        if (not isinstance(encoding, list)):\\n            encoding = [encoding]\\n        body.attempt_charsets = encoding\\n    elif default_encoding:\\n        if (not isinstance(default_encoding, list)):\\n            default_encoding = [default_encoding]\\n        body.attempt_charsets = (body.attempt_charsets + default_encoding)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    found = set()\\n    setters = False\\n    errors = 0\\n    with open('setup.py', 'r') as f:\\n        for line in f.readlines():\\n            if ('import    versioneer' in line):\\n                found.add('import')\\n            if ('versioneer.get_cmdclass()' in line):\\n                found.add('cmdclass')\\n            if ('versioneer.get_version()' in line):\\n                found.add('get_version')\\n            if ('versioneer.VCS' in line):\\n                setters = True\\n            if ('versioneer.versionfile_source' in line):\\n                setters = True\\n    if (len(found) != 3):\\n        print('')\\n        print('Your    setup.py    appears    to    be    missing    some    important    items')\\n        print('(but    I    might    be    wrong).    Please    make    sure    it    has    something')\\n        print('roughly    like    the    following:')\\n        print('')\\n        print('    import    versioneer')\\n        print('    setup(    version=versioneer.get_version(),')\\n        print('                                cmdclass=versioneer.get_cmdclass(),        ...)')\\n        print('')\\n        errors += 1\\n    if setters:\\n        print(\\\"You    should    remove    lines    like    'versioneer.VCS    =    '    and\\\")\\n        print(\\\"'versioneer.versionfile_source    =    '    .    This    configuration\\\")\\n        print('now    lives    in    setup.cfg,    and    should    be    removed    from    setup.py')\\n        print('')\\n        errors += 1\\n    return errors\\n\\n\\nWhat's a good function header?\",\"targets\":\"def scan_setup_py():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef hough_circle(image, radius, normalize=True, full_output=False):\\n\\n    ''''Perform a circular Hough transform.\\n    Parameters\\n    image : (M, N) ndarray\\n    Input image with nonzero values representing edges.\\n    radius : scalar or sequence of scalars\\n    Radii at which to compute the Hough transform.\\n    Floats are converted to integers.\\n    normalize : boolean, optional (default True)\\n    Normalize the accumulator with the number\\n    of pixels used to draw the radius.\\n    full_output : boolean, optional (default False)\\n    Extend the output size by twice the largest\\n    radius in order to detect centers outside the\\n    input picture.\\n    Returns\\n    H : 3D ndarray (radius index, (M + 2R, N + 2R) ndarray)\\n    Hough transform accumulator for each radius.\\n    R designates the larger radius if full_output is True.\\n    Otherwise, R = 0.\\n    Examples\\n    >>> from skimage.transform import hough_circle\\n    >>> from skimage.draw import circle_perimeter\\n    >>> img = np.zeros((100, 100), dtype=np.bool_)\\n    >>> rr, cc = circle_perimeter(25, 35, 23)\\n    >>> img[rr, cc] = 1\\n    >>> try_radii = np.arange(5, 50)\\n    >>> res = hough_circle(img, try_radii)\\n    >>> ridx, r, c = np.unravel_index(np.argmax(res), res.shape)\\n    >>> r, c, try_radii[ridx]\\n    (25, 35, 23)'\\n    '''\",\"targets\":\"radius = np.atleast_1d(np.asarray(radius))\\n    return _hough_circle(image, radius.astype(np.intp), normalize=normalize, full_output=full_output)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef dottedQuadToNum(ip):\\n\\n    ''''Convert decimal dotted quad string to long integer\\n    >>> int(dottedQuadToNum(\\\\'1 \\\\'))\\n    1\\n    >>> int(dottedQuadToNum(\\\\' 1.2\\\\'))\\n    16777218\\n    >>> int(dottedQuadToNum(\\\\' 1.2.3 \\\\'))\\n    16908291\\n    >>> int(dottedQuadToNum(\\\\'1.2.3.4\\\\'))\\n    16909060\\n    >>> dottedQuadToNum(\\\\'255.255.255.255\\\\')\\n    4294967295\\n    >>> dottedQuadToNum(\\\\'255.255.255.256\\\\')\\n    Traceback (most recent call last):\\n    ValueError: Not a good dotted-quad IP: 255.255.255.256'\\n    '''\",\"targets\":\"import socket, struct\\n    try:\\n        return struct.unpack('!L', socket.inet_aton(ip.strip()))[0]\\n    except socket.error:\\n        raise ValueError(('Not    a    good    dotted-quad    IP:    %s' % ip))\\n    return\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (not _state):\\n        raise RuntimeError('no    active    input()')\\n    return _state.isstdin()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def isstdin():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_args():\\n\\n    ''''Parses command line arguments\\n    :returns: Parsed command line options\\n    :rtype: argparse.Namespace'\\n    '''\",\"targets\":\"parser = argparse.ArgumentParser(description=_DESCRIPTION)\\n    parser.add_argument('-c', '--apache-ctl', default='apachectl', help='path    to    the    `apachectl`    binary')\\n    parser.add_argument('-d', '--server-root', help='location    of    the    root    directory    of    your    Apache    configuration')\\n    parser.add_argument('-f', '--config-file', help='location    of    your    main    Apache    configuration    file    relative    to    the    server    root')\\n    args = parser.parse_args()\\n    if (bool(args.server_root) != bool(args.config_file)):\\n        sys.exit('If    either    --server-root    and    --config-file    are    specified,    they    both    must    be    included')\\n    elif (args.server_root and args.config_file):\\n        args.server_root = os.path.abspath(args.server_root)\\n        args.config_file = os.path.abspath(args.config_file)\\n        if args.config_file.startswith(args.server_root):\\n            args.config_file = args.config_file[(len(args.server_root) + 1):]\\n        else:\\n            sys.exit('This    script    expects    the    Apache    configuration    file    to    be    inside    the    server    root')\\n    return args\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def groovy(registry, xml_parent, data):\",\"targets\":\"\\\"\\\"\\\"yaml: groovy\\n    Execute a groovy script or command.\\n    Requires the Jenkins :jenkins-wiki:`Groovy Plugin `.\\n    :arg str file: Groovy file to run. (Alternative: you can chose a command\\n    instead)\\n    :arg str command: Groovy command to run. (Alternative: you can chose a\\n    script file instead)\\n    :arg str version: Groovy version to use. (default \\\\(Default)\\\\)\\n    :arg str parameters: Parameters for the Groovy executable. (default \\\\\\\\)\\n    :arg str script-parameters: These parameters will be passed to the script.\\n    (default \\\\\\\\)\\n    :arg str properties: Instead of passing properties using the -D parameter\\n    you can define them here. (default \\\\\\\\)\\n    :arg str java-opts: Direct access to JAVA_OPTS. Properties allows only\\n    -D properties, while sometimes also other properties like -XX need to\\n    be setup. It can be done here. This line is appended at the end of\\n    JAVA_OPTS string. (default \\\\\\\\)\\n    :arg str class-path: Specify script classpath here. Each line is one\\n    class path item. (default \\\\\\\\)\\n    Minimal Example:\\n    .. literalinclude:: ..\\/..\\/tests\\/builders\\/fixtures\\/groovy-minimal.yaml\\n    :language: yaml\\n    Full Example:\\n    .. literalinclude:: ..\\/..\\/tests\\/builders\\/fixtures\\/groovy-full.yaml\\n    :language: yaml\\n    \\\"\\\"\\\"\\n    root_tag = 'hudson.plugins.groovy.Groovy'\\n    groovy = XML.SubElement(xml_parent, root_tag)\\n    groovy.append(_groovy_common_scriptSource(data))\\n    mappings = [('version', 'groovyName', '(Default)'), ('parameters', 'parameters', ''), ('script-parameters', 'scriptParameters', ''), ('properties', 'properties', ''), ('java-opts', 'javaOpts', ''), ('class-path', 'classPath', '')]\\n    convert_mapping_to_xml(groovy, data, mappings, fail_required=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    class __proxy__(Promise, ):\\n        '\\\\n                                Encapsulate    a    function    call    and    act    as    a    proxy    for    methods    that    are\\\\n                                called    on    the    result    of    that    function.    The    function    is    not    evaluated\\\\n                                until    one    of    the    methods    on    the    result    is    called.\\\\n                                '\\n        __dispatch = None\\n        def __init__(self, args, kw):\\n            self.__func = func\\n            self.__args = args\\n            self.__kw = kw\\n            if (self.__dispatch is None):\\n                self.__prepare_class__()\\n        def __reduce__(self):\\n            return (_lazy_proxy_unpickle, ((self.__func, self.__args, self.__kw) + resultclasses))\\n        def __prepare_class__(cls):\\n            cls.__dispatch = {}\\n            for resultclass in resultclasses:\\n                cls.__dispatch[resultclass] = {}\\n                for (k, v) in resultclass.__dict__.items():\\n                    meth = cls.__promise__(resultclass, k, v)\\n                    if hasattr(cls, k):\\n                        continue\\n                    setattr(cls, k, meth)\\n            cls._delegate_str = (str in resultclasses)\\n            cls._delegate_unicode = (unicode in resultclasses)\\n            assert (not (cls._delegate_str and cls._delegate_unicode)), 'Cannot    call    lazy()    with    both    str    and    unicode    return    types.'\\n            if cls._delegate_unicode:\\n                cls.__unicode__ = cls.__unicode_cast\\n            elif cls._delegate_str:\\n                cls.__str__ = cls.__str_cast\\n        __prepare_class__ = classmethod(__prepare_class__)\\n        def __promise__(cls, klass, funcname, func):\\n            def __wrapper__(self, *args, **kw):\\n                res = self.__func(*self.__args, **self.__kw)\\n                for t in type(res).mro():\\n                    if (t in self.__dispatch):\\n                        return...\\n\\nWhat's a good function header?\",\"targets\":\"def lazy(func, *resultclasses):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    last_valid_line_from_code = [line for line in code.split(u'\\\\n') if line][(-1)]\\n    status_code_from_last_line = int(last_valid_line_from_code.split()[0])\\n    status_code_from_first_digits = int(code[:3])\\n    if (status_code_from_last_line != status_code_from_first_digits):\\n        log.warning(u'FTP    response    status    code    seems    to    be    inconsistent.\\\\nCode    received:    %s,    extracted:    %s    and    %s', code, status_code_from_last_line, status_code_from_first_digits)\\n    return status_code_from_last_line\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_status_code_from_code_response(code):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef choicify(values):\\n\\n    ''''Takes an iterable and makes an iterable of tuples with it'\\n    '''\",\"targets\":\"return [(v, v) for v in values]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef iterkeys(d):\\n\\n    ''''Return an iterator over the keys of a dictionary.'\\n    '''\",\"targets\":\"return iter(getattr(d, _iterkeys)())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_characteristic_subpattern(subpatterns):\",\"targets\":\"\\\"\\\"\\\"Picks the most characteristic from a list of linear patterns\\n    Current order used is:\\n    names > common_names > common_chars\\n    \\\"\\\"\\\"\\n    if (not isinstance(subpatterns, list)):\\n        return subpatterns\\n    if (len(subpatterns) == 1):\\n        return subpatterns[0]\\n    subpatterns_with_names = []\\n    subpatterns_with_common_names = []\\n    common_names = ['in', 'for', 'if', 'not', 'None']\\n    subpatterns_with_common_chars = []\\n    common_chars = '[]().,:'\\n    for subpattern in subpatterns:\\n        if any(rec_test(subpattern, (lambda x: (type(x) is str)))):\\n            if any(rec_test(subpattern, (lambda x: (isinstance(x, str) and (x in common_chars))))):\\n                subpatterns_with_common_chars.append(subpattern)\\n            elif any(rec_test(subpattern, (lambda x: (isinstance(x, str) and (x in common_names))))):\\n                subpatterns_with_common_names.append(subpattern)\\n            else:\\n                subpatterns_with_names.append(subpattern)\\n    if subpatterns_with_names:\\n        subpatterns = subpatterns_with_names\\n    elif subpatterns_with_common_names:\\n        subpatterns = subpatterns_with_common_names\\n    elif subpatterns_with_common_chars:\\n        subpatterns = subpatterns_with_common_chars\\n    return max(subpatterns, key=len)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@gen.coroutine\\ndef UploadContacts(client, obj_store, user_id, device_id, request):\",\"targets\":\"\\\"\\\"\\\"Creates\\/updates contacts metadata.\\n    \\\"\\\"\\\"\\n    request['user_id'] = user_id\\n    contact_count = len(request['contacts'])\\n    result_contact_ids = []\\n    for contact in request['contacts']:\\n        canon_identities = set()\\n        identities_properties = []\\n        for contact_identity in contact['identities']:\\n            identity_key = contact_identity['identity']\\n            description = contact_identity.get('description', None)\\n            if (identity_key != Identity.Canonicalize(identity_key)):\\n                raise InvalidRequestError(IDENTITY_NOT_CANONICAL, identity_key=identity_key)\\n            canon_identities.add(identity_key)\\n            identities_properties.append((identity_key, description))\\n        contact['identities'] = list(canon_identities)\\n        contact['identities_properties'] = identities_properties\\n        contact['contact_id'] = Contact.CalculateContactId(contact)\\n        result_contact_ids.append(contact['contact_id'])\\n    (yield gen.Task(Operation.CreateAndExecute, client, user_id, device_id, 'UploadContactsOperation.Execute', request))\\n    logging.info(('UPLOAD    CONTACTS:    user:    %d,    device:    %d,    contact_count:    %d' % (user_id, device_id, contact_count)))\\n    raise gen.Return({'contact_ids': result_contact_ids})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    def decorator(func):\\n        @wraps(func, assigned=available_attrs(func))\\n        def inner(request, *args, **kwargs):\\n            if (request.method not in request_method_list):\\n                logger.warning('Method    Not    Allowed    (%s):    %s', request.method, request.path, extra={'status_code': 405, 'request': request})\\n                return HttpResponseNotAllowed(request_method_list)\\n            return func(request, *args, **kwargs)\\n        return inner\\n    return decorator\\n\\n\\nWhat's a good function header?\",\"targets\":\"def require_http_methods(request_method_list):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (vt_id == fake_vt['id']):\\n        return fake_vt\\n    raise exception.VolumeTypeNotFound(volume_type_id=vt_id)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def vt_get_volume_type(context, vt_id):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def affine_matrix_from_points(v0, v1, shear=True, scale=True, usesvd=True):\",\"targets\":\"\\\"\\\"\\\"Return affine transform matrix to register two point sets.\\n    v0 and v1 are shape (ndims, \\\\*) arrays of at least ndims non-homogeneous\\n    coordinates, where ndims is the dimensionality of the coordinate space.\\n    If shear is False, a similarity transformation matrix is returned.\\n    If also scale is False, a rigid\\/Euclidean transformation matrix\\n    is returned.\\n    By default the algorithm by Hartley and Zissermann [15] is used.\\n    If usesvd is True, similarity and Euclidean transformation matrices\\n    are calculated by minimizing the weighted sum of squared deviations\\n    (RMSD) according to the algorithm by Kabsch [8].\\n    Otherwise, and if ndims is 3, the quaternion based algorithm by Horn [9]\\n    is used, which is slower when using this Python implementation.\\n    The returned matrix performs rotation, translation and uniform scaling\\n    (if specified).\\n    >>> v0 = [[0, 1031, 1031, 0], [0, 0, 1600, 1600]]\\n    >>> v1 = [[675, 826, 826, 677], [55, 52, 281, 277]]\\n    >>> affine_matrix_from_points(v0, v1)\\n    array([[   0.14549,    0.00062,  675.50008],\\n    [   0.00048,    0.14094,   53.24971],\\n    [   0.     ,    0.     ,    1.     ]])\\n    >>> T = translation_matrix(numpy.random.random(3)-0.5)\\n    >>> R = random_rotation_matrix(numpy.random.random(3))\\n    >>> S = scale_matrix(random.random())\\n    >>> M = concatenate_matrices(T, R, S)\\n    >>> v0 = (numpy.random.rand(4, 100) - 0.5) * 20\\n    >>> v0[3] = 1\\n    >>> v1 = numpy.dot(M, v0)\\n    >>> v0[:3] += numpy.random.normal(0, 1e-8, 300).reshape(3, -1)\\n    >>> M = affine_matrix_from_points(v0[:3], v1[:3])\\n    >>> numpy.allclose(v1, numpy.dot(M, v0))\\n    True\\n    More examples in superimposition_matrix()\\n    \\\"\\\"\\\"\\n    v0 = numpy.array(v0, dtype=numpy.float64, copy=True)\\n    v1 = numpy.array(v1, dtype=numpy.float64, copy=True)\\n    ndims = v0.shape[0]\\n    if ((ndims < 2) or (v0.shape[1] < ndims) or (v0.shape != v1.shape)):\\n        raise ValueError('input    arrays    are    of    wrong    shape    or    type')\\n    t0 = (- numpy.mean(v0, axis=1))\\n    M0 = numpy.identity((ndims + 1))\\n    M0[:ndims, ndims] = t0\\n    v0 += t0.reshape(ndims, 1)\\n    t1 = (- numpy.mean(v1, axis=1))\\n    M1 = numpy.identity((ndims + 1))\\n    M1[:ndims, ndims] = t1\\n    v1 += t1.reshape(ndims, 1)\\n    if shear:\\n        A = numpy.concatenate((v0, v1), axis=0)\\n        (u, s, vh) = numpy.linalg.svd(A.T)\\n        vh = vh[:ndims].T\\n        B = vh[:ndims]\\n        C = vh[ndims:(2 * ndims)]\\n        t = numpy.dot(C, numpy.linalg.pinv(B))\\n        t = numpy.concatenate((t, numpy.zeros((ndims, 1))), axis=1)\\n        M = numpy.vstack((t, (((0.0,) * ndims) + (1.0,))))\\n    elif (usesvd or (ndims != 3)):\\n        (u, s, vh) = numpy.linalg.svd(numpy.dot(v1, v0.T))\\n        R = numpy.dot(u, vh)\\n        if (numpy.linalg.det(R) < 0.0):\\n            R -= numpy.outer(u[:, (ndims - 1)], (vh[(ndims - 1), :] * 2.0))\\n            s[(-1)] *= (-1.0)\\n        M = numpy.identity((ndims + 1))\\n        M[:ndims, :ndims] = R\\n    else:\\n        (xx, yy, zz) = numpy.sum((v0 * v1), axis=1)\\n        (xy, yz, zx) = numpy.sum((v0 * numpy.roll(v1, (-1), axis=0)), axis=1)\\n        (xz, yx, zy) = numpy.sum((v0 * numpy.roll(v1, (-2), axis=0)), axis=1)\\n        N = [[((xx + yy) + zz), 0.0, 0.0, 0.0], [(yz - zy), ((xx - yy) - zz), 0.0, 0.0], [(zx - xz), (xy + yx), ((yy - xx) - zz), 0.0], [(xy - yx), (zx + xz), (yz + zy), ((zz - xx) - yy)]]\\n        (w, V) = numpy.linalg.eigh(N)\\n        q = V[:, numpy.argmax(w)]\\n        q \\/= vector_norm(q)\\n        M = quaternion_matrix(q)\\n    if (scale and (not shear)):\\n        v0 *= v0\\n        v1 *= v1\\n        M[:ndims, :ndims] *= math.sqrt((numpy.sum(v1) \\/ numpy.sum(v0)))\\n    M = numpy.dot(numpy.linalg.inv(M1), numpy.dot(M, M0))\\n    M \\/= M[(ndims, ndims)]\\n    return M\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def label(object, index=None):\",\"targets\":\"\\\"\\\"\\\"label: set or get the label of the item. Specify file by name or fsspec.\\n    \\\"\\\"\\\"\\n    object = Carbon.File.FSRef(object)\\n    object_alias = object.FSNewAliasMinimal()\\n    if (index is None):\\n        return _getlabel(object_alias)\\n    if ((index < 0) or (index > 7)):\\n        index = 0\\n    return _setlabel(object_alias, index)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef is_style_file(filename):\\n\\n    ''''Return True if the filename looks like a style file.'\\n    '''\",\"targets\":\"return (STYLE_FILE_PATTERN.match(filename) is not None)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _pprint_dict(seq, _nest_lvl=0, max_seq_items=None, **kwds):\",\"targets\":\"\\\"\\\"\\\"internal. pprinter for iterables. you should probably use pprint_thing()\\n    rather then calling this directly.\\n    \\\"\\\"\\\"\\n    fmt = u('{%s}')\\n    pairs = []\\n    pfmt = u('%s:    %s')\\n    if (max_seq_items is False):\\n        nitems = len(seq)\\n    else:\\n        nitems = (max_seq_items or get_option('max_seq_items') or len(seq))\\n    for (k, v) in list(seq.items())[:nitems]:\\n        pairs.append((pfmt % (pprint_thing(k, (_nest_lvl + 1), max_seq_items=max_seq_items, **kwds), pprint_thing(v, (_nest_lvl + 1), max_seq_items=max_seq_items, **kwds))))\\n    if (nitems < len(seq)):\\n        return (fmt % (',    '.join(pairs) + ',    ...'))\\n    else:\\n        return (fmt % ',    '.join(pairs))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def grid_to_graph(n_x, n_y, n_z=1, mask=None, return_as=sparse.coo_matrix, dtype=np.int):\",\"targets\":\"\\\"\\\"\\\"Graph of the pixel-to-pixel connections\\n    Edges exist if 2 voxels are connected.\\n    Parameters\\n    n_x : int\\n    Dimension in x axis\\n    n_y : int\\n    Dimension in y axis\\n    n_z : int, optional, default 1\\n    Dimension in z axis\\n    mask : ndarray of booleans, optional\\n    An optional mask of the image, to consider only part of the\\n    pixels.\\n    return_as : np.ndarray or a sparse matrix class, optional\\n    The class to use to build the returned adjacency matrix.\\n    dtype : dtype, optional, default int\\n    The data of the returned sparse matrix. By default it is int\\n    Notes\\n    For scikit-learn versions 0.14.1 and prior, return_as=np.ndarray was\\n    handled by returning a dense np.matrix instance.  Going forward, np.ndarray\\n    returns an np.ndarray, as expected.\\n    For compatibility, user code relying on this method should wrap its\\n    calls in ``np.asarray`` to avoid type issues.\\n    \\\"\\\"\\\"\\n    return _to_graph(n_x, n_y, n_z, mask=mask, return_as=return_as, dtype=dtype)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def file_uri(fname):\",\"targets\":\"\\\"\\\"\\\"Select the right file uri scheme according to the operating system\\n    \\\"\\\"\\\"\\n    if (os.name == 'nt'):\\n        if re.search('^[a-zA-Z]:', fname):\\n            return ('file:\\/\\/\\/' + fname)\\n        else:\\n            return ('file:\\/\\/' + fname)\\n    else:\\n        return ('file:\\/\\/' + fname)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    from pyblockchain import validate_address\\n    addresses = config.get(CONF_ADDRESSES)\\n    name = config.get(CONF_NAME)\\n    for address in addresses:\\n        if (not validate_address(address)):\\n            _LOGGER.error('Bitcoin    address    is    not    valid:    %s', address)\\n            return False\\n    add_devices([BlockchainSensor(name, addresses)], True)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def setup_platform(hass, config, add_devices, discovery_info=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    (domain, username) = _GetDomainAndUserName()\\n    vcuser_filename = '.'.join([proj_path, domain, username, 'user'])\\n    user_file = MSVSUserFile.Writer(vcuser_filename, version, spec['target_name'])\\n    return user_file\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _CreateMSVSUserFile(proj_path, version, spec):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    f = (_Cfunctions.get('libvlc_media_player_retain', None) or _Cfunction('libvlc_media_player_retain', ((1,),), None, None, MediaPlayer))\\n    return f(p_mi)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def libvlc_media_player_retain(p_mi):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef chgroups(name, groups, append=False, root=None):\\n\\n    ''''Change the groups to which this user belongs\\n    name\\n    User to modify\\n    groups\\n    Groups to set for the user\\n    append : False\\n    If ``True``, append the specified group(s). Otherwise, this function\\n    will replace the user\\\\'s groups with the specified group(s).\\n    CLI Examples:\\n    .. code-block:: bash\\n    salt \\\\'*\\\\' user.chgroups foo wheel,root\\n    salt \\\\'*\\\\' user.chgroups foo wheel,root append=True'\\n    '''\",\"targets\":\"if isinstance(groups, six.string_types):\\n        groups = groups.split(',')\\n    ugrps = set(list_groups(name))\\n    if (ugrps == set(groups)):\\n        return True\\n    cmd = ['usermod']\\n    if (__grains__['kernel'] != 'OpenBSD'):\\n        if (append and (__grains__['kernel'] != 'AIX')):\\n            cmd.append('-a')\\n        cmd.append('-G')\\n    elif append:\\n        cmd.append('-G')\\n    else:\\n        cmd.append('-S')\\n    if (append and (__grains__['kernel'] == 'AIX')):\\n        cmd.extend([((','.join(ugrps) + ',') + ','.join(groups)), name])\\n    else:\\n        cmd.extend([','.join(groups), name])\\n    if ((root is not None) and (__grains__['kernel'] != 'AIX')):\\n        cmd.extend(('-R', root))\\n    result = __salt__['cmd.run_all'](cmd, python_shell=False)\\n    if ((__grains__['kernel'] != 'OpenBSD') and (__grains__['kernel'] != 'AIX')):\\n        if ((result['retcode'] != 0) and ('not    found    in' in result['stderr'])):\\n            ret = True\\n            for group in groups:\\n                cmd = ['gpasswd', '-a', '{0}'.format(name), '{0}'.format(group)]\\n                if (__salt__['cmd.retcode'](cmd, python_shell=False) != 0):\\n                    ret = False\\n            return ret\\n    return (result['retcode'] == 0)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def findObj(regex):\",\"targets\":\"\\\"\\\"\\\"Return a list of objects whose typeStr matches regex\\n    \\\"\\\"\\\"\\n    allObjs = get_all_objects()\\n    objs = []\\n    r = re.compile(regex)\\n    for i in allObjs:\\n        obj = allObjs[i]\\n        if r.search(typeStr(obj)):\\n            objs.append(obj)\\n    return objs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n    if (transform is not None):\\n        path = path.transformed(transform)\\n    vc_tuples = [((vertices if (path_code != Path.CLOSEPOLY) else []), PATH_DICT[path_code]) for (vertices, path_code) in path.iter_segments(simplify=simplify)]\\n    if (not vc_tuples):\\n        return (np.zeros((0, 2)), [])\\n    else:\\n        (vertices, codes) = zip(*vc_tuples)\\n        vertices = np.array(list(itertools.chain(*vertices))).reshape((-1), 2)\\n        return (vertices, list(codes))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def SVG_path(path, transform=None, simplify=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_course_update_items(course_updates, provided_index=0):\",\"targets\":\"\\\"\\\"\\\"Returns list of course_updates data dictionaries either from new format if available or\\n    from old. This function don\\\\t modify old data to new data (in db), instead returns data\\n    in common old dictionary format.\\n    New Format: {\\\"items\\\" : [{\\\"id\\\": computed_id, \\\"date\\\": date, \\\"content\\\": html-string}],\\n    \\\"data\\\": \\\"
    [
  1. date<\\/h2>content<\\/li>]<\\/ol>\\\"}\\n Old Format: {\\\"data\\\": \\\"
      [
    1. date<\\/h2>content<\\/li>]<\\/ol>\\\"}\\n \\\"\\\"\\\"\\n def _course_info_content(html_parsed):\\n '\\\\n Constructs the HTML for the course info update, not including the header.\\\\n '\\n if (len(html_parsed) == 1):\\n content = html_parsed[0].tail\\n else:\\n content = (html_parsed[0].tail if (html_parsed[0].tail is not None) else '')\\n content += '\\\\n'.join([html.tostring(ele) for ele in html_parsed[1:]])\\n return content\\n if (course_updates and getattr(course_updates, 'items', None)):\\n if (provided_index and (0 < provided_index <= len(course_updates.items))):\\n return course_updates.items[(provided_index - 1)]\\n else:\\n return list(reversed(course_updates.items))\\n course_update_items = []\\n if course_updates:\\n try:\\n course_html_parsed = html.fromstring(course_updates.data)\\n except (etree.XMLSyntaxError, etree.ParserError):\\n log.error(('Cannot parse: ' + course_updates.data))\\n escaped = escape(course_updates.data)\\n course_html_parsed = html.fromstring((('
      1. ' + escaped) + '<\\/li><\\/ol>'))\\n if (course_html_parsed.tag == 'ol'):\\n for (index, update) in enumerate(course_html_parsed):\\n if (len(update) > 0):\\n content = _course_info_content(update)\\n computed_id = (len(course_html_parsed) - index)\\n payload = {'id': computed_id, 'date': update.findtext('h2'), 'content': content}\\n if (provided_index == 0):\\n course_update_items.append(payload)\\n elif (provided_index == computed_id):\\n return payload\\n return course_update_items\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (using is None):\\n using = DEFAULT_DB_ALIAS\\n connection = connections[using]\\n connection.enter_transaction_management(managed)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def enter_transaction_management(managed=True, using=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def less_shitty_error_messages(func):\",\"targets\":\"\\\"\\\"\\\"Wraps functions where the first param is a SQL statement and enforces\\n any exceptions thrown will also contain the statement in the message.\\n \\\"\\\"\\\"\\n @wraps(func)\\n def inner(self, sql, *args, **kwargs):\\n try:\\n return func(self, sql, *args, **kwargs)\\n except Exception as e:\\n exc_info = sys.exc_info()\\n msg = '{}\\\\nSQL: {}'.format(repr(e), sql)\\n six.reraise(exc_info[0], exc_info[0](msg), exc_info[2])\\n return inner\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef detectencoding_unicode(input, final=False):\\n\\n ''''Detect the encoding of the unicode string ``input``, which contains the\\n beginning of a CSS file. The encoding is detected from the charset rule\\n at the beginning of ``input``. If there is no charset rule, ``\\\"utf-8\\\"``\\n will be returned.\\n If the encoding can\\\\'t be detected yet, ``None`` is returned. ``final``\\n specifies whether more data will be available in later calls or not. If\\n ``final`` is true, ``detectencoding_unicode()`` will never return ``None``.'\\n '''\",\"targets\":\"prefix = u'@charset \\\"'\\n if input.startswith(prefix):\\n pos = input.find(u'\\\"', len(prefix))\\n if (pos >= 0):\\n return (input[len(prefix):pos], True)\\n elif (final or (not prefix.startswith(input))):\\n return ('utf-8', False)\\n return (None, False)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (len(names) == 1):\\n return str(__proxy__['rest_sample.package_status'](names[0]))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def version(*names, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for i in CONF['COLORS']:\\n if isinstance(CONF['COLORS'][i], dict):\\n for j in CONF['COLORS'][i]:\\n CONF['COLORS'][i][j] = ''\\n else:\\n CONF['COLORS'][i] = ''\\n\\n\\nWhat's a good function header?\",\"targets\":\"def remove_colors():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef build_dataset(filename, sequence_length, alphabet_size, max_lines=(-1)):\\n\\n ''''Loads a text file, and turns each line into an encoded sequence.'\\n '''\",\"targets\":\"with open(filename) as f:\\n content = f.readlines()\\n content = content[:max_lines]\\n content = [line for line in content if (len(line) > 2)]\\n seqs = np.zeros((sequence_length, len(content), alphabet_size))\\n for (ix, line) in enumerate(content):\\n padded_line = (line + (' ' * sequence_length))[:sequence_length]\\n seqs[:, ix, :] = string_to_one_hot(padded_line, alphabet_size)\\n return seqs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n r = []\\n if head:\\n item = head\\n while item:\\n item = item.contents\\n r.append((item.id, item.name))\\n item = item.__next__\\n try:\\n libvlc_track_description_release(head)\\n except NameError:\\n libvlc_track_description_list_release(head)\\n return r\\n\\n\\nWhat's a good function header?\",\"targets\":\"def track_description_list(head):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def direct_get_object(node, part, account, container, obj, conn_timeout=5, response_timeout=15, resp_chunk_size=None, headers={}):\",\"targets\":\"\\\"\\\"\\\"Get object directly from the object server.\\n :param node: node dictionary from the ring\\n :param part: partition the container is on\\n :param account: account name\\n :param container: container name\\n :param obj: object name\\n :param conn_timeout: timeout in seconds for establishing the connection\\n :param response_timeout: timeout in seconds for getting the response\\n :param resp_chunk_size: if defined, chunk size of data to read.\\n :param headers: dict to be passed into HTTPConnection headers\\n :returns: a tuple of (response headers, the object\\\\s contents) The response\\n headers will be a dict and all header names will be lowercase.\\n \\\"\\\"\\\"\\n path = ('\\/%s\\/%s\\/%s' % (account, container, obj))\\n with Timeout(conn_timeout):\\n conn = http_connect(node['ip'], node['port'], node['device'], part, 'GET', path, headers=headers)\\n with Timeout(response_timeout):\\n resp = conn.getresponse()\\n if (not is_success(resp.status)):\\n resp.read()\\n raise ClientException(('Object server %s:%s direct GET %s gave status %s' % (node['ip'], node['port'], repr(('\\/%s\\/%s%s' % (node['device'], part, path))), resp.status)), http_host=node['ip'], http_port=node['port'], http_device=node['device'], http_status=resp.status, http_reason=resp.reason)\\n if resp_chunk_size:\\n def _object_body():\\n buf = resp.read(resp_chunk_size)\\n while buf:\\n (yield buf)\\n buf = resp.read(resp_chunk_size)\\n object_body = _object_body()\\n else:\\n object_body = resp.read()\\n resp_headers = {}\\n for (header, value) in resp.getheaders():\\n resp_headers[header.lower()] = value\\n return (resp_headers, object_body)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _build_target_proxy_dict(params, project_id=None):\\n\\n ''''Reformat services in Ansible Params.\\n :param params: Params from AnsibleModule object\\n :type params: ``dict``\\n :param project_id: The GCP project ID.\\n :type project_id: ``str``\\n :return: dictionary suitable for submission to GCP UrlMap API.\\n :rtype ``dict``'\\n '''\",\"targets\":\"url = ''\\n if project_id:\\n url = GCPUtils.build_googleapi_url(project_id)\\n gcp_dict = GCPUtils.params_to_gcp_dict(params, 'target_proxy_name')\\n if ('urlMap' in gcp_dict):\\n gcp_dict['urlMap'] = ('%s\\/global\\/urlMaps\\/%s' % (url, gcp_dict['urlMap']))\\n return gcp_dict\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _req_environ_property(environ_field):\",\"targets\":\"\\\"\\\"\\\"Set and retrieve value of the environ_field entry in self.environ.\\n (Used by both request and response)\\n \\\"\\\"\\\"\\n def getter(self):\\n return self.environ.get(environ_field, None)\\n def setter(self, value):\\n if isinstance(value, six.text_type):\\n self.environ[environ_field] = value.encode('utf-8')\\n else:\\n self.environ[environ_field] = value\\n return property(getter, setter, doc=('Get and set the %s property in the WSGI environment' % environ_field))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def avail_images(call=None, location='local'):\",\"targets\":\"\\\"\\\"\\\"Return a list of the images that are on the provider\\n CLI Example:\\n .. code-block:: bash\\n salt-cloud --list-images my-proxmox-config\\n \\\"\\\"\\\"\\n if (call == 'action'):\\n raise SaltCloudSystemExit('The avail_images function must be called with -f or --function, or with the --list-images option')\\n ret = {}\\n for (host_name, host_details) in six.iteritems(avail_locations()):\\n for item in query('get', 'nodes\\/{0}\\/storage\\/{1}\\/content'.format(host_name, location)):\\n ret[item['volid']] = item\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n cutoffs.setdefault(u'max_iter', 100)\\n cutoffchecker = CutoffChecker(cutoffs)\\n if (encoding is None):\\n encoding = BinaryMaxentFeatureEncoding.train(train_toks, labels=labels)\\n empirical_ffreq = (calculate_empirical_fcount(train_toks, encoding) \\/ len(train_toks))\\n nfmap = calculate_nfmap(train_toks, encoding)\\n nfarray = numpy.array(sorted(nfmap, key=nfmap.__getitem__), u'd')\\n nftranspose = numpy.reshape(nfarray, (len(nfarray), 1))\\n unattested = set(numpy.nonzero((empirical_ffreq == 0))[0])\\n weights = numpy.zeros(len(empirical_ffreq), u'd')\\n for fid in unattested:\\n weights[fid] = numpy.NINF\\n classifier = ConditionalExponentialClassifier(encoding, weights)\\n if (trace > 0):\\n print((u' ==> Training (%d iterations)' % cutoffs[u'max_iter']))\\n if (trace > 2):\\n print()\\n print(u' Iteration Log Likelihood Accuracy')\\n print(u' ---------------------------------------')\\n try:\\n while True:\\n if (trace > 2):\\n ll = (cutoffchecker.ll or log_likelihood(classifier, train_toks))\\n acc = (cutoffchecker.acc or accuracy(classifier, train_toks))\\n iternum = cutoffchecker.iter\\n print((u' %9d %14.5f %9.3f' % (iternum, ll, acc)))\\n deltas = calculate_deltas(train_toks, classifier, unattested, empirical_ffreq, nfmap, nfarray, nftranspose, encoding)\\n weights = classifier.weights()\\n weights += deltas\\n classifier.set_weights(weights)\\n if cutoffchecker.check(classifier, train_toks):\\n break\\n except KeyboardInterrupt:\\n print(u' Training stopped: keyboard interrupt')\\n except:\\n raise\\n if (trace > 2):\\n ll = log_likelihood(classifier, train_toks)\\n acc = accuracy(classifier, train_toks)\\n print((u' ...\\n\\nWhat's a good function header?\",\"targets\":\"def train_maxent_classifier_with_iis(train_toks, trace=3, encoding=None, labels=None, **cutoffs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _mountpoint_to_number(mountpoint):\",\"targets\":\"\\\"\\\"\\\"Translate a mountpoint like \\/dev\\/sdc into a numeric.\\n \\\"\\\"\\\"\\n if mountpoint.startswith('\\/dev\\/'):\\n mountpoint = mountpoint[5:]\\n if re.match('^[hs]d[a-p]$', mountpoint):\\n return (ord(mountpoint[2:3]) - ord('a'))\\n elif re.match('^x?vd[a-p]$', mountpoint):\\n return (ord(mountpoint[(-1)]) - ord('a'))\\n elif re.match('^[0-9]+$', mountpoint):\\n return int(mountpoint, 10)\\n else:\\n LOG.warning('Mountpoint cannot be translated: %s', mountpoint)\\n return (-1)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __do_query_into_hash(conn, sql_str):\",\"targets\":\"\\\"\\\"\\\"Perform the query that is passed to it (sql_str).\\n Returns:\\n results in a dict.\\n \\\"\\\"\\\"\\n mod = sys._getframe().f_code.co_name\\n log.debug('{0}<--({1})'.format(mod, sql_str))\\n rtn_results = []\\n try:\\n cursor = conn.cursor()\\n except MySQLdb.MySQLError:\\n log.error(\\\"{0}: Can't get cursor for SQL->{1}\\\".format(mod, sql_str))\\n cursor.close()\\n log.debug('{0}-->'.format(mod))\\n return rtn_results\\n try:\\n _execute(cursor, sql_str)\\n except MySQLdb.MySQLError:\\n log.error('{0}: try to execute : SQL->{1}'.format(mod, sql_str))\\n cursor.close()\\n log.debug('{0}-->'.format(mod))\\n return rtn_results\\n qrs = cursor.fetchall()\\n for row_data in qrs:\\n col_cnt = 0\\n row = {}\\n for col_data in cursor.description:\\n col_name = col_data[0]\\n row[col_name] = row_data[col_cnt]\\n col_cnt += 1\\n rtn_results.append(row)\\n cursor.close()\\n log.debug('{0}-->'.format(mod))\\n return rtn_results\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef add_site(name, domain):\\n\\n ''''Add a site to database, create directory tree'\\n '''\",\"targets\":\"sites = Site.objects.all()\\n used_ids = [v[0] for v in sites.values_list()]\\n site_id = (max(used_ids) + 1)\\n project_dir = os.path.realpath(os.path.join(settings.SITE_ROOT, '..\\/'))\\n site_dir = os.path.join(project_dir, ('site%s' % site_id))\\n site_template = os.path.join(os.path.dirname(__file__), 'site_template')\\n shutil.copytree(site_template, site_dir)\\n change_dict = {'$SITE_ID': str(site_id), '$SITE_NAME': name, '$DOMAIN': domain, '$SITE_ROOT': site_dir, '$SERVE_PATH': settings.SERVE_PATH, '$PORTNUM': ('8%s' % str(site_id).zfill(3)), '$GEOSERVER_URL': settings.GEOSERVER_URL, '$PROJECT_NAME': os.path.basename(os.path.dirname(settings.PROJECT_ROOT))}\\n sed(os.path.join(site_dir, 'conf\\/gunicorn'), change_dict)\\n sed(os.path.join(site_dir, 'conf\\/nginx'), change_dict)\\n sed(os.path.join(site_dir, 'settings.py'), change_dict)\\n sed(os.path.join(site_dir, 'local_settings_template.py'), change_dict)\\n sed(os.path.join(site_dir, 'wsgi.py'), change_dict)\\n site = Site(id=site_id, name=name, domain=domain)\\n site.save()\\n dump_model(Site, os.path.join(project_dir, 'sites.json'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n q = avatar.quit()\\n q.addCallback(quitServer)\\n return q\\n\\n\\nWhat's a good function header?\",\"targets\":\"def leftGroup(ignored, avatar):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_template_path_with_theme(relative_path):\\n\\n ''''Returns template path in current site\\\\'s theme if it finds one there otherwise returns same path.\\n Example:\\n >> get_template_path_with_theme(\\\\'header.html\\\\')\\n \\\\'\\/red-theme\\/lms\\/templates\\/header.html\\\\'\\n Parameters:\\n relative_path (str): template\\\\'s path relative to the templates directory e.g. \\\\'footer.html\\\\'\\n Returns:\\n (str): template path in current site\\\\'s theme'\\n '''\",\"targets\":\"relative_path = os.path.normpath(relative_path)\\n theme = get_current_theme()\\n if (not theme):\\n return relative_path\\n template_name = re.sub('^\\/+', '', relative_path)\\n template_path = (theme.template_path \\/ template_name)\\n absolute_path = ((theme.path \\/ 'templates') \\/ template_name)\\n if absolute_path.exists():\\n return str(template_path)\\n else:\\n return relative_path\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _bellman_ford(G, source, weight, pred=None, paths=None, dist=None, cutoff=None, target=None):\\n\\n ''''Relaxation loop for Bellman–Ford algorithm\\n Parameters\\n G : NetworkX graph\\n source: list\\n List of source nodes\\n weight : function\\n The weight of an edge is the value returned by the function. The\\n function must accept exactly three positional arguments: the two\\n endpoints of an edge and the dictionary of edge attributes for\\n that edge. The function must return a number.\\n pred: dict of lists, optional (default=None)\\n dict to store a list of predecessors keyed by that node\\n If None, predecessors are not stored\\n paths: dict, optional (default=None)\\n dict to store the path list from source to each node, keyed by node\\n If None, paths are not stored\\n dist: dict, optional (default=None)\\n dict to store distance from source to the keyed node\\n If None, returned dist dict contents default to 0 for every node in the\\n source list\\n cutoff: integer or float, optional\\n Depth to stop the search. Only paths of length <= cutoff are returned\\n target: node label, optional\\n Ending node for path. Path lengths to other destinations may (and\\n probably will) be incorrect.\\n Returns\\n Returns a dict keyed by node to the distance from the source.\\n Dicts for paths and pred are in the mutated input dicts by those names.\\n Raises\\n NetworkXUnbounded\\n If the (di)graph contains a negative cost (di)cycle, the\\n algorithm raises an exception to indicate the presence of the\\n negative cost (di)cycle. Note: any negative weight edge in an\\n undirected graph is a negative cost cycle'\\n '''\",\"targets\":\"if (pred is None):\\n pred = {v: [None] for v in source}\\n if (dist is None):\\n dist = {v: 0 for v in source}\\n G_succ = (G.succ if G.is_directed() else G.adj)\\n inf = float('inf')\\n n = len(G)\\n count = {}\\n q = deque(source)\\n in_q = set(source)\\n while q:\\n u = q.popleft()\\n in_q.remove(u)\\n if all(((pred_u not in in_q) for pred_u in pred[u])):\\n dist_u = dist[u]\\n for (v, e) in G_succ[u].items():\\n dist_v = (dist_u + weight(v, u, e))\\n if (cutoff is not None):\\n if (dist_v > cutoff):\\n continue\\n if (target is not None):\\n if (dist_v > dist.get(target, inf)):\\n continue\\n if (dist_v < dist.get(v, inf)):\\n if (v not in in_q):\\n q.append(v)\\n in_q.add(v)\\n count_v = (count.get(v, 0) + 1)\\n if (count_v == n):\\n raise nx.NetworkXUnbounded('Negative cost cycle detected.')\\n count[v] = count_v\\n dist[v] = dist_v\\n pred[v] = [u]\\n elif ((dist.get(v) is not None) and (dist_v == dist.get(v))):\\n pred[v].append(u)\\n if (paths is not None):\\n dsts = ([target] if (target is not None) else pred)\\n for dst in dsts:\\n path = [dst]\\n cur = dst\\n while (pred[cur][0] is not None):\\n cur = pred[cur][0]\\n path.append(cur)\\n path.reverse()\\n paths[dst] = path\\n return dist\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def add_alias(alias, canonical):\",\"targets\":\"\\\"\\\"\\\"Add a character set alias.\\n alias is the alias name, e.g. latin-1\\n canonical is the character set\\\\s canonical name, e.g. iso-8859-1\\n \\\"\\\"\\\"\\n ALIASES[alias] = canonical\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n import doctest\\n if (verbosity is None):\\n verbosity = verbose\\n else:\\n verbosity = None\\n save_stdout = sys.stdout\\n sys.stdout = get_original_stdout()\\n try:\\n (f, t) = doctest.testmod(module, verbose=verbosity)\\n if f:\\n raise TestFailed(('%d of %d doctests failed' % (f, t)))\\n finally:\\n sys.stdout = save_stdout\\n if verbose:\\n print ('doctest (%s) ... %d tests with zero failures' % (module.__name__, t))\\n return (f, t)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def run_doctest(module, verbosity=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def directional_variance(X, w):\",\"targets\":\"\\\"\\\"\\\"the variance of the data in the direction w\\n \\\"\\\"\\\"\\n return sum((directional_variance_i(x_i, w) for x_i in X))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef download_private_file(path):\\n\\n ''''Checks permissions and sends back private file'\\n '''\",\"targets\":\"try:\\n check_file_permission(path)\\n except frappe.PermissionError:\\n raise Forbidden(_(u\\\"You don't have permission to access this file\\\"))\\n return send_private_file(path.split(u'\\/private', 1)[1])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n obj = cls.__new__(cls)\\n obj.__dict__.update(dict_)\\n list.extend(obj, items)\\n return obj\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _reconstitute(cls, dict_, items):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_db_slave_ips():\",\"targets\":\"\\\"\\\"\\\"Returns the slave datastore IPs.\\n Returns:\\n A list of IP of the datastore slaves.\\n \\\"\\\"\\\"\\n try:\\n with open(constants.SLAVES_FILE_LOC) as slaves_file:\\n return [line.strip() for line in slaves_file if line.strip()]\\n except IOError:\\n return []\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def CentralMoment(xs, k):\",\"targets\":\"\\\"\\\"\\\"Computes the kth central moment of xs.\\n \\\"\\\"\\\"\\n mean = RawMoment(xs, 1)\\n return (sum((((x - mean) ** k) for x in xs)) \\/ len(xs))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dist_is_editable(dist):\",\"targets\":\"\\\"\\\"\\\"Is distribution an editable install?\\n \\\"\\\"\\\"\\n for path_item in sys.path:\\n egg_link = os.path.join(path_item, (dist.project_name + '.egg-link'))\\n if os.path.isfile(egg_link):\\n return True\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def debug(*args):\",\"targets\":\"\\\"\\\"\\\"Prints a prettyprinted version of `args` to stderr.\\n \\\"\\\"\\\"\\n try:\\n out = context.environ['wsgi.errors']\\n except:\\n out = sys.stderr\\n for arg in args:\\n print >>out, pprint.pformat(arg)\\n return ''\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def app_restore(storage, bucket_name=None):\",\"targets\":\"\\\"\\\"\\\"Restores the app source code from the backups location on the filesystem.\\n Args:\\n storage: A str, one of the StorageTypes class members.\\n bucket_name: A str, the name of the bucket to restore apps from.\\n Returns:\\n True on success, False otherwise.\\n \\\"\\\"\\\"\\n if (not makedirs(APP_BACKUP_DIR_LOCATION)):\\n logging.warning(\\\"Dir '{0}' already exists. Skipping dir creation...\\\".format(APP_BACKUP_DIR_LOCATION))\\n if (storage == StorageTypes.GCS):\\n objects = gcs_helper.list_bucket(bucket_name)\\n for app_path in objects:\\n if (not app_path.startswith(gcs_helper.APPS_GCS_PREFIX)):\\n continue\\n app_file = app_path[len(gcs_helper.APPS_GCS_PREFIX):]\\n source = 'gs:\\/\\/{0}\\/{1}'.format(bucket_name, app_path)\\n destination = '{0}\\/{1}'.format(APP_BACKUP_DIR_LOCATION, app_file)\\n if (not gcs_helper.download_from_bucket(source, destination)):\\n logging.error(\\\"Error while downloading '{0}' from GCS.\\\".format(source))\\n delete_app_tars(APP_BACKUP_DIR_LOCATION)\\n return False\\n apps_to_deploy = [os.path.join(APP_BACKUP_DIR_LOCATION, app) for app in os.listdir(APP_BACKUP_DIR_LOCATION)]\\n if (not deploy_apps(apps_to_deploy)):\\n logging.error('Failed to successfully deploy one or more of the following apps: {0}'.format(apps_to_deploy))\\n return False\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef debug(mode=True):\\n\\n ''''Change the debug level.\\n There is only one debug level supported at the moment.'\\n '''\",\"targets\":\"global DEBUG\\n if mode:\\n warnings.simplefilter('default')\\n DEBUG = bool(mode)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _strict_random_crop_image(image, boxes, labels, masks=None, keypoints=None, min_object_covered=1.0, aspect_ratio_range=(0.75, 1.33), area_range=(0.1, 1.0), overlap_thresh=0.3):\\n\\n ''''Performs random crop.\\n Note: boxes will be clipped to the crop. Keypoint coordinates that are\\n outside the crop will be set to NaN, which is consistent with the original\\n keypoint encoding for non-existing keypoints. This function always crops\\n the image and is supposed to be used by `random_crop_image` function which\\n sometimes returns image unchanged.\\n Args:\\n image: rank 3 float32 tensor containing 1 image -> [height, width, channels]\\n with pixel values varying between [0, 1].\\n boxes: rank 2 float32 tensor containing the bounding boxes with shape\\n [num_instances, 4].\\n Boxes are in normalized form meaning their coordinates vary\\n between [0, 1].\\n Each row is in the form of [ymin, xmin, ymax, xmax].\\n labels: rank 1 int32 tensor containing the object classes.\\n masks: (optional) rank 3 float32 tensor with shape\\n [num_instances, height, width] containing instance masks. The masks\\n are of the same height, width as the input `image`.\\n keypoints: (optional) rank 3 float32 tensor with shape\\n [num_instances, num_keypoints, 2]. The keypoints are in y-x\\n normalized coordinates.\\n min_object_covered: the cropped image must cover at least this fraction of\\n at least one of the input bounding boxes.\\n aspect_ratio_range: allowed range for aspect ratio of cropped image.\\n area_range: allowed range for area ratio between cropped image and the\\n original image.\\n overlap_thresh: minimum overlap thresh with new cropped\\n image to keep the box.\\n Returns:\\n image: image which is the same rank as input image.\\n boxes: boxes which is the same rank as input boxes.\\n Boxes are in normalized form.\\n labels: new labels.\\n If masks, or keypoints is not None, the function also returns:\\n masks: rank 3 float32 tensor with shape [num_instances, height, width]\\n containing instance masks.\\n keypoints: rank 3 float32 tensor with shape\\n [num_instances, num_keypoints, 2]'\\n '''\",\"targets\":\"with tf.name_scope('RandomCropImage', values=[image, boxes]):\\n image_shape = tf.shape(image)\\n boxes_expanded = tf.expand_dims(tf.clip_by_value(boxes, clip_value_min=0.0, clip_value_max=1.0), 1)\\n sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(image_shape, bounding_boxes=boxes_expanded, min_object_covered=min_object_covered, aspect_ratio_range=aspect_ratio_range, area_range=area_range, max_attempts=100, use_image_if_no_bounding_boxes=True)\\n (im_box_begin, im_box_size, im_box) = sample_distorted_bounding_box\\n new_image = tf.slice(image, im_box_begin, im_box_size)\\n new_image.set_shape([None, None, image.get_shape()[2]])\\n im_box_rank2 = tf.squeeze(im_box, squeeze_dims=[0])\\n im_box_rank1 = tf.squeeze(im_box)\\n boxlist = box_list.BoxList(boxes)\\n boxlist.add_field('labels', labels)\\n im_boxlist = box_list.BoxList(im_box_rank2)\\n (boxlist, inside_window_ids) = box_list_ops.prune_completely_outside_window(boxlist, im_box_rank1)\\n (overlapping_boxlist, keep_ids) = box_list_ops.prune_non_overlapping_boxes(boxlist, im_boxlist, overlap_thresh)\\n new_labels = overlapping_boxlist.get_field('labels')\\n new_boxlist = box_list_ops.change_coordinate_frame(overlapping_boxlist, im_box_rank1)\\n new_boxes = new_boxlist.get()\\n new_boxes = tf.clip_by_value(new_boxes, clip_value_min=0.0, clip_value_max=1.0)\\n result = [new_image, new_boxes, new_labels]\\n if (masks is not None):\\n masks_of_boxes_inside_window = tf.gather(masks, inside_window_ids)\\n masks_of_boxes_completely_inside_window = tf.gather(masks_of_boxes_inside_window, keep_ids)\\n masks_box_begin = [0, im_box_begin[0], im_box_begin[1]]\\n masks_box_size = [(-1), im_box_size[0], im_box_size[1]]\\n new_masks = tf.slice(masks_of_boxes_completely_inside_window, masks_box_begin, masks_box_size)\\n result.append(new_masks)\\n if (keypoints is not None):\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _visible_width(s):\\n\\n ''''Visible width of a printed string. ANSI color codes are removed.\\n >>> _visible_width(\\\\'\\u001b[31mhello\\u001b[0m\\\\'), _visible_width(\\\"world\\\")\\n (5, 5)'\\n '''\",\"targets\":\"if (isinstance(s, _text_type) or isinstance(s, _binary_type)):\\n return len(_strip_invisible(s))\\n else:\\n return len(_text_type(s))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n import pandas as pd\\n result_dict = pd.read_pickle(result_pickle_file_path)\\n from .report import generate_report\\n generate_report(result_dict, target_report_csv_path)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@cli.command()\\n@click.argument('result_pickle_file_path', type=click.Path(exists=True), required=True)\\n@click.argument('target_report_csv_path', type=click.Path(exists=True, writable=True), required=True)\\ndef report(result_pickle_file_path, target_report_csv_path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@protocol.commands.add(u'seek', songpos=protocol.UINT, seconds=protocol.UINT)\\ndef seek(context, songpos, seconds):\",\"targets\":\"\\\"\\\"\\\"*musicpd.org, playback section:*\\n ``seek {SONGPOS} {TIME}``\\n Seeks to the position ``TIME`` (in seconds) of entry ``SONGPOS`` in\\n the playlist.\\n *Droid MPD:*\\n - issues ``seek 1 120`` without quotes around the arguments.\\n \\\"\\\"\\\"\\n tl_track = context.core.playback.get_current_tl_track().get()\\n if (context.core.tracklist.index(tl_track).get() != songpos):\\n play(context, songpos)\\n context.core.playback.seek((seconds * 1000)).get()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_view(request):\\n\\n ''''A simple view that expects a GET request, and returns a rendered template'\\n '''\",\"targets\":\"t = Template('This is a test. {{ var }} is the value.', name='GET Template')\\n c = Context({'var': request.GET.get('var', 42)})\\n return HttpResponse(t.render(c))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from patsy.constraint import linear_constraint\\n exog_names = model_results.model.exog_names\\n LC = linear_constraint(test_formula, exog_names)\\n return LC\\n\\n\\nWhat's a good function header?\",\"targets\":\"def make_hypotheses_matrices(model_results, test_formula):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@preloaderStop\\ndef successMessage(message):\\n\\n ''''Displaying a message.'\\n '''\",\"targets\":\"printLine(message, '\\\\n')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def extract_cookies_to_jar(jar, request, response):\",\"targets\":\"\\\"\\\"\\\"Extract the cookies from the response into a CookieJar.\\n :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)\\n :param request: our own requests.Request object\\n :param response: urllib3.HTTPResponse object\\n \\\"\\\"\\\"\\n req = MockRequest(request)\\n res = MockResponse(response._original_response.msg)\\n jar.extract_cookies(res, req)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef chunk(data, index):\\n\\n ''''Split a string into two parts at the input index.'\\n '''\",\"targets\":\"return (data[:index], data[index:])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not isinstance(time, integer_types)):\\n raise SaltInvocationError(\\\"'time' must be an integer\\\")\\n if (not isinstance(min_compress_len, integer_types)):\\n raise SaltInvocationError(\\\"'min_compress_len' must be an integer\\\")\\n conn = _connect(host, port)\\n stats = conn.get_stats()\\n return conn.replace(key, value, time=time, min_compress_len=min_compress_len)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def replace(key, value, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def CMO(ds, count, timeperiod=(- (2 ** 31))):\",\"targets\":\"\\\"\\\"\\\"Chande Momentum Oscillator\\n \\\"\\\"\\\"\\n return call_talib_with_ds(ds, count, talib.CMO, timeperiod)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __methodDict(cls, _dict):\",\"targets\":\"\\\"\\\"\\\"helper function for Scrolled Canvas\\n \\\"\\\"\\\"\\n baseList = list(cls.__bases__)\\n baseList.reverse()\\n for _super in baseList:\\n __methodDict(_super, _dict)\\n for (key, value) in cls.__dict__.items():\\n if (type(value) == types.FunctionType):\\n _dict[key] = value\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _generatePermEncoderStr(options, encoderDict):\",\"targets\":\"\\\"\\\"\\\"Generate the string that defines the permutations to apply for a given\\n encoder.\\n Parameters:\\n options: experiment params\\n encoderDict: the encoder dict, which gets placed into the description.py\\n For example, if the encoderDict contains:\\n \\\\consumption\\\\: {\\n \\\\clipInput\\\\: True,\\n \\\\fieldname\\\\: u\\\\consumption\\\\,\\n \\\\n\\\\: 100,\\n \\\\name\\\\: u\\\\consumption\\\\,\\n \\\\type\\\\: \\\\AdaptiveScalarEncoder\\\\,\\n \\\\w\\\\: 21},\\n The return string will contain:\\n \\\"PermuteEncoder(fieldName=\\\\consumption\\\\,\\n encoderClass=\\\\AdaptiveScalarEncoder\\\\,\\n w=21,\\n n=PermuteInt(28, 521),\\n clipInput=True)\\\"\\n \\\"\\\"\\\"\\n permStr = ''\\n if encoderDict.get('classifierOnly', False):\\n permStr = 'dict('\\n for (key, value) in encoderDict.items():\\n if (key == 'name'):\\n continue\\n if ((key == 'n') and (encoderDict['type'] != 'SDRCategoryEncoder')):\\n permStr += ('n=PermuteInt(%d, %d), ' % ((encoderDict['w'] + 7), (encoderDict['w'] + 500)))\\n elif issubclass(type(value), basestring):\\n permStr += (\\\"%s='%s', \\\" % (key, value))\\n else:\\n permStr += ('%s=%s, ' % (key, value))\\n permStr += ')'\\n elif (encoderDict['type'] in ['ScalarSpaceEncoder', 'AdaptiveScalarEncoder', 'ScalarEncoder', 'LogEncoder']):\\n permStr = 'PermuteEncoder('\\n for (key, value) in encoderDict.items():\\n if (key == 'fieldname'):\\n key = 'fieldName'\\n elif (key == 'type'):\\n key = 'encoderClass'\\n elif (key == 'name'):\\n continue\\n if (key == 'n'):\\n permStr += ('n=PermuteInt(%d, %d), ' % ((encoderDict['w'] + 1), (encoderDict['w'] + 500)))\\n elif (key == 'runDelta'):\\n if (value and (not ('space' in encoderDict))):\\n permStr += ('space=PermuteChoices([%s,%s]), ' % (_quoteAndEscape('delta'), _quoteAndEscape('absolute')))\\n encoderDict.pop('runDelta')\\n elif issubclass(type(value), basestring):\\n permStr += (\\\"%s='%s', \\\" % (key, value))\\n else:\\n permStr += ('%s=%s, ' % (key, value))\\n permStr += ')'\\n elif (encoderDict['type'] in ['SDRCategoryEncoder']):\\n permStr = 'PermuteEncoder('\\n for (key, value) in encoderDict.items():\\n if (key == 'fieldname'):\\n key = 'fieldName'\\n elif (key == 'type'):\\n key = 'encoderClass'\\n elif (key == 'name'):\\n continue\\n if issubclass(type(value), basestring):\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Deserializer(stream_or_string, **options):\\n\\n ''''Deserialize a stream or string of JSON data.\\n Note: no change from Django version,\\n but needed to import here to use the versioned python deserializer\\n (see the import at the top for PythonDeserializer)'\\n '''\",\"targets\":\"if isinstance(stream_or_string, basestring):\\n stream = StringIO(stream_or_string)\\n else:\\n stream = stream_or_string\\n try:\\n for obj in PythonDeserializer(simplejson.load(stream), **options):\\n (yield obj)\\n except GeneratorExit:\\n raise\\n except Exception as e:\\n raise DeserializationError(e)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef MakeResponse(code=500, data=''):\\n\\n ''''A helper for creating a HTTPError exception.'\\n '''\",\"targets\":\"response = requests.Response()\\n response.status_code = code\\n response._content = data\\n return response\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@when(u'we send \\\"\\\\\\\\?\\\" command')\\ndef step_send_help(context):\",\"targets\":\"\\\"\\\"\\\"Send \\\\?\\n to see help.\\n \\\"\\\"\\\"\\n context.cli.sendline(u'\\\\\\\\?')\\n wrappers.expect_exact(context, (context.conf[u'pager_boundary'] + u'\\\\r\\\\n'), timeout=5)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from django.contrib.staticfiles.templatetags import staticfiles\\n if (mod == 'static'):\\n return staticfiles.static(filename)\\n return ''\\n\\n\\nWhat's a good function header?\",\"targets\":\"def url_for(mod, filename):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (str_len,) = struct.unpack('>I', data[:4])\\n return (data[4:(4 + str_len)], data[(4 + str_len):])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _read_next_string(data):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef isAlphanum(c):\\n\\n ''''return true if the character is a letter, digit, underscore,\\n dollar sign, or non-ASCII character.'\\n '''\",\"targets\":\"return (((c >= 'a') and (c <= 'z')) or ((c >= '0') and (c <= '9')) or ((c >= 'A') and (c <= 'Z')) or (c == '_') or (c == '$') or (c == '\\\\\\\\') or ((c is not None) and (ord(c) > 126)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef increment_lineno(node, n=1):\\n\\n ''''Increment the line number of each node in the tree starting at *node* by *n*.\\n This is useful to \\\"move code\\\" to a different location in a file.'\\n '''\",\"targets\":\"for child in walk(node):\\n if ('lineno' in child._attributes):\\n child.lineno = (getattr(child, 'lineno', 0) + n)\\n return node\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (np.abs(mu).max() > 1.0):\\n return 1.0\\n _compose_linear_fitting_data(mu, u)\\n (u['uu'], u['sing'], u['vv']) = linalg.svd(u['M'])\\n u['resi'][:] = u['y'][:]\\n for p in range((u['nfit'] - 1)):\\n dot = np.dot(u['uu'][p], u['y'])\\n for k in range((u['nterms'] - 1)):\\n u['resi'][k] = (u['resi'][k] - (u['uu'][(p, k)] * dot))\\n return np.dot(u['resi'], u['resi'])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _one_step(mu, u):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def eat_descriptor(descr):\",\"targets\":\"\\\"\\\"\\\"Read head of a field\\/method descriptor. Returns a pair of strings, where\\n the first one is a human-readable string representation of the first found\\n type, and the second one is the tail of the parameter.\\n \\\"\\\"\\\"\\n array_dim = 0\\n while (descr[0] == '['):\\n array_dim += 1\\n descr = descr[1:]\\n if (descr[0] == 'L'):\\n try:\\n end = descr.find(';')\\n except:\\n raise ParserError(('Not a valid descriptor string: ' + descr))\\n type = descr[1:end]\\n descr = descr[end:]\\n else:\\n global code_to_type_name\\n try:\\n type = code_to_type_name[descr[0]]\\n except KeyError:\\n raise ParserError(('Not a valid descriptor string: %s' % descr))\\n return ((type.replace('\\/', '.') + (array_dim * '[]')), descr[1:])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_free_namespace_port(protocol, namespace=None, start=1024, end=None):\\n\\n ''''Return an unused port from given namespace\\n WARNING: This function returns a port that is free at the execution time of\\n this function. If this port is used later for binding then there\\n is a potential danger that port will be no longer free. It\\\\'s up to\\n the programmer to handle error if port is already in use.\\n :param protocol: Return free port for given protocol. Supported protocols\\n are \\\\'tcp\\\\' and \\\\'udp\\\\'.\\n :param namespace: Namespace in which free port has to be returned.\\n :param start: The starting port number.\\n :param end: The ending port number (free port that is returned would be\\n between (start, end) values.'\\n '''\",\"targets\":\"if (protocol == n_const.PROTO_NAME_TCP):\\n param = '-tna'\\n elif (protocol == n_const.PROTO_NAME_UDP):\\n param = '-una'\\n else:\\n raise ValueError(('Unsupported protocol %s' % protocol))\\n ip_wrapper = ip_lib.IPWrapper(namespace=namespace)\\n output = ip_wrapper.netns.execute(['ss', param])\\n used_ports = _get_source_ports_from_ss_output(output)\\n return get_unused_port(used_ports, start, end)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef RGS_generalized(m):\\n\\n ''''Computes the m + 1 generalized unrestricted growth strings\\n and returns them as rows in matrix.\\n Examples\\n >>> from sympy.combinatorics.partitions import RGS_generalized\\n >>> RGS_generalized(6)\\n Matrix([\\n [ 1, 1, 1, 1, 1, 1, 1],\\n [ 1, 2, 3, 4, 5, 6, 0],\\n [ 2, 5, 10, 17, 26, 0, 0],\\n [ 5, 15, 37, 77, 0, 0, 0],\\n [ 15, 52, 151, 0, 0, 0, 0],\\n [ 52, 203, 0, 0, 0, 0, 0],\\n [203, 0, 0, 0, 0, 0, 0]])'\\n '''\",\"targets\":\"d = zeros((m + 1))\\n for i in range(0, (m + 1)):\\n d[(0, i)] = 1\\n for i in range(1, (m + 1)):\\n for j in range(m):\\n if (j <= (m - i)):\\n d[(i, j)] = ((j * d[((i - 1), j)]) + d[((i - 1), (j + 1))])\\n else:\\n d[(i, j)] = 0\\n return d\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __virtual__():\",\"targets\":\"\\\"\\\"\\\"Only load if zc.buildout libs available\\n \\\"\\\"\\\"\\n return __virtualname__\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def group_from(type):\",\"targets\":\"\\\"\\\"\\\"Get the group part of an event type name.\\n Example:\\n >>> group_from(\\\\task-sent\\\\)\\n \\\\task\\\\\\n >>> group_from(\\\\custom-my-event\\\\)\\n \\\\custom\\\\\\n \\\"\\\"\\\"\\n return type.split(u'-', 1)[0]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef add_move(move):\\n\\n ''''Add an item to six.moves.'\\n '''\",\"targets\":\"setattr(_MovedItems, move.name, move)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def connect(client=None):\",\"targets\":\"\\\"\\\"\\\"Construct a DB-API connection to Google BigQuery.\\n :type client: :class:`~google.cloud.bigquery.Client`\\n :param client:\\n (Optional) A client used to connect to BigQuery. If not passed, a\\n client is created using default options inferred from the environment.\\n :rtype: :class:`~google.cloud.bigquery.dbapi.Connection`\\n :returns: A new DB-API connection to BigQuery.\\n \\\"\\\"\\\"\\n if (client is None):\\n client = bigquery.Client()\\n return Connection(client)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_makefile_filename():\\n\\n ''''Return the path of the Makefile.'\\n '''\",\"targets\":\"if _PYTHON_BUILD:\\n return os.path.join(_PROJECT_BASE, 'Makefile')\\n if hasattr(sys, 'abiflags'):\\n config_dir_name = ('config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags))\\n else:\\n config_dir_name = 'config'\\n return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if response.has_header('Vary'):\\n vary_headers = cc_delim_re.split(response['Vary'])\\n else:\\n vary_headers = []\\n existing_headers = {header.lower() for header in vary_headers}\\n additional_headers = [newheader for newheader in newheaders if (newheader.lower() not in existing_headers)]\\n response['Vary'] = ', '.join((vary_headers + additional_headers))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def patch_vary_headers(response, newheaders):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def c12_mapping(char):\",\"targets\":\"\\\"\\\"\\\"Map non-ASCII whitespace to spaces.\\n \\\"\\\"\\\"\\n return (u' ' if stringprep.in_table_c12(char) else None)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n g = Expression.fromstring(argument_pair[0])\\n alist = [lp.parse(a) for a in argument_pair[1]]\\n m = MaceCommand(g, assumptions=alist)\\n m.build_model()\\n for a in alist:\\n print((' %s' % a))\\n print(('|- %s: %s\\\\n' % (g, m.build_model())))\\n for format in ['standard', 'portable', 'xml', 'cooked']:\\n spacer()\\n print((\\\"Using '%s' format\\\" % format))\\n spacer()\\n print(m.model(format=format))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_transform_output(argument_pair):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_info(inst):\",\"targets\":\"\\\"\\\"\\\"Retrieves instance template information\\n \\\"\\\"\\\"\\n return {'name': inst.name, 'extra': inst.extra}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n lgrp = __salt__['group.info'](name)\\n if (not lgrp):\\n return False\\n change = {}\\n if gid:\\n if (lgrp['gid'] != gid):\\n change['gid'] = gid\\n if members:\\n if (set(lgrp['members']) ^ set(members)):\\n change['members'] = members\\n if addusers:\\n users_2add = [user for user in addusers if (user not in lgrp['members'])]\\n if users_2add:\\n change['addusers'] = users_2add\\n if delusers:\\n users_2del = [user for user in delusers if (user in lgrp['members'])]\\n if users_2del:\\n change['delusers'] = users_2del\\n return change\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _changes(name, gid=None, addusers=None, delusers=None, members=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef del_tags(name=None, kwargs=None, call=None, instance_id=None, resource_id=None):\\n\\n ''''Delete tags for a resource. Normally a VM name or instance_id is passed in,\\n but a resource_id may be passed instead. If both are passed in, the\\n instance_id will be used.\\n CLI Examples:\\n .. code-block:: bash\\n salt-cloud -a del_tags mymachine tags=mytag,\\n salt-cloud -a del_tags mymachine tags=tag1,tag2,tag3\\n salt-cloud -a del_tags resource_id=vol-3267ab32 tags=tag1,tag2,tag3'\\n '''\",\"targets\":\"if (kwargs is None):\\n kwargs = {}\\n if ('tags' not in kwargs):\\n raise SaltCloudSystemExit('A tag or tags must be specified using tags=list,of,tags')\\n if ((not name) and ('resource_id' in kwargs)):\\n instance_id = kwargs['resource_id']\\n del kwargs['resource_id']\\n if (not instance_id):\\n instance_id = _get_node(name)['instanceId']\\n params = {'Action': 'DeleteTags', 'ResourceId.1': instance_id}\\n for (idx, tag) in enumerate(kwargs['tags'].split(',')):\\n params['Tag.{0}.Key'.format(idx)] = tag\\n aws.query(params, setname='tagSet', location=get_location(), provider=get_provider(), opts=__opts__, sigver='4')\\n if resource_id:\\n return get_tags(resource_id=resource_id)\\n else:\\n return get_tags(instance_id=instance_id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Only load if influxdb lib is present'\\n '''\",\"targets\":\"if HAS_INFLUXDB:\\n return __virtualname__\\n return (False, 'The influxdb execution module could not be loaded:influxdb library not available.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def decorator(func):\\n _checks[name] = func\\n return func\\n if func:\\n return decorator(func)\\n return decorator\\n\\n\\nWhat's a good function header?\",\"targets\":\"def register(name, func=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@patch('coursera.api.get_page')\\ndef test_list_courses(get_page, course):\",\"targets\":\"\\\"\\\"\\\"Test course listing method.\\n \\\"\\\"\\\"\\n get_page.side_effect = [json.loads(slurp_fixture('json\\/list-courses-input.json'))]\\n expected_output = json.loads(slurp_fixture('json\\/list-courses-output.json'))\\n expected_output = expected_output['courses']\\n output = course.list_courses()\\n assert (expected_output == output)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef long_substr(data):\\n\\n ''''https:\\/\\/stackoverflow.com\\/a\\/2894073'\\n '''\",\"targets\":\"substr = ''\\n if ((len(data) > 1) and (len(data[0]) > 0)):\\n for i in range(len(data[0])):\\n for j in range(((len(data[0]) - i) + 1)):\\n if ((j > len(substr)) and is_substr(data[0][i:(i + j)], data)):\\n substr = data[0][i:(i + j)]\\n return substr\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def api_idor(SCAN_REQUESTS, URLS_CONF):\",\"targets\":\"\\\"\\\"\\\"1. Without Cookie and Auth headers\\n 2. With a Valid Cookie and Auth header of another user\\n TO-DO:\\n Add feature to allow user to select session parameter\\n \\\"\\\"\\\"\\n global STATUS, ACCEPTED_CONTENT_TYPE\\n print '\\\\n[INFO] Performing API IDOR Checks'\\n result = []\\n try:\\n (LOGIN_API, PIN_API, REGISTER_API, LOGOUT_API) = getAPI(URLS_CONF)\\n LOGIN_API_COMBINED = (LOGIN_API + PIN_API)\\n LOGIN_API_COMBINED = list(set(LOGIN_API_COMBINED))\\n (url_n_cookie_pair, url_n_header_pair) = getAuthTokensTwoUser(SCAN_REQUESTS, URLS_CONF)\\n \\\"'\\\\n IDOR Checks starts now.\\\\n \\\"\\n for request in SCAN_REQUESTS:\\n url = request['url']\\n if ((url not in LOGIN_API_COMBINED) and (url not in REGISTER_API)):\\n req1 = req_cookie = req_authheader = request\\n res1 = HTTP_Request(req1)\\n if res1:\\n if res1.headers:\\n y = 'nil'\\n if ('Content-Type' in res1.headers):\\n y = 'Content-Type'\\n elif ('content-type' in res1.headers):\\n y = 'content-type'\\n if (y != 'nil'):\\n content_typ = res1.headers[y]\\n if (';' in content_typ):\\n content_typ = content_typ.split(';')[0]\\n if (content_typ in ACCEPTED_CONTENT_TYPE):\\n if (getProtocolDomain(url) in url_n_cookie_pair):\\n cookie = 'nil'\\n if ('Cookie' in req_cookie['headers']):\\n cookie = 'Cookie'\\n elif ('cookie' in req_cookie['headers']):\\n cookie = 'cookie'\\n if (cookie != 'nil'):\\n cookies_pair = url_n_cookie_pair[getProtocolDomain(url)]\\n for (cookie1, cookie2) in cookies_pair.items():\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def converter(self, spec_like, *args, **kwargs):\\n if (not isinstance(spec_like, spack.spec.Spec)):\\n spec_like = spack.spec.Spec(spec_like)\\n return function(self, spec_like, *args, **kwargs)\\n return converter\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _autospec(function):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef expose(func=None, alias=None):\\n\\n ''''Expose the function, optionally providing an alias or set of aliases.'\\n '''\",\"targets\":\"def expose_(func):\\n func.exposed = True\\n if (alias is not None):\\n if isinstance(alias, basestring):\\n parents[alias.replace('.', '_')] = func\\n else:\\n for a in alias:\\n parents[a.replace('.', '_')] = func\\n return func\\n import sys\\n import types\\n if isinstance(func, (types.FunctionType, types.MethodType)):\\n if (alias is None):\\n func.exposed = True\\n return func\\n else:\\n parents = sys._getframe(1).f_locals\\n return expose_(func)\\n elif (func is None):\\n if (alias is None):\\n parents = sys._getframe(1).f_locals\\n return expose_\\n else:\\n parents = sys._getframe(1).f_locals\\n return expose_\\n else:\\n parents = sys._getframe(1).f_locals\\n alias = func\\n return expose_\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n name = getattr(obj, 'name', None)\\n if (name and isinstance(name, basestring) and (name[0] != '<') and (name[(-1)] != '>')):\\n return os.path.basename(name)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def guess_filename(obj):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getCraftedTextFromText(text, repository=None):\",\"targets\":\"\\\"\\\"\\\"Preface and convert an svg text.\\n \\\"\\\"\\\"\\n if gcodec.isProcedureDoneOrFileIsEmpty(text, 'preface'):\\n return text\\n if (repository == None):\\n repository = settings.getReadRepository(PrefaceRepository())\\n return PrefaceSkein().getCraftedGcode(repository, text)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getargvalues(frame):\",\"targets\":\"\\\"\\\"\\\"Get information about arguments passed into a particular frame.\\n A tuple of four things is returned: (args, varargs, varkw, locals).\\n \\\\args\\\\ is a list of the argument names (it may contain nested lists).\\n \\\\varargs\\\\ and \\\\varkw\\\\ are the names of the * and ** arguments or None.\\n \\\\locals\\\\ is the locals dictionary of the given frame.\\n \\\"\\\"\\\"\\n (args, varargs, varkw) = getargs(frame.f_code)\\n return ArgInfo(args, varargs, varkw, frame.f_locals)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _arrays_to_mgr(arrays, arr_names, index, columns, dtype=None):\",\"targets\":\"\\\"\\\"\\\"Segregate Series based on type and coerce into matrices.\\n Needs to handle a lot of exceptional cases.\\n \\\"\\\"\\\"\\n if (index is None):\\n index = extract_index(arrays)\\n else:\\n index = _ensure_index(index)\\n arrays = _homogenize(arrays, index, dtype)\\n axes = [_ensure_index(columns), _ensure_index(index)]\\n return create_block_manager_from_arrays(arrays, arr_names, axes)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n batch_job = GetBatchJob(client, batch_job_id)\\n if (batch_job['status'] == 'CANCELED'):\\n raise Exception(('Batch Job with ID \\\"%s\\\" was canceled before completing.' % batch_job_id))\\n poll_attempt = 0\\n while ((poll_attempt in range(max_poll_attempts)) and (batch_job['status'] in PENDING_STATUSES)):\\n sleep_interval = ((30 * (2 ** poll_attempt)) + (random.randint(0, 10000) \\/ 1000))\\n print ('Batch Job not ready, sleeping for %s seconds.' % sleep_interval)\\n time.sleep(sleep_interval)\\n batch_job = GetBatchJob(client, batch_job_id)\\n poll_attempt += 1\\n if ('downloadUrl' in batch_job):\\n url = batch_job['downloadUrl']['url']\\n print ('Batch Job with Id \\\"%s\\\", Status \\\"%s\\\", and DownloadUrl \\\"%s\\\" ready.' % (batch_job['id'], batch_job['status'], url))\\n return url\\n print ('BatchJob with ID \\\"%s\\\" is being canceled because it was in a pending state after polling %d times.' % (batch_job_id, max_poll_attempts))\\n CancelBatchJob(client, batch_job)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, max_poll_attempts=MAX_POLL_ATTEMPTS):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def equateZ(point, returnValue):\",\"targets\":\"\\\"\\\"\\\"Get equation for rectangular z.\\n \\\"\\\"\\\"\\n point.z = returnValue\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Only works on Windows systems.'\\n '''\",\"targets\":\"if (not salt.utils.platform.is_windows()):\\n return (False, 'Module win_snmp: Requires Windows')\\n if (not __salt__['reg.read_value'](_HKEY, _SNMP_KEY)['success']):\\n return (False, 'Module win_snmp: SNMP not installed')\\n return __virtualname__\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n kit_dir = op.join(io_dir, 'kit', 'tests', 'data')\\n sqd_path = op.join(kit_dir, 'test.sqd')\\n mrk_path = op.join(kit_dir, 'test_mrk.sqd')\\n elp_path = op.join(kit_dir, 'test_elp.txt')\\n hsp_path = op.join(kit_dir, 'test_hsp.txt')\\n raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)\\n with warnings.catch_warnings(record=True):\\n assert_raises(RuntimeError, maxwell_filter, raw_kit)\\n raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True)\\n _assert_n_free(raw_sss, 65, 65)\\n raw_sss_auto = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True, mag_scale='auto')\\n assert_allclose(raw_sss._data, raw_sss_auto._data)\\n with warnings.catch_warnings(record=True):\\n with catch_logging() as log_file:\\n assert_raises(RuntimeError, maxwell_filter, raw_kit, ignore_ref=True, regularize=None)\\n raw_sss = maxwell_filter(raw_kit, origin='auto', ignore_ref=True, bad_condition='warning', verbose='warning')\\n log_file = log_file.getvalue()\\n assert_true(('badly conditioned' in log_file))\\n assert_true(('more than 20 mm from' in log_file))\\n _assert_n_free(raw_sss, 28, 34)\\n with warnings.catch_warnings(record=True):\\n with catch_logging() as log_file:\\n raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True, bad_condition='warning', regularize=None, verbose='warning')\\n log_file = log_file.getvalue()\\n assert_true(('badly conditioned' in log_file))\\n _assert_n_free(raw_sss, 80)\\n with warnings.catch_warnings(record=True):\\n with catch_logging() as log_file:\\n raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True, verbose=True)\\n log_file = log_file.getvalue()\\n assert_true(('badly conditioned' not in log_file))\\n _assert_n_free(raw_sss, 65)\\n bti_dir = op.join(io_dir, 'bti', 'tests', 'data')\\n bti_pdf = op.join(bti_dir, 'test_pdf_linux')\\n bti_config = op.join(bti_dir, 'test_config_linux')\\n bti_hs =...\\n\\nWhat's a good function header?\",\"targets\":\"@slow_test\\ndef test_other_systems():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n import frappe\\n from jinja2 import TemplateSyntaxError\\n jenv = get_jenv()\\n try:\\n jenv.from_string(html)\\n except TemplateSyntaxError as e:\\n frappe.msgprint(u'Line {}: {}'.format(e.lineno, e.message))\\n frappe.throw(frappe._(u'Syntax error in template'))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def validate_template(html):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n _active.value = gettext_module.NullTranslations()\\n _active.value.to_language = (lambda *args: None)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def deactivate_all():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef main(argv, version=DEFAULT_VERSION):\\n\\n ''''Install or upgrade setuptools and EasyInstall'\\n '''\",\"targets\":\"try:\\n import setuptools\\n except ImportError:\\n egg = None\\n try:\\n egg = download_setuptools(version, delay=0)\\n sys.path.insert(0, egg)\\n from setuptools.command.easy_install import main\\n return main((list(argv) + [egg]))\\n finally:\\n if (egg and os.path.exists(egg)):\\n os.unlink(egg)\\n else:\\n if (setuptools.__version__ == '0.0.1'):\\n use_setuptools(version)\\n req = ('setuptools>=' + version)\\n import pkg_resources\\n try:\\n pkg_resources.require(req)\\n except pkg_resources.VersionConflict:\\n try:\\n from setuptools.command.easy_install import main\\n except ImportError:\\n from easy_install import main\\n main((list(argv) + [download_setuptools(delay=0)]))\\n sys.exit(0)\\n else:\\n if argv:\\n from setuptools.command.easy_install import main\\n main(argv)\\n else:\\n print 'Setuptools version', version, 'or greater has been installed.'\\n print '(Run \\\"ez_setup.py -U setuptools\\\" to reinstall or upgrade.)'\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def failureFromJSON(failureDict):\",\"targets\":\"\\\"\\\"\\\"Load a L{Failure} from a dictionary deserialized from JSON.\\n @param failureDict: a JSON-deserialized object like one previously returned\\n by L{failureAsJSON}.\\n @type failureDict: L{dict} mapping L{unicode} to attributes\\n @return: L{Failure}\\n @rtype: L{Failure}\\n \\\"\\\"\\\"\\n newFailure = getattr(Failure, '__new__', None)\\n if (newFailure is None):\\n f = types.InstanceType(Failure)\\n else:\\n f = newFailure(Failure)\\n if (not _PY3):\\n failureDict = asBytes(failureDict)\\n typeInfo = failureDict['type']\\n failureDict['type'] = type(typeInfo['__name__'], (), typeInfo)\\n f.__dict__ = failureDict\\n return f\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n a = AddressList(address)\\n lst = a.addresslist\\n if (not lst):\\n return (None, None)\\n return lst[0]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parseaddr(address):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _CheckDocumentId(doc_id):\",\"targets\":\"\\\"\\\"\\\"Checks doc_id is a valid document identifier, and returns it.\\n Document ids must be visible printable ASCII and not start with \\\\!\\\\.\\n \\\"\\\"\\\"\\n _ValidateString(doc_id, 'doc_id', MAXIMUM_DOCUMENT_ID_LENGTH)\\n _ValidateVisiblePrintableAsciiNotReserved(doc_id, 'doc_id')\\n return doc_id\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n level_tags = constants.DEFAULT_TAGS.copy()\\n level_tags.update(getattr(settings, 'MESSAGE_TAGS', {}))\\n return level_tags\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_level_tags():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_nexusvlan_binding(vlan_id, switch_ip):\\n\\n ''''Lists a vlan and switch binding'\\n '''\",\"targets\":\"LOG.debug(_('get_nexusvlan_binding() called'))\\n session = db.get_session()\\n try:\\n binding = session.query(nexus_models_v2.NexusPortBinding).filter_by(vlan_id=vlan_id).filter_by(switch_ip=switch_ip).all()\\n return binding\\n except exc.NoResultFound:\\n raise c_exc.NexusPortBindingNotFound(vlan_id=vlan_id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n kwargs = {}\\n if name:\\n kwargs['name'] = name\\n return url(('^%s$' % path), views.commonplace, {'repo': 'fireplace'}, **kwargs)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def fireplace_route(path, name=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _MatchPostfix(postfix_props, index_props):\\n\\n ''''Matches a postfix constraint with an existing index.\\n postfix_props constraints are specified through a list of:\\n - sets of string: any order any direction;\\n - list of tuples(string, direction): the given order, and, if specified, the\\n given direction.\\n For example:\\n [set(\\\\'A\\\\', \\\\'B\\\\'), [(\\\\'C\\\\', None), (\\\\'D\\\\', ASC)]]\\n matches:\\n [(\\\\'F\\\\', ASC), (\\\\'B\\\\', ASC), (\\\\'A\\\\', DESC), (\\\\'C\\\\', DESC), (\\\\'D\\\\', ASC)]\\n with a return value of [(\\\\'F\\\\', ASC)], but does not match:\\n [(\\\\'F\\\\', ASC), (\\\\'A\\\\', DESC), (\\\\'C\\\\', DESC), (\\\\'D\\\\', ASC)]\\n [(\\\\'B\\\\', ASC), (\\\\'F\\\\', ASC), (\\\\'A\\\\', DESC), (\\\\'C\\\\', DESC), (\\\\'D\\\\', ASC)]\\n [(\\\\'F\\\\', ASC), (\\\\'B\\\\', ASC), (\\\\'A\\\\', DESC), (\\\\'C\\\\', DESC), (\\\\'D\\\\', DESC)]\\n Args:\\n postfix_props: A tuple of sets and lists, as output by\\n CompositeIndexForQuery. They should define the requirements for the\\n postfix of the index.\\n index_props: A list of tuples (property_name, property_direction), that\\n define the index to try and match.\\n Returns:\\n The list of tuples that define the prefix properties in the given index.\\n None if the constraints could not be satisfied.'\\n '''\",\"targets\":\"index_props_rev = reversed(index_props)\\n for property_group in reversed(postfix_props):\\n index_group_iter = itertools.islice(index_props_rev, len(property_group))\\n if isinstance(property_group, (frozenset, set)):\\n index_group = set((prop for (prop, _) in index_group_iter))\\n if (index_group != property_group):\\n return None\\n else:\\n index_group = list(index_group_iter)\\n if (len(index_group) != len(property_group)):\\n return None\\n for ((index_prop, index_dir), (prop, direction)) in itertools.izip(index_group, reversed(property_group)):\\n if ((index_prop != prop) or (direction and (index_dir != direction))):\\n return None\\n remaining = list(index_props_rev)\\n remaining.reverse()\\n return remaining\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def cloudnetwork(vm_):\",\"targets\":\"\\\"\\\"\\\"Determine if we should use an extra network to bootstrap\\n Either \\\\False\\\\ (default) or \\\\True\\\\.\\n \\\"\\\"\\\"\\n return config.get_cloud_config_value('cloudnetwork', vm_, __opts__, default=False, search_global=False)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Timer(*args, **kwargs):\\n\\n ''''Factory function to create a Timer object.\\n Timers call a function after a specified number of seconds:\\n t = Timer(30.0, f, args=[], kwargs={})\\n t.start()\\n t.cancel() # stop the timer\\\\'s action if it\\\\'s still waiting'\\n '''\",\"targets\":\"return _Timer(*args, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def changes_command(args):\",\"targets\":\"\\\"\\\"\\\"List all changes records for a zone.\\n \\\"\\\"\\\"\\n changes = list_changes(args.project_id, args.name)\\n for change in changes:\\n print change\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_connection_dropped(conn):\\n\\n ''''Returns True if the connection is dropped and should be closed.\\n :param conn:\\n :class:`httplib.HTTPConnection` object.\\n Note: For platforms like AppEngine, this will always return ``False`` to\\n let the platform handle connection recycling transparently for us.'\\n '''\",\"targets\":\"sock = getattr(conn, 'sock', False)\\n if (not sock):\\n return False\\n if (not poll):\\n if (not select):\\n return False\\n try:\\n return select([sock], [], [], 0.0)[0]\\n except SocketError:\\n return True\\n p = poll()\\n p.register(sock, POLLIN)\\n for (fno, ev) in p.poll(0.0):\\n if (fno == sock.fileno()):\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@helpers.intercept_errors(errors.UserAPIInternalError, ignore_errors=[errors.UserAPIRequestError])\\ndef activate_account(activation_key):\\n\\n ''''Activate a user\\\\'s account.\\n Args:\\n activation_key (unicode): The activation key the user received via email.\\n Returns:\\n None\\n Raises:\\n errors.UserNotAuthorized\\n errors.UserAPIInternalError: the operation failed due to an unexpected error.'\\n '''\",\"targets\":\"try:\\n registration = Registration.objects.get(activation_key=activation_key)\\n except Registration.DoesNotExist:\\n raise errors.UserNotAuthorized\\n else:\\n registration.activate()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _launch_reaper(id, pid):\\n\\n ''''Start a process that will free a lock when process pid terminates'\\n '''\",\"targets\":\"from subprocess import Popen, PIPE\\n me = __file__\\n if me.endswith('.pyc'):\\n me = me[:(-1)]\\n myloc = os.path.dirname(me)\\n if (not myloc):\\n myloc = os.getcwd()\\n reaper_cmd = os.path.join(myloc, 'run_on_me_or_pid_quit')\\n Popen([reaper_cmd, str(pid), me, '--free', str(id)], stdout=open('\\/dev\\/null', 'w'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@constructor\\ndef prod(input, axis=None, dtype=None, keepdims=False, acc_dtype=None, no_zeros_in_input=False):\\n\\n ''''Computes the product along the given axis(es) of a tensor `input`.\\n When axis is None (the default value), the product is performed\\n over the flattened tensor.\\n For full documentation see ``tensor.elemwise.Prod``.\\n Parameters\\n keepdims: bool\\n If this is set to True, the axes which are reduced are left in\\n the result as dimensions with size one. With this option, the result\\n will broadcast correctly against the original tensor.'\\n '''\",\"targets\":\"out = elemwise.Prod(axis, dtype=dtype, acc_dtype=acc_dtype, no_zeros_in_input=no_zeros_in_input)(input)\\n if keepdims:\\n out = makeKeepDims(input, out, axis)\\n return out\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef discuss(r, **attr):\\n\\n ''''Custom Method to manage the discussion of a Post'\\n '''\",\"targets\":\"id = r.id\\n rheader = s3db.cms_rheader(r)\\n ckeditor = URL(c='static', f='ckeditor', args='ckeditor.js')\\n s3.scripts.append(ckeditor)\\n adapter = URL(c='static', f='ckeditor', args=['adapters', 'jquery.js'])\\n s3.scripts.append(adapter)\\n js = ''.join(('i18n.reply=\\\"', str(T('Reply')), '\\\"\\\\nvar img_path=S3.Ap.concat(\\\\'\\/static\\/img\\/jCollapsible\\/\\\\')\\\\nvar ck_config={toolbar:[[\\\\'Bold\\\\',\\\\'Italic\\\\',\\\\'-\\\\',\\\\'NumberedList\\\\',\\\\'BulletedList\\\\',\\\\'-\\\\',\\\\'Link\\\\',\\\\'Unlink\\\\',\\\\'-\\\\',\\\\'Smiley\\\\',\\\\'-\\\\',\\\\'Source\\\\',\\\\'Maximize\\\\']],toolbarCanCollapse:false,removePlugins:\\\\'elementspath\\\\'}\\\\nfunction comment_reply(id){\\\\n $(\\\\'#cms_comment_post_id__row\\\\').hide()\\\\n $(\\\\'#cms_comment_post_id__row1\\\\').hide()\\\\n $(\\\\'#comment-title\\\\').html(i18n.reply)\\\\n $(\\\\'#cms_comment_body\\\\').ckeditorGet().destroy()\\\\n $(\\\\'#cms_comment_body\\\\').ckeditor(ck_config)\\\\n $(\\\\'#comment-form\\\\').insertAfter($(\\\\'#comment-\\\\'+id))\\\\n $(\\\\'#cms_comment_parent\\\\').val(id)\\\\n var post_id=$(\\\\'#comment-\\\\'+id).attr(\\\\'post_id\\\\')\\\\n $(\\\\'#cms_comment_post_id\\\\').val(post_id)\\\\n}'))\\n s3.js_global.append(js)\\n response.view = 'cms\\/discuss.html'\\n return dict(rheader=rheader, id=id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_item_workdays(scorecard):\",\"targets\":\"\\\"\\\"\\\"Gets the number of days in this period\\n \\\"\\\"\\\"\\n supplier = frappe.get_doc(u'Supplier', scorecard.supplier)\\n total_item_days = frappe.db.sql(u'\\\\n DCTB DCTB DCTB SELECT\\\\n DCTB DCTB DCTB DCTB SUM(DATEDIFF( %(end_date)s, po_item.schedule_date) * (po_item.qty))\\\\n DCTB DCTB DCTB FROM\\\\n DCTB DCTB DCTB DCTB `tabPurchase Order Item` po_item,\\\\n DCTB DCTB DCTB DCTB `tabPurchase Order` po\\\\n DCTB DCTB DCTB WHERE\\\\n DCTB DCTB DCTB DCTB po.supplier = %(supplier)s\\\\n DCTB DCTB DCTB DCTB AND po_item.received_qty < po_item.qty\\\\n DCTB DCTB DCTB DCTB AND po_item.schedule_date BETWEEN %(start_date)s AND %(end_date)s\\\\n DCTB DCTB DCTB DCTB AND po_item.parent = po.name', {u'supplier': supplier.name, u'start_date': scorecard.start_date, u'end_date': scorecard.end_date}, as_dict=0)[0][0]\\n if (not total_item_days):\\n total_item_days = 0\\n return total_item_days\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if ((rhi == (rlo + 1)) and (chi == (clo + 1))):\\n return cellnameabs(rlo, clo)\\n return ('%s:%s' % (cellnameabs(rlo, clo), cellnameabs((rhi - 1), (chi - 1))))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def rangename2d(rlo, rhi, clo, chi):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):\\n\\n ''''A block of standard 2d convolutions.'\\n '''\",\"targets\":\"return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef incoming():\\n\\n ''''Incoming Shipments for Sites\\n Used from Requests rheader when looking at Transport Status'\\n '''\",\"targets\":\"return s3db.inv_incoming()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def inject_content_head_last(html, content):\",\"targets\":\"\\\"\\\"\\\"将文本内容插入到head的尟郚\\n :type html: str\\n :type content: str\\n :rtype: str\\n \\\"\\\"\\\"\\n head_end_pos = html.find('<\\/head')\\n if (head_end_pos == (-1)):\\n return html\\n return ((html[:head_end_pos] + content) + html[head_end_pos:])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n attributes = []\\n class_vars = []\\n metas = []\\n variables_seen = set()\\n for table in tables:\\n attributes.extend((v for v in table.domain.attributes if (v not in variables_seen)))\\n variables_seen.update(table.domain.attributes)\\n class_vars.extend((v for v in table.domain.class_vars if (v not in variables_seen)))\\n variables_seen.update(table.domain.class_vars)\\n metas.extend((v for v in table.domain.metas if (v not in variables_seen)))\\n variables_seen.update(table.domain.metas)\\n domain = Orange.data.Domain(attributes, class_vars, metas)\\n tables = [tab.transform(domain) for tab in tables]\\n return tables[0].concatenate(tables, axis=0)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def table_concat(tables):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n Distance.__dict__['_weights'].computed = False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _clear_weights():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if hasattr(shutil, 'which'):\\n return shutil.which(cmd, path=path)\\n elif ((path is None) and (os.environ.get('PATH') is None)):\\n return None\\n else:\\n return find_executable(cmd, path=path)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def which(cmd, path=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (len(a) != len(b)):\\n return False\\n result = 0\\n for (x, y) in zip(a, b):\\n result |= (ord(x) ^ ord(y))\\n return (result == 0)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def compare_hashes(a, b):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not result):\\n raise GEOSException(('Error encountered checking Coordinate Sequence returned from GEOS C function \\\"%s\\\".' % func.__name__))\\n return result\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_cs_ptr(result, func, cargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef almost_equal_ignore_nan(a, b, rtol=None, atol=None):\\n\\n ''''Test that two NumPy arrays are almost equal (ignoring NaN in either array).\\n Combines a relative and absolute measure of approximate eqality.\\n If either the relative or absolute check passes, the arrays are considered equal.\\n Including an absolute check resolves issues with the relative check where all\\n array values are close to zero.\\n Parameters\\n a : np.ndarray\\n b : np.ndarray\\n rtol : None or float\\n The relative threshold. Default threshold will be used if set to ``None``.\\n atol : None or float\\n The absolute threshold. Default threshold will be used if set to ``None``.'\\n '''\",\"targets\":\"a = np.copy(a)\\n b = np.copy(b)\\n nan_mask = np.logical_or(np.isnan(a), np.isnan(b))\\n a[nan_mask] = 0\\n b[nan_mask] = 0\\n return almost_equal(a, b, rtol, atol)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n f = open_file(filename, mode)\\n try:\\n return f.write(value)\\n finally:\\n f.close()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def write_file(filename, value, mode='w'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getopt(args, shortopts, longopts=[]):\",\"targets\":\"\\\"\\\"\\\"getopt(args, options[, long_options]) -> opts, args\\n Parses command line options and parameter list. args is the\\n argument list to be parsed, without the leading reference to the\\n running program. Typically, this means \\\"sys.argv[1:]\\\". shortopts\\n is the string of option letters that the script wants to\\n recognize, with options that require an argument followed by a\\n colon (i.e., the same format that Unix getopt() uses). If\\n specified, longopts is a list of strings with the names of the\\n long options which should be supported. The leading \\\\--\\\\\\n characters should not be included in the option name. Options\\n which require an argument should be followed by an equal sign\\n The return value consists of two elements: the first is a list of\\n (option, value) pairs; the second is the list of program arguments\\n left after the option list was stripped (this is a trailing slice\\n of the first argument). Each option-and-value pair returned has\\n the option as its first element, prefixed with a hyphen (e.g.,\\n \\\\-x\\\\), and the option argument as its second element, or an empty\\n string if the option has no argument. The options occur in the\\n list in the same order in which they were found, thus allowing\\n multiple occurrences. Long and short options may be mixed.\\n \\\"\\\"\\\"\\n opts = []\\n if (type(longopts) == type('')):\\n longopts = [longopts]\\n else:\\n longopts = list(longopts)\\n while (args and args[0].startswith('-') and (args[0] != '-')):\\n if (args[0] == '--'):\\n args = args[1:]\\n break\\n if args[0].startswith('--'):\\n (opts, args) = do_longs(opts, args[0][2:], longopts, args[1:])\\n else:\\n (opts, args) = do_shorts(opts, args[0][1:], shortopts, args[1:])\\n return (opts, args)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def generate_control(tests, kernels=None, platform=None, is_server=False, profilers=(), client_control_file='', profile_only=None, upload_kernel_config=False):\",\"targets\":\"\\\"\\\"\\\"Generate a control file for a sequence of tests.\\n :param tests A sequence of test control files to run.\\n :param kernels A sequence of kernel info dictionaries configuring which\\n kernels to boot for this job and other options for them\\n :param platform A platform object with a kernel_config attribute.\\n :param is_server bool, Is this a server control file rather than a client?\\n :param profilers A list of profiler objects to enable during the tests.\\n :param client_control_file Contents of a client control file to run as the\\n last test after everything in tests. Requires is_server=False.\\n :param profile_only bool, should this control file run all tests in\\n profile_only mode by default\\n :param upload_kernel_config: if enabled it will generate server control\\n file code that uploads the kernel config file to the client and\\n tells the client of the new (local) path when compiling the kernel;\\n the tests must be server side tests\\n :return: The control file text as a string.\\n \\\"\\\"\\\"\\n _sanity_check_generate_control(is_server=is_server, kernels=kernels, client_control_file=client_control_file, upload_kernel_config=upload_kernel_config)\\n control_file_text = ''\\n if kernels:\\n control_file_text = get_kernel_stanza(kernels, platform, is_server=is_server, upload_kernel_config=upload_kernel_config)\\n else:\\n control_file_text = EMPTY_TEMPLATE\\n (prepend, append) = _get_profiler_commands(profilers, is_server, profile_only)\\n control_file_text += get_tests_stanza(tests, is_server, prepend, append, client_control_file)\\n return control_file_text\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef cumsum(x, axis=None):\\n\\n ''''Return the cumulative sum of the elements along a given axis.\\n Wraping of numpy.cumsum.\\n Parameters\\n x\\n Input tensor variable.\\n axis\\n The axis along which the cumulative sum is computed.\\n The default (None) is to compute the cumsum over the flattened array.\\n .. versionadded:: 0.7'\\n '''\",\"targets\":\"return CumOp(axis=axis, mode='add')(x)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n input = numpy.asarray(input)\\n def derivative(input, axis, output, mode, cval, sigma, **kwargs):\\n order = ([0] * input.ndim)\\n order[axis] = 1\\n return gaussian_filter(input, sigma, order, output, mode, cval, **kwargs)\\n return generic_gradient_magnitude(input, derivative, output, mode, cval, extra_arguments=(sigma,), extra_keywords=kwargs)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@docfiller\\ndef gaussian_gradient_magnitude(input, sigma, output=None, mode='reflect', cval=0.0, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_ami_metadata():\\n\\n ''''Fetch ami metadata for the local instance. Returns a dict of \\\\'key\\\\':\\\\'value\\\\'. eg: \\\\'instance-id\\\\':\\\\'i-e7f7e69b\\\\'.'\\n '''\",\"targets\":\"res = {}\\n base_url = 'http:\\/\\/169.254.169.254\\/latest\\/meta-data'\\n instance_id = run(('curl %s\\/instance-id' % base_url))\\n assert re.match('i-[0-9a-f]{8}', instance_id)\\n res['instance-id'] = instance_id\\n return res\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef encode(body, binary=False, maxlinelen=76, eol=NL):\\n\\n ''''Encode with quoted-printable, wrapping at maxlinelen characters.\\n If binary is False (the default), end-of-line characters will be converted\\n to the canonical email end-of-line sequence \\\\r\\\\n. Otherwise they will\\n be left verbatim.\\n Each line of encoded text will end with eol, which defaults to \\\"\\\\n\\\". Set\\n this to \\\"\\\\r\\\\n\\\" if you will be using the result of this function directly\\n in an email.\\n Each line will be wrapped at, at most, maxlinelen characters (defaults to\\n 76 characters). Long lines will have the `soft linefeed\\\\' quoted-printable\\n character \\\"=\\\" appended to them, so the decoded text will be identical to\\n the original text.'\\n '''\",\"targets\":\"if (not body):\\n return body\\n if (not binary):\\n body = fix_eols(body)\\n encoded_body = ''\\n lineno = (-1)\\n lines = body.splitlines(1)\\n for line in lines:\\n if line.endswith(CRLF):\\n line = line[:(-2)]\\n elif (line[(-1)] in CRLF):\\n line = line[:(-1)]\\n lineno += 1\\n encoded_line = ''\\n prev = None\\n linelen = len(line)\\n for j in range(linelen):\\n c = line[j]\\n prev = c\\n if bqre.match(c):\\n c = quote(c)\\n elif ((j + 1) == linelen):\\n if (c not in ' DCTB '):\\n encoded_line += c\\n prev = c\\n continue\\n if ((len(encoded_line) + len(c)) >= maxlinelen):\\n encoded_body += ((encoded_line + '=') + eol)\\n encoded_line = ''\\n encoded_line += c\\n if (prev and (prev in ' DCTB ')):\\n if ((lineno + 1) == len(lines)):\\n prev = quote(prev)\\n if ((len(encoded_line) + len(prev)) > maxlinelen):\\n encoded_body += (((encoded_line + '=') + eol) + prev)\\n else:\\n encoded_body += (encoded_line + prev)\\n else:\\n encoded_body += (((encoded_line + prev) + '=') + eol)\\n encoded_line = ''\\n if (lines[lineno].endswith(CRLF) or (lines[lineno][(-1)] in CRLF)):\\n encoded_body += (encoded_line + eol)\\n else:\\n encoded_body += encoded_line\\n encoded_line = ''\\n return encoded_body\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def bzr(registry, xml_parent, data):\",\"targets\":\"\\\"\\\"\\\"yaml: bzr\\n Specifies the bzr SCM repository for this job.\\n Requires the Jenkins :jenkins-wiki:`Bazaar Plugin `.\\n :arg str url: URL of the bzr branch (required)\\n :arg bool clean-tree: Clean up the workspace (using bzr) before pulling\\n the branch (default false)\\n :arg bool lightweight-checkout: Use a lightweight checkout instead of a\\n full branch (default false)\\n :arg str browser: The repository browser to use.\\n :browsers supported:\\n * **auto** - (default)\\n * **loggerhead** - as used by Launchpad\\n * **opengrok** - https:\\/\\/opengrok.github.io\\/OpenGrok\\/\\n :arg str browser-url:\\n URL for the repository browser (required if browser is set).\\n :arg str opengrok-root-module:\\n Root module for OpenGrok (required if browser is opengrok).\\n Example:\\n .. literalinclude:: \\/..\\/..\\/tests\\/scm\\/fixtures\\/bzr001.yaml\\n :language: yaml\\n \\\"\\\"\\\"\\n mapping = [('url', 'source', None), ('clean-tree', 'cleantree', False), ('lightweight-checkout', 'checkout', False)]\\n scm_element = XML.SubElement(xml_parent, 'scm', {'class': 'hudson.plugins.bazaar.BazaarSCM'})\\n convert_mapping_to_xml(scm_element, data, mapping, fail_required=True)\\n browser_name_to_class = {'loggerhead': 'Loggerhead', 'opengrok': 'OpenGrok'}\\n browser = data.get('browser', 'auto')\\n if (browser == 'auto'):\\n return\\n if (browser not in browser_name_to_class):\\n raise InvalidAttributeError('browser', browser, browser_name_to_class.keys())\\n browser_element = XML.SubElement(scm_element, 'browser', {'class': 'hudson.plugins.bazaar.browsers.{0}'.format(browser_name_to_class[browser])})\\n mapping = [('browser-url', 'url', None)]\\n convert_mapping_to_xml(browser_element, data, mapping, fail_required=True)\\n if (browser == 'opengrok'):\\n mapping = [('opengrok-root-module', 'rootModule', None)]\\n convert_mapping_to_xml(browser_element, data, mapping, fail_required=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _EndsWithPython(path):\\n\\n ''''Check if given path ends with a python 2.6+ or 3.3+ name.'\\n '''\",\"targets\":\"return (path and (PYTHON_BINARY_REGEX.search(path) is not None))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@main.command()\\n@click.option('-f', '--algofile', default=None, type=click.File('r'), help='The file that contains the algorithm to run.')\\n@click.option('-t', '--algotext', help='The algorithm script to run.')\\n@click.option('-D', '--define', multiple=True, help=\\\"Define a name to be bound in the namespace before executing the algotext. For example '-Dname=value'. The value may be any python expression. These are evaluated in order so they may refer to previously defined names.\\\")\\n@click.option('--data-frequency', type=click.Choice({'daily', 'minute'}), default='daily', show_default=True, help='The data frequency of the simulation.')\\n@click.option('--capital-base', type=float, default=10000000.0, show_default=True, help='The starting capital for the simulation.')\\n@click.option('-b', '--bundle', default='quantopian-quandl', metavar='BUNDLE-NAME', show_default=True, help='The data bundle to use for the simulation.')\\n@click.option('--bundle-timestamp', type=Timestamp(), default=pd.Timestamp.utcnow(), show_default=False, help='The date to lookup data on or before.\\\\n[default: ]')\\n@click.option('-s', '--start', type=Date(tz='utc', as_timestamp=True), help='The start date of the simulation.')\\n@click.option('-e', '--end', type=Date(tz='utc', as_timestamp=True), help='The end date of the simulation.')\\n@click.option('-o', '--output', default='-', metavar='FILENAME', show_default=True, help=\\\"The location to write the perf data. If this is '-' the perf will be written to stdout.\\\")\\n@click.option('--print-algo\\/--no-print-algo', is_flag=True, default=False, help='Print the algorithm to stdout.')\\n@ipython_only(click.option('--local-namespace\\/--no-local-namespace', is_flag=True, default=None, help='Should the ...\",\"targets\":\"\\\"\\\"\\\"Run a backtest for the given algorithm.\\n \\\"\\\"\\\"\\n if ((start is None) and (end is None)):\\n ctx.fail(\\\"must specify dates with '-s' \\/ '--start' and '-e' \\/ '--end'\\\")\\n if (start is None):\\n ctx.fail(\\\"must specify a start date with '-s' \\/ '--start'\\\")\\n if (end is None):\\n ctx.fail(\\\"must specify an end date with '-e' \\/ '--end'\\\")\\n if ((algotext is not None) == (algofile is not None)):\\n ctx.fail(\\\"must specify exactly one of '-f' \\/ '--algofile' or '-t' \\/ '--algotext'\\\")\\n perf = _run(initialize=None, handle_data=None, before_trading_start=None, analyze=None, algofile=algofile, algotext=algotext, defines=define, data_frequency=data_frequency, capital_base=capital_base, data=None, bundle=bundle, bundle_timestamp=bundle_timestamp, start=start, end=end, output=output, print_algo=print_algo, local_namespace=local_namespace, environ=os.environ)\\n if (output == '-'):\\n click.echo(str(perf))\\n elif (output != os.devnull):\\n perf.to_pickle(output)\\n return perf\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def find_intersection(x, tr_bounds, lb, ub):\",\"targets\":\"\\\"\\\"\\\"Find intersection of trust-region bounds and initial bounds.\\n Returns\\n lb_total, ub_total : ndarray with shape of x\\n Lower and upper bounds of the intersection region.\\n orig_l, orig_u : ndarray of bool with shape of x\\n True means that an original bound is taken as a corresponding bound\\n in the intersection region.\\n tr_l, tr_u : ndarray of bool with shape of x\\n True means that a trust-region bound is taken as a corresponding bound\\n in the intersection region.\\n \\\"\\\"\\\"\\n lb_centered = (lb - x)\\n ub_centered = (ub - x)\\n lb_total = np.maximum(lb_centered, (- tr_bounds))\\n ub_total = np.minimum(ub_centered, tr_bounds)\\n orig_l = np.equal(lb_total, lb_centered)\\n orig_u = np.equal(ub_total, ub_centered)\\n tr_l = np.equal(lb_total, (- tr_bounds))\\n tr_u = np.equal(ub_total, tr_bounds)\\n return (lb_total, ub_total, orig_l, orig_u, tr_l, tr_u)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@loader_option()\\ndef immediateload(loadopt, attr):\\n\\n ''''Indicate that the given attribute should be loaded using\\n an immediate load with a per-attribute SELECT statement.\\n This function is part of the :class:`.Load` interface and supports\\n both method-chained and standalone operation.\\n .. seealso::\\n :ref:`loading_toplevel`\\n :func:`.orm.joinedload`\\n :func:`.orm.lazyload`\\n :paramref:`.relationship.lazy`'\\n '''\",\"targets\":\"loader = loadopt.set_relationship_strategy(attr, {'lazy': 'immediate'})\\n return loader\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def l2(x):\",\"targets\":\"\\\"\\\"\\\"Computes the squared L2 norm of a tensor\\n Parameters\\n x : Theano tensor\\n Returns\\n Theano scalar\\n squared l2 norm (sum of squared values of elements)\\n \\\"\\\"\\\"\\n return T.sum((x ** 2))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@bdd.then(bdd.parsers.parse('the javascript message \\\"{message}\\\" should not be logged'))\\ndef javascript_message_not_logged(quteproc, message):\\n\\n ''''Make sure the given message was *not* logged via javascript.'\\n '''\",\"targets\":\"quteproc.ensure_not_logged(category='js', function='javaScriptConsoleMessage', message='[*] {}'.format(message))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def make_messages(locale=None, domain='django', verbosity=1, all=False, extensions=None, symlinks=False, ignore_patterns=None, no_wrap=False, no_location=False, no_obsolete=False, stdout=sys.stdout):\",\"targets\":\"\\\"\\\"\\\"Uses the ``locale\\/`` directory from the Django SVN tree or an\\n application\\/project to process all files with translatable literals for\\n the :param domain: domain and :param locale: locale.\\n \\\"\\\"\\\"\\n from django.conf import settings\\n if settings.configured:\\n settings.USE_I18N = True\\n else:\\n settings.configure(USE_I18N=True)\\n if (ignore_patterns is None):\\n ignore_patterns = []\\n invoked_for_django = False\\n if os.path.isdir(os.path.join('conf', 'locale')):\\n localedir = os.path.abspath(os.path.join('conf', 'locale'))\\n invoked_for_django = True\\n ignore_patterns += ['contrib\\/*']\\n elif os.path.isdir('locale'):\\n localedir = os.path.abspath('locale')\\n else:\\n raise CommandError('This script should be run from the Django SVN tree or your project or app tree. If you did indeed run it from the SVN checkout or your project or application, maybe you are just missing the conf\\/locale (in the django tree) or locale (for project and application) directory? It is not created automatically, you have to create it by hand if you want to enable i18n for your project or application.')\\n if (domain not in ('django', 'djangojs')):\\n raise CommandError(\\\"currently makemessages only supports domains 'django' and 'djangojs'\\\")\\n if (((locale is None) and (not all)) or (domain is None)):\\n message = (\\\"Type '%s help %s' for usage information.\\\" % (os.path.basename(sys.argv[0]), sys.argv[1]))\\n raise CommandError(message)\\n output = _popen('xgettext --version')[0]\\n match = re.search('(?P\\\\\\\\d+)\\\\\\\\.(?P\\\\\\\\d+)', output)\\n if match:\\n xversion = (int(match.group('major')), int(match.group('minor')))\\n if (xversion < (0, 15)):\\n raise CommandError(('Django internationalization requires GNU gettext 0.15 or newer. You are using version %s, please upgrade your gettext toolset.' % match.group()))\\n locales =...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@flaky(max_runs=3)\\n@pytest.mark.skipif((os.name == 'nt'), reason='It times out on Windows')\\ndef test_restart_kernel(ipyconsole, qtbot):\\n\\n ''''Test that kernel is restarted correctly'\\n '''\",\"targets\":\"shell = ipyconsole.get_current_shellwidget()\\n client = ipyconsole.get_current_client()\\n qtbot.waitUntil((lambda : (shell._prompt_html is not None)), timeout=SHELL_TIMEOUT)\\n with qtbot.waitSignal(shell.executed):\\n shell.execute('a = 10')\\n shell._prompt_html = None\\n QTimer.singleShot(1000, (lambda : close_message_box(qtbot)))\\n client.restart_kernel()\\n qtbot.waitUntil((lambda : (shell._prompt_html is not None)), timeout=SHELL_TIMEOUT)\\n assert (not shell.is_defined('a'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@pytest.fixture(scope='module')\\ndef genesis_fixture():\",\"targets\":\"\\\"\\\"\\\"Read genesis block from fixtures.\\n \\\"\\\"\\\"\\n genesis_fixture = None\\n fn = os.path.join(testutils.fixture_path, 'BasicTests', 'genesishashestest.json')\\n with open(fn, 'r') as f:\\n genesis_fixture = json.load(f)\\n assert (genesis_fixture is not None), \\\"Could not read genesishashtest.json from fixtures. Make sure you did 'git submodule init'!\\\"\\n for k in ('genesis_rlp_hex', 'genesis_state_root', 'genesis_hash'):\\n assert (k in genesis_fixture)\\n return genesis_fixture\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def decorator(method):\\n _DECORATED_EXTEND_METHODS[method].extend(resources)\\n return method\\n return decorator\\n\\n\\nWhat's a good function header?\",\"targets\":\"def extends(resources):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def wrapper(cls):\\n orig_vars = cls.__dict__.copy()\\n slots = orig_vars.get('__slots__')\\n if (slots is not None):\\n if isinstance(slots, str):\\n slots = [slots]\\n for slots_var in slots:\\n orig_vars.pop(slots_var)\\n orig_vars.pop('__dict__', None)\\n orig_vars.pop('__weakref__', None)\\n return metaclass(cls.__name__, cls.__bases__, orig_vars)\\n return wrapper\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_metaclass(metaclass):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n cls = sender\\n if cls._meta.abstract:\\n setattr(cls, 'objects', AbstractManagerDescriptor(cls))\\n return\\n elif cls._meta.swapped:\\n setattr(cls, 'objects', SwappedManagerDescriptor(cls))\\n return\\n if (not getattr(cls, '_default_manager', None)):\\n try:\\n cls._meta.get_field('objects')\\n raise ValueError((\\\"Model %s must specify a custom Manager, because it has a field named 'objects'\\\" % cls.__name__))\\n except FieldDoesNotExist:\\n pass\\n cls.add_to_class('objects', Manager())\\n cls._base_manager = cls.objects\\n elif (not getattr(cls, '_base_manager', None)):\\n default_mgr = cls._default_manager.__class__\\n if ((default_mgr is Manager) or getattr(default_mgr, 'use_for_related_fields', False)):\\n cls._base_manager = cls._default_manager\\n else:\\n for base_class in default_mgr.mro()[1:]:\\n if ((base_class is Manager) or getattr(base_class, 'use_for_related_fields', False)):\\n cls.add_to_class('_base_manager', base_class())\\n return\\n raise AssertionError('Should never get here. Please report a bug, including your model and model manager setup.')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ensure_default_manager(sender, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef fix_uri_credentials(uri, to_quoted):\\n\\n ''''Fix the given uri\\\\'s embedded credentials by round-tripping with\\n StoreLocation.\\n If to_quoted is True, the uri is assumed to have credentials that\\n have not been quoted, and the resulting uri will contain quoted\\n credentials.\\n If to_quoted is False, the uri is assumed to have credentials that\\n have been quoted, and the resulting uri will contain credentials\\n that have not been quoted.'\\n '''\",\"targets\":\"if (not uri):\\n return\\n location = glance.store.swift.StoreLocation({})\\n if to_quoted:\\n location.parse_uri = types.MethodType(legacy_parse_uri, location)\\n else:\\n location._get_credstring = types.MethodType(legacy__get_credstring, location)\\n decrypted_uri = None\\n try:\\n decrypted_uri = decrypt_location(uri)\\n except (TypeError, ValueError) as e:\\n raise exception.Invalid(str(e))\\n location.parse_uri(decrypted_uri)\\n return encrypt_location(location.get_uri())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not ismeetingrunning(trigger.sender)):\\n bot.say(u\\\"Can't do that, start meeting first\\\")\\n return\\n if (not trigger.group(2)):\\n bot.say(u'Who are the chairs?')\\n return\\n if (trigger.nick.lower() == meetings_dict[trigger.sender][u'head']):\\n meetings_dict[trigger.sender][u'chairs'] = trigger.group(2).lower().split(u' ')\\n chairs_readable = trigger.group(2).lower().replace(u' ', u', ')\\n logplain((u'Meeting chairs are: ' + chairs_readable), trigger.sender)\\n logHTML_listitem((u'Meeting chairs are: <\\/span>' + chairs_readable), trigger.sender)\\n bot.say((u'\\\\x02Meeting chairs are:\\\\x0f ' + chairs_readable))\\n else:\\n bot.say(u'Only meeting head can set chairs')\\n\\n\\nWhat's a good function header?\",\"targets\":\"@commands(u'chairs')\\n@example(u'.chairs Tyrope Jason elad')\\ndef chairs(bot, trigger):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (discovery_info is None):\\n return\\n name = 'Eight'\\n sensors = discovery_info[CONF_BINARY_SENSORS]\\n eight = hass.data[DATA_EIGHT]\\n all_sensors = []\\n for sensor in sensors:\\n all_sensors.append(EightHeatSensor(name, eight, sensor))\\n async_add_devices(all_sensors, True)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@asyncio.coroutine\\ndef async_setup_platform(hass, config, async_add_devices, discovery_info=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if isinstance(s, six.string_types):\\n return force_text(s)\\n return s\\n\\n\\nWhat's a good function header?\",\"targets\":\"def to_unicode(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _append_comment(ret, comment):\",\"targets\":\"\\\"\\\"\\\"append ``comment`` to ``ret[\\\\comment\\\\]``\\n \\\"\\\"\\\"\\n if len(ret['comment']):\\n ret['comment'] = ((ret['comment'].rstrip() + '\\\\n') + comment)\\n else:\\n ret['comment'] = comment\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_integration_manager():\\n\\n ''''Return the integration manager for Review Board.\\n Returns:\\n djblets.integrations.manager.IntegrationManager:\\n The integration manager used for Review Board.'\\n '''\",\"targets\":\"global _integration_manager\\n if (not _integration_manager):\\n from reviewboard.integrations.models import IntegrationConfig\\n _integration_manager = IntegrationManager(IntegrationConfig)\\n return _integration_manager\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def hazard():\",\"targets\":\"\\\"\\\"\\\"REST Controller\\n \\\"\\\"\\\"\\n return s3_rest_controller()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def check_headers(request):\",\"targets\":\"\\\"\\\"\\\"A view that responds with value of the X-ARG-CHECK header\\n \\\"\\\"\\\"\\n return HttpResponse(('HTTP_X_ARG_CHECK: %s' % request.META.get('HTTP_X_ARG_CHECK', 'Undefined')))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n possibles = Breakpoint.bplist[(file, line)]\\n for i in range(0, len(possibles)):\\n b = possibles[i]\\n if (b.enabled == 0):\\n continue\\n if (not checkfuncname(b, frame)):\\n continue\\n b.hits = (b.hits + 1)\\n if (not b.cond):\\n if (b.ignore > 0):\\n b.ignore = (b.ignore - 1)\\n continue\\n else:\\n return (b, 1)\\n else:\\n try:\\n val = eval(b.cond, frame.f_globals, frame.f_locals)\\n if val:\\n if (b.ignore > 0):\\n b.ignore = (b.ignore - 1)\\n else:\\n return (b, 1)\\n except:\\n return (b, 0)\\n return (None, None)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def effective(file, line, frame):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _plot_dipole_mri_orthoview(dipole, trans, subject, subjects_dir=None, coord_frame='head', idx='gof', show_all=True, ax=None, block=False, show=True):\\n\\n ''''Plot dipoles on top of MRI slices in 3-D.'\\n '''\",\"targets\":\"import matplotlib.pyplot as plt\\n from mpl_toolkits.mplot3d import Axes3D\\n from .. import Dipole\\n if (not has_nibabel()):\\n raise ImportError('This function requires nibabel.')\\n import nibabel as nib\\n from nibabel.processing import resample_from_to\\n if (coord_frame not in ['head', 'mri']):\\n raise ValueError((\\\"coord_frame must be 'head' or 'mri'. Got %s.\\\" % coord_frame))\\n if (not isinstance(dipole, Dipole)):\\n from ..dipole import _concatenate_dipoles\\n dipole = _concatenate_dipoles(dipole)\\n if (idx == 'gof'):\\n idx = np.argmax(dipole.gof)\\n elif (idx == 'amplitude'):\\n idx = np.argmax(np.abs(dipole.amplitude))\\n else:\\n idx = _ensure_int(idx, 'idx', 'an int or one of [\\\"gof\\\", \\\"amplitude\\\"]')\\n subjects_dir = get_subjects_dir(subjects_dir=subjects_dir, raise_error=True)\\n t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')\\n t1 = nib.load(t1_fname)\\n vox2ras = t1.header.get_vox2ras_tkr()\\n ras2vox = linalg.inv(vox2ras)\\n trans = _get_trans(trans, fro='head', to='mri')[0]\\n zooms = t1.header.get_zooms()\\n if (coord_frame == 'head'):\\n affine_to = trans['trans'].copy()\\n affine_to[:3, 3] *= 1000\\n aff = t1.affine.copy()\\n aff[:3, :3] \\/= zooms\\n affine_to = np.dot(affine_to, aff)\\n t1 = resample_from_to(t1, ([int((t1.shape[i] * zooms[i])) for i in range(3)], affine_to))\\n dipole_locs = (apply_trans(ras2vox, (dipole.pos * 1000.0)) * zooms)\\n ori = dipole.ori\\n scatter_points = (dipole.pos * 1000.0)\\n else:\\n scatter_points = (apply_trans(trans['trans'], dipole.pos) * 1000.0)\\n ori = apply_trans(trans['trans'], dipole.ori, move=False)\\n dipole_locs = apply_trans(ras2vox, scatter_points)\\n data = t1.get_data()\\n dims = len(data)\\n dd = (dims \\/ 2.0)\\n dd *= t1.header.get_zooms()[0]\\n if (ax is None):\\n fig = plt.figure()\\n ax = Axes3D(fig)\\n elif (not isinstance(ax, Axes3D)):\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef example_decorator(name, function):\\n\\n ''''decorator for notify which is used from utils.monkey_patch().\\n :param name: name of the function\\n :param function: - object of the function\\n :returns: function -- decorated function'\\n '''\",\"targets\":\"def wrapped_func(*args, **kwarg):\\n CALLED_FUNCTION.append(name)\\n return function(*args, **kwarg)\\n return wrapped_func\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n _reload_hooks.append(fn)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_reload_hook(fn):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_preamble():\\n\\n ''''Get LaTeX preamble from rc.'\\n '''\",\"targets\":\"latex_preamble = rcParams.get(u'pgf.preamble', u'')\\n if (type(latex_preamble) == list):\\n latex_preamble = u'\\\\n'.join(latex_preamble)\\n return latex_preamble\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n class dummy:\\n def __getattr__(self, attr):\\n return (lambda x: x)\\n return dummy()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def no_style():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def exists(storage, indexname=None):\",\"targets\":\"\\\"\\\"\\\"Returns True if the given Storage object contains a Whoosh index.\\n :param storage: a store.Storage object.\\n :param indexname: the name of the index. If None, the default index name is\\n used.\\n :param rtype: bool\\n \\\"\\\"\\\"\\n if (indexname is None):\\n indexname = _DEF_INDEX_NAME\\n try:\\n ix = storage.open_index(indexname)\\n gen = ix.latest_generation()\\n ix.close()\\n return (gen > (-1))\\n except EmptyIndexError:\\n pass\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n documented = []\\n for filename in filenames:\\n with codecs.open(filename, 'r', encoding='utf-8', errors='ignore') as f:\\n lines = f.read().splitlines()\\n documented.extend(find_autosummary_in_lines(lines, filename=filename))\\n return documented\\n\\n\\nWhat's a good function header?\",\"targets\":\"def find_autosummary_in_files(filenames):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_hwclock():\",\"targets\":\"\\\"\\\"\\\"Get current hardware clock setting (UTC or localtime)\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ timezone.get_hwclock\\n \\\"\\\"\\\"\\n return 'localtime'\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n errno_names = dir(errno)\\n nums = [getattr(errno, k) for k in errnames if (k in errno_names)]\\n return dict.fromkeys(nums).keys()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def plat_specific_errors(*errnames):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n defines = []\\n for d in config.get('defines', []):\\n if (type(d) == list):\\n fd = '='.join([str(dpart) for dpart in d])\\n else:\\n fd = str(d)\\n defines.append(fd)\\n return defines\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _GetDefines(config):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def global_parameters(b, c):\",\"targets\":\"\\\"\\\"\\\"Return global parameters for a given intersection array.\\n Given a distance-regular graph G with integers b_i, c_i,i = 0,....,d\\n such that for any 2 vertices x,y in G at a distance i=d(x,y), there\\n are exactly c_i neighbors of y at a distance of i-1 from x and b_i\\n neighbors of y at a distance of i+1 from x.\\n Thus, a distance regular graph has the global parameters,\\n [[c_0,a_0,b_0],[c_1,a_1,b_1],......,[c_d,a_d,b_d]] for the\\n intersection array [b_0,b_1,.....b_{d-1};c_1,c_2,.....c_d]\\n where a_i+b_i+c_i=k , k= degree of every vertex.\\n Parameters\\n b : list\\n c : list\\n Returns\\n iterable\\n An iterable over three tuples.\\n Examples\\n >>> G = nx.dodecahedral_graph()\\n >>> b, c = nx.intersection_array(G)\\n >>> list(nx.global_parameters(b, c))\\n [(0, 0, 3), (1, 0, 2), (1, 1, 1), (1, 1, 1), (2, 0, 1), (3, 0, 0)]\\n References\\n .. [1] Weisstein, Eric W. \\\"Global Parameters.\\\"\\n From MathWorld--A Wolfram Web Resource.\\n http:\\/\\/mathworld.wolfram.com\\/GlobalParameters.html\\n See Also\\n intersection_array\\n \\\"\\\"\\\"\\n return ((y, ((b[0] - x) - y), x) for (x, y) in zip((b + [0]), ([0] + c)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef enable_edxnotes_for_the_course(course, user_id):\\n\\n ''''Enable EdxNotes for the course.'\\n '''\",\"targets\":\"course.tabs.append(CourseTab.load('edxnotes'))\\n modulestore().update_item(course, user_id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (n < 0):\\n raise ValueError('n must be nonnegative.')\\n if (n == 0):\\n n1 = (n + 1)\\n else:\\n n1 = n\\n (x, w, mu0) = roots_hermite(n1, mu=True)\\n wfunc = (lambda x: exp(((- x) * x)))\\n if (n == 0):\\n (x, w) = ([], [])\\n hn = (((2 ** n) * _gam((n + 1))) * sqrt(pi))\\n kn = (2 ** n)\\n p = orthopoly1d(x, w, hn, kn, wfunc, ((- inf), inf), monic, (lambda x: eval_hermite(n, x)))\\n return p\\n\\n\\nWhat's a good function header?\",\"targets\":\"def hermite(n, monic=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef join(a, *p):\\n\\n ''''Join two or more pathname components, inserting sep as needed'\\n '''\",\"targets\":\"path = a\\n for b in p:\\n if isabs(b):\\n path = b\\n elif ((path == '') or (path[(-1):] in '\\/\\\\\\\\:')):\\n path = (path + b)\\n else:\\n path = ((path + '\\/') + b)\\n return path\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not snapshot_id):\\n raise CommandExecutionError('Error: No snapshot ID has been provided')\\n snapshot = get_snapshot(config=config, number=snapshot_id)\\n try:\\n updated_opts = {'description': (description if (description is not None) else snapshot['description']), 'cleanup': (cleanup if (cleanup is not None) else snapshot['cleanup']), 'userdata': (userdata if (userdata is not None) else snapshot['userdata'])}\\n snapper.SetSnapshot(config, snapshot_id, updated_opts['description'], updated_opts['cleanup'], updated_opts['userdata'])\\n return get_snapshot(config=config, number=snapshot_id)\\n except dbus.DBusException as exc:\\n raise CommandExecutionError(_dbus_exception_to_reason(exc, locals()))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def modify_snapshot(snapshot_id=None, description=None, userdata=None, cleanup=None, config='root'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global _service_command_generator\\n try:\\n return _service_command_generator\\n except NameError:\\n command_generator = _command_generators[get_name_of_init(run)]\\n _service_command_generator = _ServiceCommandGenerator(command_generator)\\n return _service_command_generator\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_service_command_generator(run=utils.run):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef allow_session_user(user_id):\\n\\n ''''Returns True or False if the user_id is allowed for the current logged in session'\\n '''\",\"targets\":\"session_user_id = get_session_user_id()\\n if (session_user_id and (str(user_id) != session_user_id)):\\n return False\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _convert_asset_timestamp_fields(dict_):\",\"targets\":\"\\\"\\\"\\\"Takes in a dict of Asset init args and converts dates to pd.Timestamps\\n \\\"\\\"\\\"\\n for key in (_asset_timestamp_fields & viewkeys(dict_)):\\n value = pd.Timestamp(dict_[key], tz='UTC')\\n dict_[key] = (None if isnull(value) else value)\\n return dict_\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef ParseKindQuery(query, filters, orders):\\n\\n ''''Parse __kind__ (schema) queries.\\n Raises exceptions for illegal queries.\\n Args:\\n query: A Query PB.\\n filters: the normalized filters from query.\\n orders: the normalized orders from query.\\n Returns:\\n The kind range (a ValueRange over string) requested in the query.'\\n '''\",\"targets\":\"if query.has_ancestor():\\n raise BadRequestError('ancestor queries on __kind__ not allowed')\\n key_range = ParseKeyFilteredQuery(filters, orders)\\n key_range.Remap(_KindKeyToString)\\n return key_range\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n is_bfv = compute_utils.is_volume_backed_instance(instance._context, instance)\\n swap_in_gb = compute_utils.convert_mb_to_ceil_gb(flavor.swap)\\n disk = (((0 if is_bfv else flavor.root_gb) + swap_in_gb) + flavor.ephemeral_gb)\\n resources = {fields.ResourceClass.VCPU: flavor.vcpus, fields.ResourceClass.MEMORY_MB: flavor.memory_mb, fields.ResourceClass.DISK_GB: disk}\\n if ('extra_specs' in flavor):\\n _process_extra_specs(flavor.extra_specs, resources)\\n return resources\\n\\n\\nWhat's a good function header?\",\"targets\":\"def resources_from_flavor(instance, flavor):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef fd_by_path(paths):\\n\\n ''''Return a list of file descriptors.\\n This method returns list of file descriptors corresponding to\\n file paths passed in paths variable.\\n Arguments:\\n paths: List[str]: List of file paths.\\n Returns:\\n List[int]: List of file descriptors.\\n Example:\\n >>> keep = fd_by_path([\\\\'\\/dev\\/urandom\\\\', \\\\'\\/my\\/precious\\/\\\\'])'\\n '''\",\"targets\":\"stats = set()\\n for path in paths:\\n try:\\n fd = os.open(path, os.O_RDONLY)\\n except OSError:\\n continue\\n try:\\n stats.add(os.fstat(fd)[1:3])\\n finally:\\n os.close(fd)\\n def fd_in_stats(fd):\\n try:\\n return (os.fstat(fd)[1:3] in stats)\\n except OSError:\\n return False\\n return [_fd for _fd in range(get_fdmax(2048)) if fd_in_stats(_fd)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if isinstance(sentence, basestring):\\n try:\\n from pattern.en import parse, Sentence\\n sentence = Sentence(parse(sentence))\\n except ImportError:\\n pass\\n (S, n, m) = (sentence, 0.0, 0)\\n if (not (hasattr(S, 'words') and hasattr(S, 'parse_token'))):\\n raise TypeError(('%s object is not a parsed Sentence' % repr(S.__class__.__name__)))\\n if (type == EPISTEMIC):\\n r = S.string.rstrip(' .!')\\n for (k, v) in epistemic_weaseling.items():\\n for phrase in v:\\n if (phrase in r):\\n n += k\\n m += 2\\n for (i, w) in enumerate(S.words):\\n for (type, dict, weight) in (('MD', epistemic_MD, 4), ('VB', epistemic_VB, 2), ('RB', epistemic_RB, 2), ('JJ', epistemic_JJ, 1), ('NN', epistemic_NN, 1), ('CC', epistemic_CC_DT_IN, 1), ('DT', epistemic_CC_DT_IN, 1), ('IN', epistemic_CC_DT_IN, 1), ('PRP', epistemic_PRP, 1), ('PRP$', epistemic_PRP, 1), ('WP', epistemic_PRP, 1)):\\n if ((i > 0) and (s(S[(i - 1)]) in MODIFIERS)):\\n weight += 1\\n if (w.type and w.type.startswith(type)):\\n for (k, v) in dict.items():\\n if ((w.lemma or s(w)) in v):\\n if ((i > 0) and (s(S[(i - 1)]) in ('not', \\\"n't\\\", 'never', 'without'))):\\n k = ((- k) * 0.5)\\n n += (weight * k)\\n m += weight\\n break\\n if (w.type in ('CD', '\\\"', \\\"'\\\", ':', '(')):\\n n += 0.75\\n m += 1\\n if (m == 0):\\n return 1.0\\n return max((-1.0), min((n \\/ (m or 1)), (+ 1.0)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def modality(sentence, type=EPISTEMIC):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def anova_lm(*args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Anova table for one or more fitted linear models.\\n Parameters\\n args : fitted linear model results instance\\n One or more fitted linear models\\n scale : float\\n Estimate of variance, If None, will be estimated from the largest\\n model. Default is None.\\n test : str {\\\"F\\\", \\\"Chisq\\\", \\\"Cp\\\"} or None\\n Test statistics to provide. Default is \\\"F\\\".\\n typ : str or int {\\\"I\\\",\\\"II\\\",\\\"III\\\"} or {1,2,3}\\n The type of Anova test to perform. See notes.\\n robust : {None, \\\"hc0\\\", \\\"hc1\\\", \\\"hc2\\\", \\\"hc3\\\"}\\n Use heteroscedasticity-corrected coefficient covariance matrix.\\n If robust covariance is desired, it is recommended to use `hc3`.\\n Returns\\n anova : DataFrame\\n A DataFrame containing.\\n Notes\\n Model statistics are given in the order of args. Models must have\\n been fit using the formula api.\\n See Also\\n model_results.compare_f_test, model_results.compare_lm_test\\n Examples\\n >>> import statsmodels.api as sm\\n >>> from statsmodels.formula.api import ols\\n >>> moore = sm.datasets.get_rdataset(\\\"Moore\\\", \\\"car\\\", cache=True) # load\\n >>> data = moore.data\\n >>> data = data.rename(columns={\\\"partner.status\\\" :\\n ... \\\"partner_status\\\"}) # make name pythonic\\n >>> moore_lm = ols(\\\\conformity ~ C(fcategory, Sum)*C(partner_status, Sum)\\\\,\\n ... data=data).fit()\\n >>> table = sm.stats.anova_lm(moore_lm, typ=2) # Type 2 Anova DataFrame\\n >>> print(table)\\n \\\"\\\"\\\"\\n typ = kwargs.get('typ', 1)\\n if (len(args) == 1):\\n model = args[0]\\n return anova_single(model, **kwargs)\\n try:\\n assert (typ in [1, 'I'])\\n except:\\n raise ValueError(('Multiple models only supported for type I. Got type %s' % str(typ)))\\n if (len(args) == 1):\\n return anova_single(*args, **kwargs)\\n test = kwargs.get('test', 'F')\\n scale = kwargs.get('scale', None)\\n n_models = len(args)\\n model_formula = []\\n pr_test = ('Pr(>%s)' % test)\\n names = ['df_resid', 'ssr', 'df_diff', 'ss_diff', test, pr_test]\\n table = DataFrame(np.zeros((n_models, 6)), columns=names)\\n if (not scale):\\n scale = args[(-1)].scale\\n table['ssr'] = lmap(getattr, args, (['ssr'] * n_models))\\n table['df_resid'] = lmap(getattr, args, (['df_resid'] * n_models))\\n table.loc[(table.index[1:], 'df_diff')] = (- np.diff(table['df_resid'].values))\\n table['ss_diff'] = (- table['ssr'].diff())\\n if (test == 'F'):\\n table['F'] = ((table['ss_diff'] \\/ table['df_diff']) \\/ scale)\\n table[pr_test] = stats.f.sf(table['F'], table['df_diff'], table['df_resid'])\\n table[pr_test][table['F'].isnull()] = np.nan\\n return table\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_archive_formats():\",\"targets\":\"\\\"\\\"\\\"Returns a list of supported formats for archiving and unarchiving.\\n Each element of the returned sequence is a tuple (name, description)\\n \\\"\\\"\\\"\\n formats = [(name, registry[2]) for (name, registry) in _ARCHIVE_FORMATS.items()]\\n formats.sort()\\n return formats\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef deprecated_version_of(f, oldname, newname=None):\\n\\n ''''Indicates that a function is deprecated and has a new name.\\n `f` is the new function, `oldname` the name of the deprecated\\n function, `newname` the name of `f`, which can be automatically\\n found.\\n Returns\\n f_deprecated\\n A function that does the same thing as f, but with a docstring\\n and a printed message on call which say that the function is\\n deprecated and that you should use f instead.\\n Examples\\n >>> # The badly named method \\\\'to_file\\\\' is replaced by \\\\'write_file\\\\'\\n >>> class Clip:\\n >>> def write_file(self, some args):\\n >>> # blablabla\\n >>> Clip.to_file = deprecated_version_of(Clip.write_file, \\\\'to_file\\\\')'\\n '''\",\"targets\":\"if (newname is None):\\n newname = f.__name__\\n warning = ('The function ``%s`` is deprecated and is kept temporarily for backwards compatibility.\\\\nPlease use the new name, ``%s``, instead.' % (oldname, newname))\\n def fdepr(*a, **kw):\\n warnings.warn(('MoviePy: ' + warning), PendingDeprecationWarning)\\n return f(*a, **kw)\\n fdepr.__doc__ = warning\\n return fdepr\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef encode_quopri(msg):\\n\\n ''''Encode the message\\\\'s payload in quoted-printable.\\n Also, add an appropriate Content-Transfer-Encoding header.'\\n '''\",\"targets\":\"orig = msg.get_payload()\\n encdata = _qencode(orig)\\n msg.set_payload(encdata)\\n msg['Content-Transfer-Encoding'] = 'quoted-printable'\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def authenticated_userid(request):\",\"targets\":\"\\\"\\\"\\\"A function that returns the value of the property\\n :attr:`pyramid.request.Request.authenticated_userid`.\\n .. deprecated:: 1.5\\n Use :attr:`pyramid.request.Request.authenticated_userid` instead.\\n \\\"\\\"\\\"\\n return request.authenticated_userid\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n _check_solver_option(solver, multi_class, penalty, dual)\\n X_train = X[train]\\n X_test = X[test]\\n y_train = y[train]\\n y_test = y[test]\\n if (sample_weight is not None):\\n sample_weight = check_array(sample_weight, ensure_2d=False)\\n check_consistent_length(y, sample_weight)\\n sample_weight = sample_weight[train]\\n (coefs, Cs, n_iter) = logistic_regression_path(X_train, y_train, Cs=Cs, fit_intercept=fit_intercept, solver=solver, max_iter=max_iter, class_weight=class_weight, pos_class=pos_class, multi_class=multi_class, tol=tol, verbose=verbose, dual=dual, penalty=penalty, intercept_scaling=intercept_scaling, random_state=random_state, check_input=False, max_squared_sum=max_squared_sum, sample_weight=sample_weight)\\n log_reg = LogisticRegression(fit_intercept=fit_intercept)\\n if (multi_class == 'ovr'):\\n log_reg.classes_ = np.array([(-1), 1])\\n elif (multi_class == 'multinomial'):\\n log_reg.classes_ = np.unique(y_train)\\n else:\\n raise ValueError(('multi_class should be either multinomial or ovr, got %d' % multi_class))\\n if (pos_class is not None):\\n mask = (y_test == pos_class)\\n y_test = np.ones(y_test.shape, dtype=np.float64)\\n y_test[(~ mask)] = (-1.0)\\n scores = list()\\n if isinstance(scoring, six.string_types):\\n scoring = SCORERS[scoring]\\n for w in coefs:\\n if (multi_class == 'ovr'):\\n w = w[np.newaxis, :]\\n if fit_intercept:\\n log_reg.coef_ = w[:, :(-1)]\\n log_reg.intercept_ = w[:, (-1)]\\n else:\\n log_reg.coef_ = w\\n log_reg.intercept_ = 0.0\\n if (scoring is None):\\n scores.append(log_reg.score(X_test, y_test))\\n else:\\n scores.append(scoring(log_reg, X_test, y_test))\\n return (coefs, Cs, np.array(scores), n_iter)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _log_reg_scoring_path(X, y, train, test, pos_class=None, Cs=10, scoring=None, fit_intercept=False, max_iter=100, tol=0.0001, class_weight=None, verbose=0, solver='lbfgs', penalty='l2', dual=False, intercept_scaling=1.0, multi_class='ovr', random_state=None, max_squared_sum=None, sample_weight=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def csrf_failure(request, reason=''):\",\"targets\":\"\\\"\\\"\\\"Default view used when request fails CSRF protection\\n \\\"\\\"\\\"\\n from django.middleware.csrf import REASON_NO_REFERER\\n t = Template(CSRF_FAILURE_TEMPLATE)\\n c = Context({'DEBUG': settings.DEBUG, 'reason': reason, 'no_referer': (reason == REASON_NO_REFERER)})\\n return HttpResponseForbidden(t.render(c), content_type='text\\/html')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _run_hook(shell_cmd):\",\"targets\":\"\\\"\\\"\\\"Run a hook command.\\n :returns: stderr if there was any\\n \\\"\\\"\\\"\\n (err, _) = execute(shell_cmd)\\n return err\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.filter\\ndef get_range(value):\\n\\n ''''Filter - returns a list containing range made from given value\\n Usage (in template):\\n
          {% for i in 3|get_range %}\\n
        • {{ i }}. Do something<\\/li>\\n {% endfor %}<\\/ul>\\n Results with the HTML:\\n
            \\n
          • 0. Do something<\\/li>\\n
          • 1. Do something<\\/li>\\n
          • 2. Do something<\\/li>\\n <\\/ul>\\n Instead of 3 one may use the variable set in the views'\\n '''\",\"targets\":\"return range(value)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def libvlc_media_player_set_title(p_mi, i_title):\",\"targets\":\"\\\"\\\"\\\"Set movie title.\\n @param p_mi: the Media Player.\\n @param i_title: title number to play.\\n \\\"\\\"\\\"\\n f = (_Cfunctions.get('libvlc_media_player_set_title', None) or _Cfunction('libvlc_media_player_set_title', ((1,), (1,)), None, None, MediaPlayer, ctypes.c_int))\\n return f(p_mi, i_title)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ensemble_preds(dataset, nb_teachers, stdnt_data):\",\"targets\":\"\\\"\\\"\\\"Given a dataset, a number of teachers, and some input data, this helper\\n function queries each teacher for predictions on the data and returns\\n all predictions in a single array. (That can then be aggregated into\\n one single prediction per input using aggregation.py (cf. function\\n prepare_student_data() below)\\n :param dataset: string corresponding to mnist, cifar10, or svhn\\n :param nb_teachers: number of teachers (in the ensemble) to learn from\\n :param stdnt_data: unlabeled student training data\\n :return: 3d array (teacher id, sample id, probability per class)\\n \\\"\\\"\\\"\\n result_shape = (nb_teachers, len(stdnt_data), FLAGS.nb_labels)\\n result = np.zeros(result_shape, dtype=np.float32)\\n for teacher_id in xrange(nb_teachers):\\n if FLAGS.deeper:\\n ckpt_path = ((((((((FLAGS.teachers_dir + '\\/') + str(dataset)) + '_') + str(nb_teachers)) + '_teachers_') + str(teacher_id)) + '_deep.ckpt-') + str((FLAGS.teachers_max_steps - 1)))\\n else:\\n ckpt_path = ((((((((FLAGS.teachers_dir + '\\/') + str(dataset)) + '_') + str(nb_teachers)) + '_teachers_') + str(teacher_id)) + '.ckpt-') + str((FLAGS.teachers_max_steps - 1)))\\n result[teacher_id] = deep_cnn.softmax_preds(stdnt_data, ckpt_path)\\n print((('Computed Teacher ' + str(teacher_id)) + ' softmax predictions'))\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not (os.path.exists(filename) and os.path.isdir(os.path.join(os.path.dirname(filename), '.svn')))):\\n return (None, None, None)\\n (svnRev, svnLastChangedRev, svnUrl) = (None, None, None)\\n if ((sys.platform in ('darwin', 'freebsd')) or sys.platform.startswith('linux')):\\n try:\\n svninfo = shellCall(['svn', 'info', filename])\\n except Exception:\\n svninfo = ''\\n for line in svninfo.splitlines():\\n if line.startswith('URL:'):\\n svnUrl = line.split()[1]\\n elif line.startswith('Revision: '):\\n svnRev = line.split()[1]\\n elif line.startswith('Last Changed Rev'):\\n svnLastChangedRev = line.split()[3]\\n else:\\n try:\\n stdout = shellCall(['subwcrev', filename])\\n except Exception:\\n stdout = ''\\n for line in stdout.splitlines():\\n if line.startswith('Last committed at revision'):\\n svnRev = line.split()[4]\\n elif line.startswith('Updated to revision'):\\n svnLastChangedRev = line.split()[3]\\n return (svnRev, svnLastChangedRev, svnUrl)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _getSvnVersion(filename):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (uid, gid) = (os.geteuid(), os.getegid())\\n if ((uid == euid) and (gid == egid)):\\n return function(*args, **kwargs)\\n else:\\n if ((uid != 0) and ((uid != euid) or (gid != egid))):\\n os.seteuid(0)\\n if (gid != egid):\\n os.setegid(egid)\\n if ((euid != 0) and ((euid != uid) or (gid != egid))):\\n os.seteuid(euid)\\n try:\\n return function(*args, **kwargs)\\n finally:\\n if ((euid != 0) and ((uid != euid) or (gid != egid))):\\n os.seteuid(0)\\n if (gid != egid):\\n os.setegid(gid)\\n if ((uid != 0) and ((uid != euid) or (gid != egid))):\\n os.seteuid(uid)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def runAsEffectiveUser(euid, egid, function, *args, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.tag(u'buttons')\\ndef bootstrap_buttons(parser, token):\\n\\n ''''Render buttons for form\\n **Tag name**::\\n buttons\\n **Parameters**:\\n submit\\n Text for a submit button\\n reset\\n Text for a reset button\\n **Usage**::\\n {% buttons %}{% endbuttons %}\\n **Example**::\\n {% buttons submit=\\\\'OK\\\\' reset=\\\"Cancel\\\" %}{% endbuttons %}'\\n '''\",\"targets\":\"kwargs = parse_token_contents(parser, token)\\n kwargs[u'nodelist'] = parser.parse((u'endbuttons',))\\n parser.delete_first_token()\\n return ButtonsNode(**kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not os.path.isdir(etcdir)):\\n return iter(())\\n return (name for name in os.listdir(etcdir) if (name.endswith('.py') and os.path.isfile(os.path.join(etcdir, name))))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def list_config_modules(etcdir):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=1, dry_run=0):\",\"targets\":\"\\\"\\\"\\\"Copy a file \\\\src\\\\ to \\\\dst\\\\.\\n If \\\\dst\\\\ is a directory, then \\\\src\\\\ is copied there with the same name;\\n otherwise, it must be a filename. (If the file exists, it will be\\n ruthlessly clobbered.) If \\\\preserve_mode\\\\ is true (the default),\\n the file\\\\s mode (type and permission bits, or whatever is analogous on\\n the current platform) is copied. If \\\\preserve_times\\\\ is true (the\\n default), the last-modified and last-access times are copied as well.\\n If \\\\update\\\\ is true, \\\\src\\\\ will only be copied if \\\\dst\\\\ does not exist,\\n or if \\\\dst\\\\ does exist but is older than \\\\src\\\\.\\n \\\\link\\\\ allows you to make hard links (os.link) or symbolic links\\n (os.symlink) instead of copying: set it to \\\"hard\\\" or \\\"sym\\\"; if it is\\n None (the default), files are copied. Don\\\\t set \\\\link\\\\ on systems that\\n don\\\\t support it: \\\\copy_file()\\\\ doesn\\\\t check if hard or symbolic\\n linking is available.\\n Under Mac OS, uses the native file copy function in macostools; on\\n other systems, uses \\\\_copy_file_contents()\\\\ to copy file contents.\\n Return a tuple (dest_name, copied): \\\\dest_name\\\\ is the actual name of\\n the output file, and \\\\copied\\\\ is true if the file was copied (or would\\n have been copied, if \\\\dry_run\\\\ true).\\n \\\"\\\"\\\"\\n from distutils.dep_util import newer\\n from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE\\n if (not os.path.isfile(src)):\\n raise DistutilsFileError((\\\"can't copy '%s': doesn't exist or not a regular file\\\" % src))\\n if os.path.isdir(dst):\\n dir = dst\\n dst = os.path.join(dst, os.path.basename(src))\\n else:\\n dir = os.path.dirname(dst)\\n if (update and (not newer(src, dst))):\\n if (verbose >= 1):\\n log.debug('not copying %s (output up-to-date)', src)\\n return (dst, 0)\\n try:\\n action = _copy_action[link]\\n except KeyError:\\n raise ValueError((\\\"invalid value '%s' for 'link' argument\\\" % link))\\n if (verbose >= 1):\\n if (os.path.basename(dst) == os.path.basename(src)):\\n log.info('%s %s -> %s', action, src, dir)\\n else:\\n log.info('%s %s -> %s', action, src, dst)\\n if dry_run:\\n return (dst, 1)\\n if (link == 'hard'):\\n if (not (os.path.exists(dst) and os.path.samefile(src, dst))):\\n os.link(src, dst)\\n elif (link == 'sym'):\\n if (not (os.path.exists(dst) and os.path.samefile(src, dst))):\\n os.symlink(src, dst)\\n else:\\n _copy_file_contents(src, dst)\\n if (preserve_mode or preserve_times):\\n st = os.stat(src)\\n if preserve_times:\\n os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))\\n if preserve_mode:\\n os.chmod(dst, S_IMODE(st[ST_MODE]))\\n return (dst, 1)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef bulk_item_promo(order):\\n\\n ''''10% discount for each LineItem with 20 or more units'\\n '''\",\"targets\":\"discount = 0\\n for item in order.cart:\\n if (item.quantity >= 20):\\n discount += (item.total() * 0.1)\\n return discount\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getDisplayToolButtonsRepository(directoryPath, importantFileNames, names, repository):\",\"targets\":\"\\\"\\\"\\\"Get the display tool buttons.\\n \\\"\\\"\\\"\\n displayToolButtons = []\\n for name in names:\\n displayToolButton = DisplayToolButton().getFromPath((name in importantFileNames), name, os.path.join(directoryPath, name), repository)\\n displayToolButtons.append(displayToolButton)\\n return displayToolButtons\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_api_version(resource_type):\\n\\n ''''Get the current API version for a given resource_type.\\n :param resource_type: The resource type.\\n :type resource_type: ResourceType.\\n :returns: str -- The API version.'\\n '''\",\"targets\":\"from azure.cli.core._profile import CLOUD\\n return _sdk_get_api_version(CLOUD.profile, resource_type)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n code = int(code)\\n if (not (1 <= code <= 2147483647)):\\n raise ValueError('code out of range')\\n key = (module, name)\\n if ((_extension_registry.get(key) == code) and (_inverted_registry.get(code) == key)):\\n return\\n if (key in _extension_registry):\\n raise ValueError(('key %s is already registered with code %s' % (key, _extension_registry[key])))\\n if (code in _inverted_registry):\\n raise ValueError(('code %s is already in use for key %s' % (code, _inverted_registry[code])))\\n _extension_registry[key] = code\\n _inverted_registry[code] = key\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_extension(module, name, code):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if target_outdated(target, deps):\\n system(cmd)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def target_update(target, deps, cmd):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef listing(output_lines):\\n\\n ''''Return list of dicts with basic item info parsed from cli output.'\\n '''\",\"targets\":\"items = []\\n table_ = table(output_lines)\\n for row in table_['values']:\\n item = {}\\n for (col_idx, col_key) in enumerate(table_['headers']):\\n item[col_key] = row[col_idx]\\n items.append(item)\\n return items\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def CopyFiles(rebalance, server_id):\",\"targets\":\"\\\"\\\"\\\"Copies data store files to the corresponding data servers.\\n \\\"\\\"\\\"\\n loc = data_store.DB.Location()\\n if (not os.path.exists(loc)):\\n return True\\n if (not os.path.isdir(loc)):\\n return True\\n pool_cache = {}\\n removed_list = []\\n ok = _RecCopyFiles(rebalance, server_id, loc, '', pool_cache, removed_list)\\n if (not ok):\\n return False\\n remove_file = _FileWithRemoveList(loc, rebalance)\\n with open(remove_file, 'wb') as fp:\\n for f in removed_list:\\n fp.write((f.encode('utf8') + '\\\\n'))\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@pytest.mark.skipif(u'not HAS_SCIPY')\\ndef test_subpixel_gauss_1D():\\n\\n ''''Test subpixel accuracy of the integrate mode with gaussian 1D model.'\\n '''\",\"targets\":\"gauss_1D = Gaussian1D(1, 0, 0.1)\\n values = discretize_model(gauss_1D, ((-1), 2), mode=u'integrate', factor=100)\\n assert_allclose(values.sum(), (np.sqrt((2 * np.pi)) * 0.1), atol=1e-05)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n _validate_path(name)\\n if (not _GCS_BUCKET_REGEX.match(name)):\\n raise ValueError(('Bucket should be 3-63 characters long using only a-z,0-9, underscore, dash or dot but got %s' % name))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def validate_bucket_name(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef clean_ascii_chars(txt, charlist=None):\\n\\n ''''Remove ASCII control chars.\\n This is all control chars except \\\\t, \\\\n and \\\\r'\\n '''\",\"targets\":\"if (not txt):\\n return ''\\n global _ascii_pat\\n if (_ascii_pat is None):\\n chars = set(xrange(32))\\n chars.add(127)\\n for x in (9, 10, 13):\\n chars.remove(x)\\n _ascii_pat = re.compile(u'|'.join(map(unichr, chars)))\\n if (charlist is None):\\n pat = _ascii_pat\\n else:\\n pat = re.compile(u'|'.join(map(unichr, charlist)))\\n return pat.sub('', txt)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef CreateSummaryResults():\\n\\n ''''Process the resulting .plist file from the test and generate the html results'\\n '''\",\"targets\":\"errors = []\\n passes = []\\n current_path = os.path.join(_RESULTS_PATH, 'current')\\n schemes = GetCurrentSchemes()\\n test_path = os.path.join(current_path, options.conf)\\n print 'Creating summary results.'\\n for testname in _SUMMARY.keys():\\n if testname.endswith('.js'):\\n testname = testname[:(-3)]\\n temp_details = ''\\n filepath = (((test_path + '\\/') + testname) + '\\/Run 1\\/Automation Results.plist')\\n print filepath\\n xmldoc = ElementTree.parse(filepath)\\n dicts = xmldoc.findall('*\\/array\\/dict')\\n for tmpdict in dicts:\\n error = {}\\n tmppass = {}\\n if ((tmpdict.find('string').text == 'Error') and (int(tmpdict.find('integer').text) == 4)):\\n error['testname'] = tmpdict[3].text\\n error['timestamp'] = tmpdict.find('date').text\\n error['status'] = tmpdict[1].text\\n errors.append(error)\\n elif ((tmpdict.find('string').text == 'Pass') and (int(tmpdict.find('integer').text) == 4)):\\n tmppass['testname'] = tmpdict[3].text\\n tmppass['timestamp'] = tmpdict.find('date').text\\n tmppass['status'] = tmpdict[1].text\\n passes.append(tmppass)\\n elif (tmpdict[1].text == 'Debug'):\\n temp_details += (tmpdict[3].text + '\\\\n')\\n _SUMMARY[testname]['details'] = temp_details\\n if (not options.regen):\\n ProcessScreenshots(testname)\\n for image_name in GetImageNames(testname):\\n if (IsImageEqual(testname, image_name) is False):\\n _SUMMARY[testname]['warnings'][image_name] = 'Warning: The screenshot does not match the Baseline. Do you want to Accept the Current image as the new Baseline?'\\n _SUMMARY[testname]['alert'] = True\\n else:\\n _SUMMARY[testname]['warnings'][image_name] = None\\n fmt_args = {'errors': errors, 'passes': passes,...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef c_login_nodig(client):\\n\\n ''''logins, don\\\\'t dig its own room'\\n '''\",\"targets\":\"cname = (DUMMY_NAME % client.gid)\\n cpwd = (DUMMY_PWD % client.gid)\\n cmds = (('create %s %s' % (cname, cpwd)), ('connect %s %s' % (cname, cpwd)))\\n return cmds\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _gen_keep_files(name, require, walk_d=None):\\n\\n ''''Generate the list of files that need to be kept when a dir based function\\n like directory or recurse has a clean.'\\n '''\",\"targets\":\"def _is_child(path, directory):\\n '\\\\n Check whether ``path`` is child of ``directory``\\\\n '\\n path = os.path.abspath(path)\\n directory = os.path.abspath(directory)\\n relative = os.path.relpath(path, directory)\\n return (not relative.startswith(os.pardir))\\n def _add_current_path(path):\\n _ret = set()\\n if os.path.isdir(path):\\n (dirs, files) = walk_d.get(path, ((), ()))\\n _ret.add(path)\\n for _name in files:\\n _ret.add(os.path.join(path, _name))\\n for _name in dirs:\\n _ret.add(os.path.join(path, _name))\\n return _ret\\n def _process_by_walk_d(name, ret):\\n if os.path.isdir(name):\\n walk_ret.update(_add_current_path(name))\\n (dirs, _) = walk_d.get(name, ((), ()))\\n for _d in dirs:\\n p = os.path.join(name, _d)\\n walk_ret.update(_add_current_path(p))\\n _process_by_walk_d(p, ret)\\n def _process(name):\\n ret = set()\\n if os.path.isdir(name):\\n for (root, dirs, files) in os.walk(name):\\n ret.add(name)\\n for name in files:\\n ret.add(os.path.join(root, name))\\n for name in dirs:\\n ret.add(os.path.join(root, name))\\n return ret\\n keep = set()\\n if isinstance(require, list):\\n required_files = [comp for comp in require if ('file' in comp)]\\n for comp in required_files:\\n for low in __lowstate__:\\n if ((low['name'] == comp['file']) or (low['__id__'] == comp['file'])):\\n fn = low['name']\\n fun = low['fun']\\n if os.path.isdir(fn):\\n if _is_child(fn, name):\\n if (fun == 'recurse'):\\n fkeep = _gen_recurse_managed_files(**low)[3]\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n entities = entities.copy()\\n entities.update({'\\\\n': ' ', '\\\\r': ' ', ' DCTB ': ' '})\\n data = escape(data, entities)\\n if ('\\\"' in data):\\n if (\\\"'\\\" in data):\\n data = ('\\\"%s\\\"' % data.replace('\\\"', '"'))\\n else:\\n data = (\\\"'%s'\\\" % data)\\n else:\\n data = ('\\\"%s\\\"' % data)\\n return data\\n\\n\\nWhat's a good function header?\",\"targets\":\"def quoteattr(data, entities={}):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n length = (max((len(str(s)) for s in str_list)) + extra)\\n def pad(string):\\n string = str(string)\\n padding = max(0, (length - len(string)))\\n return (string + (padding * ' '))\\n return pad\\n\\n\\nWhat's a good function header?\",\"targets\":\"def padder(str_list, extra=0):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def downgrade(migrate_engine):\",\"targets\":\"\\\"\\\"\\\"Call the correct dialect-specific downgrade.\\n \\\"\\\"\\\"\\n meta.bind = migrate_engine\\n t_images = _get_table('images', meta)\\n t_image_members = _get_table('image_members', meta)\\n t_image_properties = _get_table('image_properties', meta)\\n dialect = migrate_engine.url.get_dialect().name\\n if (dialect == 'sqlite'):\\n _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)\\n _downgrade_sqlite(t_images, t_image_members, t_image_properties)\\n else:\\n _downgrade_other(t_images, t_image_members, t_image_properties, dialect)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef debug(module, name, pm=False):\\n\\n ''''Debug a single doctest docstring.\\n Provide the module (or dotted name of the module) containing the\\n test to be debugged and the name (within the module) of the object\\n with the docstring with tests to be debugged.'\\n '''\",\"targets\":\"module = _normalize_module(module)\\n testsrc = testsource(module, name)\\n debug_script(testsrc, pm, module.__dict__)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n path = '\\/opt\\/mellanox\\/mxm'\\n if os.path.isdir(path):\\n return path\\n else:\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _mxm_dir():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n random_state = check_random_state(random_state)\\n X = check_array(X, ensure_min_samples=2, estimator='fast_mcd')\\n (n_samples, n_features) = X.shape\\n if (support_fraction is None):\\n n_support = int(np.ceil((0.5 * ((n_samples + n_features) + 1))))\\n else:\\n n_support = int((support_fraction * n_samples))\\n if (n_features == 1):\\n if (n_support < n_samples):\\n X_sorted = np.sort(np.ravel(X))\\n diff = (X_sorted[n_support:] - X_sorted[:(n_samples - n_support)])\\n halves_start = np.where((diff == np.min(diff)))[0]\\n location = (0.5 * (X_sorted[(n_support + halves_start)] + X_sorted[halves_start]).mean())\\n support = np.zeros(n_samples, dtype=bool)\\n X_centered = (X - location)\\n support[np.argsort(np.abs(X_centered), 0)[:n_support]] = True\\n covariance = np.asarray([[np.var(X[support])]])\\n location = np.array([location])\\n precision = linalg.pinvh(covariance)\\n dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1)\\n else:\\n support = np.ones(n_samples, dtype=bool)\\n covariance = np.asarray([[np.var(X)]])\\n location = np.asarray([np.mean(X)])\\n X_centered = (X - location)\\n precision = linalg.pinvh(covariance)\\n dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1)\\n if ((n_samples > 500) and (n_features > 1)):\\n n_subsets = (n_samples \\/\\/ 300)\\n n_samples_subsets = (n_samples \\/\\/ n_subsets)\\n samples_shuffle = random_state.permutation(n_samples)\\n h_subset = int(np.ceil((n_samples_subsets * (n_support \\/ float(n_samples)))))\\n n_trials_tot = 500\\n n_best_sub = 10\\n n_trials = max(10, (n_trials_tot \\/\\/ n_subsets))\\n n_best_tot = (n_subsets * n_best_sub)\\n all_best_locations = np.zeros((n_best_tot, n_features))\\n try:\\n all_best_covariances = np.zeros((n_best_tot, n_features, n_features))\\n except MemoryError:\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def fast_mcd(X, support_fraction=None, cov_computation_method=empirical_covariance, random_state=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (sys.platform not in supported_platforms):\\n return (system, release, version)\\n for cmd in ('ver', 'command \\/c ver', 'cmd \\/c ver'):\\n try:\\n pipe = popen(cmd)\\n info = pipe.read()\\n if pipe.close():\\n raise OSError('command failed')\\n except OSError as why:\\n continue\\n else:\\n break\\n else:\\n return (system, release, version)\\n info = info.strip()\\n m = _ver_output.match(info)\\n if (m is not None):\\n (system, release, version) = m.groups()\\n if (release[(-1)] == '.'):\\n release = release[:(-1)]\\n if (version[(-1)] == '.'):\\n version = version[:(-1)]\\n version = _norm_version(version)\\n return (system, release, version)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _syscmd_ver(system='', release='', version='', supported_platforms=('win32', 'win16', 'dos')):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n kwargs.setdefault('autoflush', False)\\n kwargs.setdefault('autocommit', True)\\n kwargs.setdefault('expire_on_commit', False)\\n return Session(bind=bind, **kwargs)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def create_session(bind=None, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (getattr(package, '__name__', None) == '__main__'):\\n return abspath\\n pp = (package_path(package) + os.path.sep)\\n if abspath.startswith(pp):\\n relpath = abspath[len(pp):]\\n return ('%s:%s' % (package_name(package), relpath.replace(os.path.sep, '\\/')))\\n return abspath\\n\\n\\nWhat's a good function header?\",\"targets\":\"def asset_spec_from_abspath(abspath, package):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n json_tags[(TAG_PREFIX + getattr(cls, 'json_tag'))] = cls\\n return cls\\n\\n\\nWhat's a good function header?\",\"targets\":\"def register_tag(cls):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):\\n\\n ''''Deserialize ``fp`` (a ``.read()``-supporting file-like object containing\\n a JSON document) to a Python object.\\n ``object_hook`` is an optional function that will be called with the\\n result of any object literal decode (a ``dict``). The return value of\\n ``object_hook`` will be used instead of the ``dict``. This feature\\n can be used to implement custom decoders (e.g. JSON-RPC class hinting).\\n ``object_pairs_hook`` is an optional function that will be called with the\\n result of any object literal decoded with an ordered list of pairs. The\\n return value of ``object_pairs_hook`` will be used instead of the ``dict``.\\n This feature can be used to implement custom decoders that rely on the\\n order that the key and value pairs are decoded (for example,\\n collections.OrderedDict will remember the order of insertion). If\\n ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.\\n To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``\\n kwarg; otherwise ``JSONDecoder`` is used.'\\n '''\",\"targets\":\"return loads(fp.read(), cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _sphere_to_cartesian(theta, phi, r):\\n\\n ''''Convert using old function.'\\n '''\",\"targets\":\"z = (r * np.sin(phi))\\n rcos_phi = (r * np.cos(phi))\\n x = (rcos_phi * np.cos(theta))\\n y = (rcos_phi * np.sin(theta))\\n return (x, y, z)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n opts_pillar = opts.get('pillar', {})\\n opts_master = opts_pillar.get('master', {})\\n opts_merged = {}\\n opts_merged.update(opts_master)\\n opts_merged.update(opts_pillar)\\n opts_merged.update(opts)\\n if profile:\\n conf = opts_merged.get(profile, {})\\n else:\\n conf = opts_merged\\n params = {}\\n for key in conf:\\n if key.startswith('consul.'):\\n params[key.split('.')[1]] = conf[key]\\n if ('dc' in params):\\n pillarenv = (opts_merged.get('pillarenv') or 'base')\\n params['dc'] = _resolve_datacenter(params['dc'], pillarenv)\\n if HAS_CONSUL:\\n if ((CONSUL_VERSION < '0.4.7') and params.get('target')):\\n params.pop('target')\\n return consul.Consul(**params)\\n else:\\n raise CommandExecutionError('(unable to import consul, module most likely not installed. Download python-consul module and be sure to import consul)')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_conn(opts, profile):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getAroundsFromLoops(loops, radius, thresholdRatio=0.9):\\n\\n ''''Get the arounds from the loops.'\\n '''\",\"targets\":\"return getAroundsFromPoints(getPointsFromLoops(loops, radius, thresholdRatio), radius)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not callable(key)):\\n key = getter(key)\\n return frequencies(map(key, seq))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def countby(key, seq):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def each_setup_in_pkg(top_dir):\",\"targets\":\"\\\"\\\"\\\"Yield path and file object for each setup.py file\\n \\\"\\\"\\\"\\n for (dir_path, dir_names, filenames) in os.walk(top_dir):\\n for fname in filenames:\\n if (fname == 'setup.py'):\\n with open(os.path.join(dir_path, 'setup.py')) as f:\\n (yield (dir_path, f))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef calculate_group_counts(messages, user_email):\\n\\n ''''Strips out most of the logic from calculate_group_scores\\n algorithm and just returns raw counts for each group.'\\n '''\",\"targets\":\"res = defaultdict(int)\\n for msg in messages:\\n participants = _get_participants(msg, [user_email])\\n if (len(participants) >= MIN_GROUP_SIZE):\\n res[', '.join(participants)] += 1\\n return res\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def find_management_module(app_name):\",\"targets\":\"\\\"\\\"\\\"Determines the path to the management module for the given app_name,\\n without actually importing the application or the management module.\\n Raises ImportError if the management module cannot be found for any reason.\\n \\\"\\\"\\\"\\n parts = app_name.split('.')\\n parts.append('management')\\n parts.reverse()\\n part = parts.pop()\\n path = None\\n try:\\n (f, path, descr) = imp.find_module(part, path)\\n except ImportError as e:\\n if (os.path.basename(os.getcwd()) != part):\\n raise e\\n while parts:\\n part = parts.pop()\\n (f, path, descr) = imp.find_module(part, ((path and [path]) or None))\\n return path\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n indentation = _get_indentation(logical_line)\\n return ((indentation + untokenize_without_newlines(generate_tokens(logical_line.lstrip()))) + u'\\\\n')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def join_logical_line(logical_line):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def isestimable(C, D):\",\"targets\":\"\\\"\\\"\\\"True if (Q, P) contrast `C` is estimable for (N, P) design `D`\\n From an Q x P contrast matrix `C` and an N x P design matrix `D`, checks if\\n the contrast `C` is estimable by looking at the rank of ``vstack([C,D])``\\n and verifying it is the same as the rank of `D`.\\n Parameters\\n C : (Q, P) array-like\\n contrast matrix. If `C` has is 1 dimensional assume shape (1, P)\\n D: (N, P) array-like\\n design matrix\\n Returns\\n tf : bool\\n True if the contrast `C` is estimable on design `D`\\n Examples\\n >>> D = np.array([[1, 1, 1, 0, 0, 0],\\n ... [0, 0, 0, 1, 1, 1],\\n ... [1, 1, 1, 1, 1, 1]]).T\\n >>> isestimable([1, 0, 0], D)\\n False\\n >>> isestimable([1, -1, 0], D)\\n True\\n \\\"\\\"\\\"\\n C = np.asarray(C)\\n D = np.asarray(D)\\n if (C.ndim == 1):\\n C = C[None, :]\\n if (C.shape[1] != D.shape[1]):\\n raise ValueError(('Contrast should have %d columns' % D.shape[1]))\\n new = np.vstack([C, D])\\n if (np_matrix_rank(new) != np_matrix_rank(D)):\\n return False\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _format_state_result(name, result, changes=None, comment=''):\\n\\n ''''Creates the state result dictionary.'\\n '''\",\"targets\":\"if (changes is None):\\n changes = {'old': '', 'new': ''}\\n return {'name': name, 'result': result, 'changes': changes, 'comment': comment}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_issues_in_bulk(bulk_data, callback=None, precall=None, **additional_fields):\",\"targets\":\"\\\"\\\"\\\"Create issues from `bulk_data`.\\n :param bulk_data: List of issues in bulk format.\\n :param callback: Callback to execute after each issue save.\\n :param additional_fields: Additional fields when instantiating each issue.\\n :return: List of created `Issue` instances.\\n \\\"\\\"\\\"\\n issues = get_issues_from_bulk(bulk_data, **additional_fields)\\n disconnect_issues_signals()\\n try:\\n db.save_in_bulk(issues, callback, precall)\\n finally:\\n connect_issues_signals()\\n return issues\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __get_ssh_interface(vm_):\",\"targets\":\"\\\"\\\"\\\"Return the ssh_interface type to connect to. Either \\\\public_ips\\\\ (default)\\n or \\\\private_ips\\\\.\\n \\\"\\\"\\\"\\n return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_version_from_git(pre_version):\\n\\n ''''Return a version which is equal to the tag that\\\\'s on the current\\n revision if there is one, or tag plus number of additional revisions\\n if the current revision has no tag.'\\n '''\",\"targets\":\"git_dir = _get_git_directory()\\n if git_dir:\\n if pre_version:\\n try:\\n return _run_shell_command((('git --git-dir=' + git_dir) + ' describe --exact-match'), throw_on_error=True).replace('-', '.')\\n except Exception:\\n sha = _run_shell_command((('git --git-dir=' + git_dir) + ' log -n1 --pretty=format:%h'))\\n return ('%s.a%s.g%s' % (pre_version, _get_revno(git_dir), sha))\\n else:\\n return _run_shell_command((('git --git-dir=' + git_dir) + ' describe --always')).replace('-', '.')\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def expandvars(path):\",\"targets\":\"\\\"\\\"\\\"Expand shell variables of the forms $var, ${var} and %var%.\\n Unknown variables are left unchanged.\\n \\\"\\\"\\\"\\n if (('$' not in path) and ('%' not in path)):\\n return path\\n import string\\n varchars = ((string.ascii_letters + string.digits) + '_-')\\n if isinstance(path, _unicode):\\n encoding = sys.getfilesystemencoding()\\n def getenv(var):\\n return os.environ[var.encode(encoding)].decode(encoding)\\n else:\\n def getenv(var):\\n return os.environ[var]\\n res = ''\\n index = 0\\n pathlen = len(path)\\n while (index < pathlen):\\n c = path[index]\\n if (c == \\\"'\\\"):\\n path = path[(index + 1):]\\n pathlen = len(path)\\n try:\\n index = path.index(\\\"'\\\")\\n res = ((res + \\\"'\\\") + path[:(index + 1)])\\n except ValueError:\\n res = ((res + c) + path)\\n index = (pathlen - 1)\\n elif (c == '%'):\\n if (path[(index + 1):(index + 2)] == '%'):\\n res = (res + c)\\n index = (index + 1)\\n else:\\n path = path[(index + 1):]\\n pathlen = len(path)\\n try:\\n index = path.index('%')\\n except ValueError:\\n res = ((res + '%') + path)\\n index = (pathlen - 1)\\n else:\\n var = path[:index]\\n try:\\n res = (res + getenv(var))\\n except KeyError:\\n res = (((res + '%') + var) + '%')\\n elif (c == '$'):\\n if (path[(index + 1):(index + 2)] == '$'):\\n res = (res + c)\\n index = (index + 1)\\n elif (path[(index + 1):(index + 2)] == '{'):\\n path = path[(index + 2):]\\n pathlen = len(path)\\n try:\\n index = path.index('}')\\n var = path[:index]\\n try:\\n res = (res + getenv(var))\\n except KeyError:\\n res = (((res + '${') + var) + '}')\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _configure(changes):\",\"targets\":\"\\\"\\\"\\\"Calls the configuration template to apply the configuration changes on the device.\\n \\\"\\\"\\\"\\n cfgred = True\\n reasons = []\\n fun = 'update_config'\\n for key in ['added', 'updated', 'removed']:\\n _updated_changes = changes.get(key, {})\\n if (not _updated_changes):\\n continue\\n _location = _updated_changes.get('location', '')\\n _contact = _updated_changes.get('contact', '')\\n _community = _updated_changes.get('community', {})\\n _chassis_id = _updated_changes.get('chassis_id', '')\\n if (key == 'removed'):\\n fun = 'remove_config'\\n _ret = __salt__['snmp.{fun}'.format(fun=fun)](location=_location, contact=_contact, community=_community, chassis_id=_chassis_id, commit=False)\\n cfgred = (cfgred and _ret.get('result'))\\n if ((not _ret.get('result')) and _ret.get('comment')):\\n reasons.append(_ret.get('comment'))\\n return {'result': cfgred, 'comment': ('\\\\n'.join(reasons) if reasons else '')}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _encode_objectid(name, value, dummy0, dummy1):\",\"targets\":\"\\\"\\\"\\\"Encode bson.objectid.ObjectId.\\n \\\"\\\"\\\"\\n return (('\\\\x07' + name) + value.binary)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (utype, vtype) = (None, None)\\n if (not (hasattr(u, 'dtype') and np.issubdtype(u.dtype, np.inexact))):\\n utype = np.float64\\n if (not (hasattr(v, 'dtype') and np.issubdtype(v.dtype, np.inexact))):\\n vtype = np.float64\\n u = _validate_vector(u, dtype=utype)\\n v = _validate_vector(v, dtype=vtype)\\n u_v = (u - v)\\n return np.dot(u_v, u_v)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def sqeuclidean(u, v):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def do_default(value, default_value=u'', boolean=False):\",\"targets\":\"\\\"\\\"\\\"If the value is undefined it will return the passed default value,\\n otherwise the value of the variable:\\n .. sourcecode:: jinja\\n {{ my_variable|default(\\\\my_variable is not defined\\\\) }}\\n This will output the value of ``my_variable`` if the variable was\\n defined, otherwise ``\\\\my_variable is not defined\\\\``. If you want\\n to use default with variables that evaluate to false you have to\\n set the second parameter to `true`:\\n .. sourcecode:: jinja\\n {{ \\\\\\\\|default(\\\\the string was empty\\\\, true) }}\\n \\\"\\\"\\\"\\n if ((boolean and (not value)) or isinstance(value, Undefined)):\\n return default_value\\n return value\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if namespace:\\n return db.Key.from_path(metadata.Namespace.KIND_NAME, namespace, _app=app)\\n else:\\n return db.Key.from_path(metadata.Namespace.KIND_NAME, metadata.Namespace.EMPTY_NAMESPACE_ID, _app=app)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _key_for_namespace(namespace, app):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef assert_quantities_allclose(coord, q1s, attrs):\\n\\n ''''Compare two tuples of quantities. This assumes that the values in q1 are of\\n order(1) and uses atol=1e-13, rtol=0. It also asserts that the units of the\\n two quantities are the *same*, in order to check that the representation\\n output has the expected units.'\\n '''\",\"targets\":\"q2s = [getattr(coord, attr) for attr in attrs]\\n assert (len(q1s) == len(q2s))\\n for (q1, q2) in zip(q1s, q2s):\\n assert (q1.shape == q2.shape)\\n assert allclose(q1, q2, rtol=0, atol=(1e-13 * q1.unit))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n path = (dirname(dirname(abspath(__file__))) if (path is None) else path)\\n repo_name = basename(path)\\n repo = git.Repo(path)\\n create_git_index(client, index)\\n client.create(index=index, doc_type='repos', id=repo_name, body={}, ignore=409)\\n for (ok, result) in streaming_bulk(client, parse_commits(repo.refs.master.commit, repo_name), index=index, doc_type='commits', chunk_size=50):\\n (action, result) = result.popitem()\\n doc_id = ('\\/%s\\/commits\\/%s' % (index, result['_id']))\\n if (not ok):\\n print(('Failed to %s document %s: %r' % (action, doc_id, result)))\\n else:\\n print(doc_id)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def load_repo(client, path=None, index='git'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef custom_key_func(key, key_prefix, version):\\n\\n ''''A customized cache key function'\\n '''\",\"targets\":\"return ('CUSTOM-' + '-'.join([key_prefix, str(version), key]))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef expand_log(expr, deep=True, force=False):\\n\\n ''''Wrapper around expand that only uses the log hint. See the expand\\n docstring for more information.\\n Examples\\n >>> from sympy import symbols, expand_log, exp, log\\n >>> x, y = symbols(\\\\'x,y\\\\', positive=True)\\n >>> expand_log(exp(x+y)*(x+y)*log(x*y**2))\\n (x + y)*(log(x) + 2*log(y))*exp(x + y)'\\n '''\",\"targets\":\"return sympify(expr).expand(deep=deep, log=True, mul=False, power_exp=False, power_base=False, multinomial=False, basic=False, force=force)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef devname(pcap_name):\\n\\n ''''Return libdnet\\/Scapy device name for given pypcap device name'\\n '''\",\"targets\":\"return ifaces.devname(pcap_name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n class K(object, ):\\n def __init__(self, obj):\\n self.obj = obj\\n def __lt__(self, other):\\n return (mycmp(self.obj, other.obj) == (-1))\\n return K\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _CmpToKey(mycmp):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef format_out_of_country_keeping_alpha_chars(numobj, region_calling_from):\\n\\n ''''Formats a phone number for out-of-country dialing purposes.\\n Note that in this version, if the number was entered originally using\\n alpha characters and this version of the number is stored in raw_input,\\n this representation of the number will be used rather than the digit\\n representation. Grouping information, as specified by characters such as\\n \\\"-\\\" and \\\" \\\", will be retained.\\n Caveats:\\n - This will not produce good results if the country calling code is both\\n present in the raw input _and_ is the start of the national\\n number. This is not a problem in the regions which typically use alpha\\n numbers.\\n - This will also not produce good results if the raw input has any\\n grouping information within the first three digits of the national\\n number, and if the function needs to strip preceding digits\\/words in\\n the raw input before these digits. Normally people group the first\\n three digits together so this is not a huge problem - and will be fixed\\n if it proves to be so.\\n Arguments:\\n numobj -- The phone number that needs to be formatted.\\n region_calling_from -- The region where the call is being placed.\\n Returns the formatted phone number'\\n '''\",\"targets\":\"num_raw_input = numobj.raw_input\\n if ((num_raw_input is None) or (len(num_raw_input) == 0)):\\n return format_out_of_country_calling_number(numobj, region_calling_from)\\n country_code = numobj.country_code\\n if (not _has_valid_country_calling_code(country_code)):\\n return num_raw_input\\n num_raw_input = _normalize_helper(num_raw_input, _ALL_PLUS_NUMBER_GROUPING_SYMBOLS, True)\\n national_number = national_significant_number(numobj)\\n if (len(national_number) > 3):\\n first_national_number_digit = num_raw_input.find(national_number[:3])\\n if (first_national_number_digit != (-1)):\\n num_raw_input = num_raw_input[first_national_number_digit:]\\n metadata_for_region_calling_from = PhoneMetadata.metadata_for_region(region_calling_from.upper(), None)\\n if (country_code == _NANPA_COUNTRY_CODE):\\n if is_nanpa_country(region_calling_from):\\n return ((unicod(country_code) + U_SPACE) + num_raw_input)\\n elif ((metadata_for_region_calling_from is not None) and (country_code == country_code_for_region(region_calling_from))):\\n formatting_pattern = _choose_formatting_pattern_for_number(metadata_for_region_calling_from.number_format, national_number)\\n if (formatting_pattern is None):\\n return num_raw_input\\n new_format = _copy_number_format(formatting_pattern)\\n new_format.pattern = u('(\\\\\\\\d+)(.*)')\\n new_format.format = u('\\\\\\\\1\\\\\\\\2')\\n return _format_nsn_using_pattern(num_raw_input, new_format, PhoneNumberFormat.NATIONAL)\\n i18n_prefix_for_formatting = U_EMPTY_STRING\\n if (metadata_for_region_calling_from is not None):\\n international_prefix = metadata_for_region_calling_from.international_prefix\\n i18n_match = fullmatch(_UNIQUE_INTERNATIONAL_PREFIX, international_prefix)\\n if i18n_match:\\n i18n_prefix_for_formatting = international_prefix\\n else:\\n i18n_prefix_for_formatting = metadata_for_region_calling_from.preferred_international_prefix\\n region_code =...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def artifactory_generic(registry, xml_parent, data):\",\"targets\":\"\\\"\\\"\\\"yaml: artifactory-generic\\n Wrapper for non-Maven projects. Requires the\\n :jenkins-wiki:`Artifactory Plugin `\\n :arg str url: URL of the Artifactory server. e.g.\\n https:\\/\\/www.jfrog.com\\/artifactory\\/ (default \\\\\\\\)\\n :arg str name: Artifactory user with permissions use for\\n connected to the selected Artifactory Server\\n (default \\\\\\\\)\\n :arg str repo-key: Release repository name (plugin < 2.3.0) (default \\\\\\\\)\\n :arg str snapshot-repo-key: Snapshots repository name (plugin < 2.3.0)\\n (default \\\\\\\\)\\n :arg str key-from-select: Repository key to use (plugin >= 2.3.0)\\n (default \\\\\\\\)\\n :arg str key-from-text: Repository key to use that can be configured\\n dynamically using Jenkins variables (plugin >= 2.3.0) (default \\\\\\\\)\\n :arg list deploy-pattern: List of patterns for mappings\\n build artifacts to published artifacts. Supports Ant-style wildcards\\n mapping to target directories. E.g.: *\\/*.zip=>dir (default [])\\n :arg list resolve-pattern: List of references to other\\n artifacts that this build should use as dependencies.\\n :arg list matrix-params: List of properties to attach to all deployed\\n artifacts in addition to the default ones: build.name, build.number,\\n and vcs.revision (default [])\\n :arg bool deploy-build-info: Deploy jenkins build metadata with\\n artifacts to Artifactory (default false)\\n :arg bool env-vars-include: Include environment variables accessible by\\n the build process. Jenkins-specific env variables are always included.\\n Use the env-vars-include-patterns and env-vars-exclude-patterns to\\n filter the environment variables published to artifactory.\\n (default false)\\n :arg list env-vars-include-patterns: List of environment variable patterns\\n for including env vars as part of the published build info. Environment\\n variables may contain the * and the ? wildcards (default [])\\n :arg list env-vars-exclude-patterns: List of environment variable patterns\\n that determine the env vars excluded from the published...\\\"\\\"\\\"\\n artifactory = XML.SubElement(xml_parent, 'org.jfrog.hudson.generic.ArtifactoryGenericConfigurator')\\n details = XML.SubElement(artifactory, 'details')\\n artifactory_common_details(details, data)\\n info = registry.get_plugin_info('artifactory')\\n version = pkg_resources.parse_version(info.get('version', '0'))\\n if (version >= pkg_resources.parse_version('2.3.0')):\\n deployReleaseRepo = XML.SubElement(details, 'deployReleaseRepository')\\n XML.SubElement(deployReleaseRepo, 'keyFromText').text = data.get('key-from-text', '')\\n XML.SubElement(deployReleaseRepo, 'keyFromSelect').text = data.get('key-from-select', '')\\n XML.SubElement(deployReleaseRepo, 'dynamicMode').text = str(('key-from-text' in data.keys())).lower()\\n else:\\n XML.SubElement(details, 'repositoryKey').text = data.get('repo-key', '')\\n XML.SubElement(details, 'snapshotsRepositoryKey').text = data.get('snapshot-repo-key', '')\\n XML.SubElement(artifactory, 'deployPattern').text = ','.join(data.get('deploy-pattern', []))\\n XML.SubElement(artifactory, 'resolvePattern').text = ','.join(data.get('resolve-pattern', []))\\n XML.SubElement(artifactory, 'matrixParams').text = ','.join(data.get('matrix-params', []))\\n XML.SubElement(artifactory, 'deployBuildInfo').text = str(data.get('deploy-build-info', False)).lower()\\n XML.SubElement(artifactory, 'includeEnvVars').text = str(data.get('env-vars-include', False)).lower()\\n XML.SubElement(artifactory, 'discardOldBuilds').text = str(data.get('discard-old-builds', False)).lower()\\n XML.SubElement(artifactory, 'discardBuildArtifacts').text = str(data.get('discard-build-artifacts', True)).lower()\\n artifactory_env_vars_patterns(artifactory, data)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_computer_name():\\n\\n ''''Get hostname.\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' network.get_hostname'\\n '''\",\"targets\":\"return __salt__['network.get_hostname']()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (G.name == ''):\\n name = 'NetworkX'\\n else:\\n name = G.name\\n (yield ('*vertices %s' % G.order()))\\n nodes = list(G)\\n nodenumber = dict(zip(nodes, range(1, (len(nodes) + 1))))\\n for n in nodes:\\n na = G.node.get(n, {})\\n x = na.get('x', 0.0)\\n y = na.get('y', 0.0)\\n id = int(na.get('id', nodenumber[n]))\\n nodenumber[n] = id\\n shape = na.get('shape', 'ellipse')\\n s = ' '.join(map(make_qstr, (id, n, x, y, shape)))\\n for (k, v) in na.items():\\n if (v.strip() != ''):\\n s += (' %s %s' % (make_qstr(k), make_qstr(v)))\\n (yield s)\\n if G.is_directed():\\n (yield '*arcs')\\n else:\\n (yield '*edges')\\n for (u, v, edgedata) in G.edges(data=True):\\n d = edgedata.copy()\\n value = d.pop('weight', 1.0)\\n s = ' '.join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))\\n for (k, v) in d.items():\\n if (v.strip() != ''):\\n s += (' %s %s' % (make_qstr(k), make_qstr(v)))\\n (yield s)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def generate_pajek(G):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def concrete(seq):\",\"targets\":\"\\\"\\\"\\\"Make nested iterators concrete lists\\n >>> data = [[1, 2], [3, 4]]\\n >>> seq = iter(map(iter, data))\\n >>> concrete(seq)\\n [[1, 2], [3, 4]]\\n \\\"\\\"\\\"\\n if isinstance(seq, Iterator):\\n seq = list(seq)\\n if isinstance(seq, (tuple, list)):\\n seq = list(map(concrete, seq))\\n return seq\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (call == 'action'):\\n raise SaltCloudSystemExit('The list_nodes function must be called with -f or --function.')\\n ret = {}\\n conn = get_conn()\\n server_list = conn.server_list()\\n if (not server_list):\\n return {}\\n for server in server_list:\\n server_tmp = conn.server_show(server_list[server]['id']).get(server)\\n if (server_tmp is None):\\n continue\\n private = []\\n public = []\\n if ('addresses' not in server_tmp):\\n server_tmp['addresses'] = {}\\n for network in server_tmp['addresses']:\\n for address in server_tmp['addresses'][network]:\\n if salt.utils.cloud.is_public_ip(address.get('addr', '')):\\n public.append(address['addr'])\\n elif (':' in address['addr']):\\n public.append(address['addr'])\\n elif ('.' in address['addr']):\\n private.append(address['addr'])\\n if server_tmp['accessIPv4']:\\n if salt.utils.cloud.is_public_ip(server_tmp['accessIPv4']):\\n public.append(server_tmp['accessIPv4'])\\n else:\\n private.append(server_tmp['accessIPv4'])\\n if server_tmp['accessIPv6']:\\n public.append(server_tmp['accessIPv6'])\\n ret[server] = {'id': server_tmp['id'], 'image': server_tmp['image']['id'], 'size': server_tmp['flavor']['id'], 'state': server_tmp['state'], 'private_ips': private, 'public_ips': public}\\n return ret\\n\\n\\nWhat's a good function header?\",\"targets\":\"def list_nodes(call=None, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_tests_info(input_dir, msg_dir, prefix, suffix):\\n\\n ''''get python input examples and output messages\\n We use following conventions for input files and messages:\\n for different inputs:\\n test for python >= x.y -> input = _pyxy.py\\n test for python < x.y -> input = _py_xy.py\\n for one input and different messages:\\n message for python >= x.y -> message = _pyxy.txt\\n lower versions -> message with highest num'\\n '''\",\"targets\":\"result = []\\n for fname in glob(join(input_dir, ((prefix + '*') + suffix))):\\n infile = basename(fname)\\n fbase = splitext(infile)[0]\\n pyrestr = fbase.rsplit('_py', 1)[(-1)]\\n if pyrestr.isdigit():\\n if (SYS_VERS_STR < pyrestr):\\n continue\\n if (pyrestr.startswith('_') and pyrestr[1:].isdigit()):\\n if (SYS_VERS_STR >= pyrestr[1:]):\\n continue\\n messages = glob(join(msg_dir, (fbase + '*.txt')))\\n if messages:\\n for outfile in sorted(messages, reverse=True):\\n py_rest = outfile.rsplit('_py', 1)[(-1)][:(-4)]\\n if (py_rest.isdigit() and (SYS_VERS_STR >= py_rest)):\\n break\\n else:\\n outfile = join(msg_dir, (fbase + '.txt'))\\n result.append((infile, outfile))\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_field_precision(df, doc=None, currency=None):\\n\\n ''''get precision based on DocField options and fieldvalue in doc'\\n '''\",\"targets\":\"from frappe.utils import get_number_format_info\\n if cint(df.precision):\\n precision = cint(df.precision)\\n elif (df.fieldtype == u'Currency'):\\n precision = cint(frappe.db.get_default(u'currency_precision'))\\n if (not precision):\\n number_format = (frappe.db.get_default(u'number_format') or u'#,###.##')\\n (decimal_str, comma_str, precision) = get_number_format_info(number_format)\\n else:\\n precision = (cint(frappe.db.get_default(u'float_precision')) or 3)\\n return precision\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n node = MockNode()\\n value = MockValue(data=0, node=node)\\n values = MockEntityValues(primary=value)\\n device = zwave.get_device(node=node, values=values, node_config={})\\n assert isinstance(device, zwave.ZwaveSwitch)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_get_device_detects_switch(mock_openzwave):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n conf = Config(None, {'type': 'alexa'})\\n number = conf.entity_id_to_number('light.test')\\n assert (number == 'light.test')\\n number = conf.entity_id_to_number('light.test')\\n assert (number == 'light.test')\\n number = conf.entity_id_to_number('light.test2')\\n assert (number == 'light.test2')\\n entity_id = conf.number_to_entity_id('light.test')\\n assert (entity_id == 'light.test')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_config_alexa_entity_id_to_number():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def addsitepackages(known_paths):\",\"targets\":\"\\\"\\\"\\\"Add site-packages (and possibly site-python) to sys.path\\n \\\"\\\"\\\"\\n for sitedir in getsitepackages():\\n if os.path.isdir(sitedir):\\n addsitedir(sitedir, known_paths)\\n return known_paths\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n @wraps(view_func)\\n def _checklogin(request, *args, **kwargs):\\n if (request.user.is_active and request.user.is_staff):\\n return view_func(request, *args, **kwargs)\\n assert hasattr(request, 'session'), \\\"The Django admin requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'.\\\"\\n defaults = {'template_name': 'admin\\/login.html', 'authentication_form': AdminAuthenticationForm, 'extra_context': {'title': _('Log in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path()}}\\n return login(request, **defaults)\\n return _checklogin\\n\\n\\nWhat's a good function header?\",\"targets\":\"def staff_member_required(view_func):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef debris_basin():\\n\\n ''''Debris Basins, RESTful controller'\\n '''\",\"targets\":\"return s3_rest_controller()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def inverse(x, n):\",\"targets\":\"\\\"\\\"\\\"Returns x^-1 (mod n)\\n >>> inverse(7, 4)\\n 3\\n >>> (inverse(143, 4) * 143) % 4\\n 1\\n \\\"\\\"\\\"\\n (divider, inv, _) = extended_gcd(x, n)\\n if (divider != 1):\\n raise ValueError(('x (%d) and n (%d) are not relatively prime' % (x, n)))\\n return inv\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not uri.startswith(u'http')):\\n uri = (u'http:\\/\\/' + uri)\\n if (headers is None):\\n headers = default_headers\\n else:\\n tmp = default_headers.copy()\\n headers = tmp.update(headers)\\n u = requests.get(uri, timeout=timeout, headers=headers, verify=verify_ssl)\\n info = u.headers\\n u.close()\\n return info\\n\\n\\nWhat's a good function header?\",\"targets\":\"@deprecated\\ndef head(uri, timeout=20, headers=None, verify_ssl=True):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n img = load_image(image_path)\\n img = pil_to_nparray(img)\\n try:\\n channel = img.shape[2]\\n except:\\n channel = 1\\n return channel\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_img_channel(image_path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def hypervolume(front, **kargs):\",\"targets\":\"\\\"\\\"\\\"Returns the index of the individual with the least the hypervolume\\n contribution. The provided *front* should be a set of non-dominated\\n individuals having each a :attr:`fitness` attribute.\\n \\\"\\\"\\\"\\n wobj = (numpy.array([ind.fitness.wvalues for ind in front]) * (-1))\\n ref = kargs.get('ref', None)\\n if (ref is None):\\n ref = (numpy.max(wobj, axis=0) + 1)\\n def contribution(i):\\n return hv.hypervolume(numpy.concatenate((wobj[:i], wobj[(i + 1):])), ref)\\n contrib_values = map(contribution, range(len(front)))\\n return numpy.argmax(contrib_values)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef create_cookie(name, value, **kwargs):\\n\\n ''''Make a cookie from underspecified parameters.\\n By default, the pair of `name` and `value` will be set for the domain \\\\'\\\\'\\n and sent on every request (this is sometimes called a \\\"supercookie\\\").'\\n '''\",\"targets\":\"result = dict(version=0, name=name, value=value, port=None, domain='', path='\\/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)\\n badargs = (set(kwargs) - set(result))\\n if badargs:\\n err = 'create_cookie() got unexpected keyword arguments: %s'\\n raise TypeError((err % list(badargs)))\\n result.update(kwargs)\\n result['port_specified'] = bool(result['port'])\\n result['domain_specified'] = bool(result['domain'])\\n result['domain_initial_dot'] = result['domain'].startswith('.')\\n result['path_specified'] = bool(result['path'])\\n return cookielib.Cookie(**result)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef call(conf, context, topic, msg, timeout, connection_pool):\\n\\n ''''Sends a message on a topic and wait for a response.'\\n '''\",\"targets\":\"rv = multicall(conf, context, topic, msg, timeout, connection_pool)\\n rv = list(rv)\\n if (not rv):\\n return\\n return rv[(-1)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n course_key = course.id\\n coupons = Coupon.objects.filter(course_id=course_key).order_by('-is_active')\\n course_price = paid_mode.min_price\\n total_amount = None\\n if access['finance_admin']:\\n single_purchase_total = PaidCourseRegistration.get_total_amount_of_purchased_item(course_key)\\n bulk_purchase_total = CourseRegCodeItem.get_total_amount_of_purchased_item(course_key)\\n total_amount = (single_purchase_total + bulk_purchase_total)\\n section_data = {'section_key': 'e-commerce', 'section_display_name': _('E-Commerce'), 'access': access, 'course_id': unicode(course_key), 'currency_symbol': settings.PAID_COURSE_REGISTRATION_CURRENCY[1], 'ajax_remove_coupon_url': reverse('remove_coupon', kwargs={'course_id': unicode(course_key)}), 'ajax_get_coupon_info': reverse('get_coupon_info', kwargs={'course_id': unicode(course_key)}), 'get_user_invoice_preference_url': reverse('get_user_invoice_preference', kwargs={'course_id': unicode(course_key)}), 'sale_validation_url': reverse('sale_validation', kwargs={'course_id': unicode(course_key)}), 'ajax_update_coupon': reverse('update_coupon', kwargs={'course_id': unicode(course_key)}), 'ajax_add_coupon': reverse('add_coupon', kwargs={'course_id': unicode(course_key)}), 'get_sale_records_url': reverse('get_sale_records', kwargs={'course_id': unicode(course_key)}), 'get_sale_order_records_url': reverse('get_sale_order_records', kwargs={'course_id': unicode(course_key)}), 'instructor_url': reverse('instructor_dashboard', kwargs={'course_id': unicode(course_key)}), 'get_registration_code_csv_url': reverse('get_registration_codes', kwargs={'course_id': unicode(course_key)}), 'generate_registration_code_csv_url': reverse('generate_registration_codes', kwargs={'course_id': unicode(course_key)}), 'active_registration_code_csv_url': reverse('active_registration_codes', kwargs={'course_id': unicode(course_key)}), 'spent_registration_code_csv_url': reverse('spent_registration_codes', kwargs={'course_id': unicode(course_key)}), 'set_course_mode_url':...\\n\\nWhat's a good function header?\",\"targets\":\"def _section_e_commerce(course, access, paid_mode, coupons_enabled, reports_enabled):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef foreign(expr):\\n\\n ''''Annotate a portion of a primaryjoin expression\\n with a \\\\'foreign\\\\' annotation.\\n See the section :ref:`relationship_custom_foreign` for a\\n description of use.\\n .. versionadded:: 0.8\\n .. seealso::\\n :ref:`relationship_custom_foreign`\\n :func:`.remote`'\\n '''\",\"targets\":\"return _annotate_columns(expression._clause_element_as_expr(expr), {'foreign': True})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@with_open_mode('rb')\\n@with_sizes('medium')\\ndef read_seek_bytewise(f):\\n\\n ''''alternate read & seek one unit'\\n '''\",\"targets\":\"f.seek(0)\\n while f.read(1):\\n f.seek(1, 1)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_preprocessing(name, is_training=False):\\n\\n ''''Returns preprocessing_fn(image, height, width, **kwargs).\\n Args:\\n name: The name of the preprocessing function.\\n is_training: `True` if the model is being used for training and `False`\\n otherwise.\\n Returns:\\n preprocessing_fn: A function that preprocessing a single image (pre-batch).\\n It has the following signature:\\n image = preprocessing_fn(image, output_height, output_width, ...).\\n Raises:\\n ValueError: If Preprocessing `name` is not recognized.'\\n '''\",\"targets\":\"preprocessing_fn_map = {'inception': inception_preprocessing, 'inception_v1': inception_preprocessing, 'inception_v2': inception_preprocessing, 'inception_v3': inception_preprocessing, 'inception_v4': inception_preprocessing, 'inception_resnet_v2': inception_preprocessing}\\n if (name not in preprocessing_fn_map):\\n raise ValueError(('Preprocessing name [%s] was not recognized' % name))\\n def preprocessing_fn(image, output_height, output_width, **kwargs):\\n return preprocessing_fn_map[name].preprocess_image(image, output_height, output_width, is_training=is_training, **kwargs)\\n return preprocessing_fn\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef diagonal(a, offset=0, axis1=0, axis2=1):\\n\\n ''''A helper function for `theano.tensor.ExtractDiag`. It accepts tensor with\\n `ndim >= 2` as input. The name `diagonal` is just meant to keep it\\n consistent with numpy.\\n Parameters\\n a : symbolic tensor\\n offset : int\\n offset\\n axis1 : int\\n axis2 : int\\n Returns\\n tensor : symbolic tensor'\\n '''\",\"targets\":\"return ExtractDiag(offset, axis1, axis2)(a)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef directional_variance_i(x_i, w):\\n\\n ''''the variance of the row x_i in the direction w'\\n '''\",\"targets\":\"return (dot(x_i, direction(w)) ** 2)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n dirs = path.parts\\n return dirs[(dirs.index('build') + 1)]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_play_name(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_lcm_config():\",\"targets\":\"\\\"\\\"\\\"Get the current Local Configuration Manager settings\\n Returns:\\n dict: A dictionary representing the Local Configuration Manager settings\\n on the machine\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ dsc.get_lcm_config\\n \\\"\\\"\\\"\\n cmd = 'Get-DscLocalConfigurationManager | Select-Object -Property ConfigurationModeFrequencyMins, LCMState, RebootNodeIfNeeded, ConfigurationMode, ActionAfterReboot, RefreshMode, CertificateID, ConfigurationID, RefreshFrequencyMins, AllowModuleOverwrite, DebugMode, StatusRetentionTimeInDays '\\n return _pshell(cmd)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def choose_names(installer):\",\"targets\":\"\\\"\\\"\\\"Display screen to select domains to validate.\\n :param installer: An installer object\\n :type installer: :class:`certbot.interfaces.IInstaller`\\n :returns: List of selected names\\n :rtype: `list` of `str`\\n \\\"\\\"\\\"\\n if (installer is None):\\n logger.debug('No installer, picking names manually')\\n return _choose_names_manually()\\n domains = list(installer.get_all_names())\\n names = get_valid_domains(domains)\\n if (not names):\\n return _choose_names_manually('No names were found in your configuration files. ')\\n (code, names) = _filter_names(names)\\n if ((code == display_util.OK) and names):\\n return names\\n else:\\n return []\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_collection_ids_matching_query(query_string, cursor=None):\",\"targets\":\"\\\"\\\"\\\"Returns a list with all collection ids matching the given search query\\n string, as well as a search cursor for future fetches.\\n Args:\\n query_string: str. The search query string.\\n cursor: str or None. Cursor indicating where, in the list of\\n collections, to start the search from.\\n Returns:\\n 2-tuple of (returned_collection_ids, search_cursor), where:\\n returned_collection_ids : list(str). A list with all collection ids\\n matching the given search query string, as well as a search\\n cursor for future fetches. The list contains exactly\\n feconf.SEARCH_RESULTS_PAGE_SIZE results if there are at least\\n that many, otherwise it contains all remaining results. (If this\\n behaviour does not occur, an error will be logged.)\\n search_cursor: str. Search cursor for future fetches.\\n \\\"\\\"\\\"\\n returned_collection_ids = []\\n search_cursor = cursor\\n for _ in range(MAX_ITERATIONS):\\n remaining_to_fetch = (feconf.SEARCH_RESULTS_PAGE_SIZE - len(returned_collection_ids))\\n (collection_ids, search_cursor) = search_collections(query_string, remaining_to_fetch, cursor=search_cursor)\\n invalid_collection_ids = []\\n for (ind, model) in enumerate(collection_models.CollectionSummaryModel.get_multi(collection_ids)):\\n if (model is not None):\\n returned_collection_ids.append(collection_ids[ind])\\n else:\\n invalid_collection_ids.append(collection_ids[ind])\\n if ((len(returned_collection_ids) == feconf.SEARCH_RESULTS_PAGE_SIZE) or (search_cursor is None)):\\n break\\n else:\\n logging.error(('Search index contains stale collection ids: %s' % ', '.join(invalid_collection_ids)))\\n if ((len(returned_collection_ids) < feconf.SEARCH_RESULTS_PAGE_SIZE) and (search_cursor is not None)):\\n logging.error(('Could not fulfill search request for query string %s; at least %s retries were needed.' % (query_string, MAX_ITERATIONS)))\\n return (returned_collection_ids, search_cursor)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@library.global_function\\ndef url(viewname, *args, **kwargs):\\n\\n ''''Helper for Django\\\\'s ``reverse`` in templates.\\n Uses sumo\\\\'s locale-aware reverse.'\\n '''\",\"targets\":\"locale = kwargs.pop('locale', None)\\n return reverse(viewname, locale=locale, args=args, kwargs=kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef libvlc_media_discoverer_is_running(p_mdis):\\n\\n ''''Query if media service discover object is running.\\n @param p_mdis: media service discover object.\\n @return: true if running, false if not \\\\libvlc_return_bool.'\\n '''\",\"targets\":\"f = (_Cfunctions.get('libvlc_media_discoverer_is_running', None) or _Cfunction('libvlc_media_discoverer_is_running', ((1,),), None, ctypes.c_int, MediaDiscoverer))\\n return f(p_mdis)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef check_symmetric(array, tol=1e-10, raise_warning=True, raise_exception=False):\\n\\n ''''Make sure that array is 2D, square and symmetric.\\n If the array is not symmetric, then a symmetrized version is returned.\\n Optionally, a warning or exception is raised if the matrix is not\\n symmetric.\\n Parameters\\n array : nd-array or sparse matrix\\n Input object to check \\/ convert. Must be two-dimensional and square,\\n otherwise a ValueError will be raised.\\n tol : float\\n Absolute tolerance for equivalence of arrays. Default = 1E-10.\\n raise_warning : boolean (default=True)\\n If True then raise a warning if conversion is required.\\n raise_exception : boolean (default=False)\\n If True then raise an exception if array is not symmetric.\\n Returns\\n array_sym : ndarray or sparse matrix\\n Symmetrized version of the input array, i.e. the average of array\\n and array.transpose(). If sparse, then duplicate entries are first\\n summed and zeros are eliminated.'\\n '''\",\"targets\":\"if ((array.ndim != 2) or (array.shape[0] != array.shape[1])):\\n raise ValueError('array must be 2-dimensional and square. shape = {0}'.format(array.shape))\\n if sp.issparse(array):\\n diff = (array - array.T)\\n if (diff.format not in ['csr', 'csc', 'coo']):\\n diff = diff.tocsr()\\n symmetric = np.all((abs(diff.data) < tol))\\n else:\\n symmetric = np.allclose(array, array.T, atol=tol)\\n if (not symmetric):\\n if raise_exception:\\n raise ValueError('Array must be symmetric')\\n if raise_warning:\\n warnings.warn('Array is not symmetric, and will be converted to symmetric by average with its transpose.')\\n if sp.issparse(array):\\n conversion = ('to' + array.format)\\n array = getattr((0.5 * (array + array.T)), conversion)()\\n else:\\n array = (0.5 * (array + array.T))\\n return array\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n mc_vars = mailchimp.listMergeVars(id=list_id)\\n mc_names = set((v['name'] for v in mc_vars))\\n mc_merge = mailchimp.listMergeVarAdd\\n tags = [v['tag'] for v in mc_vars]\\n for name in tag_names:\\n tag = name_to_tag(name)\\n if ('FULLNAME' not in tags):\\n result = mc_merge(id=list_id, tag='FULLNAME', name='Full Name', options={'field_type': 'text', 'public': False})\\n tags.append('FULLNAME')\\n log.debug(result)\\n if ((name not in mc_names) and (tag not in ['EMAIL', 'FULLNAME'])):\\n ftype = FIELD_TYPES.get(name, 'number')\\n result = mc_merge(id=list_id, tag=tag, name=name, options={'field_type': ftype, 'public': False})\\n tags.append(tag)\\n log.debug(result)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def update_merge_tags(mailchimp, list_id, tag_names):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def load_regions():\",\"targets\":\"\\\"\\\"\\\"Actually load the region\\/endpoint information from the JSON files.\\n By default, this loads from the default included ``boto\\/endpoints.json``\\n file.\\n Users can override\\/extend this by supplying either a ``BOTO_ENDPOINTS``\\n environment variable or a ``endpoints_path`` config variable, either of\\n which should be an absolute path to the user\\\\s JSON file.\\n :returns: The endpoints data\\n :rtype: dict\\n \\\"\\\"\\\"\\n endpoints = _load_builtin_endpoints()\\n additional_path = None\\n if os.environ.get('BOTO_ENDPOINTS'):\\n additional_path = os.environ['BOTO_ENDPOINTS']\\n elif boto.config.get('Boto', 'endpoints_path'):\\n additional_path = boto.config.get('Boto', 'endpoints_path')\\n if additional_path:\\n additional = load_endpoint_json(additional_path)\\n endpoints = merge_endpoints(endpoints, additional)\\n return endpoints\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@core_helper\\ndef url_for_static(*args, **kw):\",\"targets\":\"\\\"\\\"\\\"Returns the URL for static content that doesn\\\\t get translated (eg CSS)\\n It\\\\ll raise CkanUrlException if called with an external URL\\n This is a wrapper for :py:func:`routes.url_for`\\n \\\"\\\"\\\"\\n if args:\\n url = urlparse.urlparse(args[0])\\n url_is_external = ((url.scheme != '') or (url.netloc != ''))\\n if url_is_external:\\n CkanUrlException = ckan.exceptions.CkanUrlException\\n raise CkanUrlException('External URL passed to url_for_static()')\\n return url_for_static_or_external(*args, **kw)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def libvlc_media_get_type(p_md):\",\"targets\":\"\\\"\\\"\\\"Get the media type of the media descriptor object.\\n @param p_md: media descriptor object.\\n @return: media type.\\n @version: LibVLC 3.0.0 and later. See libvlc_media_type_t.\\n \\\"\\\"\\\"\\n f = (_Cfunctions.get('libvlc_media_get_type', None) or _Cfunction('libvlc_media_get_type', ((1,),), None, MediaType, Media))\\n return f(p_md)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def __virtual__():\",\"targets\":\"\\\"\\\"\\\"Load only on Windows\\n \\\"\\\"\\\"\\n if (salt.utils.platform.is_windows() and HAS_WIN32):\\n return 'win_path'\\n return (False, 'Module win_path: module only works on Windows systems')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if gcodec.isProcedureDoneOrFileIsEmpty(gcodeText, 'multiply'):\\n return gcodeText\\n if (repository == None):\\n repository = settings.getReadRepository(MultiplyRepository())\\n if (not repository.activateMultiply.value):\\n return gcodeText\\n return MultiplySkein().getCraftedGcode(gcodeText, repository)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def getCraftedTextFromText(gcodeText, repository=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def commit_on_success(using=None):\",\"targets\":\"\\\"\\\"\\\"This decorator activates commit on response. This way, if the view function\\n runs successfully, a commit is made; if the viewfunc produces an exception,\\n a rollback is made. This is one of the most common ways to do transaction\\n control in Web apps.\\n \\\"\\\"\\\"\\n warnings.warn('commit_on_success is deprecated in favor of atomic.', PendingDeprecationWarning, stacklevel=2)\\n def entering(using):\\n enter_transaction_management(using=using)\\n def exiting(exc_type, using):\\n try:\\n if (exc_type is not None):\\n if is_dirty(using=using):\\n rollback(using=using)\\n elif is_dirty(using=using):\\n try:\\n commit(using=using)\\n except:\\n rollback(using=using)\\n raise\\n finally:\\n leave_transaction_management(using=using)\\n return _transaction_func(entering, exiting, using)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def command_copytree(args):\",\"targets\":\"\\\"\\\"\\\"Copy one or more source directory(s) below a destination directory.\\n Parts of the destination directory path are created if needed.\\n Similar to the UNIX command: \\\\cp -R srcdir destdir\\\\\\n \\\"\\\"\\\"\\n for srcdir in args.srcdirs:\\n basename = os.path.basename(srcdir)\\n destdir2 = os.path.normpath(os.path.join(args.destdir, basename))\\n if os.path.exists(destdir2):\\n shutil.rmtree(destdir2)\\n sys.stdout.write(('copytree: %s => %s\\\\n' % (srcdir, destdir2)))\\n shutil.copytree(srcdir, destdir2)\\n return 0\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def CDLENGULFING(barDs, count):\",\"targets\":\"\\\"\\\"\\\"Engulfing Pattern\\n \\\"\\\"\\\"\\n return call_talib_with_ohlc(barDs, count, talib.CDLENGULFING)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef false(*args, **kwargs):\\n\\n ''''Always returns False'\\n '''\",\"targets\":\"return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _symlink(src, dest):\",\"targets\":\"\\\"\\\"\\\"Create a symlink.\\n \\\"\\\"\\\"\\n try:\\n os.symlink(src, dest)\\n except OSError:\\n warn(('Could not create symbolic link %s. Check that your partition handles symbolic links. The file will be copied instead.' % dest))\\n shutil.copy(src, dest)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (argv is None):\\n argv = sys.argv\\n print(u'Fetching samples from:')\\n for s in (test_lyrics.GOOGLE_SOURCES + test_lyrics.DEFAULT_SOURCES):\\n print(s['url'])\\n url = (s['url'] + s['path'])\\n fn = test_lyrics.url_to_filename(url)\\n if (not os.path.isfile(fn)):\\n html = requests.get(url, verify=False).text\\n with safe_open_w(fn) as f:\\n f.write(html.encode('utf-8'))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def main(argv=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from tornado.ioloop import IOLoop\\n @functools.wraps(method)\\n def wrapper(self, *args, **kwargs):\\n self._auto_finish = False\\n with stack_context.ExceptionStackContext(self._stack_context_handle_exception):\\n result = method(self, *args, **kwargs)\\n if (result is not None):\\n result = gen.convert_yielded(result)\\n def future_complete(f):\\n f.result()\\n if (not self._finished):\\n self.finish()\\n IOLoop.current().add_future(result, future_complete)\\n return None\\n return result\\n return wrapper\\n\\n\\nWhat's a good function header?\",\"targets\":\"def asynchronous(method):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef demo():\\n\\n ''''A simple demonstration showing how to use canvas widgets.'\\n '''\",\"targets\":\"def fill(cw):\\n from random import randint\\n cw['fill'] = ('#00%04d' % randint(0, 9999))\\n def color(cw):\\n from random import randint\\n cw['color'] = ('#ff%04d' % randint(0, 9999))\\n cf = CanvasFrame(closeenough=10, width=300, height=300)\\n c = cf.canvas()\\n ct3 = TextWidget(c, 'hiya there', draggable=1)\\n ct2 = TextWidget(c, 'o o\\\\n||\\\\n___\\\\n U', draggable=1, justify='center')\\n co = OvalWidget(c, ct2, outline='red')\\n ct = TextWidget(c, 'o o\\\\n||\\\\n\\\\\\\\___\\/', draggable=1, justify='center')\\n cp = ParenWidget(c, ct, color='red')\\n cb = BoxWidget(c, cp, fill='cyan', draggable=1, width=3, margin=10)\\n equation = SequenceWidget(c, SymbolWidget(c, 'forall'), TextWidget(c, 'x'), SymbolWidget(c, 'exists'), TextWidget(c, 'y: '), TextWidget(c, 'x'), SymbolWidget(c, 'notequal'), TextWidget(c, 'y'))\\n space = SpaceWidget(c, 0, 30)\\n cstack = StackWidget(c, cb, ct3, space, co, equation, align='center')\\n foo = TextWidget(c, 'try clicking\\\\nand dragging', draggable=1, justify='center')\\n cs = SequenceWidget(c, cstack, foo)\\n zz = BracketWidget(c, cs, color='green4', width=3)\\n cf.add_widget(zz, 60, 30)\\n cb.bind_click(fill)\\n ct.bind_click(color)\\n co.bind_click(fill)\\n ct2.bind_click(color)\\n ct3.bind_click(color)\\n cf.mainloop()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if ((len(args) == 1) and (args[0].type in (u'NUMBER', u'INTEGER'))):\\n return min(1, max(0, args[0].value))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_alpha(args):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _format_range_unified(start, stop):\\n\\n ''''Convert range to the \\\"ed\\\" format'\\n '''\",\"targets\":\"beginning = (start + 1)\\n length = (stop - start)\\n if (length == 1):\\n return '{}'.format(beginning)\\n if (not length):\\n beginning -= 1\\n return '{},{}'.format(beginning, length)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n indent = None\\n separators = (',', ':')\\n if (current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug):\\n indent = 2\\n separators = (', ', ': ')\\n if (args and kwargs):\\n raise TypeError('jsonify() behavior undefined when passed both args and kwargs')\\n elif (len(args) == 1):\\n data = args[0]\\n else:\\n data = (args or kwargs)\\n return current_app.response_class((dumps(data, indent=indent, separators=separators), '\\\\n'), mimetype=current_app.config['JSONIFY_MIMETYPE'])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def jsonify(*args, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (a % b):\\n return ((a \\/\\/ b) + 1)\\n return (a \\/\\/ b)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _divide_with_ceil(a, b):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def make_pretty_name(method):\",\"targets\":\"\\\"\\\"\\\"Makes a pretty name for a function\\/method.\\n \\\"\\\"\\\"\\n meth_pieces = [method.__name__]\\n if (hasattr(method, '__self__') and (method.__self__ is not None)):\\n try:\\n meth_pieces.insert(0, method.__self__.__class__.__name__)\\n except AttributeError:\\n pass\\n return '.'.join(meth_pieces)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n means_men = (20, 35, 30, 35, 27)\\n means_women = (25, 32, 34, 20, 25)\\n plt.title('\\\\xe5\\\\x8f\\\\xaf\\\\xe8\\\\xa7\\\\x86\\\\xe5\\\\x8c\\\\x96\\\\xe6\\\\xa0\\\\x87\\\\xe9\\\\xa2\\\\x98', fontproperties=myfont)\\n index = np.arange(len(means_men))\\n bar_width = 0.35\\n plt.bar(index, means_men, width=bar_width, alpha=0.2, color='b', label='\\\\xe7\\\\x94\\\\xb7\\\\xe7\\\\x94\\\\x9f')\\n plt.bar((index + bar_width), means_women, width=bar_width, alpha=0.8, color='r', label='\\\\xe5\\\\xa5\\\\xb3\\\\xe7\\\\x94\\\\x9f')\\n plt.legend(loc='upper right', prop=myfont, shadow=True)\\n for (x, y) in zip(index, means_men):\\n plt.text(x, (y + 0.3), y, ha='center', va='bottom')\\n for (x, y) in zip(index, means_women):\\n plt.text((x + bar_width), (y + 0.3), y, ha='center', va='bottom')\\n plt.ylim(0, 45)\\n plt.xlabel('\\\\xe5\\\\x88\\\\x86\\\\xe7\\\\xbb\\\\x84Group', fontproperties=myfont)\\n plt.ylabel('\\\\xe5\\\\xbe\\\\x97\\\\xe5\\\\x88\\\\x86Scores', fontproperties=myfont)\\n plt.xticks((index + (bar_width \\/ 2)), ('A\\\\xe7\\\\xbb\\\\x84', 'B\\\\xe7\\\\xbb\\\\x84', 'C\\\\xe7\\\\xbb\\\\x84', 'D\\\\xe7\\\\xbb\\\\x84', 'E\\\\xe7\\\\xbb\\\\x84'), fontproperties=myfont)\\n plt.show()\\n return\\n\\n\\nWhat's a good function header?\",\"targets\":\"def bar_plot():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (y_min, x_min, y_max, x_max) = boxlist.get_coordinates()\\n return ((y_max - y_min) * (x_max - x_min))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def area(boxlist):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (version is None):\\n from django import VERSION as version\\n else:\\n assert (len(version) == 5)\\n assert (version[3] in (u'alpha', u'beta', u'rc', u'final'))\\n parts = (2 if (version[2] == 0) else 3)\\n main = u'.'.join((str(x) for x in version[:parts]))\\n sub = u''\\n if ((version[3] == u'alpha') and (version[4] == 0)):\\n git_changeset = get_git_changeset()\\n if git_changeset:\\n sub = (u'.dev%s' % git_changeset)\\n elif (version[3] != u'final'):\\n mapping = {u'alpha': u'a', u'beta': u'b', u'rc': u'c'}\\n sub = (mapping[version[3]] + str(version[4]))\\n return str((main + sub))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_version(version=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n print 'Start testing the network ...'\\n if (batch_size is None):\\n dp_dict = dict_to_one(network.all_drop)\\n feed_dict = {x: X_test, y_: y_test}\\n feed_dict.update(dp_dict)\\n if (cost is not None):\\n print (' test loss: %f' % sess.run(cost, feed_dict=feed_dict))\\n print (' test acc: %f' % sess.run(acc, feed_dict=feed_dict))\\n else:\\n (test_loss, test_acc, n_batch) = (0, 0, 0)\\n for (X_test_a, y_test_a) in iterate.minibatches(X_test, y_test, batch_size, shuffle=True):\\n dp_dict = dict_to_one(network.all_drop)\\n feed_dict = {x: X_test_a, y_: y_test_a}\\n feed_dict.update(dp_dict)\\n if (cost is not None):\\n (err, ac) = sess.run([cost, acc], feed_dict=feed_dict)\\n test_loss += err\\n else:\\n ac = sess.run(acc, feed_dict=feed_dict)\\n test_acc += ac\\n n_batch += 1\\n if (cost is not None):\\n print (' test loss: %f' % (test_loss \\/ n_batch))\\n print (' test acc: %f' % (test_acc \\/ n_batch))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test(sess, network, acc, X_test, y_test, x, y_, batch_size, cost=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if pieces['closest-tag']:\\n rendered = pieces['closest-tag']\\n if (pieces['distance'] or pieces['dirty']):\\n rendered += ('.post%d' % pieces['distance'])\\n if pieces['dirty']:\\n rendered += '.dev0'\\n rendered += plus_or_dot(pieces)\\n rendered += ('g%s' % pieces['short'])\\n else:\\n rendered = ('0.post%d' % pieces['distance'])\\n if pieces['dirty']:\\n rendered += '.dev0'\\n rendered += ('+g%s' % pieces['short'])\\n return rendered\\n\\n\\nWhat's a good function header?\",\"targets\":\"def render_pep440_post(pieces):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef H(s):\\n\\n ''''The hash function H'\\n '''\",\"targets\":\"return md5_hex(s)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef create_api_key(name, description, enabled=True, stageKeys=None, region=None, key=None, keyid=None, profile=None):\\n\\n ''''Create an API key given name and description.\\n An optional enabled argument can be provided. If provided, the\\n valid values are True|False. This argument defaults to True.\\n An optional stageKeys argument can be provided in the form of\\n list of dictionary with \\\\'restApiId\\\\' and \\\\'stageName\\\\' as keys.\\n CLI Example:\\n .. code-block:: bash\\n salt myminion boto_apigateway.create_api_key name description\\n salt myminion boto_apigateway.create_api_key name description enabled=False\\n salt myminion boto_apigateway.create_api_key name description \\\\\\n stageKeys=\\\\'[{\\\"restApiId\\\": \\\"id\\\", \\\"stageName\\\": \\\"stagename\\\"}]\\\\''\\n '''\",\"targets\":\"try:\\n stageKeys = (list() if (stageKeys is None) else stageKeys)\\n conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n response = conn.create_api_key(name=name, description=description, enabled=enabled, stageKeys=stageKeys)\\n if (not response):\\n return {'created': False}\\n return {'created': True, 'apiKey': _convert_datetime_str(response)}\\n except ClientError as e:\\n return {'created': False, 'error': salt.utils.boto3.get_error(e)}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n mobsf_subdir_tools = CONFIG['MobSF']['tools']\\n binscope_path = (mobsf_subdir_tools + 'BinScope')\\n if platform.machine().endswith('64'):\\n binscope_url = CONFIG['binscope']['url_x64']\\n binscope_installer_path = (binscope_path + '\\\\\\\\BinScope_x64.msi')\\n else:\\n binscope_url = CONFIG['binscope']['url_x86']\\n binscope_installer_path = (binscope_path + '\\\\\\\\BinScope_x86.msi')\\n if (not os.path.exists(binscope_path)):\\n os.makedirs(binscope_path)\\n binscope_installer_file = open(binscope_installer_path, 'wb')\\n print '[*] Downloading BinScope..'\\n binscope_installer = urlrequest.urlopen(binscope_url)\\n print '[*] Saving to File {}'.format(binscope_installer_path)\\n binscope_installer_file.write(bytes(binscope_installer.read()))\\n binscope_installer_file.close()\\n print '[*] Installing BinScope to {}'.format(binscope_path)\\n os.system(((((((('msiexec' + ' INSTALLLOCATION=\\\"') + binscope_path) + '\\\" ') + '\\/i \\\"') + binscope_installer_path) + '\\\" ') + '\\/passive'))\\n CONFIG['binscope']['file'] = (binscope_path + '\\\\\\\\Binscope.exe')\\n with open(os.path.join(CONFIG_PATH, CONFIG_FILE), 'w') as configfile:\\n CONFIG.write(configfile)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def tools_binscope():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', app_identity_stub.AppIdentityServiceStub())\\n blob_storage = datastore_blob_storage.DatastoreBlobStorage(app_id)\\n apiproxy_stub_map.apiproxy.RegisterStub('blobstore', blobstore_stub.BlobstoreServiceStub(blob_storage, request_data=request_data))\\n apiproxy_stub_map.apiproxy.RegisterStub('capability_service', capability_stub.CapabilityServiceStub())\\n apiproxy_stub_map.apiproxy.RegisterStub('channel', channel_service_stub.ChannelServiceStub(request_data=request_data))\\n datastore = datastore_distributed.DatastoreDistributed(app_id, datastore_path, require_indexes=datastore_require_indexes, trusted=trusted)\\n apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3', datastore)\\n apiproxy_stub_map.apiproxy.RegisterStub('file', file_service_stub.FileServiceStub(blob_storage))\\n serve_address = os.environ['NGINX_HOST']\\n try:\\n from google.appengine.api.images import images_stub\\n except ImportError:\\n logging.warning('Could not initialize images API; you are likely missing the Python \\\"PIL\\\" module.')\\n from google.appengine.api.images import images_not_implemented_stub\\n apiproxy_stub_map.apiproxy.RegisterStub('images', images_not_implemented_stub.ImagesNotImplementedServiceStub(host_prefix=images_host_prefix))\\n else:\\n host_prefix = 'http:\\/\\/{}'.format(serve_address)\\n apiproxy_stub_map.apiproxy.RegisterStub('images', images_stub.ImagesServiceStub(host_prefix=host_prefix))\\n apiproxy_stub_map.apiproxy.RegisterStub('logservice', logservice_stub.LogServiceStub(persist=True))\\n apiproxy_stub_map.apiproxy.RegisterStub('mail', mail_stub.MailServiceStub(mail_smtp_host, mail_smtp_port, mail_smtp_user, mail_smtp_password, enable_sendmail=mail_enable_sendmail, show_mail_body=mail_show_mail_body))\\n apiproxy_stub_map.apiproxy.RegisterStub('memcache', memcache_distributed.MemcacheService())\\n apiproxy_stub_map.apiproxy.RegisterStub('search',...\\n\\nWhat's a good function header?\",\"targets\":\"def setup_stubs(request_data, app_id, application_root, trusted, blobstore_path, datastore_consistency, datastore_path, datastore_require_indexes, datastore_auto_id_policy, images_host_prefix, logs_path, mail_smtp_host, mail_smtp_port, mail_smtp_user, mail_smtp_password, mail_enable_sendmail, mail_show_mail_body, matcher_prospective_search_path, search_index_path, taskqueue_auto_run_tasks, taskqueue_default_http_server, uaserver_path, user_login_url, user_logout_url, xmpp_path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n module = AnsibleModule(argument_spec=dict(kubeconfig=dict(default='\\/etc\\/origin\\/master\\/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'list']), debug=dict(default=False, type='bool'), kind=dict(default='dc', choices=['dc', 'rc'], type='str'), namespace=dict(default='default', type='str'), replicas=dict(default=None, type='int'), name=dict(default=None, type='str')), supports_check_mode=True)\\n rval = OCScale.run_ansible(module.params, module.check_mode)\\n if ('failed' in rval):\\n module.fail_json(**rval)\\n module.exit_json(**rval)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def main():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n data = show_ver()\\n info = {'software': _parse_software(data), 'hardware': _parse_hardware(data), 'plugins': _parse_plugins(data)}\\n return info\\n\\n\\nWhat's a good function header?\",\"targets\":\"def system_info():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef IsBlockInNameSpace(nesting_state, is_forward_declaration):\\n\\n ''''Checks that the new block is directly in a namespace.\\n Args:\\n nesting_state: The _NestingState object that contains info about our state.\\n is_forward_declaration: If the class is a forward declared class.\\n Returns:\\n Whether or not the new block is directly in a namespace.'\\n '''\",\"targets\":\"if is_forward_declaration:\\n return ((len(nesting_state.stack) >= 1) and isinstance(nesting_state.stack[(-1)], _NamespaceInfo))\\n return ((len(nesting_state.stack) > 1) and nesting_state.stack[(-1)].check_namespace_indentation and isinstance(nesting_state.stack[(-2)], _NamespaceInfo))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def findall(pattern, string, flags=0):\",\"targets\":\"\\\"\\\"\\\"Return a list of all non-overlapping matches in the string.\\n If one or more capturing groups are present in the pattern, return\\n a list of groups; this will be a list of tuples if the pattern\\n has more than one group.\\n Empty matches are included in the result.\\n \\\"\\\"\\\"\\n return _compile(pattern, flags).findall(string)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _ellipsis_match(want, got):\",\"targets\":\"\\\"\\\"\\\"Essentially the only subtle case:\\n >>> _ellipsis_match(\\\\aa...aa\\\\, \\\\aaa\\\\)\\n False\\n \\\"\\\"\\\"\\n if (ELLIPSIS_MARKER not in want):\\n return (want == got)\\n ws = want.split(ELLIPSIS_MARKER)\\n assert (len(ws) >= 2)\\n (startpos, endpos) = (0, len(got))\\n w = ws[0]\\n if w:\\n if got.startswith(w):\\n startpos = len(w)\\n del ws[0]\\n else:\\n return False\\n w = ws[(-1)]\\n if w:\\n if got.endswith(w):\\n endpos -= len(w)\\n del ws[(-1)]\\n else:\\n return False\\n if (startpos > endpos):\\n return False\\n for w in ws:\\n startpos = got.find(w, startpos, endpos)\\n if (startpos < 0):\\n return False\\n startpos += len(w)\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@datastore_rpc._positional(0)\\ndef fetch(start_time=None, end_time=None, offset=None, minimum_log_level=None, include_incomplete=False, include_app_logs=False, module_versions=None, version_ids=None, request_ids=None, **kwargs):\\n\\n ''''Returns an iterator yielding an application\\\\'s request and application logs.\\n Logs will be returned by the iterator in reverse chronological order by\\n request end time, or by last flush time for requests still in progress (if\\n requested). The items yielded are RequestLog objects, the contents of which\\n are accessible via method calls.\\n All parameters are optional.\\n Args:\\n start_time: The earliest request completion or last-update time that\\n results should be fetched for, in seconds since the Unix epoch.\\n end_time: The latest request completion or last-update time that\\n results should be fetched for, in seconds since the Unix epoch.\\n offset: A byte string representing an offset into the log stream, extracted\\n from a previously emitted RequestLog. This iterator will begin\\n immediately after the record from which the offset came.\\n minimum_log_level: An application log level which serves as a filter on the\\n requests returned--requests with no application log at or above the\\n specified level will be omitted. Works even if include_app_logs is not\\n True. In ascending order, the available log levels are:\\n logservice.LOG_LEVEL_DEBUG, logservice.LOG_LEVEL_INFO,\\n logservice.LOG_LEVEL_WARNING, logservice.LOG_LEVEL_ERROR,\\n and logservice.LOG_LEVEL_CRITICAL.\\n include_incomplete: Whether or not to include requests that have started but\\n not yet finished, as a boolean. Defaults to False.\\n include_app_logs: Whether or not to include application level logs in the\\n results, as a boolean. Defaults to False.\\n module_versions: A list of tuples of the form (module, version), that\\n indicate that the logs for the given module\\/version combination should be\\n fetched. Duplicate tuples will be ignored. This kwarg may not be used\\n in conjunction with the \\\\'version_ids\\\\' kwarg.\\n version_ids: A list of version ids whose logs should be queried against.\\n Defaults to the application\\\\'s current version id only. This kwarg may not\\n be used in...'''\",\"targets\":\"args_diff = (set(kwargs) - _FETCH_KWARGS)\\n if args_diff:\\n raise InvalidArgumentError(('Invalid arguments: %s' % ', '.join(args_diff)))\\n request = log_service_pb.LogReadRequest()\\n request.set_app_id(os.environ['APPLICATION_ID'])\\n if (start_time is not None):\\n if (not isinstance(start_time, (float, int, long))):\\n raise InvalidArgumentError('start_time must be a float or integer')\\n request.set_start_time(long((start_time * 1000000)))\\n if (end_time is not None):\\n if (not isinstance(end_time, (float, int, long))):\\n raise InvalidArgumentError('end_time must be a float or integer')\\n request.set_end_time(long((end_time * 1000000)))\\n if (offset is not None):\\n try:\\n request.mutable_offset().ParseFromString(offset)\\n except (TypeError, ProtocolBuffer.ProtocolBufferDecodeError):\\n raise InvalidArgumentError('offset must be a string or read-only buffer')\\n if (minimum_log_level is not None):\\n if (not isinstance(minimum_log_level, int)):\\n raise InvalidArgumentError('minimum_log_level must be an int')\\n if (not (minimum_log_level in range((LOG_LEVEL_CRITICAL + 1)))):\\n raise InvalidArgumentError('minimum_log_level must be between 0 and 4\\\\n inclusive')\\n request.set_minimum_log_level(minimum_log_level)\\n if (not isinstance(include_incomplete, bool)):\\n raise InvalidArgumentError('include_incomplete must be a boolean')\\n request.set_include_incomplete(include_incomplete)\\n if (not isinstance(include_app_logs, bool)):\\n raise InvalidArgumentError('include_app_logs must be a boolean')\\n request.set_include_app_logs(include_app_logs)\\n if ('server_versions' in kwargs):\\n logging.warning('The ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_entry_map(dist, group=None):\\n\\n ''''Return the entry point map for `group`, or the full entry map'\\n '''\",\"targets\":\"return get_distribution(dist).get_entry_map(group)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_file_contents(*args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Retrieves the contents of a filename or file-like object.\\n See the `get_readable_fileobj` docstring for details on parameters.\\n Returns\\n content\\n The content of the file (as requested by ``encoding``).\\n \\\"\\\"\\\"\\n with get_readable_fileobj(*args, **kwargs) as f:\\n return f.read()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def analytics_upageviews(revision_ids, start_date, end_date=None):\",\"targets\":\"\\\"\\\"\\\"Given a sequence of document revision IDs, returns a dict matching\\n those with the number of users Google Analytics thinks has visited\\n each revision since start_date.\\n \\\"\\\"\\\"\\n scopes = ['https:\\/\\/www.googleapis.com\\/auth\\/analytics.readonly']\\n try:\\n ga_cred_dict = json.loads(config.GOOGLE_ANALYTICS_CREDENTIALS)\\n except (ValueError, TypeError):\\n raise ImproperlyConfigured('GOOGLE_ANALYTICS_CREDENTIALS Constance setting is badly formed.')\\n if (not ga_cred_dict):\\n raise ImproperlyConfigured('An empty GOOGLE_ANALYTICS_CREDENTIALS Constance setting is not permitted.')\\n credentials = ServiceAccountCredentials.from_json_keyfile_dict(ga_cred_dict, scopes=scopes)\\n http_auth = credentials.authorize(Http())\\n service = build('analyticsreporting', 'v4', http=http_auth)\\n if (end_date is None):\\n end_date = datetime.date.today()\\n if hasattr(start_date, 'date'):\\n start_date = start_date.date()\\n if hasattr(end_date, 'date'):\\n end_date = end_date.date()\\n start_date = start_date.isoformat()\\n end_date = end_date.isoformat()\\n request = service.reports().batchGet(body={'reportRequests': [{'dimensions': [{'name': 'ga:dimension12'}], 'metrics': [{'expression': 'ga:uniquePageviews'}], 'dimensionFilterClauses': [{'filters': [{'dimensionName': 'ga:dimension12', 'operator': 'IN_LIST', 'expressions': map(str, revision_ids)}]}], 'dateRanges': [{'startDate': start_date, 'endDate': end_date}], 'viewId': '66726481'}]})\\n response = request.execute()\\n data = {int(r): 0 for r in revision_ids}\\n data.update({int(row['dimensions'][0]): int(row['metrics'][0]['values'][0]) for row in response['reports'][0]['data'].get('rows', ())})\\n return data\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def makeXMLTags(tagStr):\",\"targets\":\"\\\"\\\"\\\"Helper to construct opening and closing tag expressions for XML, given a tag name. Matches\\n tags only in the given upper\\/lower case.\\n Example: similar to L{makeHTMLTags}\\n \\\"\\\"\\\"\\n return _makeTags(tagStr, True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if kwargs.get('label', None):\\n bfield.label = kwargs['label']\\n bfield.field.widget.attrs.update(kwargs)\\n return bfield\\n\\n\\nWhat's a good function header?\",\"targets\":\"@library.global_function\\ndef field_with_attrs(bfield, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (':' not in s):\\n return ('', s)\\n colon = 0\\n for i in range(len(s)):\\n if (s[i] == ':'):\\n colon = (i + 1)\\n (path, file) = (s[:(colon - 1)], s[colon:])\\n if (path and (not (':' in path))):\\n path = (path + ':')\\n return (path, file)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def split(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef format_timezone(offset, unnecessary_negative_timezone=False):\\n\\n ''''Format a timezone for Git serialization.\\n :param offset: Timezone offset as seconds difference to UTC\\n :param unnecessary_negative_timezone: Whether to use a minus sign for\\n UTC or positive timezones (-0000 and --700 rather than +0000 \\/ +0700).'\\n '''\",\"targets\":\"if ((offset % 60) != 0):\\n raise ValueError('Unable to handle non-minute offset.')\\n if ((offset < 0) or unnecessary_negative_timezone):\\n sign = '-'\\n offset = (- offset)\\n else:\\n sign = '+'\\n return ('%c%02d%02d' % (sign, (offset \\/ 3600), ((offset \\/ 60) % 60))).encode('ascii')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef find_command(cmd, paths=None, pathext=None):\\n\\n ''''Searches the PATH for the given command and returns its path'\\n '''\",\"targets\":\"if (paths is None):\\n paths = os.environ.get('PATH', '').split(os.pathsep)\\n if isinstance(paths, string_types):\\n paths = [paths]\\n if (pathext is None):\\n pathext = get_pathext()\\n pathext = [ext for ext in pathext.lower().split(os.pathsep) if len(ext)]\\n if (os.path.splitext(cmd)[1].lower() in pathext):\\n pathext = ['']\\n for path in paths:\\n cmd_path = os.path.join(path, cmd)\\n for ext in pathext:\\n cmd_path_ext = (cmd_path + ext)\\n if os.path.isfile(cmd_path_ext):\\n return cmd_path_ext\\n if os.path.isfile(cmd_path):\\n return cmd_path\\n raise BadCommand(('Cannot find command %r' % cmd))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dmp_primitive(f, u, K):\",\"targets\":\"\\\"\\\"\\\"Returns multivariate content and a primitive polynomial.\\n Examples\\n >>> from sympy.polys import ring, ZZ\\n >>> R, x,y, = ring(\\\"x,y\\\", ZZ)\\n >>> R.dmp_primitive(2*x*y + 6*x + 4*y + 12)\\n (2*y + 6, x + 2)\\n \\\"\\\"\\\"\\n (cont, v) = (dmp_content(f, u, K), (u - 1))\\n if (dmp_zero_p(f, u) or dmp_one_p(cont, v, K)):\\n return (cont, f)\\n else:\\n return (cont, [dmp_quo(c, cont, v, K) for c in f])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ParseResponseEx(response, select_default=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, encoding=DEFAULT_ENCODING, _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse):\",\"targets\":\"\\\"\\\"\\\"Identical to ParseResponse, except that:\\n 1. The returned list contains an extra item. The first form in the list\\n contains all controls not contained in any FORM element.\\n 2. The arguments ignore_errors and backwards_compat have been removed.\\n 3. Backwards-compatibility mode (backwards_compat=True) is not available.\\n \\\"\\\"\\\"\\n return _ParseFileEx(response, response.geturl(), select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def decorate(function):\\n @wraps(function)\\n def inner(*args, **kwargs):\\n with WAFFLE_SWITCHES.override(switch, active=active):\\n function(*args, **kwargs)\\n return inner\\n return decorate\\n\\n\\nWhat's a good function header?\",\"targets\":\"def override_switch(switch, active):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n model = context['model']\\n session = model.Session\\n return session.execute(q)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _execute(q, table, context):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not code):\\n return (None, None)\\n if (not isinstance(code, basestring)):\\n raise ValueError(u'Invalid language code specified by parser')\\n code = re.split(u'[^a-z]', code.lower())[0][:3]\\n for spec in codes:\\n if (code in spec[:(-1)]):\\n return (code, spec[(-1)])\\n return (code, (u'Unknown (%r)' % code))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def resolve(code):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@transaction.atomic\\ndef mass_get_or_create(model_class, base_queryset, id_field, default_dict, global_defaults):\\n\\n ''''Updates the data by inserting all not found records\\n Doesnt delete records if not in the new data\\n example usage\\n >>> model_class = ListItem #the class for which you are doing the insert\\n >>> base_query_set = ListItem.objects.filter(user=request.user, list=1) #query for retrieving currently stored items\\n >>> id_field = \\\\'user_id\\\\' #the id field on which to check\\n >>> default_dict = {\\\\'12\\\\': dict(comment=\\\\'my_new_item\\\\'), \\\\'13\\\\': dict(comment=\\\\'super\\\\')} #list of default values for inserts\\n >>> global_defaults = dict(user=request.user, list_id=1) #global defaults'\\n '''\",\"targets\":\"current_instances = list(base_queryset)\\n current_ids = set([unicode(getattr(c, id_field)) for c in current_instances])\\n given_ids = map(unicode, default_dict.keys())\\n new_ids = [g for g in given_ids if (g not in current_ids)]\\n prepared_models = []\\n for new_id in new_ids:\\n defaults = default_dict[new_id]\\n defaults[id_field] = new_id\\n defaults.update(global_defaults)\\n model_instance = model_class(**defaults)\\n prepared_models.append(model_instance)\\n if hasattr(model_class.objects, 'bulk_create'):\\n model_class.objects.bulk_create(prepared_models)\\n else:\\n [m.save() for m in prepared_models]\\n inserted_model_instances = prepared_models\\n return (current_instances, inserted_model_instances)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ParsePropertyQuery(query, filters, orders):\",\"targets\":\"\\\"\\\"\\\"Parse __property__ queries.\\n Raises exceptions for illegal queries.\\n Args:\\n query: A Query PB.\\n filters: the normalized filters from query.\\n orders: the normalized orders from query.\\n Returns:\\n The kind range (a ValueRange over (kind, property) pairs) requested\\n in the query.\\n \\\"\\\"\\\"\\n Check((not query.has_transaction()), 'transactional queries on __property__ not allowed')\\n key_range = ParseKeyFilteredQuery(filters, orders)\\n key_range.Remap((lambda x: _PropertyKeyToString(x, '')))\\n if query.has_ancestor():\\n ancestor = datastore_types.Key._FromPb(query.ancestor())\\n (ancestor_kind, ancestor_property) = _PropertyKeyToString(ancestor, None)\\n if (ancestor_property is not None):\\n key_range.Update(datastore_pb.Query_Filter.EQUAL, (ancestor_kind, ancestor_property))\\n else:\\n key_range.Update(datastore_pb.Query_Filter.GREATER_THAN_OR_EQUAL, (ancestor_kind, ''))\\n key_range.Update(datastore_pb.Query_Filter.LESS_THAN_OR_EQUAL, ((ancestor_kind + '\\\\x00'), ''))\\n query.clear_ancestor()\\n return key_range\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n chips = []\\n for value in chops:\\n chips.append(int2str64(value))\\n encoded = ','.join(chips)\\n return encoded\\n\\n\\nWhat's a good function header?\",\"targets\":\"def encode64chops(chops):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef add_dict_to_cookiejar(cj, cookie_dict):\\n\\n ''''Returns a CookieJar from a key\\/value dictionary.\\n :param cj: CookieJar to insert cookies into.\\n :param cookie_dict: Dict of key\\/values to insert into CookieJar.'\\n '''\",\"targets\":\"cj2 = cookiejar_from_dict(cookie_dict)\\n cj.update(cj2)\\n return cj\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _nested_variable(init, name=None, trainable=False):\",\"targets\":\"\\\"\\\"\\\"Returns a nested collection of TensorFlow variables.\\n Args:\\n init: Nested collection of TensorFlow initializers.\\n name: Variable name.\\n trainable: Make variables trainable (`False` by default).\\n Returns:\\n Nested collection (same structure as `init`) of TensorFlow variables.\\n \\\"\\\"\\\"\\n if (isinstance(init, list) or isinstance(init, tuple)):\\n result = [_nested_variable(i, name, trainable) for i in init]\\n if isinstance(init, tuple):\\n return tuple(result)\\n return result\\n else:\\n return tf.Variable(init, name=name, trainable=trainable)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef delete(url, **kwargs):\\n\\n ''''Sends a DELETE request.\\n :param url: URL for the new :class:`Request` object.\\n :param \\\\*\\\\*kwargs: Optional arguments that ``request`` takes.\\n :return: :class:`Response ` object\\n :rtype: requests.Response'\\n '''\",\"targets\":\"return request('delete', url, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n adhoc_session = False\\n session = kwargs.pop('session', None)\\n if (session is None):\\n session = sessions.session()\\n adhoc_session = True\\n try:\\n return session.request(method=method, url=url, **kwargs)\\n finally:\\n if adhoc_session:\\n session.close()\\n\\n\\nWhat's a good function header?\",\"targets\":\"@catch_exceptions_if_in_safe_mode\\ndef request(method, url, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (call != 'function'):\\n raise SaltCloudSystemExit('The show_service function must be called with -f or --function.')\\n if (not conn):\\n conn = get_conn()\\n if (kwargs is None):\\n kwargs = {}\\n if ('name' not in kwargs):\\n raise SaltCloudSystemExit('A name must be specified as \\\"name\\\"')\\n data = conn.get_hosted_service_properties(kwargs['name'], kwargs.get('details', False))\\n ret = object_to_dict(data)\\n return ret\\n\\n\\nWhat's a good function header?\",\"targets\":\"def show_service(kwargs=None, conn=None, call=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n files = ['\\/etc\\/init\\/{0}.conf'.format(name), '\\/etc\\/init\\/{0}.override'.format(name)]\\n for file_name in itertools.ifilter(os.path.isfile, files):\\n with salt.utils.files.fopen(file_name) as fp_:\\n if re.search('^\\\\\\\\s*manual', fp_.read(), re.MULTILINE):\\n return True\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _upstart_is_disabled(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getLoopsIntersection(importRadius, loopLists):\\n\\n ''''Get intersection loops.'\\n '''\",\"targets\":\"intercircle.directLoopLists(True, loopLists)\\n if (len(loopLists) < 1):\\n return []\\n if (len(loopLists) < 2):\\n return loopLists[0]\\n intercircle.directLoopLists(True, loopLists)\\n loopsIntersection = loopLists[0]\\n for loopList in loopLists[1:]:\\n loopsIntersection = getLoopsIntersectionByPair(importRadius, loopsIntersection, loopList)\\n return loopsIntersection\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef libvlc_video_get_spu_delay(p_mi):\\n\\n ''''Get the current subtitle delay. Positive values means subtitles are being\\n displayed later, negative values earlier.\\n @param p_mi: media player.\\n @return: time (in microseconds) the display of subtitles is being delayed.\\n @version: LibVLC 2.0.0 or later.'\\n '''\",\"targets\":\"f = (_Cfunctions.get('libvlc_video_get_spu_delay', None) or _Cfunction('libvlc_video_get_spu_delay', ((1,),), None, ctypes.c_int64, MediaPlayer))\\n return f(p_mi)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@click.command('set-url-root')\\n@click.argument('site')\\n@click.argument('url-root')\\ndef set_url_root(site, url_root):\\n\\n ''''Set url root for site'\\n '''\",\"targets\":\"from bench.config.site_config import set_url_root\\n set_url_root(site, url_root)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _sanitize_tag(match):\",\"targets\":\"\\\"\\\"\\\"Return the tag if it is allowed or the empty string otherwise\\n \\\"\\\"\\\"\\n tag = match.group(0)\\n if (ALLOWED_BASIC_TAG_PATTERN.match(tag) or ALLOWED_A_PATTERN.match(tag) or ALLOWED_IMG_PATTERN.match(tag)):\\n return tag\\n else:\\n return ''\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n max_x = np.max(x)\\n return (max_x + np.log(np.sum(np.exp((x - max_x)))))\\n\\n\\nWhat's a good function header?\",\"targets\":\"@primitive\\ndef logsumexp(x):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n full_str = sep.join(items)\\n if (len(full_str) < max_chars):\\n return full_str\\n n_chars = 0\\n n_items = 0\\n for (j, item) in enumerate(items):\\n n_chars += (len(item) + len(sep))\\n if (n_chars < (max_chars - len(overflow_marker))):\\n n_items += 1\\n else:\\n break\\n return sep.join((list(items[:n_items]) + [overflow_marker]))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def limited_join(sep, items, max_chars=30, overflow_marker='...'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _search_dialog(parent):\\n\\n ''''Display search test box.'\\n '''\",\"targets\":\"from tkinter import Toplevel, Text\\n from tkinter.ttk import Button\\n box = Toplevel(parent)\\n box.title('Test SearchDialog')\\n (x, y) = map(int, parent.geometry().split('+')[1:])\\n box.geometry(('+%d+%d' % (x, (y + 175))))\\n text = Text(box, inactiveselectbackground='gray')\\n text.pack()\\n text.insert('insert', ('This is a sample string.\\\\n' * 5))\\n def show_find():\\n text.tag_add('sel', '1.0', 'end')\\n _setup(text).open(text)\\n text.tag_remove('sel', '1.0', 'end')\\n button = Button(box, text='Search (selection ignored)', command=show_find)\\n button.pack()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def hessian(fun, argnum=0):\",\"targets\":\"\\\"\\\"\\\"Returns a function that computes the exact Hessian.\\n \\\"\\\"\\\"\\n return jacobian(jacobian(fun, argnum), argnum)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef centroid(*args):\\n\\n ''''Find the centroid (center of mass) of the collection containing only Points,\\n Segments or Polygons. The centroid is the weighted average of the individual centroid\\n where the weights are the lengths (of segments) or areas (of polygons).\\n Overlapping regions will add to the weight of that region.\\n If there are no objects (or a mixture of objects) then None is returned.\\n See Also\\n sympy.geometry.point.Point, sympy.geometry.line.Segment,\\n sympy.geometry.polygon.Polygon\\n Examples\\n >>> from sympy import Point, Segment, Polygon\\n >>> from sympy.geometry.util import centroid\\n >>> p = Polygon((0, 0), (10, 0), (10, 10))\\n >>> q = p.translate(0, 20)\\n >>> p.centroid, q.centroid\\n (Point2D(20\\/3, 10\\/3), Point2D(20\\/3, 70\\/3))\\n >>> centroid(p, q)\\n Point2D(20\\/3, 40\\/3)\\n >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))\\n >>> centroid(p, q)\\n Point2D(1, -sqrt(2) + 2)\\n >>> centroid(Point(0, 0), Point(2, 0))\\n Point2D(1, 0)\\n Stacking 3 polygons on top of each other effectively triples the\\n weight of that polygon:\\n >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))\\n >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))\\n >>> centroid(p, q)\\n Point2D(3\\/2, 1\\/2)\\n >>> centroid(p, p, p, q) # centroid x-coord shifts left\\n Point2D(11\\/10, 1\\/2)\\n Stacking the squares vertically above and below p has the same\\n effect:\\n >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)\\n Point2D(11\\/10, 1\\/2)'\\n '''\",\"targets\":\"from sympy.geometry import Polygon, Segment, Point\\n if args:\\n if all((isinstance(g, Point) for g in args)):\\n c = Point(0, 0)\\n for g in args:\\n c += g\\n den = len(args)\\n elif all((isinstance(g, Segment) for g in args)):\\n c = Point(0, 0)\\n L = 0\\n for g in args:\\n l = g.length\\n c += (g.midpoint * l)\\n L += l\\n den = L\\n elif all((isinstance(g, Polygon) for g in args)):\\n c = Point(0, 0)\\n A = 0\\n for g in args:\\n a = g.area\\n c += (g.centroid * a)\\n A += a\\n den = A\\n c \\/= den\\n return c.func(*[i.simplify() for i in c.args])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef list_saml_providers(region=None, key=None, keyid=None, profile=None):\\n\\n ''''List SAML providers.\\n CLI Example:\\n .. code-block:: bash\\n salt myminion boto_iam.list_saml_providers'\\n '''\",\"targets\":\"conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n try:\\n providers = []\\n info = conn.list_saml_providers()\\n for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']:\\n providers.append(arn['arn'].rsplit('\\/', 1)[1])\\n return providers\\n except boto.exception.BotoServerError as e:\\n aws = __utils__['boto.get_error'](e)\\n log.debug(aws)\\n msg = 'Failed to get list of SAML providers.'\\n log.error(msg)\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _as_macro_if_defined(meth):\\n\\n ''''Decorator for printer methods\\n When a Printer\\\\'s method is decorated using this decorator the expressions printed\\n will first be looked for in the attribute ``math_macros``, and if present it will\\n print the macro name in ``math_macros`` followed by a type suffix for the type\\n ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80.'\\n '''\",\"targets\":\"@wraps(meth)\\n def _meth_wrapper(self, expr, **kwargs):\\n if (expr in self.math_macros):\\n return ('%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real)))\\n else:\\n return meth(self, expr, **kwargs)\\n return _meth_wrapper\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef atomp(lst):\\n\\n ''''Tuple items (representing structs) are regarded as atoms.'\\n '''\",\"targets\":\"return (not isinstance(lst, list))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef conv1d_sd(input, filters, image_shape, filter_shape, border_mode='valid', subsample=(1,), filter_flip=True):\\n\\n ''''using a single dot product'\\n '''\",\"targets\":\"if (border_mode not in ('valid', 0, (0,))):\\n raise RuntimeError(('Unsupported border_mode for conv1d_sd: %s' % border_mode))\\n (batch_size, num_input_channels, input_length) = image_shape\\n (num_filters, num_input_channels_, filter_length) = filter_shape\\n stride = subsample[0]\\n if ((filter_length % stride) > 0):\\n raise RuntimeError(('Filter length (%d) is not a multiple of the stride (%d)' % (filter_length, stride)))\\n num_steps = (filter_length \\/\\/ stride)\\n output_length = (((input_length - filter_length) + stride) \\/\\/ stride)\\n padded_length = (((input_length \\/\\/ filter_length) * filter_length) + ((num_steps - 1) * stride))\\n truncated_length = min(input_length, padded_length)\\n input_truncated = input[:, :, :truncated_length]\\n input_padded_shape = (batch_size, num_input_channels, padded_length)\\n input_padded = T.zeros(input_padded_shape)\\n input_padded = T.set_subtensor(input_padded[:, :, :truncated_length], input_truncated)\\n inputs = []\\n for num in range(num_steps):\\n shift = (num * stride)\\n length = ((padded_length - shift) \\/\\/ filter_length)\\n r_input_shape = (batch_size, num_input_channels, length, filter_length)\\n r_input = input_padded[:, :, shift:((length * filter_length) + shift)].reshape(r_input_shape)\\n inputs.append(r_input)\\n inputs_stacked = T.stack(*inputs)\\n filters_flipped = (filters[:, :, ::(-1)] if filter_flip else filters)\\n r_conved = T.tensordot(inputs_stacked, filters_flipped, np.asarray([[2, 4], [1, 2]]))\\n r_conved = r_conved.dimshuffle(1, 3, 2, 0)\\n conved = r_conved.reshape((r_conved.shape[0], r_conved.shape[1], (r_conved.shape[2] * r_conved.shape[3])))\\n return conved[:, :, :output_length]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_bound(pts):\\n\\n ''''Compute a minimal rectangle that covers all the points.'\\n '''\",\"targets\":\"(x0, y0, x1, y1) = (INF, INF, (- INF), (- INF))\\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)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY]\\n (host, path) = urlparse.urlparse(url)[1:3]\\n try:\\n conn = httplib.HTTPConnection(host)\\n conn.request(u'HEAD', path)\\n return (conn.getresponse().status in good_codes)\\n except StandardError:\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_url(url):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n argument_spec = dict(state=dict(choices=['present', 'absent'], default='present'), type=dict(choices=['ip', 'vxlan'], required=True), record_name=dict(type='str'), match=dict(choices=['destination-address', 'destination-port', 'tos', 'protocol', 'source-address', 'source-port']), collect_counter=dict(choices=['bytes', 'packets']), collect_interface=dict(choices=['input', 'output']), description=dict(type='str'))\\n argument_spec.update(ce_argument_spec)\\n module = NetstreamTemplate(argument_spec=argument_spec)\\n module.work()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def main():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (':' in expr):\\n (type, value) = expr.split(':', 1)\\n if (type == 'name'):\\n return value\\n else:\\n type = expr\\n return _describe_token_type(type)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def describe_token_expr(expr):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def map(requests, prefetch=True, size=None):\",\"targets\":\"\\\"\\\"\\\"\\n \\\"\\\"\\\"\\n requests = list(requests)\\n pool = (Pool(size) if size else None)\\n jobs = [send(r, pool, prefetch=prefetch) for r in requests]\\n gevent.joinall(jobs)\\n return [r.response for r in requests]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_new_desktop_name(parent_hwnd):\",\"targets\":\"\\\"\\\"\\\"Create a dialog box to ask the user for name of desktop to be created\\n \\\"\\\"\\\"\\n msgs = {win32con.WM_COMMAND: desktop_name_dlgproc, win32con.WM_CLOSE: desktop_name_dlgproc, win32con.WM_DESTROY: desktop_name_dlgproc}\\n style = (((win32con.WS_BORDER | win32con.WS_VISIBLE) | win32con.WS_CAPTION) | win32con.WS_SYSMENU)\\n h = win32gui.CreateDialogIndirect(win32api.GetModuleHandle(None), [['One ugly dialog box !', (100, 100, 200, 100), style, 0], ['Button', 'Create', win32con.IDOK, (10, 10, 30, 20), (((win32con.WS_VISIBLE | win32con.WS_TABSTOP) | win32con.BS_HOLLOW) | win32con.BS_DEFPUSHBUTTON)], ['Button', 'Never mind', win32con.IDCANCEL, (45, 10, 50, 20), ((win32con.WS_VISIBLE | win32con.WS_TABSTOP) | win32con.BS_HOLLOW)], ['Static', 'Desktop name:', 71, (10, 40, 70, 10), win32con.WS_VISIBLE], ['Edit', '', 72, (75, 40, 90, 10), win32con.WS_VISIBLE]], parent_hwnd, msgs)\\n win32gui.EnableWindow(h, True)\\n hcontrol = win32gui.GetDlgItem(h, 72)\\n win32gui.EnableWindow(hcontrol, True)\\n win32gui.SetFocus(hcontrol)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef gammaincc(a, x, dps=50, maxterms=(10 ** 8)):\\n\\n ''''Compute gammaincc exactly like mpmath does but allow for more\\n terms in hypercomb. See\\n mpmath\\/functions\\/expintegrals.py#L187\\n in the mpmath github repository.'\\n '''\",\"targets\":\"with mp.workdps(dps):\\n (z, a) = (a, x)\\n if mp.isint(z):\\n try:\\n return mpf2float(mp.gammainc(z, a=a, regularized=True))\\n except mp.libmp.NoConvergence:\\n pass\\n nega = mp.fneg(a, exact=True)\\n G = [z]\\n try:\\n def h(z):\\n r = (z - 1)\\n return [([mp.exp(nega), a], [1, r], [], G, [1, (- r)], [], (1 \\/ nega))]\\n return mpf2float(mp.hypercomb(h, [z], force_series=True))\\n except mp.libmp.NoConvergence:\\n def h(z):\\n T1 = ([], [1, (z - 1)], [z], G, [], [], 0)\\n T2 = ([(- mp.exp(nega)), a, z], [1, z, (-1)], [], G, [1], [(1 + z)], a)\\n return (T1, T2)\\n return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef flush(bank, key=None, cachedir=None):\\n\\n ''''Remove the key from the cache bank with all the key content. If no key is\\n specified remove the entire bank with all keys and sub-banks inside.\\n CLI Examples:\\n .. code-block:: bash\\n salt-run cache.flush cloud\\/active\\/ec2\\/myec2 cachedir=\\/var\\/cache\\/salt\\/\\n salt-run cache.flush cloud\\/active\\/ec2\\/myec2 myminion cachedir=\\/var\\/cache\\/salt\\/'\\n '''\",\"targets\":\"if (cachedir is None):\\n cachedir = __opts__['cachedir']\\n try:\\n cache = salt.cache.Cache(__opts__, cachedir=cachedir)\\n except TypeError:\\n cache = salt.cache.Cache(__opts__)\\n return cache.flush(bank, key)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_mean_initializer():\",\"targets\":\"\\\"\\\"\\\"Returns a default initializer for the `moving_mean` in batch norm.\\n \\\"\\\"\\\"\\n return tf.zeros_initializer()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not value):\\n return u''\\n if isinstance(value, six.text_type):\\n return value\\n if isinstance(value, six.binary_type):\\n return value.decode(encoding)\\n return six.text_type(value)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def to_text(value, encoding=u'utf-8'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _hasclass(context, *cls):\",\"targets\":\"\\\"\\\"\\\"Checks if the context node has all the classes passed as arguments\\n \\\"\\\"\\\"\\n node_classes = set(context.context_node.attrib.get('class', '').split())\\n return node_classes.issuperset(cls)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _plot_onscroll(event, params):\\n\\n ''''Handle scroll events.'\\n '''\",\"targets\":\"if (event.key == 'control'):\\n if (event.step < 0):\\n event.key = '-'\\n else:\\n event.key = '+'\\n _plot_onkey(event, params)\\n return\\n if params['butterfly']:\\n return\\n _plot_raw_onscroll(event, params, len(params['ch_names']))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def find_font_face_rules(sheet, oeb):\",\"targets\":\"\\\"\\\"\\\"Find all @font-face rules in the given sheet and extract the relevant info from them.\\n sheet can be either a ManifestItem or a CSSStyleSheet.\\n \\\"\\\"\\\"\\n ans = []\\n try:\\n rules = sheet.data.cssRules\\n except AttributeError:\\n rules = sheet.cssRules\\n for (i, rule) in enumerate(rules):\\n if (rule.type != rule.FONT_FACE_RULE):\\n continue\\n props = get_font_properties(rule, default=u'normal')\\n if ((not props[u'font-family']) or (not props[u'src'])):\\n continue\\n try:\\n path = sheet.abshref(props[u'src'])\\n except AttributeError:\\n path = props[u'src']\\n ff = oeb.manifest.hrefs.get(urlnormalize(path), None)\\n if (not ff):\\n continue\\n props[u'item'] = ff\\n if (props[u'font-weight'] in {u'bolder', u'lighter'}):\\n props[u'font-weight'] = u'400'\\n props[u'weight'] = int(props[u'font-weight'])\\n props[u'rule'] = rule\\n props[u'chars'] = set()\\n ans.append(props)\\n return ans\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef CastTo(ob, target):\\n\\n ''''\\\\'Cast\\\\' a COM object to another interface'\\n '''\",\"targets\":\"if hasattr(target, 'index'):\\n if ('CLSID' not in ob.__class__.__dict__):\\n ob = gencache.EnsureDispatch(ob)\\n if ('CLSID' not in ob.__class__.__dict__):\\n raise ValueError('Must be a makepy-able object for this to work')\\n clsid = ob.CLSID\\n mod = gencache.GetModuleForCLSID(clsid)\\n mod = gencache.GetModuleForTypelib(mod.CLSID, mod.LCID, mod.MajorVersion, mod.MinorVersion)\\n target_clsid = mod.NamesToIIDMap.get(target)\\n if (target_clsid is None):\\n raise ValueError((\\\"The interface name '%s' does not appear in the same library as object '%r'\\\" % (target, ob)))\\n mod = gencache.GetModuleForCLSID(target_clsid)\\n target_class = getattr(mod, target)\\n target_class = getattr(target_class, 'default_interface', target_class)\\n return target_class(ob)\\n raise ValueError\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _flatten_params(params):\",\"targets\":\"\\\"\\\"\\\"Converts a dictionary of parameters to a list of parameters.\\n Any unicode strings in keys or values will be encoded as UTF-8.\\n Args:\\n params: Dictionary mapping parameter keys to values. Values will be\\n converted to a string and added to the list as tuple (key, value). If\\n a values is iterable and not a string, each contained value will be\\n added as a separate (key, value) tuple.\\n Returns:\\n List of (key, value) tuples.\\n \\\"\\\"\\\"\\n def get_string(value):\\n if isinstance(value, unicode):\\n return unicode(value).encode('utf-8')\\n else:\\n return str(value)\\n param_list = []\\n for (key, value) in params.iteritems():\\n key = get_string(key)\\n if isinstance(value, basestring):\\n param_list.append((key, get_string(value)))\\n else:\\n try:\\n iterator = iter(value)\\n except TypeError:\\n param_list.append((key, str(value)))\\n else:\\n param_list.extend(((key, get_string(v)) for v in iterator))\\n return param_list\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _MakeDispatchListIntoYaml(application, dispatch_list):\\n\\n ''''Converts list of DispatchEntry objects into a YAML string.'\\n '''\",\"targets\":\"statements = [('application: %s' % application), 'dispatch:']\\n for entry in dispatch_list:\\n statements += entry.ToYaml()\\n return ('\\\\n'.join(statements) + '\\\\n')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef listdir(dirname, ref=u'HEAD'):\\n\\n ''''Get the contents of a directory according to Git\\n Query Git for the content of a directory, taking ignored\\n files into account.'\\n '''\",\"targets\":\"dirs = []\\n files = []\\n entries = ls_tree(dirname, ref=ref)\\n for entry in entries:\\n if (entry[0][0] == u't'):\\n dirs.append(entry[1])\\n else:\\n files.append(entry[1])\\n untracked = untracked_files(paths=[dirname], directory=True)\\n for path in untracked:\\n if path.endswith(u'\\/'):\\n dirs.append(path[:(-1)])\\n else:\\n files.append(path)\\n dirs.sort()\\n files.sort()\\n return (dirs, files)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@testing.requires_testing_data\\ndef test_crop():\",\"targets\":\"\\\"\\\"\\\"Test cropping raw files.\\n \\\"\\\"\\\"\\n raw = concatenate_raws([read_raw_fif(f) for f in [fif_fname, fif_fname]])\\n split_size = 10.0\\n sfreq = raw.info['sfreq']\\n nsamp = ((raw.last_samp - raw.first_samp) + 1)\\n tmins = np.r_[(1.0, np.round(np.arange(0.0, (nsamp - 1), (split_size * sfreq))))]\\n tmins = np.sort(tmins)\\n tmaxs = np.concatenate(((tmins[1:] - 1), [(nsamp - 1)]))\\n tmaxs \\/= sfreq\\n tmins \\/= sfreq\\n raws = ([None] * len(tmins))\\n for (ri, (tmin, tmax)) in enumerate(zip(tmins, tmaxs)):\\n raws[ri] = raw.copy().crop(tmin, tmax)\\n all_raw_2 = concatenate_raws(raws, preload=False)\\n assert_equal(raw.first_samp, all_raw_2.first_samp)\\n assert_equal(raw.last_samp, all_raw_2.last_samp)\\n assert_array_equal(raw[:, :][0], all_raw_2[:, :][0])\\n tmins = np.round(np.arange(0.0, (nsamp - 1), (split_size * sfreq)))\\n tmaxs = np.concatenate(((tmins[1:] - 1), [(nsamp - 1)]))\\n tmaxs \\/= sfreq\\n tmins \\/= sfreq\\n raws = ([None] * len(tmins))\\n for (ri, (tmin, tmax)) in enumerate(zip(tmins, tmaxs)):\\n raws[ri] = raw.copy().crop(tmin, tmax)\\n all_raw_1 = concatenate_raws(raws, preload=False)\\n all_raw_2 = raw.copy().crop(0, None)\\n for ar in [all_raw_1, all_raw_2]:\\n assert_equal(raw.first_samp, ar.first_samp)\\n assert_equal(raw.last_samp, ar.last_samp)\\n assert_array_equal(raw[:, :][0], ar[:, :][0])\\n data = np.zeros((1, 1002001))\\n info = create_info(1, 1000)\\n raw = RawArray(data, info)\\n for tmin in range(0, 1001, 100):\\n raw1 = raw.copy().crop(tmin=tmin, tmax=(tmin + 2))\\n assert_equal(raw1[:][0].shape, (1, 2001))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ReserveKeys(keys):\",\"targets\":\"\\\"\\\"\\\"Reserve all ids in the paths of the given keys.\\n Args:\\n keys: A list of keys with ids in their paths, for which the corresponding\\n id sequences should be advanced to prevent id collisions.\\n \\\"\\\"\\\"\\n datastore._GetConnection()._reserve_keys(ConvertKeys(keys))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def humanFrequency(hertz):\",\"targets\":\"\\\"\\\"\\\"Convert a frequency in hertz to human classic representation.\\n It uses the values: 1 KHz is 1000 Hz, 1 MHz is 1000 KMhz, etc.\\n The result is an unicode string.\\n >>> humanFrequency(790)\\n u\\\\790 Hz\\\\\\n >>> humanFrequency(629469)\\n u\\\\629.5 kHz\\\\\\n \\\"\\\"\\\"\\n divisor = 1000\\n if (hertz < divisor):\\n return (u'%u Hz' % hertz)\\n units = [u'kHz', u'MHz', u'GHz', u'THz']\\n hertz = float(hertz)\\n for unit in units:\\n hertz = (hertz \\/ divisor)\\n if (hertz < divisor):\\n return (u'%.1f %s' % (hertz, unit))\\n return (u'%s %s' % (hertz, unit))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@verbose\\ndef gamma_map(evoked, forward, noise_cov, alpha, loose=0.2, depth=0.8, xyz_same_gamma=True, maxit=10000, tol=1e-06, update_mode=1, gammas=None, pca=True, return_residual=False, return_as_dipoles=False, verbose=None):\",\"targets\":\"\\\"\\\"\\\"Hierarchical Bayes (Gamma-MAP) sparse source localization method.\\n Models each source time course using a zero-mean Gaussian prior with an\\n unknown variance (gamma) parameter. During estimation, most gammas are\\n driven to zero, resulting in a sparse source estimate, as in\\n [1]_ and [2]_.\\n For fixed-orientation forward operators, a separate gamma is used for each\\n source time course, while for free-orientation forward operators, the same\\n gamma is used for the three source time courses at each source space point\\n (separate gammas can be used in this case by using xyz_same_gamma=False).\\n Parameters\\n evoked : instance of Evoked\\n Evoked data to invert.\\n forward : dict\\n Forward operator.\\n noise_cov : instance of Covariance\\n Noise covariance to compute whitener.\\n alpha : float\\n Regularization parameter (noise variance).\\n loose : float in [0, 1]\\n Value that weights the source variances of the dipole components\\n that are parallel (tangential) to the cortical surface. If loose\\n is 0 or None then the solution is computed with fixed orientation.\\n If loose is 1, it corresponds to free orientations.\\n depth: None | float in [0, 1]\\n Depth weighting coefficients. If None, no depth weighting is performed.\\n xyz_same_gamma : bool\\n Use same gamma for xyz current components at each source space point.\\n Recommended for free-orientation forward solutions.\\n maxit : int\\n Maximum number of iterations.\\n tol : float\\n Tolerance parameter for convergence.\\n update_mode : int\\n Update mode, 1: MacKay update (default), 2: Modified MacKay update.\\n gammas : array, shape=(n_sources,)\\n Initial values for posterior variances (gammas). If None, a\\n variance of 1.0 is used.\\n pca : bool\\n If True the rank of the data is reduced to the true dimension.\\n return_residual : bool\\n If True, the residual is returned as an Evoked instance.\\n return_as_dipoles : bool\\n If True, the sources are returned as a list of Dipole instances.\\n ...\\\"\\\"\\\"\\n _check_reference(evoked)\\n if ((loose is None) and (not is_fixed_orient(forward))):\\n forward = deepcopy(forward)\\n _to_fixed_ori(forward)\\n if (is_fixed_orient(forward) or (not xyz_same_gamma)):\\n group_size = 1\\n else:\\n group_size = 3\\n (gain, gain_info, whitener, source_weighting, mask) = _prepare_gain(forward, evoked.info, noise_cov, pca, depth, loose, None, None)\\n sel = [evoked.ch_names.index(name) for name in gain_info['ch_names']]\\n M = evoked.data[sel]\\n logger.info('Whitening data matrix.')\\n M = np.dot(whitener, M)\\n (X, active_set) = _gamma_map_opt(M, gain, alpha, maxit=maxit, tol=tol, update_mode=update_mode, gammas=gammas, group_size=group_size, verbose=verbose)\\n if (len(active_set) == 0):\\n raise Exception('No active dipoles found. alpha is too big.')\\n M_estimated = np.dot(gain[:, active_set], X)\\n n_dip_per_pos = (1 if is_fixed_orient(forward) else 3)\\n X = _reapply_source_weighting(X, source_weighting, active_set, n_dip_per_pos)\\n if return_residual:\\n residual = _compute_residual(forward, evoked, X, active_set, gain_info)\\n if ((group_size == 1) and (not is_fixed_orient(forward))):\\n active_src = np.unique((active_set \\/\\/ 3))\\n in_pos = 0\\n if (len(X) < (3 * len(active_src))):\\n X_xyz = np.zeros(((3 * len(active_src)), X.shape[1]), dtype=X.dtype)\\n for ii in range(len(active_src)):\\n for jj in range(3):\\n if (in_pos >= len(active_set)):\\n break\\n if (((active_set[in_pos] + jj) % 3) == 0):\\n X_xyz[((3 * ii) + jj)] = X[in_pos]\\n in_pos += 1\\n X = X_xyz\\n tmin = evoked.times[0]\\n tstep = (1.0 \\/ evoked.info['sfreq'])\\n if return_as_dipoles:\\n out = _make_dipoles_sparse(X, active_set, forward, tmin, tstep, M, M_estimated, active_is_idx=True)\\n else:\\n out = _make_sparse_stc(X, active_set, forward, tmin, tstep,...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n lenPad = ((messageLength - 2) - len(data))\\n return ((('\\\\x01' + ('\\\\xff' * lenPad)) + '\\\\x00') + data)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def pkcs1Pad(data, messageLength):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _node_redundancy(G, v):\\n\\n ''''Returns the redundancy of the node `v` in the bipartite graph `G`.\\n If `G` is a graph with `n` nodes, the redundancy of a node is the ratio\\n of the \\\"overlap\\\" of `v` to the maximum possible overlap of `v`\\n according to its degree. The overlap of `v` is the number of pairs of\\n neighbors that have mutual neighbors themselves, other than `v`.\\n `v` must have at least two neighbors in `G`.'\\n '''\",\"targets\":\"n = len(G[v])\\n overlap = sum((1 for (u, w) in combinations(G[v], 2) if ((set(G[u]) & set(G[w])) - {v})))\\n return ((2 * overlap) \\/ (n * (n - 1)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@core_helper\\ndef follow_button(obj_type, obj_id):\",\"targets\":\"\\\"\\\"\\\"Return a follow button for the given object type and id.\\n If the user is not logged in return an empty string instead.\\n :param obj_type: the type of the object to be followed when the follow\\n button is clicked, e.g. \\\\user\\\\ or \\\\dataset\\\\\\n :type obj_type: string\\n :param obj_id: the id of the object to be followed when the follow button\\n is clicked\\n :type obj_id: string\\n :returns: a follow button as an HTML snippet\\n :rtype: string\\n \\\"\\\"\\\"\\n obj_type = obj_type.lower()\\n assert (obj_type in _follow_objects)\\n if c.user:\\n context = {'model': model, 'session': model.Session, 'user': c.user}\\n action = ('am_following_%s' % obj_type)\\n following = logic.get_action(action)(context, {'id': obj_id})\\n return snippet('snippets\\/follow_button.html', following=following, obj_id=obj_id, obj_type=obj_type)\\n return ''\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n disp = Dispatch(clsid)\\n if (not disp.__class__.__dict__.get('CLSID')):\\n try:\\n ti = disp._oleobj_.GetTypeInfo()\\n disp_clsid = ti.GetTypeAttr()[0]\\n (tlb, index) = ti.GetContainingTypeLib()\\n tla = tlb.GetLibAttr()\\n gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)\\n disp_class = gencache.GetClassForProgID(str(disp_clsid))\\n except pythoncom.com_error:\\n raise TypeError('This COM object can not automate the makepy process - please run makepy manually for this object')\\n else:\\n disp_class = disp.__class__\\n clsid = disp_class.CLSID\\n try:\\n from types import ClassType as new_type\\n except ImportError:\\n new_type = type\\n events_class = getevents(clsid)\\n if (events_class is None):\\n raise ValueError('This COM object does not support events.')\\n result_class = new_type('COMEventClass', (disp_class, events_class, user_event_class), {'__setattr__': _event_setattr_})\\n instance = result_class(disp._oleobj_)\\n events_class.__init__(instance, instance)\\n if hasattr(user_event_class, '__init__'):\\n user_event_class.__init__(instance)\\n return EventsProxy(instance)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def DispatchWithEvents(clsid, user_event_class):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for line in codecs.getreader(encoding)(stream):\\n (yield line.encode('utf-8'))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def utf8_recoder(stream, encoding):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n ckpt = tf.train.get_checkpoint_state(os.path.dirname((config.CPT_PATH + '\\/checkpoint')))\\n if (ckpt and ckpt.model_checkpoint_path):\\n print('Loading parameters for the Chatbot')\\n saver.restore(sess, ckpt.model_checkpoint_path)\\n else:\\n print('Initializing fresh parameters for the Chatbot')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _check_restore_parameters(sess, saver):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef csrf_response_exempt(view_func):\\n\\n ''''Modifies a view function so that its response is exempt\\n from the post-processing of the CSRF middleware.'\\n '''\",\"targets\":\"def wrapped_view(*args, **kwargs):\\n resp = view_func(*args, **kwargs)\\n resp.csrf_exempt = True\\n return resp\\n return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@profiler.trace\\ndef remove_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None):\\n\\n ''''Removes a given single role for a user from a tenant.'\\n '''\",\"targets\":\"manager = keystoneclient(request, admin=True).roles\\n if (VERSIONS.active < 3):\\n return manager.remove_user_role(user, role, project)\\n else:\\n return manager.revoke(role, user=user, project=project, group=group, domain=domain)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n lock = 'perm({}) or perm(events_without_validation)'.format(WITHOUT_VALIDATION)\\n autovalid = caller.locks.check_lockstring(caller, lock)\\n callback = caller.db._callback\\n handler = get_event_handler()\\n if ((not handler) or (not callback) or (not all(((key in callback) for key in ('obj', 'name', 'number', 'valid'))))):\\n caller.msg(\\\"Couldn't save this callback.\\\")\\n return False\\n if ((callback['obj'], callback['name'], callback['number']) in handler.db.locked):\\n handler.db.locked.remove((callback['obj'], callback['name'], callback['number']))\\n handler.edit_callback(callback['obj'], callback['name'], callback['number'], buf, caller, valid=autovalid)\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _ev_save(caller, buf):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if isinstance(uri, tuple):\\n uri = url_unparse(uri)\\n uri = url_parse(to_unicode(uri, charset))\\n path = url_unquote(uri.path, charset, errors, '%\\/;?')\\n query = url_unquote(uri.query, charset, errors, '%;\\/?:@&=+,$#')\\n fragment = url_unquote(uri.fragment, charset, errors, '%;\\/?:@&=+,$#')\\n return url_unparse((uri.scheme, uri.decode_netloc(), path, query, fragment))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def uri_to_iri(uri, charset='utf-8', errors='replace'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef ensemble(nets):\\n\\n ''''Takes as input a list of nets, and then computes the accuracy on\\n the test data when classifications are computed by taking a vote\\n amongst the nets. Returns a tuple containing a list of indices\\n for test data which is erroneously classified, and a list of the\\n corresponding erroneous predictions.\\n Note that this is a quick-and-dirty kluge: it\\\\'d be more reusable\\n (and faster) to define a Theano function taking the vote. But\\n this works.'\\n '''\",\"targets\":\"(test_x, test_y) = test_data\\n for net in nets:\\n i = T.lscalar()\\n net.test_mb_predictions = theano.function([i], net.layers[(-1)].y_out, givens={net.x: test_x[(i * net.mini_batch_size):((i + 1) * net.mini_batch_size)]})\\n net.test_predictions = list(np.concatenate([net.test_mb_predictions(i) for i in xrange(1000)]))\\n all_test_predictions = zip(*[net.test_predictions for net in nets])\\n def plurality(p):\\n return Counter(p).most_common(1)[0][0]\\n plurality_test_predictions = [plurality(p) for p in all_test_predictions]\\n test_y_eval = test_y.eval()\\n error_locations = [j for j in xrange(10000) if (plurality_test_predictions[j] != test_y_eval[j])]\\n erroneous_predictions = [plurality(all_test_predictions[j]) for j in error_locations]\\n print 'Accuracy is {:.2%}'.format((1 - (len(error_locations) \\/ 10000.0)))\\n return (error_locations, erroneous_predictions)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_blocks, environment.newline_sequence)\\n lexer = _lexer_cache.get(key)\\n if (lexer is None):\\n lexer = Lexer(environment)\\n _lexer_cache[key] = lexer\\n return lexer\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_lexer(environment):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_descrs(arrays, col_name_map):\",\"targets\":\"\\\"\\\"\\\"Find the dtypes descrs resulting from merging the list of arrays\\\\ dtypes,\\n using the column name mapping ``col_name_map``.\\n Return a list of descrs for the output.\\n \\\"\\\"\\\"\\n out_descrs = []\\n for (out_name, in_names) in six.iteritems(col_name_map):\\n in_cols = [arr[name] for (arr, name) in zip(arrays, in_names) if (name is not None)]\\n names = [name for name in in_names if (name is not None)]\\n try:\\n dtype = common_dtype(in_cols)\\n except TableMergeError as tme:\\n raise TableMergeError(u\\\"The '{0}' columns have incompatible types: {1}\\\".format(names[0], tme._incompat_types))\\n uniq_shapes = set((col.shape[1:] for col in in_cols))\\n if (len(uniq_shapes) != 1):\\n raise TableMergeError(u'Key columns {0!r} have different shape'.format(names))\\n shape = uniq_shapes.pop()\\n out_descrs.append((fix_column_name(out_name), dtype, shape))\\n return out_descrs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef W3CDTF_to_datetime(formatted_string):\\n\\n ''''Convert from a timestamp string to a datetime object.'\\n '''\",\"targets\":\"match = W3CDTF_REGEX.match(formatted_string)\\n dt = [int(v) for v in match.groups()[:6]]\\n return datetime.datetime(*dt)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def copy_recursively(source_dir, target_dir):\",\"targets\":\"\\\"\\\"\\\"Recursively copy a source directory (and all its contents) to a target\\n directory.\\n :Parameters:\\n source_dir : str\\n Source directory to copy recursively. This path must\\n exist and must specify a directory; otherwise, this\\n function throws a ``ValueError``\\n target_dir : str\\n Directory to which to copy the contents of ``source_dir``.\\n This directory must not already exist.\\n :raise ValueError: If: ``source_dir`` does not exist; ``source_dir`` exists\\n but is not a directory; or ``target_dir`` exists but is\\n not a directory.\\n \\\"\\\"\\\"\\n shutil.copytree(source_dir, target_dir)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _add_gamma_multipliers(bem):\\n\\n ''''Add gamma and multipliers in-place.'\\n '''\",\"targets\":\"bem['sigma'] = np.array([surf['sigma'] for surf in bem['surfs']])\\n sigma = np.r_[(0.0, bem['sigma'])]\\n bem['source_mult'] = (2.0 \\/ (sigma[1:] + sigma[:(-1)]))\\n bem['field_mult'] = (sigma[1:] - sigma[:(-1)])\\n assert (len(bem['surfs']) == len(bem['field_mult']))\\n bem['gamma'] = ((sigma[1:] - sigma[:(-1)])[np.newaxis, :] \\/ (sigma[1:] + sigma[:(-1)])[:, np.newaxis])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def generate_min(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3'):\",\"targets\":\"\\\"\\\"\\\"Generate the salt-thin tarball and print the location of the tarball\\n Optional additional mods to include (e.g. mako) can be supplied as a comma\\n delimited string. Permits forcing an overwrite of the output file as well.\\n CLI Example:\\n .. code-block:: bash\\n salt-run thin.generate_min\\n \\\"\\\"\\\"\\n conf_mods = __opts__.get('min_extra_mods')\\n if conf_mods:\\n extra_mods = ','.join([conf_mods, extra_mods])\\n return salt.utils.thin.gen_min(__opts__['cachedir'], extra_mods, overwrite, so_mods, python2_bin, python3_bin)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _PPIGuessPayloadClass(p, **kargs):\",\"targets\":\"\\\"\\\"\\\"This function tells the PacketListField how it should extract the\\n TLVs from the payload. We pass cls only the length string\\n pfh_len says it needs. If a payload is returned, that means\\n part of the sting was unused. This converts to a Raw layer, and\\n the remainder of p is added as Raw\\\\s payload. If there is no\\n payload, the remainder of p is added as out\\\\s payload.\\n \\\"\\\"\\\"\\n if (len(p) >= 4):\\n (t, pfh_len) = struct.unpack(' pfh_len):\\n out.payload.payload = conf.padding_layer(p[pfh_len:])\\n elif (len(p) > pfh_len):\\n out.payload = conf.padding_layer(p[pfh_len:])\\n else:\\n out = conf.raw_layer(p, **kargs)\\n return out\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n _do_hypervisor_list(cs, matching=args.matching, limit=args.limit, marker=args.marker)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@api_versions.wraps('2.33')\\n@utils.arg('--matching', metavar='', default=None, help=_('List hypervisors matching the given (or pattern). If matching is used limit and marker options will be ignored.'))\\n@utils.arg('--marker', dest='marker', metavar='', default=None, help=_('The last hypervisor of the previous page; displays list of hypervisors after \\\"marker\\\".'))\\n@utils.arg('--limit', dest='limit', metavar='', type=int, default=None, help=_(\\\"Maximum number of hypervisors to display. If limit is bigger than 'CONF.api.max_limit' option of Nova API, limit 'CONF.api.max_limit' will be used instead.\\\"))\\ndef do_hypervisor_list(cs, args):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@csrf_exempt\\ndef bitbucket_build(request):\\n\\n ''''Consume webhooks from multiple versions of Bitbucket\\\\'s API\\n .. warning:: **DEPRECATED**\\n Use :py:cls:`readthedocs.restapi.views.intergrations.BitbucketWebhookView`\\n instead of this view function\\n New webhooks are set up with v2, but v1 webhooks will still point to this\\n endpoint. There are also \\\"services\\\" that point here and submit\\n ``application\\/x-www-form-urlencoded`` data.\\n API v1\\n https:\\/\\/confluence.atlassian.com\\/bitbucket\\/events-resources-296095220.html\\n API v2\\n https:\\/\\/confluence.atlassian.com\\/bitbucket\\/event-payloads-740262817.html#EventPayloads-Push\\n Services\\n https:\\/\\/confluence.atlassian.com\\/bitbucket\\/post-service-management-223216518.html'\\n '''\",\"targets\":\"if (request.method == 'POST'):\\n try:\\n if (request.META['CONTENT_TYPE'] == 'application\\/x-www-form-urlencoded'):\\n data = json.loads(request.POST.get('payload'))\\n else:\\n data = json.loads(request.body)\\n version = (2 if (request.META.get('HTTP_USER_AGENT') == 'Bitbucket-Webhooks\\/2.0') else 1)\\n if (version == 1):\\n branches = [commit.get('branch', '') for commit in data['commits']]\\n repository = data['repository']\\n search_url = 'bitbucket.org{0}'.format(repository['absolute_url'].rstrip('\\/'))\\n elif (version == 2):\\n changes = data['push']['changes']\\n branches = [change['new']['name'] for change in changes]\\n search_url = 'bitbucket.org\\/{0}'.format(data['repository']['full_name'])\\n except (TypeError, ValueError, KeyError):\\n log.error('Invalid Bitbucket webhook payload', exc_info=True)\\n return HttpResponse('Invalid request', status=400)\\n log.info('Bitbucket webhook search: url=%s branches=%s', search_url, branches)\\n log.debug('Bitbucket webhook payload:\\\\n\\\\n%s\\\\n\\\\n', data)\\n projects = get_project_from_url(search_url)\\n if (projects and branches):\\n return _build_url(search_url, projects, branches)\\n elif (not branches):\\n log.error('Commit\\/branch not found url=%s branches=%s', search_url, branches)\\n return HttpResponseNotFound('Commit\\/branch not found')\\n log.error('Project match not found: url=%s', search_url)\\n return HttpResponseNotFound('Project match not found')\\n return HttpResponse('Method not allowed, POST is required', status=405)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (_, factors) = factor_list(a.minpoly, extension=b)\\n for (f, _) in factors:\\n if (f.degree() == 1):\\n coeffs = f.rep.TC().to_sympy_list()\\n (d, terms) = ((len(coeffs) - 1), [])\\n for (i, coeff) in enumerate(coeffs):\\n terms.append((coeff * (b.root ** (d - i))))\\n root = Add(*terms)\\n if ((a.root - root).evalf(chop=True) == 0):\\n return coeffs\\n if ((a.root + root).evalf(chop=True) == 0):\\n return [(- c) for c in coeffs]\\n else:\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def field_isomorphism_factor(a, b):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def iriencode(value):\",\"targets\":\"\\\"\\\"\\\"Escapes an IRI value for use in a URL.\\n \\\"\\\"\\\"\\n return force_unicode(iri_to_uri(value))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def DownloadCollection(coll_path, target_path, token=None, overwrite=False, dump_client_info=False, flatten=False, max_threads=10):\",\"targets\":\"\\\"\\\"\\\"Iterate through a Collection object downloading all files.\\n Args:\\n coll_path: Path to an AFF4 collection.\\n target_path: Base directory to write to.\\n token: Token for access.\\n overwrite: If True, overwrite existing files.\\n dump_client_info: If True, this will detect client paths, and dump a yaml\\n version of the client object to the root path. This is useful for seeing\\n the hostname\\/users of the machine the client id refers to.\\n flatten: If True, produce a \\\"files\\\" flat folder with links to all the found\\n files.\\n max_threads: Use this many threads to do the downloads.\\n \\\"\\\"\\\"\\n completed_clients = set()\\n coll = _OpenCollectionPath(coll_path, token=token)\\n if (coll is None):\\n logging.error('%s is not a valid collection. Typo? Are you sure something was written to it?', coll_path)\\n return\\n thread_pool = threadpool.ThreadPool.Factory('Downloader', max_threads)\\n thread_pool.Start()\\n try:\\n collection_urn = coll.collection_id\\n except AttributeError:\\n collection_urn = coll.urn\\n try:\\n original_client_id = rdf_client.ClientURN(collection_urn.Split()[0])\\n except IOError:\\n original_client_id = None\\n logging.info('Expecting to download %s files', len(coll))\\n for grr_message in coll:\\n source = None\\n if isinstance(grr_message, rdf_flows.GrrMessage):\\n source = grr_message.source\\n grr_message = grr_message.payload\\n if isinstance(grr_message, rdfvalue.RDFURN):\\n urn = grr_message\\n elif isinstance(grr_message, rdf_client.StatEntry):\\n urn = rdfvalue.RDFURN(grr_message.AFF4Path((source or original_client_id)))\\n elif isinstance(grr_message, rdf_file_finder.FileFinderResult):\\n urn = rdfvalue.RDFURN(grr_message.stat_entry.AFF4Path((source or original_client_id)))\\n elif isinstance(grr_message, collectors.ArtifactFilesDownloaderResult):\\n if grr_message.HasField('downloaded_file'):\\n urn = grr_message.downloaded_file.AFF4Path((source or original_client_id))\\n else:\\n continue\\n elif isinstance(grr_message, rdfvalue.RDFBytes):\\n try:\\n os.makedirs(target_path)\\n except OSError:\\n pass\\n try:\\n client_id = source.Split()[0]\\n with open(os.path.join(target_path, client_id), 'wb') as fd:\\n fd.write(str(grr_message))\\n except AttributeError:\\n pass\\n continue\\n else:\\n continue\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef main():\\n\\n ''''Main function\\n :return: None'\\n '''\",\"targets\":\"module = AnsibleModule(argument_spec=ClcSnapshot.define_argument_spec(), supports_check_mode=True)\\n clc_snapshot = ClcSnapshot(module)\\n clc_snapshot.process_request()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef hpfilter(X, lamb=1600):\\n\\n ''''Hodrick-Prescott filter\\n Parameters\\n X : array-like\\n The 1d ndarray timeseries to filter of length (nobs,) or (nobs,1)\\n lamb : float\\n The Hodrick-Prescott smoothing parameter. A value of 1600 is\\n suggested for quarterly data. Ravn and Uhlig suggest using a value\\n of 6.25 (1600\\/4**4) for annual data and 129600 (1600*3**4) for monthly\\n data.\\n Returns\\n cycle : array\\n The estimated cycle in the data given lamb.\\n trend : array\\n The estimated trend in the data given lamb.\\n Examples\\n >>> import statsmodels.api as sm\\n >>> import pandas as pd\\n >>> dta = sm.datasets.macrodata.load_pandas().data\\n >>> index = pd.DatetimeIndex(start=\\\\'1959Q1\\\\', end=\\\\'2009Q4\\\\', freq=\\\\'Q\\\\')\\n >>> dta.set_index(index, inplace=True)\\n >>> cycle, trend = sm.tsa.filters.hpfilter(dta.realgdp, 1600)\\n >>> gdp_decomp = dta[[\\\\'realgdp\\\\']]\\n >>> gdp_decomp[\\\"cycle\\\"] = cycle\\n >>> gdp_decomp[\\\"trend\\\"] = trend\\n >>> import matplotlib.pyplot as plt\\n >>> fig, ax = plt.subplots()\\n >>> gdp_decomp[[\\\"realgdp\\\", \\\"trend\\\"]][\\\"2000-03-31\\\":].plot(ax=ax,\\n ... fontsize=16);\\n >>> plt.show()\\n .. plot:: plots\\/hpf_plot.py\\n Notes\\n The HP filter removes a smooth trend, `T`, from the data `X`. by solving\\n min sum((X[t] - T[t])**2 + lamb*((T[t+1] - T[t]) - (T[t] - T[t-1]))**2)\\n T t\\n Here we implemented the HP filter as a ridge-regression rule using\\n scipy.sparse. In this sense, the solution can be written as\\n T = inv(I - lamb*K\\\\'K)X\\n where I is a nobs x nobs identity matrix, and K is a (nobs-2) x nobs matrix\\n such that\\n K[i,j] = 1 if i == j or i == j + 2\\n K[i,j] = -2 if i == j + 1\\n K[i,j] = 0 otherwise\\n See Also\\n statsmodels.tsa.filters.bk_filter.bkfilter\\n statsmodels.tsa.filters.cf_filter.cffilter\\n statsmodels.tsa.seasonal.seasonal_decompose\\n References\\n Hodrick, R.J, and E. C. Prescott. 1980. \\\"Postwar U.S. Business Cycles: An\\n Empricial Investigation.\\\" `Carnegie Mellon University...'''\",\"targets\":\"_pandas_wrapper = _maybe_get_pandas_wrapper(X)\\n X = np.asarray(X, float)\\n if (X.ndim > 1):\\n X = X.squeeze()\\n nobs = len(X)\\n I = sparse.eye(nobs, nobs)\\n offsets = np.array([0, 1, 2])\\n data = np.repeat([[1.0], [(-2.0)], [1.0]], nobs, axis=1)\\n K = sparse.dia_matrix((data, offsets), shape=((nobs - 2), nobs))\\n use_umfpack = True\\n trend = spsolve((I + (lamb * K.T.dot(K))), X, use_umfpack=use_umfpack)\\n cycle = (X - trend)\\n if (_pandas_wrapper is not None):\\n return (_pandas_wrapper(cycle), _pandas_wrapper(trend))\\n return (cycle, trend)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef build_dev_from_opts(opts):\\n\\n ''''Convert optparse stype options into a device dictionary.'\\n '''\",\"targets\":\"for (attribute, shortopt, longopt) in (['region', '-r', '--region'], ['zone', '-z', '--zone'], ['ip', '-i', '--ip'], ['port', '-p', '--port'], ['device', '-d', '--device'], ['weight', '-w', '--weight']):\\n if (getattr(opts, attribute, None) is None):\\n raise ValueError(('Required argument %s\\/%s not specified.' % (shortopt, longopt)))\\n ip = validate_and_normalize_address(opts.ip)\\n replication_ip = validate_and_normalize_address((opts.replication_ip or opts.ip))\\n replication_port = (opts.replication_port or opts.port)\\n if (not validate_device_name(opts.device)):\\n raise ValueError('Invalid device name')\\n return {'region': opts.region, 'zone': opts.zone, 'ip': ip, 'port': opts.port, 'device': opts.device, 'meta': opts.meta, 'replication_ip': replication_ip, 'replication_port': replication_port, 'weight': opts.weight}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dispatch_on(*dispatch_args):\",\"targets\":\"\\\"\\\"\\\"Factory of decorators turning a function into a generic function\\n dispatching on the given arguments.\\n \\\"\\\"\\\"\\n assert dispatch_args, 'No dispatch args passed'\\n dispatch_str = ('(%s,)' % ', '.join(dispatch_args))\\n def check(arguments, wrong=operator.ne, msg=''):\\n 'Make sure one passes the expected number of arguments'\\n if wrong(len(arguments), len(dispatch_args)):\\n raise TypeError(('Expected %d arguments, got %d%s' % (len(dispatch_args), len(arguments), msg)))\\n def gen_func_dec(func):\\n 'Decorator turning a function into a generic function'\\n argset = set(getfullargspec(func).args)\\n if (not (set(dispatch_args) <= argset)):\\n raise NameError(('Unknown dispatch arguments %s' % dispatch_str))\\n typemap = {}\\n def vancestors(*types):\\n '\\\\n Get a list of sets of virtual ancestors for the given types\\\\n '\\n check(types)\\n ras = [[] for _ in range(len(dispatch_args))]\\n for types_ in typemap:\\n for (t, type_, ra) in zip(types, types_, ras):\\n if (issubclass(t, type_) and (type_ not in t.__mro__)):\\n append(type_, ra)\\n return [set(ra) for ra in ras]\\n def ancestors(*types):\\n '\\\\n Get a list of virtual MROs, one for each type\\\\n '\\n check(types)\\n lists = []\\n for (t, vas) in zip(types, vancestors(*types)):\\n n_vas = len(vas)\\n if (n_vas > 1):\\n raise RuntimeError(('Ambiguous dispatch for %s: %s' % (t, vas)))\\n elif (n_vas == 1):\\n (va,) = vas\\n mro = type('t', (t, va), {}).__mro__[1:]\\n else:\\n mro = t.__mro__\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef install(io_loop=None):\\n\\n ''''Install this package as the default Twisted reactor.'\\n '''\",\"targets\":\"if (not io_loop):\\n io_loop = tornado.ioloop.IOLoop.current()\\n reactor = TornadoReactor(io_loop)\\n from twisted.internet.main import installReactor\\n installReactor(reactor)\\n return reactor\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_quantifier(ch, input_iter):\\n\\n ''''Parse a quantifier from the input, where \\\"ch\\\" is the first character in the\\n quantifier.\\n Returns the minimum number of occurences permitted by the quantifier and\\n either None or the next character from the input_iter if the next character\\n is not part of the quantifier.'\\n '''\",\"targets\":\"if (ch in u'*?+'):\\n try:\\n (ch2, escaped) = next(input_iter)\\n except StopIteration:\\n ch2 = None\\n if (ch2 == u'?'):\\n ch2 = None\\n if (ch == u'+'):\\n return (1, ch2)\\n return (0, ch2)\\n quant = []\\n while (ch != u'}'):\\n (ch, escaped) = next(input_iter)\\n quant.append(ch)\\n quant = quant[:(-1)]\\n values = u''.join(quant).split(u',')\\n try:\\n (ch, escaped) = next(input_iter)\\n except StopIteration:\\n ch = None\\n if (ch == u'?'):\\n ch = None\\n return (int(values[0]), ch)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_auth_from_url(url):\",\"targets\":\"\\\"\\\"\\\"Given a url with authentication components, extract them into a tuple of\\n username,password.\\n \\\"\\\"\\\"\\n parsed = urlparse(url)\\n try:\\n auth = (unquote(parsed.username), unquote(parsed.password))\\n except (AttributeError, TypeError):\\n auth = ('', '')\\n return auth\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef list_nodes_min(call=None):\\n\\n ''''Return a list of the instances that are on the provider. Only a list of\\n instances names, and their state, is returned.\\n CLI Examples:\\n .. code-block:: bash\\n salt-cloud -f list_nodes_min my-qingcloud'\\n '''\",\"targets\":\"if (call != 'function'):\\n raise SaltCloudSystemExit('The list_nodes_min function must be called with -f or --function.')\\n nodes = list_nodes_full()\\n result = {}\\n for (instance_id, full_node) in nodes.items():\\n result[instance_id] = {'name': full_node['instance_name'], 'status': full_node['status']}\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_subordinate_users(user, site):\",\"targets\":\"\\\"\\\"\\\"Returns users queryset, containing all subordinate users to given user\\n including users created by given user and not assigned to any page.\\n Not assigned users must be returned, because they shouldn\\\\t get lost, and\\n user should still have possibility to see them.\\n Only users created_by given user which are on the same, or lover level are\\n returned.\\n If user haves global permissions or is a superuser, then he can see all the\\n users.\\n This function is currently used in PagePermissionInlineAdminForm for limit\\n users in permission combobox.\\n Example:\\n A,W level 0\\n \\/ user B,GroupE level 1\\n Z \\/ C,X D,Y,W level 2\\n Rules: W was created by user, Z was created by user, but is not assigned\\n to any page.\\n Will return [user, C, X, D, Y, Z]. W was created by user, but is also\\n assigned to higher level.\\n \\\"\\\"\\\"\\n from cms.utils.page_permissions import get_change_permissions_id_list\\n try:\\n user_level = get_user_permission_level(user, site)\\n except NoPermissionsException:\\n qs = get_user_model().objects.distinct().filter(((Q(is_staff=True) & Q(pageuser__created_by=user)) & Q(pagepermission__page=None)))\\n qs = qs.exclude(pk=user.pk).exclude(groups__user__pk=user.pk)\\n return qs\\n if (user_level == ROOT_USER_LEVEL):\\n return get_user_model().objects.all()\\n page_id_allow_list = get_change_permissions_id_list(user, site, check_global=False)\\n qs = get_user_model().objects.distinct().filter(((Q(is_staff=True) & (Q(pagepermission__page__id__in=page_id_allow_list) & Q(pagepermission__page__depth__gte=user_level))) | (Q(pageuser__created_by=user) & Q(pagepermission__page=None))))\\n qs = qs.exclude(pk=user.pk).exclude(groups__user__pk=user.pk)\\n return qs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from multiprocessing.sharedctypes import Array\\n return Array(typecode_or_type, size_or_initializer, **kwds)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def Array(typecode_or_type, size_or_initializer, **kwds):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@register.inclusion_tag('zinnia\\/tags\\/dummy.html', takes_context=True)\\ndef get_categories(context, template='zinnia\\/tags\\/categories.html'):\",\"targets\":\"\\\"\\\"\\\"Return the published categories.\\n \\\"\\\"\\\"\\n return {'template': template, 'categories': Category.published.all().annotate(count_entries_published=Count('entries')), 'context_category': context.get('category')}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef deprecated(message=None):\\n\\n ''''A decorator for deprecated functions'\\n '''\",\"targets\":\"def _decorator(func, message=message):\\n if (message is None):\\n message = ('%s is deprecated' % func.__name__)\\n def newfunc(*args, **kwds):\\n warnings.warn(message, DeprecationWarning, stacklevel=2)\\n return func(*args, **kwds)\\n return newfunc\\n return _decorator\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n parts = [directory]\\n for filename in pathnames:\\n if (filename != ''):\\n filename = posixpath.normpath(filename)\\n if (any(((sep in filename) for sep in _os_alt_seps)) or os.path.isabs(filename) or (filename == '..') or filename.startswith('..\\/')):\\n raise NotFound()\\n parts.append(filename)\\n return posixpath.join(*parts)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def safe_join(directory, *pathnames):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (module_names is None):\\n module_names = elementtree_modules\\n for mod_name in module_names:\\n try:\\n ElementTree = __import__(mod_name, None, None, ['unused'])\\n except ImportError:\\n pass\\n else:\\n try:\\n ElementTree.XML('')\\n except (SystemExit, MemoryError, AssertionError):\\n raise\\n except:\\n why = sys.exc_info()[1]\\n log(('Not using ElementTree library %r because it failed to parse a trivial document: %s' % (mod_name, why)))\\n else:\\n return ElementTree\\n else:\\n raise ImportError(('No ElementTree library found. You may need to install one. Tried importing %r' % (module_names,)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def importElementTree(module_names=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (expired, invalid, user) = login_token_status(token)\\n if invalid:\\n do_flash(*get_message('INVALID_LOGIN_TOKEN'))\\n if expired:\\n send_login_instructions(user)\\n do_flash(*get_message('LOGIN_EXPIRED', email=user.email, within=_security.login_within))\\n if (invalid or expired):\\n return redirect(url_for('login'))\\n login_user(user)\\n after_this_request(_commit)\\n do_flash(*get_message('PASSWORDLESS_LOGIN_SUCCESSFUL'))\\n return redirect(get_post_login_redirect())\\n\\n\\nWhat's a good function header?\",\"targets\":\"@anonymous_user_required\\ndef token_login(token):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def gen3():\",\"targets\":\"\\\"\\\"\\\"Non-restartable source sequence\\n \\\"\\\"\\\"\\n for i in (0, 1, 2):\\n (yield i)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n buff = raw\\n if (not raw):\\n buff = method2dot(mx)\\n method2format(output, 'jpg', mx, buff)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def method2jpg(output, mx, raw=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef currentThread():\\n\\n ''''Return the current Thread object, corresponding to the caller\\\\'s thread of control.\\n If the caller\\\\'s thread of control was not created through the threading\\n module, a dummy thread object with limited functionality is returned.'\\n '''\",\"targets\":\"try:\\n return _active[_get_ident()]\\n except KeyError:\\n return _DummyThread()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not dork):\\n return None\\n headers = {}\\n headers[HTTP_HEADER.USER_AGENT] = dict(conf.httpHeaders).get(HTTP_HEADER.USER_AGENT, DUMMY_SEARCH_USER_AGENT)\\n headers[HTTP_HEADER.ACCEPT_ENCODING] = HTTP_ACCEPT_ENCODING_HEADER_VALUE\\n try:\\n req = urllib2.Request('https:\\/\\/www.google.com\\/ncr', headers=headers)\\n conn = urllib2.urlopen(req)\\n except Exception as ex:\\n errMsg = (\\\"unable to connect to Google ('%s')\\\" % getSafeExString(ex))\\n raise SqlmapConnectionException(errMsg)\\n gpage = (conf.googlePage if (conf.googlePage > 1) else 1)\\n logger.info(('using search result page #%d' % gpage))\\n url = 'https:\\/\\/www.google.com\\/search?'\\n url += ('q=%s&' % urlencode(dork, convall=True))\\n url += 'num=100&hl=en&complete=0&safe=off&filter=0&btnG=Search'\\n url += ('&start=%d' % ((gpage - 1) * 100))\\n try:\\n req = urllib2.Request(url, headers=headers)\\n conn = urllib2.urlopen(req)\\n requestMsg = ('HTTP request:\\\\nGET %s' % url)\\n requestMsg += (' %s' % httplib.HTTPConnection._http_vsn_str)\\n logger.log(CUSTOM_LOGGING.TRAFFIC_OUT, requestMsg)\\n page = conn.read()\\n code = conn.code\\n status = conn.msg\\n responseHeaders = conn.info()\\n page = decodePage(page, responseHeaders.get('Content-Encoding'), responseHeaders.get('Content-Type'))\\n responseMsg = ('HTTP response (%s - %d):\\\\n' % (status, code))\\n if (conf.verbose <= 4):\\n responseMsg += getUnicode(responseHeaders, UNICODE_ENCODING)\\n elif (conf.verbose > 4):\\n responseMsg += ('%s\\\\n%s\\\\n' % (responseHeaders, page))\\n logger.log(CUSTOM_LOGGING.TRAFFIC_IN, responseMsg)\\n except urllib2.HTTPError as e:\\n try:\\n page = e.read()\\n except Exception as ex:\\n warnMsg = 'problem occurred while trying to get '\\n warnMsg += ('an error page information (%s)' % getSafeExString(ex))\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def _search(dork):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_gif(api_key, gif_id):\",\"targets\":\"\\\"\\\"\\\"Returns dict with gif informations from the API.\\n \\\"\\\"\\\"\\n url = 'http:\\/\\/api.giphy.com\\/v1\\/gifs\\/{}?api_key={}'.format(gif_id, api_key)\\n r = urlopen(url)\\n return json.loads(r.read().decode('utf-8'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n parsed = urlparse(uri)\\n if (parsed.path in schema_paths):\\n schema = schema_paths[parsed.path]\\n if callable(schema):\\n return schema(**dict(parse_qsl(parsed.query)))\\n return schema\\n raise jsonschema.RefResolutionError((u'%s could not be resolved' % uri))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def resolve_ref(uri):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef delimitedList(expr, delim=',', combine=False):\\n\\n ''''Helper to define a delimited list of expressions - the delimiter defaults to \\\\',\\\\'.\\n By default, the list elements and delimiters can have intervening whitespace, and\\n comments, but this can be overridden by passing \\\\'combine=True\\\\' in the constructor.\\n If combine is set to True, the matching tokens are returned as a single token\\n string, with the delimiters included; otherwise, the matching tokens are returned\\n as a list of tokens, with the delimiters suppressed.'\\n '''\",\"targets\":\"dlName = (((((_ustr(expr) + ' [') + _ustr(delim)) + ' ') + _ustr(expr)) + ']...')\\n if combine:\\n return Combine((expr + ZeroOrMore((delim + expr)))).setName(dlName)\\n else:\\n return (expr + ZeroOrMore((Suppress(delim) + expr))).setName(dlName)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global XCODE_VERSION_CACHE\\n if XCODE_VERSION_CACHE:\\n return XCODE_VERSION_CACHE\\n try:\\n version_list = GetStdout(['xcodebuild', '-version']).splitlines()\\n if (len(version_list) < 2):\\n raise GypError('xcodebuild returned unexpected results')\\n except:\\n version = CLTVersion()\\n if version:\\n version = re.match('(\\\\\\\\d\\\\\\\\.\\\\\\\\d\\\\\\\\.?\\\\\\\\d*)', version).groups()[0]\\n else:\\n raise GypError('No Xcode or CLT version detected!')\\n version_list = [version, '']\\n version = version_list[0]\\n build = version_list[(-1)]\\n version = version.split()[(-1)].replace('.', '')\\n version = (version + ('0' * (3 - len(version)))).zfill(4)\\n if build:\\n build = build.split()[(-1)]\\n XCODE_VERSION_CACHE = (version, build)\\n return XCODE_VERSION_CACHE\\n\\n\\nWhat's a good function header?\",\"targets\":\"def XcodeVersion():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _create_transformations(all_tokens, seen_ts):\\n\\n ''''Create the objects that need to know about tabstops.'\\n '''\",\"targets\":\"for (parent, token) in all_tokens:\\n if isinstance(token, TransformationToken):\\n if (token.number not in seen_ts):\\n raise RuntimeError(('Tabstop %i is not known but is used by a Transformation' % token.number))\\n Transformation(parent, seen_ts[token.number], token)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@decorators.memoize\\ndef _check_imgadm():\\n\\n ''''Looks to see if imgadm is present on the system'\\n '''\",\"targets\":\"return salt.utils.path.which('imgadm')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n net_connect.disconnect()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_disconnect(net_connect, commands, expected_responses):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@testing.requires_testing_data\\n@requires_mayavi\\ndef test_coreg_model():\\n\\n ''''Test CoregModel.'\\n '''\",\"targets\":\"from mne.gui._coreg_gui import CoregModel\\n tempdir = _TempDir()\\n trans_dst = op.join(tempdir, 'test-trans.fif')\\n model = CoregModel()\\n assert_raises(RuntimeError, model.save_trans, 'blah.fif')\\n model.mri.use_high_res_head = False\\n model.mri.subjects_dir = subjects_dir\\n model.mri.subject = 'sample'\\n assert_false(model.mri.fid_ok)\\n model.mri.lpa = [[(-0.06), 0, 0]]\\n model.mri.nasion = [[0, 0.05, 0]]\\n model.mri.rpa = [[0.08, 0, 0]]\\n assert_true(model.mri.fid_ok)\\n model.hsp.file = raw_path\\n assert_allclose(model.hsp.lpa, [[(-0.07137), 0, 5.122e-09]], 0.0001)\\n assert_allclose(model.hsp.rpa, [[(+ 0.07527), 0, 5.588e-09]], 0.0001)\\n assert_allclose(model.hsp.nasion, [[(+ 3.725e-09), 0.1026, 4.191e-09]], 0.0001)\\n assert_true(model.has_fid_data)\\n lpa_distance = model.lpa_distance\\n nasion_distance = model.nasion_distance\\n rpa_distance = model.rpa_distance\\n avg_point_distance = np.mean(model.point_distance)\\n model.fit_auricular_points()\\n old_x = ((lpa_distance ** 2) + (rpa_distance ** 2))\\n new_x = ((model.lpa_distance ** 2) + (model.rpa_distance ** 2))\\n assert_true((new_x < old_x))\\n model.fit_fiducials()\\n old_x = (((lpa_distance ** 2) + (rpa_distance ** 2)) + (nasion_distance ** 2))\\n new_x = (((model.lpa_distance ** 2) + (model.rpa_distance ** 2)) + (model.nasion_distance ** 2))\\n assert_true((new_x < old_x))\\n model.fit_hsp_points()\\n assert_true((np.mean(model.point_distance) < avg_point_distance))\\n model.save_trans(trans_dst)\\n trans = mne.read_trans(trans_dst)\\n assert_allclose(trans['trans'], model.head_mri_trans)\\n (x, y, z, rot_x, rot_y, rot_z) = (0.1, 0.2, 0.05, 1.5, 0.1, (-1.2))\\n model.trans_x = x\\n model.trans_y = y\\n model.trans_z = z\\n model.rot_x = rot_x\\n model.rot_y = rot_y\\n model.rot_z = rot_z\\n trans = model.head_mri_trans\\n model.reset_traits(['trans_x', 'trans_y', 'trans_z', 'rot_x', 'rot_y', 'rot_z'])\\n assert_equal(model.trans_x, 0)\\n model.set_trans(trans)\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@task\\n@use_master\\ndef update_supported_locales_single(id, latest=False, **kw):\",\"targets\":\"\\\"\\\"\\\"Update supported_locales for an individual app. Set latest=True to use the\\n latest current version instead of the most recent public version.\\n \\\"\\\"\\\"\\n from mkt.webapps.models import Webapp\\n try:\\n app = Webapp.objects.get(pk=id)\\n except Webapp.DoesNotExist:\\n log.info((u'[Webapp:%s] Did not find webapp to update supported locales.' % id))\\n return\\n try:\\n if app.update_supported_locales(latest=latest):\\n log.info((u'[Webapp:%s] Updated supported locales.' % app.id))\\n except Exception:\\n log.info((u'[Webapp%s] Updating supported locales failed.' % app.id), exc_info=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n Services = get_sdk(ResourceType.DATA_STORAGE, 'models#Services')\\n if (set(string) - set('bqtf')):\\n raise ValueError\\n return Services(_str=''.join(set(string)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def services_type(string):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef CreateClassFromXMLString(target_class, xml_string, string_encoding=None):\\n\\n ''''Creates an instance of the target class from the string contents.\\n Args:\\n target_class: class The class which will be instantiated and populated\\n with the contents of the XML. This class must have a _tag and a\\n _namespace class variable.\\n xml_string: str A string which contains valid XML. The root element\\n of the XML string should match the tag and namespace of the desired\\n class.\\n string_encoding: str The character encoding which the xml_string should\\n be converted to before it is interpreted and translated into\\n objects. The default is None in which case the string encoding\\n is not changed.\\n Returns:\\n An instance of the target class with members assigned according to the\\n contents of the XML - or None if the root XML tag and namespace did not\\n match those of the target class.'\\n '''\",\"targets\":\"encoding = (string_encoding or XML_STRING_ENCODING)\\n if (encoding and isinstance(xml_string, unicode)):\\n xml_string = xml_string.encode(encoding)\\n tree = ElementTree.fromstring(xml_string)\\n return _CreateClassFromElementTree(target_class, tree)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_or_verify_database(url, engine_options={}):\",\"targets\":\"\\\"\\\"\\\"Check that the database is use-able, possibly creating it if empty (this is\\n the only time we automatically create tables, otherwise we force the\\n user to do it using the management script so they can create backups).\\n 1) Empty database --> initialize with latest version and return\\n 2) Database older than migration support --> fail and require manual update\\n 3) Database at state where migrate support introduced --> add version control information but make no changes (might still require manual update)\\n 4) Database versioned but out of date --> fail with informative message, user must run \\\"sh manage_db.sh upgrade\\\"\\n \\\"\\\"\\\"\\n engine = create_engine(url, **engine_options)\\n meta = MetaData(bind=engine)\\n try:\\n Table('galaxy_user', meta, autoload=True)\\n except NoSuchTableError:\\n log.info('No database, initializing')\\n try:\\n db_schema = schema.ControlledSchema.create(engine, migrate_repository)\\n except:\\n db_schema = schema.ControlledSchema(engine, migrate_repository)\\n migrate_to_current_version(engine, db_schema)\\n return\\n try:\\n Table('migrate_version', meta, autoload=True)\\n except NoSuchTableError:\\n log.info('Adding version control to existing database')\\n try:\\n Table('metadata_file', meta, autoload=True)\\n schema.ControlledSchema.create(engine, migrate_repository, version=2)\\n except NoSuchTableError:\\n schema.ControlledSchema.create(engine, migrate_repository, version=1)\\n db_schema = schema.ControlledSchema(engine, migrate_repository)\\n if (migrate_repository.versions.latest != db_schema.version):\\n exception_msg = (\\\"Your database has version '%d' but this code expects version '%d'. \\\" % (db_schema.version, migrate_repository.versions.latest))\\n exception_msg += 'Back up your database and then migrate the schema by running the following from your Galaxy installation directory:'\\n exception_msg += '\\\\n\\\\nsh manage_db.sh upgrade tool_shed\\\\n'\\n raise Exception(exception_msg)\\n else:\\n log.info(('At database version %d' % db_schema.version))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef gettext_noop(message):\\n\\n ''''Marks strings for translation but doesn\\\\'t translate them now. This can be\\n used to store strings in global variables that should stay in the base\\n language (because they might be used externally) and will be translated\\n later.'\\n '''\",\"targets\":\"return message\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ProtosToIndexDefinitions(protos):\",\"targets\":\"\\\"\\\"\\\"Transform multiple index protocol buffers to index definitions.\\n Args:\\n A list of entity_pb.Index records.\\n \\\"\\\"\\\"\\n return [ProtoToIndexDefinition(definition) for definition in protos]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef identify_names(code):\\n\\n ''''Builds a codeobj summary by identifying and resovles used names\\n >>> code = \\\\'\\\\'\\\\'\\n ... from a.b import c\\n ... import d as e\\n ... print(c)\\n ... e.HelloWorld().f.g\\n >>> for name, o in sorted(identify_names(code).items()):\\n ... print(name, o[\\\\'name\\\\'], o[\\\\'module\\\\'], o[\\\\'module_short\\\\'])\\n c c a.b a.b\\n e.HelloWorld HelloWorld d d'\\n '''\",\"targets\":\"finder = NameFinder()\\n finder.visit(ast.parse(code))\\n example_code_obj = {}\\n for (name, full_name) in finder.get_mapping():\\n (module, attribute) = full_name.rsplit('.', 1)\\n module_short = get_short_module_name(module, attribute)\\n cobj = {'name': attribute, 'module': module, 'module_short': module_short}\\n example_code_obj[name] = cobj\\n return example_code_obj\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n html = markdown(value, extensions=[u'mdx_gfm'])\\n return mark_safe(html)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@register.filter(is_safe=True)\\ndef gfm(value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_certificate_footer_context():\",\"targets\":\"\\\"\\\"\\\"Return data to be used in Certificate Footer,\\n data returned should be customized according to the site configuration.\\n \\\"\\\"\\\"\\n data = dict()\\n terms_of_service_and_honor_code = branding_api.get_tos_and_honor_code_url()\\n if (terms_of_service_and_honor_code != branding_api.EMPTY_URL):\\n data.update({'company_tos_url': terms_of_service_and_honor_code})\\n privacy_policy = branding_api.get_privacy_url()\\n if (privacy_policy != branding_api.EMPTY_URL):\\n data.update({'company_privacy_url': privacy_policy})\\n about = branding_api.get_about_url()\\n if (about != branding_api.EMPTY_URL):\\n data.update({'company_about_url': about})\\n return data\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ReadVFS(pathspec, offset, length, progress_callback=None):\",\"targets\":\"\\\"\\\"\\\"Read from the VFS and return the contents.\\n Args:\\n pathspec: path to read from\\n offset: number of bytes to skip\\n length: number of bytes to read\\n progress_callback: A callback to indicate that the open call is still\\n working but needs more time.\\n Returns:\\n VFS file contents\\n \\\"\\\"\\\"\\n fd = VFSOpen(pathspec, progress_callback=progress_callback)\\n fd.Seek(offset)\\n return fd.Read(length)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _root_hybr(func, x0, args=(), jac=None, col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, eps=None, factor=100, diag=None, **unknown_options):\\n\\n ''''Find the roots of a multivariate function using MINPACK\\\\'s hybrd and\\n hybrj routines (modified Powell method).\\n Options\\n col_deriv : bool\\n Specify whether the Jacobian function computes derivatives down\\n the columns (faster, because there is no transpose operation).\\n xtol : float\\n The calculation will terminate if the relative error between two\\n consecutive iterates is at most `xtol`.\\n maxfev : int\\n The maximum number of calls to the function. If zero, then\\n ``100*(N+1)`` is the maximum where N is the number of elements\\n in `x0`.\\n band : tuple\\n If set to a two-sequence containing the number of sub- and\\n super-diagonals within the band of the Jacobi matrix, the\\n Jacobi matrix is considered banded (only for ``fprime=None``).\\n eps : float\\n A suitable step length for the forward-difference\\n approximation of the Jacobian (for ``fprime=None``). If\\n `eps` is less than the machine precision, it is assumed\\n that the relative errors in the functions are of the order of\\n the machine precision.\\n factor : float\\n A parameter determining the initial step bound\\n (``factor * || diag * x||``). Should be in the interval\\n ``(0.1, 100)``.\\n diag : sequence\\n N positive entries that serve as a scale factors for the\\n variables.'\\n '''\",\"targets\":\"_check_unknown_options(unknown_options)\\n epsfcn = eps\\n x0 = asarray(x0).flatten()\\n n = len(x0)\\n if (not isinstance(args, tuple)):\\n args = (args,)\\n (shape, dtype) = _check_func('fsolve', 'func', func, x0, args, n, (n,))\\n if (epsfcn is None):\\n epsfcn = finfo(dtype).eps\\n Dfun = jac\\n if (Dfun is None):\\n if (band is None):\\n (ml, mu) = ((-10), (-10))\\n else:\\n (ml, mu) = band[:2]\\n if (maxfev == 0):\\n maxfev = (200 * (n + 1))\\n retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev, ml, mu, epsfcn, factor, diag)\\n else:\\n _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n))\\n if (maxfev == 0):\\n maxfev = (100 * (n + 1))\\n retval = _minpack._hybrj(func, Dfun, x0, args, 1, col_deriv, xtol, maxfev, factor, diag)\\n (x, status) = (retval[0], retval[(-1)])\\n errors = {0: 'Improper input parameters were entered.', 1: 'The solution converged.', 2: ('The number of calls to function has reached maxfev = %d.' % maxfev), 3: ('xtol=%f is too small, no further improvement in the approximate\\\\n solution is possible.' % xtol), 4: 'The iteration is not making good progress, as measured by the \\\\n improvement from the last five Jacobian evaluations.', 5: 'The iteration is not making good progress, as measured by the \\\\n improvement from the last ten iterations.', 'unknown': 'An error occurred.'}\\n info = retval[1]\\n info['fun'] = info.pop('fvec')\\n sol = OptimizeResult(x=x, success=(status == 1), status=status)\\n sol.update(info)\\n try:\\n sol['message'] = errors[status]\\n except KeyError:\\n info['message'] = errors['unknown']\\n return sol\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef host_memory_extents(obj):\\n\\n ''''Returns (start, end) the start and end pointer of the array (half open).'\\n '''\",\"targets\":\"return mviewbuf.memoryview_get_extents(obj)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n _set_ndarray_class(ndarray_class)\\n plist = ctypes.POINTER(ctypes.c_char_p)()\\n size = ctypes.c_uint()\\n check_call(_LIB.MXListAllOpNames(ctypes.byref(size), ctypes.byref(plist)))\\n op_names = []\\n for i in range(size.value):\\n op_names.append(py_str(plist[i]))\\n module_obj = _sys.modules[('%s.ndarray' % root_namespace)]\\n module_internal = _sys.modules[('%s._ndarray_internal' % root_namespace)]\\n module_contrib = _sys.modules[('%s.contrib.ndarray' % root_namespace)]\\n for name in op_names:\\n hdl = OpHandle()\\n check_call(_LIB.NNGetOpHandle(c_str(name), ctypes.byref(hdl)))\\n function = _make_ndarray_function(hdl, name)\\n if function.__name__.startswith('_contrib_'):\\n function.__name__ = function.__name__[9:]\\n function.__module__ = 'mxnet.contrib.ndarray'\\n setattr(module_contrib, function.__name__, function)\\n elif function.__name__.startswith('_'):\\n setattr(module_internal, function.__name__, function)\\n else:\\n setattr(module_obj, function.__name__, function)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _init_ndarray_module(ndarray_class, root_namespace):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def enumerate():\",\"targets\":\"\\\"\\\"\\\"Return a list of all Thread objects currently alive.\\n The list includes daemonic threads, dummy thread objects created by\\n current_thread(), and the main thread. It excludes terminated threads and\\n threads that have not yet been started.\\n \\\"\\\"\\\"\\n with _active_limbo_lock:\\n return (_active.values() + _limbo.values())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if re.match(VALID_APP_NAME_CHARS_REGEX, app_name):\\n return True\\n else:\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def is_app_name_valid(app_name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@ensure_csrf_cookie\\n@cache_control(no_cache=True, no_store=True, must_revalidate=True)\\n@coach_dashboard\\ndef set_grading_policy(request, course, ccx=None):\",\"targets\":\"\\\"\\\"\\\"Set grading policy for the CCX.\\n \\\"\\\"\\\"\\n if (not ccx):\\n raise Http404\\n override_field_for_ccx(ccx, course, 'grading_policy', json.loads(request.POST['policy']))\\n responses = SignalHandler.course_published.send(sender=ccx, course_key=CCXLocator.from_course_locator(course.id, unicode(ccx.id)))\\n for (rec, response) in responses:\\n log.info('Signal fired when course is published. Receiver: %s. Response: %s', rec, response)\\n url = reverse('ccx_coach_dashboard', kwargs={'course_id': CCXLocator.from_course_locator(course.id, unicode(ccx.id))})\\n return redirect(url)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def fullmodname(path):\",\"targets\":\"\\\"\\\"\\\"Return a plausible module name for the path.\\n \\\"\\\"\\\"\\n comparepath = os.path.normcase(path)\\n longest = ''\\n for dir in sys.path:\\n dir = os.path.normcase(dir)\\n if (comparepath.startswith(dir) and (comparepath[len(dir)] == os.sep)):\\n if (len(dir) > len(longest)):\\n longest = dir\\n if longest:\\n base = path[(len(longest) + 1):]\\n else:\\n base = path\\n (drive, base) = os.path.splitdrive(base)\\n base = base.replace(os.sep, '.')\\n if os.altsep:\\n base = base.replace(os.altsep, '.')\\n (filename, ext) = os.path.splitext(base)\\n return filename.lstrip('.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def decode_fvwi(byts, flag_size=4):\",\"targets\":\"\\\"\\\"\\\"Decode encoded fvwi. Returns number, flags, consumed\\n \\\"\\\"\\\"\\n (arg, consumed) = decint(bytes(byts))\\n val = (arg >> flag_size)\\n flags = 0\\n for i in xrange(flag_size):\\n flags |= (arg & (1 << i))\\n return (val, flags, consumed)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def compile(pattern, flags=0):\",\"targets\":\"\\\"\\\"\\\"Compile a regular expression pattern, returning a pattern object.\\n \\\"\\\"\\\"\\n return _compile(pattern, flags)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef getparser(use_datetime=False, use_builtin_types=False):\\n\\n ''''getparser() -> parser, unmarshaller\\n Create an instance of the fastest available parser, and attach it\\n to an unmarshalling object. Return both objects.'\\n '''\",\"targets\":\"if (FastParser and FastUnmarshaller):\\n if use_builtin_types:\\n mkdatetime = _datetime_type\\n mkbytes = base64.decodebytes\\n elif use_datetime:\\n mkdatetime = _datetime_type\\n mkbytes = _binary\\n else:\\n mkdatetime = _datetime\\n mkbytes = _binary\\n target = FastUnmarshaller(True, False, mkbytes, mkdatetime, Fault)\\n parser = FastParser(target)\\n else:\\n target = Unmarshaller(use_datetime=use_datetime, use_builtin_types=use_builtin_types)\\n if FastParser:\\n parser = FastParser(target)\\n else:\\n parser = ExpatParser(target)\\n return (parser, target)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n abbreviation = name[0:3].lower()\\n try:\\n return WEEKDAYS[abbreviation]\\n except KeyError:\\n raise KeyError(name)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def weekday(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for leaf in name_leafs:\\n leaf.remove()\\n children = [Leaf(token.NAME, 'from'), Leaf(token.NAME, package_name, prefix=' '), Leaf(token.NAME, 'import', prefix=' '), Node(syms.import_as_names, name_leafs)]\\n imp = Node(syms.import_from, children)\\n return imp\\n\\n\\nWhat's a good function header?\",\"targets\":\"def FromImport(package_name, name_leafs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.filter(is_safe=True)\\ndef markdown(value, arg=''):\\n\\n ''''Runs Markdown over a given value, optionally using various\\n extensions python-markdown supports.\\n Syntax::\\n {{ value|markdown:\\\"extension1_name,extension2_name...\\\" }}\\n To enable safe mode, which strips raw HTML and only returns HTML\\n generated by actual Markdown syntax, pass \\\"safe\\\" as the first\\n extension in the list.\\n If the version of Markdown in use does not support extensions,\\n they will be silently ignored.'\\n '''\",\"targets\":\"import warnings\\n warnings.warn('The markdown filter has been deprecated', category=DeprecationWarning)\\n try:\\n import markdown\\n except ImportError:\\n if settings.DEBUG:\\n raise template.TemplateSyntaxError(\\\"Error in 'markdown' filter: The Python markdown library isn't installed.\\\")\\n return force_text(value)\\n else:\\n markdown_vers = getattr(markdown, 'version_info', 0)\\n if (markdown_vers < (2, 1)):\\n if settings.DEBUG:\\n raise template.TemplateSyntaxError(\\\"Error in 'markdown' filter: Django does not support versions of the Python markdown library < 2.1.\\\")\\n return force_text(value)\\n else:\\n extensions = [e for e in arg.split(',') if e]\\n if (extensions and (extensions[0] == 'safe')):\\n extensions = extensions[1:]\\n return mark_safe(markdown.markdown(force_text(value), extensions, safe_mode=True, enable_attributes=False))\\n else:\\n return mark_safe(markdown.markdown(force_text(value), extensions, safe_mode=False))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@nox.session\\ndef lint(session):\",\"targets\":\"\\\"\\\"\\\"Run linters.\\n Returns a failure if the linters find linting errors or sufficiently\\n serious code quality issues.\\n \\\"\\\"\\\"\\n session.interpreter = 'python3.6'\\n session.install('flake8', 'pylint', 'gcp-devrel-py-tools', *LOCAL_DEPS)\\n session.install('.')\\n session.run('flake8', os.path.join('google', 'cloud', 'bigquery'))\\n session.run('flake8', 'tests')\\n session.run('gcp-devrel-py-tools', 'run-pylint', '--config', 'pylint.config.py', '--library-filesets', 'google', '--test-filesets', 'tests', success_codes=range(0, 100))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n kwargs.setdefault('allow_redirects', False)\\n return request('head', url, **kwargs)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def head(url, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_comment_form(parser, token):\\n\\n ''''Get a (new) form object to post a new comment.\\n Syntax::\\n {% get_comment_form for [object] as [varname] %}\\n {% get_comment_form for [app].[model] [object_id] as [varname] %}'\\n '''\",\"targets\":\"return CommentFormNode.handle_token(parser, token)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (record, _) = UserCourseTag.objects.get_or_create(user=user, course_id=course_id, key=key)\\n record.value = value\\n record.save()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def set_course_tag(user, course_id, key, value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _blob_overlap(blob1, blob2):\",\"targets\":\"\\\"\\\"\\\"Finds the overlapping area fraction between two blobs.\\n Returns a float representing fraction of overlapped area.\\n Parameters\\n blob1 : sequence\\n A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob\\n and sigma is the standard deviation of the Gaussian kernel which\\n detected the blob.\\n blob2 : sequence\\n A sequence of ``(y,x,sigma)``, where ``x,y`` are coordinates of blob\\n and sigma is the standard deviation of the Gaussian kernel which\\n detected the blob.\\n Returns\\n f : float\\n Fraction of overlapped area.\\n \\\"\\\"\\\"\\n root2 = sqrt(2)\\n r1 = (blob1[2] * root2)\\n r2 = (blob2[2] * root2)\\n d = hypot((blob1[0] - blob2[0]), (blob1[1] - blob2[1]))\\n if (d > (r1 + r2)):\\n return 0\\n if (d <= abs((r1 - r2))):\\n return 1\\n ratio1 = ((((d ** 2) + (r1 ** 2)) - (r2 ** 2)) \\/ ((2 * d) * r1))\\n ratio1 = np.clip(ratio1, (-1), 1)\\n acos1 = arccos(ratio1)\\n ratio2 = ((((d ** 2) + (r2 ** 2)) - (r1 ** 2)) \\/ ((2 * d) * r2))\\n ratio2 = np.clip(ratio2, (-1), 1)\\n acos2 = arccos(ratio2)\\n a = (((- d) + r2) + r1)\\n b = ((d - r2) + r1)\\n c = ((d + r2) - r1)\\n d = ((d + r2) + r1)\\n area = ((((r1 ** 2) * acos1) + ((r2 ** 2) * acos2)) - (0.5 * sqrt(abs((((a * b) * c) * d)))))\\n return (area \\/ (math.pi * (min(r1, r2) ** 2)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def libvlc_new(argc, argv):\",\"targets\":\"\\\"\\\"\\\"Create and initialize a libvlc instance.\\n This functions accept a list of \\\"command line\\\" arguments similar to the\\n main(). These arguments affect the LibVLC instance default configuration.\\n @note\\n LibVLC may create threads. Therefore, any thread-unsafe process\\n initialization must be performed before calling L{libvlc_new}(). In particular\\n and where applicable:\\n - setlocale() and textdomain(),\\n - setenv(), unsetenv() and putenv(),\\n - with the X11 display system, XInitThreads()\\n (see also L{libvlc_media_player_set_xwindow}()) and\\n - on Microsoft Windows, SetErrorMode().\\n - sigprocmask() shall never be invoked; pthread_sigmask() can be used.\\n On POSIX systems, the SIGCHLD signal must B{not} be ignored, i.e. the\\n signal handler must set to SIG_DFL or a function pointer, not SIG_IGN.\\n Also while LibVLC is active, the wait() function shall not be called, and\\n any call to waitpid() shall use a strictly positive value for the first\\n parameter (i.e. the PID). Failure to follow those rules may lead to a\\n deadlock or a busy loop.\\n Also on POSIX systems, it is recommended that the SIGPIPE signal be blocked,\\n even if it is not, in principles, necessary.\\n On Microsoft Windows Vista\\/2008, the process error mode\\n SEM_FAILCRITICALERRORS flag B{must} with the SetErrorMode() function\\n before using LibVLC. On later versions, it is optional and unnecessary.\\n @param argc: the number of arguments (should be 0).\\n @param argv: list of arguments (should be None).\\n @return: the libvlc instance or None in case of error.\\n @version Arguments are meant to be passed from the command line to LibVLC, just like VLC media player does. The list of valid arguments depends on the LibVLC version, the operating system and platform, and set of available LibVLC plugins. Invalid or unsupported arguments will cause the function to fail (i.e. return None). Also, some arguments may alter the behaviour or otherwise interfere with other LibVLC functions. @warning There is...\\\"\\\"\\\"\\n f = (_Cfunctions.get('libvlc_new', None) or _Cfunction('libvlc_new', ((1,), (1,)), class_result(Instance), ctypes.c_void_p, ctypes.c_int, ListPOINTER(ctypes.c_char_p)))\\n return f(argc, argv)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def cluster_node_present(name, node, extra_args=None):\",\"targets\":\"\\\"\\\"\\\"Add a node to the Pacemaker cluster via PCS\\n Should be run on one cluster node only\\n (there may be races)\\n Can only be run on a already setup\\/added node\\n name\\n Irrelevant, not used (recommended: pcs_setup__node_add_{{node}})\\n node\\n node that should be added\\n extra_args\\n list of extra args for the \\\\pcs cluster node add\\\\ command\\n Example:\\n .. code-block:: yaml\\n pcs_setup__node_add_node1.example.com:\\n pcs.cluster_node_present:\\n - node: node1.example.com\\n - extra_args:\\n - \\\\--start\\\\\\n - \\\\--enable\\\\\\n \\\"\\\"\\\"\\n ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\\n node_add_required = True\\n current_nodes = []\\n is_member_cmd = ['pcs', 'status', 'nodes', 'corosync']\\n is_member = __salt__['cmd.run_all'](is_member_cmd, output_loglevel='trace', python_shell=False)\\n log.trace(('Output of pcs status nodes corosync: ' + str(is_member)))\\n for line in is_member['stdout'].splitlines():\\n if (len(line.split(':')) in [2]):\\n key = line.split(':')[0].strip()\\n value = line.split(':')[1].strip()\\n if (key in ['Offline', 'Online']):\\n if (len(value.split()) > 0):\\n if (node in value.split()):\\n node_add_required = False\\n ret['comment'] += 'Node {0} is already member of the cluster\\\\n'.format(node)\\n else:\\n current_nodes += value.split()\\n if (not node_add_required):\\n return ret\\n if __opts__['test']:\\n ret['result'] = None\\n ret['comment'] += 'Node {0} is set to be added to the cluster\\\\n'.format(node)\\n return ret\\n if (not isinstance(extra_args, (list, tuple))):\\n extra_args = []\\n node_add = __salt__['pcs.cluster_node_add'](node=node, extra_args=extra_args)\\n log.trace(('Output of pcs.cluster_node_add: ' + str(node_add)))\\n node_add_dict = {}\\n for line in node_add['stdout'].splitlines():\\n log.trace(('line: ' + line))\\n log.trace(('line.split(:).len: ' + str(len(line.split(':')))))\\n if (len(line.split(':')) in [2]):\\n current_node = line.split(':')[0].strip()\\n current_node_add_state = line.split(':')[1].strip()\\n if (current_node in (current_nodes + [node])):\\n node_add_dict.update({current_node: current_node_add_state})\\n log.trace(('node_add_dict: ' + str(node_add_dict)))\\n for current_node in current_nodes:\\n if (current_node in...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n model = context['model']\\n user = context['user']\\n name_or_id = data_dict.get('id')\\n organization_id = data_dict.get('organization_id')\\n _check_access('package_owner_org_update', context, data_dict)\\n pkg = model.Package.get(name_or_id)\\n if (pkg is None):\\n raise NotFound(_('Package was not found.'))\\n if organization_id:\\n org = model.Group.get(organization_id)\\n if ((org is None) or (not org.is_organization)):\\n raise NotFound(_('Organization was not found.'))\\n pkg.owner_org = org.id\\n else:\\n org = None\\n pkg.owner_org = None\\n if context.get('add_revision', True):\\n rev = model.repo.new_revision()\\n rev.author = user\\n if ('message' in context):\\n rev.message = context['message']\\n else:\\n rev.message = (_(u'REST API: Update object %s') % pkg.get('name'))\\n members = model.Session.query(model.Member).filter((model.Member.table_id == pkg.id)).filter((model.Member.capacity == 'organization'))\\n need_update = True\\n for member_obj in members:\\n if (org and (member_obj.group_id == org.id)):\\n need_update = False\\n else:\\n member_obj.state = 'deleted'\\n member_obj.save()\\n if (org and need_update):\\n member_obj = model.Member(table_id=pkg.id, table_name='package', group=org, capacity='organization', group_id=org.id, state='active')\\n model.Session.add(member_obj)\\n if (not context.get('defer_commit')):\\n model.Session.commit()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def package_owner_org_update(context, data_dict):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n newtable = table.copy(copy_data=False)\\n hdr = Header([Card(keyword=key, value=val[0], comment=val[1]) for (key, val) in GLOBAL_TIME_INFO.items()])\\n newtable.meta['__coordinate_columns__'] = defaultdict(OrderedDict)\\n coord_meta = newtable.meta['__coordinate_columns__']\\n time_cols = table.columns.isinstance(Time)\\n location = None\\n for col in time_cols:\\n jd12 = np.array([col.jd1, col.jd2])\\n jd12 = np.rollaxis(jd12, 0, jd12.ndim)\\n newtable.replace_column(col.info.name, Column(jd12, unit='d'))\\n n = (table.colnames.index(col.info.name) + 1)\\n coord_meta[col.info.name]['coord_type'] = col.scale.upper()\\n coord_meta[col.info.name]['coord_unit'] = 'd'\\n if (col.location is None):\\n if (location is not None):\\n warnings.warn('Time Column \\\"{}\\\" has no specified location, but global Time Position is present, which will be the default for this column in FITS specification.'.format(col.info.name), AstropyUserWarning)\\n else:\\n coord_meta[col.info.name]['time_ref_pos'] = 'TOPOCENTER'\\n if (col.scale in BARYCENTRIC_SCALES):\\n warnings.warn('Earth Location \\\"TOPOCENTER\\\" for Time Column \\\"{}\\\" is incompatabile with scale \\\"{}\\\".'.format(col.info.name, col.scale.upper()), AstropyUserWarning)\\n if (col.location.size > 1):\\n raise ValueError('Vectorized Location of Time Column \\\"{}\\\" cannot be written, as it is not supported.'.format(col.info.name))\\n if (location is None):\\n location = col.location\\n hdr.extend([Card(keyword='OBSGEO-{}'.format(dim.upper()), value=getattr(location, dim).to_value(u.m)) for dim in ('x', 'y', 'z')])\\n elif (location != col.location):\\n raise ValueError('Multiple Time Columns with different geocentric observatory locations ({}, ...\\n\\nWhat's a good function header?\",\"targets\":\"def time_to_fits(table):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def decode_sentencepiece(text):\",\"targets\":\"\\\"\\\"\\\"Decodes text that uses https:\\/\\/github.com\\/google\\/sentencepiece encoding.\\n Assumes that pieces are separated by a space\\n \\\"\\\"\\\"\\n return u''.join(text.split(u' ')).replace(u'\\\\u2581', u' ').strip()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_language_from_path(path, supported=None):\\n\\n ''''Returns the language-code if there is a valid language-code\\n found in the `path`.'\\n '''\",\"targets\":\"if (supported is None):\\n from django.conf import settings\\n supported = dict(settings.LANGUAGES)\\n regex_match = language_code_prefix_re.match(path)\\n if regex_match:\\n lang_code = regex_match.group(1)\\n if ((lang_code in supported) and check_for_language(lang_code)):\\n return lang_code\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def ParseArguments(argv, die_fn=(lambda : PrintUsageExit(1))):\",\"targets\":\"\\\"\\\"\\\"Parses command-line arguments.\\n Prints out a help message if -h or --help is supplied.\\n Args:\\n argv: List of command-line arguments.\\n die_fn: Function to invoke to end the program.\\n Returns:\\n A dictionary containing the value of command-line options.\\n \\\"\\\"\\\"\\n (opts, unused_args) = getopt.getopt(argv[1:], 'h', FLAG_SPEC)\\n arg_dict = {}\\n arg_dict['url'] = REQUIRED_OPTION\\n arg_dict['filename'] = None\\n arg_dict['config_file'] = None\\n arg_dict['kind'] = None\\n arg_dict['batch_size'] = None\\n arg_dict['num_threads'] = DEFAULT_THREAD_COUNT\\n arg_dict['bandwidth_limit'] = DEFAULT_BANDWIDTH_LIMIT\\n arg_dict['rps_limit'] = DEFAULT_RPS_LIMIT\\n arg_dict['http_limit'] = DEFAULT_REQUEST_LIMIT\\n arg_dict['application'] = ''\\n arg_dict['auth_domain'] = 'gmail.com'\\n arg_dict['create_config'] = False\\n arg_dict['db_filename'] = None\\n arg_dict['debug'] = False\\n arg_dict['download'] = False\\n arg_dict['dry_run'] = False\\n arg_dict['dump'] = False\\n arg_dict['exporter_opts'] = None\\n arg_dict['has_header'] = False\\n arg_dict['loader_opts'] = None\\n arg_dict['log_file'] = None\\n arg_dict['map'] = False\\n arg_dict['mapper_opts'] = None\\n arg_dict['namespace'] = ''\\n arg_dict['restore'] = False\\n arg_dict['result_db_filename'] = None\\n arg_dict['throttle_class'] = None\\n def ExpandFilename(filename):\\n 'Expand shell variables and ~usernames in filename.'\\n return os.path.expandvars(os.path.expanduser(filename))\\n for (option, value) in opts:\\n if (option in ('-h', '--help')):\\n PrintUsageExit(0)\\n if (not option.startswith('--')):\\n continue\\n option = option[2:]\\n if (option in DEPRECATED_OPTIONS):\\n print >>sys.stderr, ('--%s is deprecated, please use --%s.' % (option, DEPRECATED_OPTIONS[option]))\\n option = DEPRECATED_OPTIONS[option]\\n if (option in BOOL_ARGS):\\n arg_dict[option] = True\\n elif (option in INT_ARGS):\\n arg_dict[option] = int(value)\\n elif (option in FILENAME_ARGS):\\n arg_dict[option] = ExpandFilename(value)\\n elif (option in STRING_ARGS):\\n arg_dict[option] = value\\n return ProcessArguments(arg_dict, die_fn=die_fn)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def gather(boxlist, indices, fields=None):\",\"targets\":\"\\\"\\\"\\\"Gather boxes from BoxList according to indices and return new BoxList.\\n By default, Gather returns boxes corresponding to the input index list, as\\n well as all additional fields stored in the boxlist (indexing into the\\n first dimension). However one can optionally only gather from a\\n subset of fields.\\n Args:\\n boxlist: BoxList holding N boxes\\n indices: a 1-d numpy array of type int_\\n fields: (optional) list of fields to also gather from. If None (default),\\n all fields are gathered from. Pass an empty fields list to only gather\\n the box coordinates.\\n Returns:\\n subboxlist: a BoxList corresponding to the subset of the input BoxList\\n specified by indices\\n Raises:\\n ValueError: if specified field is not contained in boxlist or if the\\n indices are not of type int_\\n \\\"\\\"\\\"\\n if indices.size:\\n if ((np.amax(indices) >= boxlist.num_boxes()) or (np.amin(indices) < 0)):\\n raise ValueError('indices are out of valid range.')\\n subboxlist = np_box_list.BoxList(boxlist.get()[indices, :])\\n if (fields is None):\\n fields = boxlist.get_extra_fields()\\n for field in fields:\\n extra_field_data = boxlist.get_field(field)\\n subboxlist.add_field(field, extra_field_data[indices, ...])\\n return subboxlist\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef find_max_occupancy_node(dir_list):\\n\\n ''''Find node with maximum occupancy.\\n :param dir_list: list of directories for each node.\\n :return: number number node in list_dir'\\n '''\",\"targets\":\"count = 0\\n number = 0\\n length = 0\\n for dirs in dir_list:\\n if (length < len(dirs)):\\n length = len(dirs)\\n number = count\\n count += 1\\n return number\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n portionDirection = portionDirections[portionDirectionIndex]\\n if (portionDirection.directionReversed == True):\\n loopLists.append([])\\n loops = loopLists[(-1)]\\n interpolationOffset = derivation.interpolationDictionary['offset']\\n offset = interpolationOffset.getVector3ByPortion(portionDirection)\\n if (endMultiplier != None):\\n if (portionDirectionIndex == 0):\\n setOffsetByMultiplier(interpolationOffset.path[1], interpolationOffset.path[0], endMultiplier, offset)\\n elif (portionDirectionIndex == (len(portionDirections) - 1)):\\n setOffsetByMultiplier(interpolationOffset.path[(-2)], interpolationOffset.path[(-1)], endMultiplier, offset)\\n scale = derivation.interpolationDictionary['scale'].getComplexByPortion(portionDirection)\\n twist = derivation.interpolationDictionary['twist'].getYByPortion(portionDirection)\\n projectiveSpace = euclidean.ProjectiveSpace()\\n if (derivation.tiltTop == None):\\n tilt = derivation.interpolationDictionary['tilt'].getComplexByPortion(portionDirection)\\n projectiveSpace = projectiveSpace.getByTilt(tilt)\\n else:\\n normals = getNormals(interpolationOffset, offset, portionDirection)\\n normalFirst = normals[0]\\n normalAverage = getNormalAverage(normals)\\n if (derivation.tiltFollow and (derivation.oldProjectiveSpace != None)):\\n projectiveSpace = derivation.oldProjectiveSpace.getNextSpace(normalAverage)\\n else:\\n projectiveSpace = projectiveSpace.getByBasisZTop(normalAverage, derivation.tiltTop)\\n derivation.oldProjectiveSpace = projectiveSpace\\n projectiveSpace.unbuckle(derivation.maximumUnbuckling, normalFirst)\\n projectiveSpace = projectiveSpace.getSpaceByXYScaleAngle(twist, scale)\\n loop = []\\n if ((abs(projectiveSpace.basisX) + abs(projectiveSpace.basisY)) < 0.0001):\\n vector3Index = Vector3Index(len(vertexes))\\n addOffsetAddToLists(loop, offset, vector3Index, vertexes)\\n loops.append(loop)\\n return\\n for point in...\\n\\nWhat's a good function header?\",\"targets\":\"def addLoop(derivation, endMultiplier, loopLists, path, portionDirectionIndex, portionDirections, vertexes):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n map = ('\\/boot\\/System.map-%s' % os.uname()[2])\\n if os.path.isfile(map):\\n return map\\n map = ('\\/lib\\/modules\\/%s\\/build\\/System.map' % os.uname()[2])\\n if os.path.isfile(map):\\n return map\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_systemmap():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n import binascii\\n try:\\n with open(input, 'rb') as fd:\\n return binascii.hexlify(fd.read())\\n except IOError:\\n raise TypeError\\n\\n\\nWhat's a good function header?\",\"targets\":\"def convert_filename(input):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (full_path, arch, osx_name, version, build) = profile\\n args = ['\\/usr\\/bin\\/hdiutil', 'convert', '-quiet', full_path, '-format', 'UDTO', '-o', os.path.join(temp_dir, 'test')]\\n run_cmd(args)\\n args = ['\\/usr\\/bin\\/hdiutil', 'attach', '-quiet', '-nobrowse', '-noverify', '-noautoopen', '-mountpoint', '\\/Volumes\\/KernelDebugKit', os.path.join(temp_dir, 'test.cdr')]\\n run_cmd(args)\\n dwarf_info = os.path.join(temp_dir, 'dwarf.txt')\\n if os.path.isfile('\\/Volumes\\/KernelDebugKit\\/kernel.dSYM'):\\n kernel = '\\/Volumes\\/KernelDebugKit\\/kernel.dSYM'\\n else:\\n kernel = '\\/Volumes\\/KernelDebugKit\\/mach_kernel.dSYM'\\n args = ['\\/usr\\/bin\\/dwarfdump', '-arch', arch, '-i', kernel]\\n run_cmd(args, output_file=dwarf_info)\\n convert_py = os.path.join(volatility_dir, 'tools\\/mac\\/convert.py')\\n new_dwarf = (dwarf_info + '.conv')\\n args = ['\\/usr\\/bin\\/python', convert_py, dwarf_info, new_dwarf]\\n run_cmd(args)\\n vtypes_file = (new_dwarf + '.vtypes')\\n args = ['\\/usr\\/bin\\/python', convert_py, new_dwarf]\\n run_cmd(args, output_file=vtypes_file)\\n symbol_file = (dwarf_info + '.symbol.dsymutil')\\n if os.path.isfile('\\/Volumes\\/KernelDebugKit\\/mach_kernel'):\\n kernel = '\\/Volumes\\/KernelDebugKit\\/mach_kernel'\\n else:\\n kernel = '\\/Volumes\\/KernelDebugKit\\/kernel'\\n args = ['\\/usr\\/bin\\/dsymutil', '-s', '-arch', arch, kernel]\\n run_cmd(args, output_file=symbol_file)\\n profile_name = ((osx_name + '_') + version)\\n if (arch == 'i386'):\\n profile_name += '_Intel'\\n else:\\n profile_name += '_AMD'\\n profile_name += '.zip'\\n zip_file = os.path.join(profile_dir, profile_name)\\n args = ['\\/usr\\/bin\\/zip', zip_file, symbol_file, vtypes_file]\\n run_cmd(args)\\n args = ['\\/usr\\/bin\\/hdiutil', 'detach', '\\/Volumes\\/KernelDebugKit']\\n run_cmd(args)\\n shutil.rmtree(temp_dir)\\n os.mkdir(temp_dir)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def generate_profile(temp_dir, volatility_dir, profile_dir, profile):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global _CLIENT_KWARGS, _CLIENT_HOST, _CLIENT_PORT, _METADATA_ENCRYPTION_KEY\\n try:\\n (host, port) = (CONF.registry_host, CONF.registry_port)\\n except cfg.ConfigFileValueError:\\n msg = _('Configuration option was not valid')\\n LOG.error(msg)\\n raise exception.BadRegistryConnectionConfiguration(msg)\\n except IndexError:\\n msg = _('Could not find required configuration option')\\n LOG.error(msg)\\n raise exception.BadRegistryConnectionConfiguration(msg)\\n _CLIENT_HOST = host\\n _CLIENT_PORT = port\\n _METADATA_ENCRYPTION_KEY = CONF.metadata_encryption_key\\n _CLIENT_KWARGS = {'use_ssl': (CONF.registry_client_protocol.lower() == 'https'), 'key_file': CONF.registry_client_key_file, 'cert_file': CONF.registry_client_cert_file, 'ca_file': CONF.registry_client_ca_file, 'insecure': CONF.registry_client_insecure, 'timeout': CONF.registry_client_timeout}\\n\\n\\nWhat's a good function header?\",\"targets\":\"def configure_registry_client():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (settings.USE_TZ and (value is not None) and timezone.is_aware(value)):\\n current_timezone = timezone.get_current_timezone()\\n return timezone.make_naive(value, current_timezone)\\n return value\\n\\n\\nWhat's a good function header?\",\"targets\":\"def to_current_timezone(value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef html_safe(klass):\\n\\n ''''A decorator that defines the __html__ method. This helps non-Django\\n templates to detect classes whose __str__ methods return SafeText.'\\n '''\",\"targets\":\"if ('__html__' in klass.__dict__):\\n raise ValueError((\\\"can't apply @html_safe to %s because it defines __html__().\\\" % klass.__name__))\\n if ('__str__' not in klass.__dict__):\\n raise ValueError((\\\"can't apply @html_safe to %s because it doesn't define __str__().\\\" % klass.__name__))\\n klass_str = klass.__str__\\n klass.__str__ = (lambda self: mark_safe(klass_str(self)))\\n klass.__html__ = (lambda self: str(self))\\n return klass\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for backend in get_backends():\\n try:\\n user = backend.authenticate(**credentials)\\n except TypeError:\\n continue\\n if (user is None):\\n continue\\n user.backend = ('%s.%s' % (backend.__module__, backend.__class__.__name__))\\n return user\\n\\n\\nWhat's a good function header?\",\"targets\":\"def authenticate(**credentials):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for child in walk(node):\\n if ('lineno' in child._attributes):\\n child.lineno = (getattr(child, 'lineno', 0) + n)\\n return node\\n\\n\\nWhat's a good function header?\",\"targets\":\"def increment_lineno(node, n=1):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n lnum = parenlev = continued = 0\\n (namechars, numchars) = ((string.ascii_letters + '_'), '0123456789')\\n (contstr, needcont) = ('', 0)\\n contline = None\\n indents = [0]\\n stashed = None\\n async_def = False\\n async_def_indent = 0\\n async_def_nl = False\\n while 1:\\n try:\\n line = readline()\\n except StopIteration:\\n line = ''\\n lnum = (lnum + 1)\\n (pos, max) = (0, len(line))\\n if contstr:\\n if (not line):\\n raise TokenError('EOF in multi-line string', strstart)\\n endmatch = endprog.match(line)\\n if endmatch:\\n pos = end = endmatch.end(0)\\n (yield (STRING, (contstr + line[:end]), strstart, (lnum, end), (contline + line)))\\n (contstr, needcont) = ('', 0)\\n contline = None\\n elif (needcont and (line[(-2):] != '\\\\\\\\\\\\n') and (line[(-3):] != '\\\\\\\\\\\\r\\\\n')):\\n (yield (ERRORTOKEN, (contstr + line), strstart, (lnum, len(line)), contline))\\n contstr = ''\\n contline = None\\n continue\\n else:\\n contstr = (contstr + line)\\n contline = (contline + line)\\n continue\\n elif ((parenlev == 0) and (not continued)):\\n if (not line):\\n break\\n column = 0\\n while (pos < max):\\n if (line[pos] == ' '):\\n column = (column + 1)\\n elif (line[pos] == ' DCTB '):\\n column = (((column \\/\\/ tabsize) + 1) * tabsize)\\n elif (line[pos] == '\\\\x0c'):\\n column = 0\\n else:\\n break\\n pos = (pos + 1)\\n if (pos == max):\\n break\\n if stashed:\\n (yield stashed)\\n stashed = None\\n if (line[pos] in '#\\\\r\\\\n'):\\n if (line[pos] == '#'):\\n comment_token = line[pos:].rstrip('\\\\r\\\\n')\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def generate_tokens(readline):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef find_igw(vpc_conn, vpc_id):\\n\\n ''''Finds the Internet gateway for the given VPC ID.\\n Raises an AnsibleIgwSearchException if either no IGW can be found, or more\\n than one found for the given VPC.\\n Note that this function is duplicated in other ec2 modules, and should\\n potentially be moved into potentially be moved into a shared module_utils'\\n '''\",\"targets\":\"igw = vpc_conn.get_all_internet_gateways(filters={'attachment.vpc-id': vpc_id})\\n if (not igw):\\n raise AnsibleIgwSearchException('No IGW found for VPC {0}'.format(vpc_id))\\n elif (len(igw) == 1):\\n return igw[0].id\\n else:\\n raise AnsibleIgwSearchException('Multiple IGWs found for VPC {0}'.format(vpc_id))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if isinstance(number, float):\\n if (number > 1):\\n number = round(number, 0)\\n else:\\n number = round(math.ceil(number), 0)\\n return int(number)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def toint(number):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef assert_almost_equal_ignore_nan(a, b, rtol=None, atol=None, names=('a', 'b')):\\n\\n ''''Test that two NumPy arrays are almost equal (ignoring NaN in either array).\\n Combines a relative and absolute measure of approximate eqality.\\n If either the relative or absolute check passes, the arrays are considered equal.\\n Including an absolute check resolves issues with the relative check where all\\n array values are close to zero.\\n Parameters\\n a : np.ndarray\\n b : np.ndarray\\n rtol : None or float\\n The relative threshold. Default threshold will be used if set to ``None``.\\n atol : None or float\\n The absolute threshold. Default threshold will be used if set to ``None``.'\\n '''\",\"targets\":\"a = np.copy(a)\\n b = np.copy(b)\\n nan_mask = np.logical_or(np.isnan(a), np.isnan(b))\\n a[nan_mask] = 0\\n b[nan_mask] = 0\\n assert_almost_equal(a, b, rtol, atol, names)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n export_emails = Command()\\n export_emails.run_from_argv([u'manage.py', u'export_emails', u'--format=vcard'])\\n (out, err) = capsys.readouterr()\\n assert (u'N:Bulgak\\\\xf3v;Mija\\\\xedl;;;' in out)\\n assert out.startswith(u'BEGIN:VCARD')\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.mark.skipif(u'sys.version_info < (3, 0)', reason=u'issues with vobject library on PY2x')\\n@pytest.mark.django_db()\\ndef test_do_export_emails_format_vcard_start(capsys):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _additional_sanity_checks(module, zone):\\n\\n ''''Run input sanity checks that depend on info from the zone\\/record.'\\n '''\",\"targets\":\"overwrite = module.params['overwrite']\\n record_name = module.params['record']\\n record_type = module.params['type']\\n state = module.params['state']\\n if ((record_type == 'CNAME') and (record_name == zone.domain)):\\n module.fail_json(msg='CNAME records cannot match the zone name', changed=False)\\n if ((record_type == 'NS') and (record_name == zone.domain) and (state == 'absent')):\\n module.fail_json(msg='cannot delete root NS records', changed=False)\\n if ((record_type == 'NS') and (record_name == zone.domain) and overwrite):\\n module.fail_json(msg='cannot update existing root NS records', changed=False)\\n if ((record_type == 'SOA') and (record_name != zone.domain)):\\n module.fail_json(msg=('non-root SOA records are not permitted, got: %s' % record_name), changed=False)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (host, port) = address\\n err = None\\n for res in getaddrinfo(host, port, 0, SOCK_STREAM):\\n (af, socktype, proto, canonname, sa) = res\\n sock = None\\n try:\\n sock = socket(af, socktype, proto)\\n if (timeout is not _GLOBAL_DEFAULT_TIMEOUT):\\n sock.settimeout(timeout)\\n if source_address:\\n sock.bind(source_address)\\n sock.connect(sa)\\n return sock\\n except error as _:\\n err = _\\n if (sock is not None):\\n sock.close()\\n if (err is not None):\\n raise err\\n else:\\n raise error('getaddrinfo returns an empty list')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef byte_compile(py_files, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None):\\n\\n ''''Byte-compile a collection of Python source files to .pyc\\n files in a __pycache__ subdirectory. \\\\'py_files\\\\' is a list\\n of files to compile; any files that don\\\\'t end in \\\".py\\\" are silently\\n skipped. \\\\'optimize\\\\' must be one of the following:\\n 0 - don\\\\'t optimize\\n 1 - normal optimization (like \\\"python -O\\\")\\n 2 - extra optimization (like \\\"python -OO\\\")\\n If \\\\'force\\\\' is true, all files are recompiled regardless of\\n timestamps.\\n The source filename encoded in each bytecode file defaults to the\\n filenames listed in \\\\'py_files\\\\'; you can modify these with \\\\'prefix\\\\' and\\n \\\\'basedir\\\\'. \\\\'prefix\\\\' is a string that will be stripped off of each\\n source filename, and \\\\'base_dir\\\\' is a directory name that will be\\n prepended (after \\\\'prefix\\\\' is stripped). You can supply either or both\\n (or neither) of \\\\'prefix\\\\' and \\\\'base_dir\\\\', as you wish.\\n If \\\\'dry_run\\\\' is true, doesn\\\\'t actually do anything that would\\n affect the filesystem.\\n Byte-compilation is either done directly in this interpreter process\\n with the standard py_compile module, or indirectly by writing a\\n temporary script and executing it. Normally, you should let\\n \\\\'byte_compile()\\\\' figure out to use direct compilation or not (see\\n the source for details). The \\\\'direct\\\\' flag is used by the script\\n generated in indirect mode; unless you know what you\\\\'re doing, leave\\n it set to None.'\\n '''\",\"targets\":\"import subprocess\\n if sys.dont_write_bytecode:\\n raise DistutilsByteCompileError('byte-compiling is disabled.')\\n if (direct is None):\\n direct = (__debug__ and (optimize == 0))\\n if (not direct):\\n try:\\n from tempfile import mkstemp\\n (script_fd, script_name) = mkstemp('.py')\\n except ImportError:\\n from tempfile import mktemp\\n (script_fd, script_name) = (None, mktemp('.py'))\\n log.info(\\\"writing byte-compilation script '%s'\\\", script_name)\\n if (not dry_run):\\n if (script_fd is not None):\\n script = os.fdopen(script_fd, 'w')\\n else:\\n script = open(script_name, 'w')\\n script.write('from distutils.util import byte_compile\\\\nfiles = [\\\\n')\\n script.write((',\\\\n'.join(map(repr, py_files)) + ']\\\\n'))\\n script.write(('\\\\nbyte_compile(files, optimize=%r, force=%r,\\\\n prefix=%r, base_dir=%r,\\\\n verbose=%r, dry_run=0,\\\\n direct=1)\\\\n' % (optimize, force, prefix, base_dir, verbose)))\\n script.close()\\n cmd = [sys.executable]\\n cmd.extend(subprocess._optim_args_from_interpreter_flags())\\n cmd.append(script_name)\\n spawn(cmd, dry_run=dry_run)\\n execute(os.remove, (script_name,), ('removing %s' % script_name), dry_run=dry_run)\\n else:\\n from py_compile import compile\\n for file in py_files:\\n if (file[(-3):] != '.py'):\\n continue\\n if (optimize >= 0):\\n opt = ('' if (optimize == 0) else optimize)\\n cfile = importlib.util.cache_from_source(file, optimization=opt)\\n else:\\n cfile = importlib.util.cache_from_source(file)\\n dfile = file\\n if prefix:\\n if (file[:len(prefix)] != prefix):\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def destroy(name, call=None):\",\"targets\":\"\\\"\\\"\\\"To destroy a VM from the VMware environment\\n CLI Example:\\n .. code-block:: bash\\n salt-cloud -d vmname\\n salt-cloud --destroy vmname\\n salt-cloud -a destroy vmname\\n \\\"\\\"\\\"\\n if (call == 'function'):\\n raise SaltCloudSystemExit('The destroy action must be called with -d, --destroy, -a or --action.')\\n __utils__['cloud.fire_event']('event', 'destroying instance', 'salt\\/cloud\\/{0}\\/destroying'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])\\n vm_properties = ['name', 'summary.runtime.powerState']\\n vm_list = salt.utils.vmware.get_mors_with_properties(_get_si(), vim.VirtualMachine, vm_properties)\\n for vm in vm_list:\\n if (vm['name'] == name):\\n if (vm['summary.runtime.powerState'] != 'poweredOff'):\\n try:\\n log.info('Powering Off VM {0}'.format(name))\\n task = vm['object'].PowerOff()\\n salt.utils.vmware.wait_for_task(task, name, 'power off')\\n except Exception as exc:\\n log.error('Error while powering off VM {0}: {1}'.format(name, exc), exc_info_on_loglevel=logging.DEBUG)\\n return 'failed to destroy'\\n try:\\n log.info('Destroying VM {0}'.format(name))\\n task = vm['object'].Destroy_Task()\\n salt.utils.vmware.wait_for_task(task, name, 'destroy')\\n except Exception as exc:\\n log.error('Error while destroying VM {0}: {1}'.format(name, exc), exc_info_on_loglevel=logging.DEBUG)\\n return 'failed to destroy'\\n __utils__['cloud.fire_event']('event', 'destroyed instance', 'salt\\/cloud\\/{0}\\/destroyed'.format(name), args={'name': name}, sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])\\n if (__opts__.get('update_cachedir', False) is True):\\n __utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n group = get_object_or_404(Group, slug=slug)\\n page = get_object_or_404(GroupPage, group=group, slug=page_slug)\\n return render(request, template_name, {'group': group, 'page': page})\\n\\n\\nWhat's a good function header?\",\"targets\":\"def page_detail(request, slug, page_slug, template_name='groups\\/pages\\/page_detail.html'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _get_recarray_field(array, key):\",\"targets\":\"\\\"\\\"\\\"Compatibility function for using the recarray base class\\\\s field method.\\n This incorporates the legacy functionality of returning string arrays as\\n Numeric-style chararray objects.\\n \\\"\\\"\\\"\\n field = np.recarray.field(array, key)\\n if ((field.dtype.char in ('S', 'U')) and (not isinstance(field, chararray.chararray))):\\n field = field.view(chararray.chararray)\\n return field\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if isinstance(value, Model):\\n value = value.key()\\n if (isinstance(value, datetime.date) and (not isinstance(value, datetime.datetime))):\\n value = _date_to_datetime(value)\\n elif isinstance(value, datetime.time):\\n value = _time_to_datetime(value)\\n return value\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _normalize_query_parameter(value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _get_sort_keys(sort_keys, mapping):\\n\\n ''''Returns an array containing only whitelisted keys\\n :param sort_keys: an array of strings\\n :param mapping: a mapping from keys to DB column names\\n :returns: filtered list of sort keys'\\n '''\",\"targets\":\"if isinstance(sort_keys, six.string_types):\\n sort_keys = [sort_keys]\\n return [mapping[key] for key in (sort_keys or []) if (key in mapping)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def SimplifyNode(node):\",\"targets\":\"\\\"\\\"\\\"Simplifies the node removing singleton conjunctions and others.\\n \\\"\\\"\\\"\\n if (not node.getType()):\\n return SimplifyNode(node.children[0])\\n elif ((node.getType() == QueryParser.CONJUNCTION) and (node.getChildCount() == 1)):\\n return SimplifyNode(node.children[0])\\n elif ((node.getType() == QueryParser.DISJUNCTION) and (node.getChildCount() == 1)):\\n return SimplifyNode(node.children[0])\\n elif (((node.getType() == QueryParser.EQ) or (node.getType() == QueryParser.HAS)) and (node.getChildCount() == 1)):\\n return SimplifyNode(node.children[0])\\n for (i, child) in enumerate(node.children):\\n node.setChild(i, SimplifyNode(child))\\n return node\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@utils.decorator\\ndef transactional(func, args, kwds, **options):\",\"targets\":\"\\\"\\\"\\\"Decorator to make a function automatically run in a transaction.\\n Args:\\n **ctx_options: Transaction options (see transaction(), but propagation\\n default to TransactionOptions.ALLOWED).\\n This supports two forms:\\n (1) Vanilla:\\n @transactional\\n def callback(arg):\\n (2) With options:\\n @transactional(retries=1)\\n def callback(arg):\\n \\\"\\\"\\\"\\n return transactional_async.wrapped_decorator(func, args, kwds, **options).get_result()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get(params, is_training=False, reuse=False, run_projection=True):\\n\\n ''''Factory function to get the training\\/pretraining im->vox model (NIPS16).\\n Args:\\n params: Different parameters used througout ptn, typically FLAGS (dict).\\n is_training: Set to True if while training (boolean).\\n reuse: Set as True if sharing variables with a model that has already\\n been built (boolean).\\n run_projection: Set as False if not interested in mask and projection\\n images. Useful in evaluation routine (boolean).\\n Returns:\\n Model function for network (inputs to outputs).'\\n '''\",\"targets\":\"def model(inputs):\\n 'Model function corresponding to a specific network architecture.'\\n outputs = {}\\n encoder_fn = _get_network(params.encoder_name)\\n with tf.variable_scope('encoder', reuse=reuse):\\n enc_outputs = encoder_fn(inputs['images_1'], params, is_training)\\n outputs['ids_1'] = enc_outputs['ids']\\n decoder_fn = _get_network(params.decoder_name)\\n with tf.variable_scope('decoder', reuse=reuse):\\n outputs['voxels_1'] = decoder_fn(outputs['ids_1'], params, is_training)\\n if run_projection:\\n projector_fn = _get_network(params.projector_name)\\n with tf.variable_scope('projector', reuse=reuse):\\n outputs['projs_1'] = projector_fn(outputs['voxels_1'], inputs['matrix_1'], params, is_training)\\n with tf.variable_scope('oracle', reuse=reuse):\\n outputs['masks_1'] = projector_fn(inputs['voxels'], inputs['matrix_1'], params, False)\\n for k in range(1, params.step_size):\\n with tf.variable_scope('projector', reuse=True):\\n outputs[('projs_%d' % (k + 1))] = projector_fn(outputs['voxels_1'], inputs[('matrix_%d' % (k + 1))], params, is_training)\\n with tf.variable_scope('oracle', reuse=True):\\n outputs[('masks_%d' % (k + 1))] = projector_fn(inputs['voxels'], inputs[('matrix_%d' % (k + 1))], params, False)\\n return outputs\\n return model\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef lottery_promoted_links(sr_names, n=10):\\n\\n ''''Run weighted_lottery to order and choose a subset of promoted links.'\\n '''\",\"targets\":\"promo_tuples = get_live_promotions(sr_names)\\n weights = {p: (p.weight or 0.001) for p in promo_tuples}\\n selected = []\\n while (weights and (len(selected) < n)):\\n s = weighted_lottery(weights)\\n del weights[s]\\n selected.append(s)\\n return selected\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@register.filter(is_safe=False)\\ndef intword(value):\",\"targets\":\"\\\"\\\"\\\"Converts a large integer to a friendly text representation. Works best\\n for numbers over 1 million. For example, 1000000 becomes \\\\1.0 million\\\\,\\n 1200000 becomes \\\\1.2 million\\\\ and \\\\1200000000\\\\ becomes \\\\1.2 billion\\\\.\\n \\\"\\\"\\\"\\n try:\\n value = int(value)\\n except (TypeError, ValueError):\\n return value\\n if (value < 1000000):\\n return value\\n def _check_for_i18n(value, float_formatted, string_formatted):\\n u'\\\\n Use the i18n enabled defaultfilters.floatformat if possible\\\\n '\\n if settings.USE_L10N:\\n value = defaultfilters.floatformat(value, 1)\\n template = string_formatted\\n else:\\n template = float_formatted\\n return (template % {u'value': value})\\n for (exponent, converters) in intword_converters:\\n large_number = (10 ** exponent)\\n if (value < (large_number * 1000)):\\n new_value = (value \\/ float(large_number))\\n return _check_for_i18n(new_value, *converters(new_value))\\n return value\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if package:\\n name = package\\n if module:\\n name += ('.' + module)\\n else:\\n name = module\\n return name\\n\\n\\nWhat's a good function header?\",\"targets\":\"def makename(package, module):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef create_banner(message):\\n\\n ''''Create internal shell banner'\\n '''\",\"targets\":\"if (message is None):\\n versions = get_versions()\\n return ('Python %s %dbits [%s]' % (versions['python'], versions['bitness'], versions['system']))\\n else:\\n return message\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def log_warn(warnmsg):\",\"targets\":\"\\\"\\\"\\\"Prints\\/logs any warnings that aren\\\\t critical but should be noted.\\n Args:\\n warnmsg (str): The message to be logged.\\n \\\"\\\"\\\"\\n try:\\n warnmsg = str(warnmsg)\\n except Exception as e:\\n warnmsg = str(e)\\n for line in warnmsg.splitlines():\\n log.msg(('[WW] %s' % line))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef align_check(device, part_type, partition):\\n\\n ''''Check if partition satisfies the alignment constraint of part_type.\\n Type must be \\\"minimal\\\" or \\\"optimal\\\".\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' partition.align_check \\/dev\\/sda minimal 1'\\n '''\",\"targets\":\"_validate_device(device)\\n if (part_type not in set(['minimal', 'optimal'])):\\n raise CommandExecutionError('Invalid part_type passed to partition.align_check')\\n try:\\n int(partition)\\n except Exception:\\n raise CommandExecutionError('Invalid partition passed to partition.align_check')\\n cmd = 'parted -m {0} align-check {1} {2}'.format(device, part_type, partition)\\n out = __salt__['cmd.run'](cmd).splitlines()\\n return out\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def format_date(date=None, format='medium', locale=LC_TIME):\",\"targets\":\"\\\"\\\"\\\"Return a date formatted according to the given pattern.\\n >>> d = date(2007, 04, 01)\\n >>> format_date(d, locale=\\\\en_US\\\\)\\n u\\\\Apr 1, 2007\\\\\\n >>> format_date(d, format=\\\\full\\\\, locale=\\\\de_DE\\\\)\\n u\\\\Sonntag, 1. April 2007\\\\\\n If you don\\\\t want to use the locale default formats, you can specify a\\n custom date pattern:\\n >>> format_date(d, \\\"EEE, MMM d, \\\\\\\\yy\\\", locale=\\\\en\\\\)\\n u\\\"Sun, Apr 1, \\\\07\\\"\\n :param date: the ``date`` or ``datetime`` object; if `None`, the current\\n date is used\\n :param format: one of \\\"full\\\", \\\"long\\\", \\\"medium\\\", or \\\"short\\\", or a custom\\n date\\/time pattern\\n :param locale: a `Locale` object or a locale identifier\\n :rtype: `unicode`\\n :note: If the pattern contains time fields, an `AttributeError` will be\\n raised when trying to apply the formatting. This is also true if\\n the value of ``date`` parameter is actually a ``datetime`` object,\\n as this function automatically converts that to a ``date``.\\n \\\"\\\"\\\"\\n if (date is None):\\n date = date_.today()\\n elif isinstance(date, datetime):\\n date = date.date()\\n locale = Locale.parse(locale)\\n if (format in ('full', 'long', 'medium', 'short')):\\n format = get_date_format(format, locale=locale)\\n pattern = parse_pattern(format)\\n return pattern.apply(date, locale)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _parse_ref(text, link, info):\\n\\n ''''Manage links to references.'\\n '''\",\"targets\":\"if (link.find('\\/title\\/tt') != (-1)):\\n yearK = re_yearKind_index.match(info)\\n if (yearK and (yearK.start() == 0)):\\n text += (' %s' % info[:yearK.end()])\\n return (text.replace('\\\\n', ' '), link)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n import warnings\\n warnings.warn('commands.getstatus() is deprecated', DeprecationWarning, 2)\\n return getoutput(('ls -ld' + mkarg(file)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def getstatus(file):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@testing.requires_testing_data\\ndef test_fine_calibration():\\n\\n ''''Test Maxwell filter fine calibration.'\\n '''\",\"targets\":\"raw = read_crop(raw_fname, (0.0, 1.0))\\n sss_fine_cal = read_crop(sss_fine_cal_fname)\\n raw_sss = maxwell_filter(raw, calibration=fine_cal_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore')\\n assert_meg_snr(raw_sss, sss_fine_cal, 82, 611)\\n py_cal = raw_sss.info['proc_history'][0]['max_info']['sss_cal']\\n assert_true((py_cal is not None))\\n assert_true((len(py_cal) > 0))\\n mf_cal = sss_fine_cal.info['proc_history'][0]['max_info']['sss_cal']\\n mf_cal['cal_chans'][((mf_cal['cal_chans'][:, 1] == 3022), 1)] = 3024\\n assert_allclose(py_cal['cal_chans'], mf_cal['cal_chans'])\\n assert_allclose(py_cal['cal_corrs'], mf_cal['cal_corrs'], rtol=0.001, atol=0.001)\\n raw_missing = raw.copy().load_data()\\n raw_missing.info['bads'] = ['MEG0111', 'MEG0943']\\n raw_missing.info._check_consistency()\\n raw_sss_bad = maxwell_filter(raw_missing, calibration=fine_cal_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore')\\n raw_missing.pick_types()\\n raw_sss_bad.pick_channels(raw_missing.ch_names)\\n with warnings.catch_warnings(record=True):\\n raw_sss_missing = maxwell_filter(raw_missing, calibration=fine_cal_fname, origin=mf_head_origin, regularize=None, bad_condition='ignore')\\n assert_meg_snr(raw_sss_missing, raw_sss_bad, 1000.0, 10000.0)\\n raw_sss_3D = maxwell_filter(raw, calibration=fine_cal_fname_3d, origin=mf_head_origin, regularize=None, bad_condition='ignore')\\n assert_meg_snr(raw_sss_3D, sss_fine_cal, 1.0, 6.0)\\n raw_ctf = read_crop(fname_ctf_raw).apply_gradient_compensation(0)\\n assert_raises(RuntimeError, maxwell_filter, raw_ctf, origin=(0.0, 0.0, 0.04), calibration=fine_cal_fname)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def extract_tokens(l, known_tokens):\",\"targets\":\"\\\"\\\"\\\"Returns dictionary of known tokens with all values\\n \\\"\\\"\\\"\\n assert ((l[0].strip() == '(') and (l[(-1)].strip() == ')')), ValueError(l)\\n result = {}\\n result_has_key = result.has_key\\n result.update(known_tokens)\\n i = 0\\n l_len = len(l)\\n while (i < l_len):\\n if result_has_key(l[i]):\\n token = l[i]\\n i += 1\\n if (i < l_len):\\n if result_has_key(l[i]):\\n result[token] = ()\\n elif (l[i] == '('):\\n i += 1\\n start = i\\n while ((i < l_len) and (l[i] != ')')):\\n i += 1\\n result[token] = tuple(filter((lambda v: (v != '$')), l[start:i]))\\n i += 1\\n else:\\n result[token] = (l[i],)\\n i += 1\\n else:\\n i += 1\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n import shutil\\n app_template = os.path.normpath(app_template)\\n for (d, subdirs, files) in os.walk(app_template):\\n relative_dir = d[(len(app_template) + 1):]\\n d_new = os.path.join(copy_to, relative_dir).replace('app_name', app_name)\\n if (relative_dir and (not os.path.exists(d_new))):\\n os.mkdir(d_new)\\n for (i, subdir) in enumerate(subdirs):\\n if subdir.startswith('.'):\\n del subdirs[i]\\n replacements = {'app_name': app_name, 'project_name': project_name}\\n replacements.update(REPLACEMENTS)\\n for f in files:\\n if (f.endswith('.pyc') or f.startswith('.DS_Store')):\\n continue\\n path_old = os.path.join(d, f)\\n path_new = os.path.join(d_new, f.replace('app_name', app_name))\\n if os.path.exists(path_new):\\n path_new = os.path.join(d_new, f)\\n if os.path.exists(path_new):\\n continue\\n if path_new.endswith('.tmpl'):\\n path_new = path_new[:(-5)]\\n fp_old = open(path_old, 'r')\\n fp_new = open(path_new, 'w')\\n fp_new.write(Template(fp_old.read()).render(Context(replacements)))\\n fp_old.close()\\n fp_new.close()\\n try:\\n shutil.copymode(path_old, path_new)\\n _make_writeable(path_new)\\n except OSError:\\n sys.stderr.write((\\\"Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\\\\n\\\" % path_new))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def copy_template(app_template, copy_to, project_name, app_name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n bn = BatchNormalization(input_dim, broadcastable, conserve_memory, epsilon=0.0001, mean_only=mean_only, learn_scale=learn_scale, learn_shift=learn_shift)\\n bn.initialize()\\n b_len = (len(input_dim) if isinstance(input_dim, collections.Sequence) else 1)\\n x = tensor.TensorType(theano.config.floatX, ([False] * (b_len + 1)))()\\n return (bn, x)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def apply_setup(input_dim, broadcastable, conserve_memory, mean_only, learn_scale, learn_shift):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef importfile(path):\\n\\n ''''Import a Python source file or compiled file given its path.'\\n '''\",\"targets\":\"magic = imp.get_magic()\\n file = open(path, 'r')\\n if (file.read(len(magic)) == magic):\\n kind = imp.PY_COMPILED\\n else:\\n kind = imp.PY_SOURCE\\n file.close()\\n filename = os.path.basename(path)\\n (name, ext) = os.path.splitext(filename)\\n file = open(path, 'r')\\n try:\\n module = imp.load_module(name, file, path, (ext, 'r', kind))\\n except:\\n raise ErrorDuringImport(path, sys.exc_info())\\n file.close()\\n return module\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from django.utils.text import phone2numeric\\n return phone2numeric(value)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def phone2numeric(value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n class metaclass(type, ):\\n def __new__(cls, name, this_bases, d):\\n return meta(name, bases, d)\\n return type.__new__(metaclass, 'temporary_class', (), {})\\n\\n\\nWhat's a good function header?\",\"targets\":\"def with_metaclass(meta, *bases):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n env = inliner.document.settings.env\\n r = None\\n r = env.get_domain('py').role('obj')('obj', rawtext, etext, lineno, inliner, options, content)\\n pnode = r[0][0]\\n prefixes = get_import_prefixes_from_env(env)\\n try:\\n (name, obj, parent, modname) = import_by_name(pnode['reftarget'], prefixes)\\n except ImportError:\\n content_node = pnode[0]\\n r[0][0] = nodes.emphasis(rawtext, content_node[0].astext(), classes=content_node['classes'])\\n return r\\n\\n\\nWhat's a good function header?\",\"targets\":\"def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0):\\n\\n ''''rebuild is required if mtimes of files listed in old toc are newer\\n than last_build\\n if pyc=1, check for .py files, too\\n Use this for calculated\\/analysed values read from cache.'\\n '''\",\"targets\":\"for (nm, fnm, typ) in old:\\n if (misc.mtime(fnm) > last_build):\\n logger.info('Building because %s changed', fnm)\\n return True\\n elif (pyc and (misc.mtime(fnm[:(-1)]) > last_build)):\\n logger.info('Building because %s changed', fnm[:(-1)])\\n return True\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not hop_length):\\n hop_length = (n_fft \\/\\/ 2)\\n ifft_config = dict(win_length=n_fft, hop_length=hop_length, center=True)\\n if mag_only:\\n mag = spec[:, :, 0]\\n phase_angle = (np.pi * np.random.rand(*mag.shape))\\n elif re_im:\\n spec_real = (spec[:, :, 0] + (1j * spec[:, :, 1]))\\n else:\\n (mag, p) = (spec[:, :, 0], spec[:, :, 1])\\n if (mask and log_mag):\\n p \\/= (mag + (1e-13 * np.random.randn(*mag.shape)))\\n if dphase:\\n phase_angle = np.cumsum((p * np.pi), axis=1)\\n else:\\n phase_angle = (p * np.pi)\\n if log_mag:\\n mag = ((mag - 1.0) * 120.0)\\n mag = (10 ** (mag \\/ 20.0))\\n phase = (np.cos(phase_angle) + (1j * np.sin(phase_angle)))\\n spec_real = (mag * phase)\\n if mag_only:\\n audio = griffin_lim(mag, phase_angle, n_fft, hop_length, num_iters=num_iters)\\n else:\\n audio = librosa.core.istft(spec_real, **ifft_config)\\n return np.squeeze((audio \\/ audio.max()))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ispecgram(spec, n_fft=512, hop_length=None, mask=True, log_mag=True, re_im=False, dphase=True, mag_only=True, num_iters=1000):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n match = re.search(pattern, value)\\n if (match is None):\\n raise Exception(('Pattern \\\"%s\\\" did not match value: %s' % (pattern, value)))\\n return match.groupdict()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_to_dict(pattern, value):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dnsdomain_unregister(context, fqdomain):\",\"targets\":\"\\\"\\\"\\\"Purge associations for the specified DNS zone.\\n \\\"\\\"\\\"\\n return IMPL.dnsdomain_unregister(context, fqdomain)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (_, local_dict) = get_twill_glocals()\\n inp = raw_input(prompt)\\n local_dict['__input__'] = inp\\n return inp\\n\\n\\nWhat's a good function header?\",\"targets\":\"def getinput(prompt):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@pytest.mark.installed\\ndef test_activate_has_extra_env_vars(shell):\",\"targets\":\"\\\"\\\"\\\"Test that environment variables in activate.d show up when activated\\n \\\"\\\"\\\"\\n shell_vars = _format_vars(shell)\\n with TemporaryDirectory(prefix=ENVS_PREFIX, dir=dirname(__file__)) as envs:\\n env_dirs = gen_test_env_paths(envs, shell)\\n for path in [u'activate', u'deactivate']:\\n dir = os.path.join(shells[shell][u'path_from'](env_dirs[0]), u'etc', u'conda', (u'%s.d' % path))\\n os.makedirs(dir)\\n file = os.path.join(dir, (u'test' + shells[shell][u'env_script_suffix']))\\n setting = (u'test' if (path == u'activate') else u'')\\n with open(file, u'w') as f:\\n f.write((shells[shell][u'set_var'] + (u'TEST_VAR=%s\\\\n' % setting)))\\n commands = (shell_vars[u'command_setup'] + u'\\\\n {source} \\\"{syspath}{binpath}activate\\\" \\\"{env_dirs[0]}\\\"\\\\n {echo} {var}\\\\n ').format(envs=envs, env_dirs=env_dirs, var=shells[shell][u'var_format'].format(u'TEST_VAR'), **shell_vars)\\n (stdout, stderr) = run_in(commands, shell)\\n assert (not stderr)\\n assert_equals(stdout, u'test', stderr)\\n commands = (shell_vars[u'command_setup'] + u'\\\\n {source} \\\"{syspath}{binpath}activate\\\" \\\"{env_dirs[0]}\\\"\\\\n {source} \\\"{syspath}{binpath}deactivate\\\"\\\\n {echo} {var}.\\\\n ').format(envs=envs, env_dirs=env_dirs, var=shells[shell][u'var_format'].format(u'TEST_VAR'), **shell_vars)\\n (stdout, stderr) = run_in(commands, shell)\\n assert_equals(stdout, u'.', stderr)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n @functools.wraps(test)\\n def wrapper(*args, **kwargs):\\n msg = '{name} requires Python 2.7.x+ to run'.format(name=test.__name__)\\n if (sys.version_info < (2, 7)):\\n pytest.skip(msg)\\n return test(*args, **kwargs)\\n return wrapper\\n\\n\\nWhat's a good function header?\",\"targets\":\"def onlyPy27OrNewer(test):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if exact:\\n if (np.ndim(n) == 0):\\n return (0 if (n < 0) else math.factorial(n))\\n else:\\n n = asarray(n)\\n un = np.unique(n).astype(object)\\n if (un[(-1)] > 20):\\n dt = object\\n elif (un[(-1)] > 12):\\n dt = np.int64\\n else:\\n dt = np.int\\n out = np.empty_like(n, dtype=dt)\\n un = un[(un > 1)]\\n out[(n < 2)] = 1\\n out[(n < 0)] = 0\\n if un.size:\\n val = math.factorial(un[0])\\n out[(n == un[0])] = val\\n for i in xrange((len(un) - 1)):\\n prev = (un[i] + 1)\\n current = un[(i + 1)]\\n val *= _range_prod(prev, current)\\n out[(n == current)] = val\\n return out\\n else:\\n n = asarray(n)\\n vals = gamma((n + 1))\\n return where((n >= 0), vals, 0)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def factorial(n, exact=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _use_inf_as_na(key):\",\"targets\":\"\\\"\\\"\\\"Option change callback for na\\/inf behaviour\\n Choose which replacement for numpy.isnan \\/ -numpy.isfinite is used.\\n Parameters\\n flag: bool\\n True means treat None, NaN, INF, -INF as null (old way),\\n False means None and NaN are null, but INF, -INF are not null\\n (new way).\\n Notes\\n This approach to setting global module values is discussed and\\n approved here:\\n * http:\\/\\/stackoverflow.com\\/questions\\/4859217\\/\\n programmatically-creating-variables-in-python\\/4859312#4859312\\n \\\"\\\"\\\"\\n from pandas.core.config import get_option\\n flag = get_option(key)\\n if flag:\\n globals()['_isna'] = _isna_old\\n else:\\n globals()['_isna'] = _isna_new\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if ((n <= 0) or ((m is not None) and (m < 1)) or ((k is not None) and (k < 1)) or (m and k and ((m * k) < n))):\\n if size:\\n (yield (0, {}))\\n else:\\n (yield {})\\n return\\n if (m is None):\\n m = n\\n else:\\n m = min(m, n)\\n if (n == 0):\\n if size:\\n (yield (1, {0: 1}))\\n else:\\n (yield {0: 1})\\n return\\n k = min((k or n), n)\\n (n, m, k) = (as_int(n), as_int(m), as_int(k))\\n (q, r) = divmod(n, k)\\n ms = {k: q}\\n keys = [k]\\n if r:\\n ms[r] = 1\\n keys.append(r)\\n room = ((m - q) - bool(r))\\n if size:\\n (yield (sum(ms.values()), ms))\\n else:\\n (yield ms)\\n while (keys != [1]):\\n if (keys[(-1)] == 1):\\n del keys[(-1)]\\n reuse = ms.pop(1)\\n room += reuse\\n else:\\n reuse = 0\\n while 1:\\n i = keys[(-1)]\\n newcount = ms[i] = (ms[i] - 1)\\n reuse += i\\n if (newcount == 0):\\n del keys[(-1)], ms[i]\\n room += 1\\n i -= 1\\n (q, r) = divmod(reuse, i)\\n need = (q + bool(r))\\n if (need > room):\\n if (not keys):\\n return\\n continue\\n ms[i] = q\\n keys.append(i)\\n if r:\\n ms[r] = 1\\n keys.append(r)\\n break\\n room -= need\\n if size:\\n (yield (sum(ms.values()), ms))\\n else:\\n (yield ms)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def partitions(n, m=None, k=None, size=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def frame_from_fsnative(arg):\",\"targets\":\"\\\"\\\"\\\"Takes item from argv and returns ascii native str\\n or raises ValueError.\\n \\\"\\\"\\\"\\n assert isinstance(arg, fsnative)\\n text = fsn2text(arg, strict=True)\\n if PY2:\\n return text.encode('ascii')\\n else:\\n return text.encode('ascii').decode('ascii')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n ordering_field_columns = cl.get_ordering_field_columns()\\n for (i, field_name) in enumerate(cl.list_display):\\n (text, attr) = label_for_field(field_name, cl.model, model_admin=cl.model_admin, return_attr=True)\\n if attr:\\n field_name = _coerce_field_name(field_name, i)\\n if (field_name == 'action_checkbox'):\\n (yield {'text': text, 'class_attrib': mark_safe(' class=\\\"action-checkbox-column\\\"'), 'sortable': False})\\n continue\\n admin_order_field = getattr(attr, 'admin_order_field', None)\\n if (not admin_order_field):\\n (yield {'text': text, 'class_attrib': format_html(' class=\\\"column-{}\\\"', field_name), 'sortable': False})\\n continue\\n th_classes = ['sortable', 'column-{}'.format(field_name)]\\n order_type = ''\\n new_order_type = 'asc'\\n sort_priority = 0\\n sorted = False\\n if (i in ordering_field_columns):\\n sorted = True\\n order_type = ordering_field_columns.get(i).lower()\\n sort_priority = (list(ordering_field_columns).index(i) + 1)\\n th_classes.append(('sorted %sending' % order_type))\\n new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type]\\n o_list_primary = []\\n o_list_remove = []\\n o_list_toggle = []\\n def make_qs_param(t, n):\\n return (('-' if (t == 'desc') else '') + str(n))\\n for (j, ot) in ordering_field_columns.items():\\n if (j == i):\\n param = make_qs_param(new_order_type, j)\\n o_list_primary.insert(0, param)\\n o_list_toggle.append(param)\\n else:\\n param = make_qs_param(ot, j)\\n o_list_primary.append(param)\\n o_list_toggle.append(param)\\n o_list_remove.append(param)\\n if (i not in ordering_field_columns):\\n o_list_primary.insert(0, make_qs_param(new_order_type, i))\\n (yield {'text': text, 'sortable': True,...\\n\\nWhat's a good function header?\",\"targets\":\"def result_headers(cl):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef capture_screenshot_for_step(step, when):\\n\\n ''''Useful method for debugging acceptance tests that are run in Vagrant.\\n This method runs automatically before and after each step of an acceptance\\n test scenario. The variable:\\n world.auto_capture_screenshots\\n either enables or disabled the taking of screenshots. To change the\\n variable there is a convenient step defined:\\n I (enable|disable) auto screenshots\\n If you just want to capture a single screenshot at a desired point in code,\\n you should use the method:\\n world.capture_screenshot(\\\"image_name\\\")'\\n '''\",\"targets\":\"if world.auto_capture_screenshots:\\n scenario_num = (step.scenario.feature.scenarios.index(step.scenario) + 1)\\n step_num = (step.scenario.steps.index(step) + 1)\\n step_func_name = step.defined_at.function.func_name\\n image_name = '{prefix:03d}__{num:03d}__{name}__{postfix}'.format(prefix=scenario_num, num=step_num, name=step_func_name, postfix=when)\\n world.capture_screenshot(image_name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@mock_ec2_deprecated\\ndef test_eip_allocate_vpc():\",\"targets\":\"\\\"\\\"\\\"Allocate\\/release VPC EIP\\n \\\"\\\"\\\"\\n conn = boto.connect_ec2(u'the_key', u'the_secret')\\n with assert_raises(EC2ResponseError) as ex:\\n vpc = conn.allocate_address(domain=u'vpc', dry_run=True)\\n ex.exception.error_code.should.equal(u'DryRunOperation')\\n ex.exception.status.should.equal(400)\\n ex.exception.message.should.equal(u'An error occurred (DryRunOperation) when calling the AllocateAddress operation: Request would have succeeded, but DryRun flag is set')\\n vpc = conn.allocate_address(domain=u'vpc')\\n vpc.should.be.a(boto.ec2.address.Address)\\n vpc.domain.should.be.equal(u'vpc')\\n logging.debug(u'vpc alloc_id:'.format(vpc.allocation_id))\\n vpc.release()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n output = s3_rest_controller()\\n return output\\n\\n\\nWhat's a good function header?\",\"targets\":\"def question_metadata():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef convert_image(source, dest, out_format):\\n\\n ''''Convert image to other format'\\n '''\",\"targets\":\"cmd = ('qemu-img', 'convert', '-O', out_format, source, dest)\\n utils.execute(run_as_root=True, *cmd)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def auth(profile=None, **connection_args):\",\"targets\":\"\\\"\\\"\\\"Set up keystone credentials. Only intended to be used within Keystone-enabled modules.\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ keystone.auth\\n \\\"\\\"\\\"\\n kwargs = _get_kwargs(profile=profile, **connection_args)\\n if (float(api_version(profile=profile, **connection_args).strip('v')) >= 3):\\n global _OS_IDENTITY_API_VERSION\\n global _TENANTS\\n _OS_IDENTITY_API_VERSION = 3\\n _TENANTS = 'projects'\\n return client3.Client(**kwargs)\\n else:\\n return client.Client(**kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _plot_connectivity_circle_onpick(event, fig=None, axes=None, indices=None, n_nodes=0, node_angles=None, ylim=[9, 10]):\",\"targets\":\"\\\"\\\"\\\"Isolate connections around a single node when user left clicks a node.\\n On right click, resets all connections.\\n \\\"\\\"\\\"\\n if (event.inaxes != axes):\\n return\\n if (event.button == 1):\\n if (not (ylim[0] <= event.ydata <= ylim[1])):\\n return\\n node_angles = (node_angles % (np.pi * 2))\\n node = np.argmin(np.abs((event.xdata - node_angles)))\\n patches = event.inaxes.patches\\n for (ii, (x, y)) in enumerate(zip(indices[0], indices[1])):\\n patches[ii].set_visible((node in [x, y]))\\n fig.canvas.draw()\\n elif (event.button == 3):\\n patches = event.inaxes.patches\\n for ii in range(np.size(indices, axis=1)):\\n patches[ii].set_visible(True)\\n fig.canvas.draw()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Name(name, prefix=None):\\n\\n ''''Return a NAME leaf'\\n '''\",\"targets\":\"return Leaf(token.NAME, name, prefix=prefix)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Search(pattern, s):\\n\\n ''''Searches the string for the pattern, caching the compiled regexp.'\\n '''\",\"targets\":\"if (pattern not in _regexp_compile_cache):\\n _regexp_compile_cache[pattern] = sre_compile.compile(pattern)\\n return _regexp_compile_cache[pattern].search(s)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef length(value):\\n\\n ''''Returns the length of the value - useful for lists.'\\n '''\",\"targets\":\"try:\\n return len(value)\\n except (ValueError, TypeError):\\n return ''\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global _RC_CACHE\\n if (_RC_CACHE is not None):\\n return\\n _RC_CACHE = rc_cache.ResourceClassCache(ctx)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@db_api.api_context_manager.reader\\ndef _ensure_rc_cache(ctx):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for char in value:\\n if (char not in _VISIBLE_PRINTABLE_ASCII):\\n raise ValueError(('%r must be visible printable ASCII: %r' % (name, value)))\\n if value.startswith('!'):\\n raise ValueError(('%r must not start with \\\"!\\\": %r' % (name, value)))\\n return value\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _ValidateVisiblePrintableAsciiNotReserved(value, name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (module.check_mode and (path is not None)):\\n keysfile = path\\n return keysfile\\n try:\\n user_entry = pwd.getpwnam(user)\\n except KeyError:\\n e = get_exception()\\n if (module.check_mode and (path is None)):\\n module.fail_json(msg='Either user must exist or you must provide full path to key file in check mode')\\n module.fail_json(msg=('Failed to lookup user %s: %s' % (user, str(e))))\\n if (path is None):\\n homedir = user_entry.pw_dir\\n sshdir = os.path.join(homedir, '.ssh')\\n keysfile = os.path.join(sshdir, 'authorized_keys')\\n else:\\n sshdir = os.path.dirname(path)\\n keysfile = path\\n if (not write):\\n return keysfile\\n uid = user_entry.pw_uid\\n gid = user_entry.pw_gid\\n if manage_dir:\\n if (not os.path.exists(sshdir)):\\n os.mkdir(sshdir, int('0700', 8))\\n if module.selinux_enabled():\\n module.set_default_selinux_context(sshdir, False)\\n os.chown(sshdir, uid, gid)\\n os.chmod(sshdir, int('0700', 8))\\n if (not os.path.exists(keysfile)):\\n basedir = os.path.dirname(keysfile)\\n if (not os.path.exists(basedir)):\\n os.makedirs(basedir)\\n try:\\n f = open(keysfile, 'w')\\n finally:\\n f.close()\\n if module.selinux_enabled():\\n module.set_default_selinux_context(keysfile, False)\\n try:\\n os.chown(keysfile, uid, gid)\\n os.chmod(keysfile, int('0600', 8))\\n except OSError:\\n pass\\n return keysfile\\n\\n\\nWhat's a good function header?\",\"targets\":\"def keyfile(module, user, write=False, path=None, manage_dir=True):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n QtWebEngineWidgets = pytest.importorskip('PyQt5.QtWebEngineWidgets')\\n return QtWebEngineWidgets.QWebEngineView()\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pytest.fixture\\ndef webengineview():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@utils.positional(1)\\ndef _gql(query_string, query_class=Query):\",\"targets\":\"\\\"\\\"\\\"Parse a GQL query string (internal version).\\n Args:\\n query_string: Full GQL query, e.g. \\\\SELECT * FROM Kind WHERE prop = 1\\\\.\\n query_class: Optional class to use, default Query.\\n Returns:\\n An instance of query_class.\\n \\\"\\\"\\\"\\n from .google_imports import gql\\n gql_qry = gql.GQL(query_string)\\n kind = gql_qry.kind()\\n if (kind is None):\\n modelclass = model.Expando\\n else:\\n modelclass = model.Model._lookup_model(kind, tasklets.get_context()._conn.adapter.default_model)\\n kind = modelclass._get_kind()\\n ancestor = None\\n flt = gql_qry.filters()\\n filters = list(modelclass._default_filters())\\n for name_op in sorted(flt):\\n (name, op) = name_op\\n values = flt[name_op]\\n op = op.lower()\\n if ((op == 'is') and (name == gql.GQL._GQL__ANCESTOR)):\\n if (len(values) != 1):\\n raise ValueError('\\\"is\\\" requires exactly one value')\\n [(func, args)] = values\\n ancestor = _args_to_val(func, args)\\n continue\\n if (op not in _OPS):\\n raise NotImplementedError(('Operation %r is not supported.' % op))\\n for (func, args) in values:\\n val = _args_to_val(func, args)\\n prop = _get_prop_from_modelclass(modelclass, name)\\n if (prop._name != name):\\n raise RuntimeError(('Whoa! _get_prop_from_modelclass(%s, %r) returned a property whose name is %r?!' % (modelclass.__name__, name, prop._name)))\\n if isinstance(val, ParameterizedThing):\\n node = ParameterNode(prop, op, val)\\n elif (op == 'in'):\\n node = prop._IN(val)\\n else:\\n node = prop._comparison(op, val)\\n filters.append(node)\\n if filters:\\n filters = ConjunctionNode(*filters)\\n else:\\n filters = None\\n orders = _orderings_to_orders(gql_qry.orderings(), modelclass)\\n offset = gql_qry.offset()\\n limit = gql_qry.limit()\\n if (limit < 0):\\n limit = None\\n keys_only = gql_qry._keys_only\\n if (not keys_only):\\n keys_only = None\\n options = QueryOptions(offset=offset, limit=limit, keys_only=keys_only)\\n projection = gql_qry.projection()\\n if...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_target_domain_use_https(domain):\\n\\n ''''请求目标域名时是吊䜿甚https'\\n '''\",\"targets\":\"if (force_https_domains == 'NONE'):\\n return False\\n if (force_https_domains == 'ALL'):\\n return True\\n if (domain in force_https_domains):\\n return True\\n else:\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n dash = (_allowMOSFSNames and (p[:1] == '-'))\\n if dash:\\n q = (string.find(p, '-', 1) + 1)\\n elif (p[:1] == ':'):\\n q = 0\\n else:\\n q = (string.find(p, ':') + 1)\\n s = string.find(p, '#')\\n if ((s == (-1)) or (s > q)):\\n s = q\\n else:\\n for c in p[dash:s]:\\n if (c not in string.ascii_letters):\\n q = 0\\n break\\n r = q\\n if (p[q:(q + 1)] == ':'):\\n r = (string.find(p, '.', (q + 1)) + 1)\\n if (r == 0):\\n r = len(p)\\n return (p[:q], p[q:r], p[r:])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _split(p):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@deprecated(u'2.0', message=_hold_msg)\\ndef over(func, *args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Call a function with hold(True).\\n Calls::\\n func(*args, **kwargs)\\n with ``hold(True)`` and then restores the hold state.\\n \\\"\\\"\\\"\\n ax = gca()\\n h = ax._hold\\n ax._hold = True\\n func(*args, **kwargs)\\n ax._hold = h\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_default_version(module=None):\\n\\n ''''Returns the name of the default version for the module.\\n Args:\\n module: Module to retrieve the default version for, if None then the current\\n module will be used.\\n Returns:\\n String containing the name of the default version of the module.\\n Raises:\\n InvalidModuleError if the given module is not valid, InvalidVersionError if\\n no default version could be found.'\\n '''\",\"targets\":\"def _ResultHook(rpc):\\n mapped_errors = [modules_service_pb.ModulesServiceError.INVALID_MODULE, modules_service_pb.ModulesServiceError.INVALID_VERSION]\\n _CheckAsyncResult(rpc, mapped_errors, {})\\n return rpc.response.version()\\n request = modules_service_pb.GetDefaultVersionRequest()\\n if module:\\n request.set_module(module)\\n response = modules_service_pb.GetDefaultVersionResponse()\\n return _MakeAsyncCall('GetDefaultVersion', request, response, _ResultHook).get_result()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n name = (name[0].upper() + name[1:])\\n return name.replace('_', ' ')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def pretty_name(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@register.filter(expects_localtime=True)\\ndef naturalday(value, arg=None):\\n\\n ''''For date values that are tomorrow, today or yesterday compared to\\n present day returns representing string. Otherwise, returns a string\\n formatted according to settings.DATE_FORMAT.'\\n '''\",\"targets\":\"try:\\n tzinfo = getattr(value, u'tzinfo', None)\\n value = date(value.year, value.month, value.day)\\n except AttributeError:\\n return value\\n except ValueError:\\n return value\\n today = datetime.now(tzinfo).date()\\n delta = (value - today)\\n if (delta.days == 0):\\n return _(u'today')\\n elif (delta.days == 1):\\n return _(u'tomorrow')\\n elif (delta.days == (-1)):\\n return _(u'yesterday')\\n return defaultfilters.date(value, arg)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef copy_hparams(hparams):\\n\\n ''''Return a copy of an HParams instance.'\\n '''\",\"targets\":\"return tf.contrib.training.HParams(**hparams.values())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef isValidVariableName(name):\\n\\n ''''Checks whether a certain string could be used as a valid variable.\\n Usage::\\n OK, msg = isValidVariableName(name)\\n >>> isValidVariableName(\\\\'name\\\\')\\n (True, \\\\'\\\\')\\n >>> isValidVariableName(\\\\'0name\\\\')\\n (False, \\\\'Variables cannot begin with numeric character\\\\')\\n >>> isValidVariableName(\\\\'first second\\\\')\\n (False, \\\\'Variables cannot contain punctuation or spaces\\\\')\\n >>> isValidVariableName(\\\\'\\\\')\\n (False, \\\"Variables cannot be missing, None, or \\\\'\\\\'\\\")\\n >>> isValidVariableName(None)\\n (False, \\\"Variables cannot be missing, None, or \\\\'\\\\'\\\")\\n >>> isValidVariableName(23)\\n (False, \\\"Variables must be string-like\\\")\\n >>> isValidVariableName(\\\\'a_b_c\\\\')\\n (True, \\\\'\\\\')'\\n '''\",\"targets\":\"if (not name):\\n return (False, \\\"Variables cannot be missing, None, or ''\\\")\\n if (not isinstance(name, basestring)):\\n return (False, 'Variables must be string-like')\\n try:\\n name = str(name)\\n except Exception:\\n if (type(name) in [str, np.unicode_]):\\n msg = 'name %s (type %s) contains non-ASCII characters (e.g. accents)'\\n raise AttributeError((msg % (name, type(name))))\\n else:\\n msg = 'name %s (type %s) could not be converted to a string'\\n raise AttributeError((msg % (name, type(name))))\\n if name[0].isdigit():\\n return (False, 'Variables cannot begin with numeric character')\\n if _nonalphanumeric_re.search(name):\\n return (False, 'Variables cannot contain punctuation or spaces')\\n return (True, '')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if CONF.libvirt.disk_prefix:\\n return CONF.libvirt.disk_prefix\\n if (disk_bus == 'ide'):\\n return 'hd'\\n elif (disk_bus == 'virtio'):\\n return 'vd'\\n elif (disk_bus == 'xen'):\\n return 'xvd'\\n elif (disk_bus == 'scsi'):\\n return 'sd'\\n elif (disk_bus == 'usb'):\\n return 'sd'\\n elif (disk_bus == 'fdc'):\\n return 'fd'\\n elif (disk_bus == 'uml'):\\n return 'ubd'\\n elif (disk_bus == 'lxc'):\\n return None\\n elif (disk_bus == 'sata'):\\n return 'sd'\\n else:\\n raise exception.InternalError((_('Unable to determine disk prefix for %s') % disk_bus))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_dev_prefix_for_disk_bus(disk_bus):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n f = (_Cfunctions.get('libvlc_media_get_state', None) or _Cfunction('libvlc_media_get_state', ((1,),), None, State, Media))\\n return f(p_md)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def libvlc_media_get_state(p_md):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@docfiller\\ndef maximum_filter1d(input, size, axis=(-1), output=None, mode='reflect', cval=0.0, origin=0):\",\"targets\":\"\\\"\\\"\\\"Calculate a one-dimensional maximum filter along the given axis.\\n The lines of the array along the given axis are filtered with a\\n maximum filter of given size.\\n Parameters\\n %(input)s\\n size : int\\n Length along which to calculate the 1-D maximum.\\n %(axis)s\\n %(output)s\\n %(mode)s\\n %(cval)s\\n %(origin)s\\n Returns\\n maximum1d : ndarray, None\\n Maximum-filtered array with same shape as input.\\n None if `output` is not None\\n Notes\\n This function implements the MAXLIST algorithm [1]_, as described by\\n Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being\\n the `input` length, regardless of filter size.\\n References\\n .. [1] http:\\/\\/citeseerx.ist.psu.edu\\/viewdoc\\/summary?doi=10.1.1.42.2777\\n .. [2] http:\\/\\/www.richardhartersworld.com\\/cri\\/2001\\/slidingmin.html\\n Examples\\n >>> from scipy.ndimage import maximum_filter1d\\n >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)\\n array([8, 8, 8, 4, 9, 9, 9, 9])\\n \\\"\\\"\\\"\\n input = numpy.asarray(input)\\n if numpy.iscomplexobj(input):\\n raise TypeError('Complex type not supported')\\n axis = _ni_support._check_axis(axis, input.ndim)\\n if (size < 1):\\n raise RuntimeError('incorrect filter size')\\n (output, return_value) = _ni_support._get_output(output, input)\\n if ((((size \\/\\/ 2) + origin) < 0) or (((size \\/\\/ 2) + origin) >= size)):\\n raise ValueError('invalid origin')\\n mode = _ni_support._extend_mode_to_code(mode)\\n _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0)\\n return return_value\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n args = (args or [])\\n options = PARSER.parse_args(args)\\n options.file_params = dict()\\n options.linters_params = dict()\\n if config:\\n cfg = get_config(str(options.options), rootdir=rootdir)\\n for (opt, val) in cfg.default.items():\\n LOGGER.info('Find option %s (%s)', opt, val)\\n passed_value = getattr(options, opt, _Default())\\n if isinstance(passed_value, _Default):\\n if (opt == 'paths'):\\n val = val.split()\\n setattr(options, opt, _Default(val))\\n for (name, opts) in cfg.sections.items():\\n if ((not name.startswith('pylama')) or (name == cfg.default_section)):\\n continue\\n name = name[7:]\\n if (name in LINTERS):\\n options.linters_params[name] = dict(opts)\\n continue\\n mask = re.compile(fnmatch.translate(name))\\n options.file_params[mask] = dict(opts)\\n _override_options(options, **overrides)\\n for name in options.__dict__:\\n value = getattr(options, name)\\n if isinstance(value, _Default):\\n setattr(options, name, process_value(name, value.value))\\n if (options.async and ('pylint' in options.linters)):\\n LOGGER.warning(\\\"Can't parse code asynchronously with pylint enabled.\\\")\\n options.async = False\\n return options\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_options(args=None, config=True, rootdir=CURDIR, **overrides):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _decimal_to_128(value):\\n\\n ''''Converts a decimal.Decimal to BID (high bits, low bits).\\n :Parameters:\\n - `value`: An instance of decimal.Decimal'\\n '''\",\"targets\":\"with decimal.localcontext(_DEC128_CTX) as ctx:\\n value = ctx.create_decimal(value)\\n if value.is_infinite():\\n return (_NINF if value.is_signed() else _PINF)\\n (sign, digits, exponent) = value.as_tuple()\\n if value.is_nan():\\n if digits:\\n raise ValueError('NaN with debug payload is not supported')\\n if value.is_snan():\\n return (_NSNAN if value.is_signed() else _PSNAN)\\n return (_NNAN if value.is_signed() else _PNAN)\\n significand = int(''.join([str(digit) for digit in digits]))\\n bit_length = _bit_length(significand)\\n high = 0\\n low = 0\\n for i in range(min(64, bit_length)):\\n if (significand & (1 << i)):\\n low |= (1 << i)\\n for i in range(64, bit_length):\\n if (significand & (1 << i)):\\n high |= (1 << (i - 64))\\n biased_exponent = (exponent + _EXPONENT_BIAS)\\n if ((high >> 49) == 1):\\n high = (high & 140737488355327)\\n high |= _EXPONENT_MASK\\n high |= ((biased_exponent & 16383) << 47)\\n else:\\n high |= (biased_exponent << 49)\\n if sign:\\n high |= _SIGN\\n return (high, low)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@use_clip_fps_by_default\\ndef detect_scenes(clip=None, luminosities=None, thr=10, progress_bar=True, fps=None):\\n\\n ''''Detects scenes of a clip based on luminosity changes.\\n Note that for large clip this may take some time\\n Returns\\n cuts, luminosities\\n cuts is a series of cuts [(0,t1), (t1,t2),...(...,tf)]\\n luminosities are the luminosities computed for each\\n frame of the clip.\\n Parameters\\n clip\\n A video clip. Can be None if a list of luminosities is\\n provided instead. If provided, the luminosity of each\\n frame of the clip will be computed. If the clip has no\\n \\\\'fps\\\\' attribute, you must provide it.\\n luminosities\\n A list of luminosities, e.g. returned by detect_scenes\\n in a previous run.\\n thr\\n Determines a threshold above which the \\\\'luminosity jumps\\\\'\\n will be considered as scene changes. A scene change is defined\\n as a change between 2 consecutive frames that is larger than\\n (avg * thr) where avg is the average of the absolute changes\\n between consecutive frames.\\n progress_bar\\n We all love progress bars ! Here is one for you, in option.\\n fps\\n Must be provided if you provide no clip or a clip without\\n fps attribute.'\\n '''\",\"targets\":\"if (luminosities is None):\\n luminosities = [f.sum() for f in clip.iter_frames(fps=fps, dtype='uint32', progress_bar=progress_bar)]\\n luminosities = np.array(luminosities, dtype=float)\\n if (clip is not None):\\n end = clip.duration\\n else:\\n end = (len(luminosities) * (1.0 \\/ fps))\\n lum_diffs = abs(np.diff(luminosities))\\n avg = lum_diffs.mean()\\n luminosity_jumps = (1 + np.array(np.nonzero((lum_diffs > (thr * avg))))[0])\\n tt = (([0] + list(((1.0 \\/ fps) * luminosity_jumps))) + [end])\\n cuts = [(t1, t2) for (t1, t2) in zip(tt, tt[1:])]\\n return (cuts, luminosities)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n eslintignore_path = os.path.join(os.getcwd(), '.eslintignore')\\n parsed_args = _PARSER.parse_args()\\n if parsed_args.path:\\n input_path = os.path.join(os.getcwd(), parsed_args.path)\\n if (not os.path.exists(input_path)):\\n print ('Could not locate file or directory %s. Exiting.' % input_path)\\n print '----------------------------------------'\\n sys.exit(1)\\n if os.path.isfile(input_path):\\n all_files = [input_path]\\n else:\\n excluded_glob_patterns = _get_glob_patterns_excluded_from_eslint(eslintignore_path)\\n all_files = _get_all_files_in_directory(input_path, excluded_glob_patterns)\\n elif parsed_args.files:\\n valid_filepaths = []\\n invalid_filepaths = []\\n for f in parsed_args.files:\\n if os.path.isfile(f):\\n valid_filepaths.append(f)\\n else:\\n invalid_filepaths.append(f)\\n if invalid_filepaths:\\n print ('The following file(s) do not exist: %s\\\\nExiting.' % invalid_filepaths)\\n sys.exit(1)\\n all_files = valid_filepaths\\n else:\\n all_files = _get_changed_filenames()\\n all_files = [filename for filename in all_files if (not any((fnmatch.fnmatch(filename, pattern) for pattern in EXCLUDED_PATHS)))]\\n return all_files\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_all_files():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n config = load_yaml_config(TRAVIS_CONFIG_FILE)\\n config['deploy']['password'] = dict(secure=encrypted_password)\\n save_yaml_config(TRAVIS_CONFIG_FILE, config)\\n line = '# This file was autogenerated and will overwrite each time you run travis_pypi_setup.py\\\\n'\\n prepend_line(TRAVIS_CONFIG_FILE, line)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def update_travis_deploy_password(encrypted_password):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n int_id = ec2_id_to_id(ec2_id)\\n return get_instance_uuid_from_int_id(context, int_id)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ec2_inst_id_to_uuid(context, ec2_id):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (region_cls is None):\\n region_cls = RegionInfo\\n region = _get_region(service_name, region_name, region_cls, connection_cls)\\n if ((region is None) and _use_endpoint_heuristics()):\\n region = _get_region_with_heuristics(service_name, region_name, region_cls, connection_cls)\\n if (region is None):\\n return None\\n return region.connect(**kw_params)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def connect(service_name, region_name, region_cls=None, connection_cls=None, **kw_params):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def getFlattenedNestedRings(nestedRings):\",\"targets\":\"\\\"\\\"\\\"Get flattened nested rings.\\n \\\"\\\"\\\"\\n flattenedNestedRings = []\\n for nestedRing in nestedRings:\\n nestedRing.addFlattenedNestedRings(flattenedNestedRings)\\n return flattenedNestedRings\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (new_version == 1):\\n _create_index(engine, 'events', 'ix_events_time_fired')\\n elif (new_version == 2):\\n _create_index(engine, 'recorder_runs', 'ix_recorder_runs_start_end')\\n _create_index(engine, 'states', 'ix_states_last_updated')\\n elif (new_version == 3):\\n pass\\n elif (new_version == 4):\\n if (old_version == 3):\\n _drop_index(engine, 'states', 'ix_states_created_domain')\\n if (old_version == 2):\\n _drop_index(engine, 'states', 'ix_states_entity_id_created')\\n _drop_index(engine, 'states', 'states__state_changes')\\n _drop_index(engine, 'states', 'states__significant_changes')\\n _drop_index(engine, 'states', 'ix_states_entity_id_created')\\n _create_index(engine, 'states', 'ix_states_entity_id_last_updated')\\n else:\\n raise ValueError('No schema migration defined for version {}'.format(new_version))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _apply_update(engine, new_version, old_version):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"Main function\\n \\\"\\\"\\\"\\n generate_transaction_docs()\\n generate_vote_docs()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global templatetags_modules\\n if (not templatetags_modules):\\n _templatetags_modules = []\\n for app_module in (['django'] + list(settings.INSTALLED_APPS)):\\n try:\\n templatetag_module = ('%s.templatetags' % app_module)\\n import_module(templatetag_module)\\n _templatetags_modules.append(templatetag_module)\\n except ImportError:\\n continue\\n templatetags_modules = _templatetags_modules\\n return templatetags_modules\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_templatetags_modules():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n (l, b, w, h) = bbox.get_bounds()\\n r = Rectangle(xy=(l, b), width=w, height=h, edgecolor=color, fill=False)\\n if (trans is not None):\\n r.set_transform(trans)\\n r.set_clip_on(False)\\n r.draw(renderer)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def draw_bbox(bbox, renderer, color='k', trans=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _i18n_cache_key_suffix(request, cache_key):\\n\\n ''''If necessary, adds the current locale or time zone to the cache key.'\\n '''\",\"targets\":\"if (settings.USE_I18N or settings.USE_L10N):\\n cache_key += (u'.%s' % getattr(request, u'LANGUAGE_CODE', get_language()))\\n if settings.USE_TZ:\\n tz_name = force_text(get_current_timezone_name(), errors=u'ignore')\\n cache_key += (u'.%s' % tz_name.encode(u'ascii', u'ignore').decode(u'ascii').replace(u' ', u'_'))\\n return cache_key\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dictfind(dictionary, element):\",\"targets\":\"\\\"\\\"\\\"Returns a key whose value in `dictionary` is `element`\\n or, if none exists, None.\\n \\\"\\\"\\\"\\n for (key, value) in dictionary.iteritems():\\n if (element is value):\\n return key\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef find_strings(filename):\\n\\n ''''Return a dict of possible docstring positions.\\n The dict maps line numbers to strings. There is an entry for\\n line that contains only a string or a part of a triple-quoted\\n string.'\\n '''\",\"targets\":\"d = {}\\n prev_ttype = token.INDENT\\n f = open(filename)\\n for (ttype, tstr, start, end, line) in tokenize.generate_tokens(f.readline):\\n if (ttype == token.STRING):\\n if (prev_ttype == token.INDENT):\\n (sline, scol) = start\\n (eline, ecol) = end\\n for i in range(sline, (eline + 1)):\\n d[i] = 1\\n prev_ttype = ttype\\n f.close()\\n return d\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n check_call(['git', 'checkout', '-b', name])\\n\\n\\nWhat's a good function header?\",\"targets\":\"def git_new_branch(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_course_enrollments(student_id):\",\"targets\":\"\\\"\\\"\\\"Stubbed out Enrollment data request.\\n \\\"\\\"\\\"\\n return _ENROLLMENTS\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def map_reduce(inputs, mapper, reducer):\",\"targets\":\"\\\"\\\"\\\"runs MapReduce on the inputs using mapper and reducer\\n \\\"\\\"\\\"\\n collector = defaultdict(list)\\n for input in inputs:\\n for (key, value) in mapper(input):\\n collector[key].append(value)\\n return [output for (key, values) in collector.iteritems() for output in reducer(key, values)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def inject_rename_contenttypes_operations(plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Insert a `RenameContentType` operation after every planned `RenameModel`\\n operation.\\n \\\"\\\"\\\"\\n if (plan is None):\\n return\\n try:\\n ContentType = apps.get_model('contenttypes', 'ContentType')\\n except LookupError:\\n available = False\\n else:\\n if (not router.allow_migrate_model(using, ContentType)):\\n return\\n available = True\\n for (migration, backward) in plan:\\n if ((migration.app_label, migration.name) == ('contenttypes', '0001_initial')):\\n if backward:\\n break\\n else:\\n available = True\\n continue\\n if (not available):\\n continue\\n inserts = []\\n for (index, operation) in enumerate(migration.operations):\\n if isinstance(operation, migrations.RenameModel):\\n operation = RenameContentType(migration.app_label, operation.old_name_lower, operation.new_name_lower)\\n inserts.append(((index + 1), operation))\\n for (inserted, (index, operation)) in enumerate(inserts):\\n migration.operations.insert((inserted + index), operation)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def decorator(f):\\n @wraps(f)\\n def decorated_func(request, *args, **kwargs):\\n if (request.method == 'OPTIONS'):\\n if (('HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META) and ('HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META)):\\n response = http.HttpResponse()\\n response['Access-Control-Allow-Methods'] = ', '.join(methods)\\n response['Access-Control-Allow-Headers'] = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']\\n else:\\n return http.HttpResponseBadRequest()\\n elif (request.method in methods):\\n response = f(request, *args, **kwargs)\\n else:\\n return http.HttpResponseBadRequest()\\n response['Access-Control-Allow-Origin'] = origin\\n return response\\n return decorated_func\\n return decorator\\n\\n\\nWhat's a good function header?\",\"targets\":\"def cors_enabled(origin, methods=['GET']):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (module_name in modnames):\\n return\\n try:\\n mock = _ModuleMock()\\n mock.LOCALEPATH = osp.join(plugin_path, module_name, 'locale')\\n sys.modules[module_name] = mock\\n if osp.isdir(osp.join(plugin_path, module_name)):\\n module = _import_module_from_path(module_name, plugin_path)\\n else:\\n module = None\\n if module:\\n sys.modules[module_name] = module\\n modlist.append(module)\\n modnames.append(module_name)\\n except Exception:\\n sys.stderr.write('ERROR: 3rd party plugin import failed for `{0}`\\\\n'.format(module_name))\\n traceback.print_exc(file=sys.stderr)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _import_plugin(module_name, plugin_path, modnames, modlist):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _makeRequestProxyFactory(clsToWrap):\\n\\n ''''Return a callable that proxies instances of C{clsToWrap} via\\n L{_IDeprecatedHTTPChannelToRequestInterface}.\\n @param clsToWrap: The class whose instances will be proxied.\\n @type cls: L{_IDeprecatedHTTPChannelToRequestInterface}\\n implementer.\\n @return: A factory that returns\\n L{_IDeprecatedHTTPChannelToRequestInterface} proxies.\\n @rtype: L{callable} whose interface matches C{clsToWrap}\\\\'s constructor.'\\n '''\",\"targets\":\"def _makeRequestProxy(*args, **kwargs):\\n instance = clsToWrap(*args, **kwargs)\\n return _IDeprecatedHTTPChannelToRequestInterfaceProxy(instance)\\n directlyProvides(_makeRequestProxy, providedBy(clsToWrap))\\n return _makeRequestProxy\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef ext_pillar(minion_id, pillar, conf):\\n\\n ''''Parse varstack data and return the result'\\n '''\",\"targets\":\"vs = varstack.Varstack(config_filename=conf)\\n return vs.evaluate(__grains__)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n new_words = []\\n new_word = u''\\n for (index, word) in enumerate(words):\\n pre_word = u''\\n if ((index - 1) >= 0):\\n pre_word = words[(index - 1)]\\n if ((pre_word in u'#([!~^:') or (word[0] in u'[]]);,:?.^')):\\n new_word += word\\n elif (word == u'('):\\n if (pre_word in (u'if', u'for', u'while', u'switch', u')')):\\n new_words.append(new_word)\\n new_word = word\\n elif (pre_word[(-1)] in u'+-*\\/%<>!=&|^'):\\n new_words.append(new_word)\\n new_word = word\\n elif ((len(words) > 1) and ((words[0] + words[1]) == u'#define')):\\n is_define_func = False\\n if (u')' in words):\\n index = words.index(u')')\\n if words[(index + 1):]:\\n is_define_func = True\\n if is_define_func:\\n new_word += word\\n else:\\n new_words.append(new_word)\\n new_word = word\\n else:\\n new_word += word\\n elif (word == u'='):\\n if (pre_word in u'+-*\\/%<>!=&|^'):\\n new_word += word\\n else:\\n new_words.append(new_word)\\n new_word = word\\n elif (pre_word == u'+'):\\n if (word in u'+'):\\n new_word += word\\n else:\\n new_words.append(new_word)\\n new_word = word\\n elif (pre_word == u'-'):\\n if (word in u'->'):\\n new_word += word\\n else:\\n is_negtive = False\\n pre_2_index = (index - 2)\\n if (pre_2_index >= 0):\\n pre_2_word = words[(index - 2)]\\n if (pre_2_word[(-1)] not in (none_operator_chars + u')]')):\\n is_negtive = True\\n if is_negtive:\\n new_word += word\\n else:\\n new_words.append(new_word)\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def regular_chars(words):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n newdict = dict()\\n for (k, v) in instance.items():\\n if isinstance(v, datetime.datetime):\\n v = v.replace(tzinfo=None)\\n elif (k == 'fault'):\\n continue\\n elif (k == 'pci_devices'):\\n continue\\n newdict[k] = v\\n return newdict\\n\\n\\nWhat's a good function header?\",\"targets\":\"def unify_instance(instance):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n name = name.lower()\\n for ending in ('tar', 'tar.gz', 'tar.bz2', 'tar.xz', 'tgz', 'tbz2', 'txz', 'tar.lzma', 'tlz'):\\n if name.endswith(('.' + ending)):\\n return 'tar'\\n for ending in ('zip', 'rar'):\\n if name.endswith(('.' + ending)):\\n return ending\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def guess_archive_type(name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n logger = logging.getLogger(__name__)\\n handler = logging.StreamHandler()\\n handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))\\n logger.addHandler(handler)\\n logger.setLevel(level)\\n logger.debug(('Added a stderr logging handler to logger: %s' % __name__))\\n return handler\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_stderr_logger(level=logging.DEBUG):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@cachedmethod\\ndef asciifyUrl(url, forceQuote=False):\\n\\n ''''Attempts to make a unicode URL usuable with ``urllib\\/urllib2``.\\n More specifically, it attempts to convert the unicode object ``url``,\\n which is meant to represent a IRI, to an unicode object that,\\n containing only ASCII characters, is a valid URI. This involves:\\n * IDNA\\/Puny-encoding the domain name.\\n * UTF8-quoting the path and querystring parts.\\n See also RFC 3987.\\n Reference: http:\\/\\/blog.elsdoerfer.name\\/2008\\/12\\/12\\/opening-iris-in-python\\/\\n >>> asciifyUrl(u\\\\'http:\\/\\/www.\\\\u0161u\\\\u0107uraj.com\\\\')\\n u\\\\'http:\\/\\/www.xn--uuraj-gxa24d.com\\\\''\\n '''\",\"targets\":\"parts = urlparse.urlsplit(url)\\n if ((not parts.scheme) or (not parts.netloc)):\\n return url\\n if all(((char in string.printable) for char in url)):\\n return url\\n try:\\n hostname = parts.hostname.encode('idna')\\n except LookupError:\\n hostname = parts.hostname.encode(UNICODE_ENCODING)\\n def quote(s, safe):\\n s = (s or '')\\n if ((s.encode('ascii', 'replace') != s) or forceQuote):\\n return urllib.quote(s.encode(UNICODE_ENCODING), safe=safe)\\n return s\\n username = quote(parts.username, '')\\n password = quote(parts.password, safe='')\\n path = quote(parts.path, safe='\\/')\\n query = quote(parts.query, safe='&=')\\n netloc = hostname\\n if (username or password):\\n netloc = ('@' + netloc)\\n if password:\\n netloc = ((':' + password) + netloc)\\n netloc = (username + netloc)\\n try:\\n port = parts.port\\n except:\\n port = None\\n if port:\\n netloc += (':' + str(port))\\n return urlparse.urlunsplit([parts.scheme, netloc, path, query, parts.fragment])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from r2.lib.pages import VerifyEmail\\n user.email_verified = False\\n user._commit()\\n Award.take_away('verified_email', user)\\n token = EmailVerificationToken._new(user)\\n base = (g.https_endpoint or g.origin)\\n emaillink = ((base + '\\/verification\\/') + token._id)\\n if dest:\\n emaillink += ('?dest=%s' % dest)\\n g.log.debug(('Generated email verification link: ' + emaillink))\\n _system_email(user.email, VerifyEmail(user=user, emaillink=emaillink).render(style='email'), Email.Kind.VERIFY_EMAIL)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def verify_email(user, dest=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def decipher_bifid6(msg, key):\",\"targets\":\"\\\"\\\"\\\"Performs the Bifid cipher decryption on ciphertext ``msg``, and\\n returns the plaintext.\\n This is the version of the Bifid cipher that uses the `6 \\\\times 6`\\n Polybius square.\\n INPUT:\\n ``msg``: ciphertext string (digits okay); converted to upper case\\n ``key``: short string for key (digits okay). If ``key`` is\\n less than 36 characters long, the square will be filled with\\n letters A through Z and digits 0 through 9. All letters are\\n converted to uppercase.\\n OUTPUT:\\n plaintext from Bifid cipher (all caps, no spaces)\\n Examples\\n >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6\\n >>> key = \\\"gold bug\\\"\\n >>> encipher_bifid6(\\\\meet me on monday at 8am\\\\, key)\\n \\\\KFKLJJHF5MMMKTFRGPL\\\\\\n >>> decipher_bifid6(_, key)\\n \\\\MEETMEONMONDAYAT8AM\\\\\\n \\\"\\\"\\\"\\n (msg, key, _) = _prep(msg.upper(), key.upper(), None, bifid6)\\n key = padded_key(key, bifid6)\\n return decipher_bifid(msg, '', key)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n cj2 = cookiejar_from_dict(cookie_dict)\\n for cookie in cj2:\\n cj.set_cookie(cookie)\\n return cj\\n\\n\\nWhat's a good function header?\",\"targets\":\"def add_dict_to_cookiejar(cj, cookie_dict):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def absent(name, database, **client_args):\",\"targets\":\"\\\"\\\"\\\"Ensure that given retention policy is absent.\\n name\\n Name of the retention policy to remove.\\n database\\n Name of the database that the retention policy was defined on.\\n \\\"\\\"\\\"\\n ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'retention policy {0} is not present'.format(name)}\\n if __salt__['influxdb.retention_policy_exists'](database, name, **client_args):\\n if __opts__['test']:\\n ret['result'] = None\\n ret['comment'] = 'retention policy {0} is present and needs to be removed'.format(name)\\n return ret\\n if __salt__['influxdb.drop_retention_policy'](database, name, **client_args):\\n ret['comment'] = 'retention policy {0} has been removed'.format(name)\\n ret['changes'][name] = 'Absent'\\n return ret\\n else:\\n ret['comment'] = 'Failed to remove retention policy {0}'.format(name)\\n ret['result'] = False\\n return ret\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Condition(*args, **kwargs):\\n\\n ''''Factory function that returns a new condition variable object.\\n A condition variable allows one or more threads to wait until they are\\n notified by another thread.\\n If the lock argument is given and not None, it must be a Lock or RLock\\n object, and it is used as the underlying lock. Otherwise, a new RLock object\\n is created and used as the underlying lock.'\\n '''\",\"targets\":\"return _Condition(*args, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (not batch_size):\\n batch_size = FLAGS.batch_size\\n sparse_labels = tf.reshape(labels, [batch_size, 1])\\n indices = tf.reshape(tf.range(batch_size), [batch_size, 1])\\n concated = tf.concat(axis=1, values=[indices, sparse_labels])\\n num_classes = logits[0].get_shape()[(-1)].value\\n dense_labels = tf.sparse_to_dense(concated, [batch_size, num_classes], 1.0, 0.0)\\n slim.losses.cross_entropy_loss(logits[0], dense_labels, label_smoothing=0.1, weight=1.0)\\n slim.losses.cross_entropy_loss(logits[1], dense_labels, label_smoothing=0.1, weight=0.4, scope='aux_loss')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def loss(logits, labels, batch_size=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def legalize_path(path, replacements, length, extension, fragment):\",\"targets\":\"\\\"\\\"\\\"Given a path-like Unicode string, produce a legal path. Return\\n the path and a flag indicating whether some replacements had to be\\n ignored (see below).\\n The legalization process (see `_legalize_stage`) consists of\\n applying the sanitation rules in `replacements`, encoding the string\\n to bytes (unless `fragment` is set), truncating components to\\n `length`, appending the `extension`.\\n This function performs up to three calls to `_legalize_stage` in\\n case truncation conflicts with replacements (as can happen when\\n truncation creates whitespace at the end of the string, for\\n example). The limited number of iterations iterations avoids the\\n possibility of an infinite loop of sanitation and truncation\\n operations, which could be caused by replacement rules that make the\\n string longer. The flag returned from this function indicates that\\n the path has to be truncated twice (indicating that replacements\\n made the string longer again after it was truncated); the\\n application should probably log some sort of warning.\\n \\\"\\\"\\\"\\n if fragment:\\n extension = extension.decode('utf-8', 'ignore')\\n (first_stage_path, _) = _legalize_stage(path, replacements, length, extension, fragment)\\n (first_stage_path, _) = os.path.splitext(displayable_path(first_stage_path))\\n (second_stage_path, retruncated) = _legalize_stage(first_stage_path, replacements, length, extension, fragment)\\n if retruncated:\\n (second_stage_path, _) = _legalize_stage(first_stage_path, None, length, extension, fragment)\\n return (second_stage_path, retruncated)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_requester(user_id, access_token_id=None, is_guest=False, device_id=None, app_service=None):\",\"targets\":\"\\\"\\\"\\\"Create a new ``Requester`` object\\n Args:\\n user_id (str|UserID): id of the user making the request\\n access_token_id (int|None): *ID* of the access token used for this\\n request, or None if it came via the appservice API or similar\\n is_guest (bool): True if the user making this request is a guest user\\n device_id (str|None): device_id which was set at authentication time\\n app_service (ApplicationService|None): the AS requesting on behalf of the user\\n Returns:\\n Requester\\n \\\"\\\"\\\"\\n if (not isinstance(user_id, UserID)):\\n user_id = UserID.from_string(user_id)\\n return Requester(user_id, access_token_id, is_guest, device_id, app_service)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n posts = [getattr(generator, attr, None) for attr in PROCESS if (getattr(generator, attr, None) is not None)]\\n for post in posts[0]:\\n if ((not ('SHOW_SOURCE_ON_SIDEBAR' in generator.settings)) and (not ('SHOW_SOURCE_IN_SECTION' in generator.settings))):\\n return\\n if (('SHOW_SOURCE_ALL_POSTS' in generator.settings) or ('show_source' in post.metadata)):\\n show_source_filename = generator.settings.get('SHOW_SOURCE_FILENAME', '{}.txt'.format(post.slug))\\n try:\\n source_out = os.path.join(post.settings['OUTPUT_PATH'], post.save_as)\\n source_out_path = os.path.split(source_out)[0]\\n copy_to = os.path.join(source_out_path, show_source_filename)\\n source_url = urljoin(post.save_as, show_source_filename)\\n except Exception:\\n return\\n out = dict()\\n out['copy_raw_from'] = post.source_path\\n out['copy_raw_to'] = copy_to\\n logger.debug('Linked %s to %s', post.source_path, copy_to)\\n source_files.append(out)\\n post.show_source_url = source_url\\n\\n\\nWhat's a good function header?\",\"targets\":\"def link_source_files(generator):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef _is_attribute_explicitly_set(attribute_name, resource, target):\\n\\n ''''Verify that an attribute is present and has a non-default value'\\n '''\",\"targets\":\"return (('default' in resource[attribute_name]) and (attribute_name in target) and (target[attribute_name] is not attributes.ATTR_NOT_SPECIFIED) and (target[attribute_name] != resource[attribute_name]['default']))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_observer(settings):\",\"targets\":\"\\\"\\\"\\\"Return an observer for the docutils Reporter.\\n \\\"\\\"\\\"\\n def observer(msg):\\n 'Report docutils\\/rest messages to a Nikola user.\\\\n\\\\n Error code mapping:\\\\n\\\\n +------+---------+------+----------+\\\\n | dNUM | dNAME | lNUM | lNAME | d = docutils, l = logbook\\\\n +------+---------+------+----------+\\\\n | 0 | DEBUG | 1 | DEBUG |\\\\n | 1 | INFO | 2 | INFO |\\\\n | 2 | WARNING | 4 | WARNING |\\\\n | 3 | ERROR | 5 | ERROR |\\\\n | 4 | SEVERE | 6 | CRITICAL |\\\\n +------+---------+------+----------+\\\\n '\\n errormap = {0: 1, 1: 2, 2: 4, 3: 5, 4: 6}\\n text = docutils.nodes.Element.astext(msg)\\n line = ((msg['line'] + settings['add_ln']) if ('line' in msg) else 0)\\n out = '[{source}{colon}{line}] {text}'.format(source=settings['source'], colon=(':' if line else ''), line=line, text=text)\\n settings['logger'].log(errormap[msg['level']], out)\\n return observer\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n global options\\n options = opt\\n for fn in pre_configure:\\n fn(options, file_config)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def pre_begin(opt):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def basename(p):\",\"targets\":\"\\\"\\\"\\\"Returns the final component of a pathname\\n \\\"\\\"\\\"\\n return split(p)[1]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n base_url = ((base_url + 'users\\/') + username)\\n try:\\n url = (base_url + '\\/contributions')\\n page = urlopen(url)\\n except (HTTPError, URLError) as e:\\n print 'There was a problem fetching data from {0}'.format(url)\\n print e\\n raise SystemExit\\n return page.read().decode('utf-8')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def retrieve_contributions_calendar(username, base_url):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def flatten(debug=False):\",\"targets\":\"\\\"\\\"\\\"Wrap response.body in a generator that recursively iterates over body.\\n This allows cherrypy.response.body to consist of \\\\nested generators\\\\;\\n that is, a set of generators that yield generators.\\n \\\"\\\"\\\"\\n import types\\n def flattener(input):\\n numchunks = 0\\n for x in input:\\n if (not isinstance(x, types.GeneratorType)):\\n numchunks += 1\\n (yield x)\\n else:\\n for y in flattener(x):\\n numchunks += 1\\n (yield y)\\n if debug:\\n cherrypy.log(('Flattened %d chunks' % numchunks), 'TOOLS.FLATTEN')\\n response = cherrypy.serving.response\\n response.body = flattener(response.body)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef associate(qs, assoc_secret, assoc_handle):\\n\\n ''''Do the server\\\\'s half of the associate call, using the given\\n secret and handle.'\\n '''\",\"targets\":\"q = parseQuery(qs)\\n assert (q['openid.mode'] == 'associate')\\n assert (q['openid.assoc_type'] == 'HMAC-SHA1')\\n reply_dict = {'assoc_type': 'HMAC-SHA1', 'assoc_handle': assoc_handle, 'expires_in': '600'}\\n if (q.get('openid.session_type') == 'DH-SHA1'):\\n assert ((len(q) == 6) or (len(q) == 4))\\n message = Message.fromPostArgs(q)\\n session = DiffieHellmanSHA1ServerSession.fromMessage(message)\\n reply_dict['session_type'] = 'DH-SHA1'\\n else:\\n assert (len(q) == 2)\\n session = PlainTextServerSession.fromQuery(q)\\n reply_dict.update(session.answer(assoc_secret))\\n return kvform.dictToKV(reply_dict)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef display_output(data, out=None, opts=None, **kwargs):\\n\\n ''''Print the passed data using the desired output'\\n '''\",\"targets\":\"if (opts is None):\\n opts = {}\\n display_data = try_printout(data, out, opts, **kwargs)\\n output_filename = opts.get('output_file', None)\\n log.trace('data = {0}'.format(data))\\n try:\\n if output_filename:\\n if (not hasattr(output_filename, 'write')):\\n ofh = salt.utils.files.fopen(output_filename, 'a')\\n fh_opened = True\\n else:\\n ofh = output_filename\\n fh_opened = False\\n try:\\n fdata = display_data\\n if isinstance(fdata, six.text_type):\\n try:\\n fdata = fdata.encode('utf-8')\\n except (UnicodeDecodeError, UnicodeEncodeError):\\n pass\\n if fdata:\\n if six.PY3:\\n ofh.write(fdata.decode())\\n else:\\n ofh.write(fdata)\\n ofh.write('\\\\n')\\n finally:\\n if fh_opened:\\n ofh.close()\\n return\\n if display_data:\\n salt.utils.print_cli(display_data)\\n except IOError as exc:\\n if (exc.errno != errno.EPIPE):\\n raise exc\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_domains(api_key=None):\",\"targets\":\"\\\"\\\"\\\"Get a list of all domains.\\n Sample response:\\n \\\"total_count\\\": 1,\\n \\\"items\\\": [\\n \\\"created_at\\\": \\\"Wed, 10 Jul 2013 19:26:52 GMT\\\",\\n \\\"smtp_login\\\": \\\"postmaster@samples.mailgun.org\\\",\\n \\\"name\\\": \\\"samples.mailgun.org\\\",\\n \\\"smtp_password\\\": \\\"4rtqo4p6rrx9\\\",\\n \\\"wildcard\\\": true,\\n \\\"spam_action\\\": \\\"disabled\\\",\\n \\\"state\\\": \\\"active\\\"\\n Get a list of all domains.\\n \\\"\\\"\\\"\\n return requests.get('https:\\/\\/api.mailgun.net\\/v3\\/domains', auth=('api', api_key), params={'skip': 0, 'limit': 3})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef expect_discrete(self, fn=None, args=(), loc=0, lb=None, ub=None, conditional=False):\\n\\n ''''calculate expected value of a function with respect to the distribution\\n for discrete distribution\\n Parameters\\n (self : distribution instance as defined in scipy stats)\\n fn : function (default: identity mapping)\\n Function for which integral is calculated. Takes only one argument.\\n args : tuple\\n argument (parameters) of the distribution\\n optional keyword parameters\\n lb, ub : numbers\\n lower and upper bound for integration, default is set to the support\\n of the distribution, lb and ub are inclusive (ul<=k<=ub)\\n conditional : boolean (False)\\n If true then the expectation is corrected by the conditional\\n probability of the integration interval. The return value is the\\n expectation of the function, conditional on being in the given\\n interval (k such that ul<=k<=ub).\\n Returns\\n expected value : float\\n Notes\\n * function is not vectorized\\n * accuracy: uses self.moment_tol as stopping criterium\\n for heavy tailed distribution e.g. zipf(4), accuracy for\\n mean, variance in example is only 1e-5,\\n increasing precision (moment_tol) makes zipf very slow\\n * suppnmin=100 internal parameter for minimum number of points to evaluate\\n could be added as keyword parameter, to evaluate functions with\\n non-monotonic shapes, points include integers in (-suppnmin, suppnmin)\\n * uses maxcount=1000 limits the number of points that are evaluated\\n to break loop for infinite sums\\n (a maximum of suppnmin+1000 positive plus suppnmin+1000 negative integers\\n are evaluated)'\\n '''\",\"targets\":\"maxcount = 1000\\n suppnmin = 100\\n if (fn is None):\\n def fun(x):\\n return ((x + loc) * self._pmf(x, *args))\\n else:\\n def fun(x):\\n return (fn((x + loc)) * self._pmf(x, *args))\\n self._argcheck(*args)\\n if (lb is None):\\n lb = self.a\\n else:\\n lb = (lb - loc)\\n if (ub is None):\\n ub = self.b\\n else:\\n ub = (ub - loc)\\n if conditional:\\n invfac = (self.sf(lb, *args) - self.sf((ub + 1), *args))\\n else:\\n invfac = 1.0\\n tot = 0.0\\n (low, upp) = (self._ppf(0.001, *args), self._ppf(0.999, *args))\\n low = max(min((- suppnmin), low), lb)\\n upp = min(max(suppnmin, upp), ub)\\n supp = np.arange(low, (upp + 1), self.inc)\\n tot = np.sum(fun(supp))\\n diff = 1e+100\\n pos = (upp + self.inc)\\n count = 0\\n while ((pos <= ub) and (diff > self.moment_tol) and (count <= maxcount)):\\n diff = fun(pos)\\n tot += diff\\n pos += self.inc\\n count += 1\\n if (self.a < 0):\\n diff = 1e+100\\n pos = (low - self.inc)\\n while ((pos >= lb) and (diff > self.moment_tol) and (count <= maxcount)):\\n diff = fun(pos)\\n tot += diff\\n pos -= self.inc\\n count += 1\\n if (count > maxcount):\\n print('sum did not converge')\\n return (tot \\/ invfac)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def init_logger():\",\"targets\":\"\\\"\\\"\\\"Initialize the south logger\\n \\\"\\\"\\\"\\n logger = logging.getLogger('south')\\n logger.addHandler(NullHandler())\\n return logger\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def wrapper(func):\\n memoized_func = memoized(func)\\n @functools.wraps(func)\\n def wrapped(*args, **kwargs):\\n args = list(args)\\n request = args.pop(request_index)\\n args.insert(request_index, request_func(request))\\n return memoized_func(*args, **kwargs)\\n return wrapped\\n return wrapper\\n\\n\\nWhat's a good function header?\",\"targets\":\"def memoized_with_request(request_func, request_index=0):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def colored(text, color=None, on_color=None, attrs=None):\",\"targets\":\"\\\"\\\"\\\"Colorize text.\\n Available text colors:\\n red, green, yellow, blue, magenta, cyan, white.\\n Available text highlights:\\n on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.\\n Available attributes:\\n bold, dark, underline, blink, reverse, concealed.\\n Example:\\n colored(\\\\Hello, World!\\\\, \\\\red\\\\, \\\\on_grey\\\\, [\\\\blue\\\\, \\\\blink\\\\])\\n colored(\\\\Hello, World!\\\\, \\\\green\\\\)\\n \\\"\\\"\\\"\\n if (os.getenv('ANSI_COLORS_DISABLED') is None):\\n fmt_str = '\\\\x1b[%dm%s'\\n if (color is not None):\\n text = (fmt_str % (COLORS[color], text))\\n if (on_color is not None):\\n text = (fmt_str % (HIGHLIGHTS[on_color], text))\\n if (attrs is not None):\\n for attr in attrs:\\n text = (fmt_str % (ATTRIBUTES[attr], text))\\n if (color is not None):\\n text += RESET\\n return text\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef calc_hash(type, content):\\n\\n ''''Calculate some content\\\\'s hash in the Git fashion.'\\n '''\",\"targets\":\"header = ('%s %d\\\\x00' % (type, len(content)))\\n sum = Sha1(header)\\n sum.update(content)\\n return sum.digest()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def conv1d(x, kernel, strides=1, padding='valid', data_format=None, dilation_rate=1):\",\"targets\":\"\\\"\\\"\\\"1D convolution.\\n # Arguments\\n kernel: kernel tensor.\\n strides: stride integer.\\n padding: string, `\\\"same\\\"`, `\\\"causal\\\"` or `\\\"valid\\\"`.\\n data_format: string, one of \\\"channels_last\\\", \\\"channels_first\\\"\\n dilation_rate: integer.\\n \\\"\\\"\\\"\\n if (data_format is None):\\n data_format = image_data_format()\\n if (data_format not in {'channels_first', 'channels_last'}):\\n raise ValueError('Unknown data_format ', data_format)\\n if hasattr(kernel, '_keras_shape'):\\n kernel_shape = kernel._keras_shape\\n else:\\n kernel_shape = None\\n if (padding == 'causal'):\\n if (not kernel_shape):\\n raise AttributeError('Causal padding requires kernel._keras_shape set.')\\n left_pad = (dilation_rate * (kernel_shape[0] - 1))\\n x = temporal_padding(x, (left_pad, 0))\\n padding = 'valid'\\n if hasattr(x, '_keras_shape'):\\n shape = x._keras_shape\\n else:\\n shape = None\\n if (data_format == 'channels_last'):\\n x = expand_dims(x, 2)\\n if (shape is not None):\\n x._keras_shape = (shape[0], shape[1], 1, shape[2])\\n else:\\n x = expand_dims(x, 3)\\n if (shape is not None):\\n x._keras_shape = (shape[0], shape[1], shape[2], 1)\\n dilation_rate = (dilation_rate, 1)\\n strides = (strides, 1)\\n kernel = expand_dims(kernel, 1)\\n output = conv2d(x, kernel, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate)\\n if (data_format == 'channels_last'):\\n output = squeeze(output, 2)\\n else:\\n output = squeeze(output, 3)\\n return output\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef default_payment_handler(request, order_form, order):\\n\\n ''''Default payment handler - called when the final step of the\\n checkout process with payment information is submitted. Implement\\n your own and specify the path to import it from via the setting\\n ``SHOP_HANDLER_PAYMENT``. This function will typically contain\\n integration with a payment gateway. Raise\\n cartridge.shop.checkout.CheckoutError(\\\"error message\\\") if payment\\n is unsuccessful.'\\n '''\",\"targets\":\"pass\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def headers_to_dict(header_lines):\",\"targets\":\"\\\"\\\"\\\"Convert the list of header lines into a dictionary\\n \\\"\\\"\\\"\\n headers = {}\\n headers_list = [x for line in header_lines for x in line.split(': ', 1)]\\n headers_dict = dict(zip(headers_list[0::2], headers_list[1::2]))\\n for header in headers_dict:\\n headers[header.lower()] = headers_dict[header]\\n return headers\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def _round(a):\",\"targets\":\"\\\"\\\"\\\"Always round up.\\n ``np.round`` cannot be used here, because it rounds .5 to the nearest\\n even number.\\n \\\"\\\"\\\"\\n return int(np.floor((a + 0.5)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n page_html = ((Path(ctx.config.sphinx.destdir) \\/ 'html') \\/ 'index.html')\\n if (not page_html.exists()):\\n build(ctx, builder='html')\\n assert page_html.exists()\\n open_cmd = 'open'\\n if sys.platform.startswith('win'):\\n open_cmd = 'start'\\n ctx.run('{open} {page_html}'.format(open=open_cmd, page_html=page_html))\\n\\n\\nWhat's a good function header?\",\"targets\":\"@task\\ndef browse(ctx):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (r.representation == 'html'):\\n rheader_tabs = s3_rheader_tabs(r, tabs)\\n assess = r.record\\n if assess:\\n table = db.assess_assess\\n rheader = DIV(TABLE(TR(TH(('%s: ' % T('Date & Time'))), table.datetime.represent(assess.datetime), TH(('%s: ' % T('Location'))), table.location_id.represent(assess.location_id), TH(('%s: ' % T('Assessor'))), table.assessor_person_id.represent(assess.assessor_person_id))), rheader_tabs)\\n return rheader\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def assess_rheader(r, tabs=[]):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef is_ethernet_port(interface):\\n\\n ''''Judge whether it is ethernet port'\\n '''\",\"targets\":\"ethernet_port = ['ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'meth']\\n if_type = get_interface_type(interface)\\n if (if_type in ethernet_port):\\n return True\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n node = MockNode(manufacturer_id='0086', product_id='0062', command_classes=[const.COMMAND_CLASS_SWITCH_COLOR])\\n value = MockValue(data=0, node=node)\\n color = MockValue(data='#0000000000', node=node)\\n color_channels = MockValue(data=31, node=node)\\n values = MockLightValues(primary=value, color=color, color_channels=color_channels)\\n device = zwave.get_device(node=node, values=values, node_config={})\\n assert (device.color_temp == zwave.TEMP_MID_HASS)\\n color.data = '#000000ff00'\\n value_changed(color)\\n assert (device.color_temp == zwave.TEMP_WARM_HASS)\\n color.data = '#00000000ff'\\n value_changed(color)\\n assert (device.color_temp == zwave.TEMP_COLD_HASS)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_ct_value_changed(mock_openzwave):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef __virtual__():\\n\\n ''''Only load if boto libraries exist and if boto libraries are greater than\\n a given version.'\\n '''\",\"targets\":\"if (not HAS_BOTO3):\\n return (False, 'The boto3_elasticache module could not be loaded: boto3 libraries not found')\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef items_for_result(cl, result, form):\\n\\n ''''Generates the actual list of data.'\\n '''\",\"targets\":\"first = True\\n pk = cl.lookup_opts.pk.attname\\n for field_name in cl.list_display:\\n row_class = ''\\n try:\\n (f, attr, value) = lookup_field(field_name, result, cl.model_admin)\\n except (AttributeError, ObjectDoesNotExist):\\n result_repr = EMPTY_CHANGELIST_VALUE\\n else:\\n if (f is None):\\n if (field_name == u'action_checkbox'):\\n row_class = ' class=\\\"action-checkbox\\\"'\\n allow_tags = getattr(attr, 'allow_tags', False)\\n boolean = getattr(attr, 'boolean', False)\\n if boolean:\\n allow_tags = True\\n result_repr = _boolean_icon(value)\\n else:\\n result_repr = smart_unicode(value)\\n if (not allow_tags):\\n result_repr = escape(result_repr)\\n else:\\n result_repr = mark_safe(result_repr)\\n else:\\n if isinstance(f.rel, models.ManyToOneRel):\\n field_val = getattr(result, f.name)\\n if (field_val is None):\\n result_repr = EMPTY_CHANGELIST_VALUE\\n else:\\n result_repr = escape(field_val)\\n else:\\n result_repr = display_for_field(value, f)\\n if (isinstance(f, models.DateField) or isinstance(f, models.TimeField) or isinstance(f, models.ForeignKey)):\\n row_class = ' class=\\\"nowrap\\\"'\\n if (force_unicode(result_repr) == ''):\\n result_repr = mark_safe(' ')\\n if ((first and (not cl.list_display_links)) or (field_name in cl.list_display_links)):\\n table_tag = {True: 'th', False: 'td'}[first]\\n first = False\\n url = cl.url_for_result(result)\\n if cl.to_field:\\n attr = str(cl.to_field)\\n else:\\n attr = pk\\n value = result.serializable_value(attr)\\n result_id =...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n negated = {(- s)}\\n return [(clause - negated) for clause in clauses if (s not in clause)]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def unit_propagate_int_repr(clauses, s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_tiles_height_width(n_tiles, desired_width=None):\\n\\n ''''Get a height x width size that will fit n_tiles tiles.'\\n '''\",\"targets\":\"if (desired_width == None):\\n width = int(np.ceil(np.sqrt(n_tiles)))\\n height = width\\n else:\\n assert isinstance(desired_width, int)\\n width = desired_width\\n height = int(np.ceil((float(n_tiles) \\/ width)))\\n return (height, width)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def is_rfc1918_ip(ip):\",\"targets\":\"\\\"\\\"\\\"Checks if the given ip address is a rfc1918 one.\\n @param ip: The ip address to test\\n @type ip: a string \\\"x.x.x.x\\\"\\n @return: True if it\\\\s a LAN address, False otherwise\\n \\\"\\\"\\\"\\n if isinstance(ip, basestring):\\n ip = _ip_to_number(ip)\\n for (net, mask) in _nets:\\n if ((ip & mask) == net):\\n return True\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def in6_addrtovendor(addr):\",\"targets\":\"\\\"\\\"\\\"Extract the MAC address from a modified EUI-64 constructed IPv6\\n address provided and use the IANA oui.txt file to get the vendor.\\n The database used for the conversion is the one loaded by Scapy,\\n based on Wireshark (\\/usr\\/share\\/wireshark\\/wireshark\\/manuf) None\\n is returned on error, \\\"UNKNOWN\\\" if the vendor is unknown.\\n \\\"\\\"\\\"\\n mac = in6_addrtomac(addr)\\n if (mac is None):\\n return None\\n res = conf.manufdb._get_manuf(mac)\\n if ((len(res) == 17) and (res.count(':') != 5)):\\n res = 'UNKNOWN'\\n return res\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef make_graph(dists, scheme=u'default'):\\n\\n ''''Makes a dependency graph from the given distributions.\\n :parameter dists: a list of distributions\\n :type dists: list of :class:`distutils2.database.InstalledDistribution` and\\n :class:`distutils2.database.EggInfoDistribution` instances\\n :rtype: a :class:`DependencyGraph` instance'\\n '''\",\"targets\":\"scheme = get_scheme(scheme)\\n graph = DependencyGraph()\\n provided = {}\\n for dist in dists:\\n graph.add_distribution(dist)\\n for p in dist.provides:\\n (name, version) = parse_name_and_version(p)\\n logger.debug(u'Add to provided: %s, %s, %s', name, version, dist)\\n provided.setdefault(name, []).append((version, dist))\\n for dist in dists:\\n requires = (((dist.run_requires | dist.meta_requires) | dist.build_requires) | dist.dev_requires)\\n for req in requires:\\n try:\\n matcher = scheme.matcher(req)\\n except UnsupportedVersionError:\\n logger.warning(u'could not read version %r - using name only', req)\\n name = req.split()[0]\\n matcher = scheme.matcher(name)\\n name = matcher.key\\n matched = False\\n if (name in provided):\\n for (version, provider) in provided[name]:\\n try:\\n match = matcher.match(version)\\n except UnsupportedVersionError:\\n match = False\\n if match:\\n graph.add_edge(dist, provider, req)\\n matched = True\\n break\\n if (not matched):\\n graph.add_missing(dist, req)\\n return graph\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (': ' in data):\\n return data.split(': ')[1]\\n if (':\\\\n' in data):\\n return data.split(':\\\\n')[1]\\n else:\\n return data\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_return(data):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n from .models import ImportPurgatory\\n from ..devices.models import Device\\n own_device = Device.get_own_device()\\n if (not src_version):\\n src_version = own_device.get_version()\\n if isinstance(data, ImportPurgatory):\\n purgatory = data\\n data = purgatory.serialized_models\\n else:\\n purgatory = None\\n if (isinstance(data, str) or isinstance(data, unicode)):\\n models = deserialize(data, src_version=src_version, dest_version=own_device.get_version())\\n else:\\n models = deserialize(data, src_version=src_version, dest_version=own_device.get_version())\\n unsaved_models = []\\n exceptions = ''\\n saved_model_count = 0\\n try:\\n for modelwrapper in models:\\n try:\\n model = modelwrapper.object\\n if (not hasattr(model, 'verify')):\\n raise ValidationError(('Cannot save model: %s does not have a verify method (not a subclass of SyncedModel?)' % model.__class__))\\n model._state.adding = False\\n model.full_clean(imported=True)\\n model.save(imported=True, increment_counters=increment_counters)\\n saved_model_count += 1\\n if verbose:\\n print ('IMPORTED %s (id: %s, counter: %d, signed_by: %s)' % (model.__class__.__name__, model.id[0:5], model.counter, model.signed_by.id[0:5]))\\n except ValidationError as e:\\n exceptions += ('%s: %s\\\\n' % (model.pk, e))\\n unsaved_models.append(model)\\n try:\\n if (increment_counters and model.verify()):\\n model.signed_by.set_counter_position(model.counter, soft_set=True)\\n except:\\n pass\\n except Exception as e:\\n exceptions += unicode(e)\\n if unsaved_models:\\n if (not purgatory):\\n purgatory = ImportPurgatory()\\n purgatory.serialized_models = serialize(unsaved_models,...\\n\\nWhat's a good function header?\",\"targets\":\"def save_serialized_models(data, increment_counters=True, src_version=None, verbose=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (resp[:3] != '229'):\\n raise error_reply, resp\\n left = resp.find('(')\\n if (left < 0):\\n raise error_proto, resp\\n right = resp.find(')', (left + 1))\\n if (right < 0):\\n raise error_proto, resp\\n if (resp[(left + 1)] != resp[(right - 1)]):\\n raise error_proto, resp\\n parts = resp[(left + 1):right].split(resp[(left + 1)])\\n if (len(parts) != 5):\\n raise error_proto, resp\\n host = peer[0]\\n port = int(parts[3])\\n return (host, port)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse229(resp, peer):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_validation_errors(outfile, app=None):\\n\\n ''''Validates all models that are part of the specified app. If no app name is provided,\\n validates all models of all installed apps. Writes errors, if any, to outfile.\\n Returns number of errors.'\\n '''\",\"targets\":\"from django.db import models, connection\\n from django.db.models.loading import get_app_errors\\n from django.db.models.fields.related import RelatedObject\\n from django.db.models.deletion import SET_NULL, SET_DEFAULT\\n e = ModelErrorCollection(outfile)\\n for (app_name, error) in get_app_errors().items():\\n e.add(app_name, error)\\n for cls in models.get_models(app, include_swapped=True):\\n opts = cls._meta\\n if opts.swapped:\\n try:\\n (app_label, model_name) = opts.swapped.split('.')\\n except ValueError:\\n e.add(opts, (\\\"%s is not of the form 'app_label.app_name'.\\\" % opts.swappable))\\n continue\\n if (not models.get_model(app_label, model_name)):\\n e.add(opts, (\\\"Model has been swapped out for '%s' which has not been installed or is abstract.\\\" % opts.swapped))\\n continue\\n if (settings.AUTH_USER_MODEL == ('%s.%s' % (opts.app_label, opts.object_name))):\\n if (cls.USERNAME_FIELD in cls.REQUIRED_FIELDS):\\n e.add(opts, 'The field named as the USERNAME_FIELD should not be included in REQUIRED_FIELDS on a swappable User model.')\\n if (not opts.get_field(cls.USERNAME_FIELD).unique):\\n e.add(opts, 'The USERNAME_FIELD must be unique. Add unique=True to the field parameters.')\\n for f in opts.local_fields:\\n if ((f.name == 'id') and (not f.primary_key) and (opts.pk.name == 'id')):\\n e.add(opts, ('\\\"%s\\\": You can\\\\'t use \\\"id\\\" as a field name, because each model automatically gets an \\\"id\\\" field if none of the fields have primary_key=True. You need to either remove\\/rename your \\\"id\\\" field or add primary_key=True to a field.' % f.name))\\n if f.name.endswith('_'):\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def bulk_upload():\",\"targets\":\"\\\"\\\"\\\"Custom view to allow bulk uploading of Photos\\n @ToDo: Allow creation of a GIS Feature Layer to view on the map\\n @ToDo: Allow uploading of associated GPX track for timestamp correlation.\\n See r1595 for the previous draft of this work\\n \\\"\\\"\\\"\\n s3.stylesheets.append('plugins\\/fileuploader.css')\\n return dict()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@cachedmethod\\ndef getConsoleWidth(default=80):\\n\\n ''''Returns console width'\\n '''\",\"targets\":\"width = None\\n if os.getenv('COLUMNS', '').isdigit():\\n width = int(os.getenv('COLUMNS'))\\n else:\\n try:\\n try:\\n FNULL = open(os.devnull, 'w')\\n except IOError:\\n FNULL = None\\n process = subprocess.Popen('stty size', shell=True, stdout=subprocess.PIPE, stderr=(FNULL or subprocess.PIPE))\\n (stdout, _) = process.communicate()\\n items = stdout.split()\\n if ((len(items) == 2) and items[1].isdigit()):\\n width = int(items[1])\\n except (OSError, MemoryError):\\n pass\\n if (width is None):\\n try:\\n import curses\\n stdscr = curses.initscr()\\n (_, width) = stdscr.getmaxyx()\\n curses.endwin()\\n except:\\n pass\\n return (width or default)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if ('openstack_config.get' not in __salt__):\\n return False\\n if ('openstack_config.set' not in __salt__):\\n return False\\n if ('openstack_config.delete' not in __salt__):\\n return False\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def __virtual__():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_user_permission_codename(perm):\\n\\n ''''Returns \\\\'_\\\\'. If standard ``auth.User`` is\\n used, for \\\\'change\\\\' perm this would return ``change_user`` and if\\n ``myapp.CustomUser`` is used it would return ``change_customuser``.'\\n '''\",\"targets\":\"return get_user_permission_full_codename(perm).split(u'.')[1]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None):\\n\\n ''''Retrieve the certificate from the server at the specified address,\\n and return it as a PEM-encoded string.\\n If \\\\'ca_certs\\\\' is specified, validate the server cert against it.\\n If \\\\'ssl_version\\\\' is specified, use it in the connection attempt.'\\n '''\",\"targets\":\"(host, port) = addr\\n if (ca_certs is not None):\\n cert_reqs = CERT_REQUIRED\\n else:\\n cert_reqs = CERT_NONE\\n context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs)\\n with closing(create_connection(addr)) as sock:\\n with closing(context.wrap_socket(sock)) as sslsock:\\n dercert = sslsock.getpeercert(True)\\n return DER_cert_to_PEM_cert(dercert)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_required_parameters(dictionary, additional_params=None):\",\"targets\":\"\\\"\\\"\\\"Extract all required LTI parameters from a dictionary and verify that none\\n are missing.\\n :param dictionary: The dictionary that should contain all required parameters\\n :param additional_params: Any expected parameters, beyond those required for\\n the LTI launch.\\n :return: A new dictionary containing all the required parameters from the\\n original dictionary and additional parameters, or None if any expected\\n parameters are missing.\\n \\\"\\\"\\\"\\n params = {}\\n additional_params = (additional_params or [])\\n for key in (REQUIRED_PARAMETERS + additional_params):\\n if (key not in dictionary):\\n return None\\n params[key] = dictionary[key]\\n return params\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n if (len(ty) != len(pv)):\\n raise ValueError('len(ty) must equal to len(pv)')\\n total_correct = total_error = 0\\n sumv = sumy = sumvv = sumyy = sumvy = 0\\n for (v, y) in zip(pv, ty):\\n if (y == v):\\n total_correct += 1\\n total_error += ((v - y) * (v - y))\\n sumv += v\\n sumy += y\\n sumvv += (v * v)\\n sumyy += (y * y)\\n sumvy += (v * y)\\n l = len(ty)\\n ACC = ((100.0 * total_correct) \\/ l)\\n MSE = (total_error \\/ l)\\n try:\\n SCC = ((((l * sumvy) - (sumv * sumy)) * ((l * sumvy) - (sumv * sumy))) \\/ (((l * sumvv) - (sumv * sumv)) * ((l * sumyy) - (sumy * sumy))))\\n except:\\n SCC = float('nan')\\n return (ACC, MSE, SCC)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def evaluations(ty, pv):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\n@pytest.fixture\\ndef setup_browser(qtbot):\\n\\n ''''Set up WebBrowser.'\\n '''\",\"targets\":\"widget = WebBrowser()\\n qtbot.addWidget(widget)\\n return widget\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@testing.requires_testing_data\\ndef test_rap_music_sphere():\",\"targets\":\"\\\"\\\"\\\"Test RAP-MUSIC with real data, sphere model, MEG only.\\n \\\"\\\"\\\"\\n (evoked, noise_cov) = _get_data(ch_decim=8)\\n sphere = mne.make_sphere_model(r0=(0.0, 0.0, 0.04))\\n src = mne.setup_volume_source_space(subject=None, pos=10.0, sphere=(0.0, 0.0, 40, 65.0), mindist=5.0, exclude=0.0)\\n forward = mne.make_forward_solution(evoked.info, trans=None, src=src, bem=sphere)\\n dipoles = rap_music(evoked, forward, noise_cov, n_dipoles=2)\\n pos = np.array([dip.pos[0] for dip in dipoles])\\n assert_equal(pos.shape, (2, 3))\\n assert_equal((pos[:, 0] < 0).sum(), 1)\\n assert_equal((pos[:, 0] > 0).sum(), 1)\\n assert_true((1e-10 < dipoles[0].amplitude[0] < 1e-07))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n import pifacedigitalio as PFIO\\n hass.data[DATA_PFIO_LISTENER].register(port, PFIO.IODIR_BOTH, event_callback, settle_time=settle)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def edge_detect(hass, port, event_callback, settle):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_loc_from_db(location, country):\",\"targets\":\"\\\"\\\"\\\"Lookup a Location Hierarchy\\n \\\"\\\"\\\"\\n row = db((table.name == location)).select(table.level, table.L1, table.L2, table.L3, orderby=table.level, limitby=(0, 1)).first()\\n if (row is None):\\n return lookup_loc(location, country)\\n country_code = country_codes[country]\\n return (country_code, row.L1, row.L2, row.L3)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def make_app():\",\"targets\":\"\\\"\\\"\\\"Helper function that creates a plnt app.\\n \\\"\\\"\\\"\\n from plnt import Plnt\\n database_uri = os.environ.get('PLNT_DATABASE_URI')\\n app = Plnt((database_uri or 'sqlite:\\/\\/\\/\\/tmp\\/plnt.db'))\\n app.bind_to_context()\\n return app\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n assert (torch.distributed._initialized == _INITIALIZED_PG), 'collective only supported in process-group mode'\\n return _DistributedRequest(torch._C._dist_isend(tensor, dst))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def isend(tensor, dst):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope='deepq', reuse=None, param_noise_filter_func=None):\\n\\n ''''Creates the act function with support for parameter space noise exploration (https:\\/\\/arxiv.org\\/abs\\/1706.01905):\\n Parameters\\n make_obs_ph: str -> tf.placeholder or TfInput\\n a function that take a name and creates a placeholder of input with that name\\n q_func: (tf.Variable, int, str, bool) -> tf.Variable\\n the model that takes the following inputs:\\n observation_in: object\\n the output of observation placeholder\\n num_actions: int\\n number of actions\\n scope: str\\n reuse: bool\\n should be passed to outer variable scope\\n and returns a tensor of shape (batch_size, num_actions) with values of every action.\\n num_actions: int\\n number of actions.\\n scope: str or VariableScope\\n optional scope for variable_scope.\\n reuse: bool or None\\n whether or not the variables should be reused. To be able to reuse the scope must be given.\\n param_noise_filter_func: tf.Variable -> bool\\n function that decides whether or not a variable should be perturbed. Only applicable\\n if param_noise is True. If set to None, default_param_noise_filter is used by default.\\n Returns\\n act: (tf.Variable, bool, float, bool, float, bool) -> tf.Variable\\n function to select and action given observation.\\n ` See the top of the file for details.'\\n '''\",\"targets\":\"if (param_noise_filter_func is None):\\n param_noise_filter_func = default_param_noise_filter\\n with tf.variable_scope(scope, reuse=reuse):\\n observations_ph = U.ensure_tf_input(make_obs_ph('observation'))\\n stochastic_ph = tf.placeholder(tf.bool, (), name='stochastic')\\n update_eps_ph = tf.placeholder(tf.float32, (), name='update_eps')\\n update_param_noise_threshold_ph = tf.placeholder(tf.float32, (), name='update_param_noise_threshold')\\n update_param_noise_scale_ph = tf.placeholder(tf.bool, (), name='update_param_noise_scale')\\n reset_ph = tf.placeholder(tf.bool, (), name='reset')\\n eps = tf.get_variable('eps', (), initializer=tf.constant_initializer(0))\\n param_noise_scale = tf.get_variable('param_noise_scale', (), initializer=tf.constant_initializer(0.01), trainable=False)\\n param_noise_threshold = tf.get_variable('param_noise_threshold', (), initializer=tf.constant_initializer(0.05), trainable=False)\\n q_values = q_func(observations_ph.get(), num_actions, scope='q_func')\\n q_values_perturbed = q_func(observations_ph.get(), num_actions, scope='perturbed_q_func')\\n def perturb_vars(original_scope, perturbed_scope):\\n all_vars = U.scope_vars(U.absolute_scope_name('q_func'))\\n all_perturbed_vars = U.scope_vars(U.absolute_scope_name('perturbed_q_func'))\\n assert (len(all_vars) == len(all_perturbed_vars))\\n perturb_ops = []\\n for (var, perturbed_var) in zip(all_vars, all_perturbed_vars):\\n if param_noise_filter_func(perturbed_var):\\n op = tf.assign(perturbed_var, (var + tf.random_normal(shape=tf.shape(var), mean=0.0, stddev=param_noise_scale)))\\n else:\\n op = tf.assign(perturbed_var, var)\\n perturb_ops.append(op)\\n assert (len(perturb_ops) == len(all_vars))\\n return tf.group(*perturb_ops)\\n q_values_adaptive = q_func(observations_ph.get(), num_actions,...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def get_region_from_metadata():\",\"targets\":\"\\\"\\\"\\\"Try to get region from instance identity document and cache it\\n .. versionadded:: 2015.5.6\\n \\\"\\\"\\\"\\n global __Location__\\n if (__Location__ == 'do-not-get-from-metadata'):\\n LOG.debug('Previously failed to get AWS region from metadata. Not trying again.')\\n return None\\n if (__Location__ != ''):\\n return __Location__\\n try:\\n result = requests.get('http:\\/\\/169.254.169.254\\/latest\\/dynamic\\/instance-identity\\/document', proxies={'http': ''}, timeout=AWS_METADATA_TIMEOUT)\\n except requests.exceptions.RequestException:\\n LOG.warning('Failed to get AWS region from instance metadata.', exc_info=True)\\n __Location__ = 'do-not-get-from-metadata'\\n return None\\n try:\\n region = result.json()['region']\\n __Location__ = region\\n return __Location__\\n except (ValueError, KeyError):\\n LOG.warning('Failed to decode JSON from instance metadata.')\\n return None\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef Run(arg_dict, oauth2_parameters=None):\\n\\n ''''Sets up and runs the bulkloader, given the options as keyword arguments.\\n Args:\\n arg_dict: Dictionary of bulkloader options\\n oauth2_parameters: None, or the parameters for OAuth2 authentication.\\n Returns:\\n An exit code.'\\n '''\",\"targets\":\"arg_dict = ProcessArguments(arg_dict)\\n SetupLogging(arg_dict)\\n return _PerformBulkload(arg_dict, oauth2_parameters)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def dispatch(c, id, methodname, args=(), kwds={}):\",\"targets\":\"\\\"\\\"\\\"Send a message to manager using connection `c` and return response\\n \\\"\\\"\\\"\\n c.send((id, methodname, args, kwds))\\n (kind, result) = c.recv()\\n if (kind == '#RETURN'):\\n return result\\n raise convert_to_error(kind, result)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n print('Loading model...')\\n model = serial.load(model_path)\\n model.set_batch_size(m)\\n return model\\n\\n\\nWhat's a good function header?\",\"targets\":\"def load_model(model_path, m):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n def enumerated_type_check(var_name, val):\\n for func in allowed_type_funcs:\\n if (not func(var_name, val)):\\n return None\\n return (_('%s is not an allowed_type') % (var_name,))\\n return enumerated_type_check\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_variable_type(allowed_type_funcs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef explore_module(package):\\n\\n ''''Explore the modules.'\\n '''\",\"targets\":\"module = importlib.import_module(package)\\n if (not hasattr(module, '__path__')):\\n return []\\n for (_, name, _) in pkgutil.iter_modules(module.__path__, (package + '.')):\\n (yield name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def LU_solve(matlist, variable, constant, K):\",\"targets\":\"\\\"\\\"\\\"Solves a system of equations using LU decomposition given a matrix\\n of coefficients, a vector of variables and a vector of constants.\\n Examples\\n >>> from sympy.matrices.densesolve import LU_solve\\n >>> from sympy import QQ\\n >>> from sympy import Dummy\\n >>> x, y, z = Dummy(\\\\x\\\\), Dummy(\\\\y\\\\), Dummy(\\\\z\\\\)\\n >>> coefficients = [\\n ... [QQ(2), QQ(-1), QQ(-2)],\\n ... [QQ(-4), QQ(6), QQ(3)],\\n ... [QQ(-4), QQ(-2), QQ(8)]]\\n >>> variables = [\\n ... [x],\\n ... [y],\\n ... [z]]\\n >>> constants = [\\n ... [QQ(-1)],\\n ... [QQ(13)],\\n ... [QQ(-6)]]\\n >>> LU_solve(coefficients, variables, constants, QQ)\\n [[2], [3], [1]]\\n See Also\\n LU\\n forward_substitution\\n backward_substitution\\n \\\"\\\"\\\"\\n new_matlist = copy.deepcopy(matlist)\\n nrow = len(new_matlist)\\n (L, U) = LU(new_matlist, K)\\n y = [[i] for i in symbols(('y:%i' % nrow))]\\n forward_substitution(L, y, constant, K)\\n backward_substitution(U, variable, y, K)\\n return variable\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n for format in formats:\\n if (format not in ARCHIVE_FORMATS):\\n return format\\n return None\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_archive_formats(formats):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"@register.filter\\ndef fix_jsi18n(extrahead):\",\"targets\":\"\\\"\\\"\\\"Hack to rewrite out the jsi18n script tag from an inherited admin template.\\n This is required in order to prevent it\\\\s relative path from generating\\n server errors.\\n Please see this issue for more information:\\n * http:\\/\\/code.google.com\\/p\\/django-reversion\\/issues\\/detail?id=50\\n \\\"\\\"\\\"\\n return mark_safe(unicode(extrahead).replace(u'..\\/..\\/..\\/jsi18n\\/', reverse('admin:jsi18n')))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef cookie_date(epoch_seconds=None):\\n\\n ''''Formats the time to ensure compatibility with Netscape\\\\'s cookie standard.\\n Accepts a floating point number expressed in seconds since the epoch, in\\n UTC - such as that outputted by time.time(). If set to None, defaults to\\n the current time.\\n Outputs a string in the format \\\\'Wdy, DD-Mon-YYYY HH:MM:SS GMT\\\\'.'\\n '''\",\"targets\":\"rfcdate = formatdate(epoch_seconds)\\n return (u'%s-%s-%s GMT' % (rfcdate[:7], rfcdate[8:11], rfcdate[12:25]))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"I wrote the below code\\n\\n p[0] = p[1]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def p_container_type(p):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"def create_virtualenv(venv=VENV, no_site_packages=True):\",\"targets\":\"\\\"\\\"\\\"Creates the virtual environment and installs PIP only into the\\n virtual environment\\n \\\"\\\"\\\"\\n print 'Creating venv...',\\n if no_site_packages:\\n run_command(['virtualenv', '-q', '--no-site-packages', VENV])\\n else:\\n run_command(['virtualenv', '-q', VENV])\\n print 'done.'\\n print 'Installing pip in virtualenv...',\\n if (not run_command(['tools\\/with_venv.sh', 'easy_install', 'pip>1.0']).strip()):\\n die('Failed to install pip.')\\n print 'done.'\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n" "{\"inputs\":\"Complete the below\\ndef logical_volume_info(path):\\n\\n ''''Get logical volume info.\\n :param path: logical volume path'\\n '''\",\"targets\":\"(out, err) = execute('lvs', '-o', 'vg_all,lv_all', '--separator', '|', path, run_as_root=True)\\n info = [line.split('|') for line in out.splitlines()]\\n if (len(info) != 2):\\n raise RuntimeError((_('Path %s must be LVM logical volume') % path))\\n return dict(zip(*info))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"