%s%s %s<\\/td><\\/tr>' % (' <\\/big>', link, call))]\\n if (index is not None):\\n i = (lnum - index)\\n for line in lines:\\n num = (small(((' ' * (5 - len(str(i)))) + str(i))) + ' ')\\n if (i in highlight):\\n line = ('=>%s%s<\\/tt>' % (num, pydoc.html.preformat(line)))\\n rows.append(('%s<\\/td><\\/tr>' % line))\\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 conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n r = _execute_with_retries(conn, 'delete_stream', StreamName=stream_name)\\n if ('error' not in r):\\n r['result'] = True\\n return r\\n\\n\\nWhat's a good function header?\",\"targets\":\"def delete_stream(stream_name, region=None, key=None, keyid=None, profile=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 (groupname == u'member'):\\n group = Group.get_member_group()\\n else:\\n group = Group.query.filter((getattr(Group, groupname) == True)).first()\\n user = User.create(username=username, password=password, email=email, primary_group_id=group.id, activated=True)\\n return user\\n\\n\\nWhat's a good function header?\",\"targets\":\"def create_user(username, password, email, groupname):\",\"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 response[0]):\\n body = []\\n elif ('show run' in command):\\n body = response\\n else:\\n body = [json.loads(response[0])]\\n return body\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_cli_body_ssh_vrf_interface(command, response, module):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n imp.acquire_lock()\\n try:\\n for package in _namespace_packages.get(parent, ()):\\n subpath = _handle_ns(package, path_item)\\n if subpath:\\n fixup_namespace_packages(subpath, package)\\n finally:\\n imp.release_lock()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def fixup_namespace_packages(path_item, parent=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 os.path.isabs(path)):\\n path = os.path.expanduser(path)\\n try:\\n with open(path, 'rb') as handle:\\n yaml_doc = handle.read()\\n except IOError:\\n raise googleads.errors.GoogleAdsValueError(('Given yaml file, %s, could not be opened.' % path))\\n try:\\n client_kwargs = LoadFromString(yaml_doc, product_yaml_key, required_client_values, optional_product_values)\\n except googleads.errors.GoogleAdsValueError as e:\\n e.message = ('Given yaml file, %s, could not find some keys. %s' % (path, e.message))\\n raise\\n return client_kwargs\\n\\n\\nWhat's a good function header?\",\"targets\":\"def LoadFromStorage(path, product_yaml_key, required_client_values, optional_product_values):\",\"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 callable(variables):\\n variables = variables()\\n clean_revert = variables.pop('clean_revert', False)\\n previous = {}\\n new = []\\n for (key, value) in variables.iteritems():\\n if (key in state.env):\\n previous[key] = state.env[key]\\n else:\\n new.append(key)\\n state.env[key] = value\\n try:\\n (yield)\\n finally:\\n if clean_revert:\\n for (key, value) in variables.iteritems():\\n if ((key in state.env) and (value == state.env[key])):\\n if (key in previous):\\n state.env[key] = previous[key]\\n else:\\n del state.env[key]\\n else:\\n state.env.update(previous)\\n for key in new:\\n del state.env[key]\\n\\n\\nWhat's a good function header?\",\"targets\":\"@documented_contextmanager\\ndef _setenv(variables):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def load_package_dependencies(package, load_recursive=False):\",\"targets\":\"\\\"\\\"\\\"Register all messages that the specified package depends on.\\n @param load_recursive: (optional) if True, load all dependencies,\\n not just direct dependencies. By default, this is false to\\n prevent packages from incorrectly inheriting dependencies.\\n @type load_recursive: bool\\n \\\"\\\"\\\"\\n global _loaded_packages\\n _init()\\n if VERBOSE:\\n print('Load dependencies for package', package)\\n if (not load_recursive):\\n manifest_file = roslib.manifest.manifest_file(package, True)\\n m = roslib.manifest.parse_file(manifest_file)\\n depends = [d.package for d in m.depends]\\n else:\\n depends = rospkg.RosPack().get_depends(package, implicit=True)\\n msgs = []\\n failures = []\\n for d in depends:\\n if VERBOSE:\\n print('Load dependency', d)\\n if ((d in _loaded_packages) or (d == package)):\\n continue\\n _loaded_packages.append(d)\\n (specs, failed) = get_pkg_msg_specs(d)\\n msgs.extend(specs)\\n failures.extend(failed)\\n for (key, spec) in msgs:\\n register(key, spec)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_group(name, match_obj):\\n\\n ''''return a blank string if the match group is None'\\n '''\",\"targets\":\"try:\\n obj = match_obj.group(name)\\n except:\\n return ''\\n else:\\n if (obj is not None):\\n return obj\\n else:\\n return ''\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_user_policy(user_name, policy_name, region=None, key=None, keyid=None, profile=None):\\n\\n ''''Retrieves the specified policy document for the specified user.\\n .. versionadded:: 2015.8.0\\n CLI Example:\\n .. code-block:: bash\\n salt myminion boto_iam.get_user_policy myuser mypolicyname'\\n '''\",\"targets\":\"conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n try:\\n info = conn.get_user_policy(user_name, policy_name)\\n log.debug('Info for user policy is : {0}.'.format(info))\\n if (not info):\\n return False\\n info = info.get_user_policy_response.get_user_policy_result.policy_document\\n info = _unquote(info)\\n info = json.loads(info, object_pairs_hook=odict.OrderedDict)\\n return info\\n except boto.exception.BotoServerError as e:\\n log.debug(e)\\n msg = 'Failed to get user {0} policy.'\\n log.error(msg.format(user_name))\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _poll_while(predicate, steps, sleep=None):\\n\\n ''''Like common.poll_until, but with the reverse meaning of the predicate.'\\n '''\",\"targets\":\"return poll_until((lambda : (not predicate())), steps, sleep)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _get_unpatched(cls):\",\"targets\":\"\\\"\\\"\\\"Protect against re-patching the distutils if reloaded\\n Also ensures that no other distutils extension monkeypatched the distutils\\n first.\\n \\\"\\\"\\\"\\n while cls.__module__.startswith('setuptools'):\\n (cls,) = cls.__bases__\\n if (not cls.__module__.startswith('distutils')):\\n raise AssertionError(('distutils has already been patched by %r' % cls))\\n return cls\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef layer_theme():\\n\\n ''''RESTful CRUD controller'\\n '''\",\"targets\":\"def prep(r):\\n if r.interactive:\\n if (r.component_name == 'config'):\\n ltable = s3db.gis_layer_config\\n ltable.base.writable = ltable.base.readable = False\\n if (r.method != 'update'):\\n table = r.table\\n query = ((ltable.layer_id == table.layer_id) & (table.id == r.id))\\n rows = db(query).select(ltable.config_id)\\n ltable.config_id.requires = IS_ONE_OF(db, 'gis_config.id', '%(name)s', not_filterby='config_id', not_filter_opts=[row.config_id for row in rows])\\n else:\\n type = 'Theme'\\n LAYERS = T((TYPE_LAYERS_FMT % type))\\n ADD_NEW_LAYER = T((ADD_NEW_TYPE_LAYER_FMT % type))\\n EDIT_LAYER = T((EDIT_TYPE_LAYER_FMT % type))\\n LIST_LAYERS = T((LIST_TYPE_LAYERS_FMT % type))\\n NO_LAYERS = T((NO_TYPE_LAYERS_FMT % type))\\n s3.crud_strings['gis_layer_theme'] = Storage(label_create=ADD_LAYER, title_display=LAYER_DETAILS, title_list=LAYERS, title_update=EDIT_LAYER, label_list_button=LIST_LAYERS, label_delete_button=DELETE_LAYER, msg_record_created=LAYER_ADDED, msg_record_modified=LAYER_UPDATED, msg_record_deleted=LAYER_DELETED, msg_list_empty=NO_LAYERS)\\n return True\\n s3.prep = prep\\n def postp(r, output):\\n if (r.interactive and (r.method != 'import')):\\n if (not r.component):\\n s3_action_buttons(r, copyable=True)\\n inject_enable(output)\\n s3.rfooter = DIV(A(T('Import Layers'), _href=URL(args='import'), _class='action-btn'), A(T('Import Data'), _href=URL(f='theme_data', args='import'), _class='action-btn'))\\n return output\\n s3.postp = postp\\n if ('import' in request.args):\\n output = s3_rest_controller('gis', 'layer_config', csv_template='layer_theme', csv_stylesheet='layer_theme.xsl')\\n else:\\n output = s3_rest_controller(rheader=s3db.gis_rheader)\\n return output\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"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\":\"connection.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\":\"Complete the below\\ndef auth_wanted(view_func):\\n\\n ''''Twitter sessions are SSL only, so redirect to SSL if needed.\\n Don\\\\'t redirect if TWITTER_COOKIE_SECURE is False.'\\n '''\",\"targets\":\"def wrapper(request, *args, **kwargs):\\n is_secure = settings.TWITTER_COOKIE_SECURE\\n if (request.COOKIES.get(REDIRECT_NAME) and (is_secure and (not request.is_secure()))):\\n ssl_url = url(request, {'scheme': ('https' if is_secure else 'http')})\\n return http.HttpResponseRedirect(ssl_url)\\n return view_func(request, *args, **kwargs)\\n return wrapper\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def add_representer(data_type, representer, Dumper=Dumper):\",\"targets\":\"\\\"\\\"\\\"Add a representer for the given type.\\n Representer is a function accepting a Dumper instance\\n and an instance of the given data type\\n and producing the corresponding representation node.\\n \\\"\\\"\\\"\\n Dumper.add_representer(data_type, representer)\",\"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 work on Windows'\\n '''\",\"targets\":\"if salt.utils.platform.is_windows():\\n return __virtualname__\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def encode(in_file, out_file, name=None, mode=None):\",\"targets\":\"\\\"\\\"\\\"Uuencode file\\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()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef downcaseTokens(s, l, t):\\n\\n ''''Helper parse action to convert tokens to lower case.'\\n '''\",\"targets\":\"return [tt.lower() for tt in map(_ustr, t)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@verbose\\ndef make_bem_solution(surfs, verbose=None):\\n\\n ''''Create a BEM solution using the linear collocation approach.\\n Parameters\\n surfs : list of dict\\n The BEM surfaces to use (`from make_bem_model`)\\n verbose : bool, str, int, or None\\n If not None, override default verbose level (see :func:`mne.verbose`\\n and :ref:`Logging documentation ` for more).\\n Returns\\n bem : instance of ConductorModel\\n The BEM solution.\\n Notes\\n .. versionadded:: 0.10.0\\n See Also\\n make_bem_model\\n read_bem_surfaces\\n write_bem_surfaces\\n read_bem_solution\\n write_bem_solution'\\n '''\",\"targets\":\"logger.info('Approximation method : Linear collocation\\\\n')\\n if isinstance(surfs, string_types):\\n logger.info('Loading surfaces...')\\n surfs = read_bem_surfaces(surfs)\\n bem = ConductorModel(is_sphere=False, surfs=surfs)\\n _add_gamma_multipliers(bem)\\n if (len(bem['surfs']) == 3):\\n logger.info('Three-layer model surfaces loaded.')\\n elif (len(bem['surfs']) == 1):\\n logger.info('Homogeneous model surface loaded.')\\n else:\\n raise RuntimeError('Only 1- or 3-layer BEM computations supported')\\n _check_bem_size(bem['surfs'])\\n _fwd_bem_linear_collocation_solution(bem)\\n logger.info('BEM geometry computations complete.')\\n return bem\",\"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(context, RequestContext):\\n ctx = context.flatten()\\n else:\\n ctx = context\\n return ctx\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_context_dict(context):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def ParseRate(rate):\",\"targets\":\"\\\"\\\"\\\"Parses a rate string in the form number\\/unit, or the literal 0.\\n The unit is one of s (seconds), m (minutes), h (hours) or d (days).\\n Args:\\n rate: the rate string.\\n Returns:\\n a floating point number representing the rate\\/second.\\n Raises:\\n MalformedQueueConfiguration: if the rate is invalid\\n \\\"\\\"\\\"\\n if (rate == '0'):\\n return 0.0\\n elements = rate.split('\\/')\\n if (len(elements) != 2):\\n raise MalformedQueueConfiguration(('Rate \\\"%s\\\" is invalid.' % rate))\\n (number, unit) = elements\\n try:\\n number = float(number)\\n except ValueError:\\n raise MalformedQueueConfiguration(('Rate \\\"%s\\\" is invalid: \\\"%s\\\" is not a number.' % (rate, number)))\\n if (unit not in 'smhd'):\\n raise MalformedQueueConfiguration(('Rate \\\"%s\\\" is invalid: \\\"%s\\\" is not one of s, m, h, d.' % (rate, unit)))\\n if (unit == 's'):\\n return number\\n if (unit == 'm'):\\n return (number \\/ 60)\\n if (unit == 'h'):\\n return (number \\/ (60 * 60))\\n if (unit == 'd'):\\n return (number \\/ ((24 * 60) * 60))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef framework_find(fn, executable_path=None, env=None):\\n\\n ''''Find a framework using dyld semantics in a very loose manner.\\n Will take input such as:\\n Python\\n Python.framework\\n Python.framework\\/Versions\\/Current'\\n '''\",\"targets\":\"try:\\n return dyld_find(fn, executable_path=executable_path, env=env)\\n except ValueError as e:\\n pass\\n fmwk_index = fn.rfind('.framework')\\n if (fmwk_index == (-1)):\\n fmwk_index = len(fn)\\n fn += '.framework'\\n fn = os.path.join(fn, os.path.basename(fn[:fmwk_index]))\\n try:\\n return dyld_find(fn, executable_path=executable_path, env=env)\\n except ValueError:\\n raise e\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef asksaveasfilename(**options):\\n\\n ''''Ask for a filename to save as'\\n '''\",\"targets\":\"return SaveAs(**options).show()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _split_map_maybe(function, sequence, marker=None):\",\"targets\":\"\\\"\\\"\\\"Lazily map ``function`` over ``sequence``, yielding two streams:\\n ``(original, applied)``\\n :param function: Unary callable that might return ``marker``.\\n :param sequence: Iterable of objects that ``function`` will be applied to.\\n :param marker: Value returned by ``function`` when it cannot be\\n meaningfully applied to an object in ``sequence``.\\n :return: ``(original, applied)``, where ``original`` is an iterable of all\\n the elements, ``x``, in ``sequence`` where ``function(x)`` is\\n ``marker``, and ``applied`` is an iterable of all of the results of\\n ``function(x)`` that are not ``marker``.\\n \\\"\\\"\\\"\\n annotated = ((x, function(x)) for x in sequence)\\n (original, mapped) = tee(annotated)\\n return ((x for (x, y) in original if (y is marker)), (y for (x, y) in mapped if (y is not marker)))\",\"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 _SYS_ARGV_PROCESSED\\n if _SYS_ARGV_PROCESSED:\\n return False\\n from ctypes import byref, c_int, POINTER, windll, WINFUNCTYPE\\n from ctypes.wintypes import LPCWSTR, LPWSTR\\n GetCommandLineW = WINFUNCTYPE(LPWSTR)(('GetCommandLineW', windll.kernel32))\\n CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(('CommandLineToArgvW', windll.shell32))\\n argc = c_int(0)\\n argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))\\n argv = [argv_unicode[i].encode(encoding, 'replace') for i in range(0, argc.value)]\\n if (not hasattr(sys, 'frozen')):\\n argv = argv[1:]\\n while (len(argv) > 0):\\n arg = argv[0]\\n if ((not arg.startswith(u'-')) or (arg == u'-')):\\n break\\n argv = argv[1:]\\n if (arg == u'-m'):\\n break\\n if (arg == u'-c'):\\n argv[0] = u'-c'\\n break\\n sys.argv = argv\\n _SYS_ARGV_PROCESSED = True\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def fix_win_sys_argv(encoding):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def log(x):\",\"targets\":\"\\\"\\\"\\\"Returns the logarithm of a Theano scalar x.\\n \\\"\\\"\\\"\\n raise NotImplementedError('TODO: implement this function.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n _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)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def fetch_differentiable_fixed_embeddings(comp, state, stride):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n attrs = {'host': 'host', 'port': 'port', 'db': 'db', 'user': 'user', 'password': 'password'}\\n _options = salt.returners.get_returner_options(__virtualname__, ret, attrs, __salt__=__salt__, __opts__=__opts__)\\n return _options\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_options(ret=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 inferred = utils.safe_infer(node)\\n if ((inferred is None) or (not isinstance(inferred.value, six.string_types))):\\n return True\\n for (_, _, format_spec, _) in string.Formatter().parse(inferred.value):\\n if format_spec:\\n return True\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def is_complex_format_str(node):\",\"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 c in line:\\n if ((c is not ' ') and (c is not ' ')):\\n return (c is ' ')\\n return line\\n\\n\\nWhat's a good function header?\",\"targets\":\"def onlywhite(line):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n listed_subtitles = defaultdict(list)\\n checked_videos = []\\n for video in videos:\\n if (not check_video(video, languages=languages)):\\n logger.info('Skipping video %r', video)\\n continue\\n checked_videos.append(video)\\n if (not checked_videos):\\n return listed_subtitles\\n with pool_class(**kwargs) as pool:\\n for video in checked_videos:\\n logger.info('Listing subtitles for %r', video)\\n subtitles = pool.list_subtitles(video, (languages - video.subtitle_languages))\\n listed_subtitles[video].extend(subtitles)\\n logger.info('Found %d subtitle(s)', len(subtitles))\\n return listed_subtitles\\n\\n\\nWhat's a good function header?\",\"targets\":\"def list_subtitles(videos, languages, pool_class=ProviderPool, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@register.filter(name='widget_type')\\ndef widget_type(field):\",\"targets\":\"\\\"\\\"\\\"Return the widget type\\n \\\"\\\"\\\"\\n if hasattr(field, 'widget'):\\n return field.widget.__class__.__name__.lower()\\n elif hasattr(field, 'field'):\\n return field.field.widget.__class__.__name__.lower()\\n else:\\n return None\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"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')\\n session.install('.')\\n session.run('flake8', 'google\\/cloud\\/vision')\\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 parent = node.parent\\n if isinstance(parent, astroid.For):\\n return True\\n elif isinstance(parent, astroid.Comprehension):\\n if (parent.iter == node):\\n return True\\n elif isinstance(parent, astroid.Call):\\n if isinstance(parent.func, astroid.Name):\\n parent_scope = parent.func.lookup(parent.func.name)[0]\\n if (_is_builtin(parent_scope) and (parent.func.name in _ACCEPTS_ITERATOR)):\\n return True\\n elif isinstance(parent.func, astroid.Attribute):\\n if (parent.func.attrname == 'join'):\\n return True\\n elif (isinstance(parent, astroid.Assign) and isinstance(parent.targets[0], (astroid.List, astroid.Tuple))):\\n if (len(parent.targets[0].elts) > 1):\\n return True\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _in_iterating_context(node):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def build_test(label):\",\"targets\":\"\\\"\\\"\\\"Construct a test case with the specified label. Label should be of the\\n form model.TestClass or model.TestClass.test_method. Returns an\\n instantiated test or test suite corresponding to the label provided.\\n \\\"\\\"\\\"\\n parts = label.split('.')\\n if ((len(parts) < 2) or (len(parts) > 3)):\\n raise ValueError((\\\"Test label '%s' should be of the form app.TestCase or app.TestCase.test_method\\\" % label))\\n app_module = get_app(parts[0])\\n test_module = get_tests(app_module)\\n TestClass = getattr(app_module, parts[1], None)\\n if (TestClass is None):\\n if test_module:\\n TestClass = getattr(test_module, parts[1], None)\\n try:\\n if issubclass(TestClass, (unittest.TestCase, real_unittest.TestCase)):\\n if (len(parts) == 2):\\n try:\\n return unittest.TestLoader().loadTestsFromTestCase(TestClass)\\n except TypeError:\\n raise ValueError((\\\"Test label '%s' does not refer to a test class\\\" % label))\\n else:\\n return TestClass(parts[2])\\n except TypeError:\\n pass\\n tests = []\\n for module in (app_module, test_module):\\n try:\\n doctests = make_doctest(module)\\n for test in doctests:\\n if (test._dt_test.name in (('%s.%s' % (module.__name__, '.'.join(parts[1:]))), ('%s.__test__.%s' % (module.__name__, '.'.join(parts[1:]))))):\\n tests.append(test)\\n except ValueError:\\n pass\\n if (not tests):\\n raise ValueError((\\\"Test label '%s' does not refer to a test\\\" % label))\\n return unittest.TestSuite(tests)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@handle_response_format\\n@treeio_login_required\\ndef sla_index(request, response_format='html'):\",\"targets\":\"\\\"\\\"\\\"All available Service Level Agreements\\n \\\"\\\"\\\"\\n if request.GET:\\n query = _get_filter_query(request.GET, ServiceLevelAgreement)\\n slas = Object.filter_by_request(request, ServiceLevelAgreement.objects.filter(query))\\n else:\\n slas = Object.filter_by_request(request, ServiceLevelAgreement.objects)\\n filters = SLAFilterForm(request.user.profile, '', request.GET)\\n context = _get_default_context(request)\\n context.update({'slas': slas, 'filters': filters})\\n return render_to_response('services\\/sla_index', context, context_instance=RequestContext(request), response_format=response_format)\",\"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 _ignore_patterns(path, names):\\n ignored_names = []\\n for pattern in patterns:\\n ignored_names.extend(fnmatch.filter(names, pattern))\\n return set(ignored_names)\\n return _ignore_patterns\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ignore_patterns(*patterns):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _register_user(request, facebook, profile_callback=None, remove_old_connections=False):\",\"targets\":\"\\\"\\\"\\\"Creates a new user and authenticates\\n The registration form handles the registration and validation\\n Other data on the user profile is updates afterwards\\n if remove_old_connections = True we will disconnect old\\n profiles from their facebook flow\\n \\\"\\\"\\\"\\n if (not facebook.is_authenticated()):\\n raise ValueError('Facebook needs to be authenticated for connect flows')\\n backend = get_registration_backend()\\n logger.info('running backend %s for registration', backend)\\n form_class = get_form_class(backend, request)\\n facebook_data = facebook.facebook_registration_data()\\n data = request.POST.copy()\\n for (k, v) in facebook_data.items():\\n if (not data.get(k)):\\n data[k] = v\\n if remove_old_connections:\\n _remove_old_connections(facebook_data['facebook_id'])\\n if (request.POST.get('force_registration_hard') or request.GET.get('force_registration_hard')):\\n data['email'] = data['email'].replace('@', ('+test%s@' % randint(0, 1000000000)))\\n form = form_class(data=data, files=request.FILES, initial={'ip': request.META['REMOTE_ADDR']})\\n if (not form.is_valid()):\\n form_errors = form.errors\\n error = facebook_exceptions.IncompleteProfileError('Facebook signup incomplete')\\n error.form = form\\n raise error\\n try:\\n new_user = None\\n if backend:\\n new_user = backend.register(request, form=form, **form.cleaned_data)\\n if (new_user is None):\\n raise ValueError('new_user is None, note that backward compatability for the older versions of django registration has been dropped.')\\n except IntegrityError as e:\\n raise facebook_exceptions.AlreadyRegistered(e)\\n new_user = _update_user(new_user, facebook)\\n signals.facebook_user_registered.send(sender=get_user_model(), user=new_user, facebook_data=facebook_data, request=request, converter=facebook)\\n new_user.backend = 'django_facebook.auth_backends.FacebookBackend'\\n auth.login(request, new_user)\\n return new_user\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _multiplicative_update_h(X, W, H, beta_loss, l1_reg_H, l2_reg_H, gamma):\",\"targets\":\"\\\"\\\"\\\"update H in Multiplicative Update NMF\\n \\\"\\\"\\\"\\n if (beta_loss == 2):\\n numerator = safe_sparse_dot(W.T, X)\\n denominator = np.dot(np.dot(W.T, W), H)\\n else:\\n WH_safe_X = _special_sparse_dot(W, H, X)\\n if sp.issparse(X):\\n WH_safe_X_data = WH_safe_X.data\\n X_data = X.data\\n else:\\n WH_safe_X_data = WH_safe_X\\n X_data = X\\n WH = WH_safe_X.copy()\\n if ((beta_loss - 1.0) < 0):\\n WH[(WH == 0)] = EPSILON\\n if ((beta_loss - 2.0) < 0):\\n WH_safe_X_data[(WH_safe_X_data == 0)] = EPSILON\\n if (beta_loss == 1):\\n np.divide(X_data, WH_safe_X_data, out=WH_safe_X_data)\\n elif (beta_loss == 0):\\n WH_safe_X_data **= (-1)\\n WH_safe_X_data **= 2\\n WH_safe_X_data *= X_data\\n else:\\n WH_safe_X_data **= (beta_loss - 2)\\n WH_safe_X_data *= X_data\\n numerator = safe_sparse_dot(W.T, WH_safe_X)\\n if (beta_loss == 1):\\n W_sum = np.sum(W, axis=0)\\n W_sum[(W_sum == 0)] = 1.0\\n denominator = W_sum[:, np.newaxis]\\n else:\\n if sp.issparse(X):\\n WtWH = np.empty(H.shape)\\n for i in range(X.shape[1]):\\n WHi = np.dot(W, H[:, i])\\n if ((beta_loss - 1) < 0):\\n WHi[(WHi == 0)] = EPSILON\\n WHi **= (beta_loss - 1)\\n WtWH[:, i] = np.dot(W.T, WHi)\\n else:\\n WH **= (beta_loss - 1)\\n WtWH = np.dot(W.T, WH)\\n denominator = WtWH\\n if (l1_reg_H > 0):\\n denominator += l1_reg_H\\n if (l2_reg_H > 0):\\n denominator = (denominator + (l2_reg_H * H))\\n denominator[(denominator == 0)] = EPSILON\\n numerator \\/= denominator\\n delta_H = numerator\\n if (gamma != 1):\\n delta_H **= gamma\\n return delta_H\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef gaussian_reduce(w, a, b):\\n\\n ''''Returns a reduced solution `(x, z)` to the congruence\\n `X^2 - aZ^2 \\\\equiv 0 \\\\ (mod \\\\ b)` so that `x^2 + |a|z^2` is minimal.\\n Details\\n Here ``w`` is a solution of the congruence `x^2 \\\\equiv a \\\\ (mod \\\\ b)`\\n References\\n .. [1] Gaussian lattice Reduction [online]. Available:\\n http:\\/\\/home.ie.cuhk.edu.hk\\/~wkshum\\/wordpress\\/?p=404\\n .. [2] Efficient Solution of Rational Conices, J. E. Cremona and D. Rusin,\\n Mathematics of Computation, Volume 00, Number 0.'\\n '''\",\"targets\":\"u = (0, 1)\\n v = (1, 0)\\n if (dot(u, v, w, a, b) < 0):\\n v = ((- v[0]), (- v[1]))\\n if (norm(u, w, a, b) < norm(v, w, a, b)):\\n (u, v) = (v, u)\\n while (norm(u, w, a, b) > norm(v, w, a, b)):\\n k = (dot(u, v, w, a, b) \\/\\/ dot(v, v, w, a, b))\\n (u, v) = (v, ((u[0] - (k * v[0])), (u[1] - (k * v[1]))))\\n (u, v) = (v, u)\\n if ((dot(u, v, w, a, b) < (dot(v, v, w, a, b) \\/ 2)) or (norm(((u[0] - v[0]), (u[1] - v[1])), w, a, b) > norm(v, w, a, b))):\\n c = v\\n else:\\n c = ((u[0] - v[0]), (u[1] - v[1]))\\n return (((c[0] * w) + (b * c[1])), c[0])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _basic_auth_str(username, password):\\n\\n ''''Returns a Basic Auth string.'\\n '''\",\"targets\":\"return ('Basic ' + b64encode(('%s:%s' % (username, password)).encode('latin1')).strip().decode('latin1'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def block_device_mappings(vm_):\",\"targets\":\"\\\"\\\"\\\"Return the block device mapping:\\n [{\\\\DeviceName\\\\: \\\\\\/dev\\/sdb\\\\, \\\\VirtualName\\\\: \\\\ephemeral0\\\\},\\n {\\\\DeviceName\\\\: \\\\\\/dev\\/sdc\\\\, \\\\VirtualName\\\\: \\\\ephemeral1\\\\}]\\n \\\"\\\"\\\"\\n return config.get_cloud_config_value('block_device_mappings', vm_, __opts__, search_global=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef assert_fingerprint(cert, fingerprint):\\n\\n ''''Checks if given fingerprint matches the supplied certificate.\\n :param cert:\\n Certificate as bytes object.\\n :param fingerprint:\\n Fingerprint as string of hexdigits, can be interspersed by colons.'\\n '''\",\"targets\":\"hashfunc_map = {16: md5, 20: sha1}\\n fingerprint = fingerprint.replace(':', '').lower()\\n (digest_length, rest) = divmod(len(fingerprint), 2)\\n if (rest or (digest_length not in hashfunc_map)):\\n raise SSLError('Fingerprint is of invalid length.')\\n fingerprint_bytes = unhexlify(fingerprint.encode())\\n hashfunc = hashfunc_map[digest_length]\\n cert_digest = hashfunc(cert).digest()\\n if (not (cert_digest == fingerprint_bytes)):\\n raise SSLError('Fingerprints did not match. Expected \\\"{0}\\\", got \\\"{1}\\\".'.format(hexlify(fingerprint_bytes), hexlify(cert_digest)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef inception_arg_scope(weight_decay=4e-05, use_batch_norm=True, batch_norm_decay=0.9997, batch_norm_epsilon=0.001):\\n\\n ''''Defines the default arg scope for inception models.\\n Args:\\n weight_decay: The weight decay to use for regularizing the model.\\n use_batch_norm: \\\"If `True`, batch_norm is applied after each convolution.\\n batch_norm_decay: Decay for batch norm moving average.\\n batch_norm_epsilon: Small float added to variance to avoid dividing by zero\\n in batch norm.\\n Returns:\\n An `arg_scope` to use for the inception models.'\\n '''\",\"targets\":\"batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'updates_collections': tf.GraphKeys.UPDATE_OPS}\\n if use_batch_norm:\\n normalizer_fn = slim.batch_norm\\n normalizer_params = batch_norm_params\\n else:\\n normalizer_fn = None\\n normalizer_params = {}\\n with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay)):\\n with slim.arg_scope([slim.conv2d], weights_initializer=slim.variance_scaling_initializer(), activation_fn=tf.nn.relu, normalizer_fn=normalizer_fn, normalizer_params=normalizer_params) as sc:\\n return sc\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@login_required\\ndef register_service(request):\\n\\n ''''This view is used for manually registering a new service, with only URL as a\\n parameter.'\\n '''\",\"targets\":\"if (request.method == 'GET'):\\n service_form = CreateServiceForm()\\n return render_to_response('services\\/service_register.html', RequestContext(request, {'create_service_form': service_form}))\\n elif (request.method == 'POST'):\\n service_form = CreateServiceForm(request.POST)\\n if service_form.is_valid():\\n url = _clean_url(service_form.cleaned_data['url'])\\n name = service_form.cleaned_data['name']\\n type = service_form.cleaned_data['type']\\n server = None\\n if (type == 'AUTO'):\\n (type, server) = _verify_service_type(url)\\n if (type is None):\\n return HttpResponse('Could not determine server type', status=400)\\n if (('user' in request.POST) and ('password' in request.POST)):\\n user = request.POST.get('user')\\n password = request.POST.get('password')\\n else:\\n user = None\\n password = None\\n if (type in ['WMS', 'OWS']):\\n return _process_wms_service(url, name, type, user, password, wms=server, owner=request.user)\\n elif (type == 'REST'):\\n return _register_arcgis_url(url, name, user, password, owner=request.user)\\n elif (type == 'CSW'):\\n return _register_harvested_service(url, name, user, password, owner=request.user)\\n elif (type == 'OGP'):\\n return _register_ogp_service(url, owner=request.user)\\n else:\\n return HttpResponse('Not Implemented (Yet)', status=501)\\n elif (request.method == 'PUT'):\\n return HttpResponse('Not Implemented (Yet)', status=501)\\n elif (request.method == 'DELETE'):\\n return HttpResponse('Not Implemented (Yet)', status=501)\\n else:\\n return HttpResponse('Invalid Request', status=400)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n RemoteOrganization = apps.get_model(u'oauth', u'RemoteOrganization')\\n SocialAccount = apps.get_model(u'socialaccount', u'SocialAccount')\\n for account in SocialAccount.objects.all():\\n rows = account.remote_organizations.update(account=None, source=account.provider)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def backwards_move_org_source(apps, schema_editor):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _interact(cookiejar, url, set_cookie_hdrs, hdr_name):\\n\\n ''''Perform a single request \\/ response cycle, returning Cookie: header.'\\n '''\",\"targets\":\"from urllib2 import Request\\n req = Request(url)\\n cookiejar.add_cookie_header(req)\\n cookie_hdr = req.get_header('Cookie', '')\\n headers = []\\n for hdr in set_cookie_hdrs:\\n headers.append(('%s: %s' % (hdr_name, hdr)))\\n res = FakeResponse(headers, url)\\n cookiejar.extract_cookies(res, req)\\n return cookie_hdr\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_privs():\\n\\n ''''Current privileges\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'kdc.example.com\\\\' kerberos.get_privs'\\n '''\",\"targets\":\"ret = {}\\n cmd = __execute_kadmin('get_privs')\\n if ((cmd['retcode'] != 0) or cmd['stderr']):\\n ret['comment'] = cmd['stderr'].splitlines()[(-1)]\\n ret['result'] = False\\n return ret\\n for i in cmd['stdout'].splitlines()[1:]:\\n (prop, val) = i.split(':', 1)\\n ret[prop] = [j for j in val.split()]\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def compute_node_create(context, values):\",\"targets\":\"\\\"\\\"\\\"Create a computeNode from the values dictionary.\\n \\\"\\\"\\\"\\n return IMPL.compute_node_create(context, values)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def create_node(kwargs):\",\"targets\":\"\\\"\\\"\\\"Convenience function to make the rest api call for node creation.\\n \\\"\\\"\\\"\\n if (not isinstance(kwargs, dict)):\\n kwargs = {}\\n params = {'Action': 'CreateInstance', 'InstanceType': kwargs.get('size_id', ''), 'RegionId': kwargs.get('region_id', DEFAULT_LOCATION), 'ImageId': kwargs.get('image_id', ''), 'SecurityGroupId': kwargs.get('securitygroup_id', ''), 'InstanceName': kwargs.get('name', '')}\\n optional = ['InstanceName', 'InternetChargeType', 'InternetMaxBandwidthIn', 'InternetMaxBandwidthOut', 'HostName', 'Password', 'SystemDisk.Category', 'VSwitchId']\\n for item in optional:\\n if (item in kwargs):\\n params.update({item: kwargs[item]})\\n result = query(params)\\n return result['InstanceId']\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@login_required\\ndef project_manage(__, project_slug):\\n\\n ''''Project management view\\n Where you will have links to edit the projects\\\\' configuration, edit the\\n files associated with that project, etc.\\n Now redirects to the normal \\/projects\\/ view.'\\n '''\",\"targets\":\"return HttpResponseRedirect(reverse('projects_detail', args=[project_slug]))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef fftconvolve3(in1, in2=None, in3=None, mode='full'):\\n\\n ''''Convolve two N-dimensional arrays using FFT. See convolve.\\n for use with arma (old version: in1=num in2=den in3=data\\n * better for consistency with other functions in1=data in2=num in3=den\\n * note in2 and in3 need to have consistent dimension\\/shape\\n since I\\\\'m using max of in2, in3 shapes and not the sum\\n copied from scipy.signal.signaltools, but here used to try out inverse\\n filter doesn\\\\'t work or I can\\\\'t get it to work\\n 2010-10-23\\n looks ok to me for 1d,\\n from results below with padded data array (fftp)\\n but it doesn\\\\'t work for multidimensional inverse filter (fftn)\\n original signal.fftconvolve also uses fftn'\\n '''\",\"targets\":\"if ((in2 is None) and (in3 is None)):\\n raise ValueError('at least one of in2 and in3 needs to be given')\\n s1 = np.array(in1.shape)\\n if (not (in2 is None)):\\n s2 = np.array(in2.shape)\\n else:\\n s2 = 0\\n if (not (in3 is None)):\\n s3 = np.array(in3.shape)\\n s2 = max(s2, s3)\\n complex_result = (np.issubdtype(in1.dtype, np.complex) or np.issubdtype(in2.dtype, np.complex))\\n size = ((s1 + s2) - 1)\\n fsize = (2 ** np.ceil(np.log2(size)))\\n if (not (in2 is None)):\\n IN1 = fft.fftn(in2, fsize)\\n if (not (in3 is None)):\\n IN1 \\/= fft.fftn(in3, fsize)\\n IN1 *= fft.fftn(in1, fsize)\\n fslice = tuple([slice(0, int(sz)) for sz in size])\\n ret = fft.ifftn(IN1)[fslice].copy()\\n del IN1\\n if (not complex_result):\\n ret = ret.real\\n if (mode == 'full'):\\n return ret\\n elif (mode == 'same'):\\n if (np.product(s1, axis=0) > np.product(s2, axis=0)):\\n osize = s1\\n else:\\n osize = s2\\n return trim_centered(ret, osize)\\n elif (mode == 'valid'):\\n return trim_centered(ret, (abs((s2 - s1)) + 1))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def PropertyTypeName(value):\",\"targets\":\"\\\"\\\"\\\"Returns the name of the type of the given property value, as a string.\\n Raises BadValueError if the value is not a valid property type.\\n Args:\\n value: any valid property value\\n Returns:\\n string\\n \\\"\\\"\\\"\\n if (value.__class__ in _PROPERTY_MEANINGS):\\n meaning = _PROPERTY_MEANINGS[value.__class__]\\n name = entity_pb.Property._Meaning_NAMES[meaning]\\n return name.lower().replace('_', ':')\\n elif isinstance(value, basestring):\\n return 'string'\\n elif isinstance(value, users.User):\\n return 'user'\\n elif isinstance(value, long):\\n return 'int'\\n elif (value is None):\\n return 'null'\\n else:\\n return typename(value).lower()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef itervalues(d, **kw):\\n\\n ''''Return an iterator over the values of a dictionary.'\\n '''\",\"targets\":\"return iter(getattr(d, _itervalues)(**kw))\",\"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 (cell_name is None):\\n return item\\n return ((cell_name + CELL_ITEM_SEP) + str(item))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def cell_with_item(cell_name, item):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n boundary = ('----------%s' % hex(int((time.time() * 1000))))\\n data = []\\n for (k, v) in kw.iteritems():\\n data.append(('--%s' % boundary))\\n if hasattr(v, 'read'):\\n filename = getattr(v, 'name', '')\\n content = v.read()\\n data.append(('Content-Disposition: form-data; name=\\\"%s\\\"; filename=\\\"hidden\\\"' % k))\\n data.append(('Content-Length: %d' % len(content)))\\n data.append(('Content-Type: %s\\\\r\\\\n' % _guess_content_type(filename)))\\n data.append(content)\\n else:\\n data.append(('Content-Disposition: form-data; name=\\\"%s\\\"\\\\r\\\\n' % k))\\n data.append((v.encode('utf-8') if isinstance(v, unicode) else v))\\n data.append(('--%s--\\\\r\\\\n' % boundary))\\n return ('\\\\r\\\\n'.join(data), boundary)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _encode_multipart(**kw):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _avoid_invalidating_lineage(config, lineage, original_server):\\n\\n ''''Do not renew a valid cert with one from a staging server!'\\n '''\",\"targets\":\"latest_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, open(lineage.cert).read())\\n now_valid = ('fake' not in repr(latest_cert.get_issuer()).lower())\\n if util.is_staging(config.server):\\n if ((not util.is_staging(original_server)) or now_valid):\\n if (not config.break_my_certs):\\n names = ', '.join(lineage.names())\\n raise errors.Error(\\\"You've asked to renew\\/replace a seemingly valid certificate with a test certificate (domains: {0}). We will not do that unless you use the --break-my-certs flag!\\\".format(names))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _CheckFieldName(name):\\n\\n ''''Checks field name is not too long and matches field name pattern.\\n Field name pattern: \\\"[A-Za-z][A-Za-z0-9_]*\\\".'\\n '''\",\"targets\":\"_ValidateString(name, 'name', MAXIMUM_FIELD_NAME_LENGTH)\\n if (not re.match(_FIELD_NAME_PATTERN, name)):\\n raise ValueError(('field name \\\"%s\\\" should match pattern: %s' % (name, _FIELD_NAME_PATTERN)))\\n return 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 assert (12 >= month >= 1)\\n return ((((year - 1) * 12) + month) - 1)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def month_to_index(year, month):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n install_c = 0\\n for package in packages:\\n if query_package(module, port_path, package):\\n continue\\n (rc, out, err) = module.run_command(('%s install %s' % (port_path, package)))\\n if (not query_package(module, port_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')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def install_packages(module, port_path, packages):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_users_with_role(role_prefix):\",\"targets\":\"\\\"\\\"\\\"An expensive operation which finds all users in the db with the given role prefix\\n \\\"\\\"\\\"\\n return User.objects.filter(groups__name__startswith=role_prefix)\",\"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 ('\\\"' in etag):\\n raise ValueError('invalid etag')\\n etag = ('\\\"%s\\\"' % etag)\\n if weak:\\n etag = ('W\\/' + etag)\\n return etag\\n\\n\\nWhat's a good function header?\",\"targets\":\"def quote_etag(etag, weak=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def handle_email_alerts(app, host, repository, content_alert_str='', new_repo_alert=False, admin_only=False):\",\"targets\":\"\\\"\\\"\\\"There are 2 complementary features that enable a tool shed user to receive email notification:\\n 1. Within User Preferences, they can elect to receive email when the first (or first valid)\\n change set is produced for a new repository.\\n 2. When viewing or managing a repository, they can check the box labeled \\\"Receive email alerts\\\"\\n which caused them to receive email alerts when updates to the repository occur. This same feature\\n is available on a per-repository basis on the repository grid within the tool shed.\\n There are currently 4 scenarios for sending email notification when a change is made to a repository:\\n 1. An admin user elects to receive email when the first change set is produced for a new repository\\n from User Preferences. The change set does not have to include any valid content. This allows for\\n the capture of inappropriate content being uploaded to new repositories.\\n 2. A regular user elects to receive email when the first valid change set is produced for a new repository\\n from User Preferences. This differs from 1 above in that the user will not receive email until a\\n change set tha tincludes valid content is produced.\\n 3. An admin user checks the \\\"Receive email alerts\\\" check box on the manage repository page. Since the\\n user is an admin user, the email will include information about both HTML and image content that was\\n included in the change set.\\n 4. A regular user checks the \\\"Receive email alerts\\\" check box on the manage repository page. Since the\\n user is not an admin user, the email will not include any information about both HTML and image content\\n that was included in the change set.\\n \\\"\\\"\\\"\\n sa_session = app.model.context.current\\n repo = hg_util.get_repo_for_repository(app, repository=repository, repo_path=None, create=False)\\n sharable_link = repository_util.generate_sharable_link_for_repository_in_tool_shed(repository, changeset_revision=None)\\n smtp_server = app.config.smtp_server\\n if (smtp_server and (new_repo_alert or repository.email_alerts)):\\n if (app.config.email_from is not None):\\n email_from = app.config.email_from\\n elif (host.split(':')[0] in ['localhost', '127.0.0.1', '0.0.0.0']):\\n email_from = ('galaxy-no-reply@' + socket.getfqdn())\\n else:\\n email_from = ('galaxy-no-reply@' + host.split(':')[0])\\n tip_changeset = repo.changelog.tip()\\n ctx = repo.changectx(tip_changeset)\\n try:\\n username = ctx.user().split()[0]\\n except:\\n username = ctx.user()\\n if new_repo_alert:\\n template = new_repo_email_alert_template\\n else:\\n template = email_alert_template\\n display_date = hg_util.get_readable_ctx_date(ctx)\\n admin_body = string.Template(template).safe_substitute(host=host, sharable_link=sharable_link, repository_name=repository.name, revision=('%s:%s' % (str(ctx.rev()), ctx)), display_date=display_date, description=ctx.description(), username=username, content_alert_str=content_alert_str)\\n body = string.Template(template).safe_substitute(host=host, sharable_link=sharable_link, repository_name=repository.name, revision=('%s:%s' % (str(ctx.rev()), ctx)), display_date=display_date, description=ctx.description(), username=username, content_alert_str='')\\n admin_users = app.config.get('admin_users', '').split(',')\\n frm = email_from\\n if new_repo_alert:\\n subject = ('Galaxy tool shed alert for new repository named %s' % str(repository.name))\\n subject = subject[:80]\\n email_alerts = []\\n for user 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 course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key_string)\\n get_course_with_access(request.user, 'staff', course_key)\\n username = request.POST.get('username')\\n if (username is None):\\n return json_http_response({'success': False, 'msg': 'No username specified'})\\n try:\\n user = User.objects.get(username=username)\\n except User.DoesNotExist:\\n log.debug('no user')\\n return json_http_response({'success': False, 'msg': \\\"No user '{0}'\\\".format(username)})\\n try:\\n membership = CohortMembership.objects.get(user=user, course_id=course_key)\\n membership.delete()\\n except CohortMembership.DoesNotExist:\\n pass\\n return json_http_response({'success': True})\\n\\n\\nWhat's a good function header?\",\"targets\":\"@ensure_csrf_cookie\\n@require_POST\\ndef remove_user_from_cohort(request, course_key_string, cohort_id):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _count_diff_NG86(codon1, codon2, codon_table=default_codon_table):\\n\\n ''''Count differences between two codons (three-letter string; PRIVATE).\\n The function will take multiple pathways from codon1 to codon2\\n into account.'\\n '''\",\"targets\":\"if ((not isinstance(codon1, str)) or (not isinstance(codon2, str))):\\n raise TypeError('_count_diff_NG86 accepts string object to represent codon ({0}, {1} detected)'.format(type(codon1), type(codon2)))\\n if ((len(codon1) != 3) or (len(codon2) != 3)):\\n raise RuntimeError('codon should be three letter string ({0}, {1} detected)'.format(len(codon1), len(codon2)))\\n SN = [0, 0]\\n if ((codon1 == '---') or (codon2 == '---')):\\n return SN\\n base_tuple = ('A', 'C', 'G', 'T')\\n if (not all(((i in base_tuple) for i in codon1))):\\n raise RuntimeError('Unrecognized character detected in codon1 {0} (Codons consist of A, T, C or G)'.format(codon1))\\n if (not all(((i in base_tuple) for i in codon2))):\\n raise RuntimeError('Unrecognized character detected in codon2 {0} (Codons consist of A, T, C or G)'.format(codon2))\\n if (codon1 == codon2):\\n return SN\\n else:\\n diff_pos = []\\n for (i, k) in enumerate(zip(codon1, codon2)):\\n if (k[0] != k[1]):\\n diff_pos.append(i)\\n def compare_codon(codon1, codon2, codon_table=default_codon_table, weight=1):\\n 'Compare two codon accounting for different pathways.'\\n sd = nd = 0\\n if (len(set(map(codon_table.forward_table.get, [codon1, codon2]))) == 1):\\n sd += weight\\n else:\\n nd += weight\\n return (sd, nd)\\n if (len(diff_pos) == 1):\\n SN = [(i + j) for (i, j) in zip(SN, compare_codon(codon1, codon2, codon_table=codon_table))]\\n elif (len(diff_pos) == 2):\\n codon2_aa = codon_table.forward_table[codon2]\\n for i in diff_pos:\\n temp_codon = ((codon1[:i] + codon2[i]) + codon1[(i + 1):])\\n SN = [(i + j) for (i, j) in zip(SN, compare_codon(codon1, temp_codon, codon_table=codon_table, weight=0.5))]\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _build_dependency_manager_no_config(kwargs):\\n\\n ''''Simplified variant of build_dependency_manager from galaxy.tools.deps.\\n The canonical factory method requires a full Galaxy configuration object\\n which we do not have available in this script (an optimization).'\\n '''\",\"targets\":\"configure_logging(kwargs)\\n root = find_root(kwargs)\\n dependency_resolvers_config_file = find_path(kwargs, 'dependency_resolvers_config_file', root)\\n (use_dependencies, tool_dependency_dir, use_cached_dependency_manager, tool_dependency_cache_dir, precache_dependencies) = parse_dependency_options(kwargs, root, dependency_resolvers_config_file)\\n if (not use_dependencies):\\n dependency_manager = NullDependencyManager()\\n else:\\n dependency_manager_kwds = {'default_base_path': tool_dependency_dir, 'conf_file': dependency_resolvers_config_file, 'app_config': kwargs}\\n if use_cached_dependency_manager:\\n dependency_manager_kwds['tool_dependency_cache_dir'] = tool_dependency_cache_dir\\n dependency_manager = CachedDependencyManager(**dependency_manager_kwds)\\n else:\\n dependency_manager = DependencyManager(**dependency_manager_kwds)\\n return dependency_manager\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def butterworthFilter(data, wPass, wStop=None, gPass=2.0, gStop=20.0, order=1, dt=None, btype='low', bidir=True):\",\"targets\":\"\\\"\\\"\\\"return data passed through bessel filter\\n \\\"\\\"\\\"\\n try:\\n import scipy.signal\\n except ImportError:\\n raise Exception('butterworthFilter() requires the package scipy.signal.')\\n if (dt is None):\\n try:\\n tvals = data.xvals('Time')\\n dt = ((tvals[(-1)] - tvals[0]) \\/ (len(tvals) - 1))\\n except:\\n dt = 1.0\\n if (wStop is None):\\n wStop = (wPass * 2.0)\\n (ord, Wn) = scipy.signal.buttord(((wPass * dt) * 2.0), ((wStop * dt) * 2.0), gPass, gStop)\\n (b, a) = scipy.signal.butter(ord, Wn, btype=btype)\\n return applyFilter(data, b, a, bidir=bidir)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def am_following_user(context, data_dict):\",\"targets\":\"\\\"\\\"\\\"Return ``True`` if you\\\\re following the given user, ``False`` if not.\\n :param id: the id or name of the user\\n :type id: string\\n :rtype: boolean\\n \\\"\\\"\\\"\\n return _am_following(context, data_dict, ckan.logic.schema.default_follow_user_schema(), context['model'].UserFollowingUser)\",\"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 load if the docker execution module is available'\\n '''\",\"targets\":\"if ('docker.version' in __salt__):\\n return __virtualname__\\n return (False, __salt__.missing_fun_string('docker.version'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def build_html_page(classified_text, title='python', css=default_css, html=default_html):\",\"targets\":\"\\\"\\\"\\\"Create a complete HTML page with colorized source code\\n \\\"\\\"\\\"\\n css_str = '\\\\n'.join([('%s %s' % item) for item in css.items()])\\n result = html_highlight(classified_text)\\n title = html_module.escape(title)\\n return html.format(title=title, css=css_str, body=result)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@click.command()\\n@click.option('-f', '--filename', help='Fixtures JSON path', default='.\\/etc\\/fixtures\\/initial_data.json')\\n@click.option('-b', '--baseurl', help='base url to use', default=None)\\n@click.option('--reset\\/--no-reset', default=False)\\ndef populate(filename, baseurl=None, reset=False):\\n\\n ''''Populate the database with sample data'\\n '''\",\"targets\":\"populator = Populate(db, filepath=filename, baseurl=baseurl, app=app)\\n if (not reset):\\n try:\\n populator()\\n except RuntimeError:\\n with app.test_request_context(base_url=(baseurl or 'http:\\/\\/localhost:5000\\/')):\\n populator()\\n else:\\n populator.reset()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def isLargeSameDirection(inset, loop, radius):\",\"targets\":\"\\\"\\\"\\\"Determine if the inset is in the same direction as the loop and it is large enough.\\n \\\"\\\"\\\"\\n if (euclidean.isWiddershins(inset) != euclidean.isWiddershins(loop)):\\n return False\\n return (getIsLarge(inset, radius) and (len(inset) > 2))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def check_envelope(result, func, cargs, offset=(-1)):\",\"targets\":\"\\\"\\\"\\\"Checks a function that returns an OGR Envelope by reference.\\n \\\"\\\"\\\"\\n env = ptr_byref(cargs, offset)\\n return env\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef RegisterModule(modName, modPath):\\n\\n ''''Register an explicit module in the registry. This forces the Python import\\n mechanism to locate this module directly, without a sys.path search. Thus\\n a registered module need not appear in sys.path at all.\\n modName -- The name of the module, as used by import.\\n modPath -- The full path and file name of the module.'\\n '''\",\"targets\":\"try:\\n import os\\n os.stat(modPath)\\n except os.error:\\n print ('Warning: Registering non-existant module %s' % modPath)\\n win32api.RegSetValue(GetRootKey(), (BuildDefaultPythonKey() + ('\\\\\\\\Modules\\\\\\\\%s' % modName)), win32con.REG_SZ, modPath)\",\"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 MESSAGES\\n keys = MESSAGES.keys()\\n keys.sort()\\n offsets = []\\n ids = strs = ''\\n for id in keys:\\n offsets.append((len(ids), len(id), len(strs), len(MESSAGES[id])))\\n ids += (id + '\\\\x00')\\n strs += (MESSAGES[id] + '\\\\x00')\\n output = ''\\n keystart = ((7 * 4) + (16 * len(keys)))\\n valuestart = (keystart + len(ids))\\n koffsets = []\\n voffsets = []\\n for (o1, l1, o2, l2) in offsets:\\n koffsets += [l1, (o1 + keystart)]\\n voffsets += [l2, (o2 + valuestart)]\\n offsets = (koffsets + voffsets)\\n output = struct.pack('Iiiiiii', 2500072158L, 0, len(keys), (7 * 4), ((7 * 4) + (len(keys) * 8)), 0, 0)\\n output += array.array('i', offsets).tostring()\\n output += ids\\n output += strs\\n return output\\n\\n\\nWhat's a good function header?\",\"targets\":\"def generate():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _set_binops_check_loose(self, obj):\\n\\n ''''Allow anything set-like to participate in set binops.'\\n '''\",\"targets\":\"return (isinstance(obj, (_set_binop_bases + (self.__class__,))) or (util.duck_type_collection(obj) == set))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n qt_start = ''\\n qt_end_with_lang_len = 5\\n qt_chunks = text.split(qt_start)\\n content_by_lang = {}\\n common_txt_list = []\\n for c in qt_chunks:\\n if (not c.strip()):\\n continue\\n if c.startswith(qt_end):\\n lang = ''\\n c = c.lstrip(qt_end)\\n if (not c):\\n continue\\n elif c[2:].startswith(qt_end):\\n lang = c[:2]\\n c = c[qt_end_with_lang_len:]\\n else:\\n lang = ''\\n if (not lang):\\n common_txt_list.append(c)\\n for l in content_by_lang.keys():\\n content_by_lang[l].append(c)\\n else:\\n content_by_lang[lang] = (content_by_lang.get(lang, common_txt_list) + [c])\\n if (common_txt_list and (not content_by_lang)):\\n content_by_lang[''] = common_txt_list\\n for l in content_by_lang.keys():\\n content_by_lang[l] = ' '.join(content_by_lang[l])\\n return content_by_lang\\n\\n\\nWhat's a good function header?\",\"targets\":\"def separate_qtranslate_content(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 from sklearn.decomposition import PCA\\n from sklearn.kernel_ridge import KernelRidge\\n raw = io.read_raw_fif(raw_fname)\\n events = read_events(event_name)\\n picks = pick_types(raw.info, meg=True, stim=False, ecg=False, eog=False, exclude='bads')\\n picks = picks[1:13:3]\\n epochs = Epochs(raw, events, event_id, tmin, tmax, picks=picks, preload=True, baseline=None, verbose=False)\\n assert_raises(ValueError, UnsupervisedSpatialFilter, KernelRidge(2))\\n X = epochs.get_data()\\n n_components = 4\\n usf = UnsupervisedSpatialFilter(PCA(n_components))\\n usf.fit(X)\\n usf1 = UnsupervisedSpatialFilter(PCA(n_components))\\n assert_equal(usf.transform(X).ndim, 3)\\n assert_array_almost_equal(usf.transform(X), usf1.fit_transform(X))\\n assert_equal(usf.transform(X).shape[1], n_components)\\n assert_array_almost_equal(usf.inverse_transform(usf.transform(X)), X)\\n usf = UnsupervisedSpatialFilter(PCA(4), average=True)\\n usf.fit_transform(X)\\n assert_raises(ValueError, UnsupervisedSpatialFilter, PCA(4), 2)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@requires_sklearn_0_15\\ndef test_unsupervised_spatial_filter():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef AND(*params):\\n\\n ''''Emulate SQLObject\\\\'s AND.'\\n '''\",\"targets\":\"return and_(*params)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n module = _BUILDER.string_build(textwrap.dedent('\\\\n import unittest\\\\n\\\\n class Test(unittest.TestCase):\\\\n pass\\\\n a = Test()\\\\n '))\\n try:\\n case = next(module['a'].infer())\\n except astroid.InferenceError:\\n return\\n for method in case.methods():\\n if (method.name.startswith('assert') and ('_' not in method.name)):\\n pep8_name = _pep8(method.name)\\n (yield (pep8_name, astroid.BoundMethod(method, case)))\\n if (method.name == 'assertEqual'):\\n (yield ('assert_equals', astroid.BoundMethod(method, case)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _nose_tools_functions():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _split_stages(node, duplicates=None, aliases=None, stages=None, parents=None):\\n\\n ''''Split out all reductions and post reduction scalar operations into seperate\\n stacks (stages)\\n This leaves remaining in the tree anything not in these categories.'\\n '''\",\"targets\":\"if (duplicates is None):\\n duplicates = dict()\\n aliases = set()\\n stages = list()\\n parents = list()\\n if (type(node) is list):\\n if (node[0][0] != 'assign'):\\n parents.append(node)\\n if (len(node) > 3):\\n _split_stages(node[3], duplicates, aliases, stages, parents)\\n if (len(node) > 4):\\n _split_stages(node[4], duplicates, aliases, stages, parents)\\n if (len(parents) > 0):\\n parents.pop()\\n if (node[0][0] in _reduction_ops):\\n red_stack = _process_node(node, aliases, duplicates)\\n if red_stack:\\n stages.append(('reduction', red_stack))\\n for parent in parents:\\n parent[2] -= 1\\n scalar_parent = None\\n for parent in parents[::(-1)]:\\n if (parent[1] and (parent[2] == 0)):\\n scalar_parent = parent\\n else:\\n break\\n if (scalar_parent is not None):\\n scalar_stack = _process_node(scalar_parent, aliases, duplicates)\\n if scalar_stack:\\n stages.append(('scalar', scalar_stack))\\n return stages\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@task\\ndef test():\",\"targets\":\"\\\"\\\"\\\"Run tests by launching tasks\\n :return:\\n \\\"\\\"\\\"\\n import django\\n sys.path.append(os.path.dirname(__file__))\\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dva.settings')\\n django.setup()\\n from django.core.files.uploadedfile import SimpleUploadedFile\\n from dvaapp.views import handle_uploaded_file, handle_youtube_video\\n for fname in glob.glob('tests\\/*.mp4'):\\n name = fname.split('\\/')[(-1)].split('.')[0]\\n f = SimpleUploadedFile(fname, file(fname).read(), content_type='video\\/mp4')\\n handle_uploaded_file(f, name)\\n for fname in glob.glob('tests\\/*.zip'):\\n name = fname.split('\\/')[(-1)].split('.')[0]\\n f = SimpleUploadedFile(fname, file(fname).read(), content_type='application\\/zip')\\n handle_uploaded_file(f, name)\\n handle_youtube_video('tomorrow never dies', 'https:\\/\\/www.youtube.com\\/watch?v=gYtz5sw98Bc')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def fixed_ip_count_by_project(context, project_id, session=None):\",\"targets\":\"\\\"\\\"\\\"Count fixed ips used by project.\\n \\\"\\\"\\\"\\n return IMPL.fixed_ip_count_by_project(context, project_id, session=session)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef demo(choice=None, print_times=True, print_grammar=False, print_trees=True, trace=2, sent=u'I saw John with a dog with my cookie', numparses=5):\\n\\n ''''A demonstration of the chart parsers.'\\n '''\",\"targets\":\"import sys, time\\n from nltk import nonterminals, Production, CFG\\n grammar = demo_grammar()\\n if print_grammar:\\n print(u'* Grammar')\\n print(grammar)\\n print(u'* Sentence:')\\n print(sent)\\n tokens = sent.split()\\n print(tokens)\\n print()\\n if (choice is None):\\n print(u' 1: Top-down chart parser')\\n print(u' 2: Bottom-up chart parser')\\n print(u' 3: Bottom-up left-corner chart parser')\\n print(u' 4: Left-corner chart parser with bottom-up filter')\\n print(u' 5: Stepping chart parser (alternating top-down & bottom-up)')\\n print(u' 6: All parsers')\\n print(u'\\\\nWhich parser (1-6)? ', end=u' ')\\n choice = sys.stdin.readline().strip()\\n print()\\n choice = str(choice)\\n if (choice not in u'123456'):\\n print(u'Bad parser number')\\n return\\n times = {}\\n strategies = {u'1': (u'Top-down', TD_STRATEGY), u'2': (u'Bottom-up', BU_STRATEGY), u'3': (u'Bottom-up left-corner', BU_LC_STRATEGY), u'4': (u'Filtered left-corner', LC_STRATEGY)}\\n choices = []\\n if (choice in strategies):\\n choices = [choice]\\n if (choice == u'6'):\\n choices = u'1234'\\n for strategy in choices:\\n print((u'* Strategy: ' + strategies[strategy][0]))\\n print()\\n cp = ChartParser(grammar, strategies[strategy][1], trace=trace)\\n t = time.time()\\n chart = cp.chart_parse(tokens)\\n parses = list(chart.parses(grammar.start()))\\n times[strategies[strategy][0]] = (time.time() - t)\\n print(u'Nr edges in chart:', len(chart.edges()))\\n if numparses:\\n assert (len(parses) == numparses), u'Not all parses found'\\n if print_trees:\\n for tree in parses:\\n print(tree)\\n else:\\n print(u'Nr trees:', len(parses))\\n print()\\n if (choice in u'56'):\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef create_test_input(batch_size, height, width, channels):\\n\\n ''''Create test input tensor.\\n Args:\\n batch_size: The number of images per batch or `None` if unknown.\\n height: The height of each image or `None` if unknown.\\n width: The width of each image or `None` if unknown.\\n channels: The number of channels per image or `None` if unknown.\\n Returns:\\n Either a placeholder `Tensor` of dimension\\n [batch_size, height, width, channels] if any of the inputs are `None` or a\\n constant `Tensor` with the mesh grid values along the spatial dimensions.'\\n '''\",\"targets\":\"if (None in [batch_size, height, width, channels]):\\n return tf.placeholder(tf.float32, (batch_size, height, width, channels))\\n else:\\n return tf.to_float(np.tile(np.reshape((np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width])), [1, height, width, 1]), [batch_size, 1, 1, channels]))\",\"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(spec, tuple):\\n if (spec[0] == u'|'):\\n res = u'|'.join(map(untreeify, spec[1:]))\\n if _inand:\\n res = (u'(%s)' % res)\\n else:\\n res = u','.join(map((lambda x: untreeify(x, _inand=True)), spec[1:]))\\n return res\\n return spec\\n\\n\\nWhat's a good function header?\",\"targets\":\"def untreeify(spec, _inand=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 (h5py is None):\\n raise ImportError('`save_model` requires h5py.')\\n def get_json_type(obj):\\n 'Serialize any object to a JSON-serializable structure.\\\\n\\\\n # Arguments\\\\n obj: the object to serialize\\\\n\\\\n # Returns\\\\n JSON-serializable structure representing `obj`.\\\\n\\\\n # Raises\\\\n TypeError: if `obj` cannot be serialized.\\\\n '\\n if hasattr(obj, 'get_config'):\\n return {'class_name': obj.__class__.__name__, 'config': obj.get_config()}\\n if (type(obj).__module__ == np.__name__):\\n if isinstance(obj, np.ndarray):\\n return {'type': type(obj), 'value': obj.tolist()}\\n else:\\n return obj.item()\\n if callable(obj):\\n return obj.__name__\\n if (type(obj).__name__ == type.__name__):\\n return obj.__name__\\n raise TypeError('Not JSON Serializable:', obj)\\n from . import __version__ as keras_version\\n if ((not overwrite) and os.path.isfile(filepath)):\\n proceed = ask_to_proceed_with_overwrite(filepath)\\n if (not proceed):\\n return\\n with h5py.File(filepath, mode='w') as f:\\n f.attrs['keras_version'] = str(keras_version).encode('utf8')\\n f.attrs['backend'] = K.backend().encode('utf8')\\n f.attrs['model_config'] = json.dumps({'class_name': model.__class__.__name__, 'config': model.get_config()}, default=get_json_type).encode('utf8')\\n model_weights_group = f.create_group('model_weights')\\n if legacy_models.needs_legacy_support(model):\\n model_layers = legacy_models.legacy_sequential_layers(model)\\n else:\\n model_layers = model.layers\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def save_model(model, filepath, overwrite=True, include_optimizer=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 cursor.execute('SHOW TABLES')\\n return [row[0] for row in cursor.fetchall()]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_table_list(cursor):\",\"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 = _asarray_validated(A, check_finite=True)\\n if (len(A.shape) != 2):\\n raise ValueError(('expected 2D array, got shape %s' % (A.shape,)))\\n QA = orth(A)\\n del A\\n B = _asarray_validated(B, check_finite=True)\\n if (len(B.shape) != 2):\\n raise ValueError(('expected 2D array, got shape %s' % (B.shape,)))\\n if (len(B) != len(QA)):\\n raise ValueError(('A and B must have the same number of rows, got %s and %s' % (QA.shape[0], B.shape[0])))\\n QB = orth(B)\\n del B\\n QA_T_QB = dot(QA.T, QB)\\n sigma = svdvals(QA_T_QB)\\n if (QA.shape[1] >= QB.shape[1]):\\n B = (QB - dot(QA, QA_T_QB))\\n else:\\n B = (QA - dot(QB, QA_T_QB.T))\\n del QA, QB, QA_T_QB\\n mask = ((sigma ** 2) >= 0.5)\\n if mask.any():\\n mu_arcsin = arcsin(clip(svdvals(B, overwrite_a=True), (-1.0), 1.0))\\n else:\\n mu_arcsin = 0.0\\n theta = where(mask, mu_arcsin, arccos(clip(sigma, (-1.0), 1.0)))\\n return theta\\n\\n\\nWhat's a good function header?\",\"targets\":\"def subspace_angles(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 input_shape = utils.get_incoming_shape(incoming)\\n assert (len(input_shape) == 4), 'Incoming Tensor shape must be 4-D'\\n kernel = utils.autoformat_kernel_2d(kernel_size)\\n strides = (utils.autoformat_kernel_2d(strides) if strides else kernel)\\n padding = utils.autoformat_padding(padding)\\n with tf.name_scope(name) as scope:\\n inference = tf.nn.avg_pool(incoming, kernel, strides, padding)\\n tf.add_to_collection(tf.GraphKeys.ACTIVATIONS, inference)\\n inference.scope = scope\\n tf.add_to_collection(((tf.GraphKeys.LAYER_TENSOR + '\\/') + name), inference)\\n return inference\\n\\n\\nWhat's a good function header?\",\"targets\":\"def avg_pool_2d(incoming, kernel_size, strides=None, padding='same', name='AvgPool2D'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n formatters[func.__name__] = func\\n return func\\n\\n\\nWhat's a good function header?\",\"targets\":\"def formatter(func):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n (start_timestamp, end_timestamp) = _GetTimestamps()\\n fd_cache = {}\\n log_heap = []\\n def _HeapPush(next_log_record, fn, pos):\\n 'Starting with the contents of \\\"next_line\\\", reads lines from the\\\\n file until the start of the next log record, which is defined as a\\\\n line starting with the iso date regexp. If there are no more bytes\\\\n in the file, returns without pushing. Otherwise, pushes the log\\\\n line, filename (\\\"fn\\\"), and file object (\\\"f\\\") to the log heap for\\\\n merging.\\\\n '\\n fd = _GetFD(fn, pos, fd_cache)\\n while ((next_log_record != '') and (not _ISO_DATE_RE.search(next_log_record))):\\n print ('not merging log line: \\\"%s\\\"' % next_log_record.rstrip())\\n next_log_record = fd.readline()\\n next_line = fd.readline()\\n while (next_line != ''):\\n if (not _ISO_DATE_RE.search(next_line)):\\n next_log_record += next_line\\n else:\\n break\\n next_line = fd.readline()\\n if (next_log_record == ''):\\n fd.close()\\n del fd_cache[fn]\\n return\\n next_log_record = next_log_record.rstrip()\\n heapq.heappush(log_heap, (next_log_record, next_line, fn, fd.tell()))\\n directives = _InitColorize(output_file)\\n re_map = dict()\\n merge_re = re.compile(options.options.merge_filter)\\n for log_url in log_urls:\\n fn = log_url['local_filename']\\n if (merge_re.search(fn) is None):\\n continue\\n try:\\n (directive,) = [d for d in directives if d.filename_re.search(fn)]\\n re_map[fn] = directive\\n except:\\n pass\\n fd = _GetFD(fn, 0, fd_cache)\\n _HeapPush(fd.readline(), fn, fd.tell())\\n while (len(log_heap) > 0):\\n (lr, nl, fn, pos) =...\\n\\nWhat's a good function header?\",\"targets\":\"def MergeLogs(log_urls, output_file=sys.stdout):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@contextmanager\\ndef filetexts(d, open=open, mode='t', use_tmpdir=True):\\n\\n ''''Dumps a number of textfiles to disk\\n d - dict\\n a mapping from filename to text like {\\\\'a.csv\\\\': \\\\'1,1\\n 2,2\\\\'}\\n Since this is meant for use in tests, this context manager will\\n automatically switch to a temporary current directory, to avoid\\n race conditions when running tests in parallel.'\\n '''\",\"targets\":\"with (tmp_cwd() if use_tmpdir else noop_context()):\\n for (filename, text) in d.items():\\n f = open(filename, ('w' + mode))\\n try:\\n f.write(text)\\n finally:\\n try:\\n f.close()\\n except AttributeError:\\n pass\\n (yield list(d))\\n for filename in d:\\n if os.path.exists(filename):\\n with ignoring(OSError):\\n os.remove(filename)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _naive_eval_2(x, t, c, k):\\n\\n ''''Naive B-spline evaluation, another way.'\\n '''\",\"targets\":\"n = (len(t) - (k + 1))\\n assert (n >= (k + 1))\\n assert (len(c) >= n)\\n assert (t[k] <= x <= t[n])\\n return sum(((c[i] * _naive_B(x, k, i, t)) for i in range(n)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef lambda2nu(lambda_):\\n\\n ''''Convert wavelength to optical frequency\\n Parameters\\n lambda_ : array_like\\n Wavelength(s) to be converted.\\n Returns\\n nu : float or array of floats\\n Equivalent optical frequency.\\n Notes\\n Computes ``nu = c \\/ lambda`` where c = 299792458.0, i.e., the\\n (vacuum) speed of light in meters\\/second.\\n Examples\\n >>> from scipy.constants import lambda2nu, speed_of_light\\n >>> lambda2nu(np.array((1, speed_of_light)))\\n array([ 2.99792458e+08, 1.00000000e+00])'\\n '''\",\"targets\":\"return (_np.asanyarray(c) \\/ lambda_)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def do_wordwrap(s, width=79, break_long_words=True):\",\"targets\":\"\\\"\\\"\\\"Return a copy of the string passed to the filter wrapped after\\n ``79`` characters. You can override this default using the first\\n parameter. If you set the second parameter to `false` Jinja will not\\n split words apart if they are longer than `width`.\\n \\\"\\\"\\\"\\n import textwrap\\n return u'\\\\n'.join(textwrap.wrap(s, width=width, expand_tabs=False, replace_whitespace=False, break_long_words=break_long_words))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_links_for_username(browser, username, amount, is_random=False, media=None):\\n\\n ''''Fetches the number of links specified\\n by amount and returns a list of links'\\n '''\",\"targets\":\"if (media is None):\\n media = ['', 'Post', 'Video']\\n elif (media == 'Photo'):\\n media = ['', 'Post']\\n else:\\n media = [media]\\n print ('Getting ', username, 'image list...')\\n browser.get(('https:\\/\\/www.instagram.com\\/' + username))\\n sleep(2)\\n body_elem = browser.find_element_by_tag_name('body')\\n try:\\n is_private = body_elem.find_element_by_xpath('\\/\\/h2[@class=\\\"_glq0k\\\"]')\\n except:\\n print 'Interaction begin...'\\n print ''\\n else:\\n if is_private:\\n print 'This user is private...'\\n print ''\\n return False\\n sleep(2)\\n abort = True\\n try:\\n load_button = body_elem.find_element_by_xpath('\\/\\/a[contains(@class, \\\"_1cr2e _epyes\\\")]')\\n except:\\n print 'Load button not found, working with current images!'\\n else:\\n abort = False\\n body_elem.send_keys(Keys.END)\\n sleep(2)\\n load_button.click()\\n body_elem.send_keys(Keys.HOME)\\n sleep(2)\\n main_elem = browser.find_element_by_tag_name('main')\\n link_elems = main_elem.find_elements_by_tag_name('a')\\n total_links = len(link_elems)\\n links = []\\n filtered_links = 0\\n try:\\n if link_elems:\\n links = [link_elem.get_attribute('href') for link_elem in link_elems if (link_elem and (link_elem.text in media))]\\n filtered_links = len(links)\\n except BaseException as e:\\n print ('link_elems error \\\\n', str(e))\\n if is_random:\\n amount = (amount * 5)\\n while ((filtered_links < amount) and (not abort)):\\n amount_left = (amount - filtered_links)\\n new_per_page = ceil(((12 * filtered_links) \\/ total_links))\\n if (new_per_page == 0):\\n new_per_page = (1.0 \\/ 12.0)\\n new_needed = int(ceil((amount_left \\/ new_per_page)))\\n if (new_needed > 12):\\n new_needed = 12\\n for i in range(new_needed):\\n before_load = total_links\\n body_elem.send_keys(Keys.END)\\n ...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _build_shadow_vm_config_spec(session, name, size_kb, disk_type, ds_name):\\n\\n ''''Return spec for creating a shadow VM for image disk.\\n The VM is never meant to be powered on. When used in importing\\n a disk it governs the directory name created for the VM\\n and the disk type of the disk image to convert to.\\n :param name: Name of the backing\\n :param size_kb: Size in KB of the backing\\n :param disk_type: VMDK type for the disk\\n :param ds_name: Datastore name where the disk is to be provisioned\\n :return: Spec for creation'\\n '''\",\"targets\":\"cf = session.vim.client.factory\\n controller_device = cf.create('ns0:VirtualLsiLogicController')\\n controller_device.key = (-100)\\n controller_device.busNumber = 0\\n controller_device.sharedBus = 'noSharing'\\n controller_spec = cf.create('ns0:VirtualDeviceConfigSpec')\\n controller_spec.operation = 'add'\\n controller_spec.device = controller_device\\n disk_device = cf.create('ns0:VirtualDisk')\\n disk_device.capacityInKB = max(1, int(size_kb))\\n disk_device.key = (-101)\\n disk_device.unitNumber = 0\\n disk_device.controllerKey = (-100)\\n disk_device_bkng = cf.create('ns0:VirtualDiskFlatVer2BackingInfo')\\n if (disk_type == constants.DISK_TYPE_EAGER_ZEROED_THICK):\\n disk_device_bkng.eagerlyScrub = True\\n elif (disk_type == constants.DISK_TYPE_THIN):\\n disk_device_bkng.thinProvisioned = True\\n disk_device_bkng.fileName = ('[%s]' % ds_name)\\n disk_device_bkng.diskMode = 'persistent'\\n disk_device.backing = disk_device_bkng\\n disk_spec = cf.create('ns0:VirtualDeviceConfigSpec')\\n disk_spec.operation = 'add'\\n disk_spec.fileOperation = 'create'\\n disk_spec.device = disk_device\\n vm_file_info = cf.create('ns0:VirtualMachineFileInfo')\\n vm_file_info.vmPathName = ('[%s]' % ds_name)\\n create_spec = cf.create('ns0:VirtualMachineConfigSpec')\\n create_spec.name = name\\n create_spec.guestId = constants.DEFAULT_OS_TYPE\\n create_spec.numCPUs = 1\\n create_spec.memoryMB = 128\\n create_spec.deviceChange = [controller_spec, disk_spec]\\n create_spec.files = vm_file_info\\n return create_spec\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _inject_admin_password_into_fs(admin_passwd, fs):\",\"targets\":\"\\\"\\\"\\\"Set the root password to admin_passwd\\n admin_password is a root password\\n fs is the path to the base of the filesystem into which to inject\\n the key.\\n This method modifies the instance filesystem directly,\\n and does not require a guest agent running in the instance.\\n \\\"\\\"\\\"\\n LOG.debug('Inject admin password fs=%(fs)s admin_passwd=', {'fs': fs})\\n admin_user = 'root'\\n passwd_path = os.path.join('etc', 'passwd')\\n shadow_path = os.path.join('etc', 'shadow')\\n passwd_data = fs.read_file(passwd_path)\\n shadow_data = fs.read_file(shadow_path)\\n new_shadow_data = _set_passwd(admin_user, admin_passwd, passwd_data, shadow_data)\\n fs.replace_file(shadow_path, new_shadow_data)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _sign_app(src, dest, ids, reviewer, tempname, local=False):\\n\\n ''''Generate a manifest and signature and send signature to signing server to\\n be signed.'\\n '''\",\"targets\":\"active_endpoint = _get_endpoint(reviewer)\\n timeout = settings.SIGNED_APPS_SERVER_TIMEOUT\\n if (not active_endpoint):\\n _no_sign(src, dest)\\n return\\n try:\\n jar = JarExtractor(src, tempname, ids, omit_signature_sections=settings.SIGNED_APPS_OMIT_PER_FILE_SIGS)\\n except:\\n log.error('Archive extraction failed. Bad archive?', exc_info=True)\\n raise SigningError('Archive extraction failed. Bad archive?')\\n log.info(('App signature contents: %s' % jar.signatures))\\n log.info(('Calling service: %s' % active_endpoint))\\n try:\\n with statsd.timer('services.sign.app'):\\n response = requests.post(active_endpoint, timeout=timeout, files={'file': ('zigbert.sf', str(jar.signatures))})\\n except requests.exceptions.HTTPError as error:\\n log.error(('Posting to app signing failed: %s, %s' % (error.response.status, error)))\\n raise SigningError(('Posting to app signing failed: %s, %s' % (error.response.status, error)))\\n except:\\n log.error('Posting to app signing failed', exc_info=True)\\n raise SigningError('Posting to app signing failed')\\n if (response.status_code != 200):\\n log.error(('Posting to app signing failed: %s' % response.reason))\\n raise SigningError(('Posting to app signing failed: %s' % response.reason))\\n pkcs7 = b64decode(json.loads(response.content)['zigbert.rsa'])\\n try:\\n jar.make_signed(pkcs7, sigpath='zigbert')\\n except:\\n log.error('App signing failed', exc_info=True)\\n raise SigningError('App signing failed')\\n storage = public_storage\\n if reviewer:\\n storage = private_storage\\n elif local:\\n storage = local_storage\\n copy_stored_file(tempname, dest, src_storage=local_storage, dst_storage=storage)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def execute_sql(ctask, query_id, return_results=True, store_results=False):\",\"targets\":\"\\\"\\\"\\\"Executes the sql query returns the results.\\n \\\"\\\"\\\"\\n session = get_session((not ctask.request.called_directly))\\n query = get_query(query_id, session)\\n payload = dict(query_id=query_id)\\n database = query.database\\n db_engine_spec = database.db_engine_spec\\n db_engine_spec.patch()\\n def handle_error(msg):\\n 'Local method handling error while processing the SQL'\\n query.error_message = msg\\n query.status = QueryStatus.FAILED\\n query.tmp_table_name = None\\n session.commit()\\n payload.update({'status': query.status, 'error_essage': msg})\\n return payload\\n if (store_results and (not results_backend)):\\n return handle_error(\\\"Results backend isn't configured.\\\")\\n superset_query = SupersetQuery(query.sql)\\n executed_sql = superset_query.stripped()\\n if ((not superset_query.is_select()) and (not database.allow_dml)):\\n return handle_error('Only `SELECT` statements are allowed against this database')\\n if query.select_as_cta:\\n if (not superset_query.is_select()):\\n return handle_error('Only `SELECT` statements can be used with the CREATE TABLE feature.')\\n return\\n if (not query.tmp_table_name):\\n start_dttm = datetime.fromtimestamp(query.start_time)\\n query.tmp_table_name = 'tmp_{}_table_{}'.format(query.user_id, start_dttm.strftime('%Y_%m_%d_%H_%M_%S'))\\n executed_sql = superset_query.as_create_table(query.tmp_table_name)\\n query.select_as_cta_used = True\\n elif (query.limit and superset_query.is_select() and (db_engine_spec.limit_method == LimitMethod.WRAP_SQL)):\\n executed_sql = database.wrap_sql_limit(executed_sql, query.limit)\\n query.limit_used = True\\n try:\\n template_processor = get_template_processor(database=database, query=query)\\n executed_sql = template_processor.process_template(executed_sql)\\n except Exception as e:\\n logging.exception(e)\\n msg = ('Template rendering failed: ' +...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_folded_parameter_help_string(display_name, allow_none=False, allow_new=False, default_none=False, other_required_option=None):\\n\\n ''''Assembles a parameterized help string for folded parameters.'\\n '''\",\"targets\":\"quotes = ('\\\"\\\"' if (platform.system() == 'Windows') else \\\"''\\\")\\n if (default_none and (not allow_none)):\\n raise CLIError('Cannot use default_none=True and allow_none=False')\\n if ((not allow_new) and (not allow_none) and (not default_none)):\\n help_text = 'Name or ID of an existing {}.'.format(display_name)\\n elif ((not allow_new) and allow_none and (not default_none)):\\n help_text = 'Name or ID of an existing {}, or {} for none.'.format(display_name, quotes)\\n elif (allow_new and (not allow_none) and (not default_none)):\\n help_text = 'Name or ID of the {}. Will create resource if it does not exist.'.format(display_name)\\n elif (allow_new and allow_none and (not default_none)):\\n help_text = 'Name or ID of the {}, or {} for none. Uses existing resource if available or will create a new resource with defaults if omitted.'\\n help_text = help_text.format(display_name, quotes)\\n elif ((not allow_new) and allow_none and default_none):\\n help_text = 'Name or ID of an existing {}, or none by default.'.format(display_name)\\n elif (allow_new and allow_none and default_none):\\n help_text = 'Name or ID of a {}. Uses existing resource or creates new if specified, or none if omitted.'\\n help_text = help_text.format(display_name)\\n if other_required_option:\\n help_text = '{} If name specified, also specify {}'.format(help_text, other_required_option)\\n return help_text\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def is_complete_v3_key(v3_key):\",\"targets\":\"\\\"\\\"\\\"Returns True if a key specifies an ID or name, False otherwise.\\n Args:\\n v3_key: a datastore_pb.Reference\\n Returns:\\n True if the key specifies an ID or name, False otherwise.\\n \\\"\\\"\\\"\\n assert (v3_key.path().element_size() >= 1)\\n last_element = v3_key.path().element_list()[(-1)]\\n return ((last_element.has_id() and (last_element.id() != 0)) or (last_element.has_name() and (last_element.name() != '')))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef getFabmetheusUtilitiesPath(subName=''):\\n\\n ''''Get the fabmetheus utilities directory path.'\\n '''\",\"targets\":\"return getJoinedPath(getFabmetheusPath('fabmetheus_utilities'), subName)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@require_admin_context\\ndef compute_node_update(context, compute_id, values, auto_adjust):\",\"targets\":\"\\\"\\\"\\\"Creates a new ComputeNode and populates the capacity fields\\n with the most recent data.\\n \\\"\\\"\\\"\\n session = get_session()\\n if auto_adjust:\\n _adjust_compute_node_values_for_utilization(context, values, session)\\n with session.begin(subtransactions=True):\\n values['updated_at'] = timeutils.utcnow()\\n convert_datetimes(values, 'created_at', 'deleted_at', 'updated_at')\\n compute_ref = compute_node_get(context, compute_id, session=session)\\n for (key, value) in values.iteritems():\\n compute_ref[key] = value\\n compute_ref.save(session=session)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def extractField(field, event):\",\"targets\":\"\\\"\\\"\\\"Extract a given format field from the given event.\\n @param field: A string describing a format field or log key. This is the\\n text that would normally fall between a pair of curly braces in a\\n format string: for example, C{\\\"key[2].attribute\\\"}. If a conversion is\\n specified (the thing after the C{\\\"!\\\"} character in a format field) then\\n the result will always be L{unicode}.\\n @type field: L{str} (native string)\\n @param event: A log event.\\n @type event: L{dict}\\n @return: A value extracted from the field.\\n @rtype: L{object}\\n @raise KeyError: if the field is not found in the given event.\\n \\\"\\\"\\\"\\n keyFlattener = KeyFlattener()\\n [[literalText, fieldName, formatSpec, conversion]] = aFormatter.parse((('{' + field) + '}'))\\n key = keyFlattener.flatKey(fieldName, formatSpec, conversion)\\n if ('log_flattened' not in event):\\n flattenEvent(event)\\n return event['log_flattened'][key]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def blankout(src, char):\",\"targets\":\"\\\"\\\"\\\"Changes every non-whitespace character to the given char.\\n Used in the templatize function.\\n \\\"\\\"\\\"\\n return dot_re.sub(char, src)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def create(vm_):\",\"targets\":\"\\\"\\\"\\\"Provision a single machine\\n \\\"\\\"\\\"\\n clone_strategy = (vm_.get('clone_strategy') or 'full')\\n if (clone_strategy not in set(['quick', 'full'])):\\n raise SaltCloudSystemExit(\\\"'clone_strategy' must be one of quick or full. Got '{0}'\\\".format(clone_strategy))\\n ip_source = (vm_.get('ip_source') or 'ip-learning')\\n if (ip_source not in set(['ip-learning', 'qemu-agent'])):\\n raise SaltCloudSystemExit(\\\"'ip_source' must be one of qemu-agent or ip-learning. Got '{0}'\\\".format(ip_source))\\n validate_xml = (vm_.get('validate_xml') if (vm_.get('validate_xml') is not None) else True)\\n log.info(\\\"Cloning machine '{0}' with strategy '{1}' validate_xml='{2}'\\\".format(vm_['name'], clone_strategy, validate_xml))\\n try:\\n if (vm_['profile'] and (config.is_profile_configured(__opts__, (__active_provider_name__ or 'libvirt'), vm_['profile']) is False)):\\n return False\\n except AttributeError:\\n pass\\n name = vm_['name']\\n __utils__['cloud.fire_event']('event', 'starting create', 'salt\\/cloud\\/{0}\\/creating'.format(name), args=__utils__['cloud.filter_event']('creating', vm_, ['name', 'profile', 'provider', 'driver']), sock_dir=__opts__['sock_dir'], transport=__opts__['transport'])\\n key_filename = config.get_cloud_config_value('private_key', vm_, __opts__, search_global=False, default=None)\\n if ((key_filename is not None) and (not os.path.isfile(key_filename))):\\n raise SaltCloudConfigError(\\\"The defined key_filename '{0}' does not exist\\\".format(key_filename))\\n vm_['key_filename'] = key_filename\\n vm_['private_key'] = key_filename\\n cleanup = []\\n try:\\n base = vm_['base_domain']\\n conn = __get_conn(vm_['url'])\\n try:\\n clone_domain = conn.lookupByName(name)\\n except libvirtError as e:\\n domain = conn.lookupByName(base)\\n xml = domain.XMLDesc(0)\\n kwargs = {'name': name, 'base_domain': base}\\n __utils__['cloud.fire_event']('event',...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef decode(input, output, encoding):\\n\\n ''''Decode common content-transfer-encodings (base64, quopri, uuencode).'\\n '''\",\"targets\":\"if (encoding == 'base64'):\\n import base64\\n return base64.decode(input, output)\\n if (encoding == 'quoted-printable'):\\n import quopri\\n return quopri.decode(input, output)\\n if (encoding in ('uuencode', 'x-uuencode', 'uue', 'x-uue')):\\n import uu\\n return uu.decode(input, output)\\n if (encoding in ('7bit', '8bit')):\\n return output.write(input.read())\\n if (encoding in decodetab):\\n pipethrough(input, decodetab[encoding], output)\\n else:\\n raise ValueError, ('unknown Content-Transfer-Encoding: %s' % encoding)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@api_error_handler\\n@require_POST\\ndef share_document(request):\",\"targets\":\"\\\"\\\"\\\"Set who else or which other group can interact with the document.\\n Example of input: {\\\\read\\\\: {\\\\user_ids\\\\: [1, 2, 3], \\\\group_ids\\\\: [1, 2, 3]}}\\n \\\"\\\"\\\"\\n perms_dict = request.POST.get('data')\\n uuid = request.POST.get('uuid')\\n if ((not uuid) or (not perms_dict)):\\n raise PopupException(_('share_document requires uuid and perms_dict'))\\n else:\\n perms_dict = json.loads(perms_dict)\\n uuid = json.loads(uuid)\\n doc = Document2.objects.get_by_uuid(user=request.user, uuid=uuid)\\n for (name, perm) in perms_dict.iteritems():\\n users = groups = None\\n if perm.get('user_ids'):\\n users = User.objects.in_bulk(perm.get('user_ids'))\\n else:\\n users = []\\n if perm.get('group_ids'):\\n groups = Group.objects.in_bulk(perm.get('group_ids'))\\n else:\\n groups = []\\n doc = doc.share(request.user, name=name, users=users, groups=groups)\\n return JsonResponse({'status': 0, 'document': doc.to_dict()})\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@event(u'task.execute.started')\\ndef load_task(task):\",\"targets\":\"\\\"\\\"\\\"Loads all key\\/value pairs into memory before a task starts.\\n \\\"\\\"\\\"\\n if (not SimplePersistence.class_store[task.name]):\\n SimplePersistence.load(task.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 if (replay and ((no_input is not False) or (extra_context is not None))):\\n err_msg = u'You can not use both replay and no_input or extra_context at the same time.'\\n raise InvalidModeException(err_msg)\\n config_dict = get_user_config(config_file=config_file, default_config=default_config)\\n repo_dir = determine_repo_dir(template=template, abbreviations=config_dict[u'abbreviations'], clone_to_dir=config_dict[u'cookiecutters_dir'], checkout=checkout, no_input=no_input)\\n template_name = os.path.basename(os.path.abspath(repo_dir))\\n if replay:\\n context = load(config_dict[u'replay_dir'], template_name)\\n else:\\n context_file = os.path.join(repo_dir, u'cookiecutter.json')\\n logger.debug(u'context_file is {}'.format(context_file))\\n context = generate_context(context_file=context_file, default_context=config_dict[u'default_context'], extra_context=extra_context)\\n context[u'cookiecutter'] = prompt_for_config(context, no_input)\\n context[u'cookiecutter'][u'_template'] = template\\n dump(config_dict[u'replay_dir'], template_name, context)\\n return generate_files(repo_dir=repo_dir, context=context, overwrite_if_exists=overwrite_if_exists, output_dir=output_dir)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def cookiecutter(template, checkout=None, no_input=False, extra_context=None, replay=False, overwrite_if_exists=False, output_dir=u'.', config_file=None, default_config=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef list_nodes(call=None, **kwargs):\\n\\n ''''Return a list of the VMs that in this location'\\n '''\",\"targets\":\"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\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def from_html(html_code, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Generates a list of PrettyTables from a string of HTML code. Each in\\n the HTML becomes one PrettyTable object.\\n \\\"\\\"\\\"\\n parser = TableHandler(**kwargs)\\n parser.feed(html_code)\\n return parser.tables\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def b16encode(s):\",\"targets\":\"\\\"\\\"\\\"Encode a string using Base16.\\n s is the string to encode. The encoded string is returned.\\n \\\"\\\"\\\"\\n return binascii.hexlify(s).upper()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def encode_b64jose(data):\",\"targets\":\"\\\"\\\"\\\"Encode JOSE Base-64 field.\\n :param bytes data:\\n :rtype: `unicode`\\n \\\"\\\"\\\"\\n return b64.b64encode(data).decode('ascii')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@pytest.mark.parametrize('parallel', [True, False])\\ndef test_no_data(parallel, read_basic):\\n\\n ''''As long as column names are supplied, the C reader\\n should return an empty table in the absence of data.'\\n '''\",\"targets\":\"table = read_basic('a b c', parallel=parallel)\\n expected = Table([[], [], []], names=('a', 'b', 'c'))\\n assert_table_equal(table, expected)\\n table = read_basic('a b c\\\\n1 2 3', data_start=2, parallel=parallel)\\n assert_table_equal(table, expected)\",\"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, email) = parseaddr(email_string)\\n if check_format(email):\\n name = get_name_from_email_string(email_string, email, name)\\n return (name, email)\\n else:\\n email_regex = re.compile(u'([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\\\\\\\.[a-zA-Z0-9-.]+)')\\n email_list = re.findall(email_regex, email_string)\\n if ((len(email_list) > 0) and check_format(email_list[0])):\\n email = email_list[0]\\n name = get_name_from_email_string(email_string, email, name)\\n return (name, email)\\n return (None, email)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def parse_addr(email_string):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef describe_method(method):\\n\\n ''''Build descriptor for service method.\\n Args:\\n method: Remote service method to describe.\\n Returns:\\n Initialized MethodDescriptor instance describing the service method.'\\n '''\",\"targets\":\"method_info = method.remote\\n descriptor = MethodDescriptor()\\n descriptor.name = method_info.method.func_name\\n descriptor.request_type = method_info.request_type.definition_name()\\n descriptor.response_type = method_info.response_type.definition_name()\\n return descriptor\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n cmd_path = salt.utils.path.which(cmd)\\n if (not cmd_path):\\n return False\\n elif (not salt.utils.path.which('ldd')):\\n raise CommandNotFoundError('ldd')\\n out = __salt__['cmd.run']('ldd {0}'.format(cmd_path), python_shell=False)\\n return ('libfuse' in out)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def is_fuse_exec(cmd):\",\"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__(import_str)\\n return sys.modules[import_str]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def import_module(import_str):\",\"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_video_get_title_description', None) or _Cfunction('libvlc_video_get_title_description', ((1,),), None, ctypes.POINTER(TrackDescription), MediaPlayer))\\n return f(p_mi)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def libvlc_video_get_title_description(p_mi):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def check_bucket_name_dns_support(bucket_host, bucket_name):\",\"targets\":\"\\\"\\\"\\\"Check whether either the host_bucket support buckets and\\n either bucket name is dns compatible\\n \\\"\\\"\\\"\\n if ('%(bucket)s' not in bucket_host):\\n return False\\n return check_bucket_name_dns_conformity(bucket_name)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def cmd(command, *args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"run commands from __proxy__\\n :mod:`salt.proxy.nxos`\\n command\\n function from `salt.proxy.nxos` to run\\n args\\n positional args to pass to `command` function\\n kwargs\\n key word arguments to pass to `command` function\\n .. code-block:: bash\\n salt \\\\*\\\\ nxos.cmd sendline \\\\show ver\\\\\\n salt \\\\*\\\\ nxos.cmd show_run\\n salt \\\\*\\\\ nxos.cmd check_password username=admin password=\\\\$5$lkjsdfoi$blahblahblah\\\\ encrypted=True\\n \\\"\\\"\\\"\\n proxy_prefix = __opts__['proxy']['proxytype']\\n proxy_cmd = '.'.join([proxy_prefix, command])\\n if (proxy_cmd not in __proxy__):\\n return False\\n for k in kwargs:\\n if k.startswith('__pub_'):\\n kwargs.pop(k)\\n return __proxy__[proxy_cmd](*args, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n path_item = _normalize_cached(path_item)\\n if (os.path.isdir(path_item) and os.access(path_item, os.R_OK)):\\n if path_item.lower().endswith('.egg'):\\n (yield Distribution.from_filename(path_item, metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO'))))\\n else:\\n for entry in os.listdir(path_item):\\n lower = entry.lower()\\n if lower.endswith('.egg-info'):\\n fullpath = os.path.join(path_item, entry)\\n if os.path.isdir(fullpath):\\n metadata = PathMetadata(path_item, fullpath)\\n else:\\n metadata = FileMetadata(fullpath)\\n (yield Distribution.from_location(path_item, entry, metadata, precedence=DEVELOP_DIST))\\n elif ((not only) and lower.endswith('.egg')):\\n for dist in find_distributions(os.path.join(path_item, entry)):\\n (yield dist)\\n elif ((not only) and lower.endswith('.egg-link')):\\n for line in file(os.path.join(path_item, entry)):\\n if (not line.strip()):\\n continue\\n for item in find_distributions(os.path.join(path_item, line.rstrip())):\\n (yield item)\\n break\\n\\n\\nWhat's a good function header?\",\"targets\":\"def find_on_path(importer, path_item, only=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef checkProxy(selfip, proxies):\\n\\n '''':param\\n :return:'\\n '''\",\"targets\":\"protocol = (-1)\\n types = (-1)\\n speed = (-1)\\n (http, http_types, http_speed) = _checkHttpProxy(selfip, proxies)\\n (https, https_types, https_speed) = _checkHttpProxy(selfip, proxies, False)\\n if (http and https):\\n protocol = 2\\n types = http_types\\n speed = http_speed\\n elif http:\\n types = http_types\\n protocol = 0\\n speed = http_speed\\n elif https:\\n types = https_types\\n protocol = 1\\n speed = https_speed\\n else:\\n types = (-1)\\n protocol = (-1)\\n speed = (-1)\\n return (protocol, types, speed)\",\"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_parts = path.split(_PATH_CELL_SEP)\\n path_parts.reverse()\\n return _PATH_CELL_SEP.join(path_parts)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _reverse_path(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef convert_xor(tokens, local_dict, global_dict):\\n\\n ''''Treats XOR, ``^``, as exponentiation, ``**``.'\\n '''\",\"targets\":\"result = []\\n for (toknum, tokval) in tokens:\\n if (toknum == OP):\\n if (tokval == '^'):\\n result.append((OP, '**'))\\n else:\\n result.append((toknum, tokval))\\n else:\\n result.append((toknum, tokval))\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef check_ip_valid6(ip):\\n\\n ''''\u00e6\u00a3\u0080\u00e6\u009f\u00a5ipv6\u00e5\u009c\u00b0\u00e5\u009d\u0080\u00e7\u009a\u0084\u00e5\u0090\u0088\u00e6\u00b3\u0095\u00e6\u0080\u00a7'\\n '''\",\"targets\":\"if is_valid_ipv6(ip):\\n return 1\\n else:\\n return 0\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def GetAvailabilityZones(region):\",\"targets\":\"\\\"\\\"\\\"Retrieve the list of availability zones for \\\\region\\\\. Returns list of names.\\n \\\"\\\"\\\"\\n ec2 = _Connect(region)\\n return [z.name for z in ec2.get_all_zones()]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def is_orm_value(obj):\",\"targets\":\"\\\"\\\"\\\"Check if object is an ORM field.\\n \\\"\\\"\\\"\\n return IMPL.is_orm_value(obj)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef create_binding(name, site, hostheader='', ipaddress='*', port=80, protocol='http', sslflags=0):\\n\\n ''''Create an IIS binding.\\n .. note:\\n This function only validates against the binding ipaddress:port:hostheader combination,\\n and will return True even if the binding already exists with a different configuration.\\n It will not modify the configuration of an existing binding.\\n :param str site: The IIS site name.\\n :param str hostheader: The host header of the binding.\\n :param str ipaddress: The IP address of the binding.\\n :param str port: The TCP port of the binding.\\n :param str protocol: The application protocol of the binding.\\n :param str sslflags: The flags representing certificate type and storage of the binding.\\n Example of usage with only the required arguments:\\n .. code-block:: yaml\\n site0-https-binding:\\n win_iis.create_binding:\\n - site: site0\\n Example of usage specifying all available arguments:\\n .. code-block:: yaml\\n site0-https-binding:\\n win_iis.create_binding:\\n - site: site0\\n - hostheader: site0.local\\n - ipaddress: \\\\'*\\\\'\\n - port: 443\\n - protocol: https\\n - sslflags: 0'\\n '''\",\"targets\":\"ret = {'name': name, 'changes': {}, 'comment': str(), 'result': None}\\n binding_info = _get_binding_info(hostheader, ipaddress, port)\\n current_bindings = __salt__['win_iis.list_bindings'](site)\\n if (binding_info in current_bindings):\\n ret['comment'] = 'Binding already present: {0}'.format(binding_info)\\n ret['result'] = True\\n elif __opts__['test']:\\n ret['comment'] = 'Binding will be created: {0}'.format(binding_info)\\n ret['changes'] = {'old': None, 'new': binding_info}\\n else:\\n ret['comment'] = 'Created binding: {0}'.format(binding_info)\\n ret['changes'] = {'old': None, 'new': binding_info}\\n ret['result'] = __salt__['win_iis.create_binding'](site, hostheader, ipaddress, port, protocol, sslflags)\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _retry_on_integrity_error(func):\",\"targets\":\"\\\"\\\"\\\"Wraps a database function so that it gets retried on IntegrityError,\\n with `delete_existing=True` passed in.\\n Args:\\n func: function that returns a Deferred and accepts a `delete_existing` arg\\n \\\"\\\"\\\"\\n @wraps(func)\\n @defer.inlineCallbacks\\n def f(self, *args, **kwargs):\\n try:\\n res = (yield func(self, *args, **kwargs))\\n except self.database_engine.module.IntegrityError:\\n logger.exception('IntegrityError, retrying.')\\n res = (yield func(self, delete_existing=True, *args, **kwargs))\\n defer.returnValue(res)\\n return f\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def fail_without_changes(name):\",\"targets\":\"\\\"\\\"\\\"Returns failure.\\n .. versionadded:: 2014.7.0\\n name:\\n A unique string.\\n \\\"\\\"\\\"\\n ret = {'name': name, 'changes': {}, 'result': False, 'comment': 'Failure!'}\\n if __opts__['test']:\\n ret['result'] = False\\n ret['comment'] = \\\"If we weren't testing, this would be a failure!\\\"\\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 if (not _exactly_one((conn_id, name))):\\n raise SaltInvocationError('One (but not both) of vpc_peering_connection_id or name must be provided.')\\n conn = _get_conn3(region=region, key=key, keyid=keyid, profile=profile)\\n if name:\\n conn_id = _vpc_peering_conn_id_for_name(name, conn)\\n if (not conn_id):\\n raise SaltInvocationError('No ID found for this VPC peering connection! ({0}) Please make sure this VPC peering connection exists or invoke this function with a VPC peering connection ID'.format(name))\\n try:\\n log.debug('Trying to accept vpc peering connection')\\n conn.accept_vpc_peering_connection(DryRun=dry_run, VpcPeeringConnectionId=conn_id)\\n return {'msg': 'VPC peering connection accepted.'}\\n except botocore.exceptions.ClientError as err:\\n log.error('Got an error while trying to accept vpc peering')\\n return {'error': salt.utils.boto.get_error(err)}\\n\\n\\nWhat's a good function header?\",\"targets\":\"def accept_vpc_peering_connection(conn_id='', name='', region=None, key=None, keyid=None, profile=None, dry_run=False):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def isstdin():\",\"targets\":\"\\\"\\\"\\\"Returns true if the last line was read from sys.stdin,\\n otherwise returns false.\\n \\\"\\\"\\\"\\n if (not _state):\\n raise RuntimeError('no active input()')\\n return _state.isstdin()\",\"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 subprocess\\n if (sys.platform in ('dos', 'win32', 'win16', 'os2')):\\n return default\\n target = _follow_symlinks(target)\\n try:\\n proc = subprocess.Popen(['file', target], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\\n except (AttributeError, os.error):\\n return default\\n output = proc.communicate()[0]\\n rc = proc.wait()\\n if ((not output) or rc):\\n return default\\n else:\\n return output\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _syscmd_file(target, default=''):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef from_key_val_list(value):\\n\\n ''''Take an object and test to see if it can be represented as a\\n dictionary. Unless it can not be represented as such, return an\\n OrderedDict, e.g.,\\n >>> from_key_val_list([(\\\\'key\\\\', \\\\'val\\\\')])\\n OrderedDict([(\\\\'key\\\\', \\\\'val\\\\')])\\n >>> from_key_val_list(\\\\'string\\\\')\\n ValueError: need more than 1 value to unpack\\n >>> from_key_val_list({\\\\'key\\\\': \\\\'val\\\\'})\\n OrderedDict([(\\\\'key\\\\', \\\\'val\\\\')])'\\n '''\",\"targets\":\"if (value is None):\\n return None\\n if isinstance(value, (str, bytes, bool, int)):\\n raise ValueError('cannot encode objects that are not 2-tuples')\\n return OrderedDict(value)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _list_existing(filesystem, glob, paths):\\n\\n ''''Get all the paths that do in fact exist. Returns a set of all existing paths.\\n Takes a luigi.target.FileSystem object, a str which represents a glob and\\n a list of strings representing paths.'\\n '''\",\"targets\":\"globs = _constrain_glob(glob, paths)\\n time_start = time.time()\\n listing = []\\n for g in sorted(globs):\\n logger.debug('Listing %s', g)\\n if filesystem.exists(g):\\n listing.extend(filesystem.listdir(g))\\n logger.debug('%d %s listings took %f s to return %d items', len(globs), filesystem.__class__.__name__, (time.time() - time_start), len(listing))\\n return set(listing)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef fnmatchcase(name, pat):\\n\\n ''''Test whether FILENAME matches PATTERN, including case.\\n This is a version of fnmatch() which doesn\\\\'t case-normalize\\n its arguments.'\\n '''\",\"targets\":\"try:\\n re_pat = _cache[pat]\\n except KeyError:\\n res = translate(pat)\\n if (len(_cache) >= _MAXCACHE):\\n _cache.clear()\\n _cache[pat] = re_pat = re.compile(res)\\n return (re_pat.match(name) is not 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 for pattern in patterns:\\n if fnmatch(pathname, pattern):\\n return True\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def match_patterns(pathname, patterns):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def escape(s, quote=None):\",\"targets\":\"\\\"\\\"\\\"Replace special characters \\\"&\\\", \\\"<\\\" and \\\">\\\" to HTML-safe sequences.\\n If the optional flag quote is true, the quotation mark character (\\\")\\n is also translated.\\n \\\"\\\"\\\"\\n s = s.replace('&', '&')\\n s = s.replace('<', '<')\\n s = s.replace('>', '>')\\n if quote:\\n s = s.replace('\\\"', '"')\\n return s\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef libvlc_video_set_track(p_mi, i_track):\\n\\n ''''Set video track.\\n @param p_mi: media player.\\n @param i_track: the track ID (i_id field from track description).\\n @return: 0 on success, -1 if out of range.'\\n '''\",\"targets\":\"f = (_Cfunctions.get('libvlc_video_set_track', None) or _Cfunction('libvlc_video_set_track', ((1,), (1,)), None, ctypes.c_int, MediaPlayer, ctypes.c_int))\\n return f(p_mi, i_track)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"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 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 _get_virtual():\\n\\n ''''Return a dict of virtual package information'\\n '''\",\"targets\":\"try:\\n return __context__['pkg._get_virtual']\\n except KeyError:\\n __context__['pkg._get_virtual'] = {}\\n if HAS_APT:\\n try:\\n apt_cache = apt.cache.Cache()\\n except SystemError as syserr:\\n msg = 'Failed to get virtual package information ({0})'.format(syserr)\\n log.error(msg)\\n raise CommandExecutionError(msg)\\n pkgs = getattr(apt_cache._cache, 'packages', [])\\n for pkg in pkgs:\\n for item in getattr(pkg, 'provides_list', []):\\n realpkg = item[2].parent_pkg.name\\n if (realpkg not in __context__['pkg._get_virtual']):\\n __context__['pkg._get_virtual'][realpkg] = []\\n __context__['pkg._get_virtual'][realpkg].append(pkg.name)\\n elif _has_dctrl_tools():\\n cmd = ['grep-available', '-F', 'Provides', '-s', 'Package,Provides', '-e', '^.+$']\\n out = __salt__['cmd.run_stdout'](cmd, output_loglevel='trace', python_shell=False)\\n virtpkg_re = re.compile('Package: (\\\\\\\\S+)\\\\\\\\nProvides: ([\\\\\\\\S, ]+)')\\n for (realpkg, provides) in virtpkg_re.findall(out):\\n __context__['pkg._get_virtual'][realpkg] = provides.split(', ')\\n return __context__['pkg._get_virtual']\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef add_default_fields(elem, default_fields):\\n\\n ''''Add blank elements and subelements specified in default_fields.\\n :param elem: toolbox data in an elementtree structure\\n :type elem: ElementTree._ElementInterface\\n :param default_fields: fields to add to each type of element and subelement\\n :type default_fields: dict(tuple)'\\n '''\",\"targets\":\"for field in default_fields.get(elem.tag, []):\\n if (elem.find(field) is None):\\n SubElement(elem, field)\\n for child in elem:\\n add_default_fields(child, default_fields)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef execute_from_command_line(argv=None):\\n\\n ''''A simple method that runs a ManagementUtility.'\\n '''\",\"targets\":\"utility = ManagementUtility(argv)\\n utility.execute()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def irshift(a, b):\",\"targets\":\"\\\"\\\"\\\"Same as a >>= b.\\n \\\"\\\"\\\"\\n a >>= b\\n return a\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _create_base_cipher(dict_parameters):\\n\\n ''''This method instantiates and returns a handle to a low-level\\n base cipher. It will absorb named parameters in the process.'\\n '''\",\"targets\":\"try:\\n key = dict_parameters.pop('key')\\n except KeyError:\\n raise TypeError(\\\"Missing 'key' parameter\\\")\\n expect_byte_string(key)\\n if (len(key) != key_size):\\n raise ValueError(('Incorrect DES key length (%d bytes)' % len(key)))\\n start_operation = _raw_des_lib.DES_start_operation\\n stop_operation = _raw_des_lib.DES_stop_operation\\n cipher = VoidPointer()\\n result = start_operation(key, c_size_t(len(key)), cipher.address_of())\\n if result:\\n raise ValueError(('Error %X while instantiating the DES cipher' % result))\\n return SmartPointer(cipher.get(), stop_operation)\",\"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 theano.printing.pydot_imported):\\n raise SkipTest('pydot not available')\\n A = tensor.matrix()\\n prof = theano.compile.ProfileStats(atexit_print=False, gpu_checks=False)\\n f = theano.function([A], (A + 1), profile=prof)\\n theano.printing.pydotprint(f, print_output_file=False)\\n f([[1]])\\n theano.printing.pydotprint(f, print_output_file=False)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_pydotprint_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 from sklearn.base import clone\\n n_epochs = len(x_chunk)\\n estimators = list()\\n values = np.unique([val for sl in slices for val in sl])\\n for t_slice in slices:\\n t_slice = np.array([np.where((ii == values))[0][0] for ii in t_slice])\\n X = x_chunk[..., t_slice]\\n X = X.reshape(n_epochs, np.prod(X.shape[1:]))\\n estimators_ = list()\\n for (fold, (train, test)) in enumerate(cv_splits):\\n clf_ = clone(clf)\\n clf_.fit(X[train, :], y[train])\\n estimators_.append(clf_)\\n estimators.append(estimators_)\\n return estimators\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _fit_slices(clf, x_chunk, y, slices, cv_splits):\",\"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 ('Unpacking %s to %s' % (gz_path, new_path))\\n with gzip.open(gz_path, 'rb') as gz_file:\\n with open(new_path, 'wb') as new_file:\\n for line in gz_file:\\n new_file.write(line)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def gunzip_file(gz_path, new_path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef has_no_date(at):\\n\\n ''''Returns True if the given object is an ``adatetime`` where ``year``,\\n ``month``, and ``day`` are all None.'\\n '''\",\"targets\":\"if isinstance(at, datetime):\\n return False\\n return ((at.year is None) and (at.month is None) and (at.day is None))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef env(ip='1.2.3.4', **kwargs):\\n\\n '''':rtype: dict'\\n '''\",\"targets\":\"result = {'REMOTE_ADDR': ip}\\n result.update(kwargs)\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@dispatch(ColumnElement)\\ndef _coerce_op_input(i):\",\"targets\":\"\\\"\\\"\\\"Make input to SQLAlchemy operator an amenable type.\\n Parameters\\n i : ColumnElement\\n The column element to coerce.\\n Returns\\n coerced_input : sa.selectable.Select\\n A select wrapping the column element.\\n \\\"\\\"\\\"\\n return select(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 def wrapper(*args, **kwargs):\\n for arg in (list(args) + kwargs.values()):\\n if isinstance(arg, Promise):\\n break\\n else:\\n return func(*args, **kwargs)\\n return lazy(func, *resultclasses)(*args, **kwargs)\\n return wraps(func)(wrapper)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def allow_lazy(func, *resultclasses):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef educateEllipses(str):\\n\\n ''''Parameter: String.\\n Returns: The string, with each instance of \\\"...\\\" translated to\\n an ellipsis HTML entity.\\n Example input: Huh...?\\n Example output: Huh…?'\\n '''\",\"targets\":\"str = re.sub('\\\\\\\\.\\\\\\\\.\\\\\\\\.', '…', str)\\n str = re.sub('\\\\\\\\. \\\\\\\\. \\\\\\\\.', '…', str)\\n return str\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def catalog():\",\"targets\":\"\\\"\\\"\\\"Returns the current active catalog for further processing.\\n This can be used if you need to modify the catalog or want to access the\\n whole message catalog instead of just translating one string.\\n \\\"\\\"\\\"\\n global _default\\n t = getattr(_active, u'value', None)\\n if (t is not None):\\n return t\\n if (_default is None):\\n from django.conf import settings\\n _default = translation(settings.LANGUAGE_CODE)\\n return _default\",\"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 _ENGINE\\n if (_ENGINE is None):\\n _ENGINE = nova_session.create_engine(CONF.baremetal.sql_connection)\\n return _ENGINE\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_engine():\",\"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 url):\\n return False\\n try:\\n return (urlparse(url).scheme is not None)\\n except LocationParseError:\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def is_url(url):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _build_score_converter(score_converter_config):\",\"targets\":\"\\\"\\\"\\\"Builds score converter based on the config.\\n Builds one of [tf.identity, tf.sigmoid, tf.softmax] score converters based on\\n the config.\\n Args:\\n score_converter_config: post_processing_pb2.PostProcessing.score_converter.\\n Returns:\\n Callable score converter op.\\n Raises:\\n ValueError: On unknown score converter.\\n \\\"\\\"\\\"\\n if (score_converter_config == post_processing_pb2.PostProcessing.IDENTITY):\\n return tf.identity\\n if (score_converter_config == post_processing_pb2.PostProcessing.SIGMOID):\\n return tf.sigmoid\\n if (score_converter_config == post_processing_pb2.PostProcessing.SOFTMAX):\\n return tf.nn.softmax\\n raise ValueError('Unknown score converter.')\",\"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 unixtime:\\n return str(datetime.datetime.fromtimestamp((unixtime \\/ 1000)).strftime('%x %X %Z'))\\n else:\\n return ''\\n\\n\\nWhat's a good function header?\",\"targets\":\"def format_unixtime_ms(unixtime):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def copula_bv_ev(u, v, transform, args=()):\",\"targets\":\"\\\"\\\"\\\"generic bivariate extreme value copula\\n \\\"\\\"\\\"\\n return np.exp((np.log((u * v)) * transform((np.log(v) \\/ np.log((u * v))), *args)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def add_driver(notification_driver):\",\"targets\":\"\\\"\\\"\\\"Add a notification driver at runtime.\\n \\\"\\\"\\\"\\n _get_drivers()\\n if isinstance(notification_driver, basestring):\\n try:\\n driver = importutils.import_module(notification_driver)\\n _drivers[notification_driver] = driver\\n except ImportError:\\n LOG.exception((_('Failed to load notifier %s. These notifications will not be sent.') % notification_driver))\\n else:\\n _drivers[notification_driver] = notification_driver\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@hooks.before('Custom Forms > Custom Form Detail > Custom Form Detail')\\ndef custom_form_get_detail(transaction):\",\"targets\":\"\\\"\\\"\\\"GET \\/custom-forms\\/1\\n :param transaction:\\n :return:\\n \\\"\\\"\\\"\\n with stash['app'].app_context():\\n custom_form = CustomFormFactory()\\n db.session.add(custom_form)\\n db.session.commit()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def check_dependencies(model, model_queue, avaliable_models):\",\"targets\":\"\\\"\\\"\\\"Check that all the depenedencies for this model are already in the queue.\\n \\\"\\\"\\\"\\n allowed_links = ([m.model.__name__ for m in model_queue] + [model.__name__, 'ContentType'])\\n for field in model._meta.fields:\\n remote_field = (field.remote_field if hasattr(field, 'remote_field') else field.rel)\\n if (not remote_field):\\n continue\\n remote_field_model = (remote_field.model if hasattr(remote_field, 'model') else remote_field.to)\\n if (remote_field_model.__name__ not in allowed_links):\\n if (remote_field_model not in avaliable_models):\\n continue\\n return False\\n for field in model._meta.many_to_many:\\n remote_field = (field.remote_field if hasattr(field, 'remote_field') else field.rel)\\n if (not remote_field):\\n continue\\n remote_field_model = (remote_field.model if hasattr(remote_field, 'model') else remote_field.to)\\n if (remote_field_model.__name__ not in allowed_links):\\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 dist_string(dist):\\n\\n ''''Formats a distance (a float) as a colorized similarity percentage\\n string.'\\n '''\",\"targets\":\"out = (u'%.1f%%' % ((1 - dist) * 100))\\n if (dist <= config['match']['strong_rec_thresh'].as_number()):\\n out = ui.colorize('text_success', out)\\n elif (dist <= config['match']['medium_rec_thresh'].as_number()):\\n out = ui.colorize('text_warning', out)\\n else:\\n out = ui.colorize('text_error', out)\\n return out\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef argspec_report(functions, module=''):\\n\\n ''''Pass in a functions dict as it is returned from the loader and return the\\n argspec function signatures'\\n '''\",\"targets\":\"import salt.utils.args\\n ret = {}\\n if (('*' in module) or ('.' in module)):\\n for fun in fnmatch.filter(functions, module):\\n try:\\n aspec = salt.utils.args.get_function_argspec(functions[fun])\\n except TypeError:\\n continue\\n (args, varargs, kwargs, defaults) = aspec\\n ret[fun] = {}\\n ret[fun]['args'] = (args if args else None)\\n ret[fun]['defaults'] = (defaults if defaults else None)\\n ret[fun]['varargs'] = (True if varargs else None)\\n ret[fun]['kwargs'] = (True if kwargs else None)\\n else:\\n moduledot = (module + '.')\\n for fun in functions:\\n if fun.startswith(moduledot):\\n try:\\n aspec = salt.utils.args.get_function_argspec(functions[fun])\\n except TypeError:\\n continue\\n (args, varargs, kwargs, defaults) = aspec\\n ret[fun] = {}\\n ret[fun]['args'] = (args if args else None)\\n ret[fun]['defaults'] = (defaults if defaults else None)\\n ret[fun]['varargs'] = (True if varargs else None)\\n ret[fun]['kwargs'] = (True if kwargs else None)\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef funcEquipBuildCost(mapDict, allDatas, datas, dataName):\\n\\n '''''\\n '''\",\"targets\":\"d = {}\\n if (dataName == 'costBaseDatas'):\\n for (no, costInfo) in datas.items():\\n type = costInfo['type']\\n if (not d.get(type, False)):\\n d[type] = {}\\n level = costInfo['level']\\n d[type][level] = (costInfo['costType'], costInfo['cost'])\\n elif (dataName == 'costFactorDatas'):\\n for (no, costInfo) in datas.items():\\n type = costInfo['type']\\n if (not d.get(type, False)):\\n d[type] = {}\\n subType = costInfo['subType']\\n d[type][subType] = costInfo['factor']\\n return d\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef addObserverAndInit(name, cb):\\n\\n ''''We go ahead and call our observer once at startup to get an initial value'\\n '''\",\"targets\":\"vehicle.add_attribute_listener(name, cb)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n context = req.environ['placement.context']\\n uuid = util.wsgi_path_item(req.environ, 'uuid')\\n resource_class = util.wsgi_path_item(req.environ, 'resource_class')\\n resource_provider = objects.ResourceProvider.get_by_uuid(context, uuid)\\n data = _extract_inventory(req.body, BASE_INVENTORY_SCHEMA)\\n if (data['resource_provider_generation'] != resource_provider.generation):\\n raise webob.exc.HTTPConflict(_('resource provider generation conflict'))\\n inventory = _make_inventory_object(resource_provider, resource_class, **data)\\n try:\\n resource_provider.update_inventory(inventory)\\n except (exception.ConcurrentUpdateDetected, db_exc.DBDuplicateEntry) as exc:\\n raise webob.exc.HTTPConflict((_('update conflict: %(error)s') % {'error': exc}))\\n except exception.InventoryWithResourceClassNotFound as exc:\\n raise webob.exc.HTTPBadRequest((_('No inventory record with resource class for resource provider %(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, 'error': exc}))\\n except exception.InvalidInventoryCapacity as exc:\\n raise webob.exc.HTTPBadRequest((_('Unable to update inventory for resource provider %(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, 'error': exc}))\\n return _send_inventory(req.response, resource_provider, inventory)\\n\\n\\nWhat's a good function header?\",\"targets\":\"@wsgi_wrapper.PlacementWsgify\\n@util.require_content('application\\/json')\\ndef update_inventory(req):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n is_version_line = (lambda line: line.lower().startswith('version:'))\\n version_lines = filter(is_version_line, lines)\\n line = next(iter(version_lines), '')\\n (_, _, value) = line.partition(':')\\n return (safe_version(value.strip()) or None)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _version_from_file(lines):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef bing(phenny, input):\\n\\n ''''Queries Bing for the specified input.'\\n '''\",\"targets\":\"query = input.group(2)\\n if query.startswith(':'):\\n (lang, query) = query.split(' ', 1)\\n lang = lang[1:]\\n else:\\n lang = 'en-GB'\\n if (not query):\\n return phenny.reply('.bing what?')\\n query = query.encode('utf-8')\\n uri = bing_search(query, lang)\\n if uri:\\n phenny.reply(uri)\\n if (not hasattr(phenny.bot, 'last_seen_uri')):\\n phenny.bot.last_seen_uri = {}\\n phenny.bot.last_seen_uri[input.sender] = uri\\n else:\\n phenny.reply((\\\"No results found for '%s'.\\\" % query))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef fromstring(html, guess_charset=True, parser=None):\\n\\n ''''Parse the html, returning a single element\\/document.\\n This tries to minimally parse the chunk of text, without knowing if it\\n is a fragment or a document.\\n base_url will set the document\\\\'s base_url attribute (and the tree\\\\'s docinfo.URL)'\\n '''\",\"targets\":\"if (not isinstance(html, _strings)):\\n raise TypeError('string required')\\n doc = document_fromstring(html, parser=parser, guess_charset=guess_charset)\\n start = html[:50]\\n if isinstance(start, bytes):\\n start = start.decode('ascii', 'replace')\\n start = start.lstrip().lower()\\n if (start.startswith(',\\\\\\\\g<2>', str(value))\\n if (orig == new):\\n return new\\n else:\\n return intcomma(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 nsems_min = 256\\n try:\\n nsems = os.sysconf('SC_SEM_NSEMS_MAX')\\n except (AttributeError, ValueError):\\n return\\n if ((nsems == (-1)) or (nsems >= nsems_min)):\\n return\\n raise unittest.SkipTest((\\\"The OS doesn't support enough semaphores to run the test (required: %d).\\\" % nsems_min))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_enough_semaphores():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef dnslib_record2iplist(record):\\n\\n ''''convert dnslib.DNSRecord to iplist'\\n '''\",\"targets\":\"assert isinstance(record, dnslib.DNSRecord)\\n iplist = [x for x in (str(r.rdata) for r in record.rr) if (re.match('^\\\\\\\\d+\\\\\\\\.\\\\\\\\d+\\\\\\\\.\\\\\\\\d+\\\\\\\\.\\\\\\\\d+$', x) or (':' in x))]\\n return iplist\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef is_not_nat(builder, val):\\n\\n ''''Return a predicate which is true if *val* is not NaT.'\\n '''\",\"targets\":\"return builder.icmp(lc.ICMP_NE, val, NAT)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def check(rule, target, creds, exc=None, *args, **kwargs):\",\"targets\":\"\\\"\\\"\\\"Checks authorization of a rule against the target and credentials.\\n :param rule: The rule to evaluate.\\n :param target: As much information about the object being operated\\n on as possible, as a dictionary.\\n :param creds: As much information about the user performing the\\n action as possible, as a dictionary.\\n :param exc: Class of the exception to raise if the check fails.\\n Any remaining arguments passed to check() (both\\n positional and keyword arguments) will be passed to\\n the exception class. If exc is not provided, returns\\n False.\\n :return: Returns False if the policy does not allow the action and\\n exc is not provided; otherwise, returns a value that\\n evaluates to True. Note: for rules using the \\\"case\\\"\\n expression, this True value will be the specified string\\n from the expression.\\n \\\"\\\"\\\"\\n if isinstance(rule, BaseCheck):\\n result = rule(target, creds)\\n elif (not _rules):\\n result = False\\n else:\\n try:\\n result = _rules[rule](target, creds)\\n except KeyError:\\n result = False\\n if (exc and (result is False)):\\n raise exc(*args, **kwargs)\\n return result\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@image_comparison(baseline_images=[u'magnitude_spectrum_freqs_linear', u'magnitude_spectrum_freqs_dB'], remove_text=True, extensions=[u'png'])\\ndef test_magnitude_spectrum_freqs():\\n\\n ''''test axes.magnitude_spectrum with sinusoidal stimuli'\\n '''\",\"targets\":\"n = 10000\\n Fs = 100.0\\n fstims1 = [(Fs \\/ 4), (Fs \\/ 5), (Fs \\/ 11)]\\n NFFT = int(((1000 * Fs) \\/ min(fstims1)))\\n pad_to = int((2 ** np.ceil(np.log2(NFFT))))\\n x = np.arange(0, n, (1 \\/ Fs))\\n y = np.zeros(x.size)\\n for (i, fstim1) in enumerate(fstims1):\\n y += (np.sin((((fstim1 * x) * np.pi) * 2)) * (10 ** i))\\n y = y\\n fig1 = plt.figure()\\n fig2 = plt.figure()\\n ax11 = fig1.add_subplot(3, 1, 1)\\n ax12 = fig1.add_subplot(3, 1, 2)\\n ax13 = fig1.add_subplot(3, 1, 3)\\n ax21 = fig2.add_subplot(3, 1, 1)\\n ax22 = fig2.add_subplot(3, 1, 2)\\n ax23 = fig2.add_subplot(3, 1, 3)\\n (spec11, freqs11, line11) = ax11.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides=u'default')\\n (spec12, freqs12, line12) = ax12.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides=u'onesided')\\n (spec13, freqs13, line13) = ax13.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides=u'twosided')\\n (spec21, freqs21, line21) = ax21.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides=u'default', scale=u'dB')\\n (spec22, freqs22, line22) = ax22.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides=u'onesided', scale=u'dB')\\n (spec23, freqs23, line23) = ax23.magnitude_spectrum(y, Fs=Fs, pad_to=pad_to, sides=u'twosided', scale=u'dB')\\n ax11.set_xlabel(u'')\\n ax12.set_xlabel(u'')\\n ax13.set_xlabel(u'')\\n ax11.set_ylabel(u'')\\n ax12.set_ylabel(u'')\\n ax13.set_ylabel(u'')\\n ax21.set_xlabel(u'')\\n ax22.set_xlabel(u'')\\n ax23.set_xlabel(u'')\\n ax21.set_ylabel(u'')\\n ax22.set_ylabel(u'')\\n ax23.set_ylabel(u'')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef escape_dn_chars(dn):\\n\\n ''''Old versions of python-ldap won\\\\'t get DN escaping. Use with care.'\\n '''\",\"targets\":\"return dn\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def getKeyM(row, column, prefix=''):\",\"targets\":\"\\\"\\\"\\\"Get the m format key string from row & column, counting from one.\\n \\\"\\\"\\\"\\n return ('%sm%s%s' % (prefix, (row + 1), (column + 1)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _repr_pprint(obj, p, cycle):\",\"targets\":\"\\\"\\\"\\\"A pprint that just redirects to the normal repr function.\\n \\\"\\\"\\\"\\n output = repr(obj)\\n for (idx, output_line) in enumerate(output.splitlines()):\\n if idx:\\n p.break_()\\n p.text(output_line)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n handler = TestHandler(*args, **kwargs)\\n testcase.addCleanup(handler.close)\\n return handler\\n\\n\\nWhat's a good function header?\",\"targets\":\"@nottest\\ndef make_test_handler(testcase, *args, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _sympy_to_scalar(e):\\n\\n ''''Convert from a sympy scalar to a Python scalar.'\\n '''\",\"targets\":\"if isinstance(e, Expr):\\n if e.is_Integer:\\n return int(e)\\n elif e.is_Float:\\n return float(e)\\n elif e.is_Rational:\\n return float(e)\\n elif (e.is_Number or e.is_NumberSymbol or (e == I)):\\n return complex(e)\\n raise TypeError(('Expected number, got: %r' % e))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_commands():\",\"targets\":\"\\\"\\\"\\\"Returns a dictionary mapping command names to their callback applications.\\n This works by looking for a management.commands package in django.core, and\\n in each installed application -- if a commands package exists, all commands\\n in that package are registered.\\n Core commands are always included. If a settings module has been\\n specified, user-defined commands will also be included.\\n The dictionary is in the format {command_name: app_name}. Key-value\\n pairs from this dictionary can then be used in calls to\\n load_command_class(app_name, command_name)\\n If a specific version of a command must be loaded (e.g., with the\\n startapp command), the instantiated module can be placed in the\\n dictionary in place of the application name.\\n The dictionary is cached on the first call and reused on subsequent\\n calls.\\n \\\"\\\"\\\"\\n global _commands\\n if (_commands is None):\\n _commands = dict([(name, 'django.core') for name in find_commands(__path__[0])])\\n from django.conf import settings\\n try:\\n apps = settings.INSTALLED_APPS\\n except ImproperlyConfigured:\\n apps = []\\n for app_name in apps:\\n try:\\n path = find_management_module(app_name)\\n _commands.update(dict([(name, app_name) for name in find_commands(path)]))\\n except ImportError:\\n pass\\n return _commands\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef column_index_from_string(column, fast=False):\\n\\n ''''Convert a column letter into a column number (e.g. B -> 2)\\n Excel only supports 1-3 letter column names from A -> ZZZ, so we\\n restrict our column names to 1-3 characters, each in the range A-Z.\\n .. note::\\n Fast mode is faster but does not check that all letters are capitals between A and Z'\\n '''\",\"targets\":\"column = column.upper()\\n clen = len(column)\\n if ((not fast) and (not all((('A' <= char <= 'Z') for char in column)))):\\n msg = ('Column string must contain only characters A-Z: got %s' % column)\\n raise ColumnStringIndexException(msg)\\n if (clen == 1):\\n return (ord(column[0]) - 64)\\n elif (clen == 2):\\n return (((1 + (ord(column[0]) - 65)) * 26) + (ord(column[1]) - 64))\\n elif (clen == 3):\\n return ((((1 + (ord(column[0]) - 65)) * 676) + ((1 + (ord(column[1]) - 65)) * 26)) + (ord(column[2]) - 64))\\n elif (clen > 3):\\n raise ColumnStringIndexException('Column string index can not be longer than 3 characters')\\n else:\\n raise ColumnStringIndexException('Column string index can not be empty')\",\"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 = os.path.join(os.path.dirname(included_from), included_path)\\n if (not _IsFileOrDirWithFile(path)):\\n path = os.path.join(basepath, included_path)\\n if (not _IsFileOrDirWithFile(path)):\\n path = included_path\\n if (not _IsFileOrDirWithFile(path)):\\n return ''\\n if os.path.isfile(path):\\n return os.path.normcase(os.path.abspath(path))\\n return os.path.normcase(os.path.abspath(os.path.join(path, 'include.yaml')))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _ResolvePath(included_from, included_path, basepath):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@calculator(5571840)\\ndef calculate_perf_counter_100ns_queuelen_type(previous, current, property_name):\",\"targets\":\"\\\"\\\"\\\"PERF_COUNTER_100NS_QUEUELEN_TYPE\\n Average length of a queue to a resource over time in 100 nanosecond units.\\n https:\\/\\/msdn.microsoft.com\\/en-us\\/library\\/aa392905(v=vs.85).aspx\\n Formula (n1 - n0) \\/ (d1 - d0)\\n \\\"\\\"\\\"\\n n0 = previous[property_name]\\n n1 = current[property_name]\\n d0 = previous['Timestamp_Sys100NS']\\n d1 = current['Timestamp_Sys100NS']\\n if ((n0 is None) or (n1 is None)):\\n return\\n return ((n1 - n0) \\/ (d1 - d0))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef RawArray(typecode_or_type, size_or_initializer):\\n\\n ''''Returns a shared array'\\n '''\",\"targets\":\"from multiprocessing.sharedctypes import RawArray\\n return RawArray(typecode_or_type, size_or_initializer)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n argument_spec = dict(vrf=dict(required=True, type='str'), description=dict(required=False, type='str'), state=dict(choices=['absent', 'present'], default='present', required=False))\\n argument_spec.update(ce_argument_spec)\\n interface = Vrf(argument_spec)\\n interface.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 pass\\n\\n\\nWhat's a good function header?\",\"targets\":\"def p_primary_expression(t):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _node(default=''):\\n\\n ''''Helper to determine the node name of this machine.'\\n '''\",\"targets\":\"try:\\n import socket\\n except ImportError:\\n return default\\n try:\\n return socket.gethostname()\\n except socket.error:\\n return 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 logging.getLogger().setLevel(getattr(logging, flags.logging_level))\\n if (not flags.noauth_local_webserver):\\n success = False\\n port_number = 0\\n for port in flags.auth_host_port:\\n port_number = port\\n try:\\n httpd = ClientRedirectServer((flags.auth_host_name, port), ClientRedirectHandler)\\n except socket.error:\\n pass\\n else:\\n success = True\\n break\\n flags.noauth_local_webserver = (not success)\\n if (not success):\\n print('Failed to start a local webserver listening on either port 8080')\\n print('or port 9090. Please check your firewall settings and locally')\\n print('running programs that may be blocking or using those ports.')\\n print()\\n print('Falling back to --noauth_local_webserver and continuing with')\\n print('authorization.')\\n print()\\n if (not flags.noauth_local_webserver):\\n oauth_callback = ('http:\\/\\/%s:%s\\/' % (flags.auth_host_name, port_number))\\n else:\\n oauth_callback = client.OOB_CALLBACK_URN\\n flow.redirect_uri = oauth_callback\\n authorize_url = flow.step1_get_authorize_url()\\n if (not flags.noauth_local_webserver):\\n import webbrowser\\n webbrowser.open(authorize_url, new=1, autoraise=True)\\n print('Your browser has been opened to visit:')\\n print()\\n print((' ' + authorize_url))\\n print()\\n print('If your browser is on a different machine then exit and re-run this')\\n print('application with the command-line parameter ')\\n print()\\n print(' --noauth_local_webserver')\\n print()\\n else:\\n print('Go to the following link in your browser:')\\n print()\\n print((' ...\\n\\nWhat's a good function header?\",\"targets\":\"@util.positional(3)\\ndef run_flow(flow, storage, flags, http=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@hooks.before('Event Topics > Event Topic Details > Update Event Topic')\\ndef event_topic_patch(transaction):\",\"targets\":\"\\\"\\\"\\\"PATCH \\/event-topics\\/1\\n :param transaction:\\n :return:\\n \\\"\\\"\\\"\\n with stash['app'].app_context():\\n event_topic = EventTopicFactory()\\n db.session.add(event_topic)\\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 logging_client = logging.Client()\\n logger = logging_client.logger(logger_name)\\n logger.log_text('Hello, world!')\\n logger.log_text('Goodbye, world!', severity='ERROR')\\n logger.log_struct({'name': 'King Arthur', 'quest': 'Find the Holy Grail', 'favorite_color': 'Blue'})\\n print 'Wrote logs to {}.'.format(logger.name)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def write_entry(logger_name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@gen.coroutine\\ndef wait_for_spawner(spawner, timeout=10):\",\"targets\":\"\\\"\\\"\\\"Wait for an http server to show up\\n polling at shorter intervals for early termination\\n \\\"\\\"\\\"\\n deadline = (time.monotonic() + timeout)\\n def wait():\\n return spawner.server.wait_up(timeout=1, http=True)\\n while (time.monotonic() < deadline):\\n status = (yield spawner.poll())\\n assert (status is None)\\n try:\\n (yield wait())\\n except TimeoutError:\\n continue\\n else:\\n break\\n (yield wait())\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n path = os.path.expanduser(path)\\n if (not isinstance(file_hash, six.string_types)):\\n raise SaltInvocationError('hash must be a string')\\n for sep in (':', '='):\\n if (sep in file_hash):\\n (hash_type, hash_value) = file_hash.split(sep, 1)\\n break\\n else:\\n hash_value = file_hash\\n hash_len = len(file_hash)\\n hash_type = HASHES_REVMAP.get(hash_len)\\n if (hash_type is None):\\n raise SaltInvocationError('Hash {0} (length: {1}) could not be matched to a supported hash type. The supported hash types and lengths are: {2}'.format(file_hash, hash_len, ', '.join(['{0} ({1})'.format(HASHES_REVMAP[x], x) for x in sorted(HASHES_REVMAP)])))\\n return (get_hash(path, hash_type) == hash_value)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def check_hash(path, file_hash):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@constructor\\ndef sum(input, axis=None, dtype=None, keepdims=False, acc_dtype=None):\\n\\n ''''Computes the sum along the given axis(es) of a tensor `input`.\\n When axis is None (the default value), the sum is performed\\n over the flattened tensor.\\n For full documentation see ``tensor.elemwise.Sum``.\\n In particular please pay attention to the important warning when using\\n a custom acc_dtype.\\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.Sum(axis=axis, dtype=dtype, acc_dtype=acc_dtype)(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\":\"I wrote the below code\\n\\n po_path = '{path}\\/en\\/LC_MESSAGES\\/django.po'.format(path=base_path)\\n p = Popen(\\\"git diff -U0 {0} | egrep '^[-+]msgid' | wc -l\\\".format(po_path), stdout=PIPE, stderr=PIPE, shell=True)\\n (output, errors) = p.communicate()\\n num_changes = int(output.strip())\\n print \\\"{0} changed\\/added messages in '{1}' catalog.\\\".format(num_changes, cat_name)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _check_diff(cat_name, base_path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@layer_register()\\ndef ImageSample(inputs, borderMode='repeat'):\\n\\n ''''Sample the template image using the given coordinate, by bilinear interpolation.\\n This was described in the paper:\\n `Spatial Transformer Networks `_.\\n Args:\\n inputs (list): [template, coords]. template has shape NHWC.\\n coords has shape (N,H\\\\',W\\\\',2), where each pair of the last dimension is a (y, x) real-value\\n coordinate.\\n borderMode: either \\\"repeat\\\" or \\\"constant\\\" (zero-filled)\\n Returns:\\n tf.Tensor: a tensor named ``output`` of shape (N,H\\\\',W\\\\',C).'\\n '''\",\"targets\":\"(template, mapping) = inputs\\n assert ((template.get_shape().ndims == 4) and (mapping.get_shape().ndims == 4))\\n input_shape = template.get_shape().as_list()[1:]\\n assert (None not in input_shape), 'Images in ImageSample layer must have fully-defined shape'\\n assert (borderMode in ['repeat', 'constant'])\\n orig_mapping = mapping\\n mapping = tf.maximum(mapping, 0.0)\\n lcoor = tf.floor(mapping)\\n ucoor = (lcoor + 1)\\n diff = (mapping - lcoor)\\n neg_diff = (1.0 - diff)\\n (lcoory, lcoorx) = tf.split(lcoor, 2, 3)\\n (ucoory, ucoorx) = tf.split(ucoor, 2, 3)\\n lyux = tf.concat([lcoory, ucoorx], 3)\\n uylx = tf.concat([ucoory, lcoorx], 3)\\n (diffy, diffx) = tf.split(diff, 2, 3)\\n (neg_diffy, neg_diffx) = tf.split(neg_diff, 2, 3)\\n ret = tf.add_n([((sample(template, lcoor) * neg_diffx) * neg_diffy), ((sample(template, ucoor) * diffx) * diffy), ((sample(template, lyux) * neg_diffy) * diffx), ((sample(template, uylx) * diffy) * neg_diffx)], name='sampled')\\n if (borderMode == 'constant'):\\n max_coor = tf.constant([(input_shape[0] - 1), (input_shape[1] - 1)], dtype=tf.float32)\\n mask = tf.greater_equal(orig_mapping, 0.0)\\n mask2 = tf.less_equal(orig_mapping, max_coor)\\n mask = tf.logical_and(mask, mask2)\\n mask = tf.reduce_all(mask, [3])\\n mask = tf.expand_dims(mask, 3)\\n ret = (ret * tf.cast(mask, tf.float32))\\n return tf.identity(ret, name='output')\",\"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 outer_scope_test():\\n class Referenced:\\n pass\\n class C:\\n if Referenced:\\n pass\\n Assert(('Referenced' not in C.__dict__.keys()))\\n outer_scope_test()\\n for x in [None, 'abc', 3]:\\n class foo(object, ):\\n pass\\n a = foo()\\n try:\\n a.__dict__ = x\\n AssertUnreachable()\\n except TypeError:\\n pass\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_outer_scope():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@utils.arg('backup', metavar='', help='ID of the backup to delete.')\\n@utils.service_type('monitor')\\ndef do_backup_delete(cs, args):\",\"targets\":\"\\\"\\\"\\\"Remove a backup.\\n \\\"\\\"\\\"\\n backup = _find_backup(cs, args.backup)\\n backup.delete()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _encode_auth(auth):\",\"targets\":\"\\\"\\\"\\\"A function compatible with Python 2.3-3.3 that will encode\\n auth from a URL suitable for an HTTP header.\\n >>> str(_encode_auth(\\\\username%3Apassword\\\\))\\n \\\\dXNlcm5hbWU6cGFzc3dvcmQ=\\\\\\n Long auth strings should not cause a newline to be inserted.\\n >>> long_auth = \\\\username:\\\\ + \\\\password\\\\*10\\n >>> chr(10) in str(_encode_auth(long_auth))\\n False\\n \\\"\\\"\\\"\\n auth_s = unquote(auth)\\n auth_bytes = auth_s.encode()\\n encoded_bytes = base64.encodestring(auth_bytes)\\n encoded = encoded_bytes.decode()\\n return encoded.replace('\\\\n', '')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_algorithm_and_mac(wire, tsig_rdata, tsig_rdlen):\",\"targets\":\"\\\"\\\"\\\"Return the tsig algorithm for the specified tsig_rdata\\n @raises FormError: The TSIG is badly formed.\\n \\\"\\\"\\\"\\n current = tsig_rdata\\n (aname, used) = dns.name.from_wire(wire, current)\\n current = (current + used)\\n (upper_time, lower_time, fudge, mac_size) = struct.unpack('!HIHH', wire[current:(current + 10)])\\n current += 10\\n mac = wire[current:(current + mac_size)]\\n current += mac_size\\n if (current > (tsig_rdata + tsig_rdlen)):\\n raise dns.exception.FormError\\n return (aname, mac)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n parts = []\\n (quanta, leftover) = divmod(len(s), 5)\\n if leftover:\\n s += ('\\\\x00' * (5 - leftover))\\n quanta += 1\\n for i in range(quanta):\\n (c1, c2, c3) = struct.unpack('!HHB', s[(i * 5):((i + 1) * 5)])\\n c2 += ((c1 & 1) << 16)\\n c3 += ((c2 & 3) << 8)\\n parts.extend([_b32tab[(c1 >> 11)], _b32tab[((c1 >> 6) & 31)], _b32tab[((c1 >> 1) & 31)], _b32tab[(c2 >> 12)], _b32tab[((c2 >> 7) & 31)], _b32tab[((c2 >> 2) & 31)], _b32tab[(c3 >> 5)], _b32tab[(c3 & 31)]])\\n encoded = EMPTYSTRING.join(parts)\\n if (leftover == 1):\\n return (encoded[:(-6)] + '======')\\n elif (leftover == 2):\\n return (encoded[:(-4)] + '====')\\n elif (leftover == 3):\\n return (encoded[:(-3)] + '===')\\n elif (leftover == 4):\\n return (encoded[:(-1)] + '=')\\n return encoded\\n\\n\\nWhat's a good function header?\",\"targets\":\"def b32encode(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@skip('multiple_execute')\\ndef test_lookup_error():\",\"targets\":\"\\\"\\\"\\\"\\n \\\"\\\"\\\"\\n AssertError(LookupError, codecs.lookup_error, 'blah garbage xyz')\\n def garbage_error1(someError):\\n pass\\n codecs.register_error('blah garbage xyz', garbage_error1)\\n AreEqual(codecs.lookup_error('blah garbage xyz'), garbage_error1)\\n def garbage_error2(someError):\\n pass\\n codecs.register_error('some other', garbage_error2)\\n AreEqual(codecs.lookup_error('some other'), garbage_error2)\",\"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 _exponents_(expr, x, res):\\n if (expr == x):\\n res.update([1])\\n return\\n if (expr.is_Pow and (expr.base == x)):\\n res.update([expr.exp])\\n return\\n for arg in expr.args:\\n _exponents_(arg, x, res)\\n res = set()\\n _exponents_(expr, x, res)\\n return res\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _exponents(expr, 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 func.__doc__ = doc\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _add_doc(func, doc):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n conn = _auth(profile)\\n return conn.secgroup_create(name, description)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def secgroup_create(name, description, profile=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _get_offset_time(utc_offset):\",\"targets\":\"\\\"\\\"\\\"Will return the current time adjusted using the input timezone offset.\\n :rtype datetime:\\n \\\"\\\"\\\"\\n if (utc_offset is not None):\\n minutes = _offset_to_min(utc_offset)\\n offset = timedelta(minutes=minutes)\\n offset_time = (datetime.utcnow() + offset)\\n offset_time = offset_time.replace(tzinfo=_FixedOffset(minutes))\\n else:\\n offset_time = datetime.now()\\n return offset_time\",\"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 random\\n fdist = FreqDist()\\n for x in range(numoutcomes):\\n y = (random.randint(1, ((1 + numsamples) \\/\\/ 2)) + random.randint(0, (numsamples \\/\\/ 2)))\\n fdist[y] += 1\\n return fdist\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _create_rand_fdist(numsamples, numoutcomes):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"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\":\"Complete the below\\ndef latest(name, rev=None, target=None, clean=False, user=None, identity=None, force=False, opts=False, update_head=True):\\n\\n ''''Make sure the repository is cloned to the given directory and is up to date\\n name\\n Address of the remote repository as passed to \\\"hg clone\\\"\\n rev\\n The remote branch, tag, or revision hash to clone\\/pull\\n target\\n Target destination directory path on minion to clone into\\n clean\\n Force a clean update with -C (Default: False)\\n user\\n Name of the user performing repository management operations\\n .. versionadded:: 0.17.0\\n identity\\n Private SSH key on the minion server for authentication (ssh:\\/\\/)\\n .. versionadded:: 2015.5.0\\n force\\n Force hg to clone into pre-existing directories (deletes contents)\\n opts\\n Include additional arguments and options to the hg command line\\n update_head\\n Should we update the head if new changes are found? Defaults to True\\n .. versionadded:: 2017.7.0'\\n '''\",\"targets\":\"ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}\\n if (not target):\\n return _fail(ret, '\\\"target option is required')\\n is_repository = (os.path.isdir(target) and os.path.isdir('{0}\\/.hg'.format(target)))\\n if is_repository:\\n ret = _update_repo(ret, name, target, clean, user, identity, rev, opts, update_head)\\n else:\\n if os.path.isdir(target):\\n fail = _handle_existing(ret, target, force)\\n if (fail is not None):\\n return fail\\n else:\\n log.debug('target {0} is not found, \\\"hg clone\\\" is required'.format(target))\\n if __opts__['test']:\\n return _neutral_test(ret, 'Repository {0} is about to be cloned to {1}'.format(name, target))\\n _clone_repo(ret, target, name, user, identity, rev, opts)\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def create_git_repository(test_case, bare=False):\",\"targets\":\"\\\"\\\"\\\"Create a git repository with a ``master`` branch and ``README``.\\n :param test_case: The ``TestCase`` calling this.\\n \\\"\\\"\\\"\\n directory = FilePath(test_case.mktemp())\\n repository = Repo.init(path=directory.path, bare=bare)\\n if (not bare):\\n directory.child('README').makedirs()\\n directory.child('README').touch()\\n repository.index.add(['README'])\\n repository.index.commit('Initial commit')\\n repository.create_head('master')\\n return repository\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _yyyywwd2yyyymmdd(year, week, weekday):\\n\\n ''''Returns (year, month, day) for given (year, week, weekday).'\\n '''\",\"targets\":\"d = datetime(year, month=1, day=4)\\n d = ((d - timedelta((d.isoweekday() - 1))) + timedelta(days=(weekday - 1), weeks=(week - 1)))\\n return (d.year, d.month, d.day)\",\"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 hashlib import md5\\n hash = md5((namespace.bytes + bytes(name, 'utf-8'))).digest()\\n return UUID(bytes=hash[:16], version=3)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def uuid3(namespace, name):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_ordered_locations(locations, **kwargs):\\n\\n ''''Order 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 image location list with strategy-specific order.'\\n '''\",\"targets\":\"if (not locations):\\n return []\\n strategy_module = _available_strategies[CONF.location_strategy]\\n return strategy_module.get_ordered_locations(copy.deepcopy(locations), **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 acc = 0\\n unpack = struct.unpack\\n length = len(s)\\n if (length % 4):\\n extra = (4 - (length % 4))\\n s = ((b('\\\\x00') * extra) + s)\\n length = (length + extra)\\n for i in range(0, length, 4):\\n acc = ((acc << 32) + unpack('>I', s[i:(i + 4)])[0])\\n return acc\\n\\n\\nWhat's a good function header?\",\"targets\":\"def bytes_to_long(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def check_err(code):\",\"targets\":\"\\\"\\\"\\\"Checks the given OGRERR, and raises an exception where appropriate.\\n \\\"\\\"\\\"\\n if (code == OGRERR_NONE):\\n return\\n elif (code in OGRERR_DICT):\\n (e, msg) = OGRERR_DICT[code]\\n raise e(msg)\\n else:\\n raise OGRException(('Unknown error code: \\\"%s\\\"' % code))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n buf = []\\n iterator = imap(soft_unicode, seq)\\n for arg in iterator:\\n buf.append(arg)\\n if hasattr(arg, '__html__'):\\n return Markup(u'').join(chain(buf, iterator))\\n return concat(buf)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def markup_join(seq):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_template_dirs():\\n\\n ''''Returns a set of all directories that contain project templates.'\\n '''\",\"targets\":\"from django.conf import settings\\n dirs = set()\\n if (('django.template.loaders.filesystem.load_template_source' in settings.TEMPLATE_LOADERS) or ('django.template.loaders.filesystem.Loader' in settings.TEMPLATE_LOADERS)):\\n dirs.update(map(unicode, settings.TEMPLATE_DIRS))\\n if (('django.template.loaders.app_directories.load_template_source' in settings.TEMPLATE_LOADERS) or ('django.template.loaders.app_directories.Loader' in settings.TEMPLATE_LOADERS)):\\n from django.template.loaders.app_directories import app_template_dirs\\n dirs.update(app_template_dirs)\\n return dirs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def daub(p):\",\"targets\":\"\\\"\\\"\\\"The coefficients for the FIR low-pass filter producing Daubechies wavelets.\\n p>=1 gives the order of the zero at f=1\\/2.\\n There are 2p filter coefficients.\\n Parameters\\n p : int\\n Order of the zero at f=1\\/2, can have values from 1 to 34.\\n Returns\\n daub : ndarray\\n Return\\n \\\"\\\"\\\"\\n sqrt = np.sqrt\\n if (p < 1):\\n raise ValueError('p must be at least 1.')\\n if (p == 1):\\n c = (1 \\/ sqrt(2))\\n return np.array([c, c])\\n elif (p == 2):\\n f = (sqrt(2) \\/ 8)\\n c = sqrt(3)\\n return (f * np.array([(1 + c), (3 + c), (3 - c), (1 - c)]))\\n elif (p == 3):\\n tmp = (12 * sqrt(10))\\n z1 = ((1.5 + (sqrt((15 + tmp)) \\/ 6)) - ((1j * (sqrt(15) + sqrt((tmp - 15)))) \\/ 6))\\n z1c = np.conj(z1)\\n f = (sqrt(2) \\/ 8)\\n d0 = np.real(((1 - z1) * (1 - z1c)))\\n a0 = np.real((z1 * z1c))\\n a1 = (2 * np.real(z1))\\n return ((f \\/ d0) * np.array([a0, ((3 * a0) - a1), (((3 * a0) - (3 * a1)) + 1), ((a0 - (3 * a1)) + 3), (3 - a1), 1]))\\n elif (p < 35):\\n if (p < 35):\\n P = [comb(((p - 1) + k), k, exact=1) for k in range(p)][::(-1)]\\n yj = np.roots(P)\\n else:\\n P = [(comb(((p - 1) + k), k, exact=1) \\/ (4.0 ** k)) for k in range(p)][::(-1)]\\n yj = (np.roots(P) \\/ 4)\\n c = (np.poly1d([1, 1]) ** p)\\n q = np.poly1d([1])\\n for k in range((p - 1)):\\n yval = yj[k]\\n part = (2 * sqrt((yval * (yval - 1))))\\n const = (1 - (2 * yval))\\n z1 = (const + part)\\n if (abs(z1) < 1):\\n z1 = (const - part)\\n q = (q * [1, (- z1)])\\n q = (c * np.real(q))\\n q = ((q \\/ np.sum(q)) * sqrt(2))\\n return q.c[::(-1)]\\n else:\\n raise ValueError('Polynomial factorization does not work well for p too large.')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def collect_const(expr, *vars, **kwargs):\",\"targets\":\"\\\"\\\"\\\"A non-greedy collection of terms with similar number coefficients in\\n an Add expr. If ``vars`` is given then only those constants will be\\n targeted. Although any Number can also be targeted, if this is not\\n desired set ``Numbers=False`` and no Float or Rational will be collected.\\n Examples\\n >>> from sympy import sqrt\\n >>> from sympy.abc import a, s, x, y, z\\n >>> from sympy.simplify.radsimp import collect_const\\n >>> collect_const(sqrt(3) + sqrt(3)*(1 + sqrt(2)))\\n sqrt(3)*(sqrt(2) + 2)\\n >>> collect_const(sqrt(3)*s + sqrt(7)*s + sqrt(3) + sqrt(7))\\n (sqrt(3) + sqrt(7))*(s + 1)\\n >>> s = sqrt(2) + 2\\n >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7))\\n (sqrt(2) + 3)*(sqrt(3) + sqrt(7))\\n >>> collect_const(sqrt(3)*s + sqrt(3) + sqrt(7)*s + sqrt(7), sqrt(3))\\n sqrt(7) + sqrt(3)*(sqrt(2) + 3) + sqrt(7)*(sqrt(2) + 2)\\n The collection is sign-sensitive, giving higher precedence to the\\n unsigned values:\\n >>> collect_const(x - y - z)\\n x - (y + z)\\n >>> collect_const(-y - z)\\n -(y + z)\\n >>> collect_const(2*x - 2*y - 2*z, 2)\\n 2*(x - y - z)\\n >>> collect_const(2*x - 2*y - 2*z, -2)\\n 2*x - 2*(y + z)\\n See Also\\n collect, collect_sqrt, rcollect\\n \\\"\\\"\\\"\\n if (not expr.is_Add):\\n return expr\\n recurse = False\\n Numbers = kwargs.get('Numbers', True)\\n if (not vars):\\n recurse = True\\n vars = set()\\n for a in expr.args:\\n for m in Mul.make_args(a):\\n if m.is_number:\\n vars.add(m)\\n else:\\n vars = sympify(vars)\\n if (not Numbers):\\n vars = [v for v in vars if (not v.is_Number)]\\n vars = list(ordered(vars))\\n for v in vars:\\n terms = defaultdict(list)\\n Fv = Factors(v)\\n for m in Add.make_args(expr):\\n f = Factors(m)\\n (q, r) = f.div(Fv)\\n if r.is_one:\\n fwas = f.factors.copy()\\n fnow = q.factors\\n if (not any((((k in fwas) and fwas[k].is_Integer and (not fnow[k].is_Integer)) for k in fnow))):\\n terms[v].append(q.as_expr())\\n continue\\n terms[S.One].append(m)\\n args = []\\n hit = False\\n uneval = False\\n for k in ordered(terms):\\n v = terms[k]\\n if (k is S.One):\\n args.extend(v)\\n continue\\n if (len(v) > 1):\\n v = Add(*v)\\n hit = True\\n if (recurse and (v != expr)):\\n vars.append(v)\\n else:\\n v = v[0]\\n if (Numbers and k.is_Number and v.is_Add):\\n args.append(_keep_coeff(k, v, sign=True))\\n uneval = True\\n else:\\n args.append((k * v))\\n if hit:\\n if uneval:\\n expr = _unevaluated_Add(*args)\\n else:\\n expr = Add(*args)\\n if (not expr.is_Add):\\n break\\n return expr\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@_ConfigurableFilter(executable='HTML_TIDY_EXECUTABLE')\\ndef html_tidy_wrap_attr(infile, executable='tidy5'):\",\"targets\":\"\\\"\\\"\\\"Run HTML tidy with line wrapping and attribute indentation.\\n \\\"\\\"\\\"\\n return _html_tidy_runner(infile, '-quiet --show-info no --show-warnings no -utf8 -indent --indent-attributes yes --sort-attributes alpha --wrap 80 --wrap-sections no --drop-empty-elements no --tidy-mark no -modify %1', executable=executable)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n parser = CreateParser(query)\\n try:\\n return parser.query()\\n except Exception as e:\\n msg = (\\\"%s in query '%s'\\\" % (e.message, query))\\n raise QueryException(msg)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def Parse(query):\",\"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 = (iterable if isinstance(iterable, list) else list(iterable))\\n for m in xrange(len(a)):\\n i = (m - k)\\n j = ((m + k) + 1)\\n w = a[max(0, i):j]\\n (yield (float(sum(w)) \\/ (len(w) or 1)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def simple_moving_average(iterable, k=10):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@allow_unvouched\\n@never_cache\\ndef confirm_delete(request):\",\"targets\":\"\\\"\\\"\\\"Display a confirmation page asking the user if they want to\\n leave.\\n \\\"\\\"\\\"\\n return render(request, 'phonebook\\/confirm_delete.html')\",\"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 (0 <= n < (8 ** (digits - 1))):\\n s = (('%0*o' % ((digits - 1), n)).encode('ascii') + NUL)\\n else:\\n if ((format != GNU_FORMAT) or (n >= (256 ** (digits - 1)))):\\n raise ValueError('overflow in number field')\\n if (n < 0):\\n n = struct.unpack('L', struct.pack('l', n))[0]\\n s = bytearray()\\n for i in range((digits - 1)):\\n s.insert(0, (n & 255))\\n n >>= 8\\n s.insert(0, 128)\\n return s\\n\\n\\nWhat's a good function header?\",\"targets\":\"def itn(n, digits=8, format=DEFAULT_FORMAT):\",\"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 node.getchildren():\\n if (GetTag(child) == tag):\\n return child\\n\\n\\nWhat's a good function header?\",\"targets\":\"def GetChild(node, tag):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef encrypt_password(password, key=None):\\n\\n ''''Encrypt a password and encode as Base64.\\n The password will be encrypted using AES encryption in CFB mode (using an\\n 8-bit shift register), and serialized into Base64.\\n Args:\\n password (bytes):\\n The password to encrypt. If a unicode string is passed in, it will\\n be encoded to UTF-8 first.\\n key (bytes, optional):\\n The optional custom encryption key to use. If not supplied, the\\n default encryption key (from\\n :py:func:`get_default_aes_encryption_key)` will be used.\\n Returns:\\n bytes:\\n The encrypted password encoded in Base64.\\n Raises:\\n ValueError:\\n The encryption key was not in the right format.'\\n '''\",\"targets\":\"return base64.b64encode(aes_encrypt(password, key=key))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _objects_eq(manager, list_):\\n\\n ''''Assert that the objects contained by `manager` are those in `list_`.'\\n '''\",\"targets\":\"eq_(set(manager.all()), set(list_))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def getlocale(category=LC_CTYPE):\",\"targets\":\"\\\"\\\"\\\"Returns the current setting for the given locale category as\\n tuple (language code, encoding).\\n category may be one of the LC_* value except LC_ALL. It\\n defaults to LC_CTYPE.\\n Except for the code \\\\C\\\\, the language code corresponds to RFC\\n 1766. code and encoding can be None in case the values cannot\\n be determined.\\n \\\"\\\"\\\"\\n localename = _setlocale(category)\\n if ((category == LC_ALL) and (';' in localename)):\\n raise TypeError, 'category LC_ALL is not supported'\\n return _parse_localename(localename)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def clean_up():\",\"targets\":\"\\\"\\\"\\\"Delete tests files (to be used as tearDown() function in test fixtures)\\n \\\"\\\"\\\"\\n for filename in ['test_file', 'Phylip\\/opuntia.phy', 'Phylip\\/hedgehog.phy']:\\n if os.path.isfile(filename):\\n os.remove(filename)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef add_changes(parser, argparse):\\n\\n '''':type parser: argparse.ArgumentParser\\n :type argparse: argparse'\\n '''\",\"targets\":\"parser.add_argument('--changed', action='store_true', help='limit targets based on changes')\\n changes = parser.add_argument_group(title='change detection arguments')\\n changes.add_argument('--tracked', action='store_true', help=argparse.SUPPRESS)\\n changes.add_argument('--untracked', action='store_true', help='include untracked files')\\n changes.add_argument('--ignore-committed', dest='committed', action='store_false', help='exclude committed files')\\n changes.add_argument('--ignore-staged', dest='staged', action='store_false', help='exclude staged files')\\n changes.add_argument('--ignore-unstaged', dest='unstaged', action='store_false', help='exclude unstaged files')\\n changes.add_argument('--changed-from', metavar='PATH', help=argparse.SUPPRESS)\\n changes.add_argument('--changed-path', metavar='PATH', action='append', help=argparse.SUPPRESS)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _create_cadf_payload(operation, resource_type, resource_id, outcome, initiator, reason=None):\",\"targets\":\"\\\"\\\"\\\"Prepare data for CADF audit notifier.\\n Transform the arguments into content to be consumed by the function that\\n emits CADF events (_send_audit_notification). Specifically the\\n ``resource_type`` (role, user, etc) must be transformed into a CADF\\n keyword, such as: ``data\\/security\\/role``. The ``resource_id`` is added as a\\n top level value for the ``resource_info`` key. Lastly, the ``operation`` is\\n used to create the CADF ``action``, and the ``event_type`` name.\\n As per the CADF specification, the ``action`` must start with create,\\n update, delete, etc... i.e.: created.user or deleted.role\\n However the ``event_type`` is an OpenStack-ism that is typically of the\\n form project.resource.operation. i.e.: identity.project.updated\\n :param operation: operation being performed (created, updated, or deleted)\\n :param resource_type: type of resource being operated on (role, user, etc)\\n :param resource_id: ID of resource being operated on\\n :param outcome: outcomes of the operation (SUCCESS, FAILURE, etc)\\n :param initiator: CADF representation of the user that created the request\\n :param reason: pycadf object containing the response code and\\n message description\\n \\\"\\\"\\\"\\n if (resource_type not in CADF_TYPE_MAP):\\n target_uri = taxonomy.UNKNOWN\\n else:\\n target_uri = CADF_TYPE_MAP.get(resource_type)\\n target = resource.Resource(typeURI=target_uri, id=resource_id)\\n audit_kwargs = {'resource_info': resource_id}\\n cadf_action = ('%s.%s' % (operation, resource_type))\\n event_type = ('%s.%s.%s' % (SERVICE, resource_type, operation))\\n _send_audit_notification(cadf_action, initiator, outcome, target, event_type, reason=reason, **audit_kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef load_modules(rule, args=None):\\n\\n ''''Loads things that could be modules. Enhancements, alerts and rule type.'\\n '''\",\"targets\":\"match_enhancements = []\\n for enhancement_name in rule.get('match_enhancements', []):\\n if (enhancement_name in dir(enhancements)):\\n enhancement = getattr(enhancements, enhancement_name)\\n else:\\n enhancement = get_module(enhancement_name)\\n if (not issubclass(enhancement, enhancements.BaseEnhancement)):\\n raise EAException(('Enhancement module %s not a subclass of BaseEnhancement' % enhancement_name))\\n match_enhancements.append(enhancement(rule))\\n rule['match_enhancements'] = match_enhancements\\n if (rule['type'] in rules_mapping):\\n rule['type'] = rules_mapping[rule['type']]\\n else:\\n rule['type'] = get_module(rule['type'])\\n if (not issubclass(rule['type'], ruletypes.RuleType)):\\n raise EAException(('Rule module %s is not a subclass of RuleType' % rule['type']))\\n reqs = rule['type'].required_options\\n if (reqs - frozenset(rule.keys())):\\n raise EAException(('Missing required option(s): %s' % ', '.join((reqs - frozenset(rule.keys())))))\\n try:\\n rule['type'] = rule['type'](rule, args)\\n except (KeyError, EAException) as e:\\n raise EAException(('Error initializing rule %s: %s' % (rule['name'], e))), None, sys.exc_info()[2]\\n rule['alert'] = load_alerts(rule, alert_field=rule['alert'])\",\"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 = None\\n try:\\n if (not os.path.exists(fname)):\\n fname = (fname + '.gz')\\n f = gzip.open(fname)\\n elif fname.endswith('.gz'):\\n f = gzip.open(fname)\\n else:\\n f = open(fname)\\n d = ft.read(f)\\n finally:\\n if f:\\n f.close()\\n return d\\n\\n\\nWhat's a good function header?\",\"targets\":\"def load_filetensor(fname):\",\"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 ('\\\"' not in realm), 'Realms cannot contain the \\\" (quote) character.'\\n return ('Basic realm=\\\"%s\\\"' % realm)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def basicAuth(realm):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n blocksize = common.byte_size(pub_key.n)\\n encrypted = transform.bytes2int(signature)\\n decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)\\n clearsig = transform.int2bytes(decrypted, blocksize)\\n if (clearsig[0:2] != b('\\\\x00\\\\x01')):\\n raise VerificationError('Verification failed')\\n try:\\n sep_idx = clearsig.index(b('\\\\x00'), 2)\\n except ValueError:\\n raise VerificationError('Verification failed')\\n (method_name, signature_hash) = _find_method_hash(clearsig[(sep_idx + 1):])\\n message_hash = _hash(message, method_name)\\n if (message_hash != signature_hash):\\n raise VerificationError('Verification failed')\\n\\n\\nWhat's a good function header?\",\"targets\":\"def verify(message, signature, pub_key):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef i(message):\\n\\n ''''Print a normal log message.'\\n '''\",\"targets\":\"print_log(message)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def cache_clean(is_force_flush=False):\",\"targets\":\"\\\"\\\"\\\":param is_force_flush: \u00e6\u0098\u00af\u00e5\u0090\u0160\u00e6\u0097\u00a0\u00e8\u00a7\u0086\u00e6\u009c\u0089\u00e6\u0095\u0088\u00e6\u009c\u009f, \u00e6\u017e\u0085\u00e7\u0090\u0086\u00e6\u0089\u0080\u00e6\u009c\u0089\u00e7\u0152\u0093\u00e5\u00ad\u0098\\n :type is_force_flush: bool\\n \\\"\\\"\\\"\\n if enable_connection_keep_alive:\\n connection_pool.clear(force_flush=is_force_flush)\\n if local_cache_enable:\\n cache.check_all_expire(force_flush_all=is_force_flush)\\n if is_force_flush:\\n try:\\n url_to_use_cdn.clear()\\n is_domain_match_glob_whitelist.cache_clear()\\n is_mime_streamed.cache_clear()\\n extract_real_url_from_embedded_url.cache_clear()\\n embed_real_url_to_embedded_url.cache_clear()\\n check_global_ua_pass.cache_clear()\\n is_mime_represents_text.cache_clear()\\n extract_mime_from_content_type.cache_clear()\\n is_content_type_using_cdn.cache_clear()\\n is_ua_in_whitelist.cache_clear()\\n verify_ip_hash_cookie.cache_clear()\\n is_denied_because_of_spider.cache_clear()\\n is_ip_not_in_allow_range.cache_clear()\\n except:\\n errprint('ErrorWhenCleaningFunctionLruCache')\\n traceback.print_exc()\",\"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 isinstance(measure[name], (Date, DateTime))):\\n raise TypeError(\\\"'{name}' field must be a '{dt}', not: '{dshape}'\\\".format(name=name, dt=DateTime(), dshape=measure[name]))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _check_datetime_field(name, measure):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@sensitive_post_parameters()\\n@never_cache\\ndef password_reset_confirm(request, uidb36=None, token=None, template_name='registration\\/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None):\",\"targets\":\"\\\"\\\"\\\"View that checks the hash in a password reset link and presents a\\n form for entering a new password.\\n \\\"\\\"\\\"\\n UserModel = get_user_model()\\n assert ((uidb36 is not None) and (token is not None))\\n if (post_reset_redirect is None):\\n post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete')\\n try:\\n uid_int = base36_to_int(uidb36)\\n user = UserModel._default_manager.get(pk=uid_int)\\n except (ValueError, OverflowError, UserModel.DoesNotExist):\\n user = None\\n if ((user is not None) and token_generator.check_token(user, token)):\\n validlink = True\\n if (request.method == 'POST'):\\n form = set_password_form(user, request.POST)\\n if form.is_valid():\\n form.save()\\n return HttpResponseRedirect(post_reset_redirect)\\n else:\\n form = set_password_form(None)\\n else:\\n validlink = False\\n form = None\\n context = {'form': form, 'validlink': validlink}\\n if (extra_context is not None):\\n context.update(extra_context)\\n return TemplateResponse(request, template_name, context, current_app=current_app)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef file_dict(*packages):\\n\\n ''''List the files that belong to a package, grouped by package. Not\\n specifying any packages will return a list of _every_ file on the system\\\\'s\\n package database (not generally recommended).\\n CLI Examples:\\n .. code-block:: bash\\n salt \\\\'*\\\\' pkg.file_list httpd\\n salt \\\\'*\\\\' pkg.file_list httpd postfix\\n salt \\\\'*\\\\' pkg.file_list'\\n '''\",\"targets\":\"errors = []\\n ret = {}\\n cmd_files = ['opkg', 'files']\\n if (not packages):\\n packages = list(list_pkgs().keys())\\n for package in packages:\\n files = []\\n cmd = cmd_files[:]\\n cmd.append(package)\\n out = __salt__['cmd.run_all'](cmd, output_loglevel='trace', python_shell=False)\\n for line in out['stdout'].splitlines():\\n if line.startswith('\\/'):\\n files.append(line)\\n elif line.startswith(' * '):\\n errors.append(line[3:])\\n break\\n else:\\n continue\\n if files:\\n ret[package] = files\\n return {'errors': errors, 'packages': ret}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n hash_len = HASHES.get(hash_type)\\n if (hash_len is None):\\n if hash_type:\\n log.warning(\\\"file.extract_hash: Unsupported hash_type '%s', falling back to matching any supported hash_type\\\", hash_type)\\n hash_type = ''\\n hash_len_expr = '{0},{1}'.format(min(HASHES_REVMAP), max(HASHES_REVMAP))\\n else:\\n hash_len_expr = str(hash_len)\\n filename_separators = (string.whitespace + '\\\\\\\\\\/')\\n if source_hash_name:\\n if (not isinstance(source_hash_name, six.string_types)):\\n source_hash_name = str(source_hash_name)\\n source_hash_name_idx = ((len(source_hash_name) + 1) * (-1))\\n log.debug(\\\"file.extract_hash: Extracting %s hash for file matching source_hash_name '%s'\\\", ('any supported' if (not hash_type) else hash_type), source_hash_name)\\n if file_name:\\n if (not isinstance(file_name, six.string_types)):\\n file_name = str(file_name)\\n file_name_basename = os.path.basename(file_name)\\n file_name_idx = ((len(file_name_basename) + 1) * (-1))\\n if source:\\n if (not isinstance(source, six.string_types)):\\n source = str(source)\\n urlparsed_source = _urlparse(source)\\n source_basename = os.path.basename((urlparsed_source.path or urlparsed_source.netloc))\\n source_idx = ((len(source_basename) + 1) * (-1))\\n basename_searches = [x for x in (file_name, source) if x]\\n if basename_searches:\\n log.debug('file.extract_hash: %s %s hash for file matching%s: %s', ('If no source_hash_name match found, will extract' if source_hash_name else 'Extracting'), ('any supported' if (not hash_type) else hash_type), ('' if (len(basename_searches) == 1) else ' either of the following'), ', '.join(basename_searches))\\n partial = None\\n found = {}\\n with salt.utils.files.fopen(hash_fn, 'r') as fp_:\\n for line in fp_:\\n line = line.strip()\\n hash_re =...\\n\\nWhat's a good function header?\",\"targets\":\"def extract_hash(hash_fn, hash_type='sha256', file_name='', source='', source_hash_name=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _process_image_files_batch(coder, thread_index, ranges, name, filenames, texts, labels, num_shards):\\n\\n ''''Processes and saves list of images as TFRecord in 1 thread.\\n Args:\\n coder: instance of ImageCoder to provide TensorFlow image coding utils.\\n thread_index: integer, unique batch to run index is within [0, len(ranges)).\\n ranges: list of pairs of integers specifying ranges of each batches to\\n analyze in parallel.\\n name: string, unique identifier specifying the data set\\n filenames: list of strings; each string is a path to an image file\\n texts: list of strings; each string is human readable, e.g. \\\\'dog\\\\'\\n labels: list of integer; each integer identifies the ground truth\\n num_shards: integer number of shards for this data set.'\\n '''\",\"targets\":\"num_threads = len(ranges)\\n assert (not (num_shards % num_threads))\\n num_shards_per_batch = int((num_shards \\/ num_threads))\\n shard_ranges = np.linspace(ranges[thread_index][0], ranges[thread_index][1], (num_shards_per_batch + 1)).astype(int)\\n num_files_in_thread = (ranges[thread_index][1] - ranges[thread_index][0])\\n counter = 0\\n for s in range(num_shards_per_batch):\\n shard = ((thread_index * num_shards_per_batch) + s)\\n output_filename = ('%s-%.5d-of-%.5d' % (name, shard, num_shards))\\n output_file = os.path.join(FLAGS.output_directory, output_filename)\\n writer = tf.python_io.TFRecordWriter(output_file)\\n shard_counter = 0\\n files_in_shard = np.arange(shard_ranges[s], shard_ranges[(s + 1)], dtype=int)\\n for i in files_in_shard:\\n filename = filenames[i]\\n label = labels[i]\\n text = texts[i]\\n try:\\n (image_buffer, height, width) = _process_image(filename, coder)\\n except Exception as e:\\n print(e)\\n print(('SKIPPED: Unexpected eror while decoding %s.' % filename))\\n continue\\n example = _convert_to_example(filename, image_buffer, label, text, height, width)\\n writer.write(example.SerializeToString())\\n shard_counter += 1\\n counter += 1\\n if (not (counter % 1000)):\\n print(('%s [thread %d]: Processed %d of %d images in thread batch.' % (datetime.now(), thread_index, counter, num_files_in_thread)))\\n sys.stdout.flush()\\n writer.close()\\n print(('%s [thread %d]: Wrote %d images to %s' % (datetime.now(), thread_index, shard_counter, output_file)))\\n sys.stdout.flush()\\n shard_counter = 0\\n print(('%s [thread %d]: Wrote %d images to %d shards.' % (datetime.now(), thread_index, counter, num_files_in_thread)))\\n sys.stdout.flush()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def ismount(path):\",\"targets\":\"\\\"\\\"\\\"Test whether a path is a mount point (defined as root of drive)\\n \\\"\\\"\\\"\\n (unc, rest) = splitunc(path)\\n if unc:\\n return (rest in ('', '\\/', '\\\\\\\\'))\\n p = splitdrive(path)[1]\\n return ((len(p) == 1) and (p[0] in '\\/\\\\\\\\'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_async_test_timeout():\\n\\n ''''Get the global timeout setting for async tests.\\n Returns a float, the timeout in seconds.\\n .. versionadded:: 3.1'\\n '''\",\"targets\":\"try:\\n return float(os.environ.get('ASYNC_TEST_TIMEOUT'))\\n except (ValueError, TypeError):\\n return 5\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def main():\",\"targets\":\"\\\"\\\"\\\"Main function.\\n \\\"\\\"\\\"\\n args = docopt(__doc__, version='Mackup {}'.format(VERSION))\\n mckp = Mackup()\\n app_db = ApplicationsDatabase()\\n def printAppHeader(app_name):\\n if verbose:\\n print '\\\\n{0} {1} {0}'.format(header('---'), bold(app_name))\\n if args['--force']:\\n utils.FORCE_YES = True\\n dry_run = args['--dry-run']\\n verbose = args['--verbose']\\n if args['backup']:\\n mckp.check_for_usable_backup_env()\\n for app_name in sorted(mckp.get_apps_to_backup()):\\n app = ApplicationProfile(mckp, app_db.get_files(app_name), dry_run, verbose)\\n printAppHeader(app_name)\\n app.backup()\\n elif args['restore']:\\n mckp.check_for_usable_restore_env()\\n mackup_app = ApplicationProfile(mckp, app_db.get_files(MACKUP_APP_NAME), dry_run, verbose)\\n printAppHeader(MACKUP_APP_NAME)\\n mackup_app.restore()\\n mckp = Mackup()\\n app_db = ApplicationsDatabase()\\n app_names = mckp.get_apps_to_backup()\\n app_names.discard(MACKUP_APP_NAME)\\n for app_name in sorted(app_names):\\n app = ApplicationProfile(mckp, app_db.get_files(app_name), dry_run, verbose)\\n printAppHeader(app_name)\\n app.restore()\\n elif args['uninstall']:\\n mckp.check_for_usable_restore_env()\\n if (dry_run or utils.confirm('You are going to uninstall Mackup.\\\\nEvery configuration file, setting and dotfile managed by Mackup will be unlinked and moved back to their original place, in your home folder.\\\\nAre you sure ?')):\\n app_names = mckp.get_apps_to_backup()\\n app_names.discard(MACKUP_APP_NAME)\\n for app_name in sorted(app_names):\\n app = ApplicationProfile(mckp, app_db.get_files(app_name), dry_run, verbose)\\n printAppHeader(app_name)\\n app.uninstall()\\n mackup_app = ApplicationProfile(mckp, app_db.get_files(MACKUP_APP_NAME), dry_run,...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_bootinfo():\\n\\n ''''build and return boot info'\\n '''\",\"targets\":\"frappe.set_user_lang(frappe.session.user)\\n bootinfo = frappe._dict()\\n hooks = frappe.get_hooks()\\n doclist = []\\n get_user(bootinfo)\\n bootinfo.sysdefaults = frappe.defaults.get_defaults()\\n bootinfo.user_permissions = get_user_permissions()\\n bootinfo.server_date = frappe.utils.nowdate()\\n if (frappe.session[u'user'] != u'Guest'):\\n bootinfo.user_info = get_fullnames()\\n bootinfo.sid = frappe.session[u'sid']\\n bootinfo.modules = {}\\n bootinfo.module_list = []\\n load_desktop_icons(bootinfo)\\n bootinfo.letter_heads = get_letter_heads()\\n bootinfo.active_domains = frappe.get_active_domains()\\n bootinfo.all_domains = [d.get(u'name') for d in frappe.get_all(u'Domain')]\\n bootinfo.module_app = frappe.local.module_app\\n bootinfo.single_types = frappe.db.sql_list(u'select name from tabDocType\\\\n DCTB DCTB where issingle=1')\\n add_home_page(bootinfo, doclist)\\n bootinfo.page_info = get_allowed_pages()\\n load_translations(bootinfo)\\n add_timezone_info(bootinfo)\\n load_conf_settings(bootinfo)\\n load_print(bootinfo, doclist)\\n doclist.extend(get_meta_bundle(u'Page'))\\n bootinfo.home_folder = frappe.db.get_value(u'File', {u'is_home_folder': 1})\\n if frappe.session.data.get(u'ipinfo'):\\n bootinfo.ipinfo = frappe.session[u'data'][u'ipinfo']\\n bootinfo.docs = doclist\\n for method in (hooks.boot_session or []):\\n frappe.get_attr(method)(bootinfo)\\n if bootinfo.lang:\\n bootinfo.lang = text_type(bootinfo.lang)\\n bootinfo.versions = {k: v[u'version'] for (k, v) in get_versions().items()}\\n bootinfo.error_report_email = frappe.get_hooks(u'error_report_email')\\n bootinfo.calendars = sorted(frappe.get_hooks(u'calendars'))\\n bootinfo.treeviews = (frappe.get_hooks(u'treeviews') or [])\\n bootinfo.lang_dict = get_lang_dict()\\n bootinfo.feedback_triggers = get_enabled_feedback_trigger()\\n bootinfo.gsuite_enabled = get_gsuite_status()\\n bootinfo.update(get_email_accounts(user=frappe.session.user))\\n return bootinfo\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _MakeSyncCall(service, call, request, response, config=None):\",\"targets\":\"\\\"\\\"\\\"The APIProxy entry point for a synchronous API call.\\n Args:\\n service: For backwards compatibility, must be \\\\datastore_v3\\\\.\\n call: String representing which function to call.\\n request: Protocol buffer for the request.\\n response: Protocol buffer for the response.\\n config: Optional Configuration to use for this request.\\n Returns:\\n Response protocol buffer. Caller should always use returned value\\n which may or may not be same as passed in \\\\response\\\\.\\n Raises:\\n apiproxy_errors.Error or a subclass.\\n \\\"\\\"\\\"\\n conn = _GetConnection()\\n if isinstance(request, datastore_pb.Query):\\n conn._set_request_read_policy(request, config)\\n conn._set_request_transaction(request)\\n rpc = conn._make_rpc_call(config, call, request, response)\\n conn.check_rpc_success(rpc)\\n return response\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def add_or_replace_jacket(container):\",\"targets\":\"\\\"\\\"\\\"Either create a new jacket from the book\\\\s metadata or replace an\\n existing jacket. Returns True if an existing jacket was replaced.\\n \\\"\\\"\\\"\\n name = find_existing_jacket(container)\\n found = True\\n if (name is None):\\n jacket_item = container.generate_item(u'jacket.xhtml', id_prefix=u'jacket')\\n name = container.href_to_name(jacket_item.get(u'href'), container.opf_name)\\n found = False\\n if found:\\n remove_jacket_images(container, name)\\n replace_jacket(container, name)\\n if (not found):\\n index = 0\\n sp = container.abspath_to_name(container.spine_items.next())\\n if (sp == find_cover_page(container)):\\n index = 1\\n itemref = container.opf.makeelement(OPF(u'itemref'), idref=jacket_item.get(u'id'))\\n container.insert_into_xml(container.opf_xpath(u'\\/\\/opf:spine')[0], itemref, index=index)\\n return found\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def build_graph(ifilenames, graph, num_threads=1, tags=False):\",\"targets\":\"\\\"\\\"\\\"Construct a counting graph from a set of input files.\\n - ifilenames: list of input files\\n - graph: existing graph\\n - num_threads: number of threads (optional)\\n - tags: should there be tags\\n \\\"\\\"\\\"\\n if tags:\\n eat = graph.consume_seqfile_and_tag_with_reads_parser\\n else:\\n eat = graph.consume_seqfile_with_reads_parser\\n for (_, ifile) in enumerate(ifilenames):\\n rparser = khmer.ReadParser(ifile)\\n threads = []\\n for _ in range(num_threads):\\n cur_thread = threading.Thread(target=eat, args=(rparser,))\\n threads.append(cur_thread)\\n cur_thread.start()\\n for thread in threads:\\n thread.join()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n new_id = uuid4()\\n get_cache('event_transaction')['id'] = new_id\\n return new_id\\n\\n\\nWhat's a good function header?\",\"targets\":\"def create_new_event_transaction_id():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _save_and_remove_module(name, orig_modules):\",\"targets\":\"\\\"\\\"\\\"Helper function to save and remove a module from sys.modules\\n Raise ImportError if the module can\\\\t be imported.\\n \\\"\\\"\\\"\\n if (name not in sys.modules):\\n __import__(name)\\n del sys.modules[name]\\n for modname in list(sys.modules):\\n if ((modname == name) or modname.startswith((name + '.'))):\\n orig_modules[modname] = sys.modules[modname]\\n del sys.modules[modname]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n kv = kernel_ver()\\n pid = os.getpid()\\n if (kv[:2] == (2, 4)):\\n if (proc.open('meminfo').read().find('Inact_') == (-1)):\\n return 1\\n return 0\\n elif (kv[:2] == (2, 6)):\\n if os.path.exists(proc.path(pid, 'smaps')):\\n if (proc.open(pid, 'smaps').read().find('Pss:') != (-1)):\\n return 2\\n else:\\n return 1\\n if ((2, 6, 1) <= kv <= (2, 6, 9)):\\n return (-1)\\n return 0\\n elif ((kv[0] > 2) and os.path.exists(proc.path(pid, 'smaps'))):\\n return 2\\n else:\\n return 1\\n\\n\\nWhat's a good function header?\",\"targets\":\"def shared_val_accuracy():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n bits = token.split_contents()[1:]\\n var = TemplateIfParser(parser, bits).parse()\\n nodelist_true = parser.parse(('else', 'endsmart_if'))\\n token = parser.next_token()\\n if (token.contents == 'else'):\\n nodelist_false = parser.parse(('endsmart_if',))\\n parser.delete_first_token()\\n else:\\n nodelist_false = None\\n return SmartIfNode(var, nodelist_true, nodelist_false)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def smart_if(parser, token):\",\"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 prep(r):\\n if (r.method == 'profile'):\\n table = r.table\\n record = r.record\\n code = record.code\\n def dt_row_actions(component):\\n return (lambda r, list_id: [{'label': T('Open'), 'url': r.url(component=component, component_id='[id]', method='update.popup', vars={'refresh': list_id}), '_class': 'action-btn edit s3_modal'}, {'label': T('Delete'), '_ajaxurl': r.url(component=component, component_id='[id]', method='delete.json'), '_class': 'action-btn delete-btn-ajax dt-ajax-delete'}])\\n data_widget = dict(label='Data', label_create='Add Data', type='datatable', actions=dt_row_actions('indicator_data'), tablename='project_indicator_data', filter=(FS('indicator_id') == record.id), create_controller='project', create_function='indicator', create_component='indicator_data')\\n profile_widgets = [data_widget]\\n s3db.configure('project_indicator', profile_cols=1, profile_header=DIV(H2(code), H3(table.name.label), P(record.name), H3(table.verification.label), P(record.verification), _class='profile-header'), profile_title=('%s : %s' % (s3_unicode(s3.crud_strings['project_indicator'].title_display), code)), profile_widgets=profile_widgets)\\n s3db.configure('project_indicator_data', list_fields=['name', 'end_date', 'target_value', 'value', (T('Percentage'), 'percentage'), 'comments'])\\n s3.rfooter = A(T('Return to Project'), _href=URL(f='project', args=[record.project_id, 'indicator']), _class='action-btn')\\n elif (r.component_name == 'indicator_data'):\\n field = s3db.project_indicator_data.project_id\\n field.default = r.record.project_id\\n field.readable = field.writable = False\\n return True\\n s3.prep = prep\\n return s3_rest_controller()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def indicator():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def login_protected_redirect_view(request):\",\"targets\":\"\\\"\\\"\\\"A view that redirects all requests to the GET view\\n \\\"\\\"\\\"\\n return HttpResponseRedirect('\\/test_client_regress\\/get_view\\/')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_organization_courses(organization_id):\\n\\n ''''Client API operation adapter\\/wrapper'\\n '''\",\"targets\":\"if (not organizations_enabled()):\\n return []\\n from organizations import api as organizations_api\\n return organizations_api.get_organization_courses(organization_id)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef check_cs_op(result, func, cargs):\\n\\n ''''Checks the status code of a coordinate sequence operation.'\\n '''\",\"targets\":\"if (result == 0):\\n raise GEOSException('Could not set value on coordinate sequence')\\n else:\\n return 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 pass\\n\\n\\nWhat's a good function header?\",\"targets\":\"def release_lock():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def build_property_spec(client_factory, type='VirtualMachine', properties_to_collect=None, all_properties=False):\",\"targets\":\"\\\"\\\"\\\"Builds the Property Spec.\\n \\\"\\\"\\\"\\n if (not properties_to_collect):\\n properties_to_collect = ['name']\\n property_spec = client_factory.create('ns0:PropertySpec')\\n property_spec.all = all_properties\\n property_spec.pathSet = properties_to_collect\\n property_spec.type = type\\n return property_spec\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _add_doc(func, doc):\",\"targets\":\"\\\"\\\"\\\"Add documentation to a function.\\n \\\"\\\"\\\"\\n func.__doc__ = doc\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _find_identity_pool_ids(name, pool_id, conn):\",\"targets\":\"\\\"\\\"\\\"Given identity pool name (or optionally a pool_id and name will be ignored),\\n find and return list of matching identity pool id\\\\s.\\n \\\"\\\"\\\"\\n ids = []\\n if (pool_id is None):\\n for pools in salt.utils.boto3.paged_call(conn.list_identity_pools, marker_flag='NextToken', marker_arg='NextToken', MaxResults=25):\\n for pool in pools['IdentityPools']:\\n if (pool['IdentityPoolName'] == name):\\n ids.append(pool['IdentityPoolId'])\\n else:\\n ids.append(pool_id)\\n return ids\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"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 lst = []\\n path = cfg.script_dir.get_path()\\n if (path and os.access(path, os.R_OK)):\\n for script in globber_full(path):\\n if os.path.isfile(script):\\n if ((sabnzbd.WIN32 and (os.path.splitext(script)[1].lower() in PATHEXT) and (not (win32api.GetFileAttributes(script) & win32file.FILE_ATTRIBUTE_HIDDEN))) or script.endswith('.py') or ((not sabnzbd.WIN32) and userxbit(script) and (not os.path.basename(script).startswith('.')))):\\n lst.append(os.path.basename(script))\\n if none:\\n lst.insert(0, 'None')\\n if default:\\n lst.insert(0, 'Default')\\n return lst\\n\\n\\nWhat's a good function header?\",\"targets\":\"def list_scripts(default=False, none=True):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef internalcode(f):\\n\\n ''''Marks the function as internally used'\\n '''\",\"targets\":\"internal_code.add(f.func_code)\\n return f\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef isValidColor(color):\\n\\n ''''check color validity (equivalent to existing checks in _setColor)'\\n '''\",\"targets\":\"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\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n from headphones import updater, searcher, librarysync, postprocessor, torrentfinished\\n with SCHED_LOCK:\\n start_jobs = (not len(SCHED.get_jobs()))\\n minutes = CONFIG.SEARCH_INTERVAL\\n schedule_job(searcher.searchforalbum, 'Search for Wanted', hours=0, minutes=minutes)\\n minutes = CONFIG.DOWNLOAD_SCAN_INTERVAL\\n schedule_job(postprocessor.checkFolder, 'Download Scan', hours=0, minutes=minutes)\\n hours = CONFIG.LIBRARYSCAN_INTERVAL\\n schedule_job(librarysync.libraryScan, 'Library Scan', hours=hours, minutes=0)\\n hours = CONFIG.UPDATE_DB_INTERVAL\\n schedule_job(updater.dbUpdate, 'MusicBrainz Update', hours=hours, minutes=0)\\n if CONFIG.CHECK_GITHUB:\\n if CONFIG.CHECK_GITHUB_INTERVAL:\\n minutes = CONFIG.CHECK_GITHUB_INTERVAL\\n else:\\n minutes = 0\\n schedule_job(versioncheck.checkGithub, 'Check GitHub for updates', hours=0, minutes=minutes)\\n if (headphones.CONFIG.TORRENT_DOWNLOADER != 0):\\n minutes = CONFIG.TORRENT_REMOVAL_INTERVAL\\n schedule_job(torrentfinished.checkTorrentFinished, 'Torrent removal check', hours=0, minutes=minutes)\\n if (start_jobs and len(SCHED.get_jobs())):\\n try:\\n SCHED.start()\\n except Exception as e:\\n logger.info(e)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def initialize_scheduler():\",\"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 vehicle_class):\\n vehicle_class = Vehicle\\n handler = MAVConnection(ip, baud=baud, source_system=source_system, use_native=use_native)\\n vehicle = vehicle_class(handler)\\n if status_printer:\\n @vehicle.on_message('STATUSTEXT')\\n def listener(self, name, m):\\n status_printer(re.sub('(^|\\\\\\\\n)', '>>> ', m.text.decode('utf-8').rstrip()))\\n if _initialize:\\n vehicle.initialize(rate=rate, heartbeat_timeout=heartbeat_timeout)\\n if wait_ready:\\n if (wait_ready == True):\\n vehicle.wait_ready(True)\\n else:\\n vehicle.wait_ready(*wait_ready)\\n return vehicle\\n\\n\\nWhat's a good function header?\",\"targets\":\"def connect(ip, _initialize=True, wait_ready=None, status_printer=errprinter, vehicle_class=None, rate=4, baud=115200, heartbeat_timeout=30, source_system=255, use_native=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 def decorator(func):\\n def inner(request, *args, **kwargs):\\n if_modified_since = request.META.get('HTTP_IF_MODIFIED_SINCE')\\n if if_modified_since:\\n if_modified_since = parse_http_date_safe(if_modified_since)\\n if_none_match = request.META.get('HTTP_IF_NONE_MATCH')\\n if_match = request.META.get('HTTP_IF_MATCH')\\n if (if_none_match or if_match):\\n try:\\n etags = parse_etags((if_none_match or if_match))\\n except ValueError:\\n if_none_match = None\\n if_match = None\\n if etag_func:\\n res_etag = etag_func(request, *args, **kwargs)\\n else:\\n res_etag = None\\n if last_modified_func:\\n dt = last_modified_func(request, *args, **kwargs)\\n if dt:\\n res_last_modified = timegm(dt.utctimetuple())\\n else:\\n res_last_modified = None\\n else:\\n res_last_modified = None\\n response = None\\n if (not ((if_match and (if_modified_since or if_none_match)) or (if_match and if_none_match))):\\n if ((if_none_match and ((res_etag in etags) or (('*' in etags) and res_etag))) and ((not if_modified_since) or (res_last_modified and if_modified_since and (res_last_modified <= if_modified_since)))):\\n if (request.method in ('GET', 'HEAD')):\\n response = HttpResponseNotModified()\\n else:\\n logger.warning(('Precondition Failed: %s' % request.path), extra={'status_code': 412, 'request': request})\\n response = HttpResponse(status=412)\\n elif (if_match and (((not res_etag) and ('*' in etags)) or (res_etag and (res_etag not in etags)))):\\n logger.warning(('Precondition Failed: %s' % request.path), extra={'status_code': 412, 'request': request})\\n ...\\n\\nWhat's a good function header?\",\"targets\":\"def condition(etag_func=None, last_modified_func=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef load_grammar(gt='Grammar.txt', gp=None, save=True, force=False, logger=None):\\n\\n ''''Load the grammar (maybe from a pickle).'\\n '''\",\"targets\":\"if (logger is None):\\n logger = logging.getLogger()\\n if (gp is None):\\n (head, tail) = os.path.splitext(gt)\\n if (tail == '.txt'):\\n tail = ''\\n gp = (((head + tail) + '.'.join(map(str, sys.version_info))) + '.pickle')\\n if (force or (not _newer(gp, gt))):\\n logger.info('Generating grammar tables from %s', gt)\\n g = pgen.generate_grammar(gt)\\n if save:\\n logger.info('Writing grammar tables to %s', gp)\\n try:\\n g.dump(gp)\\n except IOError as e:\\n logger.info(('Writing failed:' + str(e)))\\n else:\\n g = grammar.Grammar()\\n g.load(gp)\\n return g\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef export_users(path_prefix='\\/', region=None, key=None, keyid=None, profile=None):\\n\\n ''''Get all IAM user details. Produces results that can be used to create an\\n sls file.\\n .. versionadded:: 2016.3.0\\n CLI Example:\\n salt-call boto_iam.export_users --out=txt | sed \\\"s\\/local: \\/\\/\\\" > iam_users.sls'\\n '''\",\"targets\":\"conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)\\n if (not conn):\\n return None\\n results = odict.OrderedDict()\\n users = get_all_users(path_prefix, region, key, keyid, profile)\\n for user in users:\\n name = user.user_name\\n _policies = conn.get_all_user_policies(name, max_items=100)\\n _policies = _policies.list_user_policies_response.list_user_policies_result.policy_names\\n policies = {}\\n for policy_name in _policies:\\n _policy = conn.get_user_policy(name, policy_name)\\n _policy = json.loads(_unquote(_policy.get_user_policy_response.get_user_policy_result.policy_document))\\n policies[policy_name] = _policy\\n user_sls = []\\n user_sls.append({'name': name})\\n user_sls.append({'policies': policies})\\n user_sls.append({'path': user.path})\\n results[('manage user ' + name)] = {'boto_iam.user_present': user_sls}\\n return _safe_dump(results)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@ignore_warnings(category=(DeprecationWarning, FutureWarning))\\ndef check_class_weight_balanced_linear_classifier(name, Classifier):\\n\\n ''''Test class weights with non-contiguous class labels.'\\n '''\",\"targets\":\"X = np.array([[(-1.0), (-1.0)], [(-1.0), 0], [(-0.8), (-1.0)], [1.0, 1.0], [1.0, 0.0]])\\n y = np.array([1, 1, 1, (-1), (-1)])\\n classifier = Classifier()\\n if hasattr(classifier, 'n_iter'):\\n classifier.set_params(n_iter=1000)\\n if hasattr(classifier, 'max_iter'):\\n classifier.set_params(max_iter=1000)\\n set_random_state(classifier)\\n classifier.set_params(class_weight='balanced')\\n coef_balanced = classifier.fit(X, y).coef_.copy()\\n n_samples = len(y)\\n n_classes = float(len(np.unique(y)))\\n class_weight = {1: (n_samples \\/ (np.sum((y == 1)) * n_classes)), (-1): (n_samples \\/ (np.sum((y == (-1))) * n_classes))}\\n classifier.set_params(class_weight=class_weight)\\n coef_manual = classifier.fit(X, y).coef_.copy()\\n assert_allclose(coef_balanced, coef_manual)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n parsed = raw_config_parse(config_filename)\\n return build_profile_map(parsed)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def load_config(config_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 a = 0\\n for temp in INV_VM:\\n if (uuid == temp):\\n a = (a + 1)\\n if (a < 1):\\n print DS_VM[uuid]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def find_match(uuid):\",\"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 (__grains__['kernel'] == 'Linux'):\\n if os.path.exists('\\/sbin\\/ethtool'):\\n return _mod_bufsize_linux(iface, *args, **kwargs)\\n return False\\n\\n\\nWhat's a good function header?\",\"targets\":\"def mod_bufsize(iface, *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 (context is None):\\n context = {}\\n context.setdefault('user', '127.0.0.1')\\n context.setdefault('ignore_auth', True)\\n return logic.get_action(action_name)(context=context, data_dict=kwargs)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def call_action(action_name, context=None, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@register.filter(is_safe=True)\\ndef floatformat(text, arg=(-1)):\",\"targets\":\"\\\"\\\"\\\"Displays a float to a specified number of decimal places.\\n If called without an argument, it displays the floating point number with\\n one decimal place -- but only if there\\\\s a decimal place to be displayed:\\n * num1 = 34.23234\\n * num2 = 34.00000\\n * num3 = 34.26000\\n * {{ num1|floatformat }} displays \\\"34.2\\\"\\n * {{ num2|floatformat }} displays \\\"34\\\"\\n * {{ num3|floatformat }} displays \\\"34.3\\\"\\n If arg is positive, it will always display exactly arg number of decimal\\n places:\\n * {{ num1|floatformat:3 }} displays \\\"34.232\\\"\\n * {{ num2|floatformat:3 }} displays \\\"34.000\\\"\\n * {{ num3|floatformat:3 }} displays \\\"34.260\\\"\\n If arg is negative, it will display arg number of decimal places -- but\\n only if there are places to be displayed:\\n * {{ num1|floatformat:\\\"-3\\\" }} displays \\\"34.232\\\"\\n * {{ num2|floatformat:\\\"-3\\\" }} displays \\\"34\\\"\\n * {{ num3|floatformat:\\\"-3\\\" }} displays \\\"34.260\\\"\\n If the input float is infinity or NaN, the (platform-dependent) string\\n representation of that value will be displayed.\\n \\\"\\\"\\\"\\n try:\\n input_val = force_text(text)\\n d = Decimal(input_val)\\n except UnicodeEncodeError:\\n return u''\\n except InvalidOperation:\\n if (input_val in special_floats):\\n return input_val\\n try:\\n d = Decimal(force_text(float(text)))\\n except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError):\\n return u''\\n try:\\n p = int(arg)\\n except ValueError:\\n return input_val\\n try:\\n m = (int(d) - d)\\n except (ValueError, OverflowError, InvalidOperation):\\n return input_val\\n if ((not m) and (p < 0)):\\n return mark_safe(formats.number_format((u'%d' % int(d)), 0))\\n if (p == 0):\\n exp = Decimal(1)\\n else:\\n exp = (Decimal(u'1.0') \\/ (Decimal(10) ** abs(p)))\\n try:\\n tupl = d.as_tuple()\\n units = (len(tupl[1]) - tupl[2])\\n prec = ((abs(p) + units) + 1)\\n (sign, digits, exponent) = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)).as_tuple()\\n digits = [six.text_type(digit) for digit in reversed(digits)]\\n while (len(digits) <= abs(exponent)):\\n digits.append(u'0')\\n digits.insert((- exponent), u'.')\\n if sign:\\n digits.append(u'-')\\n number = u''.join(reversed(digits))\\n return mark_safe(formats.number_format(number, abs(p)))\\n except InvalidOperation:\\n return input_val\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef action_allowed_user(user, app, action):\\n\\n ''''Similar to action_allowed, but takes user instead of request.'\\n '''\",\"targets\":\"allowed = any((match_rules(group.rules, app, action) for group in user.groups.all()))\\n return allowed\",\"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_sq = ((x ** 2) + (y ** 2))\\n theta = np.arctan2(y, x)\\n z = (np.cos(theta) \\/ r_sq)\\n return ((np.max(z) - z) \\/ (np.max(z) - np.min(z)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def dipole_potential(x, y):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n certs = {}\\n if (not os.path.isdir(directory)):\\n raise IOError('Invalid certificate directory: {0}'.format(directory))\\n glob_string = os.path.join(directory, '*.key')\\n cert_files = glob.glob(glob_string)\\n for cert_file in cert_files:\\n (public_key, _) = load_certificate(cert_file)\\n if public_key:\\n certs[public_key] = True\\n return certs\\n\\n\\nWhat's a good function header?\",\"targets\":\"def load_certificates(directory='.'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef list_url_unsafe_chars(name):\\n\\n ''''Return a list of the reserved characters.'\\n '''\",\"targets\":\"reserved_chars = ''\\n for i in name:\\n if (i in URL_RESERVED_CHARS):\\n reserved_chars += i\\n return reserved_chars\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n query = model_query(context, models.Aggregate)\\n query = query.join('_metadata')\\n query = query.filter((models.AggregateMetadata.key == key))\\n query = query.options(contains_eager('_metadata'))\\n query = query.options(joinedload('_hosts'))\\n return query.all()\\n\\n\\nWhat's a good function header?\",\"targets\":\"@pick_context_manager_reader\\ndef aggregate_get_by_metadata_key(context, key):\",\"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 enumerate(elts):\\n 'Return an iterable that pairs the index of an element with\\\\n that element.\\\\n\\\\n For Python 2.2 compatibility'\\n return zip(range(len(elts)), elts)\\n def bestMatchingService(service):\\n 'Return the index of the first matching type, or something\\\\n higher if no type matches.\\\\n\\\\n This provides an ordering in which service elements that\\\\n contain a type that comes earlier in the preferred types list\\\\n come before service elements that come later. If a service\\\\n element has more than one type, the most preferred one wins.\\\\n '\\n for (i, t) in enumerate(preferred_types):\\n if (preferred_types[i] in service.type_uris):\\n return i\\n return len(preferred_types)\\n prio_services = [(bestMatchingService(s), orig_index, s) for (orig_index, s) in enumerate(service_list)]\\n prio_services.sort()\\n for i in range(len(prio_services)):\\n prio_services[i] = prio_services[i][2]\\n return prio_services\\n\\n\\nWhat's a good function header?\",\"targets\":\"def arrangeByType(service_list, preferred_types):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@require_admin\\n@api_handle_error_with_json\\n@process_log_from_request\\ndef cancel_update_progress(request, process_log):\",\"targets\":\"\\\"\\\"\\\"API endpoint for getting progress data on downloads.\\n \\\"\\\"\\\"\\n process_log.cancel_requested = True\\n process_log.save()\\n return JsonResponseMessageSuccess(_('Cancelled update progress successfully.'))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef file_upload_view_verify(request):\\n\\n ''''Use the sha digest hash to verify the uploaded contents.'\\n '''\",\"targets\":\"form_data = request.POST.copy()\\n form_data.update(request.FILES)\\n for (key, value) in form_data.items():\\n if key.endswith('_hash'):\\n continue\\n if ((key + '_hash') not in form_data):\\n continue\\n submitted_hash = form_data[(key + '_hash')]\\n if isinstance(value, UploadedFile):\\n new_hash = hashlib.sha1(value.read()).hexdigest()\\n else:\\n new_hash = hashlib.sha1(force_bytes(value)).hexdigest()\\n if (new_hash != submitted_hash):\\n return HttpResponseServerError()\\n largefile = request.FILES['file_field2']\\n obj = FileModel()\\n obj.testfile.save(largefile.name, largefile)\\n return HttpResponse('')\",\"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 (limit == 'upstart'):\\n return (not _service_is_upstart(name))\\n elif (limit == 'sysvinit'):\\n return (not _service_is_sysv(name))\\n elif (_service_is_upstart(name) or _service_is_sysv(name)):\\n return False\\n else:\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def missing(name, limit=''):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def config(settings):\",\"targets\":\"\\\"\\\"\\\"Template settings for a default system\\n @ToDo: Rename this as \\\\Demo\\\\\\n \\\"\\\"\\\"\\n T = current.T\\n settings.base.prepopulate.append('default')\\n settings.base.guided_tour = True\\n settings.L10n.languages = OrderedDict([('ar', '\\\\xd8\\\\xa7\\\\xd9\\\\x84\\\\xd8\\\\xb9\\\\xd8\\\\xb1\\\\xd8\\\\xa8\\\\xd9\\\\x8a\\\\xd8\\\\xa9'), ('bs', 'Bosanski'), ('en', 'English'), ('fr', 'Fran\\\\xc3\\\\xa7ais'), ('de', 'Deutsch'), ('el', '\\\\xce\\\\xb5\\\\xce\\\\xbb\\\\xce\\\\xbb\\\\xce\\\\xb7\\\\xce\\\\xbd\\\\xce\\\\xb9\\\\xce\\\\xba\\\\xce\\\\xac'), ('es', 'Espa\\\\xc3\\\\xb1ol'), ('it', 'Italiano'), ('ja', '\\\\xe6\\\\x97\\\\xa5\\\\xe6\\\\x9c\\\\xac\\\\xe8\\\\xaa\\\\x9e'), ('km', '\\\\xe1\\\\x9e\\\\x97\\\\xe1\\\\x9e\\\\xb6\\\\xe1\\\\x9e\\\\x9f\\\\xe1\\\\x9e\\\\xb6\\\\xe1\\\\x9e\\\\x81\\\\xe1\\\\x9f\\\\x92\\\\xe1\\\\x9e\\\\x98\\\\xe1\\\\x9f\\\\x82\\\\xe1\\\\x9e\\\\x9a'), ('ko', '\\\\xed\\\\x95\\\\x9c\\\\xea\\\\xb5\\\\xad\\\\xec\\\\x96\\\\xb4'), ('mn', '\\\\xd0\\\\x9c\\\\xd0\\\\xbe\\\\xd0\\\\xbd\\\\xd0\\\\xb3\\\\xd0\\\\xbe\\\\xd0\\\\xbb \\\\xd1\\\\x85\\\\xd1\\\\x8d\\\\xd0\\\\xbb'), ('my', '\\\\xe1\\\\x80\\\\x99\\\\xe1\\\\x80\\\\xbc\\\\xe1\\\\x80\\\\x94\\\\xe1\\\\x80\\\\xba\\\\xe1\\\\x80\\\\x99\\\\xe1\\\\x80\\\\xac\\\\xe1\\\\x80\\\\x85\\\\xe1\\\\x80\\\\xac'), ('ne', '\\\\xe0\\\\xa4\\\\xa8\\\\xe0\\\\xa5\\\\x87\\\\xe0\\\\xa4\\\\xaa\\\\xe0\\\\xa4\\\\xbe\\\\xe0\\\\xa4\\\\xb2\\\\xe0\\\\xa5\\\\x80'), ('prs', '\\\\xd8\\\\xaf\\\\xd8\\\\xb1\\\\xdb\\\\x8c'), ('ps', '\\\\xd9\\\\xbe\\\\xda\\\\x9a\\\\xd8\\\\xaa\\\\xd9\\\\x88'), ('pt', 'Portugu\\\\xc3\\\\xaas'), ('pt-br', 'Portugu\\\\xc3\\\\xaas (Brasil)'), ('ru', '\\\\xd1\\\\x80\\\\xd1\\\\x83\\\\xd1\\\\x81\\\\xd1\\\\x81\\\\xd0\\\\xba\\\\xd0\\\\xb8\\\\xd0\\\\xb9'), ('tet', 'Tetum'), ('tl', 'Tagalog'), ('tr', 'T\\\\xc3\\\\xbcrk\\\\xc3\\\\xa7e'), ('ur', '\\\\xd8\\\\xa7\\\\xd8\\\\xb1\\\\xd8\\\\xaf\\\\xd9\\\\x88'), ('vi', 'Ti\\\\xe1\\\\xba\\\\xbfng Vi\\\\xe1\\\\xbb\\\\x87t'), ('zh-cn', '\\\\xe4\\\\xb8\\\\xad\\\\xe6\\\\x96\\\\x87 (\\\\xe7\\\\xae\\\\x80\\\\xe4\\\\xbd\\\\x93)'), ('zh-tw', '\\\\xe4\\\\xb8\\\\xad\\\\xe6\\\\x96\\\\x87 (\\\\xe7\\\\xb9\\\\x81\\\\xe9\\\\xab\\\\x94)')])\\n settings.L10n.decimal_separator = '.'\\n settings.gis.geonames_username = 'eden_test'\\n settings.modules = OrderedDict([('default', Storage(name_nice=T('Home'), restricted=False, access=None, module_type=None)), ('admin', Storage(name_nice=T('Administration'), restricted=True, access='|1|', module_type=None)), ('appadmin', Storage(name_nice=T('Administration'), restricted=True, module_type=None)), ('errors', Storage(name_nice=T('Ticket Viewer'), restricted=False, module_type=None)), ('sync', Storage(name_nice=T('Synchronization'), restricted=True, access='|1|', module_type=None)), ('tour',...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def dmp_to_dict(f, u, K=None, zero=False):\",\"targets\":\"\\\"\\\"\\\"Convert a ``K[X]`` polynomial to a ``dict````.\\n Examples\\n >>> from sympy.polys.densebasic import dmp_to_dict\\n >>> dmp_to_dict([[1, 0], [], [2, 3]], 1)\\n {(0, 0): 3, (0, 1): 2, (2, 1): 1}\\n >>> dmp_to_dict([], 0)\\n \\\"\\\"\\\"\\n if (not u):\\n return dup_to_dict(f, K, zero=zero)\\n if (dmp_zero_p(f, u) and zero):\\n return {((0,) * (u + 1)): K.zero}\\n (n, v, result) = (dmp_degree(f, u), (u - 1), {})\\n if (n == (- oo)):\\n n = (-1)\\n for k in range(0, (n + 1)):\\n h = dmp_to_dict(f[(n - k)], v)\\n for (exp, coeff) in h.items():\\n result[((k,) + exp)] = coeff\\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 range_header):\\n return (None, None)\\n try:\\n (range_type, ranges) = range_header.split('=', 1)\\n if (range_type != 'bytes'):\\n return (None, None)\\n ranges = ranges.lstrip()\\n if (',' in ranges):\\n return (None, None)\\n end = None\\n if ranges.startswith('-'):\\n start = int(ranges)\\n if (start == 0):\\n return (None, None)\\n else:\\n split_range = ranges.split('-', 1)\\n start = int(split_range[0])\\n if ((len(split_range) == 2) and split_range[1].strip()):\\n end = (int(split_range[1]) + 1)\\n if (start > end):\\n return (None, None)\\n return (start, end)\\n except ValueError:\\n return (None, None)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def ParseRangeHeader(range_header):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _set_controls(bundle, root, namespace):\\n\\n ''''Get controls from bundle XML\\n Set properties on ``bundle`` with controls from XML etree ``root``.'\\n '''\",\"targets\":\"namespaces = {'n': namespace}\\n controls = root.xpath('n:controls', namespaces=namespaces)[0]\\n kick_off_time = controls.xpath('n:kick-off-time', namespaces=namespaces)\\n if kick_off_time:\\n bundle.kick_off_time = oozie_to_django_datetime(kick_off_time[0].text)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_create_job_common_args(local_args):\",\"targets\":\"\\\"\\\"\\\"Returns a dict containing only the args that apply for create_job_common\\n Returns a subset of local_args, which contains only the arguments that can\\n be passed in to create_job_common().\\n \\\"\\\"\\\"\\n (arg_names, _, _, _) = inspect.getargspec(create_job_common)\\n return dict((item for item in local_args.iteritems() if (item[0] in arg_names)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n mean = tf.reduce_mean(x, axis=[(-1)], keep_dims=True)\\n variance = tf.reduce_mean(tf.square((x - mean)), axis=[(-1)], keep_dims=True)\\n norm_x = ((x - mean) * tf.rsqrt((variance + epsilon)))\\n return ((norm_x * scale) + bias)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def layer_norm_compute_python(x, epsilon, scale, bias):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_internal_wsgi_application():\\n\\n ''''Loads and returns the WSGI application as configured by the user in\\n ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,\\n this will be the ``application`` object in ``projectname\\/wsgi.py``.\\n This function, and the ``WSGI_APPLICATION`` setting itself, are only useful\\n for Django\\\\'s internal servers (runserver, runfcgi); external WSGI servers\\n should just be configured to point to the correct application object\\n directly.\\n If settings.WSGI_APPLICATION is not set (is ``None``), we just return\\n whatever ``django.core.wsgi.get_wsgi_application`` returns.'\\n '''\",\"targets\":\"from django.conf import settings\\n app_path = getattr(settings, u'WSGI_APPLICATION')\\n if (app_path is None):\\n return get_wsgi_application()\\n (module_name, attr) = app_path.rsplit(u'.', 1)\\n try:\\n mod = import_module(module_name)\\n except ImportError as e:\\n raise ImproperlyConfigured((u\\\"WSGI application '%s' could not be loaded; could not import module '%s': %s\\\" % (app_path, module_name, e)))\\n try:\\n app = getattr(mod, attr)\\n except AttributeError as e:\\n raise ImproperlyConfigured((u\\\"WSGI application '%s' could not be loaded; can't find '%s' in module '%s': %s\\\" % (app_path, attr, module_name, e)))\\n return app\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef chroomnumber(name, roomnumber):\\n\\n ''''Change the user\\\\'s Room Number\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' user.chroomnumber foo 123'\\n '''\",\"targets\":\"return _update_gecos(name, 'roomnumber', roomnumber)\",\"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 (key, value) in locals.iteritems():\\n if (key == 'self'):\\n continue\\n setattr(self, key, value)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def autoassign(self, locals):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_port_by_display_name(clusters, lswitch, display_name):\",\"targets\":\"\\\"\\\"\\\"Return (url, cluster_id) of port or raises ResourceNotFound\\n \\\"\\\"\\\"\\n query = ('\\/ws.v1\\/lswitch\\/%s\\/lport?display_name=%s&fields=*' % (lswitch, display_name))\\n LOG.debug(_(\\\"Looking for port with display_name '%(display_name)s' on: %(lswitch)s\\\"), locals())\\n for c in clusters:\\n try:\\n res_obj = do_single_request(HTTP_GET, query, cluster=c)\\n except Exception as e:\\n continue\\n res = json.loads(res_obj)\\n if (len(res['results']) == 1):\\n return (res['results'][0], c)\\n LOG.error(_('Port or Network not found, Error: %s'), str(e))\\n raise exception.PortNotFound(port_id=display_name, net_id=lswitch)\",\"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(path, six.text_type):\\n return path\\n assert isinstance(path, bytes)\\n if six.PY2:\\n return path\\n return os.fsdecode(path)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def py3_path(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def install_js():\",\"targets\":\"\\\"\\\"\\\"Copy built BokehJS files into the Python source tree.\\n Returns:\\n None\\n \\\"\\\"\\\"\\n target_jsdir = join(SERVER, 'static', 'js')\\n target_cssdir = join(SERVER, 'static', 'css')\\n STATIC_ASSETS = [join(JS, 'bokeh.js'), join(JS, 'bokeh.min.js'), join(CSS, 'bokeh.css'), join(CSS, 'bokeh.min.css')]\\n if (not all([exists(a) for a in STATIC_ASSETS])):\\n print(BOKEHJS_INSTALL_FAIL)\\n sys.exit(1)\\n if exists(target_jsdir):\\n shutil.rmtree(target_jsdir)\\n shutil.copytree(JS, target_jsdir)\\n if exists(target_cssdir):\\n shutil.rmtree(target_cssdir)\\n shutil.copytree(CSS, target_cssdir)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _read_3(fid):\\n\\n ''''Read 3 byte integer from file.'\\n '''\",\"targets\":\"data = np.fromfile(fid, dtype=np.uint8, count=3).astype(np.int32)\\n out = ((np.left_shift(data[0], 16) + np.left_shift(data[1], 8)) + data[2])\\n return out\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def insert_pure_function(module, fnty, name):\",\"targets\":\"\\\"\\\"\\\"Insert a pure function (in the functional programming sense) in the\\n given module.\\n \\\"\\\"\\\"\\n fn = module.get_or_insert_function(fnty, name=name)\\n fn.attributes.add('readonly')\\n fn.attributes.add('nounwind')\\n return fn\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_environ_proxies(url):\\n\\n ''''Return a dict of environment proxies.'\\n '''\",\"targets\":\"if should_bypass_proxies(url):\\n return {}\\n else:\\n return getproxies()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def educate_ellipses(s):\",\"targets\":\"\\\"\\\"\\\"Parameter: String.\\n Returns: The string, with each instance of \\\"...\\\" translated to\\n an ellipsis HTML entity.\\n Example input: Huh...?\\n Example output: Huh…?\\n \\\"\\\"\\\"\\n return s.replace('...', '…').replace('. . .', '…')\",\"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)\\n@stringfilter\\ndef slugify(value):\\n\\n ''''Normalizes string, converts to lowercase, removes non-alpha characters,\\n and converts spaces to hyphens.'\\n '''\",\"targets\":\"value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')\\n value = unicode(re.sub('[^\\\\\\\\w\\\\\\\\s-]', '', value).strip().lower())\\n return mark_safe(re.sub('[-\\\\\\\\s]+', '-', value))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef debug(request, message, extra_tags='', fail_silently=False):\\n\\n ''''Adds a message with the ``DEBUG`` level.'\\n '''\",\"targets\":\"add_message(request, constants.DEBUG, message, extra_tags=extra_tags, fail_silently=fail_silently)\",\"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 getattr(mat, 'is_Matrix', False):\\n return mat\\n if hasattr(mat, 'shape'):\\n if (len(mat.shape) == 2):\\n return _MatrixWrapper(mat)\\n return mat\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _matrixify(mat):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n _handle_old_style_images(staging_path)\\n _validate_sequenced_vhds(staging_path)\\n files_to_move = []\\n seq_num = 0\\n while True:\\n orig_vhd_path = os.path.join(staging_path, ('%d.vhd' % seq_num))\\n if (not os.path.exists(orig_vhd_path)):\\n break\\n vhd_uuid = uuid_stack.pop()\\n vhd_path = os.path.join(staging_path, ('%s.vhd' % vhd_uuid))\\n _rename(orig_vhd_path, vhd_path)\\n if (seq_num == 0):\\n leaf_vhd_path = vhd_path\\n leaf_vhd_uuid = vhd_uuid\\n files_to_move.append(vhd_path)\\n seq_num += 1\\n parent_path = None\\n for vhd_path in reversed(files_to_move):\\n if parent_path:\\n modify_cmd = ('vhd-util modify -n %(vhd_path)s -p %(parent_path)s' % locals())\\n modify_proc = make_subprocess(modify_cmd, stderr=True)\\n finish_subprocess(modify_proc, modify_cmd)\\n parent_path = vhd_path\\n _assert_vhd_not_hidden(leaf_vhd_path)\\n _validate_vdi_chain(leaf_vhd_path)\\n for orig_path in files_to_move:\\n new_path = os.path.join(sr_path, os.path.basename(orig_path))\\n _rename(orig_path, new_path)\\n imported_vhds = dict(root=dict(uuid=leaf_vhd_uuid))\\n return imported_vhds\\n\\n\\nWhat's a good function header?\",\"targets\":\"def import_vhds(sr_path, staging_path, uuid_stack):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def assert_user_is_system_admin(user_db):\",\"targets\":\"\\\"\\\"\\\"Assert that the currently logged in user is a system administrator.\\n If the user is not a system administrator, an exception is thrown.\\n \\\"\\\"\\\"\\n is_system_admin = user_is_system_admin(user_db=user_db)\\n if (not is_system_admin):\\n raise AccessDeniedError(message='System Administrator access required', user_db=user_db)\",\"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, basestring):\\n try:\\n return bool(strtobool(value))\\n except ValueError:\\n return False\\n else:\\n return bool(value)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def boolify(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 def get(key):\\n r = msg.get(key)\\n if (r is not None):\\n if (not isinstance(r, dict)):\\n r = {None: r}\\n else:\\n return {}\\n return r\\n lowerLevels = get('lowerLevels')\\n raiseLevels = get('raiseLevels')\\n setLevels = get('setLevels')\\n for (k, v) in lowerLevels.iteritems():\\n logger = core.getLogger(k)\\n level = logging._checkLevel(v)\\n if (not l.isEnabledFor((level + 1))):\\n logger.setLevel(v)\\n for (k, v) in raiseLevels.iteritems():\\n logger = core.getLogger(k)\\n if (not l.isEnabledFor(v)):\\n logger.setLevel(v)\\n for (k, v) in setLevels.iteritems():\\n logger = core.getLogger(k)\\n logger.setLevel(v)\\n message = msg.get('message', None)\\n if message:\\n level = msg.get('level', 'DEBUG')\\n if isinstance(level, basestring):\\n import logging\\n if (not level.isalpha()):\\n level = logging.DEBUG\\n else:\\n level = level.upper()\\n level = getattr(logging, level, logging.DEBUG)\\n sub = msg.get('subsystem', '')\\n logging.getLogger(sub).log(level, message)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _process_commands(msg):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _calculate_to_transitions(trans_probs):\\n\\n ''''Calculate which \\\\'to transitions\\\\' are allowed for each state.\\n This looks through all of the trans_probs, and uses this dictionary\\n to determine allowed transitions. It converts this information into\\n a dictionary, whose keys are destination states and whose values are\\n lists of source states from which the destination is reachable via a\\n transition.'\\n '''\",\"targets\":\"transitions = dict()\\n for (from_state, to_state) in trans_probs:\\n try:\\n transitions[to_state].append(from_state)\\n except KeyError:\\n transitions[to_state] = [from_state]\\n return transitions\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@register.tag(u'with')\\ndef do_with(parser, token):\\n\\n ''''Adds one or more values to the context (inside of this block) for caching\\n and easy access.\\n For example::\\n {% with total=person.some_sql_method %}\\n {{ total }} object{{ total|pluralize }}\\n {% endwith %}\\n Multiple values can be added to the context::\\n {% with foo=1 bar=2 %}\\n {% endwith %}\\n The legacy format of ``{% with person.some_sql_method as total %}`` is\\n still accepted.'\\n '''\",\"targets\":\"bits = token.split_contents()\\n remaining_bits = bits[1:]\\n extra_context = token_kwargs(remaining_bits, parser, support_legacy=True)\\n if (not extra_context):\\n raise TemplateSyntaxError((u'%r expected at least one variable assignment' % bits[0]))\\n if remaining_bits:\\n raise TemplateSyntaxError((u'%r received an invalid token: %r' % (bits[0], remaining_bits[0])))\\n nodelist = parser.parse((u'endwith',))\\n parser.delete_first_token()\\n return WithNode(None, None, nodelist, extra_context=extra_context)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@with_open_mode('w')\\n@with_sizes('medium')\\ndef write_medium_chunks(f, source):\\n\\n ''''write 4096 units at a time'\\n '''\",\"targets\":\"for i in xrange(0, len(source), 4096):\\n f.write(source[i:(i + 4096)])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n extra_read = 'APETAGEX'.index('TAG')\\n try:\\n fileobj.seek(((-128) - extra_read), 2)\\n except IOError as e:\\n if (e.errno == errno.EINVAL):\\n fileobj.seek(0, 0)\\n else:\\n raise\\n data = fileobj.read((128 + extra_read))\\n try:\\n idx = data.index('TAG')\\n except ValueError:\\n return (None, 0)\\n else:\\n try:\\n ape_idx = data.index('APETAGEX')\\n except ValueError:\\n pass\\n else:\\n if (idx == (ape_idx + extra_read)):\\n return (None, 0)\\n tag = ParseID3v1(data[idx:])\\n if (tag is None):\\n return (None, 0)\\n offset = (idx - len(data))\\n return (tag, offset)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def find_id3v1(fileobj):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef filenameToModuleName(fn):\\n\\n ''''Convert a name in the filesystem to the name of the Python module it is.\\n This is aggressive about getting a module name back from a file; it will\\n always return a string. Aggressive means \\\\'sometimes wrong\\\\'; it won\\\\'t look\\n at the Python path or try to do any error checking: don\\\\'t use this method\\n unless you already know that the filename you\\\\'re talking about is a Python\\n module.\\n @param fn: A filesystem path to a module or package; C{bytes} on Python 2,\\n C{bytes} or C{unicode} on Python 3.\\n @return: A hopefully importable module name.\\n @rtype: C{str}'\\n '''\",\"targets\":\"if isinstance(fn, bytes):\\n initPy = '__init__.py'\\n else:\\n initPy = '__init__.py'\\n fullName = os.path.abspath(fn)\\n base = os.path.basename(fn)\\n if (not base):\\n base = os.path.basename(fn[:(-1)])\\n modName = nativeString(os.path.splitext(base)[0])\\n while 1:\\n fullName = os.path.dirname(fullName)\\n if os.path.exists(os.path.join(fullName, initPy)):\\n modName = ('%s.%s' % (nativeString(os.path.basename(fullName)), nativeString(modName)))\\n else:\\n break\\n return modName\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _bsd_bradd(br):\",\"targets\":\"\\\"\\\"\\\"Internal, creates the bridge\\n \\\"\\\"\\\"\\n kernel = __grains__['kernel']\\n ifconfig = _tool_path('ifconfig')\\n if (not br):\\n return False\\n if (__salt__['cmd.retcode']('{0} {1} create up'.format(ifconfig, br), python_shell=False) != 0):\\n return False\\n if (kernel == 'NetBSD'):\\n brconfig = _tool_path('brconfig')\\n if (__salt__['cmd.retcode']('{0} {1} up'.format(brconfig, br), python_shell=False) != 0):\\n return False\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def create_x509_dir(path, cacert_subj, server_subj, passphrase, secure=False, bits=1024, days=1095):\",\"targets\":\"\\\"\\\"\\\"Creates directory with freshly generated:\\n ca-cart.pem, ca-key.pem, server-cert.pem, server-key.pem,\\n :param path: defines path to directory which will be created\\n :param cacert_subj: ca-cert.pem subject\\n :param server_key.csr subject\\n :param passphrase - passphrase to ca-key.pem\\n :param secure = False - defines if the server-key.pem will use a passphrase\\n :param bits = 1024: bit length of keys\\n :param days = 1095: cert expiration\\n :raise ValueError: openssl not found or rc != 0\\n :raise OSError: if os.makedirs() fails\\n \\\"\\\"\\\"\\n ssl_cmd = os_dep.command('openssl')\\n path = (path + os.path.sep)\\n shutil.rmtree(path, ignore_errors=True)\\n os.makedirs(path)\\n server_key = 'server-key.pem.secure'\\n if secure:\\n server_key = 'server-key.pem'\\n cmd_set = [('%s genrsa -des3 -passout pass:%s -out %sca-key.pem %d' % (ssl_cmd, passphrase, path, bits)), ('%s req -new -x509 -days %d -key %sca-key.pem -passin pass:%s -out %sca-cert.pem -subj \\\"%s\\\"' % (ssl_cmd, days, path, passphrase, path, cacert_subj)), ('%s genrsa -out %s %d' % (ssl_cmd, (path + server_key), bits)), ('%s req -new -key %s -out %s\\/server-key.csr -subj \\\"%s\\\"' % (ssl_cmd, (path + server_key), path, server_subj)), ('%s x509 -req -passin pass:%s -days %d -in %sserver-key.csr -CA %sca-cert.pem -CAkey %sca-key.pem -set_serial 01 -out %sserver-cert.pem' % (ssl_cmd, passphrase, days, path, path, path, path))]\\n if (not secure):\\n cmd_set.append(('%s rsa -in %s -out %sserver-key.pem' % (ssl_cmd, (path + server_key), path)))\\n for cmd in cmd_set:\\n run(cmd)\\n logging.info(cmd)\",\"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 (objects is None):\\n return get_hub().join(timeout=timeout)\\n result = []\\n if (count is None):\\n return list(iwait(objects, timeout))\\n for obj in iwait(objects=objects, timeout=timeout):\\n result.append(obj)\\n count -= 1\\n if (count <= 0):\\n break\\n return result\\n\\n\\nWhat's a good function header?\",\"targets\":\"def wait(objects=None, timeout=None, count=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 G = nx.Graph()\\n G.add_nodes_from(['a', 2, 3, 4], bipartite=0)\\n G.add_nodes_from([1, 'b', 'c'], bipartite=1)\\n G.add_edges_from([('a', 1), ('a', 'b'), (2, 'b'), (2, 'c'), (3, 'c'), (4, 1)])\\n matching = eppstein_matching(G)\\n assert_true((len(matching) == len(maximum_matching(G))))\\n assert all(((x in set(matching.keys())) for x in set(matching.values())))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def test_eppstein_matching():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def exp_re(DE, r, k):\",\"targets\":\"\\\"\\\"\\\"Converts a DE with constant coefficients (explike) into a RE.\\n Performs the substitution:\\n .. math::\\n f^j(x) \\\\to r(k + j)\\n Normalises the terms so that lowest order of a term is always r(k).\\n Examples\\n >>> from sympy import Function, Derivative\\n >>> from sympy.series.formal import exp_re\\n >>> from sympy.abc import x, k\\n >>> f, r = Function(\\\\f\\\\), Function(\\\\r\\\\)\\n >>> exp_re(-f(x) + Derivative(f(x)), r, k)\\n -r(k) + r(k + 1)\\n >>> exp_re(Derivative(f(x), x) + Derivative(f(x), x, x), r, k)\\n r(k) + r(k + 1)\\n See Also\\n sympy.series.formal.hyper_re\\n \\\"\\\"\\\"\\n RE = S.Zero\\n g = DE.atoms(Function).pop()\\n mini = None\\n for t in Add.make_args(DE):\\n (coeff, d) = t.as_independent(g)\\n if isinstance(d, Derivative):\\n j = (len(d.args) - 1)\\n else:\\n j = 0\\n if ((mini is None) or (j < mini)):\\n mini = j\\n RE += (coeff * r((k + j)))\\n if mini:\\n RE = RE.subs(k, (k - mini))\\n return RE\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef interpgrid(a, xi, yi):\\n\\n ''''Fast 2D, linear interpolation on an integer grid'\\n '''\",\"targets\":\"(Ny, Nx) = np.shape(a)\\n if isinstance(xi, np.ndarray):\\n x = xi.astype(int)\\n y = yi.astype(int)\\n xn = np.clip((x + 1), 0, (Nx - 1))\\n yn = np.clip((y + 1), 0, (Ny - 1))\\n else:\\n x = int(xi)\\n y = int(yi)\\n if (x == (Nx - 2)):\\n xn = x\\n else:\\n xn = (x + 1)\\n if (y == (Ny - 2)):\\n yn = y\\n else:\\n yn = (y + 1)\\n a00 = a[(y, x)]\\n a01 = a[(y, xn)]\\n a10 = a[(yn, x)]\\n a11 = a[(yn, xn)]\\n xt = (xi - x)\\n yt = (yi - y)\\n a0 = ((a00 * (1 - xt)) + (a01 * xt))\\n a1 = ((a10 * (1 - xt)) + (a11 * xt))\\n ai = ((a0 * (1 - yt)) + (a1 * yt))\\n if (not isinstance(xi, np.ndarray)):\\n if np.ma.is_masked(ai):\\n raise TerminateTrajectory\\n return ai\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _get_limit_param(request):\",\"targets\":\"\\\"\\\"\\\"Extract integer limit from request or fail.\\n \\\"\\\"\\\"\\n try:\\n limit = int(request.GET['limit'])\\n except ValueError:\\n msg = _('limit param must be an integer')\\n raise webob.exc.HTTPBadRequest(explanation=msg)\\n if (limit < 0):\\n msg = _('limit param must be positive')\\n raise webob.exc.HTTPBadRequest(explanation=msg)\\n return limit\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def getID(lang=None):\",\"targets\":\"\\\"\\\"\\\"Get wx ID of language to use for translations:\\n `lang`, pref, or system default.\\n `lang` is a 5 char `language_REGION`, eg ja_JP\\n \\\"\\\"\\\"\\n if lang:\\n val = lang\\n else:\\n try:\\n val = prefs.app['locale']\\n except KeyError:\\n val = locale.GetLocale()\\n if (not val):\\n val = codeFromWxId[wx.LANGUAGE_DEFAULT]\\n try:\\n language = wxIdFromCode[val]\\n except KeyError:\\n logging.error(('locale %s not known to wx.Locale, using default' % val))\\n language = wx.LANGUAGE_DEFAULT\\n return (language, val)\",\"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 _setup_stop_after\\n if (stop_after not in ('init', 'config', 'commandline', 'run')):\\n raise ValueError, (\\\"invalid value for 'stop_after': %r\\\" % (stop_after,))\\n _setup_stop_after = stop_after\\n save_argv = sys.argv\\n g = {'__file__': script_name}\\n l = {}\\n try:\\n try:\\n sys.argv[0] = script_name\\n if (script_args is not None):\\n sys.argv[1:] = script_args\\n f = open(script_name)\\n try:\\n exec f.read() in g, l\\n finally:\\n f.close()\\n finally:\\n sys.argv = save_argv\\n _setup_stop_after = None\\n except SystemExit:\\n pass\\n except:\\n raise\\n if (_setup_distribution is None):\\n raise RuntimeError, (\\\"'distutils.core.setup()' was never called -- perhaps '%s' is not a Distutils setup script?\\\" % script_name)\\n return _setup_distribution\\n\\n\\nWhat's a good function header?\",\"targets\":\"def run_setup(script_name, script_args=None, stop_after='run'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef addpackage(sys_path, sitedir, name, known_paths):\\n\\n ''''Process a .pth file within the site-packages directory:\\n For each line in the file, either combine it with sitedir to a path\\n and add that to known_paths, or execute it if it starts with \\\\'import \\\\'.'\\n '''\",\"targets\":\"if (known_paths is None):\\n known_paths = _init_pathinfo(sys_path)\\n reset = 1\\n else:\\n reset = 0\\n fullname = os.path.join(sitedir, name)\\n try:\\n f = open(fullname, 'r')\\n except OSError:\\n return\\n with f:\\n for (n, line) in enumerate(f):\\n if line.startswith('#'):\\n continue\\n try:\\n if line.startswith(('import ', 'import DCTB ')):\\n continue\\n line = line.rstrip()\\n (dir, dircase) = makepath(sitedir, line)\\n if ((not (dircase in known_paths)) and os.path.exists(dir)):\\n sys_path.append(dir)\\n known_paths.add(dircase)\\n except Exception:\\n print('Error processing line {:d} of {}:\\\\n'.format((n + 1), fullname), file=sys.stderr)\\n import traceback\\n for record in traceback.format_exception(*sys.exc_info()):\\n for line in record.splitlines():\\n print((' ' + line), file=sys.stderr)\\n print('\\\\nRemainder of file ignored', file=sys.stderr)\\n break\\n if reset:\\n known_paths = None\\n return known_paths\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n mod = mod_import(module)\\n if (not mod):\\n return {}\\n members = getmembers(mod, predicate=(lambda obj: (callable(obj) and (getmodule(obj) == mod))))\\n return dict(((key, val) for (key, val) in members if (not key.startswith('_'))))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def callables_from_module(module):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _refresh_course_tabs(request, course_module):\",\"targets\":\"\\\"\\\"\\\"Automatically adds\\/removes tabs if changes to the course require them.\\n Raises:\\n InvalidTabsException: raised if there\\\\s a problem with the new version of the tabs.\\n \\\"\\\"\\\"\\n def update_tab(tabs, tab_type, tab_enabled):\\n '\\\\n Adds or removes a course tab based upon whether it is enabled.\\\\n '\\n tab_panel = {'type': tab_type.type}\\n has_tab = (tab_panel in tabs)\\n if (tab_enabled and (not has_tab)):\\n tabs.append(CourseTab.from_json(tab_panel))\\n elif ((not tab_enabled) and has_tab):\\n tabs.remove(tab_panel)\\n course_tabs = copy.copy(course_module.tabs)\\n for tab_type in CourseTabPluginManager.get_tab_types():\\n if ((not tab_type.is_dynamic) and tab_type.is_default):\\n tab_enabled = tab_type.is_enabled(course_module, user=request.user)\\n update_tab(course_tabs, tab_type, tab_enabled)\\n CourseTabList.validate_tabs(course_tabs)\\n if (course_tabs != course_module.tabs):\\n course_module.tabs = course_tabs\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def load_tests(loader, tests, pattern):\",\"targets\":\"\\\"\\\"\\\"Provide a TestSuite to the discovery process.\\n \\\"\\\"\\\"\\n test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)\\n return driver.build_tests(test_dir, loader, host=None, prefix='\\/telemetry', intercept=fixture_module.setup_app, fixture_module=fixture_module)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef getDOMImplementation(name=None, features=()):\\n\\n ''''getDOMImplementation(name = None, features = ()) -> DOM implementation.\\n Return a suitable DOM implementation. The name is either\\n well-known, the module name of a DOM implementation, or None. If\\n it is not None, imports the corresponding module and returns\\n DOMImplementation object if the import succeeds.\\n If name is not given, consider the available implementations to\\n find one with the required feature set. If no implementation can\\n be found, raise an ImportError. The features list must be a sequence\\n of (feature, version) pairs which are passed to hasFeature.'\\n '''\",\"targets\":\"import os\\n creator = None\\n mod = well_known_implementations.get(name)\\n if mod:\\n mod = __import__(mod, {}, {}, ['getDOMImplementation'])\\n return mod.getDOMImplementation()\\n elif name:\\n return registered[name]()\\n elif ('PYTHON_DOM' in os.environ):\\n return getDOMImplementation(name=os.environ['PYTHON_DOM'])\\n if isinstance(features, str):\\n features = _parse_feature_string(features)\\n for creator in registered.values():\\n dom = creator()\\n if _good_enough(dom, features):\\n return dom\\n for creator in well_known_implementations.keys():\\n try:\\n dom = getDOMImplementation(name=creator)\\n except Exception:\\n continue\\n if _good_enough(dom, features):\\n return dom\\n raise ImportError('no suitable DOM implementation found')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _rewrite_sin(m_n, s, a, b):\",\"targets\":\"\\\"\\\"\\\"Re-write the sine function ``sin(m*s + n)`` as gamma functions, compatible\\n with the strip (a, b).\\n Return ``(gamma1, gamma2, fac)`` so that ``f == fac\\/(gamma1 * gamma2)``.\\n >>> from sympy.integrals.transforms import _rewrite_sin\\n >>> from sympy import pi, S\\n >>> from sympy.abc import s\\n >>> _rewrite_sin((pi, 0), s, 0, 1)\\n (gamma(s), gamma(-s + 1), pi)\\n >>> _rewrite_sin((pi, 0), s, 1, 0)\\n (gamma(s - 1), gamma(-s + 2), -pi)\\n >>> _rewrite_sin((pi, 0), s, -1, 0)\\n (gamma(s + 1), gamma(-s), -pi)\\n >>> _rewrite_sin((pi, pi\\/2), s, S(1)\\/2, S(3)\\/2)\\n (gamma(s - 1\\/2), gamma(-s + 3\\/2), -pi)\\n >>> _rewrite_sin((pi, pi), s, 0, 1)\\n (gamma(s), gamma(-s + 1), -pi)\\n >>> _rewrite_sin((2*pi, 0), s, 0, S(1)\\/2)\\n (gamma(2*s), gamma(-2*s + 1), pi)\\n >>> _rewrite_sin((2*pi, 0), s, S(1)\\/2, 1)\\n (gamma(2*s - 1), gamma(-2*s + 2), -pi)\\n \\\"\\\"\\\"\\n from sympy import expand_mul, pi, ceiling, gamma\\n (m, n) = m_n\\n m = expand_mul((m \\/ pi))\\n n = expand_mul((n \\/ pi))\\n r = ceiling((((- m) * a) - n.as_real_imag()[0]))\\n return (gamma((((m * s) + n) + r)), gamma((((1 - n) - r) - (m * s))), (((-1) ** r) * pi))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def make_attendance_records(student, student_name, status, course_schedule=None, student_group=None, date=None):\",\"targets\":\"\\\"\\\"\\\"Creates\\/Update Attendance Record.\\n :param student: Student.\\n :param student_name: Student Name.\\n :param course_schedule: Course Schedule.\\n :param status: Status (Present\\/Absent)\\n \\\"\\\"\\\"\\n student_attendance_list = frappe.get_list(u'Student Attendance', fields=[u'name'], filters={u'student': student, u'course_schedule': course_schedule, u'student_group': student_group, u'date': date})\\n if student_attendance_list:\\n student_attendance = frappe.get_doc(u'Student Attendance', student_attendance_list[0])\\n else:\\n student_attendance = frappe.new_doc(u'Student Attendance')\\n student_attendance.student = student\\n student_attendance.student_name = student_name\\n student_attendance.course_schedule = course_schedule\\n student_attendance.student_group = student_group\\n student_attendance.date = date\\n student_attendance.status = status\\n student_attendance.save()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@pytest.mark.network\\ndef test_git_with_branch_name_as_revision(script):\",\"targets\":\"\\\"\\\"\\\"Git backend should be able to install from branch names\\n \\\"\\\"\\\"\\n version_pkg_path = _create_test_package(script)\\n script.run('git', 'checkout', '-b', 'test_branch', expect_stderr=True, cwd=version_pkg_path)\\n _change_test_package_version(script, version_pkg_path)\\n script.pip('install', '-e', ('%s@test_branch#egg=version_pkg' % ('git+file:\\/\\/' + version_pkg_path.abspath.replace('\\\\\\\\', '\\/'))))\\n version = script.run('version_pkg')\\n assert ('some different version' in version.stdout)\",\"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 (tb is None):\\n try:\\n tb = sys.last_traceback\\n except AttributeError:\\n raise RuntimeError, 'no last traceback to disassemble'\\n while tb.tb_next:\\n tb = tb.tb_next\\n disassemble(tb.tb_frame.f_code, tb.tb_lasti)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def distb(tb=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _get_init_fn():\",\"targets\":\"\\\"\\\"\\\"Returns a function run by the chief worker to warm-start the training.\\n Note that the init_fn is only run when initializing the model during the very\\n first global step.\\n Returns:\\n An init function run by the supervisor.\\n \\\"\\\"\\\"\\n if (FLAGS.checkpoint_path is None):\\n return None\\n if tf.train.latest_checkpoint(FLAGS.train_dir):\\n tf.logging.info(('Ignoring --checkpoint_path because a checkpoint already exists in %s' % FLAGS.train_dir))\\n return None\\n exclusions = []\\n if FLAGS.checkpoint_exclude_scopes:\\n exclusions = [scope.strip() for scope in FLAGS.checkpoint_exclude_scopes.split(',')]\\n variables_to_restore = []\\n for var in slim.get_model_variables():\\n excluded = False\\n for exclusion in exclusions:\\n if var.op.name.startswith(exclusion):\\n excluded = True\\n break\\n if (not excluded):\\n variables_to_restore.append(var)\\n if tf.gfile.IsDirectory(FLAGS.checkpoint_path):\\n checkpoint_path = tf.train.latest_checkpoint(FLAGS.checkpoint_path)\\n else:\\n checkpoint_path = FLAGS.checkpoint_path\\n tf.logging.info(('Fine-tuning from %s' % checkpoint_path))\\n return slim.assign_from_checkpoint_fn(checkpoint_path, variables_to_restore, ignore_missing_vars=FLAGS.ignore_missing_vars)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@pytest.mark.network\\ndef test_simple_uninstall(script):\\n\\n ''''Test simple install and uninstall.'\\n '''\",\"targets\":\"result = script.pip('install', 'INITools==0.2')\\n assert (join(script.site_packages, 'initools') in result.files_created), sorted(result.files_created.keys())\\n script.run('python', '-c', 'import initools')\\n result2 = script.pip('uninstall', 'INITools', '-y')\\n assert_all_changes(result, result2, [(script.venv \\/ 'build'), 'cache'])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n profile.enable()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def enable_profiling(profile, signal, frame):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@not_implemented_for('directed')\\ndef min_weighted_dominating_set(G, weight=None):\\n\\n ''''Returns a dominating set that approximates the minimum weight node\\n dominating set.\\n Parameters\\n G : NetworkX graph\\n Undirected graph.\\n weight : string\\n The node attribute storing the weight of an edge. If provided,\\n the node attribute with this key must be a number for each\\n node. If not provided, each node is assumed to have weight one.\\n Returns\\n min_weight_dominating_set : set\\n A set of nodes, the sum of whose weights is no more than `(\\\\log\\n w(V)) w(V^*)`, where `w(V)` denotes the sum of the weights of\\n each node in the graph and `w(V^*)` denotes the sum of the\\n weights of each node in the minimum weight dominating set.\\n Notes\\n This algorithm computes an approximate minimum weighted dominating\\n set for the graph `G`. The returned solution has weight `(\\\\log\\n w(V)) w(V^*)`, where `w(V)` denotes the sum of the weights of each\\n node in the graph and `w(V^*)` denotes the sum of the weights of\\n each node in the minimum weight dominating set for the graph.\\n This implementation of the algorithm runs in `O(m)` time, where `m`\\n is the number of edges in the graph.\\n References\\n .. [1] Vazirani, Vijay V.\\n *Approximation Algorithms*.\\n Springer Science & Business Media, 2001.'\\n '''\",\"targets\":\"if (len(G) == 0):\\n return set()\\n dom_set = set()\\n def _cost(node_and_neighborhood):\\n 'Returns the cost-effectiveness of greedily choosing the given\\\\n node.\\\\n\\\\n `node_and_neighborhood` is a two-tuple comprising a node and its\\\\n closed neighborhood.\\\\n\\\\n '\\n (v, neighborhood) = node_and_neighborhood\\n return (G.node[v].get(weight, 1) \\/ len((neighborhood - dom_set)))\\n vertices = set(G)\\n neighborhoods = {v: ({v} | set(G[v])) for v in G}\\n while vertices:\\n (dom_node, min_set) = min(neighborhoods.items(), key=_cost)\\n dom_set.add(dom_node)\\n del neighborhoods[dom_node]\\n vertices -= min_set\\n return dom_set\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def getsourcelines(object):\",\"targets\":\"\\\"\\\"\\\"Return a list of source lines and starting line number for an object.\\n The argument may be a module, class, method, function, traceback, frame,\\n or code object. The source code is returned as a list of the lines\\n corresponding to the object and the line number indicates where in the\\n original source file the first line of code was found. An IOError is\\n raised if the source code cannot be retrieved.\\n \\\"\\\"\\\"\\n (lines, lnum) = findsource(object)\\n if ismodule(object):\\n return (lines, 0)\\n else:\\n return (getblock(lines[lnum:]), (lnum + 1))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def info(request, message, extra_tags='', fail_silently=False):\",\"targets\":\"\\\"\\\"\\\"Adds a message with the ``INFO`` level.\\n \\\"\\\"\\\"\\n add_message(request, constants.INFO, message, extra_tags=extra_tags, fail_silently=fail_silently)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef flood(stepFunction, fullSet, initSet, relevant=None):\\n\\n ''''Returns a list of elements of fullSet linked to some element of initSet\\n through the neighborhood-setFunction (which must be defined on all elements of fullSet).\\n :key relevant: (optional) list of relevant elements: stop once all relevant elements are found.'\\n '''\",\"targets\":\"if (fullSet is None):\\n flooded = set(initSet)\\n else:\\n full = set(fullSet)\\n flooded = full.intersection(set(initSet))\\n if (relevant is None):\\n relevant = full.copy()\\n if relevant:\\n relevant = set(relevant)\\n change = flooded.copy()\\n while (len(change) > 0):\\n new = set()\\n for m in change:\\n if (fullSet is None):\\n new.update(stepFunction(m))\\n else:\\n new.update(full.intersection(stepFunction(m)))\\n change = new.difference(flooded)\\n flooded.update(change)\\n if ((relevant is not None) and relevant.issubset(flooded)):\\n break\\n return list(flooded)\",\"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 wrapper(self, *args, **kwargs):\\n if (not self.is_authenticated()):\\n log.debug(u'None API token. Authenticating with \\\"%s\\\" account...', self.credentials.get(u'username'))\\n self.auth()\\n assert self.is_authenticated()\\n return func(self, *args, **kwargs)\\n return wrapper\\n\\n\\nWhat's a good function header?\",\"targets\":\"def auth_required(func):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef delete(url, **kwargs):\\n\\n '''''\\n '''\",\"targets\":\"return request('delete', url, **kwargs)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_html_section(name):\\n\\n ''''Return a new section as HTML, with the given name and a time stamp.\\n :param name: section name\\n :type name: str\\n :rtype: str'\\n '''\",\"targets\":\"datetime = time.strftime('%a %b %d %y, %H:%M:%S')\\n return \\\"{} {}<\\/h1>\\\".format(name, datetime)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef gateway_help(gateway_client, var, pattern=None, short_name=True, display=True):\\n\\n ''''Displays a help page about a class or an object.\\n :param gateway_client: The gatway client\\n :param var: JavaObject, JavaClass or JavaMember for which a help page\\n will be generated.\\n :param pattern: Star-pattern used to filter the members. For example\\n \\\"get*Foo\\\" may return getMyFoo, getFoo, getFooBar, but not bargetFoo.\\n The pattern is matched against the entire signature. To match only\\n the name of a method, use \\\"methodName(*\\\".\\n :param short_name: If True, only the simple name of the parameter\\n types and return types will be displayed. If False, the fully\\n qualified name of the types will be displayed.\\n :param display: If True, the help page is displayed in an interactive\\n page similar to the `help` command in Python. If False, the page is\\n returned as a string.'\\n '''\",\"targets\":\"if hasattr2(var, u'_get_object_id'):\\n command = ((((((proto.HELP_COMMAND_NAME + proto.HELP_OBJECT_SUBCOMMAND_NAME) + var._get_object_id()) + u'\\\\n') + get_command_part(pattern)) + get_command_part(short_name)) + proto.END_COMMAND_PART)\\n answer = gateway_client.send_command(command)\\n elif hasattr2(var, u'_fqn'):\\n command = ((((((proto.HELP_COMMAND_NAME + proto.HELP_CLASS_SUBCOMMAND_NAME) + var._fqn) + u'\\\\n') + get_command_part(pattern)) + get_command_part(short_name)) + proto.END_COMMAND_PART)\\n answer = gateway_client.send_command(command)\\n elif (hasattr2(var, u'container') and hasattr2(var, u'name')):\\n if (pattern is not None):\\n raise Py4JError(u'pattern should be None with var is a JavaMember')\\n pattern = (var.name + u'(*')\\n var = var.container\\n return gateway_help(gateway_client, var, pattern, short_name=short_name, display=display)\\n else:\\n raise Py4JError(u'var is none of Java Object, Java Class or Java Member')\\n help_page = get_return_value(answer, gateway_client, None, None)\\n if display:\\n pager(help_page)\\n else:\\n return help_page\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n gzip.time = FakeTime()\\n zbuf = BytesIO()\\n zfile = gzip.GzipFile(mode='wb', compresslevel=9, fileobj=zbuf)\\n zfile.write(s)\\n zfile.close()\\n return zbuf.getvalue()\\n\\n\\nWhat's a good function header?\",\"targets\":\"def compressString(s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef getDBTables(uri=None):\\n\\n ''''Return a list of TableAdapter objects to be used to access the\\n database through the SQLAlchemy ORM. The connection uri is optional, and\\n can be used to tailor the db schema to specific needs.'\\n '''\",\"targets\":\"DB_TABLES = []\\n for table in DB_SCHEMA:\\n if (table.name in TABLES_REPOSITORY):\\n DB_TABLES.append(TABLES_REPOSITORY[table.name])\\n continue\\n tableAdapter = TableAdapter(table, uri)\\n DB_TABLES.append(tableAdapter)\\n TABLES_REPOSITORY[table.name] = tableAdapter\\n return DB_TABLES\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def asrun(ascript):\",\"targets\":\"\\\"\\\"\\\"Run the given AppleScript and return the standard output and error.\\n \\\"\\\"\\\"\\n osa = subprocess.Popen(['osascript', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)\\n return osa.communicate(ascript)[0]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef generate(X, Y, phi):\\n\\n ''''Generates Z data for the points in the X, Y meshgrid and parameter phi.'\\n '''\",\"targets\":\"R = (1 - np.sqrt(((X ** 2) + (Y ** 2))))\\n return (np.cos((((2 * np.pi) * X) + phi)) * 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 (indexname is None):\\n indexname = _DEF_INDEX_NAME\\n from whoosh.filedb.filestore import FileStorage\\n storage = FileStorage(dirname, mapped=mapped, readonly=readonly)\\n return storage.open_index(indexname)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def open_dir(dirname, indexname=None, mapped=True, readonly=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 (base is None):\\n base = __opts__['cachedir']\\n fname = '{0}.p'.format(minion_id)\\n src = os.path.join(base, 'requested', fname)\\n dst = os.path.join(base, 'active')\\n shutil.move(src, dst)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def activate_minion_cachedir(minion_id, base=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def interfaces(br=None):\",\"targets\":\"\\\"\\\"\\\"Returns interfaces attached to a bridge\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\*\\\\ bridge.interfaces br0\\n \\\"\\\"\\\"\\n if (not br):\\n return None\\n br_ret = _os_dispatch('brshow', br)\\n if br_ret:\\n return br_ret['interfaces']\",\"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):\\n return []\\n it = iter(iterable)\\n result = list(islice(it, n))\\n if (not result):\\n return result\\n _heapify_max(result)\\n _heappushpop = _heappushpop_max\\n for elem in it:\\n _heappushpop(result, elem)\\n result.sort()\\n return result\\n\\n\\nWhat's a good function header?\",\"targets\":\"def nsmallest(n, iterable):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n is_module = (osp.isfile(path) and (osp.splitext(path)[1] in ('.py', '.pyw')))\\n is_package = (osp.isdir(path) and osp.isfile(osp.join(path, '__init__.py')))\\n return (is_module or is_package)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def is_module_or_package(path):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_notes(request, course, page=DEFAULT_PAGE, page_size=DEFAULT_PAGE_SIZE, text=None):\\n\\n ''''Returns paginated list of notes for the user.\\n Arguments:\\n request: HTTP request object\\n course: Course descriptor\\n page: requested or default page number\\n page_size: requested or default page size\\n text: text to search. If None then return all results for the current logged in user.\\n Returns:\\n Paginated dictionary with these key:\\n start: start of the current page\\n current_page: current page number\\n next: url for next page\\n previous: url for previous page\\n count: total number of notes available for the sent query\\n num_pages: number of pages available\\n results: list with notes info dictionary. each item in this list will be a dict'\\n '''\",\"targets\":\"path = ('search' if text else 'annotations')\\n response = send_request(request.user, course.id, page, page_size, path, text)\\n try:\\n collection = json.loads(response.content)\\n except ValueError:\\n log.error('Invalid JSON response received from notes api: response_content=%s', response.content)\\n raise EdxNotesParseError(_('Invalid JSON response received from notes api.'))\\n expected_keys = ['total', 'rows', 'num_pages', 'start', 'next', 'previous', 'current_page']\\n keys = collection.keys()\\n if ((not keys) or (not all(((key in expected_keys) for key in keys)))):\\n log.error('Incorrect data received from notes api: collection_data=%s', str(collection))\\n raise EdxNotesParseError(_('Incorrect data received from notes api.'))\\n filtered_results = preprocess_collection(request.user, course, collection['rows'])\\n collection['count'] = collection['total']\\n del collection['total']\\n collection['results'] = filtered_results\\n del collection['rows']\\n (collection['next'], collection['previous']) = construct_pagination_urls(request, course.id, collection['next'], collection['previous'])\\n return collection\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n n_samples_min = ((10 * (n_chan + 1)) \\/\\/ 2)\\n if (n_samples <= 0):\\n raise ValueError('No samples found to compute the covariance matrix')\\n if (n_samples < n_samples_min):\\n warn(('Too few samples (required : %d got : %d), covariance estimate may be unreliable' % (n_samples_min, n_samples)))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _check_n_samples(n_samples, n_chan):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@register.function\\n@jinja2.contextfunction\\ndef sort_link(context, pretty_name, sort_field):\\n\\n ''''Get table header sort links.\\n pretty_name -- name displayed on table header\\n sort_field -- name of get parameter, referenced to in views'\\n '''\",\"targets\":\"request = context['request']\\n (sort, order) = clean_sort_param(request)\\n get_params = [(k, v) for (k, v) in urlparse.parse_qsl(smart_str(request.META['QUERY_STRING'])) if (k not in ('sort', 'order'))]\\n return create_sort_link(pretty_name, sort_field, get_params, sort, order)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def advance(n, iterator):\",\"targets\":\"\\\"\\\"\\\"Advances an iterator n places.\\n \\\"\\\"\\\"\\n next(itertools.islice(iterator, n, n), None)\\n return iterator\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _maybe_download_corpus(tmp_dir):\",\"targets\":\"\\\"\\\"\\\"Download corpus if necessary.\\n Args:\\n tmp_dir: directory containing dataset.\\n Returns:\\n filepath of the downloaded corpus file.\\n \\\"\\\"\\\"\\n corpus_url = 'https:\\/\\/dumps.wikimedia.org\\/enwiki\\/20170620\\/enwiki-20170620-pages-articles-multistream.xml.bz2'\\n corpus_filename = os.path.basename(corpus_url)\\n corpus_filepath = os.path.join(tmp_dir, corpus_filename)\\n if (not os.path.exists(corpus_filepath)):\\n generator_utils.maybe_download(tmp_dir, corpus_filename, corpus_url)\\n return corpus_filepath\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n actor = tr[0].text_content().strip()\\n if (actor.startswith('H') or actor.startswith('S')):\\n actor = actor[0]\\n return {'H': 'lower', 'S': 'upper'}[actor]\\n else:\\n h_or_s = tr.xpath(('ancestor::table[1]\\/preceding-sibling::' + 'table\\/tr\\/td\\/b[contains(text(), \\\"TRANSMIT TO\\\")]'))\\n if h_or_s:\\n h_or_s = h_or_s[(-1)].text_content().strip()\\n actor = ('upper' if h_or_s.endswith('SENATE:') else 'lower')\\n else:\\n actor = chamber\\n return actor\\n\\n\\nWhat's a good function header?\",\"targets\":\"def get_actor(tr, chamber):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef iterServices(xrd_tree):\\n\\n ''''Return an iterable over the Service elements in the Yadis XRD\\n sorted by priority'\\n '''\",\"targets\":\"xrd = getYadisXRD(xrd_tree)\\n return prioSort(xrd.findall(service_tag))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n bootTestStart = time()\\n basename = path.basename(image)\\n image = abspath(image)\\n tmpdir = mkdtemp(prefix=('test-' + basename))\\n log('* Using tmpdir', tmpdir)\\n cow = path.join(tmpdir, (basename + '.qcow2'))\\n log('* Creating COW disk', cow)\\n run(('qemu-img create -f qcow2 -b %s %s' % (image, cow)))\\n log('* Extracting kernel and initrd')\\n (kernel, initrd) = extractKernel(image, flavor=basename, imageDir=tmpdir)\\n if LogToConsole:\\n logfile = stdout\\n else:\\n logfile = NamedTemporaryFile(prefix=basename, suffix='.testlog', delete=False)\\n log('* Logging VM output to', logfile.name)\\n vm = boot(cow=cow, kernel=kernel, initrd=initrd, logfile=logfile, memory=memory, cpuCores=cpuCores)\\n login(vm)\\n log('* Waiting for prompt after login')\\n vm.expect(prompt)\\n if runFunction:\\n runFunction(vm, **runArgs)\\n log('* Shutting down')\\n vm.sendline('sudo -n shutdown -h now ')\\n log('* Waiting for shutdown')\\n vm.wait()\\n if outputFile:\\n log(('* Saving temporary image to %s' % outputFile))\\n convert(cow, outputFile)\\n log('* Removing temporary dir', tmpdir)\\n srun(('rm -rf ' + tmpdir))\\n elapsed = (time() - bootTestStart)\\n log(('* Boot and test completed in %.2f seconds' % elapsed))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def bootAndRun(image, prompt=Prompt, memory=1024, cpuCores=1, outputFile=None, runFunction=None, **runArgs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@then('the command output should not contain log records from categories')\\ndef step_command_output_should_not_contain_log_records_from_categories(context):\\n\\n ''''Verifies that the command output contains not log records from\\n the provided log categories (in any order).\\n .. code-block: gherkin\\n Given I define the log record schema:\\n | category | level | message |\\n | root | ERROR | __LOG_MESSAGE__ |\\n Then the command output should not contain log records from categories:\\n | category |\\n | bar |'\\n '''\",\"targets\":\"assert context.table, 'REQUIRE: context.table'\\n context.table.require_column('category')\\n record_schema = context.log_record_row_schema\\n LogRecordTable.annotate_with_row_schema(context.table, record_schema)\\n step_command_output_should_not_contain_log_records(context)\\n context.table.remove_columns(['level', 'message'])\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _import_module(name):\\n\\n ''''Import module, returning the module after the last dot.'\\n '''\",\"targets\":\"__import__(name)\\n return sys.modules[name]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef exists(*nictag, **kwargs):\\n\\n ''''Check if nictags exists\\n nictag : string\\n one or more nictags to check\\n verbose : boolean\\n return list of nictags\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' nictagadm.exists admin'\\n '''\",\"targets\":\"ret = {}\\n nictagadm = _check_nictagadm()\\n if (len(nictag) == 0):\\n return {'Error': 'Please provide at least one nictag to check.'}\\n cmd = '{nictagadm} exists -l {nictags}'.format(nictagadm=nictagadm, nictags=' '.join(nictag))\\n res = __salt__['cmd.run_all'](cmd)\\n if (not kwargs.get('verbose', False)):\\n ret = (res['retcode'] == 0)\\n else:\\n missing = res['stderr'].splitlines()\\n for nt in nictag:\\n ret[nt] = (nt not in missing)\\n return ret\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def convert_line(line, comments):\",\"targets\":\"\\\"\\\"\\\"Convert the given requirement line to place into the output.\\n \\\"\\\"\\\"\\n for (pattern, repl) in comments['replace'].items():\\n line = re.sub(pattern, repl, line)\\n pkgname = line.split('=')[0]\\n if (pkgname in comments['ignore']):\\n line = ('# ' + line)\\n try:\\n line += (' # ' + comments['comment'][pkgname])\\n except KeyError:\\n pass\\n try:\\n line += ' # rq.filter: {}'.format(comments['filter'][pkgname])\\n except KeyError:\\n pass\\n return line\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef arbitrary_n(module_name, func_name, args, kwargs={}, notification=(lambda x, y: y)):\\n\\n ''''Same as :func:`arbitrary` above, except that func_name must support a\\n keyword argument \\\"notification\\\". This will be a function that accepts two\\n arguments. func_name should call it periodically with progress information.\\n The first argument is a float between 0 and 1 that represent percent\\n completed and the second is a string with a message (it can be an empty\\n string).'\\n '''\",\"targets\":\"if module_name.startswith('calibre_plugins'):\\n from calibre.customize.ui import find_plugin\\n find_plugin\\n module = importlib.import_module(module_name)\\n func = getattr(module, func_name)\\n kwargs['notification'] = notification\\n return func(*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 path):\\n raise ValueError('no path specified')\\n start_list = os.path.abspath(start).split(os.path.sep)\\n path_list = os.path.abspath(path).split(os.path.sep)\\n i = len(os.path.commonprefix([start_list, path_list]))\\n rel_list = (([os.path.pardir] * (len(start_list) - i)) + path_list[i:])\\n if (not rel_list):\\n return os.path.curdir\\n return os.path.join(*rel_list)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _relpath_posix(path, start=os.path.curdir):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _split_repo_str(repo):\",\"targets\":\"\\\"\\\"\\\"Return APT source entry as a tuple.\\n \\\"\\\"\\\"\\n split = sourceslist.SourceEntry(repo)\\n return (split.type, split.uri, split.dist, split.comps)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef bridge_has_port(bridge, is_port_predicate):\\n\\n ''''True if there is an OVS port for which is_port_predicate is True.'\\n '''\",\"targets\":\"try:\\n ifaces = bridge.get_iface_name_list()\\n except RuntimeError as e:\\n LOG.error(_LE('Cannot obtain interface list for bridge %(bridge)s: %(err)s'), {'bridge': bridge.br_name, 'err': e})\\n return False\\n return any((iface for iface in ifaces if is_port_predicate(iface)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef binary_ip(host):\\n\\n ''''binary_ip(host) -> str\\n Resolve host and return IP as four byte string.\\n Example:\\n >>> binary_ip(\\\"127.0.0.1\\\")\\n \\\\'\\\\x7f\\\\x00\\\\x00\\\\x01\\\\''\\n '''\",\"targets\":\"return socket.inet_aton(socket.gethostbyname(host))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n options = _parse_args()\\n tarball = download_setuptools(download_base=options.download_base)\\n return _install(tarball, _build_install_args(options))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def main(version=DEFAULT_VERSION):\",\"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 _chooser\\n if (not _chooser):\\n _chooser = Chooser(**options)\\n return _chooser.show(color, options)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def askcolor(color=None, **options):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def iterCombinations(tup):\",\"targets\":\"\\\"\\\"\\\"all possible of integer tuples of the same dimension than tup, and each component being\\n positive and strictly inferior to the corresponding entry in tup.\\n \\\"\\\"\\\"\\n if (len(tup) == 1):\\n for i in range(tup[0]):\\n (yield (i,))\\n elif (len(tup) > 1):\\n for prefix in iterCombinations(tup[:(-1)]):\\n for i in range(tup[(-1)]):\\n (yield tuple((list(prefix) + [i])))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@disabled\\n@retry_on_failure\\ndef test_SSLType_ssl_neg():\",\"targets\":\"\\\"\\\"\\\"See comments on test_SSLType_ssl. Basically this needs to be revisited\\n entirely (TODO) after we\\\\re more compatible with CPython.\\n \\\"\\\"\\\"\\n s = socket.socket(socket.AF_INET)\\n s.connect((SSL_URL, SSL_PORT))\\n AssertError(TypeError, real_ssl.sslwrap)\\n AssertError(TypeError, real_ssl.sslwrap, False)\\n AssertError(TypeError, real_ssl.sslwrap, None, False)\\n AssertError(real_ssl.SSLError, real_ssl.sslwrap, s._sock, False, 'bad keyfile')\\n AssertError(real_ssl.SSLError, real_ssl.sslwrap, s._sock, False, 'bad keyfile', 'bad certfile')\\n s.close()\",\"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 options.namespaces:\\n return ExpatBuilderNS(options)\\n else:\\n return ExpatBuilder(options)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def makeBuilder(options):\",\"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(info_center_enable=dict(choices=['true', 'false']), packet_priority=dict(type='str'), suppress_enable=dict(choices=['true', 'false']), logfile_max_num=dict(type='str'), logfile_max_size=dict(choices=['4', '8', '16', '32']), channel_id=dict(type='str'), channel_cfg_name=dict(type='str'), channel_out_direct=dict(choices=['console', 'monitor', 'trapbuffer', 'logbuffer', 'snmp', 'logfile']), filter_feature_name=dict(type='str'), filter_log_name=dict(type='str'), ip_type=dict(choices=['ipv4', 'ipv6']), server_ip=dict(type='str'), server_domain=dict(type='str'), is_default_vpn=dict(default=False, type='bool'), vrf_name=dict(type='str'), level=dict(choices=['emergencies', 'alert', 'critical', 'error', 'warning', 'notification', 'informational', 'debugging']), server_port=dict(type='str'), facility=dict(choices=['local0', 'local1', 'local2', 'local3', 'local4', 'local5', 'local6', 'local7']), channel_name=dict(type='str'), timestamp=dict(choices=['UTC', 'localtime']), transport_mode=dict(choices=['tcp', 'udp']), ssl_policy_name=dict(type='str'), source_ip=dict(type='str'), state=dict(choices=['present', 'absent'], default='present'))\\n argument_spec.update(ce_argument_spec)\\n module = InfoCenterGlobal(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\":\"Complete the below\\ndef exists_in_default_path(sheet):\\n\\n ''''Predicate that returns true if the sheet exists in default_path'\\n '''\",\"targets\":\"default_path_sheet = os.path.join(sheets.default_path(), sheet)\\n return ((sheet in sheets.get()) and os.access(default_path_sheet, os.R_OK))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def build_train(make_obs_ph, q_func, num_actions, optimizer, grad_norm_clipping=None, gamma=1.0, double_q=True, scope='deepq', reuse=None, param_noise=False, param_noise_filter_func=None):\",\"targets\":\"\\\"\\\"\\\"Creates the train function:\\n Parameters\\n make_obs_ph: str -> tf.placeholder or TfInput\\n a function that takes 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 reuse: bool\\n whether or not to reuse the graph variables\\n optimizer: tf.train.Optimizer\\n optimizer to use for the Q-learning objective.\\n grad_norm_clipping: float or None\\n clip gradient norms to this value. If None no clipping is performed.\\n gamma: float\\n discount rate.\\n double_q: bool\\n if true will use Double Q Learning (https:\\/\\/arxiv.org\\/abs\\/1509.06461).\\n In general it is a good idea to keep it enabled.\\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: bool\\n whether or not to use parameter space noise (https:\\/\\/arxiv.org\\/abs\\/1706.01905)\\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) -> tf.Variable\\n function to select and action given observation.\\n ` See the top of the file for details.\\n train: (object, np.array, np.array, object, np.array, np.array) -> np.array\\n optimize the error in Bellman\\\\s equation.\\n ` See the top of the file for details.\\n update_target: () -> ()\\n copy the parameters from optimized Q function to the target Q function.\\n ` See the top of the...\\\"\\\"\\\"\\n if param_noise:\\n act_f = build_act_with_param_noise(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse, param_noise_filter_func=param_noise_filter_func)\\n else:\\n act_f = build_act(make_obs_ph, q_func, num_actions, scope=scope, reuse=reuse)\\n with tf.variable_scope(scope, reuse=reuse):\\n obs_t_input = U.ensure_tf_input(make_obs_ph('obs_t'))\\n act_t_ph = tf.placeholder(tf.int32, [None], name='action')\\n rew_t_ph = tf.placeholder(tf.float32, [None], name='reward')\\n obs_tp1_input = U.ensure_tf_input(make_obs_ph('obs_tp1'))\\n done_mask_ph = tf.placeholder(tf.float32, [None], name='done')\\n importance_weights_ph = tf.placeholder(tf.float32, [None], name='weight')\\n q_t = q_func(obs_t_input.get(), num_actions, scope='q_func', reuse=True)\\n q_func_vars = U.scope_vars(U.absolute_scope_name('q_func'))\\n q_tp1 = q_func(obs_tp1_input.get(), num_actions, scope='target_q_func')\\n target_q_func_vars = U.scope_vars(U.absolute_scope_name('target_q_func'))\\n q_t_selected = tf.reduce_sum((q_t * tf.one_hot(act_t_ph, num_actions)), 1)\\n if double_q:\\n q_tp1_using_online_net = q_func(obs_tp1_input.get(), num_actions, scope='q_func', reuse=True)\\n q_tp1_best_using_online_net = tf.arg_max(q_tp1_using_online_net, 1)\\n q_tp1_best = tf.reduce_sum((q_tp1 * tf.one_hot(q_tp1_best_using_online_net, num_actions)), 1)\\n else:\\n q_tp1_best = tf.reduce_max(q_tp1, 1)\\n q_tp1_best_masked = ((1.0 - done_mask_ph) * q_tp1_best)\\n q_t_selected_target = (rew_t_ph + (gamma * q_tp1_best_masked))\\n td_error = (q_t_selected - tf.stop_gradient(q_t_selected_target))\\n errors = U.huber_loss(td_error)\\n weighted_error = tf.reduce_mean((importance_weights_ph * errors))\\n if (grad_norm_clipping is not None):\\n optimize_expr = U.minimize_and_clip(optimizer, weighted_error, var_list=q_func_vars, clip_val=grad_norm_clipping)\\n else:\\n optimize_expr =...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _render_login_template(login_url, continue_url, email, admin):\",\"targets\":\"\\\"\\\"\\\"Renders the login page.\\n Args:\\n login_url: The parameter to _login_response.\\n continue_url: The parameter to _login_response.\\n email: The email address of the current user, if any.\\n admin: True if the user is currently an admin; False otherwise.\\n Returns:\\n A string containing the contents of the login page.\\n \\\"\\\"\\\"\\n if email:\\n login_message = 'Logged in'\\n else:\\n login_message = 'Not logged in'\\n email = 'test@example.com'\\n admin_checked = ('checked' if admin else '')\\n template_dict = {'email': cgi.escape(email, quote=True), 'admin_checked': admin_checked, 'login_message': login_message, 'login_url': cgi.escape(login_url, quote=True), 'continue_url': cgi.escape(continue_url, quote=True)}\\n return (_LOGIN_TEMPLATE % template_dict)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def iter_slices(string, slice_length):\",\"targets\":\"\\\"\\\"\\\"Iterate over slices of a string.\\n \\\"\\\"\\\"\\n pos = 0\\n while (pos < len(string)):\\n (yield string[pos:(pos + slice_length)])\\n pos += slice_length\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _handle_meas_date(meas_date):\\n\\n ''''Convert meas_date to seconds.'\\n '''\",\"targets\":\"if (meas_date is None):\\n meas_date = 0\\n elif (not np.isscalar(meas_date)):\\n if (len(meas_date) > 1):\\n meas_date = (meas_date[0] + (meas_date[1] \\/ 1000000.0))\\n else:\\n meas_date = meas_date[0]\\n return meas_date\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n meaning = None\\n if is_list:\\n if (len(value_pb.array_value.values) == 0):\\n return None\\n all_meanings = [_get_meaning(sub_value_pb) for sub_value_pb in value_pb.array_value.values]\\n unique_meanings = set(all_meanings)\\n if (len(unique_meanings) == 1):\\n meaning = unique_meanings.pop()\\n else:\\n meaning = all_meanings\\n elif value_pb.meaning:\\n meaning = value_pb.meaning\\n return meaning\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _get_meaning(value_pb, is_list=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 (query is None):\\n return query\\n for key in sorted(filters):\\n column_attr = getattr(model, key)\\n if ('property' == type(column_attr).__name__):\\n continue\\n value = filters[key]\\n if (not (isinstance(value, six.string_types) or isinstance(value, int))):\\n continue\\n query = query.filter(column_attr.op('LIKE')((u'%%%s%%' % value)))\\n return query\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _process_model_like_filter(model, query, filters):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _read(path, encoding='utf-8', comment=';;;'):\\n\\n ''''Returns an iterator over the lines in the file at the given path,\\n strippping comments and decoding each line to Unicode.'\\n '''\",\"targets\":\"if path:\\n if (isinstance(path, basestring) and os.path.exists(path)):\\n f = open(path, 'rb')\\n elif isinstance(path, basestring):\\n f = path.splitlines()\\n else:\\n f = path\\n for (i, line) in enumerate(f):\\n line = (line.strip(codecs.BOM_UTF8) if ((i == 0) and isinstance(line, str)) else line)\\n line = line.strip()\\n line = decode_utf8(line, encoding)\\n if ((not line) or (comment and line.startswith(comment))):\\n continue\\n (yield line)\\n raise StopIteration\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef copy_propagate(blocks, typemap):\\n\\n ''''compute copy propagation information for each block using fixed-point\\n iteration on data flow equations:\\n in_b = intersect(predec(B))\\n out_b = gen_b | (in_b - kill_b)'\\n '''\",\"targets\":\"cfg = compute_cfg_from_blocks(blocks)\\n entry = cfg.entry_point()\\n c_data = init_copy_propagate_data(blocks, entry, typemap)\\n (gen_copies, all_copies, kill_copies, in_copies, out_copies) = c_data\\n old_point = None\\n new_point = copy.deepcopy(out_copies)\\n while (old_point != new_point):\\n for label in blocks.keys():\\n if (label == entry):\\n continue\\n predecs = [i for (i, _d) in cfg.predecessors(label)]\\n in_copies[label] = out_copies[predecs[0]].copy()\\n for p in predecs:\\n in_copies[label] &= out_copies[p]\\n out_copies[label] = (gen_copies[label] | (in_copies[label] - kill_copies[label]))\\n old_point = new_point\\n new_point = copy.deepcopy(out_copies)\\n if (config.DEBUG_ARRAY_OPT == 1):\\n print ('copy propagate out_copies:', out_copies)\\n return (in_copies, out_copies)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def S_ISCHR(mode):\",\"targets\":\"\\\"\\\"\\\"Return True if mode is from a character special device file.\\n \\\"\\\"\\\"\\n return (S_IFMT(mode) == S_IFCHR)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_comment_app_name():\\n\\n ''''Returns the name of the comment app (either the setting value, if it\\n exists, or the default).'\\n '''\",\"targets\":\"return getattr(settings, 'COMMENTS_APP', DEFAULT_COMMENTS_APP)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n cmd_kwargs = copy.deepcopy(cmd_kwargs)\\n cmd_kwargs['python_shell'] = True\\n if onlyif:\\n if (__salt__['cmd.retcode'](onlyif, **cmd_kwargs) != 0):\\n return {'comment': 'onlyif execution failed', 'skip_watch': True, 'result': True}\\n if unless:\\n if (__salt__['cmd.retcode'](unless, **cmd_kwargs) == 0):\\n return {'comment': 'unless execution succeeded', 'skip_watch': True, 'result': True}\\n return True\\n\\n\\nWhat's a good function header?\",\"targets\":\"def mod_run_check(cmd_kwargs, onlyif, unless):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef decode_pair(s, pos=0):\\n\\n ''''Decodes a name\\/value pair.\\n The number of bytes decoded as well as the name\\/value pair\\n are returned.'\\n '''\",\"targets\":\"nameLength = ord(s[pos])\\n if (nameLength & 128):\\n nameLength = (struct.unpack('!L', s[pos:(pos + 4)])[0] & 2147483647)\\n pos += 4\\n else:\\n pos += 1\\n valueLength = ord(s[pos])\\n if (valueLength & 128):\\n valueLength = (struct.unpack('!L', s[pos:(pos + 4)])[0] & 2147483647)\\n pos += 4\\n else:\\n pos += 1\\n name = s[pos:(pos + nameLength)]\\n pos += nameLength\\n value = s[pos:(pos + valueLength)]\\n pos += valueLength\\n return (pos, (name, 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 _validate_device(device)\\n if (part_type not in set(['primary', 'logical', 'extended'])):\\n raise CommandExecutionError('Invalid part_type passed to partition.mkpartfs')\\n if (fs_type not in set(['ext2', 'fat32', 'fat16', 'linux-swap', 'reiserfs', 'hfs', 'hfs+', 'hfsx', 'NTFS', 'ufs', 'xfs'])):\\n raise CommandExecutionError('Invalid fs_type passed to partition.mkpartfs')\\n _validate_partition_boundary(start)\\n _validate_partition_boundary(end)\\n cmd = 'parted -m -s -- {0} mkpart {1} {2} {3} {4}'.format(device, part_type, fs_type, start, end)\\n out = __salt__['cmd.run'](cmd).splitlines()\\n return out\\n\\n\\nWhat's a good function header?\",\"targets\":\"def mkpartfs(device, part_type, fs_type, start, end):\",\"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 &= b\\n return a\\n\\n\\nWhat's a good function header?\",\"targets\":\"def iand(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 (len(root.handlers) == 0):\\n basicConfig()\\n root.info(msg, *args, **kwargs)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def info(msg, *args, **kwargs):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef get_config_h_filename():\\n\\n ''''Return full pathname of installed pyconfig.h file.'\\n '''\",\"targets\":\"if python_build:\\n if (os.name == 'nt'):\\n inc_dir = os.path.join(project_base, 'PC')\\n else:\\n inc_dir = project_base\\n else:\\n inc_dir = get_python_inc(plat_specific=1)\\n if (get_python_version() < '2.2'):\\n config_h = 'config.h'\\n else:\\n config_h = 'pyconfig.h'\\n return os.path.join(inc_dir, config_h)\",\"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 conf.url):\\n return\\n originalUrl = conf.url\\n if (re.search('\\\\\\\\[.+\\\\\\\\]', conf.url) and (not socket.has_ipv6)):\\n errMsg = 'IPv6 addressing is not supported '\\n errMsg += 'on this platform'\\n raise SqlmapGenericException(errMsg)\\n if ((not re.search('^http[s]*:\\/\\/', conf.url, re.I)) and (not re.search('^ws[s]*:\\/\\/', conf.url, re.I))):\\n if (':443\\/' in conf.url):\\n conf.url = ('https:\\/\\/' + conf.url)\\n else:\\n conf.url = ('http:\\/\\/' + conf.url)\\n if (kb.customInjectionMark in conf.url):\\n conf.url = conf.url.replace('?', URI_QUESTION_MARKER)\\n try:\\n urlSplit = urlparse.urlsplit(conf.url)\\n except ValueError as ex:\\n errMsg = (\\\"invalid URL '%s' has been given ('%s'). \\\" % (conf.url, getSafeExString(ex)))\\n errMsg += \\\"Please be sure that you don't have any leftover characters (e.g. '[' or ']') \\\"\\n errMsg += 'in the hostname part'\\n raise SqlmapGenericException(errMsg)\\n hostnamePort = (urlSplit.netloc.split(':') if (not re.search('\\\\\\\\[.+\\\\\\\\]', urlSplit.netloc)) else filter(None, (re.search('\\\\\\\\[.+\\\\\\\\]', urlSplit.netloc).group(0), re.search('\\\\\\\\](:(?P\\\\\\\\d+))?', urlSplit.netloc).group('port'))))\\n conf.scheme = (urlSplit.scheme.strip().lower() if (not conf.forceSSL) else 'https')\\n conf.path = urlSplit.path.strip()\\n conf.hostname = hostnamePort[0].strip()\\n conf.ipv6 = (conf.hostname != conf.hostname.strip('[]'))\\n conf.hostname = conf.hostname.strip('[]').replace(kb.customInjectionMark, '')\\n try:\\n _ = conf.hostname.encode('idna')\\n except LookupError:\\n _ = conf.hostname.encode(UNICODE_ENCODING)\\n except UnicodeError:\\n _ = None\\n if any(((_ is None), re.search('\\\\\\\\s', conf.hostname), ('..' in conf.hostname), conf.hostname.startswith('.'), ('\\\\n' in originalUrl))):\\n errMsg = (\\\"invalid target URL ('%s')\\\" % originalUrl)\\n raise...\\n\\nWhat's a good function header?\",\"targets\":\"def parseTargetUrl():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef finddir(o, match, case=False):\\n\\n ''''return all attributes of *o* which match string in match. if case\\n is True require an exact case match.'\\n '''\",\"targets\":\"if case:\\n names = [(name, name) for name in dir(o) if is_string_like(name)]\\n else:\\n names = [(name.lower(), name) for name in dir(o) if is_string_like(name)]\\n match = match.lower()\\n return [orig for (name, orig) in names if (name.find(match) >= 0)]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def fill_width(bytes_, width):\",\"targets\":\"\\\"\\\"\\\"Ensure a byte string representing a positive integer is a specific width\\n (in bytes)\\n :param bytes_:\\n The integer byte string\\n :param width:\\n The desired width as an integer\\n :return:\\n A byte string of the width specified\\n \\\"\\\"\\\"\\n while (len(bytes_) < width):\\n bytes_ = ('\\\\x00' + bytes_)\\n return bytes_\",\"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 sympy.functions.elementary.trigonometric import _pi_coeff as coeff\\n if theta.is_Interval:\\n interval_len = theta.measure\\n if (interval_len >= (2 * S.Pi)):\\n if ((interval_len == (2 * S.Pi)) and theta.left_open and theta.right_open):\\n k = coeff(theta.start)\\n return Union(Interval(0, (k * S.Pi), False, True), Interval((k * S.Pi), (2 * S.Pi), True, True))\\n return Interval(0, (2 * S.Pi), False, True)\\n (k_start, k_end) = (coeff(theta.start), coeff(theta.end))\\n if ((k_start is None) or (k_end is None)):\\n raise NotImplementedError('Normalizing theta without pi as coefficient is not yet implemented')\\n new_start = (k_start * S.Pi)\\n new_end = (k_end * S.Pi)\\n if (new_start > new_end):\\n return Union(Interval(S.Zero, new_end, False, theta.right_open), Interval(new_start, (2 * S.Pi), theta.left_open, True))\\n else:\\n return Interval(new_start, new_end, theta.left_open, theta.right_open)\\n elif theta.is_FiniteSet:\\n new_theta = []\\n for element in theta:\\n k = coeff(element)\\n if (k is None):\\n raise NotImplementedError('Normalizing theta without pi as coefficient, is not Implemented.')\\n else:\\n new_theta.append((k * S.Pi))\\n return FiniteSet(*new_theta)\\n elif theta.is_Union:\\n return Union(*[normalize_theta_set(interval) for interval in theta.args])\\n elif theta.is_subset(S.Reals):\\n raise NotImplementedError(('Normalizing theta when, it is of type %s is not implemented' % type(theta)))\\n else:\\n raise ValueError((' %s is not a real set' % theta))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def normalize_theta_set(theta):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef disable_job(name=None):\\n\\n ''''Return true is job is disabled successfully.\\n :param name: The name of the job to disable.\\n :return: Return true if job is disabled successfully.\\n CLI Example:\\n .. code-block:: bash\\n salt \\\\'*\\\\' jenkins.disable_job jobname'\\n '''\",\"targets\":\"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 exists.'.format(name))\\n try:\\n server.disable_job(name)\\n except jenkins.JenkinsException as err:\\n raise SaltInvocationError('Something went wrong {0}.'.format(err))\\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 isinstance(radius, Quantity):\\n sr_angle = radius.to(u.degree)\\n else:\\n sr_angle = (radius * u.degree)\\n return sr_angle.value\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _validate_sr(radius):\",\"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 = TpPd(pd=3)\\n b = MessageType(mesType=2)\\n c = AttachResult()\\n d = ForceToStandby()\\n e = GprsTimer()\\n f = RadioPriorityAndSpareHalfOctets()\\n h = RoutingAreaIdentification()\\n packet = ((((((a \\/ b) \\/ c) \\/ d) \\/ e) \\/ f) \\/ h)\\n if (PTmsiSignature_presence is 1):\\n i = PTmsiSignature(ieiPTS=25)\\n packet = (packet \\/ i)\\n if (GprsTimer_presence is 1):\\n j = GprsTimer(ieiGT=23)\\n packet = (packet \\/ j)\\n if (MobileId_presence is 1):\\n k = MobileIdHdr(ieiMI=24, eightBitMI=0)\\n packet = (packet \\/ k)\\n if (MobileId_presence1 is 1):\\n l = MobileIdHdr(ieiMI=35, eightBitMI=0)\\n packet = (packet \\/ l)\\n if (GmmCause_presence is 1):\\n m = GmmCause(ieiGC=37)\\n packet = (packet \\/ m)\\n return packet\\n\\n\\nWhat's a good function header?\",\"targets\":\"def attachAccept(PTmsiSignature_presence=0, GprsTimer_presence=0, MobileId_presence=0, MobileId_presence1=0, GmmCause_presence=0):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _is_unorderable_exception(e):\",\"targets\":\"\\\"\\\"\\\"Check if the exception raised is an unorderable exception.\\n The error message differs for 3 <= PY <= 3.5 and PY >= 3.6, so\\n we need to condition based on Python version.\\n Parameters\\n e : Exception or sub-class\\n The exception object to check.\\n Returns\\n boolean : Whether or not the exception raised is an unorderable exception.\\n \\\"\\\"\\\"\\n if PY36:\\n return (\\\"'>' not supported between instances of\\\" in str(e))\\n elif PY3:\\n return ('unorderable' in str(e))\\n return False\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef is_undefined(obj):\\n\\n ''''Check if the object passed is undefined. This does nothing more than\\n performing an instance check against :class:`Undefined` but looks nicer.\\n This can be used for custom filters or tests that want to react to\\n undefined variables. For example a custom default filter can look like\\n this::\\n def default(var, default=\\\\'\\\\'):\\n if is_undefined(var):\\n return default\\n return var'\\n '''\",\"targets\":\"from jinja2.runtime import Undefined\\n return isinstance(obj, Undefined)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def cucumber_testresult(registry, xml_parent, data):\",\"targets\":\"\\\"\\\"\\\"yaml: cucumber-testresult\\n Publish cucumber test results.\\n Requires the Jenkins :jenkins-wiki:`cucumber testresult\\n `.\\n :arg str results: Results filename (required)\\n :arg bool ignore-bad-steps: Ignore not existed step results (default false)\\n Minimal example:\\n .. literalinclude::\\n \\/..\\/..\\/tests\\/publishers\\/fixtures\\/cucumber-testresult-minimal.yaml\\n :language: yaml\\n Full Example:\\n .. literalinclude::\\n \\/..\\/..\\/tests\\/publishers\\/fixtures\\/cucumber-testresult-full.yaml\\n :language: yaml\\n \\\"\\\"\\\"\\n cucumber_result = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.cucumber.jsontestsupport.CucumberTestResultArchiver')\\n cucumber_result.set('plugin', 'cucumber-testresult-plugin')\\n mappings = [('results', 'testResults', None), ('ignore-bad-steps', 'ignoreBadSteps', False)]\\n helpers.convert_mapping_to_xml(cucumber_result, data, mappings, fail_required=True)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _getAccessibleAttribute(attributeName, stringObject):\",\"targets\":\"\\\"\\\"\\\"Get the accessible attribute.\\n \\\"\\\"\\\"\\n if (attributeName in globalNativeFunctionSet):\\n return getattr(stringObject, attributeName, None)\\n if (attributeName in globalGetAccessibleAttributeSet):\\n stringAttribute = StringAttribute(stringObject)\\n return getattr(stringAttribute, attributeName, 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 get_db_ips():\\n\\n ''''Returns a list of database machines.\\n Returns:\\n A list of strings containing IP addresses.'\\n '''\",\"targets\":\"return list(set(([get_db_master_ip()] + get_db_slave_ips())))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def long_answer_prepare_decoder(inputs, targets, hparams):\",\"targets\":\"\\\"\\\"\\\"Prepare one shard of the model for the decoder.\\n Args:\\n inputs: a Tensor.\\n targets: a Tensor.\\n hparams: run hyperparameters\\n Returns:\\n decoder_input: a Tensor, bottom of decoder stack\\n \\\"\\\"\\\"\\n decoder_input = tf.concat([length_embedding(targets, hparams), inputs, common_layers.shift_left_3d(targets)], 1)\\n if (hparams.pos == 'timing'):\\n decoder_input = common_attention.add_timing_signal_1d(decoder_input)\\n return decoder_input\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@asyncio.coroutine\\ndef async_trigger(hass, config, action):\\n\\n ''''Listen for state changes based on configuration.'\\n '''\",\"targets\":\"entity_id = config.get(CONF_ENTITY_ID)\\n zone_entity_id = config.get(CONF_ZONE)\\n event = config.get(CONF_EVENT)\\n @callback\\n def zone_automation_listener(entity, from_s, to_s):\\n 'Listen for state changes and calls action.'\\n if ((from_s and (not location.has_location(from_s))) or (not location.has_location(to_s))):\\n return\\n zone_state = hass.states.get(zone_entity_id)\\n if from_s:\\n from_match = condition.zone(hass, zone_state, from_s)\\n else:\\n from_match = False\\n to_match = condition.zone(hass, zone_state, to_s)\\n if (((event == EVENT_ENTER) and (not from_match) and to_match) or ((event == EVENT_LEAVE) and from_match and (not to_match))):\\n hass.async_run_job(action, {'trigger': {'platform': 'zone', 'entity_id': entity, 'from_state': from_s, 'to_state': to_s, 'zone': zone_state, 'event': event}})\\n return async_track_state_change(hass, entity_id, zone_automation_listener, MATCH_ALL, MATCH_ALL)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _force_mutable(x):\\n\\n ''''Return a matrix as a Matrix, otherwise return x.'\\n '''\",\"targets\":\"if getattr(x, 'is_Matrix', False):\\n return x.as_mutable()\\n elif isinstance(x, Basic):\\n return x\\n elif hasattr(x, '__array__'):\\n a = x.__array__()\\n if (len(a.shape) == 0):\\n return sympify(a)\\n return Matrix(x)\\n return x\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def check_output(output, unit, inputs, function=None):\",\"targets\":\"\\\"\\\"\\\"Check that function output can be stored in the output array given.\\n Parameters\\n output : array or `~astropy.units.Quantity` or tuple\\n Array that should hold the function output (or tuple of such arrays).\\n unit : `~astropy.units.Unit` or None, or tuple\\n Unit that the output will have, or `None` for pure numbers (should be\\n tuple of same if output is a tuple of outputs).\\n inputs : tuple\\n Any input arguments. These should be castable to the output.\\n function : callable\\n The function that will be producing the output. If given, used to\\n give a more informative error message.\\n Returns\\n arrays : `~numpy.ndarray` view of ``output`` (or tuple of such views).\\n Raises\\n UnitTypeError : If ``unit`` is inconsistent with the class of ``output``\\n TypeError : If the ``inputs`` cannot be cast safely to ``output``.\\n \\\"\\\"\\\"\\n if isinstance(output, tuple):\\n return tuple((check_output(output_, unit_, inputs, function) for (output_, unit_) in zip(output, unit)))\\n if (output is None):\\n return None\\n if hasattr(output, '__quantity_subclass__'):\\n if (unit is None):\\n raise TypeError('Cannot store non-quantity output{0} in {1} instance'.format((' from {0} function'.format(function.__name__) if (function is not None) else ''), type(output)))\\n if (output.__quantity_subclass__(unit)[0] is not type(output)):\\n raise UnitTypeError(\\\"Cannot store output with unit '{0}'{1} in {2} instance. Use {3} instance instead.\\\".format(unit, (' from {0} function'.format(function.__name__) if (function is not None) else ''), type(output), output.__quantity_subclass__(unit)[0]))\\n output = output.view(np.ndarray)\\n elif (not ((unit is None) or (unit is dimensionless_unscaled))):\\n raise UnitTypeError('Cannot store quantity with dimension {0}in a non-Quantity instance.'.format(('' if (function is None) else 'resulting from {0} function '.format(function.__name__))))\\n if (not np.can_cast(np.result_type(*inputs), output.dtype, casting='same_kind')):\\n raise TypeError('Arguments cannot be cast safely to inplace output with dtype={0}'.format(output.dtype))\\n return output\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@register.inclusion_tag('admin\\/submit_line.html', takes_context=True)\\ndef submit_row(context):\",\"targets\":\"\\\"\\\"\\\"Displays the row of buttons for delete and save.\\n \\\"\\\"\\\"\\n opts = context['opts']\\n change = context['change']\\n is_popup = context['is_popup']\\n save_as = context['save_as']\\n ctx = {'opts': opts, 'onclick_attrib': ((opts.get_ordered_objects() and change and 'onclick=\\\"submitOrderForm();\\\"') or ''), 'show_delete_link': ((not is_popup) and context['has_delete_permission'] and change and context.get('show_delete', True)), 'show_save_as_new': ((not is_popup) and change and save_as), 'show_save_and_add_another': (context['has_add_permission'] and (not is_popup) and ((not save_as) or context['add'])), 'show_save_and_continue': ((not is_popup) and context['has_change_permission']), 'is_popup': is_popup, 'show_save': True}\\n if (context.get('original') is not None):\\n ctx['original'] = context['original']\\n return ctx\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n handle_prompt_abort('a user-specified prompt() call')\\n if key:\\n previous_value = env.get(key)\\n default_str = ''\\n if (default != ''):\\n default_str = (' [%s] ' % str(default).strip())\\n else:\\n default_str = ' '\\n prompt_str = (text.strip() + default_str)\\n value = None\\n while (value is None):\\n value = (raw_input(prompt_str) or default)\\n if validate:\\n if callable(validate):\\n try:\\n value = validate(value)\\n except Exception as e:\\n value = None\\n print 'Validation failed for the following reason:'\\n print (indent(e.message) + '\\\\n')\\n else:\\n if (not validate.startswith('^')):\\n validate = ('^' + validate)\\n if (not validate.endswith('$')):\\n validate += '$'\\n result = re.findall(validate, value)\\n if (not result):\\n print (\\\"Regular expression validation failed: '%s' does not match '%s'\\\\n\\\" % (value, validate))\\n value = None\\n if key:\\n env[key] = value\\n if (key and (previous_value is not None) and (previous_value != value)):\\n warn((\\\"overwrote previous env variable '%s'; used to be '%s', is now '%s'.\\\" % (key, previous_value, value)))\\n return value\\n\\n\\nWhat's a good function header?\",\"targets\":\"def prompt(text, key=None, default='', validate=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _good_enough(dom, features):\",\"targets\":\"\\\"\\\"\\\"_good_enough(dom, features) -> Return 1 if the dom offers the features\\n \\\"\\\"\\\"\\n for (f, v) in features:\\n if (not dom.hasFeature(f, v)):\\n return 0\\n return 1\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _gram_omp(Gram, Xy, n_nonzero_coefs, tol_0=None, tol=None, copy_Gram=True, copy_Xy=True, return_path=False):\\n\\n ''''Orthogonal Matching Pursuit step on a precomputed Gram matrix.\\n This function uses the Cholesky decomposition method.\\n Parameters\\n Gram : array, shape (n_features, n_features)\\n Gram matrix of the input data matrix\\n Xy : array, shape (n_features,)\\n Input targets\\n n_nonzero_coefs : int\\n Targeted number of non-zero elements\\n tol_0 : float\\n Squared norm of y, required if tol is not None.\\n tol : float\\n Targeted squared error, if not None overrides n_nonzero_coefs.\\n copy_Gram : bool, optional\\n Whether the gram matrix must be copied by the algorithm. A false\\n value is only helpful if it is already Fortran-ordered, otherwise a\\n copy is made anyway.\\n copy_Xy : bool, optional\\n Whether the covariance vector Xy must be copied by the algorithm.\\n If False, it may be overwritten.\\n return_path : bool, optional. Default: False\\n Whether to return every value of the nonzero coefficients along the\\n forward path. Useful for cross-validation.\\n Returns\\n gamma : array, shape (n_nonzero_coefs,)\\n Non-zero elements of the solution\\n idx : array, shape (n_nonzero_coefs,)\\n Indices of the positions of the elements in gamma within the solution\\n vector\\n coefs : array, shape (n_features, n_nonzero_coefs)\\n The first k values of column k correspond to the coefficient value\\n for the active features at that step. The lower left triangle contains\\n garbage. Only returned if ``return_path=True``.\\n n_active : int\\n Number of active features at convergence.'\\n '''\",\"targets\":\"Gram = (Gram.copy('F') if copy_Gram else np.asfortranarray(Gram))\\n if copy_Xy:\\n Xy = Xy.copy()\\n min_float = np.finfo(Gram.dtype).eps\\n (nrm2, swap) = linalg.get_blas_funcs(('nrm2', 'swap'), (Gram,))\\n (potrs,) = get_lapack_funcs(('potrs',), (Gram,))\\n indices = np.arange(len(Gram))\\n alpha = Xy\\n tol_curr = tol_0\\n delta = 0\\n gamma = np.empty(0)\\n n_active = 0\\n max_features = (len(Gram) if (tol is not None) else n_nonzero_coefs)\\n if solve_triangular_args:\\n L = np.empty((max_features, max_features), dtype=Gram.dtype)\\n else:\\n L = np.zeros((max_features, max_features), dtype=Gram.dtype)\\n L[(0, 0)] = 1.0\\n if return_path:\\n coefs = np.empty_like(L)\\n while True:\\n lam = np.argmax(np.abs(alpha))\\n if ((lam < n_active) or ((alpha[lam] ** 2) < min_float)):\\n warnings.warn(premature, RuntimeWarning, stacklevel=3)\\n break\\n if (n_active > 0):\\n L[n_active, :n_active] = Gram[lam, :n_active]\\n linalg.solve_triangular(L[:n_active, :n_active], L[n_active, :n_active], trans=0, lower=1, overwrite_b=True, **solve_triangular_args)\\n v = (nrm2(L[n_active, :n_active]) ** 2)\\n if ((1 - v) <= min_float):\\n warnings.warn(premature, RuntimeWarning, stacklevel=3)\\n break\\n L[(n_active, n_active)] = np.sqrt((1 - v))\\n (Gram[n_active], Gram[lam]) = swap(Gram[n_active], Gram[lam])\\n (Gram.T[n_active], Gram.T[lam]) = swap(Gram.T[n_active], Gram.T[lam])\\n (indices[n_active], indices[lam]) = (indices[lam], indices[n_active])\\n (Xy[n_active], Xy[lam]) = (Xy[lam], Xy[n_active])\\n n_active += 1\\n (gamma, _) = potrs(L[:n_active, :n_active], Xy[:n_active], lower=True, overwrite_b=False)\\n if return_path:\\n coefs[:n_active, (n_active - 1)] = gamma\\n beta = np.dot(Gram[:, :n_active], gamma)\\n alpha = (Xy - beta)\\n if (tol is not None):\\n tol_curr += delta\\n delta =...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _cloned_intersection(a, b):\",\"targets\":\"\\\"\\\"\\\"return the intersection of sets a and b, counting\\n any overlap between \\\\cloned\\\\ predecessors.\\n The returned set is in terms of the entities present within \\\\a\\\\.\\n \\\"\\\"\\\"\\n all_overlap = set(_expand_cloned(a)).intersection(_expand_cloned(b))\\n return set((elem for elem in a if all_overlap.intersection(elem._cloned_set)))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _str_to_num(n):\",\"targets\":\"\\\"\\\"\\\"Convert a hex or octal string to a decimal number.\\n :param n: Hex or octal string to be converted.\\n :return: Resulting decimal number.\\n \\\"\\\"\\\"\\n val = 0\\n col = long(1)\\n if (n[:1] == 'x'):\\n n = ('0' + n)\\n if (n[:2] == '0x'):\\n n = string.lower(n[2:])\\n while (len(n) > 0):\\n l = n[(len(n) - 1)]\\n val = (val + (string.hexdigits.index(l) * col))\\n col = (col * 16)\\n n = n[:(len(n) - 1)]\\n elif (n[0] == '\\\\\\\\'):\\n n = n[1:]\\n while (len(n) > 0):\\n l = n[(len(n) - 1)]\\n if ((ord(l) < 48) or (ord(l) > 57)):\\n break\\n val = (val + (int(l) * col))\\n col = (col * 8)\\n n = n[:(len(n) - 1)]\\n else:\\n val = string.atol(n)\\n return val\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef dh_shared_key(key, b):\\n\\n ''''Return an integer that is the shared key.\\n This is what Bob and Alice can both calculate using the public\\n keys they received from each other and their private keys.\\n Parameters\\n key: Tuple (p, g, x) generated by ``dh_public_key``\\n b: Random number in the range of 2 to p - 1\\n (Chosen by second key exchange member (Bob))\\n Returns\\n shared key (int)\\n Examples\\n >>> from sympy.crypto.crypto import (\\n ... dh_private_key, dh_public_key, dh_shared_key)\\n >>> prk = dh_private_key();\\n >>> p, g, x = dh_public_key(prk);\\n >>> sk = dh_shared_key((p, g, x), 1000)\\n >>> sk == pow(x, 1000, p)\\n True'\\n '''\",\"targets\":\"(p, _, x) = key\\n if ((1 >= b) or (b >= p)):\\n raise ValueError(filldedent(('\\\\n Value of b should be greater 1 and less\\\\n than prime %s.' % p)))\\n return pow(x, b, p)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def create_hadoopcli_client():\",\"targets\":\"\\\"\\\"\\\"Given that we want one of the hadoop cli clients (unlike snakebite),\\n this one will return the right one.\\n \\\"\\\"\\\"\\n version = hdfs_config.get_configured_hadoop_version()\\n if (version == 'cdh4'):\\n return HdfsClient()\\n elif (version == 'cdh3'):\\n return HdfsClientCdh3()\\n elif (version == 'apache1'):\\n return HdfsClientApache1()\\n else:\\n raise ValueError('Error: Unknown version specified in Hadoop versionconfiguration parameter')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n h = sdm_zero()\\n g = f\\n while g:\\n g = sdm_nf_buchberger(g, G, O, K)\\n if g:\\n h = sdm_add(h, [sdm_LT(g)], O, K)\\n g = g[1:]\\n return h\\n\\n\\nWhat's a good function header?\",\"targets\":\"def sdm_nf_buchberger_reduced(f, G, O, K):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def compute_node_search_by_hypervisor(context, hypervisor_match):\",\"targets\":\"\\\"\\\"\\\"Get computeNodes given a hypervisor hostname match string.\\n \\\"\\\"\\\"\\n return IMPL.compute_node_search_by_hypervisor(context, hypervisor_match)\",\"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 (k, v) in expected.iteritems():\\n eq_(v, getattr(received, k))\\n\\n\\nWhat's a good function header?\",\"targets\":\"def attrs_eq(received, **expected):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"@synchronized(DIR_LOCK)\\ndef cleanup_empty_directories(path):\",\"targets\":\"\\\"\\\"\\\"Remove all empty folders inside (and including) \\\\path\\\\\\n \\\"\\\"\\\"\\n path = os.path.normpath(path)\\n while 1:\\n repeat = False\\n for (root, dirs, files) in os.walk(path, topdown=False):\\n if ((not dirs) and (not files) and (root != path)):\\n try:\\n remove_dir(root)\\n repeat = True\\n except:\\n pass\\n if (not repeat):\\n break\\n try:\\n remove_dir(path)\\n except:\\n pass\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def __virtual__():\",\"targets\":\"\\\"\\\"\\\"Only load if RabbitMQ is installed.\\n \\\"\\\"\\\"\\n if __salt__['cmd.has_exec']('rabbitmqctl'):\\n return True\\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 print(('Determining list of input files and labels from %s.' % data_dir))\\n challenge_synsets = [l.strip() for l in tf.gfile.FastGFile(labels_file, 'r').readlines()]\\n labels = []\\n filenames = []\\n synsets = []\\n label_index = 1\\n for synset in challenge_synsets:\\n jpeg_file_path = ('%s\\/%s\\/*.JPEG' % (data_dir, synset))\\n matching_files = tf.gfile.Glob(jpeg_file_path)\\n labels.extend(([label_index] * len(matching_files)))\\n synsets.extend(([synset] * len(matching_files)))\\n filenames.extend(matching_files)\\n if (not (label_index % 100)):\\n print(('Finished finding files in %d of %d classes.' % (label_index, len(challenge_synsets))))\\n label_index += 1\\n shuffled_index = list(range(len(filenames)))\\n random.seed(12345)\\n random.shuffle(shuffled_index)\\n filenames = [filenames[i] for i in shuffled_index]\\n synsets = [synsets[i] for i in shuffled_index]\\n labels = [labels[i] for i in shuffled_index]\\n print(('Found %d JPEG files across %d labels inside %s.' % (len(filenames), len(challenge_synsets), data_dir)))\\n return (filenames, synsets, labels)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _find_image_files(data_dir, labels_file):\",\"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 HAS_CX_ORACLE:\\n return __virtualname__\\n return (False, 'The oracle execution module not loaded: python oracle library not found.')\\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 _byte_string(s):\\n\\n ''''Cast a string or byte string to an ASCII byte string.'\\n '''\",\"targets\":\"return s.encode('US-ASCII')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _ParseValue(value, index, arg, metadata):\",\"targets\":\"\\\"\\\"\\\"Parses value, a string, into the appropriate type.\\n The function used to parse value is determined by the remaining arguments.\\n Args:\\n value: The string value to be parsed, typically a command line argument.\\n index: The index of the value in the function\\\\s argspec.\\n arg: The name of the argument the value is being parsed for.\\n metadata: Metadata about the function, typically from Fire decorators.\\n Returns:\\n value, parsed into the appropriate type for calling a function.\\n \\\"\\\"\\\"\\n parse_fn = parser.DefaultParseValue\\n parse_fns = metadata.get(decorators.FIRE_PARSE_FNS)\\n if parse_fns:\\n default = parse_fns['default']\\n positional = parse_fns['positional']\\n named = parse_fns['named']\\n if ((index is not None) and (0 <= index < len(positional))):\\n parse_fn = positional[index]\\n elif (arg in named):\\n parse_fn = named[arg]\\n elif (default is not None):\\n parse_fn = default\\n return parse_fn(value)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef OpenDocumentPresentation():\\n\\n ''''Creates a presentation document'\\n '''\",\"targets\":\"doc = OpenDocument('application\\/vnd.oasis.opendocument.presentation')\\n doc.presentation = Presentation()\\n doc.body.addElement(doc.presentation)\\n return doc\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n message = get_object_or_404(GroupMessage, pk=message_id, is_active=True)\\n if (request.method == 'POST'):\\n message.is_active = False\\n message.save()\\n return redirect(request, message.topic)\\n return render(request, template_name, {'group': message.topic.group, 'topic': message.topic, 'message': message})\\n\\n\\nWhat's a good function header?\",\"targets\":\"@membership_required\\ndef message_remove(request, slug, topic_id, message_id, template_name='groups\\/messages\\/message_remove_confirm.html'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _CopyDocumentToProtocolBuffer(document, pb):\\n\\n ''''Copies Document to a document_pb.Document protocol buffer.'\\n '''\",\"targets\":\"pb.set_storage(document_pb.Document.DISK)\\n if document.doc_id:\\n pb.set_id(document.doc_id.encode('utf-8'))\\n if document.language:\\n pb.set_language(document.language.encode('utf-8'))\\n for field in document.fields:\\n field_pb = pb.add_field()\\n _CopyFieldToProtocolBuffer(field, field_pb)\\n for facet in document.facets:\\n facet_pb = pb.add_facet()\\n facet._CopyToProtocolBuffer(facet_pb)\\n pb.set_order_id(document.rank)\\n return pb\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def generate_recommendation_data():\",\"targets\":\"\\\"\\\"\\\"Traverses topic tree to generate a dictionary with related subtopics per subtopic.\\n \\\"\\\"\\\"\\n global recommendation_data\\n if recommendation_data:\\n return recommendation_data\\n tree = get_topic_nodes_with_children(parent='root')\\n topic_index = 0\\n subtopic_index = 0\\n for topic in tree:\\n subtopic_index = 0\\n for subtopic_id in topic['children']:\\n neighbors_dist_1 = get_neighbors_at_dist_1(topic_index, subtopic_index, topic)\\n recommendation_data[subtopic_id] = {'related_subtopics': ([(subtopic_id + ' 0')] + neighbors_dist_1)}\\n subtopic_index += 1\\n topic_index += 1\\n for subtopic in recommendation_data:\\n related = recommendation_data[subtopic]['related_subtopics']\\n other_neighbors = get_subsequent_neighbors(related, recommendation_data, subtopic)\\n recommendation_data[subtopic]['related_subtopics'] += other_neighbors\\n for subtopic in recommendation_data:\\n at_dist_4 = []\\n at_dist_lt_4 = []\\n for recc in recommendation_data[subtopic]['related_subtopics']:\\n if (recc.split(' ')[1] == '4'):\\n at_dist_4.append(recc.split(' ')[0])\\n else:\\n at_dist_lt_4.append(recc.split(' ')[0])\\n sorted_related = (at_dist_lt_4 + at_dist_4)\\n recommendation_data[subtopic]['related_subtopics'] = sorted_related\\n return recommendation_data\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef byte2bin(number, classic_mode=True):\\n\\n ''''Convert a byte (integer in 0..255 range) to a binary string.\\n If classic_mode is true (default value), reverse bits.\\n >>> byte2bin(10)\\n \\\\'00001010\\\\'\\n >>> byte2bin(10, False)\\n \\\\'01010000\\\\''\\n '''\",\"targets\":\"text = ''\\n for i in range(0, 8):\\n if classic_mode:\\n mask = (1 << (7 - i))\\n else:\\n mask = (1 << i)\\n if ((number & mask) == mask):\\n text += '1'\\n else:\\n text += '0'\\n return text\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n klasses = (bool, int, float, complex, str)\\n if six.PY2:\\n klasses += (unicode, long)\\n klasses += (bytes,)\\n for kls in klasses:\\n CONST_CLS[kls] = Const\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _update_const_classes():\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _import_module(name):\\n\\n ''''Import module, returning the module after the last dot.'\\n '''\",\"targets\":\"__import__(name)\\n return sys.modules[name]\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _band2array(a, lower=0, symmetric=False, hermitian=False):\\n\\n ''''Take an upper or lower triangular banded matrix and return a\\n numpy array.\\n INPUTS:\\n a -- a matrix in upper or lower triangular banded matrix\\n lower -- is the matrix upper or lower triangular?\\n symmetric -- if True, return the original result plus its transpose\\n hermitian -- if True (and symmetric False), return the original\\n result plus its conjugate transposed'\\n '''\",\"targets\":\"n = a.shape[1]\\n r = a.shape[0]\\n _a = 0\\n if (not lower):\\n for j in range(r):\\n _b = np.diag(a[((r - 1) - j)], k=j)[j:(n + j), j:(n + j)]\\n _a += _b\\n if (symmetric and (j > 0)):\\n _a += _b.T\\n elif (hermitian and (j > 0)):\\n _a += _b.conjugate().T\\n else:\\n for j in range(r):\\n _b = np.diag(a[j], k=j)[0:n, 0:n]\\n _a += _b\\n if (symmetric and (j > 0)):\\n _a += _b.T\\n elif (hermitian and (j > 0)):\\n _a += _b.conjugate().T\\n _a = _a.T\\n return _a\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def get_generic_info(block, category):\",\"targets\":\"\\\"\\\"\\\"\\n \\\"\\\"\\\"\\n generic_info = {}\\n generic_block = get_generic_block(block)\\n for line in generic_block:\\n (key, value) = get_key_value(line)\\n if (key == u'name'):\\n key = ((category + u'.') + key)\\n generic_info[key] = value\\n return generic_info\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@gen.engine\\ndef SetupAndDispatch(callback):\\n\\n ''''Sets the environment and dispatches according to command-line options.'\\n '''\",\"targets\":\"EmailManager.SetInstance(SendGridEmailManager())\\n ThrottleUsage()\\n client = db_client.DBClient.Instance()\\n (yield gen.Task(Dispatch, client))\\n callback()\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n feAbbrevs = OrderedDict()\\n posspec = []\\n posspec_separate = False\\n for lyr in (u'Verb', u'Noun', u'Adj', u'Adv', u'Prep', u'Scon', u'Art'):\\n if ((lyr in sent) and sent[lyr]):\\n for (a, b, lbl) in sent[lyr]:\\n if (lbl == u'X'):\\n continue\\n if any((1 for (x, y, felbl) in sent.FE[0] if ((x <= a < y) or (a <= x < b)))):\\n posspec_separate = True\\n posspec.append((a, b, lbl.lower().replace(u'-', u'')))\\n if posspec_separate:\\n POSSPEC = _annotation_ascii_FE_layer(posspec, {}, feAbbrevs)\\n FE1 = _annotation_ascii_FE_layer(sorted((sent.FE[0] + (posspec if (not posspec_separate) else []))), sent.FE[1], feAbbrevs)\\n FE2 = FE3 = None\\n if (u'FE2' in sent):\\n FE2 = _annotation_ascii_FE_layer(sent.FE2[0], sent.FE2[1], feAbbrevs)\\n if (u'FE3' in sent):\\n FE3 = _annotation_ascii_FE_layer(sent.FE3[0], sent.FE3[1], feAbbrevs)\\n for (i, j) in sent.Target:\\n (FE1span, FE1name, FE1exp) = FE1\\n if (len(FE1span) < j):\\n FE1span += (u' ' * (j - len(FE1span)))\\n if (len(FE1name) < j):\\n FE1name += (u' ' * (j - len(FE1name)))\\n FE1[1] = FE1name\\n FE1[0] = ((FE1span[:i] + FE1span[i:j].replace(u' ', u'*').replace(u'-', u'=')) + FE1span[j:])\\n long_lines = [sent.text]\\n if posspec_separate:\\n long_lines.extend(POSSPEC[:2])\\n long_lines.extend([FE1[0], (FE1[1] + FE1[2])])\\n if FE2:\\n long_lines.extend([FE2[0], (FE2[1] + FE2[2])])\\n if FE3:\\n long_lines.extend([FE3[0], (FE3[1] + FE3[2])])\\n long_lines.append(u'')\\n outstr = u'\\\\n'.join(map(u'\\\\n'.join, zip_longest(fillvalue=u' ', *mimic_wrap(long_lines))))\\n if feAbbrevs:\\n outstr += ((u'(' + u', '.join((u'='.join(pair) for pair in feAbbrevs.items()))) + u')')\\n assert (len(feAbbrevs) == len(dict(feAbbrevs))), u'Abbreviation clash'\\n outstr += u'\\\\n'\\n return outstr\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _annotation_ascii_FEs(sent):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def CreateCustomizerFeed(client, feed_name):\",\"targets\":\"\\\"\\\"\\\"Creates a new AdCustomizerFeed.\\n Args:\\n client: an AdWordsClient instance.\\n feed_name: the name for the new AdCustomizerFeed.\\n Returns:\\n The new AdCustomizerFeed.\\n \\\"\\\"\\\"\\n ad_customizer_feed_service = client.GetService('AdCustomizerFeedService', 'v201705')\\n customizer_feed = {'feedName': feed_name, 'feedAttributes': [{'type': 'STRING', 'name': 'Name'}, {'type': 'STRING', 'name': 'Price'}, {'type': 'DATE_TIME', 'name': 'Date'}]}\\n feed_service_operation = {'operator': 'ADD', 'operand': customizer_feed}\\n response = ad_customizer_feed_service.mutate([feed_service_operation])\\n if (response and ('value' in response)):\\n feed = response['value'][0]\\n feed_data = {'feedId': feed['feedId'], 'nameId': feed['feedAttributes'][0]['id'], 'priceId': feed['feedAttributes'][1]['id'], 'dateId': feed['feedAttributes'][2]['id']}\\n print ('Feed with name \\\"%s\\\" and ID %s was added with:\\\\n DCTB Name attribute ID %s and price attribute ID %s and date attributeID %s' % (feed['feedName'], feed['feedId'], feed_data['nameId'], feed_data['priceId'], feed_data['dateId']))\\n return feed\\n else:\\n raise errors.GoogleAdsError('No feeds were added')\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@keras_test\\ndef test_saving_without_compilation():\\n\\n ''''Test saving model without compiling.'\\n '''\",\"targets\":\"model = Sequential()\\n model.add(Dense(2, input_shape=(3,)))\\n model.add(Dense(3))\\n (_, fname) = tempfile.mkstemp('.h5')\\n save_model(model, fname)\\n model = load_model(fname)\\n os.remove(fname)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef is_deriv_k(fa, fd, DE):\\n\\n ''''Checks if Df\\/f is the derivative of an element of k(t).\\n a in k(t) is the derivative of an element of k(t) if there exists b in k(t)\\n such that a = Db. Either returns (ans, u), such that Df\\/f == Du, or None,\\n which means that Df\\/f is not the derivative of an element of k(t). ans is\\n a list of tuples such that Add(*[i*j for i, j in ans]) == u. This is useful\\n for seeing exactly which elements of k(t) produce u.\\n This function uses the structure theorem approach, which says that for any\\n f in K, Df\\/f is the derivative of a element of K if and only if there are ri\\n in QQ such that::\\n --- --- Dt\\n \\\\ r * Dt + \\\\ r * i Df\\n \\/ i i \\/ i --- = --.\\n --- --- t f\\n i in L i in E i\\n K\\/C(x) K\\/C(x)\\n Where C = Const(K), L_K\\/C(x) = { i in {1, ..., n} such that t_i is\\n transcendental over C(x)(t_1, ..., t_i-1) and Dt_i = Da_i\\/a_i, for some a_i\\n in C(x)(t_1, ..., t_i-1)* } (i.e., the set of all indices of logarithmic\\n monomials of K over C(x)), and E_K\\/C(x) = { i in {1, ..., n} such that t_i\\n is transcendental over C(x)(t_1, ..., t_i-1) and Dt_i\\/t_i = Da_i, for some\\n a_i in C(x)(t_1, ..., t_i-1) } (i.e., the set of all indices of\\n hyperexponential monomials of K over C(x)). If K is an elementary extension\\n over C(x), then the cardinality of L_K\\/C(x) U E_K\\/C(x) is exactly the\\n transcendence degree of K over C(x). Furthermore, because Const_D(K) ==\\n Const_D(C(x)) == C, deg(Dt_i) == 1 when t_i is in E_K\\/C(x) and\\n deg(Dt_i) == 0 when t_i is in L_K\\/C(x), implying in particular that E_K\\/C(x)\\n and L_K\\/C(x) are disjoint.\\n The sets L_K\\/C(x) and E_K\\/C(x) must, by their nature, be computed\\n recursively using this same function. Therefore, it is required to pass\\n them as indices to D (or T). E_args are the arguments of the\\n hyperexponentials indexed by E_K (i.e., if i is in E_K, then T[i] ==\\n exp(E_args[i])). This is needed to...'''\",\"targets\":\"(dfa, dfd) = (((fd * derivation(fa, DE)) - (fa * derivation(fd, DE))), (fd * fa))\\n (dfa, dfd) = dfa.cancel(dfd, include=True)\\n if (len(DE.exts) != len(DE.D)):\\n if ([i for i in DE.cases if (i == 'tan')] or (set([i for i in DE.cases if (i == 'primitive')]) - set(DE.indices('log')))):\\n raise NotImplementedError('Real version of the structure theorems with hypertangent support is not yet implemented.')\\n raise NotImplementedError('Nonelementary extensions not supported in the structure theorems.')\\n E_part = [DE.D[i].quo(Poly(DE.T[i], DE.T[i])).as_expr() for i in DE.indices('exp')]\\n L_part = [DE.D[i].as_expr() for i in DE.indices('log')]\\n lhs = Matrix([(E_part + L_part)])\\n rhs = Matrix([(dfa.as_expr() \\/ dfd.as_expr())])\\n (A, u) = constant_system(lhs, rhs, DE)\\n if ((not all((derivation(i, DE, basic=True).is_zero for i in u))) or (not A)):\\n return None\\n elif (not all((i.is_Rational for i in u))):\\n raise NotImplementedError('Cannot work with non-rational coefficients in this case.')\\n else:\\n terms = ([DE.extargs[i] for i in DE.indices('exp')] + [DE.T[i] for i in DE.indices('log')])\\n ans = list(zip(terms, u))\\n result = Add(*[Mul(i, j) for (i, j) in ans])\\n argterms = ([DE.T[i] for i in DE.indices('exp')] + [DE.extargs[i] for i in DE.indices('log')])\\n l = []\\n ld = []\\n for (i, j) in zip(argterms, u):\\n (i, d) = i.as_numer_denom()\\n (icoeff, iterms) = sqf_list(i)\\n l.append(Mul(*([Pow(icoeff, j)] + [Pow(b, (e * j)) for (b, e) in iterms])))\\n (dcoeff, dterms) = sqf_list(d)\\n ld.append(Mul(*([Pow(dcoeff, j)] + [Pow(b, (e * j)) for (b, e) in dterms])))\\n const = cancel((((fa.as_expr() \\/ fd.as_expr()) \\/ Mul(*l)) * Mul(*ld)))\\n return (ans, result, const)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@verbose\\ndef _setup_bem(bem, bem_extra, neeg, mri_head_t, verbose=None):\\n\\n ''''Set up a BEM for forward computation.'\\n '''\",\"targets\":\"logger.info('')\\n if isinstance(bem, string_types):\\n logger.info(('Setting up the BEM model using %s...\\\\n' % bem_extra))\\n bem = read_bem_solution(bem)\\n if (not isinstance(bem, ConductorModel)):\\n raise TypeError('bem must be a string or ConductorModel')\\n if bem['is_sphere']:\\n logger.info('Using the sphere model.\\\\n')\\n if ((len(bem['layers']) == 0) and (neeg > 0)):\\n raise RuntimeError('Spherical model has zero shells, cannot use with EEG data')\\n if (bem['coord_frame'] != FIFF.FIFFV_COORD_HEAD):\\n raise RuntimeError('Spherical model is not in head coordinates')\\n else:\\n if ((neeg > 0) and (len(bem['surfs']) == 1)):\\n raise RuntimeError('Cannot use a homogeneous model in EEG calculations')\\n logger.info('Employing the head->MRI coordinate transform with the BEM model.')\\n bem['head_mri_t'] = _ensure_trans(mri_head_t, 'head', 'mri')\\n logger.info(('BEM model %s is now set up' % op.split(bem_extra)[1]))\\n logger.info('')\\n return bem\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _quaternion_align(from_frame, to_frame, from_pts, to_pts):\\n\\n ''''Perform an alignment using the unit quaternions (modifies points).'\\n '''\",\"targets\":\"assert (from_pts.shape[1] == to_pts.shape[1] == 3)\\n (from_c, to_c) = (from_pts.mean(axis=0), to_pts.mean(axis=0))\\n from_ = (from_pts - from_c)\\n to_ = (to_pts - to_c)\\n S = np.dot(from_.T, to_)\\n N = np.array([[((S[(0, 0)] + S[(1, 1)]) + S[(2, 2)]), 0.0, 0.0, 0.0], [(S[(1, 2)] - S[(2, 1)]), ((S[(0, 0)] - S[(1, 1)]) - S[(2, 2)]), 0.0, 0.0], [(S[(2, 0)] - S[(0, 2)]), (S[(0, 1)] + S[(1, 0)]), (((- S[(0, 0)]) + S[(1, 1)]) - S[(2, 2)]), 0.0], [(S[(0, 1)] - S[(1, 0)]), (S[(2, 0)] + S[(0, 2)]), (S[(1, 2)] + S[(2, 1)]), (((- S[(0, 0)]) - S[(1, 1)]) + S[(2, 2)])]])\\n (eig_vals, eig_vecs) = linalg.eigh(N, overwrite_a=True)\\n which = np.argmax(eig_vals)\\n if (eig_vals[which] < 0):\\n raise RuntimeError('No positive eigenvalues. Cannot do the alignment.')\\n q = eig_vecs[:, which]\\n trans = np.eye(4)\\n trans[(0, 0)] = ((((q[0] * q[0]) + (q[1] * q[1])) - (q[2] * q[2])) - (q[3] * q[3]))\\n trans[(0, 1)] = (2.0 * ((q[1] * q[2]) - (q[0] * q[3])))\\n trans[(0, 2)] = (2.0 * ((q[1] * q[3]) + (q[0] * q[2])))\\n trans[(1, 0)] = (2.0 * ((q[2] * q[1]) + (q[0] * q[3])))\\n trans[(1, 1)] = ((((q[0] * q[0]) - (q[1] * q[1])) + (q[2] * q[2])) - (q[3] * q[3]))\\n trans[(1, 2)] = (2.0 * ((q[2] * q[3]) - (q[0] * q[1])))\\n trans[(2, 0)] = (2.0 * ((q[3] * q[1]) - (q[0] * q[2])))\\n trans[(2, 1)] = (2.0 * ((q[3] * q[2]) + (q[0] * q[1])))\\n trans[(2, 2)] = ((((q[0] * q[0]) - (q[1] * q[1])) - (q[2] * q[2])) + (q[3] * q[3]))\\n trans[:3, 3] = (to_c - np.dot(trans[:3, :3], from_c))\\n del to_c, from_c\\n logger.info(' Quaternion matching (desired vs. transformed):')\\n for (fro, to) in zip(from_pts, to_pts):\\n rr = (np.dot(trans[:3, :3], fro) + trans[:3, 3])\\n diff = np.sqrt(np.sum(((to - rr) ** 2)))\\n logger.info((' %7.2f %7.2f %7.2f mm <-> %7.2f %7.2f %7.2f mm (orig : %7.2f %7.2f %7.2f mm) diff = %8.3f mm' % (((tuple((1000 * to)) + tuple((1000 * rr))) + tuple((1000 *...\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef is_user_context(context):\\n\\n ''''Indicates if the request context is a normal user.'\\n '''\",\"targets\":\"if (not context):\\n return False\\n if context.is_admin:\\n return False\\n if ((not context.user_id) or (not context.project_id)):\\n return False\\n return True\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef getRectangularGrid(diameter, loopsComplex, maximumComplex, minimumComplex, zigzag):\\n\\n ''''Get rectangular grid.'\\n '''\",\"targets\":\"demiradius = (0.25 * diameter)\\n xStart = (minimumComplex.real - demiradius.real)\\n y = (minimumComplex.imag - demiradius.imag)\\n gridPath = []\\n rowIndex = 0\\n while (y < maximumComplex.imag):\\n addGridRow(diameter, gridPath, loopsComplex, maximumComplex, rowIndex, xStart, y, zigzag)\\n y += diameter.imag\\n rowIndex += 1\\n return gridPath\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def bench_isotonic_regression(Y):\",\"targets\":\"\\\"\\\"\\\"Runs a single iteration of isotonic regression on the input data,\\n and reports the total time taken (in seconds).\\n \\\"\\\"\\\"\\n gc.collect()\\n tstart = datetime.now()\\n isotonic_regression(Y)\\n delta = (datetime.now() - tstart)\\n return total_seconds(delta)\",\"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 = browser.split()[0]\\n if (not _iscommand(cmd)):\\n return [None, None]\\n name = os.path.basename(cmd)\\n try:\\n command = _browsers[name.lower()]\\n except KeyError:\\n return [None, None]\\n controller = command[1]\\n if (controller and (name.lower() == controller.basename)):\\n import copy\\n controller = copy.copy(controller)\\n controller.name = browser\\n controller.basename = os.path.basename(browser)\\n register(browser, None, controller, update_tryorder)\\n return [None, controller]\\n return [None, None]\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _synthesize(browser, update_tryorder=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 binmode = fileobj_is_binary(f)\\n if (binmode and isinstance(s, text_type)):\\n s = encode_ascii(s)\\n elif ((not binmode) and (not isinstance(f, text_type))):\\n s = decode_ascii(s)\\n elif (isinstance(f, StringIO) and isinstance(s, np.ndarray)):\\n s = s.data\\n f.write(s)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def _write_string(f, s):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n conn = _auth(profile)\\n return conn.update_vpnservice(vpnservice, desc)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def update_vpnservice(vpnservice, desc, profile=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def javascript_confirm(url, js_msg, abort_on):\",\"targets\":\"\\\"\\\"\\\"Display a javascript confirm prompt.\\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)\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def global_max_pool(incoming, name='GlobalMaxPool'):\",\"targets\":\"\\\"\\\"\\\"Global Max Pooling.\\n Input:\\n 4-D Tensor [batch, height, width, in_channels].\\n Output:\\n 2-D Tensor [batch, pooled dim]\\n Arguments:\\n incoming: `Tensor`. Incoming 4-D Tensor.\\n name: A name for this layer (optional). Default: \\\\GlobalMaxPool\\\\.\\n \\\"\\\"\\\"\\n input_shape = utils.get_incoming_shape(incoming)\\n assert (len(input_shape) == 4), 'Incoming Tensor shape must be 4-D'\\n with tf.name_scope(name):\\n inference = tf.reduce_max(incoming, [1, 2])\\n tf.add_to_collection(((tf.GraphKeys.LAYER_TENSOR + '\\/') + name), inference)\\n return inference\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\n@not_implemented_for('directed')\\n@not_implemented_for('multigraph')\\ndef chain_decomposition(G, root=None):\\n\\n ''''Return the chain decomposition of a graph.\\n The *chain decomposition* of a graph with respect a depth-first\\n search tree is a set of cycles or paths derived from the set of\\n fundamental cycles of the tree in the following manner. Consider\\n each fundamental cycle with respect to the given tree, represented\\n as a list of edges beginning with the nontree edge oriented away\\n from the root of the tree. For each fundamental cycle, if it\\n overlaps with any previous fundamental cycle, just take the initial\\n non-overlapping segment, which is a path instead of a cycle. Each\\n cycle or path is called a *chain*. For more information, see [1]_.\\n Parameters\\n G : undirected graph\\n root : node (optional)\\n A node in the graph `G`. If specified, only the chain\\n decomposition for the connected component containing this node\\n will be returned. This node indicates the root of the depth-first\\n search tree.\\n Yields\\n chain : list\\n A list of edges representing a chain. There is no guarantee on\\n the orientation of the edges in each chain (for example, if a\\n chain includes the edge joining nodes 1 and 2, the chain may\\n include either (1, 2) or (2, 1)).\\n Raises\\n NodeNotFound\\n If `root` is not in the graph `G`.\\n Notes\\n The worst-case running time of this implementation is linear in the\\n number of nodes and number of edges [1]_.\\n References\\n .. [1] Jens M. Schmidt (2013). \\\"A simple test on 2-vertex-\\n and 2-edge-connectivity.\\\" *Information Processing Letters*,\\n 113, 241\u00e2\u0080\u0093244. Elsevier. '\\n '''\",\"targets\":\"def _dfs_cycle_forest(G, root=None):\\n 'Builds a directed graph composed of cycles from the given graph.\\\\n\\\\n `G` is an undirected simple graph. `root` is a node in the graph\\\\n from which the depth-first search is started.\\\\n\\\\n This function returns both the depth-first search cycle graph\\\\n (as a :class:`~networkx.DiGraph`) and the list of nodes in\\\\n depth-first preorder. The depth-first search cycle graph is a\\\\n directed graph whose edges are the edges of `G` oriented toward\\\\n the root if the edge is a tree edge and away from the root if\\\\n the edge is a non-tree edge. If `root` is not specified, this\\\\n performs a depth-first search on each connected component of `G`\\\\n and returns a directed forest instead.\\\\n\\\\n If `root` is not in the graph, this raises :exc:`KeyError`.\\\\n\\\\n '\\n H = nx.DiGraph()\\n nodes = []\\n for (u, v, d) in nx.dfs_labeled_edges(G, source=root):\\n if (d == 'forward'):\\n if (u == v):\\n H.add_node(v, parent=None)\\n nodes.append(v)\\n else:\\n H.add_node(v, parent=u)\\n H.add_edge(v, u, nontree=False)\\n nodes.append(v)\\n elif ((d == 'nontree') and (v not in H[u])):\\n H.add_edge(v, u, nontree=True)\\n else:\\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 app = (app or webapp2.get_app())\\n app.registry[key] = store\\n\\n\\nWhat's a good function header?\",\"targets\":\"def set_store(store, key=_store_registry_key, app=None):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def all_pairs_shortest_path(G, cutoff=None):\",\"targets\":\"\\\"\\\"\\\"Compute shortest paths between all nodes.\\n Parameters\\n G : NetworkX graph\\n cutoff : integer, optional\\n Depth at which to stop the search. Only paths of length at most\\n `cutoff` are returned.\\n Returns\\n lengths : dictionary\\n Dictionary, keyed by source and target, of shortest paths.\\n Examples\\n >>> G = nx.path_graph(5)\\n >>> path = nx.all_pairs_shortest_path(G)\\n >>> print(path[0][4])\\n [0, 1, 2, 3, 4]\\n See Also\\n floyd_warshall()\\n \\\"\\\"\\\"\\n return {n: single_source_shortest_path(G, n, cutoff=cutoff) for n in G}\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funccont\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"def _has_constant_term(p, x):\",\"targets\":\"\\\"\\\"\\\"Check if ``p`` has a constant term in ``x``\\n Examples\\n >>> from sympy.polys.domains import QQ\\n >>> from sympy.polys.rings import ring\\n >>> from sympy.polys.ring_series import _has_constant_term\\n >>> R, x = ring(\\\\x\\\\, QQ)\\n >>> p = x**2 + x + 1\\n >>> _has_constant_term(p, x)\\n True\\n \\\"\\\"\\\"\\n R = p.ring\\n iv = R.gens.index(x)\\n zm = R.zero_monom\\n a = ([0] * R.ngens)\\n a[iv] = 1\\n miv = tuple(a)\\n for expv in p:\\n if (monomial_min(expv, miv) == zm):\\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 find_undeclared(nodes, names):\\n\\n ''''Check if the names passed are accessed undeclared. The return value\\n is a set of all the undeclared names from the sequence of names found.'\\n '''\",\"targets\":\"visitor = UndeclaredNameVisitor(names)\\n try:\\n for node in nodes:\\n visitor.visit(node)\\n except VisitorExit:\\n pass\\n return visitor.undeclared\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef format_date(date=None, format=None, rebase=True):\\n\\n ''''See :meth:`I18n.format_date`.'\\n '''\",\"targets\":\"return get_i18n().format_date(date, format, rebase)\",\"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 initialize(self, *args, **kwargs):\\n cls = type(self)\\n for (k, v) in kwargs.items():\\n if hasattr(cls, k):\\n attr = getattr(cls, k)\\n if isinstance(attr, InstrumentedAttribute):\\n column = attr.property.columns[0]\\n if isinstance(column.type, String):\\n if (column.type.length and (column.type.length < len(str(v)))):\\n if ((config.CONF.signing.token_format == 'PKI') and (self.__tablename__ == 'token') and (k == 'id')):\\n continue\\n raise exception.StringLengthExceeded(string=v, type=k, length=column.type.length)\\n init(self, *args, **kwargs)\\n return initialize\\n\\n\\nWhat's a good function header?\",\"targets\":\"def initialize_decorator(init):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef color_palette(name=None, n_colors=6, desat=None):\\n\\n ''''Return a list of colors defining a color palette.\\n Availible seaborn palette names:\\n deep, muted, bright, pastel, dark, colorblind\\n Other options:\\n hls, husl, any matplotlib palette\\n Matplotlib paletes can be specified as reversed palettes by appending\\n \\\"_r\\\" to the name or as dark palettes by appending \\\"_d\\\" to the name.\\n This function can also be used in a ``with`` statement to temporarily\\n set the color cycle for a plot or set of plots.\\n Parameters\\n name: None, string, or sequence\\n Name of palette or None to return current palette. If a\\n sequence, input colors are used but possibly cycled and\\n desaturated.\\n n_colors : int\\n Number of colors in the palette. If larger than the number of\\n colors in the palette, they will cycle.\\n desat : float\\n Value to desaturate each color by.\\n Returns\\n palette : list of RGB tuples.\\n Color palette.\\n Examples\\n >>> p = color_palette(\\\"muted\\\")\\n >>> p = color_palette(\\\"Blues_d\\\", 10)\\n >>> p = color_palette(\\\"Set1\\\", desat=.7)\\n >>> import matplotlib.pyplot as plt\\n >>> with color_palette(\\\"husl\\\", 8):\\n ... f, ax = plt.subplots()\\n ... ax.plot(x, y) # doctest: +SKIP\\n See Also\\n set_palette : set the default color cycle for all plots.\\n axes_style : define parameters to set the style of plots\\n plotting_context : define parameters to scale plot elements'\\n '''\",\"targets\":\"seaborn_palettes = dict(deep=['#4C72B0', '#55A868', '#C44E52', '#8172B2', '#CCB974', '#64B5CD'], muted=['#4878CF', '#6ACC65', '#D65F5F', '#B47CC7', '#C4AD66', '#77BEDB'], pastel=['#92C6FF', '#97F0AA', '#FF9F9A', '#D0BBFF', '#FFFEA3', '#B0E0E6'], bright=['#003FFF', '#03ED3A', '#E8000B', '#8A2BE2', '#FFC400', '#00D7FF'], dark=['#001C7F', '#017517', '#8C0900', '#7600A1', '#B8860B', '#006374'], colorblind=['#0072B2', '#009E73', '#D55E00', '#CC79A7', '#F0E442', '#56B4E9'])\\n if (name is None):\\n palette = mpl.rcParams['axes.color_cycle']\\n elif (not isinstance(name, string_types)):\\n palette = name\\n elif (name == 'hls'):\\n palette = hls_palette(n_colors)\\n elif (name == 'husl'):\\n palette = husl_palette(n_colors)\\n elif (name in seaborn_palettes):\\n palette = seaborn_palettes[name]\\n elif (name in dir(mpl.cm)):\\n palette = mpl_palette(name, n_colors)\\n elif (name[:(-2)] in dir(mpl.cm)):\\n palette = mpl_palette(name, n_colors)\\n else:\\n raise ValueError(('%s is not a valid palette name' % name))\\n if (desat is not None):\\n palette = [desaturate(c, desat) for c in palette]\\n pal_cycle = cycle(palette)\\n palette = [next(pal_cycle) for _ in range(n_colors)]\\n try:\\n palette = map(mpl.colors.colorConverter.to_rgb, palette)\\n palette = _ColorPalette(palette)\\n except ValueError:\\n raise ValueError(('Could not generate a palette for %s' % str(name)))\\n return palette\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"I wrote the below code\\n\\n module = asmodule(module)\\n name = module.__name__\\n module_filename = module.__file__\\n provider = pkg_resources.get_provider(name)\\n if provider.loader:\\n m_time = os.stat(provider.loader.archive)[stat.ST_MTIME]\\n else:\\n basename = os.path.basename(module_filename)\\n path = pkg_resources.resource_filename(name, basename)\\n m_time = os.stat(path)[stat.ST_MTIME]\\n return (module_filename, m_time)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def module_modified_time(module):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef fanout_cast(conf, context, topic, msg):\\n\\n ''''Sends a message on a fanout exchange without waiting for a response.'\\n '''\",\"targets\":\"return rpc_amqp.fanout_cast(conf, context, topic, msg, rpc_amqp.get_connection_pool(conf, Connection))\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"complete\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
"{\"inputs\":\"Complete the below\\ndef _turtle_docrevise(docstr):\\n\\n ''''To reduce docstrings from RawTurtle class for functions'\\n '''\",\"targets\":\"import re\\n if (docstr is None):\\n return None\\n turtlename = _CFG['exampleturtle']\\n newdocstr = docstr.replace(('%s.' % turtlename), '')\\n parexp = re.compile((' \\\\\\\\(.+ %s\\\\\\\\):' % turtlename))\\n newdocstr = parexp.sub(':', newdocstr)\\n return newdocstr\",\"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 SynthesizeUserId(email):\",\"targets\":\"\\\"\\\"\\\"Return a synthetic user ID from an email address.\\n Note that this is not the same user ID found in the production system.\\n Args:\\n email: An email address.\\n Returns:\\n A string userid derived from the email address.\\n \\\"\\\"\\\"\\n user_id_digest = _MD5_FUNC(email.lower()).digest()\\n user_id = ('1' + ''.join([('%02d' % ord(x)) for x in user_id_digest])[:20])\\n return user_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 if (state == 'present'):\\n lcmd = ('%s info %s' % (_get_pear_path(module), name))\\n (lrc, lstdout, lstderr) = module.run_command(lcmd, check_rc=False)\\n if (lrc != 0):\\n return (False, False)\\n rcmd = ('%s remote-info %s' % (_get_pear_path(module), name))\\n (rrc, rstdout, rstderr) = module.run_command(rcmd, check_rc=False)\\n lversion = get_local_version(rstdout)\\n rversion = get_repository_version(rstdout)\\n if (rrc == 0):\\n return (True, (lversion == rversion))\\n return (False, False)\\n\\n\\nWhat's a good function header?\",\"targets\":\"def query_package(module, name, state='present'):\",\"language\":\"python\",\"split\":\"top_level\",\"template\":\"funcname\",\"dataset\":\"teven\\/code_docstring_corpus\",\"config\":\"top_level\"}\n"
| |